Java ScriptEngine cannot find module referenced by Javascript file - java

I am using Java 7, and I have the following code that uses the jsondiffpatch Javascript library:
logger.debug("CURRENT PATH=" + Paths.get("").toAbsolutePath());
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
reader = new FileReader("webclient/common/js/jsondiffpatch.min.js");
engine.eval(reader);
If you look at line 48 of jsondiffpatch.js (the uncompressed version of jsondiffpatch.min.js), you can see it references another module:
var packageInfoModuleName = '../package.json';
When executing the Java code, the engine.eval(reader) line can't find package.json and throws the following exception:
javax.script.ScriptException: Error: Cannot find module '../package.json' in <Unknown source> at line number 1
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:224) ~[na:1.7.0_51]
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249) ~[na:1.7.0_51]
at nms.server.domain.AuditManager$ConfigAuditProcessor.run(AuditManager.java:465) ~[nms.jar:na]
Caused by: sun.org.mozilla.javascript.internal.JavaScriptException: Error: Cannot find module '../package.json' (<Unknown source>#1)
at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:1066) ~[na:1.7.0_51]
at sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:849) ~[na:1.7.0_51]
at sun.org.mozilla.javascript.internal.InterpretedFunction.call(InterpretedFunction.java:162) ~[na:1.7.0_51]
at sun.org.mozilla.javascript.internal.ContextFactory.doTopCall(ContextFactory.java:430) ~[na:1.7.0_51]
at com.sun.script.javascript.RhinoScriptEngine$1.superDoTopCall(RhinoScriptEngine.java:116) ~[na:1.7.0_51]
at com.sun.script.javascript.RhinoScriptEngine$1.doTopCall(RhinoScriptEngine.java:109) ~[na:1.7.0_51]
at sun.org.mozilla.javascript.internal.ScriptRuntime.doTopCall(ScriptRuntime.java:3160) ~[na:1.7.0_51]
at sun.org.mozilla.javascript.internal.InterpretedFunction.exec(InterpretedFunction.java:173) ~[na:1.7.0_51]
at sun.org.mozilla.javascript.internal.Context.evaluateReader(Context.java:1169) ~[na:1.7.0_51]
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:214) ~[na:1.7.0_51]
The jsondiffpatch.min.js file is located in the webclient/common/js directory, and the package.json file is located in the webclient/common directory.
The logger.debug line printed out the following for the current working directory:
CURRENT PATH=/usr/local/project/version/Software
So I tried copying the package.json file to the /usr/local/project/version directory, and I still got the same exception.
Why can't the ScriptEngine find the package.json file?

