Rhino and envjs: share Javascript objects with Java application - rhino

I'm using rhino and envjs embedded in my java application as described in the envjs guide
Java code:
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.tools.shell.Global;
import org.mozilla.javascript.tools.shell.Main;
...
Context cx = ContextFactory.getGlobal().enterContext();
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
Global global = Main.getGlobal();
global.init(cx);
Main.processSource(cx, "path/to/your/JSfile");
This is working and my test javascript file correctly loads a remote site and does some manipulation with the HTML elements using jQuery.
What I can't figure out is how to send data from the JavaScript back to my Java application.
Here's my .js file:
load('env.rhino.js');
load('jquery.js');
Envjs.scriptTypes['text/javascript'] = true;
window.location = 'http://[mytestpage].html'
var body = $("body");
print("The body is: "+ $.trim(body));//this prints in the Java console!
//I'd like to call a function in my Java code from the Javascript and pass the bodyText as a parameter to it. How can i do this?
myJavaFunction(bodytext);

So this Rhino tutorial was very useful in learning how to connect your Java to JS.
https://developer.mozilla.org/en-US/docs/Scripting_Java

Related

Getting paperjs to work in an electron app

Another learning project in the works... I am trying to use paperjs in an electron app.
According to the instructions, I think I should be using paper-jsdom (please correct me if I'm wrong). BTW, I am using TypeScript if that makes a difference. I have an HTML document with nothing but an empty <canvas> and a <script> tag referencing this:
import paper, {Color, Point, Path} from 'paper-jsdom'
window.onload = (): void => {
let canvas = document.getElementById("workspace") as HTMLCanvasElement;
paper.setup(canvas);
let path = new Path();
path.strokeColor = Color.random();
let start = new Point(100, 100);
path.moveTo(start);
path.lineTo(start.add(new Point(200, -50)));
paper.view.update();
};
So right off the bat I get:
Uncaught TypeError: paper_jsdom_1.Path is not a constructor
Ugh... So I tried a few random things (it's late, I'm tired...) and changing my import to:
import paper from 'paper'
import {Color, Point, Path} from 'paper-jsdom'
works, or at least the code above works.
Am I supposed to be importing some things from 'paper' and others from 'paper-jsdom'? What is the correct way to use paperjs in an electron app?
Unfortunately paper-jsdom doesn't seem to have any type info for TS.
Thanks!!
Since you are using Paper.js in the renderer process of Electron, you are using it in the browser context and not in Node.js context so you should use the common paper package which relies on browser Canvas API (and not paper-jsdom which targets browserless usage).
So you should be able to use Paper.js as you would for a website.
From your code example, I see that you are using TypeScript so you can have a look at this simple quickstart project that I made to play with Paper.js and TypeScript.
It uses this kind of import:
import * as paper from 'paper';
And then access Paper.js classes through the imported paper object:
new paper.Path.Circle({
center : paper.view.center,
radius : 50,
fillColor: 'orange',
});
Edit
Here is a repository showing the simplest way of using Paper.js in an Electron app.

Using thirdparty libraries from dart language

How can import and use any third party javascript libraries in dart..? I want to use snapsvg in my dart application to render svg. But not sure how to add dependencies to add and import it.
I added js: any to my pubspec.yaml and imported packages/browser/interop.js into my html. Where do I place downloaded snapsvg.js and import it to my dart source file to use it.
I am trying to use following javascript code using snapsvg framework from dart.
s = Snap(800, 600);
s.rect(0, 0, 100, 100).attr({
fill: 'white',
stroke: 'black'
});
I tried this code from in dart:
import 'package:js/js.dart' as js;
void main() {
var s = js.context.Snap(800, 600);
s.rect(0, 0, 100, 100);
}
This works fine in dartium, but when I Run as Javascript after build, I got javascript error "method zm not found in object"
I believe this is not right way and I should use be using callMethod on proxy. So I changed code like this
import 'dart:js' show context, JsObject;
void main() {
var snap = context['Snap'];
snap.callMethod('rect', 0,0,100,100);
}
This is not working in Dartium as itself. I would appreciate if someone can provide example of how to call constructor Snap(800, 600) from dart and also rect and attr methods in my example code.
You add them to the HTML file using <script> tags.
You can call JavaScript functions from Dart using dart-js-interop.
There are many examples here on Stackoverflow under this tag - just click on the tag below your question.
When you provide a more concrete example it is easier to help.
You can call into JavaScript with the built-in dart:js library. Please try to avoid using /package/ js, which is what you install by adding js: any to your pubspec. The js package is likely to cause the dart2js output to be bloated and we're probably going to deprecate it at some point.
You can reference JavaScript files like you would in any HTML page, via script tags. You don't actually import them into Dart source, you use dart:js to access JavaScript via its top-level context property.

"document" in mozilla extension js modules?

I am building Firefox extension, that creates single XMPP chat connection, that can be accessed from all tabs and windows, so I figured, that only way to to this, is to create connection in javascript module and include it on every browser window. Correct me if I am wrong...
EDIT: I am building traditional extension with xul overlays, not using sdk, and talking about those modules: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules
So I copied Strophe.js into js module. Strophe.js uses code like this:
/*_Private_ function that creates a dummy XML DOM document to serve as
* an element and text node generator.
*/
[---]
if (document.implementation.createDocument === undefined) {
doc = this._getIEXmlDom();
doc.appendChild(doc.createElement('strophe'));
} else {
doc = document.implementation
.createDocument('jabber:client', 'strophe', null);
}
and later uses doc.createElement() to create xml(or html?) nodes.
All worked fine, but in module I got error "Error: ReferenceError: document is not defined".
How to get around this?
(Larger piece of exact code: http://pastebin.com/R64gYiKC )
Use the hiddenDOMwindow
Cu.import("resource://gre/modules/Services.jsm");
var doc = Services.appShell.hiddenDOMWindow.document;
It sounds like you might not be correctly attaching your content script to the worker page. Make sure that you're using something like tabs.attach() to attach one or more content scripts to the worker page (see documentation here).
Otherwise you may need to wait for the DOM to load, waiting for the entire page to load
window.onload = function ()
{
Javascript code goes here
}
Should take at least diagnose that issue (even if the above isn't the best method to use in production). But if I had to wager, I'd say that you're not attaching the content script.

How to call a Dart program from Javascript?

Given that Dart will need to inter-operate with other javascript frameworks. In the client-web environment what are the current or intended best-practices to communicate with a Dart program from javascript?
Currently you need to use window.postMessage to communicate with Dart however a interorp layer is planned and should arrive in dart2js any day now (although I believe that its initial incarnation will focus more Dart->JavaScript than JavaScript->Dart).
Sample code:
import 'package:js/js.dart' as js;
js.context.jQuery();
var context = js.context;
var param = js.map({ 'modal': true, "width":1000, "height":600});
js.context.jQuery("#dialog").dialog(param);
in html
<script src="packages/browser/interop.js"></script>
The above code open a div as dialog using jQuery.

Grails support for consuming web services

Does Grails provide built-in or via a plugin support to consume (not to generate) XML based REST or SOAP web services ( esp. REST) ?
http://www.grails.org/plugin/rest
For SOAP based webservices, use WSClient. The plugin is a wrapper around GroovyWS. Under the hood, Apache CXF is working there.
In the past, I created a script (grails create-script) that used wsimport to create POJOs in the java src directory. Each time the script ran, it would delete the generated directory if it existed first, then generate new files.
I did this because the API that was being consumed was being developed and I wanted an easy way to consume the latest and greatest when new functionality was added.
In grails 3.x you can use the plugin in build.gradle
compile 'com.github.groovy-wslite:groovy-wslite:1.1.2'
Then add the import to your controller like in http://guides.grails.org/grails-soap/guide/index.html
import wslite.soap.*
import wslite.soap.SOAPClient
import wslite.soap.SOAPResponse
and use as the example available in https://github.com/jwagenleitner/groovy-wslite
def client = new SOAPClient('http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx')
def response = client.send(SOAPAction:'http://www.27seconds.com/Holidays/US/Dates/GetMothersDay') {
body {
GetMothersDay('xmlns':'http://www.27seconds.com/Holidays/US/Dates/') {
year(2011)
}
}
}
assert "2011-05-08T00:00:00" == response.GetMothersDayResponse.GetMothersDayResult.text()
assert 200 == response.httpResponse.statusCode
assert "ASP.NET" == response.httpResponse.headers['X-Powered-By']
render (response.GetMothersDayResponse.GetMothersDayResult.text())

Resources