How to create Websocket Java SE client? - java

My problem is that not since a Websocket creates client in Java SE to be able to connect to the Websocket HTML5 server.
Ningun example I dress in Internet they me have worked.
Code in HTML5
<script type="text/javascript">
var mysocket = new WebSocket("ws://localhost:8080");
mysocket.onopen = function (evt){
escribir("Websocket abierto");
};
mysocket.onmessage = function (evt){
escribir("RECIBIDO: " + evt.data);
};
mysocket.onclose = function (evt){
escribir("Websocket cerrado");
};
mysocket.onerror = function (evt) {
escribir("ERROR: " + evt.data);
}
function escribir(texto){
valor = document.getElementById("caja").value;
document.getElementById("caja").value = valor + texto + "\n";
}
function enviar(texto) {
mysocket.send(texto);
escribir("ENVIADO: " + texto);
}
function desconectar(){
mysocket.close();
}
</script>
I have tried Jetty and it me has not worked.
Do you help me please?

In java there are some options, if you aren't interested in secure websocket server, then this link can help you. There are enough examples.
PD: You can try Jetty, using some dependencies needed for websocket.

Related

Is there a way to use PhantomJS's onResourceRequested callback in the Java driver?

I want to avoid loading css files in PhantomJS. I'm using the Java driver.
I saw a nice example js code for PhantomJS like this:
page.onResourceRequested = function(requestData, request) {
if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData['Content-Type'] == 'text/css') {
request.abort();
}
};
My code is using the PhantomJSDriver like this (scala):
val sb = new PhantomJSDriverService.Builder()
val svc = sb.usingPhantomJSExecutable(new java.io.File("./phantomjs")).usingCommandLineArguments(Array("--load-images=false","--disk-cache=true")).build()
Is there a way I can achieve the same thing, perhaps via the Java API?
I was able to register the page's onResourceRequested callback using the PhantomJSDriver#executePhantomJS method.
Here is an example of disabling Google Analytic requests:
PhantomJSDriver driver = new PhantomJSDriver(service, capabilities);
driver.executePhantomJS("this.onResourceRequested = function(request, net) {" +
" console.log('REQUEST ' + request.url);" +
" if (request.url.indexOf('google-analytics') !== -1) {" +
" console.log('Abort ' + request.url);" +
" net.abort();" +
" }" +
"};");

Detect java version using deployJava.js ,pops up java upgrade menu

