I'm looking to invoke a Java program from RPG running on Iseries V5r4. The remote program is a web service client (performing a postcode lookup), running in Websphere.
Ideally I'd like to call it direct from RPG? is that possible? or do I have to create a java program to run on the iSeries and use RMI or something to call the remote java program.
We aren't keen on calling the extenral webservice direct as it means opening path from otherside world direct to iSeries.
I'm not an RPG programmer, just looking for something to point our guys in the right direction or anything I need to enable to make the java programs more consumable for the RPG folks.
Thanks,
Scott
Since the program is running on a remote server, you can't call it directly from RPG. Given that it's a web service, I would create a Java program to run on the iSeries and call that Java program from within RPG. Nowaday's, RPG can interface directly with Java. You have to create some D-specs to declare the class and prototype out the method calls. In the following example, assume a Java class exists called ServiceCaller in the package 'tools'. It has a single method called getServiceReply which accepts three character fields and returns an integer.
*Define the Java class locally.
DServiceCaller S O CLASS(*JAVA:'tools.ServiceCaller')
*Class constructor. No parameters.
DnewServiceCaller PR O EXTPROC(*JAVA:
D 'tools.ServiceCaller':
D *CONSTRUCTOR)
D CLASS(*JAVA:'tools.ServiceCaller')
*GetServiceReply.
*public int getServiceReply(byte[] parm1, byte[] parm2, byte[] parm3)
DgetServiceReply PR 10I 0 EXTPROC(*JAVA:
D 'tools.ServiceCaller':
D 'getServiceReply')
D Parm1 400A CONST
D Parm2 400A CONST
D Parm3 400A CONST
Your RPG calc specs will look something like this free-form example:
/free
ServiceCaller = newServiceCaller();
iReply = getServiceReply(ServiceCaller:'Parm1':'Parm2':'Parm3');
/end-free
Inside the java code, within the getServiceReply method, convert those byte arrays to strings like this:
sParm1 = new String(parm1);
sParm2 = new String(parm2);
sParm3 = new String(parm3);
Granted, this is an oversimplified example and your application needs will be slightly different. You will want to add error handling code in case the web service doesn't reply. You may also want to use getters and setters in your class. It all depends on your application needs and the requirements of the remote web service.
Some notes on RPG types to Java types:
RPG Type Java Type
10I 0 int
3I 0 byte
5I 0 short
20I 0 long
N boolean
A byte[]
If you are feeling particularly ambitious, you can call the native Java HTTP classes from within your RPG. But I've found that a custom Java program to act as an in-between that is written specifically to talk to RPG is an easier way to go. Although RPG can talk to Java, it's not as pretty as Java talking to Java.
Additional information on calling Java from RPG can be found in the ILE RPG Programmer's guide. The V5R4 version can be found here: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/books/sc092507.pdf
Since the is a web service, another solution would be to use Scott Klement's HTTP API. It's available on his website at http://www.scottklement.com/httpapi/.
One of the big benefits for me is this is entirely RPG and doesn't use any Java which can be a bit sluggish sometimes. I'm not real familiar with how web services work in Java but it appears that you don't have to form all of the XML and it's done for you. With the HTTP API you would need to do that yourself.
Also Scott Klement has several other useful things on his website. Another site with some neat tools is http://www.think400.dk/downloads.htm.
Related
I am new to java and DLL-s
I need to access DLL's methods from java. So go easy on me.
I have tried using JNA to access the DLL here is what I have done.
import com.sun.jna.Library;
public class mapper {
public interface mtApi extends Library {
public boolean IsStopped();
}
public static void main(String []args){
mtApi lib = (mtApi) Native.loadLibrary("MtApi", mtApi.class);
boolean test = lib.IsStopped();
System.out.println(test);
}
}
When I run the code, I am getting the following error:
Exception in thread "main" java.lang.UnsatisfiedLinkError:Error looking up function 'IsStopped':The specified procedure could not be found.
I understand that this error is saying it cannot find the function, but I have no idea how to fix it.
I am trying to use this API mt4api
and here is the method, I am attempting to access MQL4
Can anyone tell me what I am doing wrong?
I have looked at other alternatives, like jni4net, but I cannot get this working either.
If anyone can link me to a tutorial that shows me how to set this up, or knows how to, I would be greatfull.
Trading?Hunting for milliseconds to shave-off?Go rather into Distributed Processing... Definitely safer than relying on API !
While your OP was directed onto how bend java to call .NET DLL-functions,
let me sketch a much future-safer solution.
Using AI/ML-regression based predictors for FOREX trading, I was hunting in the same forest. The best solution found within the last about 12-years, having spent about a few hundreds man*years of experience, was setup in the following manner:
Host A executes trades: operates MetaTrader Terminal 4, with both Script and EA --- the distributed-processing system communicates with with a use of ZeroMQ low-latency messaging/signalling framework ( about a few tens of microseconds needed )
Host B executes AI/ML processing of predictions for a traded instrument ( about a few hundreds of microseconds apply )
Cluster C executes continuous AI/ML predictor re-trainings and HyperParameterSPACE model selections ( many CPU-hours indeed needed, continuous model self-adapting process running 24/7 )
Signalling / Messaging layer with ZeroMQ has ports and/or bindings available and ready for most of the mainstream and many of niche programming languages, including java.
Hidden dangers of going just against a published API:
While the efforts for system integration and testing are immense, the API specifications are always dangerous for specification creeping.
This said, add countless man*months consumed on debugging after a silent change in MT4 language specifications that de-rail your previous tools + libraries. Why? Just imagine. Some time ago, MQL4 stopped to be MQL4 and was silently shifted towards MQL5, under a name New-MQL4. Among other changes in compilation, there were many small and big nails in the coffin -- string surprisingly ceased to be a string and was hidden as an internal struct -- which one could guess what will cause with all DLL-calls.
So, beware of API creepings.
Does it hurt a distributed processing solution?
No.
With a wise message-layout design, there are no adverse effects of MetaTrader Terminal 4 behaviour and all the logic ( incl. the strategy decision ) is put outside this creeping platform.
Doable. Fast and smart. Also could use remote-GPU-cluster processing, if your budget allows.
Does it work even in Strategy Tester?
Yes, it does.
If anyone has the gut to rely on the in-built Strategy Tester, the distributed-processing model still works there. Performance depends on the preferred style of modelling, a full one year, tick-by-tick simulation, with a quite complex AI/ML components took a few days on a common COTS desktops PC-systems ( after years of Quant R&D, we do not use Strategy Tester internally at all, but the request was to batch-test the y/y tick-data, so could be commented here ).
I'm writing my first Java project for Semantic Web using Jena framework.
My ontology was peopled and now I'd like to use some SPIN function (they weren't written by me) in my project.
They are very simple: they receive 2 string arguments and return 1 string.
I never do this kind of project so I don't know from where I can begin.
Can you help me?
The question lacks far too many details, but a wild guess may be that you want to use this in the form:
SELECT *
WHERE {
...
BIND(spin-function(?param1, ?param2) AS ?result)
...
}
That assumes that the Jena framework you are using has SPIN installed.
I have a Java application that I want to automate for testing. Unfortunately, the app window only registers as a SunAWTFrame, which means none of the controls are exposed to typical window analysis and automation tools.
My search has lead me to C# and utilising Java Access Bridge DLLS in a C# program to automate it.
Has anyone had any experience of this?
Oracle provides JavaAccessBridge (JAB) with some DLLS to help with this as I understand it after reading a few articles around the internet. There are some code examples but I'm really not groking it right now. By breaking it down, I think this is what needs to be achieved:
Import / load / parse the JAB dlls
Map functions in the JAB dll to methods / calls within my program
Have the Java application to automate run (with JAB enabled) and get handle of it to my program
Utilise the JAB functions to control the Java application
I don't know C# as well as I know Java, but that's not going to stop me.
If anyone can provide help, guidance, pointers or anything to get me started, that'd be truly awesome.
As of 2019 we have a great tool AccessBridgeExplorer created and open-sourced by google. It's a really good staring point that contains a WindowsAccessBridgeInterop project which encapsulates almost every JAB API into a class oriented, .NET friendly assembly.
One notable thing, AccessBridge.Initialize() must be called in WPF/WinForm UI thread or in your own messaging pump thread, otherwise some methods like AccessBridge.EnumJvms() will always return false/empty.
Building on Stackia's great tip to use Google's AccessBridgeExplorer, Here are some tips to get you going:
Download Access Bridge Explorer
Use the WindowsAccessBridgeInterop.dll in your own (WinForms not Console) project (Add> Project Reference> Select the DLL)
Create a new access bridge object
AccessBridge Java = new AccessBridge();
Initialize the Access Bridge object
Java.Initialize();
Call Application.DoEvents() - A hack to wait for Java.Initialize to complete (My simple understanding is Java Access Bridge Uses a hidden window or similar)
Application.DoEvents(); //this waits for Java Bridge to initilize ;)
Get the handle of the Java Window
(plenty of examples online of how to get a Window Handle in C#)
Get Access to the Java Object that represents the window:
Java.Functions.GetAccessibleContextFromHWND(Handle, out int vmid, out JavaObjectHandle javaObjectHandle);
Get AccessibleWindow Object for Window (so you can find its children)
AccessibleWindow win = Java.CreateAccessibleWindow(handle);
Come up with your own way to cycle through the children, and the childrens children until you find the object you are after:
//Similar to:
foreach(var child in win.GetChildren())
JavaObjectHandle? javaObject = Java.Functions.GetAccessibleChildFromContext(node.JvmId, parentJavaObject, child.GetIndexInParent());
//to get the label or title of the object:
child.GetTitle();
To Interact with an object (eg click a button), do similar to the following:
(please note where it says JavaObject - it means the child java object (eg. to click a button you need to get the JavaObject for that button using GetAccessibleChildFromContext as i mentioned above)
//Get Possible Actions
JavaAutomation.Java.Functions.GetAccessibleActions(VMID, JavaObject, out AccessibleActions accessibleActions);
foreach( var action in accessibleActions.actionInfo)
{
Log.Info($"DoAction: {action.name}");
}
AccessibleActionsToDo accessibleActionsToDo = new AccessibleActionsToDo();
accessibleActionsToDo.actions = accessibleActions.actionInfo;
accessibleActionsToDo.actionsCount = accessibleActions.actionsCount;
//Do Actions
JavaAutomation.Java.Functions.DoAccessibleActions(VMID, JavaObject, ref accessibleActionsToDo, out int failure);
I am aware we can use ScriptEngineManager to execute scripts for example: java script.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
}
}
But this is a very trivial example and I am not sure in what real scenarios ScriptEngineManager can be used? Please elaborate.
Let me try to answer this from my project standpoint.
We have a framework that will make outbound calls and allow the integrators to extract the portions from json response and map it into internal data model.
This is completely driven by metadata, integrator uses the jsonpath (similar to xpath but for json ) to specify what to extract and what to map it to.
But there are times, where the integrator want to specify some of these conditionally.
For example, if the json value extracted is null, I want model to have 0.
If the array length is 0, then i want to use certain value.
We have exposed these logic as javascript. We execute the javascript using this engine to find out what the inetgrator wanted to do with the data ( basically we execute the script provided by integrator on the data obtained and set that value on the model, which eventually gets persisted )
Hope this answers your question.
There are many possible uses. For example: automation. The Microsoft Office programs and also Adobe Photoshop can run scripts to automatically execute functions of the program. You could use the Java script engine API for something similar in a Java application.
I used it once in a project where our software had to do some complex data processing. Certain parts of the processing could be customized by running a script. The advantage of this was that the script could be modified easily; if we would have written the custom processing in Java that would mean that every time when some small change was necessary, we would have to make a whole new build of the system.
Going by the differences, Java is statically typed, implying, the program written in Java, is first compiled and then run but in case of dynamically typed languages, like JavaScript and Python, we can execute even a part of the program for it is not compiled as a whole as such.
Coming to the question, suppose you have a server(eg: WildFly) on which you have deployed your application. Now building and hosting is a time intensive process, thus if you have to make any small change, you'll have to rebuild it and then again go through that time consuming process but if you could have used any dynamically typed language like JavaScript in place of it, it would have taken no time and in the next implementation, you would have been ready with the updated code. That's the main advantage of using JS and thus ScriptEngine was added in JSR.
Currently I'm working with JBoss to add ScriptEngine functionality to their WildFly server so have been spending time with it in the real time.
Hi
I want to write a program to be able to parse & execute some files
The file consists of some custom commands (I want to be able to define commands and appropriate methods so when program see that command it should execute the appropriate method)
It's grammar is not important for me; I just want to be able to define commands
Something like a simple and small interpreter written in java.
Is there any library for this purpose?
Or I need to write by myself?
Thanks
Java 6 (and newer) have this in the standard library: have a look at the API documentation of the package javax.script. You can use this to run scripts from your Java program (for example to automate your program) using any scripting language for which there is a plug-in engine available for the javax.script API. By default, support for JavaScript is supplied.
See the Java Scripting Programmer's Guide.
Simple example from that guide:
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
engine.eval("print('Hello, World')");
}
}
Have you considered looking at BeanShell?
Provides for having Java-like snippets interpreted at runtime.
If you need a bit more than that, then consider embedding e.g. JPython or another small interpreter. Just choose one that is JSR-233 compliant to get generic debugging support.
What you need is called "scripting engine". Quick search reveals Rhino. This is a good option cause it's JavaScript, and many people know JavaScript and there exists a certain amount of third-party extensions (libraries and code snippets) for it.
You could use ANTLR, but you will have to define a grammar (the parser will be generated for you).
Check this expression elevator example, it is similar to your problem, but instead of reading files it reads from the standard input.
If you choose ANTLR, take I look at ANTLRWorks, it is a GUI that will help with ANTLR development (I think it is also available as an Eclipse plugin).
I know this an old thread, but some time ago I've implemented a small interpreter for language similar with JavaScript (with more restrictions), the code is published in Github at https://github.com/guilhermelabigalini/interpreter
But it does support IF/CASE/LOOPS/FUNCTIONs, see below:
function factorial(n) {
if (n == 1)
return 1;
return n * factorial(n - 1);
}
var x = factorial(6);