the jsondiffpatch.js file found in /public/build is a bundle (created with browserify) intended only for using it in a browser (the require function called there is defined at the top of the file, it doesn't read files from disc).
I'm not familiar with Java ScriptEngine, but it looks it's not allowing a redefine of the require function. if it supports CommonJS, you shouldn't use the bundled version, you should require ./src/main.js (the library main module, as pointed in package.json)
(Disclaimer: I'm jsondiffpatch author)

Attempt to try the full path of the module you want to include.

I used Java 8, Nashorn, nashorn-commonjs-modules, jsondiffpatch.js.
I deleted chalk external module and package.json from the file main.js because it's outside the scope of my Nashorn base folder.
It's work now :)
public String diff() throws ScriptException {
NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
FilesystemFolder rootFolder = FilesystemFolder.create(new File("C:\\Users\\Maxime\\Documents\\writecontrol\\default\\gateway\\src\\main\\resources\\static\\bower_components\\jsondiffpatch\\src"), "UTF-8");
Module module = Require.enable(engine, rootFolder);
try {
ScriptObjectMirror result = (ScriptObjectMirror) engine.eval("var jsondiffpatch = require('./main.js');" +
" var country = {\n" +
" name: \"Argentina\",\n" +
" capital: \"Buenos Aires\",\n" +
" independence: new Date(1816, 6, 9),\n" +
" unasur: true\n" +
" };" +
"var country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver);" +
" country2.name = \"Republica Argentina\";\n" +
" country2.population = 41324992;\n" +
" delete country2.capital;\n" +
" var delta = jsondiffpatch.diff(country, country2);" +
"print(delta.name);" +
"print('Nashorn Hello World!');" +
"data=JSON.stringify(delta);" +
"var result = {delta : data};" +
"result");
delta = (String) result.getMember("delta");
System.out.println(delta);
} catch (final ScriptException se) {
se.printStackTrace();
}
return delta;
}

Related

Dovx4J: Enabling page numbers in ToC results in TocException

I am using Docx4j in an internship project and when I try to generate a ToC with page numbers it does not work.
Executing the code with
if (template.isGenerateToc()) {
Toc.setTocHeadingText("Inhaltsverzeichnis");
TocGenerator tocGenerator = new TocGenerator(wordPackage);
tocGenerator.generateToc(2, " TOC \\o \"1-3\" \\h \\z \\u ", true);
}
Works perfectly fine, but results in no page numbers in the .docx (when exporting to PDF via the Gotenberg API (https://gotenberg.dev), the page numbers are existant and correct).
When I try to pass "false" for the third parameter, the application crashes with the following exception/stacktrace:
org.docx4j.toc.TocException: Exception exporting package
at org.docx4j.toc.TocGenerator.getPageNumbersMapViaFOP(TocGenerator.java:871)
at org.docx4j.toc.TocGenerator.getPageNumbersMap(TocGenerator.java:694)
at org.docx4j.toc.TocGenerator.populateToc(TocGenerator.java:441)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:306)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:234)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:194)
If usefull: This is my TocHeading:
private static String XML_TOCHeading_BasedOn_Nothing = "<w:style w:styleId=\"TOCHeading\" w:type=\"paragraph\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
+ "<w:name w:val=\"TOC Heading\"/>"
// + "<w:basedOn w:val=\"Heading1\"/>" // would be ok if provided already present, since
+ "<w:next w:val=\"Normal\"/>"
+ "<w:uiPriority w:val=\"39\"/>"
+ "<w:semiHidden/>"
+ "<w:unhideWhenUsed/>"
+ "<w:qFormat/>"
+ "<w:pPr>"
+ "<w:keepNext/>"
+ "<w:keepLines/>"
+ "<w:spacing w:after=\"150\" w:before=\"480\"/>"
+ "<w:outlineLvl w:val=\"9\"/>"
+ "</w:pPr>"
+ "<w:rPr>"
+ "<w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:cs=\"Arial\"/>"
+ "<w:b/>"
+ "<w:bCs/>"
+ "<w:sz w:val=\"36\"/>"
+ "<w:szCs w:val=\"36\"/>"
+ "</w:rPr>"
+ "</w:style>";
Any ideas on how to fix this exception and generate page numbers in my toc?
EDIT:
I updated the dependencies and now I am still getting the TocException but now with another cause:
Caused by: org.docx4j.openpackaging.exceptions.Docx4JException: Exception exporting package
at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:106)
at org.docx4j.Docx4J.toFO(Docx4J.java:734)
at org.docx4j.toc.TocGenerator.getPageNumbersMapViaFOP(TocGenerator.java:843)
... 97 more
Caused by: java.lang.NullPointerException
at org.docx4j.convert.out.common.preprocess.Containerization.borderChanged(Containerization.java:390)
at org.docx4j.convert.out.common.preprocess.Containerization.bordersChanged(Containerization.java:377)
at org.docx4j.convert.out.common.preprocess.Containerization.groupBodyContent(Containerization.java:204)
at org.docx4j.convert.out.common.preprocess.Containerization.groupAdjacentBorders(Containerization.java:129)
at org.docx4j.convert.out.common.preprocess.Containerization.process(Containerization.java:120)
at org.docx4j.convert.out.common.Preprocess.process(Preprocess.java:165)
at org.docx4j.convert.out.common.AbstractWmlExporter.preprocess(AbstractWmlExporter.java:51)
at org.docx4j.convert.out.common.AbstractWmlExporter.preprocess(AbstractWmlExporter.java:32)
at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:63)
Not sure which version of docx4j you are using, but generally, to update page numbers, you need FOP on your classpath.
We broke this in 8.3.3; it is fixed at https://github.com/plutext/docx4j/commit/50cfa5cabe08ab133f28c54b59f73d082d3e80a4#diff-29cfd63b63bfe585aa3468870ca54f1afb6e2246342c396155801b0d0aa9ae43L763
So you could try 8.3.2 with FOP on your classpath.
Alternatively, you could try the approach described at https://www.docx4java.org/blog/2020/03/documents4j-for-toc-update/
See further:
documents4j-local: https://github.com/plutext/docx4j/blob/master/docx4j-samples-documents4j-local/src/main/java/org/docx4j/samples/documents4j/local/TocOperations.java
documents4j-remote: https://github.com/plutext/docx4j/tree/master/docx4j-samples-documents4j-remote

