Use of calling javascript from java and vice versa? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am learning java 8 Nashorn Javascript engine. But i am not getting what is the practical useof it. Here are my specific
questions
Calling JavaScript from Java
1) What is the practical scenario when as a developer i would like to call javascript from java ?
Calling Java from Javascript
2) What is the practical scenario when as a developer i would like to call java from javascript ?
3) If yes, How browser will execute java from javascript. Does system hosting needs to have JRE and browser will use that ?

1) What is the practical scenario when as a developer i would like to call javascript from java ?
Suppose that you're writing a browser in Java then you'll need to run JS interpreter from Java to display the page and handle JS code.
Suppose you want to provide a JS syntax checker in Java for example like JS editors in eclipse.
Or you want to run a tutorial website of JS where users write JS code in Browser and you evaluate it and show errors like it's done by most of the sites like Learnstreet, Udacity.
As a back end (server side) developer you have to provide a functionality to you front end (client side) developer where they can send you JS code and you do stuff with it on server. Service Now and Presto Mashups are a few examples where it's done.
There is a JS API that you want to use without having to convert it to Java code first. It's common pattern to support your JS library for Java and several other languages now, so that they can be run with JS engines like Mozilla Rhino and Oracle Nashorn without much hasstle.
2) What is the practical scenario when as a developer i would like to call java from javascript ?
You'll have entire Java API at your finger tips while writing JS code, answer is why not?
You're running some JS code on the Server using JS engine and you need to communicate output back to JVM or invoke some event. May be even listing directories, reading files calling database is the requirement from JS code.
Consider Node JS, it's just a JS interpreter written in C, C++ It's doing the same thing. It's providing power of C and C++ to a JS developer. Same is done with the Rhino and Nashorn. By it's nature JS has a limited functionality as its used to run on brower, it needs some additional APIs to get a power boost. I took the example of Node JS as it's popularity shows just how much this power up was needed. Just for fun try this video interview Ryan Dahl.
3) If yes, How browser will execute java from javascript. Does system hosting needs to have JRE and browser will use that ?
Browser will not run JS code containing Java parts. JS engines are meant to get the JS code on server side. This gives a JS developer an opportunity to use his JS skills to write server side code. However if needed browser can send the JS code to server for interpretation as in case of Presto Jackbe Mashups.

I have no experience with calling java from Javascript. However I have seen Javascript being called from Java. The use case I have seen is where a Java framework needed to be extended by end clients. This was achieved by letting the end clients add logic in Javascript. The actual Javascript code could then be stored in the database and executed when required by the framework.

1) A practical use of a JavaScript engine in Java would be when creating or using an HTTP Adapter. In this case, you would need to be able to handle all javascript, to simulate a real browser connection. An example of a Java HTTP Adapter that deals with JavaScript is HTMLUnit.
2) I do not believe this is used very often, or at all, especially with the disapproval of the NPAPI plugin by Chrome and, in the future, Firefox (source). Despite these points, communicating between javascript and java could be used to add functionality to a website or application, although this does not seem feasible.
3) See above.

Related

