Skip to content

Commit

Permalink
switch to rhino instead of nashorn for Java 17 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
b3nn0 authored and faiteanu committed Apr 4, 2024
1 parent 80840e8 commit 17d074a
Show file tree
Hide file tree
Showing 6 changed files with 162 additions and 58 deletions.
1 change: 1 addition & 0 deletions .classpath
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@
<classpathentry kind="lib" path="lib/org.htmlunit/htmlunit-core-js-3.2.0.jar"/>
<classpathentry kind="lib" path="lib/org.htmlunit/htmlunit-cssparser-3.2.0.jar"/>
<classpathentry kind="lib" path="lib/org.htmlunit/neko-htmlunit-3.2.0.jar"/>
<classpathentry kind="lib" path="lib/rhino/rhino-1.7.14.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
14 changes: 4 additions & 10 deletions js/ariva.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,10 @@
// Hotfix 21.03.2023 Karl Heesch
// Hotfix 07.03.2024 @gnampf1

try {
load("nashorn:mozilla_compat.js");
var prejava8 = false;
var ArrayList = Java.type('java.util.ArrayList');
var Logger = Java.type('de.willuhn.logging.Logger');
} catch(e) {
// Rhino
var prejava8 = true;
var ArrayList = java.util.ArrayList;
};

var Logger = Packages.de.willuhn.logging.Logger;
var ArrayList = java.util.ArrayList;

var fetcher;
var webClient;
var url;
Expand Down
14 changes: 3 additions & 11 deletions js/finanzennet.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
try {
load("nashorn:mozilla_compat.js");
var prejava8 = false;
var ArrayList = Java.type('java.util.ArrayList');

} catch(e) {
// Rhino
var prejava8 = true;
var ArrayList = java.util.ArrayList;
};
importPackage(Packages.jsq.config);

var ArrayList = java.util.ArrayList;

var fetcher;
var wc;

Expand Down
72 changes: 72 additions & 0 deletions js/portfolioreport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
var ArrayList = java.util.ArrayList;
var Logger = Packages.de.willuhn.logging.Logger;

var fetcher;
var webClient;


var s,y1,m1,d1,y2,m2,d2;

function getAPIVersion() {
return "1";
};

function getVersion() {
return "2024-02-25";
};

function getName() {
return "PortfolioReport";
};

function getURL() {
return "https://www.portfolio-report.net/";
};



function prepare(fetch, search, startyear, startmon, startday, stopyear, stopmon, stopday) {
Logger.info("prepare...");
fetcher = fetch;
s = search;
y1 = startyear; m1 = startmon; d1 = startday;
y2 = stopyear; m2 = stopmon; d2 = stopday;
return new ArrayList();
}

function process(config) {
Logger.info("process...");
var webClient = fetcher.getWebClient(false);

var page = webClient.getPage("https://api.portfolio-report.net/securities/search/" + s);
var json = JSON.parse(page.getWebResponse().getContentAsString());
var uuid = json[0]["uuid"];

var startDate = new Date(y1, m1, d1);

var start = startDate.toISOString().substring(0, 10);
page = webClient.getPage("https://api.portfolio-report.net/securities/uuid/" + uuid + "/markets/XETR?from=" + start);
var jsondata = page.getWebResponse().getContentAsString();

var data = JSON.parse(jsondata);

var currency = data["currencyCode"];

var res = new ArrayList();
for (var i = 0; i < data["prices"].length; i++) {
var price = data["prices"][i];
var dc = new Packages.jsq.datastructes.Datacontainer();
dc.put("currency", currency);
dc.put("date", Packages.jsq.tools.VarTools.parseDate(price["date"], "yyyy-MM-dd"));
dc.put("last", Packages.jsq.tools.VarTools.stringToBigDecimal(price["close"]));

//dc.put("first", Packages.jsq.tools.VarTools.stringToBigDecimal(record.get("Open")));
//dc.put("last", Packages.jsq.tools.VarTools.stringToBigDecimal(price["close"]));
//dc.put("low", Packages.jsq.tools.VarTools.stringToBigDecimal(record.get("Low")));
//dc.put("high", Packages.jsq.tools.VarTools.stringToBigDecimal(record.get("High")));
//dc.put("currency", defaultcur);
res.add(dc);
}
fetcher.setHistQuotes(res);
}

Binary file added lib/rhino/rhino-1.7.14.jar
Binary file not shown.
119 changes: 82 additions & 37 deletions src/jsq/fetcher/history/GenericJSFetcher.java
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
package jsq.fetcher.history;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import jsq.config.Config;
import jsq.fetch.factory.Factory;

