Porting Java classes to the web whilst maintaining all functionality - java

So I have written a few Java classes that take input via the main method as passed arguments and then print to the screen. Is there any way I can 'port' this to something I can include in the HTML of a web document? There are multiple classes that work together so I would need some way of including all of these and forcing one specific file to run. For example, if I have Class1.java and Class2.java I would want to run Class1.java but somehow the second class must be included as the first relies on it.
I understand that this is probably not as simple as I'm making it, for example there may be complications with changing stdout to use the application screen etc, but anything that can get me started would be helpful.
Thanks!

The closest fit to what you are asking for is something called CGI, which is a technology that was popular 15 years ago, but is rarely used now. The next best fit would be to wrap your classes in something that can run in a java servlet container.
Simply put, instead of taking arguments in on the main method, you would accept them as URL parameters. Instead of printing to stdout, you would print to a special stream that sends the content over a socket to a web browser. There are many fine tutorials on the web for creating servlets. I like this one: http://helloworldprograms.blogspot.com/2010/08/servlet-hello-world.html

Related

How to load a .java file into a variable? [duplicate]

This question already has answers here:
What is a Java ClassLoader?
(8 answers)
Closed 5 months ago.
I'm still fairly new to java and currently working on a text-based adventure game as a practice project.
The engine loads scenes to play that are all child-classes from a "Scene" superclass and appear as for eg. "dungeon.java". Now I want the game to be expandable.
The ideas is that a user can drop new scenes as .java-files into a "Scenes" folder and everytime the game is launched it reads all files in that folder and safes them into a "Scene"-class array.
My problem is that I don't know how to code this. I googled a lot and tried various phrasings but all I can find are tutorials for reading lines from txt-files or similar.
Is it even possible to read a complete file into a variable without serialzation?
I already tried the following code, but didn't get around to test it yet.
private static void buildScenePool() {
File scenesFolder = new File("/scenes");
\\ setup filter for .java files
FilenameFilter javafilter = (dir, name) -> name.endsWith(".java");
File[] sceneList = scenesFolder.listFiles(javafilter);
\\ create new arry large enough for all scenes
allScenes = new Scene[sceneList.length];
try{
FileInputStream fileIn = new FileInputStream(scenesFolder);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
\\ iterate trough the list array and safe files to array
for (int x = 0; x < allScenes.length; x++) {
allScenes[x] = objectIn.readObject( (Scene)sceneList[x] );
}
objectIn.close;
} catch (IOException e) {
System.err.println(e.toString());
}
}
This is rather very complicated. java code is normally compiled, and thus, that means you'd have to scan for a new java file, compile it (which is its own complicated ordeal, as that also means setting up the classpath and the like properly so that the compiler knows what to do), then load in the class file the compiler produced, and then call the appropriate methods in there.
You can do that. It's just, quite complicated. Your standard JVM doesn't necessarily even ship with a compiler; this is solvable too (either demand that this runs only on one that does, and the modern deployment rules for java involve you getting a JVM on your user's machines, so you thus pick one that does include a compiler – or you can just ship the compiler as dependency with your app, javac is itself a java app and runs on any JVM).
However, the more usual approach is to not actually use java for this. Instead, use something java-like, but not java: Scripting languages, like groovy, or javascript (okay, that is not particularly java-like perhaps).
That is its own sort of complication. There are no easy answers to any of this.
I think it's time to first think broad strokes and determine how you want the user's experience (that is, a user that wants to add a scene) should be, and then ask a new SO question about your specific choice.
You write em, they install em
In this model, users simply download or pick a 'scene' impl that someone else wrote (a 'real' programmer with a full fork of the entire source code, an IDE, a build tool, the works). Don't knock it - programming is hard, and saying: "Oh, look, anybody can customize a scene, it's easy, just open notepad.exe, write something like this (example java file here), and dump it in the Scene folder and off you go!", but this is not at all easy. To us programmers that seems familiar at least, but to your average user you're asking them to just rattle off a poem in ancient sumerian - normal people don't program. And if they do program, they're programmers. They would much rather get instructions about how to fork a project and set it up in an IDE than some bizarreness about tossing raw java files someplace.
Scripting
This is what Processing (for programming arduinos) does, more or less what webbrowsers did (which explains why javascript is so weird), and most 'plugin systems' for pseudo-smart editors like TextMate and Emacs do: You script them. As in, you fully buy into the idea that the custom stuff written by the user is extremely simple and highly targeted (really only makes sense to run within the confines of your app, not as standalone stuff - and dependencies don't generally come up), and pick a language that fits that model, and java certainly is not that.
Obvious options are javascript and groovy. This is certainly possible but not at all easy. Still, if you're interested, search the web for tutorials on how to run javascript or groovy inside a JVM, and you'll get plenty of hits.
Java code, and you compile it
That's what your question is positing as only option. I don't recommend it, but you can do this if you must. Be aware that it seems to me, based on the way you worded your question and your example code which makes various newbie mistakes (such as print-and-continue exception handling, which is always wrong, using obsolete APIs, and messing with built-in serialization) that this is a few ballparks beyond your current skillset. A challenge is always cool, so, if you want to go for it, you should! Just be aware it'll be the most difficult thing you've ever written and it'll take a few fully dedicated weeks, with a lot of reading and experimenting.
Just definitions, really
The central tenet so far has been that you can actually program. Instructions that make the machine act in certain ways. Possibly you don't need any of that. If a Scene is really just a background colour and a few widgets displayed here and there, should it even be code at all? Maybe you just want a declarative setup: The plugin/scene writer just declares certain properties and that's all they get to do, you just 'run' such a declarative definition. In which case the 'language' of the declaration can be in JSON, XML, YAML, TOML, or any other format designed for configuration files and such, and you can forego the hairy business of attempting to compile/run user-provided code in the first place.
In order to load the Java classes into your application, you need to compile them. You could do this from Java by invoking the javac executable. See Starting a process in Java? for instructions on how you could do that. Once compiled, you'd then need to load the classes into the JVM using a class loader, e.g. by invoking ClassLoader.defineClass. You probably want to configure a protection domain as well, to prevent user provided classes from misbehaving.
However, Java might not be the best approach for extending your application. You could consider using a scripting language instead, like JavaScript. See Nashorn (an open source script engine that was included in previous versions of Java, and that can now be downloaded separately) and the Java Scripting Programmer's Guide for more information.

In Karate, how to disable the output of every line of the .js file when is failing?

We run some initial scenarios directly from karate-config.js via karate.callSingle.
Problem is, when any of those scenarios fail, the whole karate-config.js file is printed in logs, line by line.
We found where this behaviour is written:
https://github.com/karatelabs/karate/blob/3ea821f9d326b7eb96eaf0e7ab8efffc52c7f831/karate-core/src/main/java/com/intuit/karate/graal/JsEngine.java#L210
which is a static function.
Is it possible to modify this behavior to just print the name of the .js file, for instance?
That routine has evolved over 5 years to make it easier for people to figure out what went wrong in JS. You are welcome to contribute code to make it better or maybe we can use a separate logger namespace.
Personal opinion follows:
And when things fail, I think it is a good thing to provide enough information for troubleshooting. Failures should be a rare occurrence and should not be happening all the time. Finally, let me say that you should not be having very large JS files when you use Karate, and if you are doing that, I consider it an anti-pattern.

How to run java code from javascript?

I have some java class files that I would like to run from javascript. They take in a string and spit out a string. I am trying to figure out the best/easiest way to execute them the class files from javascript so I can get/use its response. So as far as I know now here are my options.
Javascript ajax request to php then maybe exec() the jar
Javascript ajax request to my class files re implemented as servlet
Rewriting the class files as javascript and call it a day
1 is not ideal because I don't avoid using php, if I can. 2 sucks cause I don't want to run Apache Tomcat. 3 sucks naturally.
Long story short, I wrote a beautiful implementation of A* in java and I want to use it in a game I wrote in js without rewriting it. What would you do?
It isn't possible to run Java through Javascript completely independently without using HTML. However, it isn't impossible.
You will first need to convert your Java game (.JRE file) into an applet. To do that, you might take the public static main void and replace it with an Applet initialization (how to use applets). It might seem tedious, but when you actually do it, it won't be that difficult.
Then, using Javascript's HTML Document Object Model (learn more), you can easily do something like this:
document.write('<embed src="foo.class">');
Also, keep in mind that the <applet> tag is NOT supported in HTML5. Like shown above, you can use the <embed> tag or also the <object> tag.
Sincerely, PD.

How to reuse/extend closed java webapp (.ear)?

I've got webapp project written in java (.ear).
It is running under glassfish-3 server.
I really have to extend its functonality. but there is no way to change even a line of it.
Is it possible to wrap that webapp or anything else (it has no API, only html for user)?
I know it's very generic, but i cannot provide a code or other useful things.
A similar situation to mine would be (expect my case needs much SECURITY because of sensitive data)...
Let's have a blog application (this would be the java closed webapp), which allows everything You expect from an blog app, BUT one instance handles one user.
You would like to allow new user to create blog (new instances of blog app?). The instances should be isolated each other.. but it's simple to achieve. Different instance different db and so on..
I do not expect solution (because of my generic description) but direction where to go.
I'm java novice, but i can read and reason so.. :)
.ear is just a zipped file, see doc http://en.wikipedia.org/wiki/EAR_(file_format). You can always unzip it and get hold of all files. JSP and config-files can be altered but not the java-classes (unless you decompile them).
This not a complete solution but hopefully a hint in some direction...

Call js webscript from Java webscript in Alfresco

I have a problem. I need execute js webscript from Java webscript. I know, how do it:
req.getRuntime().getContainer().getRegistry().getWebScript("com/home/testJs/testJs.get").execute(req, res)
, but how to construct the new WebScriptRequest object? I need do it for rewrite request path. It's a really problem for me.
Thank you.
In general, you should use WebScriptRequestURLImpl. Without any other detail, it's hard go any deeper.
That said, it's in general a bad idea to go through yet another HTTP call to yourself to fix your problem, it's basically an indication of poor modularization or lack of code reuse.
I'd rather move the piece of code that's common in both the JS and Java web scripts flows to be an Action, which you could invoke from both places without having to repackage the input parameters, or worse send them via HTTP.
Of course skuro is correct saying it is a bad idea going through the HTTP layer twice.
But in fact, executing both, a script controller and a java method is supported by Alfresco right out of the box - without ugly hacks, and without passing the entire HTTP layer twice.
You may do this:
Put your script code in the corresponding .js file.
Make sure your Java class is a subclass of DeclarativeWebScript, override executeImpl and put your custom logic there.
Sure, you can still argue that having two controllers is bad style. :)

Categories