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.
Related
So, this is a rather unusual question, and I can't find anything else anywhere which has been helpful on how to do this, or if its even possible to do so.
I'm working on a game server wrote in java, and I'm trying to get the users default web browser to open to a specific link, when a command is typed into the chat box and sent to the server.
The current Issue I have is, when a user issues the command, it opens the browser on the host system, and not the players system.
I haven't been able to try any other methods, as I am unable to find any information regarding my specific situation!
#CommandHandlerMethod(accessLevel = EAccessLevel.USER)
public static Object[] vote(final Player player, final String... params) {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("www.example.com");
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
return AbstractCommandHandler.getAcceptResult("");
}
What I was hoping for via this code, was to open the web browser on the players system to allow them to view a specific webpage, but this has not been the case, and opens it on the server host system.
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();
}
}
}
I'm currently learning Java by developing a tool for creating and filling out multiple-choice-forms client-side and saving aswell as evaluating them server-side. I used a code skeleton from a RMI Tutorial for the network-part and it was working fine until just now. Both the client and the server application are in the same package but run as seperate applications. For easier developing they're both running on the same system right now, although this will change when things are done.
So let's cut to the chase with some code and what exactly goes wrong:
Server.java
Server() throws RemoteException {
super();
}
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
}
catch (RemoteException ex) {
System.out.println("SERVER: " + ex.getMessage());
}
try {
Naming.rebind("Server", new Server()); <---
}
catch(MalformedURLException ex) {
System.out.println("SERVER: " + ex.getMessage());
}
catch(RemoteException ex) {
System.out.println("SERVER: " + ex.getMessage());
}
}
[...] methods that are called by the client via ServerInterface
The <--- marks where the Client-GUI is started.
Client.java
private static Gui_loadSets gui_loadSets = new Gui_loadSets();
public static void main(String[] args) {
loadGuiLoadSets();
}
This is where the first GUI is turned visible; the one to choose a form to load from. This GUI is loaded by starting the server EVEN IF I COMMENT THIS OUT. So the Server doesn't really load the Client-App, but instead somehow magically accesses it's GUI and showing it for no reason.
I already tried "stepping into" the line before the GUI is loaded, but I end up in an infinite loop eventually, so I really have no idea what is going an.
This is my first question here, so please forgive me if I missed out anything obvious.
Thanks for your help in advance. If you need any more code I'd be happy to supply, but most of the remaining code is all about the multiple-choice-forms.
Naming.rebind() needs a URL, not just a service name. It should be
Naming.rebind("rmi://localhost/Server", new Server());
But I'm puzzled by your comment on this line. The --> doesn't 'mark where the Client-GUI is started', it marks the line where the remote object is constructed, exported, and bound into the Registry. The client GUI is at the client.
Thanks for your effort, I got it working now.
A very basic class the server was creating an object from was referring to a method provided by the client. So apparently this caused the problem. I must've forgotten about it, since it was in there since the beginning but somehow just now started to turn out to be a visible problem.
I'm sorry for any inconvenience my bad design has caused you. :)
Also, how do I mark this problem as solved without being frowned upon? Do people attach importance to getting the accepted-answer-button? I can't do this on comments I believe.
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.
I'm trying to test my code that reads from a USB port (COM25 when the device is connected) that is created when a device is connected to my computer and to a boat. I cannot power the USB device when not on the boat so testing is difficult. Can someone let me know how to simulate a COM port and write data to it so my test program is able to connect to that simulated COM port and read that data?
I'm reading this from a Java program but the simulation doesn't need to be in Java or any specific language. Just a program that will simulate the COM port and allow me to connect to it. I downloaded a COM port emulator from AGG Software and it appears that it's writing to what I deem COM25 but I'm not able to connect to it from my Java test.
The general answer for this kind of problem is to wrap the code that talks to the COM port in a class that implements an interface. If you do this as a Facade (pattern) then you can also make the COM methods you call sensible from your end.
The interface can then be mocked or faked for the test. (There is a great article on test objects, but I haven't been able to find it yet.) One advantage here is that you can create a fake version that throws exceptions or otherwise does things that are possible for the port to do but hard to get it to do in practice.
Where I work, we solved a similar issue by having our emulator not spoof a COM port at all. Here's how you can do it:
Define an interface for talking with your COM port, something like IUsbCommService
Implement your real COM-communcation service, using the standard Java Comm API
For your emulator, simply kick of a thread that spits out the same sort of data you can expect from your USB device at regular intervals.
Use your IOC framework of choice (e.g., Spring) to wire up either the emulator or the real service.
As long as you hide your implementation logic appropriately, and as long as you code to your interface, your service-consumer code won't care whether it's talking to the real USB device or to the emulator.
For example:
import yourpackage.InaccessibleDeviceException;
import yourpackage.NoDataAvailableException;
public interface IUsbProviderService {
public void initDevice() throws InaccessibleDeviceException;
public UsbData getUsbData()
throws InaccessibleDeviceException, NoDataAvailableException;
}
// The real service
import javax.comm.SerialPort; //....and the rest of the java comm API
public class UsbService implements IUsbProviderService {
.
.
.
}
// The emulator
public class UsbServiceEmulator implements IUsbProviderService {
private Thread listenerThread;
private static final Long WAITTIMEMS = 10L;
private String usbData;
public UsbServiceEmulator(long maxWaitTime) throws InaccessibleDeviceException{
initialize();
boolean success = false;
long slept = 0;
while (!success && slept < maxWaitTime) {
Thread.sleep(WAITTIMEMS);
slept += WAITTIMEMS;
}
}
private void initialize() throws InaccessibleDeviceException{
listenerThread = new Thread();
listenerThread.start();
}
private class UsbRunner implements Runnable {
private String[] lines = {"Data line 1", "Data line 2", "Data line 3"};
public void run() {
int line = 0;
while(true) {
serialEvent(lines[line]);
if(line == 3) {
line = 0;
} else {
line++;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
//handle the error
}
}
private void serialEvent(String line) {
if(/*you have detected you have enough data */) {
synchronized(this) {
usbData = parser.getUsbData();
}
}
}
}
Hope this helps!
Thanks to all the answers so far! Here's what I ended up doing as a result of recommendations from someone at work.
Downloaded the COM Port Data Emulator (CPDE) from AGG Software
Downloaded the Virtual Serial Port Driver (VSPD) from Eltima Software
(I just randomly picked a free data emulator and virtual serial port package. There are plenty of alternatives out there)
Using VSPD, created virtual serial ports 24 and 25 and connected them via a virtual null modem cable. This effectively creates a write port at 24 and a read port at 25.
Ran the CPDE, connected to 24 and started writing my test data.
Ran my test program, connected to 25 and was able to read the test data from it
There are plenty of relevant answers in this section. But as for me, I personally use Virtual Serial Port Driver, which works perfect for me. But I must admit that there are plenty alternatives when it comes to creating virtual ports: freevirtualserialports.com; comOcom to name a few. But I haven't got a chance to use them, so my recommendation for solving this problem is Virtual Serial Port Driver.
I recommend fabulatech's virtual modem.
Get it at http://www.virtual-modem.com
You might also want to get a COM port monitor for your tests - You can find it at
http://www.serial-port-monitor.com
Good luck with the boat! :)
I use com0com and it works great for what I need.
In addition all others, I would like to added this nice, free emulator https://sites.google.com/site/terminalbpp/ I do use. I do also use AGG Com port data emulator.