Java ScriptEngine - Disable Importing - java

I've been searching everywhere and have found nothing, so I would like use Java's inbuilt JavaScript engine, but whilst users can't import java class, like any of the following:
importPackage(package.example);
or
importClass(package.example.MessWithEverythingClass)
or
new package.example.MessWithEverythingClass(ApplicationIsBroken aib);

I'm a little confused. Based off of your title I think you want to prevent users from importing classes inside JavaScript. In that case this question has already been asked here,
security problem with Java ScriptEngine.
Some of the solutions suggested there were to look into Java SecurityManager and another user said he solves this problem by putting "importPackage = null" on the top of all scripts.
On the contrary based on the contents of your script I get the feeling you are having trouble importing Java classes. If that's the case I answer that here,
Use a jar in JavaScript through Java ScriptEngine
Basically there is another way to import inside JavaScript that you did not show. I do it this way,
pack = Packages.abc.foo.pack.name;
var foo = new pack.ClassFromTheJarFile("arg1","arg2");
foo.doSomething();
var fooSister = new pack.AnotherCLassFromTheJarFile("arg1");
fooSister.doSomthingFromThisClass();
Although that example uses a package from a jar file it does not have to be from a jar and the code would still remain the same.

Related

Create Java PsiAssignmentExpression

I'm trying to write a Java plugin that does a custom refactoring that involves inserting new assignment statements, and I'm not sure how to create a PsiAssignmentExpression.
I have a PsiElementFactory, but while I see PsiElementFactory#createIdentifier and PsiElementFactory#createVariableDeclarationStatement, I don't see how to do an assignment.
I tried looking for the extract variable refactoring in the base source code to try and find an example but wasn't able to find it yet.
P.S. I looked at IntelliJ IDEA plugin development: how to modify the Psi tree?, which recommended creating PsiElements by creating a PsiFile and then extracting the element from it back in, but I am wondering if that's specific to creating a custom language that doesn't have the Java api.
Use PsiElementFactory#createExpressionFromText and pass in the text of the assignment you want to create. For example "s = \"Hello World\"".

Class wrapper extending different base class

I have a Java project and now I also want to use this code for a GWT project so I don't have to write the same code twice. The problem is that some classes are not available in gwt, for example java.awt.geom.Rectangle2D.Double.
I was thinking of creating a wrapper class called RectangleWrapper that would extend either the standard Rectangle class or a gwt version of the same class.
In the shared code I would replace all my Rectangle2D.Double with my Rectangle and depending on a final boolean my wrapper class (compiler flags java) would either extend on or the other Rectangle class.
Is this even possible or is there a better way to do this?
I just took one of my GWT-project client-side classes and added the following lines:
if (false) {
String a = StringEscapeUtils.escapeHtml("lalala");
}
This obviously compiles just fine, but when I launch the GWT app I get this:
ERROR: Errors in 'file:/C:/gwtproject/src/main/java/package/ClientSideClass.java'
ERROR: Line 119: No source code is available for type org.apache.commons.lang.StringEscapeUtils; did you forget to inherit a required module?
So the answer would be no, you can't use a wrapper like that.
Is there any other way of achieving that? I highly doubt it.
One of the main features of GWT is replacing the old AWT/Swing desktop GUI components with a whole set of web GUI components designed for Javascript compatibility; there's no point in making the old components available or supported in any way.
If you were talking about utility libraries like Apache Commons, I could advise you to make an RPC call instead (client-side calls server-side where you can use anything you like, and return the results asynchronously), but that's not the case.

How do I find the name of the program that would launch a given file?

