calling JS function from orientdb through java API - javascript

I'm trying to call a custom JS function stored in OrientDB, from Java, through the OrientDB Java API.
I can use the function inside studio, and it works as expected.
This is the code used to connect to the db and get the function:
OrientGraphFactory factory = new OrientGraphFactory(SERVER_URL, "user", "pass");
OrientGraph txGraph = factory.getTx();
OFunction functionObject = txGraph.getRawGraph().getMetadata()
.getFunctionLibrary().getFunction("functionName");
The problem is that the functionObject returned is null, and inspecting the getFunctionLibrary() result, I can see the list of functions is empty.
Any idea what I'm doing wrong?
Using the official Documentation example, gives the same null result.
LE: For anyone stumbling on this, the full working code is:
OrientGraphFactory factory = new OrientGraphFactory(SERVER_URL, "user", "pass");
OrientGraph txGraph = factory.getTx();
Double response = (Double) txGraph.command(new OCommandFunction("functionName")).execute(functionParameter);
where response is the result the function gives and functionParameteris a parameter I'm passing to the function.

This will work for java functions only (and example in doc is correct because it retrieves java function).
In order to execute js/sql/whatever function use OCommandFunction. Something like this:
txGraph.command(new OCommandFunction("functionName")).execute()
Possibly it could work directly too (if you don't need to convert result to graph objects)
new OCommandFunction("functionName").execute()
But in this case db instance must be attached to thread (db connection object created before function call)

Related

How to initialize z object to use z.JSON.parse function in a code Zap?

I'm developing a Zapier zap. The source is Google calendar. I collect the event description. It is a json string. I want to turn it into an object to process it in a Zap code (in JavaScript). The doc recommends to use the z.JSON.parse() function. I do it but at run time the error z is not initialized is sent. How to JSON parse a string to make an object ?
I tried to add z = new Z(), but it didn't work.
var eventDescriptorString = {
codeEvt: 'ID-LGC-02/21/2019-testoon_mail',
appCible: 'SIB',
action: 'testoon_mail',
parametre: 'ID-LGC-02/21/2019-testoon_mail-presents'
}
var eventDescriptorObject = z.JSON.parse(inputData.eventDescriptorString);
console.log('action', eventDescriptorObject.action);
output = [{
'action': eventDescriptorObject.action
}];
I expect action to equal 'testoon_mail'
David here, from the Zapier Platform team.
The docs you found are probably for the app scripting environment. While similar, it's got access to a separate set of functions (and the z object itself). Code steps (which is what you're using here) are "plain" javascript environments.
If you change z.JSON.parse -> JSON.parse it should work as expected.

API Connect - 500 error when including basic Javascript

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.
I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:
[{"itemId":1,"charge":9,"itemSize":2,"id":2}]
I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.
You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?
var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object
json.platform = 'Powered by IBM API Connect'; //add new property
apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:
apim.readInputAsJSON(function (error, json) {
if (error)
{
// handle error
apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
if(json){
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
}
}
});
Reference:
IBM Reference
You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.

Variable used to store data from Excel file broken? JavaScript

