Is it possible to use Java WebSockets in Eclipse without Jetty? - java

I am trying to develop a web server using Java's WebSockets. I am using Eclipse with Tomcat 7, so the javax.websocket-jar file is already included.
I created a simple ServerEndpoint
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/login")
public class LoginServer {
#OnMessage
public String onMessage(String message) {
User foobar = new User("Foo", "Bar", "Baz");
return foobar.toString();
}
}
Then I opened the console in Firefox and tried to connect:
var ws = new WebSocket('ws://localhost:8080/MyServer/login');
This ends in an error message which says it can't connect (404).
So I searched the web and found this Jetty thing. I don't really want to add an unnecessary layer on top of my software, but I couldn't find a way to connect to my server.
Do I need to use Jetty when programming WebSockets in Eclipse? If so, why?

I fixed it. I wanted to have a minimal example so I wanted to add the methods bit by bit. But I needed the #OnOpen method. Now it works. (Embarrassing...)

Related

How to receive data from a python ZeroMQ PUB server on a Java SUB client (ZMQ)

I'm working with Pupil Labs, a huge open source for eye/pupil tracking. The entire code is written in Python. The so-called Pupil Remote is based on ZeroMQ.
If I start running the Filter Messages everything is fine. For my purposes I need to "translate" Filter Messages into Java because I created an Android app, which should call a client, which has the purpose to serve as the python client.
Here's what I've done so far:
import android.annotation.SuppressLint;
import org.zeromq.ZMQ;
import java.nio.charset.Charset;
import static java.lang.Thread.sleep;
public class ZeroMQClient {
#SuppressLint("NewApi")
public static void requestGazeData() {
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
System.out.println("Connecting to server...");
subscriber.connect("tcp://xxx.x.x.x:50020");
System.out.println("Connected");
String gaze = "gaze";
subscriber.subscribe(gaze.getBytes(Charset.forName("UTF-8")));
while (true) {
String msg = subscriber.recvStr();
System.out.println(msg);
subscriber.close();
context.term();
}
}
}
Now as you can expect, why I'm asking you, nothing happens, I don't receive any data from the Pupil Labs server. I oriented myself on this post, but unfortunately, it didn't work out for me. Also the IP-Address and port are the same as on the server. It works neither locally nor remotely.
Happy about any answer, since I stuck at this.
Due to the correct establishment in terms of my implementation the actual issue was the firewall, which just blocked the connection. By posting my solution I'm hopefully able to help future visitors of this question.
The final solution, after having debugged the root-cause issue is below
Happy about having answer, you have to set a subscription Policy:
ZeroMQ expects each SUB-side to first explicitly say, what this SUB-side wants to receive from PUB ( Yes, what it to subscribes to ).
Like your mailbox will never get newspapers in, without first subscribing to any. :o)
So setup an empty string "" in the subscriber and you are done:
// String filterPermitANY = ""; // WAS AN EXAMPLE TO TEST
// subscriber.subscribe( filterPermitANY.getBytes() );// IF PUB.send()-s ANY
String gaze = "gaze"; // WAS ON TOPIC
subscriber.subscribe( gaze.getBytes() ); //
Voilá.
Having zero-warranty what python version is running on the opposite side, tweaking may take place for string-representation matching...
( Also recommended to setup LINGER to 1, that prevents from hanging terminations
and preferably it is the best time to turn the process
into using a non-blocking .poll() + .recv( ..., ZMQ_DONTWAIT ) in a soft-realtime maintained event-loop )
[ 1 ] We have got confirmed the Android/ZeroMQ side is working fine
if the PUB-side was mocked by a plain python-PUB infinite-sender and the Android-SUB was subscribed to String filterPermitANY ="";
This makes the above claim "It's an issue from the android side" actually void if not misleading.
[ 2 ] Next comes the question why it still does not work?
And the answer is: because the above designed code does not follow the published principles, how to connect and use the Pupil Labs API.
A careful reader will notice that the Pupil Labs API is not connected by the SUB-side ( be it an Android or python or whatever else implementation of such a peer ) on a port :50020, but on another port, which is first asked about via another dialogue, held over an REQ/REP-formal communication archetype ( lines 13/14/15+19 ).
Epilogue
Knocking on a wrong door will never make the intended interview happen.
One first has to ask onto which door to knock next, so as to get the Pupil Labs API into the game.