I have a need to know the java version installed on client machine, have come up with the solution here
How to write JavaScript function to check JRE version
When I tried, got with the answer:
console.log(deployJava.getJREs());
But at the address bar, pop up menu is displayed like this
How to hide this?.
If this can not be achieved, please suggest any other idea to implement, as this can not be used,if this popup is not suppressed
I am pretty sure from recent experiments that there is no way to suppress it. For the script to detect the plug-in versions, it must invoke the plug-in itself.
After those experiments I worked to create a script that could detect a variety of things out about the Java plug-in without invoking the plug-in itself. They relied on examining the mime-types info.
This still shows a warning in IE if opened from the local file-system. But I hope it will be more forgiving if loaded from the internet. Please report back.
But note this is what it reports for IE when the 'allow scripts' check is OK'd.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Java Information - Non Deployment Toolkit Script</title>
<meta name='author' content='Andrew Thompson'>
<meta name='description' content='Non Deployment Toolkit Script'>
<script src='mimetypes.js'></script>
<style type='text/css'>
.true {
background-color: #6F6;
}
.false {
background-color: #FB0;
}
.undefined {
background-color: #FF0;
}
.datum {
font-family: monospace;
}
td {
padding: 4px;
}
</style>
</head>
<body>
<h1>Java on this PC</h1>
<h2>Overview</h2>
<p>This page endeavors to ascertain the installation, availability
& version of the Java installed on the client PC.
More importantly, it attempts to discover the information <b>without
invoking the Java Plug-In</b> itself.
The last part is what makes it different
to the Deployment Toolkit Script supplied by Oracle.
</p>
<script type='text/javascript'>
document.write("<h2>Browser Info.</h2>");
document.write(getBrowserInfo());
document.write("<h2>Basic Info.</h2>");
document.write("<table border='1'>");
document.write(get3CellRow('<b>Enabled</b>', isJava(), 'Java is enabled (1.1+) - IE info. (short of ActiveX) stops here'));
document.write(get3CellRow('<b>Version</b>', getVersion(), 'Maximum version reliably <em>known</em> to be available'));
if (isIE()) {
document.write(get3CellRow('<b>MSIE</b>', getIEVersion(), 'Maximum version reliably known to be available in IE, tested using ActiveX'));
}
document.write(get3CellRow('<b>JWS</b>', isJWS(), 'Java Web Start available (1.4.2+)'));
document.write(get3CellRow('<b>Plug-In 2</b>', isPlugin2(), 'Plug-In 2 available (1.6.0_10+)'));
document.write("</table>");
if (plugins.length>0) {
document.write("<h2>Navigator Plug-Ins</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Name</th><th>Version</th><th>File Name</th><th>Description</th></tr>");
for (var ii=0; ii<plugins.length; ii++) {
var t = plugins[ii].name;
if (t.indexOf("Java")>-1) {
document.write("<tr>");
document.write("<td>" + plugins[ii].name + "</td>");
document.write(getDataStyledCell(plugins[ii].version));
document.write("<td>" + plugins[ii].filename + "</td>");
document.write("<td>" + plugins[ii].description + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
if (mimes.length>0) {
document.write("<h2>Navigator Mime-Types</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Mime</th><th>Description</th><th>Types</th></tr>");
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
((t.indexOf("jpi")>0 || t.indexOf("deploy")>0 || t.indexOf("jnlp")>0 || t.indexOf("vm")>0) ||
mimes[ii].description.length>0)
) {
document.write("<tr>");
document.write("<td>" + mimes[ii].type + "</td>");
document.write("<td>" + mimes[ii].description + "</td>");
document.write("<td>" + mimes[ii].suffixes + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
</script>
<hr>
<h2>Description</h2>
<p>In order (if available) the information is:
<ul>
<li><b>Browser info. Table:</b> Not strictly related to Java - the
information in the other tables is determined without
further reference to any information shown in this table (except for the <code>appName</code> used for
identifying IE).
OTOH it is an helpful guide
as to what we should be <em>expecting</em>
from the other information. E.G. IE
will not show the Plug-In or Mime Type tables. <em>Only</em>
FF displays the plug-in version numbers.
</li>
<li><b>Basic info. Table</b>
<ul>
<li><b>Enabled</b>: Java is known to this browser and enabled, according to JavaScript <code>navigator.javaEnabled()</code>.</li>
<li><b>Version</b>: The maximum Java version known to be supported in this browser/PC.
It is set to <code>1.1</code> if the previous check is <code>true</code>, since the MSVM
was the first Java version the public could get in a browser, and the MSVM
implemented Java 1.1. Goes on to check
<code>application/x-java-applet;jpi-version</code>
in the mime types if available
(i.e. typically browsers that are <em>not</em> IE).
</li>
<li><b>MSIE</b> (IE Only): The maximum Java version known to be supported by this instance of Internet Explorer
as determined using ActiveX. It runs from 1.4.2, 1.5.0.. through 1.9.0.
</li>
<li><b>JWS</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was co-bundled.</li>
<li><b>Plug-In 2</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was introduced.</li>
</ul>
</li>
<li><b>Navigator Object Tables:</b>
<em>The rest of the info. is gleaned from the <code>navigator</code> object.
IE does not include this information.</em>
<ul>
<li><b>Plug-Ins</b>: More details of the Java related plugins.
Filtered for <code>Java</code> in the <code>name</code>.
A <code>description</code> showing "Next Generation Java Plug-in" or <code>name</code>
"Java Deployment Toolkit" should be 1.6.0_10+.</li>
<li><b>Mime-Types</b>: More information on the Java related Mime-Types.
Filtered in <code>mime</code> field for <code>'java'</code> + <code>('jpi'||'vm'||'deploy')</code>
or a non-empty <code>description</code>.
The value <code>java-deployment-toolkit</code> in the <code>mime</code>
is a good indicator of 1.6.0_10+.
</li>
</ul>
</li>
</ul>
</body>
</html>
mimetypes.js
// As a version string, this might be '1.4.2_31'.
// I.E. it is not a 'number' but a 'string' and therefore must be treated as a string.
var highestVersion = 'undefined';
var mimes = window.navigator.mimeTypes;
var plugins = window.navigator.plugins;
function isJava() {
return (
typeof(navigator.javaEnabled) !== 'undefined' &&
navigator.javaEnabled());
}
function getVersion() {
var version = 0;
if (isJava()) {
version = 1.1;
}
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
t.indexOf("jpi")>0 &&
t.indexOf("applet")>0
) {
var parts = t.split("=");
version = parts[parts.length-1];
}
}
if (highestVersion=='undefined') highestVersion = version;
return version;
}
function isJWS() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.4.2') {
className = true;
}
return className;
}
function isPlugin2() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.6.0_10') {
className = true;
}
return className;
}
var versionFamily = [
'1.9.0', '1.8.0', '1.7.0',
'1.6.0', '1.5.0', '1.4.2'
];
function getIEVersion() {
for (var i=0; i<versionFamily.length; i++) {
if (testUsingActiveX(versionFamily[i])) {
return versionFamily[i];
}
}
return false;
}
if (isIE() && getVersion()=='1.1') {
highestVersion = getIEVersion();
}
function isIE() {
return navigator.appName=='Microsoft Internet Explorer';
}
function testUsingActiveX(version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
// we need the typeof check here for this to run on FF/Chrome
// the check needs to be in place here - cannot even pass ActiveXObject
// as arg to another function
if (typeof ActiveXObject == 'undefined' || !ActiveXObject) {
alert('[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?');
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
}
function get3CellRow(cell1, cell2, cell3) {
var s = "" +
"<tr>" +
"<td class='" +
getClassName(cell1) +
"'>" +
cell1 +
"</td>" +
getDataStyledCell(cell2) +
"<td class='" +
getClassName(cell3) +
"'>" +
cell3 +
"</td>" +
"</tr>" +
"";
return s;
}
function getDataStyledCell(value) {
var s = "<td class='datum " +
getClassName(value) +
"'>" +
value +
"</td>";
return s;
}
function getClassName(val) {
var className = undefined;
if (
(val) ||
(!val) ||
(val!=="undefined")
) {
className = val;
}
return className;
}
function getBrowserInfo() {
var s = "";
var props = [
'appCodeName','appName','appVersion',
'userAgent',
'platform','cookieEnabled'
];
s += "<table border='1'>";
for (var i=0; i<props.length; i++) {
s+= "<tr>";
s+= "<td><b>";
s+= props[i];
s+= "</b></td>";
s+= "<td>";
s+= navigator[props[i]];
s+= "</td>";
s+= "</tr>";
}
s += "</table>";
return s;
}
Please note (be warned) this script was written by me, a Java programmer. Java programmers are typically the absolute worst people on the planet for writing JS, since we foolishly tend to presume. "It's JavaScript, how hard can it be?".
To write really good JavaScript is indeed an art.
Even worse, this was experimental code that was 'hacked out' with the intention of improving it later, but the project was abandoned and 'later' never arrived.
Caveat emptor.

JavaScript Cookie Creation Issue

I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!
If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.

WEBSOCKETS: client does not revice the messages I send from server

I will try to explain my problem without attaching any code, I think that that is not needed.
Okay, I have a websocket client in JS that connects to my java server. The handshake is done, connected handler is called on the client, so I send a message to server, wich is readed. Then the message is reversed and sended back to the client, but the client messagerecived handler or any other handler are not called.
This is the message that I send to the client:
b[0]=-127;//Its the same of 129?
b[1]=1;
b[2]=18;//any char..
I think that the problem must be on the first byte. I write "b[0] = (byte)129;" but when I read it it returns -127, maybe because, ¿the byte 129 have to be unsigned?
Thanks for help :P
The requested client code:
<html><head><meta charset="utf-8">
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:10637/penise";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
var msg = String.fromCharCode(1)+ String.fromCharCode(0)+"This is niceeee"
doSend(msg);
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
function char(i) {
return String.fromCharCode(i);
}
</script>
</head><body><h2>WebSocket Test</h2>
<div id="output"><p style="word-wrap: break-word;">CONNECTED</p><p style="word-wrap: break-word;">SENT: This is niceeee</p><p style="word-wrap: break-word;"><span style="color: red;">ERROR:</span> undefined</p><p style="word-wrap: break-word;">DISCONNECTED</p></div>
</body></html>
I would recommend that you use a buffer of unsigned bytes to avoid confusion.
Your main problem is that the first byte indicates that the payload is UTF-8 text, but the single byte value in your payload is 180 which is not a valid UTF-8 character. If you are trying to send a binary value then you need to indicate that in the first byte by setting the opcode to 0x2 rather than 0x1 (e.g. 130 rather than 129).
OK, I have solved the problem. The problem was that, when i sent the header, I putted 2 "\r\n", instead of only one, so one of the \r\n becomes part of the next frame and the connection is broken (because it becomes the opcode of the next frame).
Thanks you for trying to help me <3

DJ Native Swing javascript command problems

Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.

Categories