I am currently developing a Keyword driven framework using JavaScript / TestComplete and have an Excel file which contains a step number, Description, Keyword, Locator and Data.
I am currently reading the data from the Excel file (.xlsx) and storing the data (in this case the locator) in a variable..
I am storing the String Browsers.Item(btlExplorer,"",Browsers.pX64 in a variable called locator. When I then attempt this: locator.Run(https://www.google.ie/?gws_rd=ssl#spf=1); I receive this error: JavaScript runtime error. TypeError. getLocator(...).Run is not a function.
This is my getLocator function:
function getLocator(x){
var driver;
var value;
driver = DDT.ExcelDriver("C:\\Users\\Username\\Desktop\\Automation Framework.xlsx", "Sheet1", false);
while (! driver.EOF() && driver.Value(0) != x){
DDT.CurrentDriver.Next();
}
value = driver.Value(3);
Log.Message(value);
DDT.CloseDriver(driver.Name);
return value;
}
And here is the function I am running:
function openGoogle()
{
//Launches the specified browser and opens the specified URL in it.
getLocator(1).Run("https://www.google.ie/?gws_rd=ssl#spf=1");
}
I am new to JavaScript, if you could give me any tips / advice on what is going wrong it would be greatly appreciated.
Since the value returned by the getLocator function is a string, you can work with it as a string and it does not have the Run method.
To get the actual object with the Run method, you need to evaluate the string in this way:
function openGoogle()
{
//Launches the specified browser and opens the specified URL in it.
let brwsr = eval(getLocator(1));
brwsr.Run("https://www.google.ie/?gws_rd=ssl#spf=1");
}

Couchbase Java API and javascript view not returning value for a specific Key

I am using couchbase API in java
View view = client.getView("dev_1", "view1");
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(this.Key);
ViewResponse res=client.query(view, query);
for(ViewRow row: res)
{
// Print out some infos about the document
a=a+" "+row.getKey()+" : "+row.getValue()+"<br/>";
}
return a;
and the java script view in couchbase
function (doc,meta) {
emit(meta.id,doc);
}
So, when I remove the statement query.setkey(this.Key) it works returns me all the tables, what am I missing here .. How can I change the function to refect only the table name mentioned in the key
Change the map function like this:
function (doc,meta) {
emit(doc.table,null);
}
it is good practice not to emit the entire document like:
emit(doc.table, doc)
NB: This is surprisingly important:
i have tried using setKey("key") so many times from Java projects and setting the key using CouchBase Console 3.0.1's Filter Result dialog, but nothing get returned.
One day, i used setInclusiveEnd and it worked. i checked the setInclusiveEnd checkbox in CouchBase Console 3.0.1's Filter Result dialog and i got json output.
query.setKey("whatEverKey");
query.setInclusiveEnd(true);
i hope this will be helpful to others having the same issue. if anyone finds another way out, please feel free to add a comment about it.
i don't know why their documentation does not specify this.
EXTRA
If your json is derived from an entity class in a Java Project, make sure to include an if statement to test the json field for the entity class name to enclose you emit statement. This will avoid the key being emitted as null:
if(doc._class == "path.to.Entity") {
emit(doc.table, null);
}

Passing objects from NodeJS to client and then into KnockoutJS viewmodel

So thanks to SO I can pass an object from node to the client, but then getting it into a knockout view model is a bit awkward. These are the steps I have so far (I've included links to the relevant lines as they appear in my github project. Thought the context might help.):
Apply JSON.stringify and pass to the jade file
recipeJSON: JSON.stringify(recipe);
Wrap this in a function in a header script that just parses the JSON and returns the result
script
function getRecipeObject() {
var r = '!{recipeJSON}';
return JSON.parse(r);
}
Call this function and pass the result to a view model constructor
self.recipe = ko.observable(new Recipe(getRecipeObject()));
This works but is there a better way?
Question clarification (Edit): I feel step 2 shouldn't be necessary. Is there a way to directly pass the JSON from node to the Recipe() constructor, without the getRecipeObject() acting as an intermediate step? I tried passing recipeJSON in directly like so
self.recipe = ko.observable(JSON.parse('!{recipeJSON}'));
That doesn't work I think because its not a jade template and has no access to the variable.
According to the answer to this question rendering data into scripts is bad practice and I should instead make an XHR call on page load instead.
Edit
I just saw you linked a github repo! So you're already familiar with most of this...you even have an endpoint set up at /recipe/:id/view, so now I'm really confused...what isn't working out for you? Just the last step of deserialization using ko.utils.*?
Sorry about all the exposition -- I thought this was way more rudimentary than it actually was; I hope no offense taken there!
You really don't want to return a script to execute -- instead, treat this as a DTO: an object that just stores data (no behaviors). An example would be:
{
recipeID: 12,
reviewIDs: [42, 12, 55, 31],
rating: 4.2
recipeName: "A super tasty pie!"
}
This object (representation) is a projection -- a simplified version of the full data stored in the database.
The next step is to create an endpoint to access that data on the server. Let's assume you're using Express:
var app = express();
app.get('/recipes/:recipeID', function(req, res) {
var recipeID = req.params.recipeID;
// It would be cool if this existed, huh?
getRecipeAsync(recipeID, function(recipe) {
res.status(200).json(recipe);
});
});
If you send a GET request to your (hypothetical) application (let's say it's https://localhost:8080/recipes/12), you'll get json representing the (admittedly imaginary) recipe with ID 12.
You can accomplish getting the JSON with jQuery (or any other library that makes XHR nice and pretty)
var recipeID = 12;
$.ajax({
url: "/recipes/" + recipeID,
type: "GET"
}).then(function(recipe) {
console.log("Hey! I got the recipe: %O", recipe);
// Note: you might need to use ko.utils.fromJS(recipe) if the returned
// data is JSON that ISN'T deserialized into an object
var recipeObservable = ko.utils.fromJS(recipe);
});
That's about everything you need to know. Obviously, the devil's in the details, but that's basic idea; let me know if that helps!

Categories

Resources