I am curious as to how python is connected to websites [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am a new programmer and I saw that Google is written in python. I know that HTML, CSS, and JS are used to make websites, so how is python "linked" to this. This is probably a very basic question but I am new to all this.
So your code in browser is called front-end (FE). Sometimes it's all you need. However, sometimes you need to store some data on the server and/or retrieve it from there. That is where back-end (BE) comes into play.
BE is basically an app on some computer (maybe a server, maybe a Raspberry Pi, anything really) that listens to requests from the network. Let's say your code needs some data from the server. Your code on the front end makes an AJAX request to the network address of this server on some specific port. The BE, which may be written in Python, or any other language, receives the request and does something with it.
It can fetch data from the DB or anything really. Then it send a response to your FE back, sending some data, or confirmation that everything was done successfully, or an error if something went wrong.
Python is used for backend development. Backend is the part of your website that runs on your server, not browser. Backend is used for authentication and communicating with database and many more. There are some popular frameworks in python like django and flask.
Google in front of you is called front end which is written in HTML, CSS, and JS and usually interpreted by browsers. In the end, HTML, CSS, and JS are all codes, thus, string (or binary).
Python is used to generate those strings, the codes, in back end.
According to the Mozilla Developer Network (MDN),
HTML — Structuring the web
HTML is the language that we use to structure the different parts of our content and define what their meaning or purpose is. This topic teaches HTML in detail.
CSS — Styling the web
CSS is the language that we can use to style and layout our web content, as well as adding behavior like animation. This topic provides comprehensive coverage of CSS.
JavaScript — Dynamic client-side scripting
JavaScript is the scripting language used to add dynamic functionality to web pages. This topic teaches all the essentials needed to become comfortable with writing and understanding JavaScript.
Below is where you will find how Python is linked to HTML, CSS, and JS.
Server-side website programming
Even if you are concentrating on client-side web development, it is still useful to know how servers and server-side code features work. This topic provides a general introduction to how the server-side works and detailed tutorials showing how to build up a server-side app using two popular frameworks: Django (Python) and Express (Node.js).
(Ref.: https://developer.mozilla.org/en-US/docs/Learn)
Below, you can read more about
what clients and servers are,
how they are linked, and
how and what the clients request to the servers and the servers respond to the clients
Some of the useful keywords are HTTP verbs (HTTP request methods), Uniform Resource Identifier (URI), and HTTP status code.
An article about Back-End Web Architecture from Codecademy
Note: As someone who just started programming, it could be really overwhelming to look for satisfying/precise answers across the web. You could also start from some reliable learning sources and search for the keywords to get a specific result. Happy learning!
The old way to to do this is with cgi-bin, which is an interface between the web-server and a program installed on the same machine.
When a user requests a static page, the web-server returns the contents a file, with some headers prefixed. cgi-bin allows for dynamic pages. Here the web-server runs a local program, passing it the URL and any headers from the client (web-browser). The program then generates the headers and body of the reply, and the web-server passes them back to the client. The program then exits.
The program can be written in any language. Perl was traditional, however Python or a compiled program is frequently used nowadays.
It was common to have cgi-bin at the start of URL to denote this to the server, but it isn't really needed - the server can be told that any specific (or all) URLs are to be fetched via cgi-bin.

Is it possible to use javascript instead of java in such conditions?

I made up desktop application using java few years ago. It is no problem to use until now, but these day I think it's better way to run web application than desktop, for some reasons. anyway, I use some objects in java desktop application, for example...
BufferedReader, DataOutputStream, InputStreamReader, OutputStreamWriter,
PrintWriter, HttpUrlConnection ....
Do javascript have such objects supporting similar fucntions...? I'm afraid to they don't have it. I'm just newbie on this, It is just a hobby. so I don't know much about it. but I heard these day's hottest language is javascript, so I just want to jump to javascript...so please help me if you know about something. thanks.
Although the default JavaScript language doesn't allow reading and writing to files the program node.js is designed to act as a server side JavaScript and does allow reading and writing of files along with a broad npm library to add different functionalities.
More information on the nodejs web site

Avoiding writing the same algorithm in multiple different languages

I am a web developer, and I have observed that many times I need the same function on both client and server. So I write it in JS as well as in PHP or whichever server side language. I am fed up with this. If I have to change it then I need to change it in both places. If I want to use it for some hand held devices, then I will have to rewrite that code yet again using objective-C or Java etc. Then if I need to change that function then I will need to change it everywhere.
Is there a solution for this? If I will call some webservice via ajax, then the client will have a delay. If it will be in JS then it can't be accessed from within PHP or Java, etc. If I use some service in PHP from another language then that can also become a performance issue.
It is also possible that some time we need such functions output from some paramters as input using db or without db.
I know there would be some pretty simpler solution but I am not aware of that. Please tell some language independent solution as I don't have VPS always.
I am not sure if my question actually belongs to stackoverflow.com or programmers.stackexchange.com so please transfer it to programmers.stackexchange.com instead of closing this question if it belongs to there.
Typically, the solution to this problem is to write common code in one language and use translators or library linking to allow access from other languages.
Node.js allows you to write server-side code in JavaScript.
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
You can also use JavaScript to write HTML5 apps for mobile devices.
"Building iPhone Apps with HTML, CSS, and JavaScript"
Now web designers and developers can join the iPhone app party without having to learn Cocoa's Objective-C programming language. It's true: You can write iPhone apps quickly and efficiently using your existing skills with HTML, CSS, and JavaScript. This book shows you how with lots of detailed examples, step-by-step instructions, and hands-on exercises.
If you don't want to try to write large complex applications in JavaScript, GWT provides a way to write Java and via-translation, run it on the client.
The GWT SDK contains the Java API libraries, compiler, and development server. It lets you write client-side applications in Java and deploy them as JavaScript.
If you develop in .Net languages: C# -> JavaScript ScriptSharp
Script# is a free tool that enables developers to author C# source code and subsequently compile it into regular script that works across all modern browsers
you could use the spidermonkey extension to translate php into javascript. this way you can write your functions in php then simply convert them to javascript and re-use them at the browser.
here is a good tutorial to show you how this is done

Getting Server-side Javascript to work for me

I am wondering how to install a Javascript runtime engine to work with an Apache HTTP server. My aim is to run server-side Javascript.
Thanks in advance for any help!
I think you may have to clarify why you want to do this.
If you're just looking to execute JavaScript code, Rhino will get you the ability to run javascript within a Java application. However, since its not in a web browser you won't have any access to any sort of DOM.
Other than that, JavaScript is mostly a language that was intended to run in a web browser on the client.

How to Cross-Compile Java Source Code to JavaScript?

Given a set of Java source code files, how can I compile them into one or more JavaScript files that can be used with hand-crafted JavaScript?
GWT is one option, but every example I've seen so far is aimed at building fancy websites. The simple use case of just converting Java source to Javascript that can be used together with handcrafted JavaScript hasn't been well-documented.
I started a thread on the GWT mailing list on this subject, but opinions seem to be mixed on whether this is even feasible.
One person gave a very useful tip, which was to check out GWT-Exporter. The problem is that neither source code nor documentation is readily available, although there's this and this.
edit: GWT-Exporter source code is here
I've also seen Java2Script. But again, I wasn't able to find examples of how to solve my simple use case.
What's the best approach to this problem? Is there something better I'm missing?
When you use GWT, you're basically converting the UI portion into Javascript (and it assumes that you use the UI widgets provided when you write your Java). Only some of the Java libraries are accessible within Javascript. Typically in a GWT application anything that makes heavy use of Java libraries would run on the server side and connect to the Javascript as AJAX (which GWT handles for you). So GWT isn't necessarily converting your full application into Javascript (though it can if you're willing to limit your use of Java libraries and some functionality).
At any rate, if this approach (calling out to Java running on a server from within Javascript) appeals to you, one nice option is DWR, which basically allows your Javascript to directly call methods in Java classes running on the server (without you having to build a web service or other frontend). Not what you asked, I know.
More relevantly, it looks like there's source code for a sample app demonstrating the use of gwt-exporter.
I am not sure if it fits your use case, but if you agree to drop Java APIs and use JavaScript APIs from Java, then you can use JSweet, a Java to JavaScript transpiler built on the top of TypeScript. It gives you access to hundreds of well-typed JavaScript APIs (DOM, jQuery, underscore, angularjs, etc). It generates JavaScript code and you can mix it with legacy JavaScript and TypeScript code.
Note: JSweet will not work for legacy Java code and legacy Java APIs, but your use case did not mention reusing legacy code.
[UPDATE] Since version 1.1, JSweet now also supports some Java APIs such as Collections (java.util). So, it is possible to reuse legacy Java code to a certain extent. It is also quite straightforward to add your own support for Java APIs.
While the question is about compiling Java sources to JavaScript I think it's worth mentioning that there is TeaVM which compiles Java bytecode to JavaScript. I have never tried it, but it seems very promising.
Given a set of Java source code files, how can I compile them into one or more JavaScript files that can be used with hand-crafted JavaScript?
Although there are many solutions to convert Java applications to Javascript, you are interested on a solution where new javascript code may interact with the resulting code. This is an update (as 2018) of the other answers.
There are different types of tools. For instance, you may find tools that allow you (1) convert java code to javascript; (2) convert bytecode to javascript, asm.js or webassembly; (3) execute java applications directly in the browser and (4) create solutions that combine java and javascript. You must select the solution to use depending on your requirements.
Converting Java source code to Javascript
Some solutions take java source code and produce a javascript equivalent version. Usually, these solutions transforms the Java to Javascript, but do not support all the behaviours and libraries of the Java runtime. The resulting code may not support some java standard libraries. Typically, they are used to create HTML application using Java but not for migrating the code. Pros: The resulting solution may include very small files. You can use it to reuse your own business logic classes without considering GUI or platform specific libraries. Cons: it is possible that you cannot use some functionalities of the Java platform. It requires access to the source code.
JSweet converts Java to javascript. It includes API bindings for 1000+ javascript libraries. You can write java code that use these libraries.
It converts java to typescript and later uses the typescript compiler to create the corresponding javascript.
It can produce multiple types of javascript modules and typescript definitions. You can use the resulting code in javascript very easily.
j2s, is the compiler used by the Eclipse RAP platform to translate java code to javascript. It is used there to convert the SWT (GUI) widgets to javascript and HTML. It does not support all the Java standard libraries
It may convert simple Java classes to be used in javascript. You must use the classes considering the OO Java-Javascript simulation performed by j2s.
Converting Javascript bytecode to javascript
These solutions take compiled java code (.class files) and produces equivalent code in javascript, asm.js or webassembly. Considering that the java code may depend on java standard libraries (i.e., the JRE), these solutions typically includes ported and pre-compiled libraries. Pros: you do not need to change anything in your code. You do not need the source code neither. Cons: the resulting solution may require the load of a lot of files.
Bck2Brwsr, a Java VM that may compile ahead-of-time the java bytecode to javascript. It produces a javascript file for each .jar file.
You may use the vm javascript object to load a class into javascript and execute static methods (using vm.loadClass(.., function(class){..}}). There is an example in the documentation for the gradle plugin and the maven task.
TeaVM, is another Java VM that may convert ahead-of-time the code to javascript. In contrast to Bck2Brwsr, it supports threads, produces a single file for all your classes and provide better debugging support.
You may call java from javascript using the javaMethods.get(..).invoke(...) method.
DukeScript, transpile java code and bytecode to javascript using Bck2Brwsr or TeaVM.
It provides maven tasks to compile the java code. The resulting code (and technique to call java from javascript) depends on the used transpiler.
Dragome, transpile java bytecode to javascript.
You can annotate static methods in Java and use it in Javascript: e.g. you can annotate a method with #MethodAlias(alias="windows.method1") and invoke it from javascript using window.method1()
CheerpJ (a commercial product) may run complete java applications using Swing and AWT. It provides a very complete javascript environment that support operating system, thread and network functionalities.
It provides a complete runtime API. You can run a main method using cheerpjRunMain( <class>, <jar> ). You can create objects using cjNew( <class>, <params>...) and invoke static methods using cjCall( <class>,<method>,<params>...). There are many other methods you may consider.
Running Java code in Javascript
DoppioJVM is a complete JVM written in Typescript. Pros: It emulates a lot of elements of the operating system, including filesystems, TTY consoles and threads. Cons: Considering that it is an interpeter, it may result slower than other solutions. (I have not tested it)
DoppioJVM is a JVM written in Typescript
The documentation includes snippets of code to load and run the classes. You can run a static method using jvm.runClass( <class>, [ <args>...], function(response){..}). You can run a Jar file and perform many other tasks.
Create applications combining Java and Javascript
Some other solutions provide, not only the tools for compiling the code, but also frameworks and solutions to create java and javascript solutions. For instance, CheerpJ has complete versions of the Swing and AWT libraries for graphical user interfaces, but they may result very slow. You may replace the user interface by using new HTML versions that run faster on the browser. Pros: You can reuse existing code without changes, mainly some libraries and business logic. You may remove from your solutions libraries that run not efficiently in the browser. Cons: If you wanna keep maintaining your java desktop version, you must deal with different code for the browser.
GWT converts Java code to javascript but uses a different set of libraries for the user interface and client-to-server communications.
The documentation maintains information of differences with the JRE
You may export Java classes to be used by Javascript code.
Dukescript uses the conversion tools mentioned before.
It provides a Knockout4j library that may interact easily with HTM, DOM and additional javascript code.
Dragome not only convert java code but also include means to interact with the HTML/DOM
You may use annotations to bind java objects to HTML elements and to handle the DOM
HTML/Java API is an Apache project that standardize the access to HTML/DOM/javascript from transpiled code
It was donated by Dukescript and other tool providers.
Recommendation
If you wanna reuse few classes created by your own, you may try JSweet. You may create javascript modules (libraries) that you can use easily with javascript and typescript.
If you wanna reuse a medium to large codebase that rely on multiple java libraries, you may try CheerpJ, Dukescript or Dragome. You may reuse large parts of your code and create (gradually) the user interface and client-to-server communications using technologies that are more browser-friendly.
If you wanna run complete java applications without change, you may try CheerpJ. It can run Swing and AWT user interfaces. It also provide an Applet runner.
Here's two other options, things to look into and a third option not converting, just living together.
Java2Javascript
I have been wanting to try this out -- Looks closer to what's been asked. Quoting the web page:
an Eclipse Java to JavaScript compiler plugin and an implementation of JavaScript version of Eclipse Standard Widget Toolkit (SWT) with other common utilities, such as java.lang.* and java.util.*. You can convert your SWT-base Rich Client Platform (RCP) into Rich Internet Application (RIA) by Java2Script Pacemaker.
A limited Java in Javascript experience - You'd need to port your necessary dependencies or find alternatives via tools like jQuery, etc.
DukeScript
As I view DukeScript, it compiles some front-end Javascript and calls Java behind, from the browser's Javascript. It seems more or less a hybrid approach so you can use the Java wealth of libraries from Javascript. I will fall foul of a browser security policy for Java.
A more full-Javascript on Java experience leveraging the Java-runtime. If I wanted that outside the browser environment I'd use Javascript on Java.
Nashhorn
Consider this as an example of using Java's resources as foundation for Javascript: Nashorn and JavaFX, as an example for a rich Javascript operated client. Anyway with a Javascript engine inside Java you're not needing to translate between a Javascript-VM to object-code to a Java-VM quite so much.
Not entirely on-topic, but Kotlin is a 100% Java-compatible language that can compile to JavaScript.
IntelliJ IDEA can automatically convert Java to Kotlin and compile it to run on Node or the browser.
Given a set of Java source code files, how can I compile them into one
or more JavaScript files that can be used with hand-crafted
JavaScript?
There is no direct correlation between both the built-in Java API and Java language features, and those of JavaScript. So any attempt at creating a "converter" is going to be incomplete. As a fundamental example, Java classes don't have a direct corresponding JavaScript idiom.
Whether or not an incomplete conversion tool will work for your use case is impossible to know without the source code.
That said, my suggestion to solving your problem would be to first attempt to use GWT: set up a demo project, drop in the source of your library and call it from the JavaScript side and see what GWT outputs in it's .js file. Some of the other tools suggested by other posters here are definitely worth checking out as well.
If that is fruitful and gets you part of the way, great.
From there, you'll need/want to do the remainder of the conversion by hand. After all, assuming you want the code to actually function correctly, a manual review would definitely be in order. Some unit tests being converted along with it would be ideal as well.
You don't state how large the source of your project is, but if it's small (let's say less than a thousand lines of code), even a complete conversion by hand shouldn't be extremely difficult. If it's much larger than that, I would suggest reviewing if you actually want that as JavaScript code anyway.
This question is from 13 years ago; yes, I know. But I'll put my addition here as this is an excellent repository of answers on the topic, and as it comes up first in a Google search it is likely to have the most eyeballs on it.
I'm a former GWT developer. And agree it is an excellent solution & technology. But also yes as mentioned, the cross compilation part mostly (arguably, completely) focuses on the W in its name (Google WEB Toolkit): the client-side JavaScript part of full stack SPA Web applications, its serialization & communication, it's client/server logic partitioning, et al.
I just stumbled onto something that is relatively new -- a 2014-2015 offshoot of GWT placed into the public domain in 2018 -- that I think is more generally focused and what was being requested in the original post (13 years ago, lol). I'm eager to try it.
J2CL: https://github.com/google/j2cl
I read about it here, which to me was a good & thorough intro of the technology (have a look and let me know if you agree or not):
https://www.infoq.com/news/2019/05/j2cl-java-javascript-transpiler/

Categories