I am looking for a way to find the name of the program (in my code) that will launch when an operating system tries to open a given file. I will not be launching the application I'm just looking for its name. Ideally the routine I'm looking for/building would take a filename and return a string. I am programming in Java 8 on Eclipse and need my jar file to stay cross platform.
Simplest solution I can find is to use SWT's class 'Program'. Although this assumes that I can correctly identify filetype which is another big can of worms I'm not going to into here.
String ext = extractFileType(filename);
Program p2 = Program.findProgram(ext);
if (p2 != null) programName = p2.toString();
But for a number of reasons I DON'T WANT TO USE the SWT library if at all possible. I'm using Swing and and I really don't want my clients to need to download a different application (jar) dependent on their operating system. I'm well aware that the underlying code is operating system/Window Manager dependent.
Anyone know of any other package besides SWT that already does this? I can't find one. Or similar enough I can strip the results to get what I want? Even if it's only for one platform? I'm experimenting with Apache Tika but I don't see anything helpful there.
Any hints on where to look to start write this myself? I know this entails reading the registry on Windows. I need this code to work on the most recent versions of Windows, and OS X. And eventually Linux but Linux windowing systems are not a priority.
Is there a way to link/load SWT in Eclipse to make the cross-dependent part of using SWT this code a little more lightweight and invisible to the end user? I'm not new to coding but am to using Eclipse.
Here is a quick description of my solution. I did a fair amount of hunting around and I deciding on simply using the JNA library. https://github.com/java-native-access/jna and writing my own native library on a Macintosh to get it to work.
Windows: Fairly straight forward usage of JNA. I'm calling FindExecutable & PathFindExtension from JNA.
public interface MyShell32 extends Shell32 {
MyShell32 INSTANCE = (MyShell32) Native.loadLibrary("shell32", MyShell32.class, W32APIOptions.DEFAULT_OPTIONS);
WinDef.HINSTANCE FindExecutable(String lpFile, String lpDirectory, char[] lpResult);
}
{
...
char[] returnBuffer = new char[WinDef.MAX_PATH];
shell.FindExecutable(filename, null, returnBuffer);
app = Native.toString(returnBuffer);
...
}
PathFindExtention() call is similar but returns a pointer so it's more straight forward.
Macintosh: I tried all sorts of things and finally decided to write my own tiny native library to call in objective C
rtnValue = [[NSWorkspace sharedWorkspace] getInfoForFile:filenameNS
application:&AStr
type:&TStr];
This library is tiny (but I may add to it if I need other native calls) but I need to write a C/C++ shell as well as the Objective C to get it to work. I then call this library JNA. Not that different from writing straight JNI but I found it easier to code.
public interface NSWWraper extends Library {
/** The instance **/
NSWWraper INSTANCE = (NSWWraper) Native.loadLibrary("NSWWraper", NSWWraper.class);
// CP_NSWWraper
Pointer FindFileInfo(String filename);
void FreeMem(Pointer memory);
}
I honestly haven't tested this calling this a large number of files so I don't know how much it slows down my code. JNA calls are supposed to be expensive. It's interesting timing on someone asking for my solution as I'd had to put this on back burner and only got it working on Windows yesterday. I was going to incorporate this into the rest of my project today.
Edited to add. I didn't use JINI because I found it's not being very well supported on a Macintosh anymore and JNA was the better solution for Windows and I had to use it anyway.

How do I load a local file from rhino embedded in a vendor product?

My question is pretty similar to How can I load a local file from embedded Rhino?.
Most of the suggestions I've have read suggested modifying java code, but I'm using Rhino that's embedded in vendor software (both Shibboleth and NetIQ IDM), so I don't have access to context in which Rhino exists (or the code that creates it), only the script engine that's been spawned in that context.
Corderer suggested doing something like...
eval("" + Packages.org.apache.commons.io.FileUtils.readFileToString(
new java.io.File("/the/local/root", "script.js");
));
...which works! Like Corderer, though, I was hoping for a less ugly solution (maybe actually being able to use load()). Is eval() the best / easiest option to do this?
Liam
Maybe I'm missing something but from what I understand, you just want to read a file on disk from within JavaScript. If so, you can do this:
var fileObj = new java.io.File("/the/local/root/somefile.txt");
This will basically give you access to a Java file object, which then you can manipulate to your heart's content. See the documentation for the java.io.File class to see what methods are available.
Edit: After further review of the question, it seems that you want to load a JavaScript source file from within JavaScript. If so, then you can use Rhino's built-in load command like so:
load("/the/local/root/script.js");
Years later, here's my take:
Create a Global object that has the missing load function.
g = new Packages.org.mozilla.javascript.tools.shell.Global(Packages.org.mozilla.javascript.Context.getCurrentContext());
this.load = g.load;
The g variable now holds the global object used in Rhino scripts.

Can java import text methods

To make my question abit more specific I'm wondering if a compiled java program can import methods from a simple "text.txt" file, basiclly from text characters?? Is this possible? If so how?
Yes it is possible, here is an example of how to do it: example. On that page a string is compiled but it is the same basic principle. If you read the stuff in your text file into a string you can do the same thing.
This can be done easily using BeanShell.
http://www.beanshell.org/
Been around for years, rock solid, works.
It can, but if you want those methods to be written in standard Java then it will require a bit of technical creativity.
Essentially, you can use the "Scripting API" ( http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html ). This API allows you to execute "scripts" in any language as part of your greater Java application. To get it to run Java, you'd need to create a ScriptEngine implementation which could take the source, run it through the compiler API ( http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html ), and execute it.
If the method doesn't have to be coded in Java, then you can use the scripting API pretty much out-of-the-box, along with one of the standard scripting engines. (The JavaScript engine is very well tested, for example).
All methods must be part of a class.
You can only use methods in bytecode.
IFF your text file defines an unique class, you can use the Java Compiler API and reflection to use such a method.

Categories