I am working on a Java program where an object needs to have user-customization behavior for one function. I am implementing this using Mozilla Rhino, JavaScript and Java.
I cannot figure out how to take the already instantiated object and pass it to a pre-written script.
I have looked through many tutorials on Rhino, and none have given an example like this. Any advice or links would be greatly appreciated.
Thank you for your time.
This answer to another question passes an object, data, from Java to Rhino Javascript.
I have no idea whether or not it works (well I suppose it does). Here are the relevant parts:
public static class data {
Double value = 1.0d;
}
ScriptEngine engine = new ScriptEngineManager().getEngineByName ("rhino");
data data = new data();
Context.enter().getWrapFactory().setJavaPrimitiveWrap(false);
engine.eval("function test(data) { return data.get('value1') + 5;};");
System.out.println("Result:" + ((Invocable)engine).invokeFunction("test", data));
(I didn't know about that setJavaPrimitiveWrap(), here is some WrapFactory Javadoc.)
Related
I want to run JavaScript code at the server side. I want to manipulate result returned by JavaScript inside my Java code. How can it be done?
The start is clearly to look into rhino.
I think you will find this 3 links very useful
JavaScript EE, Part 1: Run JavaScript files on the server side
JavaScript EE, Part 2: Call remote JavaScript functions with Ajax
JavaScript EE, Part 3: Use Java scripting API with JSP
You can also have a look to helma
Helma is a server-side Javascript environment and web application framework for fast and efficient scripting and serving of your websites and Internet applications.
Helma is written in Java and employs Javascript for its server-side scripting environment ...
The other answers are correct that if you want to execute Javascript on the server side, you'd need to evaluate it in the context of a JS runtime.
However, I'm not convinced that this is exactly what you're asking. I think there may be a chance that you want to run some "typical" JS functionality that relates to how the page is displayed on the client's machine or interacted with on the client - and that will not be possible to run on the server side.
As a concrete examples:
If you want to run some kind of algorithm in JS without porting it to Java - say, you have some opaque Javascript code that generates a particular sequence given a seed - this would work fine if you run it on Rhino on the server.
If you want to invoke a Javascript function while creating the page, rather than while it's running - say, to get the user's colour depth/screen resolution and change how the page is generated - then this will not be possible from the server, as there is no client at this point to query.
Broadly speaking, any Javascript that involves document or navigator or even any elements of the page itself, is likely to fall into the latter category.
If you really need to get information about the client environment in order to control how the page is rendered, this must be extracted from the client on the previous page, and encoded into the request (as query parameters or form data). These parameters can then be read directly on the server and used to control the output.
Remember that when your code is running on the server side, you're creating a page (ultimately a bunch of HTML, CSS and JS) that will be sent to the client once it's done - at this point there is no client yet and so you can't interact with them.
Apologies if I've got the wrong end of the stick on this one, but this type of question is typically asked by people who haven't grasped the client/server separation.
You need a JS runtime inside of a Java runtime. One way to do this is Rhino
You execute the JavaScript with Rhino, a JavaScript library for Java.
You can use RHINO or NASHORN.
public class RhinoApp {
private String simpleAdd = "var z=9; z*=9";
public void runJavaScript() {
Context jsCx = Context.enter();
Context.getCurrentContext().setOptimizationLevel(-1);
ScriptableObject scope = jsCx.initStandardObjects();
Object result = jsCx.evaluateString(scope, simpleAdd , "formula", 0, null);
Context.exit();
System.out.println(result);
}
This example should clearly state how to load, evaluate and execute a Javascript function in Java:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
URI source_js = JavascriptExecutor.class.getResource("/file.js").toURI();
String source_text = Files.readAllLines(Paths.get(source_js)).stream().collect(Collectors.joining("\n"));
engine.eval(source_text);
Invocable inv = (Invocable) engine;
Object returnValue = inv.invokeFunction("functionJsName", "functionJsParameter");
System.out.println(returnValue.toString());
i have a SAP-DLL to enable communication between a Programming interface and the SAP Programm.
I have following example Code for c# in combination with the dll-File:
var loggerService = LoggerService.GetLoggerService("FileLogger");
var itasProxy = SapProxyFactory.CreateSapProxy(SapSystem.Example, loggerService, "Example_User", StringExtension.CreateSecureString("Example_Password"));
var funcResult = sapProxy.SearchSapAddress(clientNo);
if (funcResult.Successfull)
{
funcResult.ReturnValue = withFormatting
? AddressFormatter.SplitStreetHouseNo(funcResult.ReturnValue)
: funcResult.ReturnValue;
}
Now i want the same functionality to be transferred to java. I have absolutely no clue how to do that. I tried the following with Loggerservice as a starter, but it doesn't work:
public class SAPConnector {
public static void main(String[] args) {
// TODO Auto-generated method stub
connectSAP();
}
public void connectSAP()
{
System.load("C://Temp//SapConnector.dll");
Object loggerService = getLoggerService("FileLogger");
}
public native Object getLoggerService(String lcLogger);
}
i just need some kind of information how to call the Functions from the dll or an example how to transfer the C# Code to working Code in Java.
Greetings,
Kevin
DLL is Microsoft format. Java is cross-platform, thus can't acknowledge anything operating-system specific, such as DLL.
One way around that is to use JNI (Java Native Interface), but that's usually not a good solution, as it makes your program platform-dependent.
Instead, I would look for a JAR from SAP, that provides a similar interface.
Maybe something along SAP JCO.
You can see some actual code examples using JCO here, and some technical information on step-by-step download and configure here.
I'm very new in using web services. Appreciate if anyone can help me on this.
In my PHP codes, I'm trying to use the SOAP web services from another server (JIRA, java). The JIRA SOAP API is shown here.
$jirasoap = new SoapClient($jiraserver['url']);
$token = $jirasoap->login($jiraserver['username'], $jiraserver['password']);
$remoteissue = $jirasoap->getIssue($token, "issuekey");
I found that my codes have no problem to call the functions listed on that page. However, I don't know how to use the objects returned by the API calls.
My question are:
In my PHP codes, how can I use the methods in the Java class objects returned by SOAP API calls?
For example, the function $remoteissue = $jirasoap->getIssue($a, $b) will return a RemoteIssue. Based on this (http://docs.atlassian.com/rpc-jira-plugin/latest/com/atlassian/jira/rpc/soap/beans/RemoteIssue.html), there are methods like getSummary, getKey, etc. How can I use these functions in my codes?
Based on some PHP examples I found from the internet, it seems that everyone is using something like this:
$remoteissue = $jirasoap->getIssue($token, "issuekey");
$key = $remoteissue->key;
They are not using the object's methods.
Refer to this example, it seems that someone is able to do this in other languages. Can it be done in PHP too?
The problem I'm facing is that, I am trying to get the ID of an Attachment. However, it seems that we can't get the Attachment ID using this method: $attachmentid = $remoteattachment->id;. I am trying to use the $remoteattachment->getId() method.
In PHP codes, after we made a SOAP API call and received the returned objects, how do we know what data fields are available in that object?
For example,
$remoteissue = $jirasoap->getIssue($token, "issuekey");
$summary = $remoteissue->summary;
How do we know ->summary is available in $remoteissue?
When i refer to this document (http://docs.atlassian.com/rpc-jira-plugin/latest/com/atlassian/jira/rpc/soap/beans/RemoteIssue.html), I don't see it mention any data fields in RemoteIssue. How do we know we can get key, summary, etc, from this object? How do we know it is ->summary, not ->getsummary? We need to use a web browser to open the WSDL URL?
Thanks.
This question is over one year old, but to share knowledge and provide an answer to people who have this same question and found this page, here are my findings.
The document mentioned in the question is an overview of the JiraSoapService interface. This is a good reference for what functions can be called with which arguments and what they return.
If you use Java for your Jira SoapClient the returned objects are implemented, but if you use PHP, the returned objects aren't of the type stated in this documentation and do not have any of the methods mentioned. The returned objects are instances of the internal PHP class stdClass, which is a placeholder for undefined objects. The best way to know what is returned is to use var_dump() on the objects returned from the SoapCalls.
$jirasoap = new SoapClient($jiraserver['url']);
$token = $jirasoap->login($jiraserver['username'], $jiraserver['password']);
$remoteissue = $jirasoap->getIssue($token, "PROJ-1");
var_dump($remoteissue);
/* -- You will get something like this ---
object(stdClass)#2 (21) {
["id"]=> string(3) "100"
["affectsVersions"]=> array(0) { }
["assignee"]=> string(4) "user"
...
["created"]=> string(24) "2012-12-13T09:27:49.934Z"
...
["description"]=> string(17) "issue description"
....
["key"]=> string(6) "PROJ-1"
["priority"]=> string(1) "3"
["project"]=> string(4) "PROJ"
["reporter"]=> string(4) "user"
["resolution"]=> NULL
["status"]=> string(1) "1"
["summary"]=> string(15) "Project issue 1"
["type"]=> string(1) "3"
["updated"]=> string(24) "2013-01-21T16:11:43.073Z"
["votes"]=> int(0)
}
*/
// You can access data like this:
$jiraKey = $remoteissue->key;
$jiraProject = $remoteissue->project;
The document you referred to in #2 is to a Java implementation and really doesn't give you any help with PHP. If they do not publish a public API for their service (which would be unusual), then using the WSDL as a reference will let you know what objects and methods are accepted by the service and you can plan your method calls accordingly.
The technique you used to call getIssue(...) seems fine, although you should consider using try...catch in case of a SoapException.
I have used Jira SOAP in .NET project and IntelliSense hinted me what fields are available for returned object.
You can use something like VS.Php for Visual Studio or Php for Visual Studio if you are using Visual Studio.
Or you can choose one of the IDEs from here with support of IntelliSense.
Can anybody show an example of how to use heap.heapForEachClass in a select statement?
It would be great if you could provide some links with different examples of queries (other than those in the oqlhelp page of course :) )
I don't believe heap.forEachClass() is meant to be used in a select statement, at least not directly. Consider the fact that it doesn't return anything:
var result=heap.forEachClass(function(it){return it;});
typeof result
//returns undefined
The OQL used in jhat and VisualVM does support plain ol' JavaScript, just like the "query" I use above. I believe that the heap.forEachClass() finds more use in either JavaScript-style queries or in JavaScript functions within select-type queries.
That said, I don't know why this function exists since the heap.classes() enumeration is much easier to use, both with with select-style queries and plain JavaScript ones.
You could even even recreate the same functionality as heap.forEachClass() with the following JavaScript function:
function heapForEachClass(func){
map(heap.classes(),func)
return undefined;
}
Any sample queries that I could provide you would likely be easier written with heap.classes(). For example, you could use heap.forEachClass() to get list of all classes:
var list=[];
heap.forEachClass(function(it){
list.push(it);
});
list
but this is more complicated than how you'd do it with heap.classes():
select heap.classes()
or just
heap.classes()
I've used this function before to look for classes that are loaded multiple times (usually, this happens when two different class loaders load the same lib taking more memory for no reason, and making the JVM serialize and deserialize objects passed from one class instance to the other -because it doesn't know that they are actually the same class-)
This is my OQL script that selects (and count) classes that has the same name:
var classes = {};
var multipleLoadedClasses = {};
heap.forEachClass(function(it) {
if (classes[it.name] != null) {
if (multipleLoadedClasses[it.name] != null) {
multipleLoadedClasses[it.name] = multipleLoadedClasses[it.name] + 1;
} else {
multipleLoadedClasses[it.name] = 1;
}
} else {
classes[it.name] = it;
}
});
multipleLoadedClasses;
hopes that this will help further visitors ;)
like code:
public static void main(String[] args) throws Exception {
String content="<HTML>"
+"<HEAD><TITLE>title</TITLE></HEAD>"
+"<BODY>"
+"<script>var jsvar=123;</script>"
+"</div>"
+"</BODY>"
+"</HTML>"
;
}
in this case,how to get jsvar variable value?
thanks for help :)
If you want to execute JavaScript code in Java, You can use scripting API of Java 6 and Java 6 is included with Mozilla Rhino engine.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
jsEngine.eval("jsvar = 123");
System.out.println(jsEngine.get("jsvar")); //prints 123.0
Reference: http://download-llnw.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html
Seems to me that this is backward. If you are serving the page then you already have the value on the server. I would inject the value from Java into JavaScript not the other way around.
In fact, you're asking something that requires a browser. As a consequence, you may have to take a look at HtmlUnit, which could solve your issue.
However, were you to directly run pure javascript code from Java, you would have better using a Javascript interpreter like Rhino (I think).