Dynamic BlazeDS endpoint configuration

I search for some help creating a web Flex application using BlazeDS and Java server with dynamic BlazeDS endpoint configuration.
First, I will try to explain my current situation.
I have a Flex 3.2 application that provides GUI of the application. From the ActionScript I call Java methods using BlazeDS. To access the BlazeDS I use a Config class that provides the endpoint as shown below (it is a constructor):
public function Config(): void {
if (_serviceUrl == null) {
try {
var browser: IBrowserManager = BrowserManager.getInstance();
browser.init();
var url: String = browser.url;
var host: String = mx.utils.URLUtil.getServerName(url);
var port: uint = mx.utils.URLUtil.getPort(url);
var parts: Array = url.split('/');
if (parts[2] == '') {
url = DEFAULT_URL;
Alert.show("Unable to determine server location, using default URL: " + DEFAULT_URL, "Connection error");
}
else {
url = parts[0] + '//' + parts[2] + '/' + parts[3] + '/messagebroker/amf';
}
_serviceUrl = url;
} catch (e: Error) {
Alert.show("Exception while trying to determine server location, using default URL: " + DEFAULT_URL, "Connection exception");
_serviceUrl = DEFAULT_URL;
}
}
}
The idea of the class is to determine the endpoint from the request URL. I use a Delegate class to call the remote methods using BlazeDS like the following:
{
import com.adobe.cairngorm.business.ServiceLocator;
import mx.rpc.IResponder;
import mx.rpc.remoting.RemoteObject;
public class AbstractRemoteDelegate
{
public function AbstractRemoteDelegate(responder:IResponder,serviceName:String)
{
_responder=responder;
_locator=ServiceLocator.getInstance();
_service=_locator.getRemoteObject(serviceName);
_service.showBusyCursor=true;
_service.endpoint = Config.instance.serviceUrl;
}
private var _responder:IResponder;
private var _locator:ServiceLocator;
private var _service:RemoteObject;
protected function send(operationName:String,... args:Array) : void {
_service.getOperation(operationName).send.apply(_service.getOperation(operationName),args).addResponder(_responder);
}
}
}
This approach actually works fine. However, I got across a situation where I can't use dynamically determined URL. In such a situation, I need a hard-coded URL in the Config.as file. And this is the problem. When trying to deploy the application to another server, I always need to rebuild the application with a new URL configuration in the ActionScript class Config.
Therefore I search for a way to define a static configuration for the Flex application to connect to a BlazeDS server. And the way to change such configuration without rebuilding the application so I can give the customer his own way to reconfigure and move the Flex application.
I thought about using a configuration file, but Flex runs on the client side and there is no configuration file!
I thought about using database configuration, but I don't have any database on the client side!
To sum up, I am looking for a way, how to get BlazeDS URL from a configuration to be able to change it without rebuilding the whole app.
Thanks for any useful suggestions.
EDIT: Revised the question to be more actual. I improved the way to determine the URL dynamically from the request URL, so it works now even for proxy server. However, my curiosity persists for the configuration of flex without rebuilding.
Here is an old example Blaze DS Service of mine which does basically the same as you did. It's just the string which needs to be created correctly. If the endpoint address is wrong, catch the error accordingly.
My project may currently not build because of Flexmojos ... I'm not able to test that yet.
Since it did not read you question properly, I misunderstood you: You can put a configuration file next to the SWF and load it via URLLoader or pass it via FlashVars. That should give you the freedom to pass the endpoint dynamically.

Sending large files from C# client to Glassfish using MTOM and streaming