ASE is terminating this process when trying to install the jar file (Msg 5702, Level 10, State 1)

I have an SAP ASE 16 server on a Windows OS.
I have enabled the java service:
sp_configure 'enable java'
Parameter Name Default Memory Used Config Value Run Value Unit Type
-------------- ----------- ----------- ------------ ------------ ------ ------
enable java 0 0 1 1 switch static
Rows affected (1) Time (0.094 s)
I have created a basic class to test the service (JDBCExamples.java):
import java.sql.*; // JDBC
public class JDBCExamples {
public static void main(String args[]){
if (args.length != 2) {
System.out.println("\n Usage: " + "name secondName \n");
return;
}
try {
String name = args[0];
String secondName = args[1].toLowerCase();
System.out.println("\n HOLA " + name + " " + secondName +" FUNCIONO!!!\n");
} catch (Exception e) {
System.out.println("\n Exception: ");
e.printStackTrace();
}
}
}
I have the class file JDBCExamples.class and I make a file JDBCExamples.jar.
When I try to install the jar file it shows the error message:
instjava -f JDBCExamples.jar -SDEFAULT -Uuser -Ppassword -Ddatabase -new
Server Message: - Msg 5702, Level 10, State 1:
ASE is terminating this process.
I don't see any in log database.
Any idea what the problem is?
Update:
I posted the same problem in https://answers.sap.com/questions/13241081/ase-is-terminating-this-process-when-trying-to-ins.html
In this post suspect the issue is caused by an ASE bug fixed in PL06:
2687973 - NTPCI__exit(1); Native Thread failed to unwind - SAP ASE http://service.sap.com/sap/support/notes/2687973
I have a trial version and I can not download a newer patch (PL06 at least but recommend PL09 as most recent)
Does anyone have this patch?

Stanford NER Error: Loading distsim lexicon Failed

