Search code examples
javajavascriptorientdb

OrientDB - OrientDB function not executing using Java


I have a database with the following Javascript function. But when I try to execute the same function using Java, it doesn't work. enter image description here

And I'm trying to connect using this Java code:

ODatabaseDocumentTx db = new ODatabaseDocumentTx("remote:localhost/localDBDocumentAPI").open("admin", "admin");
OFunction func = db.getMetadata().getFunctionLibrary().getFunction("CreateLinks");
func.execute();

When I ran the Java code, it ran without any error though. But no results.


Solution

  • String URL = "remote:localhost/localDBDocumentAPI";
    String functionName = "funfun";
    try (ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL)) {
        db.open("admin", "admin");
        OFunction f = new OFunction();
        f.setName(functionName);
        f.setLanguage("javascript");
        f.setParameters(new ArrayList());
        f.setCode("print(\"hellooo\\n\");");
        f.save();
    }
    
    try (ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL)) {
        db.open("admin", "admin");
        OFunction f = db.getMetadata().getFunctionLibrary().getFunction(functionName);
        f.execute();
    }
    
    try (ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL)) {
        db.open("admin", "admin");
        OFunction f = db.getMetadata().getFunctionLibrary().getFunction(functionName);
        db.command(new OCommandScript("javascript", f.getCode())).execute();
    }
    

    You can see that the first one is executed on client side, and the second on server side (which I believe it's your intent). Although for this to work you have to change your $ODB_HOME/orientdb-server-config.xml to allow javascript to be run on server side.

    Mine looks like this:

        <handler class="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter">
            <parameters>
                <parameter value="true" name="enabled"/>
                <parameter value="SQL" name="allowedLanguages"/>
                <parameter value="javascript" name="allowedLanguages"/>
            </parameters>
        </handler>
    

    See OrientDB note about this.