I'm working on a web service that must be able to receive potentially large files (up to 2~3GB).
For the moment I configured a very simple test web service that runs in Glassfish :
package ch.geste.MTOMTest;
import javax.activation.DataHandler;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.soap.MTOM;
#MTOM
#WebService(name="ServiceMTOM_Svc")
public class ServiceMTOM {
public int upload(#WebParam(name="filename") String filename, #WebParam(name="data") DataHandler data)
{
return 0;
}
}
On the client side (C#) I imported this web service, and the generated proxy method signature to call my upload function is :
public int upload(string filename, byte[] data)
My problem is that I want to stream the data variable, because it can be quite large. That's why on the server side I'm using the DataHandler class instead of a byte array.
But on client side, if I make a naive call to upload method like this (with a 3.8GB file) :
svc.upload(Path.GetFileName(path), File.ReadAllBytes(path));
I get an exception because the C# program tries to load the whole file into memory... I understand that, I would crash too :)
So I think I need to pass a Stream object to the proxy method but I don't know how.
Do you have any idea?
Oh by the way, in my app.config, I set the transferMode="Streamed" in my binding tag.
Many thanks,
Nicolas
EDIT : Crap, I made a duplicate of an unanswered question... really sorry.
See How to use Stream instead of byte[] in C# client with a Java MTOM webservice

how to get the list of jobs in Jenkins using java?

I have downloaded and configured Jenkins in a server, my problem is that i need to access Jenkins through Java to perform some process such as starting a job, returning the current working job and returning list of jobs in the server(all that using Json) i've tried several codes such as this but im getting no results, also i cant find a clear way to achieve that, is there is any clear API and example to do it?
You can use the Jenkins API over XML:
import org.dom4j.io.*;
import org.dom4j.*;
import java.net.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("http://your-hudson-server.local/hudson/api/xml");
Document dom = new SAXReader().read(url);
for( Element job : (List<Element>)dom.getRootElement().elements("job")) {
System.out.println(String.format("Job %s has status %s",
job.elementText("name"), job.elementText("color")));
}
}
}
A complete example (with sources) can be found here.
If these examples don't work, you might have problems with Jenkins Security (your client must provide login data before it can send the request)or with CSRF protection (you have to retrieve a token before the first request and add this token as a parameter to each request).

How can I poll FTP location to trigger the changes in it?

I am trying to poll the ftp location.
I'm using Jenkins for continuous integration of the projects.So, it would be helpful if anyone can suggest me with a plugin in Jenkins or any other method to watch over the changes in FTP location.
I need to monitor the changes in FTP location and as the changes are found I have to build another job.
Not sure how to do it with Jenkins, but if you want to monitor an FTP location for changes (i.e. receive notifications when files added/removed/modified in a directory) using plain java, then the following library can help you with the actual polling/notification mechanism: https://github.com/drapostolos/rdp4j (Remote Directory Poller for Java).
Simple usage example of the API:
package example
import java.util.concurrent.TimeUnit;
import com.github.drapostolos.rdp4j.DirectoryPoller;
import com.github.drapostolos.rdp4j.spi.PolledDirectory;
public class FtpExample {
public static void main(String[] args) throws Exception {
String host = "ftp.mozilla.org";
String workingDirectory = "pub/addons";
String username = "anonymous";
String password = "anonymous";
PolledDirectory polledDirectory = new FtpDirectory(host, workingDirectory, username, password);
DirectoryPoller dp = DirectoryPoller.newBuilder()
.addPolledDirectory(polledDirectory)
.addListener(new MyListener())
.setPollingInterval(10, TimeUnit.MINUTES)
.start();
TimeUnit.HOURS.sleep(2);
dp.stop();
}
}
The RDP4J User Guide:
provides an example of FtpDirectory class which lists files in an FTP location using appache commons FTPClient
describes what events MyListener can listen for
How to configure the DirectoryPoller
Not sure how you can achieve this in Jenkins. If I were to just answer monitoring the FTP location part here is how you can do this.
Determine what programming language you want to use. (Java, .NET etc). Write code to
monitor the FTP server (assuming it is a specific remote directory you want to monitor)
and execute the job that needs to be executed. Both the monitoring and the executing the
job needs to be done in the programming language.
I am also assuming that you need a timer of some sort to do the monitoring, this can
also be done using a programming language such as Java.

Categories