In my project. I need to use NER annotation so I used NERDemo.java
It works fine when I create a new project and have only this code, but when I add it to my project I keep getting errors. I have edited the path in my code to the specific location of the classifiers.
I added the Jar files:
This is the code:
String serializedClassifier = "/Users/ha/stanford-ner-2014-10-26/classifiers/english.all.3class.distsim.crf.ser.gz";
String serializedClassifier2 = "/Users/ha/stanford-ner-2014-10-26/classifiers/english.muc.7class.distsim.crf.ser.gz";
if (args.length > 0) {
serializedClassifier = args[0];
}
NERClassifierCombiner classifier = new NERClassifierCombiner(false, false, serializedClassifier, serializedClassifier2);
String fileContents = IOUtils.slurpFile("/Users/ha/NetBeansProjects/StanfordPOSCode/src/stanfordposcode/input.txt");
List<List<CoreLabel>> out = classifier.classify(fileContents);
int i = 0;
for (List<CoreLabel> lcl : out) {
i++;
int j = 0;
for (CoreLabel cl : lcl) {
j++;
System.out.printf("%d:%d: %s%n", i, j,
cl.toShorterString("Text", "CharacterOffsetBegin", "CharacterOffsetEnd", "NamedEntityTag"));
}
}
But I got this error:
run:
Loading classifier from /Users/ha/stanford-ner-2014-10-26/classifiers/english.all.3class.distsim.crf.ser.gz ... Loading distsim lexicon from /u/nlp/data/pos_tags_are_useless/egw4-reut.512.clusters ... java.lang.RuntimeException: java.io.FileNotFoundException: /u/nlp/data/pos_tags_are_useless/egw4-reut.512.clusters (No such file or directory)
at edu.stanford.nlp.objectbank.ReaderIteratorFactory$ReaderIterator.setNextObject(ReaderIteratorFactory.java:225)
at edu.stanford.nlp.objectbank.ReaderIteratorFactory$ReaderIterator.<init>(ReaderIteratorFactory.java:161)
at edu.stanford.nlp.objectbank.ReaderIteratorFactory.iterator(ReaderIteratorFactory.java:98)
at edu.stanford.nlp.objectbank.ObjectBank$OBIterator.<init>(ObjectBank.java:404)
at edu.stanford.nlp.objectbank.ObjectBank.iterator(ObjectBank.java:242)
at edu.stanford.nlp.ie.NERFeatureFactory.initLexicon(NERFeatureFactory.java:471)
at edu.stanford.nlp.ie.NERFeatureFactory.init(NERFeatureFactory.java:379)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.reinit(AbstractSequenceClassifier.java:171)
at edu.stanford.nlp.ie.crf.CRFClassifier.loadClassifier(CRFClassifier.java:2630)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1620)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1736)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1679)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1662)
at edu.stanford.nlp.ie.crf.CRFClassifier.getClassifier(CRFClassifier.java:2851)
at edu.stanford.nlp.ie.ClassifierCombiner.loadClassifierFromPath(ClassifierCombiner.java:189)
at edu.stanford.nlp.ie.ClassifierCombiner.loadClassifiers(ClassifierCombiner.java:173)
at edu.stanford.nlp.ie.ClassifierCombiner.<init>(ClassifierCombiner.java:125)
at edu.stanford.nlp.ie.NERClassifierCombiner.<init>(NERClassifierCombiner.java:52)
at stanfordposcode.MultipleNERs.main(MultipleNERs.java:24)
Caused by: java.io.FileNotFoundException: /u/nlp/data/pos_tags_are_useless/egw4-reut.512.clusters (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at edu.stanford.nlp.io.EncodingFileReader.<init>(EncodingFileReader.java:78)
at edu.stanford.nlp.objectbank.ReaderIteratorFactory$ReaderIterator.setNextObject(ReaderIteratorFactory.java:192)
... 18 more
Loading classifier from /Users/ha/stanford-ner-2014-10-26/classifiers/english.all.3class.distsim.crf.ser.gz ... Exception in thread "main" java.io.FileNotFoundException
at edu.stanford.nlp.ie.ClassifierCombiner.loadClassifierFromPath(ClassifierCombiner.java:199)
at edu.stanford.nlp.ie.ClassifierCombiner.loadClassifiers(ClassifierCombiner.java:173)
at edu.stanford.nlp.ie.ClassifierCombiner.<init>(ClassifierCombiner.java:125)
at edu.stanford.nlp.ie.NERClassifierCombiner.<init>(NERClassifierCombiner.java:52)
at stanfordposcode.MultipleNERs.main(MultipleNERs.java:24)
Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to edu.stanford.nlp.classify.LinearClassifier
at edu.stanford.nlp.ie.ner.CMMClassifier.loadClassifier(CMMClassifier.java:1070)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1620)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1736)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1679)
at edu.stanford.nlp.ie.AbstractSequenceClassifier.loadClassifier(AbstractSequenceClassifier.java:1662)
at edu.stanford.nlp.ie.ner.CMMClassifier.getClassifier(CMMClassifier.java:1116)
at edu.stanford.nlp.ie.ClassifierCombiner.loadClassifierFromPath(ClassifierCombiner.java:195)
... 4 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
You are mixing and matching the code from version 3.4 and the models from version 3.5. I suggest upgrading everything to the latest version.

