from what I've read it seems to be possible to run some javascript within a java program, however I'm still struggling on fully grasping how. Would I be able to do enough to execute a googlemap api to be displayed in my java program?
The two examples of code that I have been looking at is this in java:
import javax.script.*;
public class script {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script = "function hello(name) { print('Hello, ' + name); }";
// evaluate script
engine.eval(script);
// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
Invocable inv = (Invocable) engine;
// invoke the global function named "hello"
inv.invokeFunction("hello", "Scripting!!" );
}
}
and this as an example found on the google doc site in javascript to produce this:
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var markers = [];
for (var i = 0; i < 100; i++) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var marker = new google.maps.Marker({'position': latLng});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
If any of you can assist me in understanding how to integrate these two samples of code so that the map appears in a JPanel instead of "hello world", I think I could figure the rest of it out.
UPDATE: After reading through the terms of usage, I found out that I would be violating the terms, however; if I move the map onto our organizations public site, I should be able to load the result of that script into my Java programs JPanel which would give public access to the map and not be in violation. Am I correct? Is this possible to do? I don't have any experience with javascript.
I don't know much about integrating Google map script with or the integration policies.
But, you can execute JavaScript file from your java code.So i feel you can write your script code in a js file and execute it as follows :
import javax.script.*;
public class EvalFile {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from given file - specified by first argument
engine.eval(new java.io.FileReader(yourfile.js));
}
}
For more info please refer this link http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html. I hope it may help you
Related
I extracted uglifyJs2 via uglifyjs --self and I'm trying to minify app.js using uglify.js. I expect, that minified js should be generated into new file or console at least but now it doesn't work. What should I do to minify app.js using uglify.min.js?
public static void main(String[] args) throws Exception {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
Bindings bindings = new SimpleBindings();
bindings.put("console", System.console());
executeJs("uglifyjs.min.js",scriptEngine, bindings);
String res = (String) invocable.invokeFunction("UglifyJS.parse(code)", code);
//Here I got NoSuchMethodException: No such function UglifyJS.parse(code)
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
private static void executeJs(String fileName, ScriptEngine engine, Bindings bindings) throws Exception {
String test = readFile(fileName, StandardCharsets.UTF_8);
engine.put(ScriptEngine.FILENAME, fileName);
engine.eval(test, bindings);
}
When i mo
invokeFunction can be used to invoke only global functions. It can not be used to evaluate arbitrary code like you've above. The following will work:
// define a global function that accepts one arg and invoke UglifyJS.parse on it
scriptEngine.eval("function func(code) { return UglifyJS.parse(code) }");
// call the newly defined global function "func"
invocable.invokeFunction("func", code);
As an alternative...
ScriptObjectMirror uglify = (ScriptObjectMirror)this.scriptEngine.eval("UglifyJS");
String ugly = (String)uglify.callMember("parse", "mycode");
It does appear a wee bit slower in 100,000 calls of uglify.callMember(...) on my system its about 150ms slower. It didn't seem to make any improvement by first calling uglify.getMember("parse") and using call directly on that object.
It does however avoid a naming conflict
Let's say that you have a web page that only contains obfuscated Javascript in the form of an eval(...) function within a script tag.
Dean Edwards' online unpacker (link) correctly unpacks this Javascript.
I would like to write a simple Java class that loads the initial web page (I use HttpClient), extracts the eval(...) function from the HTML, and unpacks it, in order to obtain the de-obfuscated Javascript.
I've tried with Rhino, here's my code :
int start = html.indexOf("<script>eval") + "<script>".length();
int end = html.indexOf("</script>");
javascript = html.substring(start, end);
evaled = eval(javascript);
NativeFunction fEvaled = (NativeFunction) evaled;
String encodedSource = fEvaled.getEncodedSource();
log.info("encodedSource: " + encodedSource);
and the "eval" java function called:
private Object eval(String javascript){
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Object eval = null;
try {
eval = engine.eval(javascript);
} catch (ScriptException e) {
// TODO Auto-generated catch block
log.error("Exception evaluating javascript " + javascript, e);
}
return eval;
}
But, that doesn't work, the code returned is far from being the correct code (returned by Edwards' unpacker). I've inspected the Rhino variables, found nothing useful.
Am I doing something wrong ?
I'm open to any suggestion, for example if there's a command-line tool that will work I can make a system call.
I'm on Ubuntu.
Thanks.
I have no idea how to do this and found some examples of how to call it however creating the script in java code (what I don't want), in ASP.NET I would use this code ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "info only", "alert('" + message + "');", true); to call my script + pass parameters and would work fine as I wished. However I have no idea of how to do this in java. Thank you
Simply by googling I found this link which provides good examples on how to invoke a javascript file.
Here is a simple example to get you going:
import java.io.*;
import javax.script.*;
public class App
{
public static void main(String[] args)
{
String file = "javascript.js";
try
{
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("javascript");
FileReader fr = new FileReader(file);
engine.eval(fr);
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
catch(ScriptException scrEx)
{
scrEx.printStackTrace();
}
}
}
I saw that it wasn't possible to call my javascript via Servlet, however if I just pass my parameters using my resp/req objects and retrieve them in my JSP page and my JSP page call myt javascript method would work.
Anyway here is the code I used:
Check if my params arent empty and call my script
<c:if test="${not empty errors}">
<script>displayErrors(errors);</script>
</c:if>
The script I would like to call (sample):
<script>
var errors = ${errors};
if (errors.length) {
displayErrors(errors);
}
</script>
And I found this answer here (How to call function of JavaScript from servlet)
Big thanks for everybody
i'm using Flex 4 Native Process to interact with Java to connect to a remote server using PHP.
I tried this example i found on the internet to connect Flex with Java:
Flex:
protected function windowedApplication1_creationCompleteHandler(event: FlexEvent): void
{
var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();
info.executable = new File("C:/Program Files/Java/jre6/bin/java.exe");
info.workingDirectory = File.applicationDirectory;
var args: Vector.<String> = new Vector.<String>();
args.push("-cp", "../bin", "scanner.Main");
info.arguments = args;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onDataOutput);
process.start(info);
}
private function onDataOutput(event: ProgressEvent): void
{
var message:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
Alert.show(message);
}
Java:
public static void main(String[] args)
{
String input;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext("hello|stop"))
{
input = scanner.next();
if (input.equals("hello"))
{
System.out.println("hello flex! ... from java");
}
else if (input.equals("stop"))
{
return;
}
}
}
And it works perfect.
But when i try calling the Java method that connects to the remote server, switching the line System.out.println("hello flex! ... from java"); for the name of the method, it dies (does nothing).
I'm new to the Native Process concept, but researching on the web i found out that you need to send the libraries as arguments that your project uses.
I need some help on how to do so.
The Java project uses Http and JSon libraries.
How do i add those to the arguments? and do i need to add the JRE System libraries too?
PS: The java method works fine if i execute it from eclipse.
Thank you.
Edit: Tried it with a Jar file
var file:File = new File("C:/Program Files/Java/jre6/");
file = file.resolvePath("bin/javaw.exe");
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("prueba3.jar").nativePath);
arg.push("-Djava.library.path=C:\\Users\\Administrador\\Desktop\\libhttp");
var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
npInfo.executable = file;
npInfo.arguments = arg;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData);
process.start(npInfo);
and adding the library path, but still didn't work.
You could make a AMFPHP service, and connect directly to PHP with AS3
Does this code require the Digital Persona One Touch RTE (Runtime environment) to work?:
DPFPVerification verifier = DPFPGlobal.getVerificationFactory().createVerification();
If so, is there another way to verify Digital Persona SampleFeatures (serialized) against a Digital Persona Template (serialized) using only the dpfp JARs?
Reason: We plan to have our DPFP verifier on a Web Service provided by TIBCO.
Any help is greatly appreciated!
I get a Java JNI exception with this sample test main code:
import com.digitalpersona.onetouch.DPFPFeatureSet;
import com.digitalpersona.onetouch.DPFPFeatureSetFactory;
import com.digitalpersona.onetouch.DPFPGlobal;
import com.digitalpersona.onetouch.DPFPTemplate;
import com.digitalpersona.onetouch.DPFPTemplateFactory;
import com.digitalpersona.onetouch.verification.DPFPVerification;
import com.digitalpersona.onetouch.verification.DPFPVerificationResult;
public class Main {
/**
* fingerScanTemplate is from WC DB
* sample is from the WS input parameters
*/
public boolean performVerification(byte[] fingerScanTemplate, byte[] sampleFeatures) {
DPFPTemplateFactory templateFactory = DPFPGlobal.getTemplateFactory();
DPFPFeatureSetFactory featureSetFactory = DPFPGlobal.getFeatureSetFactory();
DPFPVerification verifier = DPFPGlobal.getVerificationFactory().createVerification();
// Deserialize template & sampleFeature
DPFPTemplate deserializedTemplate = templateFactory.createTemplate(fingerScanTemplate);
DPFPFeatureSet features = featureSetFactory.createFeatureSet(sampleFeatures);
//Compare the feature set with the template, based on which finger was captured
DPFPVerificationResult result = null;
result = verifier.verify(features, deserializedTemplate);
return result != null && result.isVerified();
}
/**
* #param args
*/
public static void main(String[] args) {
new Main().performVerification(null, null);
}
}
No you should not need some sort of RTE. I do know that I had to have the One Touch SDK installed because it runs a windows service called Biometric scanning or something similar. The main problem I see with your code is that:
DPFPVerificationResult result = null;
result = verifier.verify(features, deserializedTemplate);
Needs to be:
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
verifier.verify(features, template, ref result );
At least that is what got my code to start verifying correctly. I also had to fix a programmer's mistake in creating the FeatureSet which needs to be done like this:
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
I have a feeling you are using an older SDK than I am but maybe this will help out some.