import org.htmlunit.SilentCssErrorHandler;
import org.htmlunit.ThreadedRefreshHandler;
import org.htmlunit.WebClient;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class GenericJSFetcher extends BaseFetcher {
import jsq.config.Config;
import jsq.fetch.factory.Factory;

private Invocable inv;


public class GenericJSFetcher extends BaseFetcher {
private Calendar start;
private Calendar stop;
private Calendar stop;

private Scriptable scope;

private File scriptFile;
private long modifiedTs;

/**
* Create a new generic fetcher from the JavaScript file passed in {@code filename}.
Expand All @@ -34,48 +34,80 @@ public class GenericJSFetcher extends BaseFetcher {
*/
public GenericJSFetcher(String filename) throws Exception {
try {
File f = new File(filename);
ScriptEngineManager manager = new ScriptEngineManager(null);
ScriptEngine engine = manager.getEngineByName("nashorn");
engine.put("fetcher", this);
engine.eval( new InputStreamReader(new FileInputStream(f),"utf-8"));

inv = (Invocable) engine;

this.scriptFile = new File(filename);
reloadScriptIfNeeded();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}

private Context enterContext() {
Context context = Context.enter();
context.setLanguageVersion(Context.VERSION_ES6);
context.setOptimizationLevel(-1);
context.getWrapFactory().setJavaPrimitiveWrap(true);
return context;
}

private void reloadScriptIfNeeded() throws Exception {
if (scriptFile.lastModified() == modifiedTs)
return;
modifiedTs = scriptFile.lastModified();

Context context = enterContext();

scope = context.initStandardObjects();
Object jsFetcher = Context.javaToJS(this, scope);
ScriptableObject.putProperty(scope, "fetcher", jsFetcher);


// print function is not part of default rhino
context.evaluateString(scope, "function print() { "
+ "Packages.jsq.fetcher.history.GenericJSFetcher.print(Array.from(arguments).map((x) => x.toString()).join(' '))"
+ "}", "", 1, null);

FileReader reader = new FileReader(scriptFile);
context.evaluateReader(scope, reader, scriptFile.getName(), 1, null);

context.exit();
}

public static void print(Object o) {
System.out.println(o.toString());
}

@Override
public String getName() {
return (String) callFunc("getName");
return (String) callFunc("getName", null);
}

@Override
public String getURL() {
return (String) callFunc("getURL");
return (String) callFunc("getURL", null);
}

public String getAPIVersion() {
return (String) callFunc("getAPIVersion");
return (String) callFunc("getAPIVersion", null);
}
public String getVersion() {
return (String) callFunc("getVersion");
return (String) callFunc("getVersion", null);
}

@Override
public void prepare(String search, int beginYear, int beginMon,
int beginDay, int stopYear, int stopMon, int stopDay) throws Exception {
reloadScriptIfNeeded();

super.prepare(search, beginYear, beginMon, beginDay, stopYear, stopMon, stopDay);
start = Calendar.getInstance();
start.setTime(getStartdate());
stop = Calendar.getInstance();
stop.setTime(getStopdate());
try {
Object x = inv.invokeFunction("prepare", this, search, beginYear, beginMon, beginDay, stopYear, stopMon, stopDay);
Object x = callFunc("prepare", new Object[] { this, search, beginYear, beginMon, beginDay, stopYear, stopMon, stopDay });
setConfig((List<Config>) x);
} catch (NoSuchMethodException | ScriptException e) {
} catch (Exception e) {
e.printStackTrace();
throw e;
}
Expand All @@ -86,8 +118,8 @@ public void prepare(String search, int beginYear, int beginMon,
public void process(List<Config> options) {
super.process(options);
try {
inv.invokeFunction("process", options);
} catch (NoSuchMethodException | ScriptException e) {
callFunc("process", new Object[] { options} );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Expand All @@ -111,20 +143,33 @@ public boolean within(Date d) {
(d.getTime() <= getStopdate().getTime());
}

public Object callFunc(String funcname) {
public Object callFunc(String funcname, Object[] args) {
try {
return inv.invokeFunction(funcname);
} catch (NoSuchMethodException | ScriptException e) {
Context context = enterContext();
if (args == null)
args = new Object[0];
Function f = (Function) scope.get(funcname, scope);
Object result = f.call(context, scope, f, args);
if (result instanceof NativeJavaObject)
result = ((NativeJavaObject) result).unwrap();
return result;
} catch (Exception e) {
e.printStackTrace();
}
} finally {
Context.exit();
}
return null;
}
public void search(String string) {
try {
inv.invokeFunction("search", this, string);
} catch (NoSuchMethodException | ScriptException e) {
Context context = enterContext();
Function f = (Function) scope.get("search", scope);
f.call(context, scope, f, new Object[] { string });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Context.exit();
}
}
}

0 comments on commit 17d074a

Please sign in to comment.