java.lang.UnsatisfiedLinkError:Can't find dependent libraries [duplicate]

This question already has answers here:
How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project
(18 answers)
Closed 8 years ago.
I am new to lp solve.
I am trying to run the following code and getting the following error:
package package1;
/**
* Created by ANJANEY on 6/13/2014.
*/
import lpsolve.*;
public class Demo {
public static void main(String[] args) {
try {
// Create a problem with 4 variables and 0 constraints
LpSolve solver = LpSolve.makeLp(0, 4);
// add constraints
solver.strAddConstraint("3 2 2 1", LpSolve.LE, 4);
solver.strAddConstraint("0 4 3 1", LpSolve.GE, 3);
// set objective function
solver.strSetObjFn("2 3 -2 3");
// solve the problem
solver.solve();
// print solution
System.out.println("Value of objective function: " + solver.getObjective());
double[] var = solver.getPtrVariables();
for (int i = 0; i < var.length; i++) {
System.out.println("Value of var[" + i + "] = " + var[i]);
}
// delete the problem and free memory
solver.deleteLp();
}
catch (LpSolveException e) {
e.printStackTrace();
}
}
}
Error:
Exception in thread "main" java.lang.UnsatisfiedLinkError:E:\HIVEMINDS\ThirdProject\lp_solve_5.5.2.0_dev_win64\lpsolve55j.dll: Can't find dependent libraries
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary1(ClassLoader.java:1957)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1882)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1872)
at java.lang.Runtime.loadLibrary0(Runtime.java:849)
at java.lang.System.loadLibrary(System.java:1087)
at lpsolve.LpSolve.<clinit>(LpSolve.java:275)
at package1.Demo.main(Demo.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Are you sure you load correct libraries in other classes with System.loadlibrary?
If yes, I think quick solution can be putting all libraries in a folder that exists in os's PATH (for instance system32, windows) This has worked for me everytime if there is no any other issue

List all the lotus notes database

I tried to create a lotus notes client using Java. Now, I have a problem to list all the user defined databases. What I tried to do is
// testing purpose
private void printAllDb() throws NotesException
{
DbDirectory dir = session.getDbDirectory(host);
String server = dir.getName();
if(server.equals(""))
{
server = "Local";
}
System.out.println("database direcory list on server (" + server + ")");
Database db = dir.getFirstDatabase(DbDirectory.DATABASE);
do
{
System.out.println("file name: " + db.getFileName().toUpperCase() + " - " + db.getTitle());
} while((db = dir.getNextDatabase()) != null);
}
However, the program will throw the exception:
Exception in thread "main" NotesException: Server access denied
at lotus.domino.NotesExceptionHelper.read(Unknown Source)
at lotus.domino.NotesExceptionHolder._read(Unknown Source)
at lotus.priv.CORBA.iiop.RepImpl.invoke(Unknown Source)
at lotus.priv.CORBA.portable.ObjectImpl._invoke(Unknown Source)
at lotus.domino.corba._IDbDirectoryStub.getFirstDatabase(Unknown Source)
at lotus.domino.cso.DbDirectory.getFirstDatabase(Unknown Source)
at nz.co.sylresearch.sylsearch.agents.lotusnotes.LotusNotesAPIHandler.printAllDb(LotusNotesAPIHandler.java:58)
at nz.co.sylresearch.sylsearch.agents.lotusnotes.LotusNotesAPIHandler.main(LotusNotesAPIHandler.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
The issue is pretty clear. You are getting an access denied error to the server. The tricky part now is figuring out why.
You should start with making sure the username and password used to create the session object is correct. Then make sure that user has access to the server and has access to run Java code on the server. You'll have to check the server document in the Directory for that.

Categories

Resources