I am trying to run this Graalvm sample code:
package org.homi.scripting.experimental;
import org.graalvm.polyglot.*;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import java.io.File;
import java.io.IOException;
public class ScriptEngine {
public static class Name {
#HostAccess.Export public String name = "hello";
#HostAccess.Export
public String getName() {
return name;
}
}
public static void main(String[] args) {
Name n = new Name();
Context context = Context.newBuilder("js")
.allowAllAccess(true)
.allowIO(true)
.allowPolyglotAccess(PolyglotAccess.ALL)
.build();
context.getPolyglotBindings().putMember("name", n);
context.eval("js", "var name = Polyglot.import('name');");
context.eval("js", "console.log(name.getName())");
}
}
I am getting this exception:
Exception in thread "main" TypeError: invokeMember (getName) on org.homi.scripting.experimental.Name#2313052e failed due to: Unknown identifier: getName
at <js> :program(Unnamed:1:12-25)
at org.graalvm.sdk/org.graalvm.polyglot.Context.eval(Context.java:379)
at ScriptEngine/org.homi.scripting.experimental.ScriptEngine.tester(ScriptEngine.java:43)
at ScriptEngine/org.homi.scripting.experimental.ScriptEngine.main(ScriptEngine.java:29)
I'm new to graalvm, what am I doing wrong? I was following this demo from the documentation (see the section on host interoperability):
https://www.graalvm.org/sdk/javadoc/
The code and the stack trace don't match, for example the code lacks the tester method
at ScriptEngine/org.homi.scripting.experimental.ScriptEngine.tester(ScriptEngine.java:43)
When you specify allowAllAccess(true) you allow all access, so the HostAccess stops being necesary.
The code in the question works for me and prints hello as expected.
Related
I have created simple Lambda function and upload this to AWS Lambda.
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class Hello implements RequestHandler<String, String> {
#Override
public String handleRequest(String input, Context context) {
String output = "Bonjour, " + input + "!";
return output;
}
}
}
I want to invoke this Lambda function from some other project using java class. I am using aws-java-sdk-lambda-1.10.22 to call the function. But I am not able to succeed in that.
Here is my InvokeLambda class which is a separate project.
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambdaClient;
import com.amazonaws.services.lambda.model.InvokeRequest;
public class InvokeLambda {
private static final Log logger = LogFactory.getLog(InvokeLambda.class);
private static final String awsAccessKeyId = "XXXXXX";
private static final String awsSecretAccessKey = "YYYY";
private static final String regionName = "us-west-2";
private static final String functionName = "Hello";
private static Region region;
private static AWSCredentials credentials;
private static AWSLambdaClient lambdaClient;
/**
* The entry point into the AWS lambda function.
*/
public static void main(String... args) {
credentials = new BasicAWSCredentials(awsAccessKeyId,
awsSecretAccessKey);
lambdaClient = (credentials == null) ? new AWSLambdaClient()
: new AWSLambdaClient(credentials);
//lambdaClient.configureRegion(Regions.US_WEST_2);
region = Region.getRegion(Regions.fromName(regionName));
lambdaClient.setRegion(region);
try {
InvokeRequest invokeRequest = new InvokeRequest();
invokeRequest.setFunctionName(functionName);
invokeRequest.setPayload("\" AWS Lambda\"");
System.out.println(byteBufferToString(
lambdaClient.invoke(invokeRequest).getPayload(),
Charset.forName("UTF-8")));
} catch (Exception e) {
logger.error(e.getMessage());
// System.out.println(e.getMessage());
}
}
public static String byteBufferToString(ByteBuffer buffer, Charset charset) {
byte[] bytes;
if (buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
return new String(bytes, charset);
}
}
How to call the lambda function using java?
Given the information in your comment, your client code to invoke the function is fine. The problem appears to be with the configuration of the function itself. Specifically, AWS Lambda is not able to find the handler you've specified (com.aws.HelloLambda::handleRequest) because that doesn't match the name and package of your handler class (Hello) and the name of your method in that class (handleRequest).
You can update the function handler name through the AWS Console. Choose your function, then the configuration tab and then the Handler property.
You probably want to change it from com.aws.HelloLambda::handleRequest to Hello::handleRequest.
Before testing the function from your Java client, you could test it directly through the console, this will help you ensure the function is configured correctly.
Another way to invoke lambda from java code is to use LambdaInvokerFactory and I found this approach cleaner.
You need to do the following:
Define interface representing your function and annotate method with #LambdaFunction
Create implementation of the above interface using LambdaInvokerFactory
Invoke lambda function using just created proxy object (interface implementation)
More detailed example can be found here.
This is my first java program, so please excuse me if its too naive.
I have a 3rd party jar. I want to instantiate a class in the jar and be able to use its methods. Some details about the class in the jar:
Class File: rediff.inecom.catalog.product.CSVAPI
Constructor: CSVAPI()
Method: UpdateCSVAPI(key, csvpath)
Return: String
I have written the following program:
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.IOException;
class MyLoaderClass{
public void myLoaderFunction(){
File file = new File("vendorcatalogapi.jar");
try {
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("rediff.inecom.catalog.product.CSVAPI");
Object cls_object = cls.newInstance();
System.out.println(cls_object);
String output = cls_object.UpdateCSVAPI(12345,"myfile.csv");
System.out.println(output);
System.out.println("try");
}
catch (Exception e) {
System.out.println("catch");
e.printStackTrace();
}
}
public static void main(String args[]){
new MyLoaderClass().myLoaderFunction();
}
}
I am trying to compile it using:
javac -cp vendorcatalogapi.jar temp.java
But I am getting the following error:
temp.java:17: error: cannot find symbol
String output = cls_object.UpdateCSVAPI(12345,"myfile.csv");
^
symbol: method UpdateCSVAPI(int,String)
location: variable cls_object of type Object
1 error
Looks like the object is not correctly initialized. Please can someone help me with the correct way of doing it
If this is your first java program, then loading the class dynamically is probably overkill. Just use it normally and let the default class loader load it:
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.IOException;
import rediff.inecom.catalog.product.CSVAPI;
class MyFirstClass{
public void myFunction() {
CSVAPI cvsapi = new CSVAPI();
System.out.println(cvsapi);
String output = cvsapi.UpdateCSVAPI(12345,"myfile.csv");
System.out.println(output);
System.out.println("Success!");
}
public static void main(String args[]){
new MyFirstClass().myFunction();
}
}
Compile (note that the source code file name must match the class name):
javac -cp vendorcatalogapi.jar MyFirstClass.java
Run:
java -cp .:vendorcatalogapi.jar MyFirstClass (on Unix based)
java -cp .;vendorcatalogapi.jar MyFirstClass (on Windows)
You have to let the compiler know that cls_object is an instance of CSVAPI. If you don't, you can only use the object methods (toString, equals, etc.).
To do this, you can do the following:
rediff.inecom.catalog.product.CSVAPI cls_object = (rediff.inecom.catalog.product.CSVAPI) cls.newInstance();
Please, note that you need to have CSVAPI in your classpath!
Object class doesnt know the methods of rediff.inecom.catalog.product.CSVAPI class.
Class cls = cl.loadClass("rediff.inecom.catalog.product.CSVAPI");
Object cls_object = cls.newInstance();
So, explicit casting is required
rediff.inecom.catalog.product.CSVAPI object =
(rediff.inecom.catalog.product.CSVAPI) cls.newInstance();
will do the job.
This is the code I have written but the new built-in does not seem to work. I get the error:
Exception in thread "main" com.hp.hpl.jena.reasoner.rulesys.impl.LPRuleSyntaxException: Syntax error in backward rule: matematica Unknown builtin operation mysum
Can anyone tell me where the error is? Here is my code:
package JenaRules;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.ReasonerVocabulary;
public class RulesOntology_MT {
public static void main(String[] args) throws OWLOntologyStorageException,
OWLOntologyCreationException, IOException {
BuiltinRegistry.theRegistry.register(new BaseBuiltin() {
#Override
public String getName() {
return "mysum";
}
#Override
public int getArgLength() {
return 2;
}
#Override
public boolean bodyCall(Node[] args, int length, RuleContext context) {
checkArgs(length, context);
BindingEnvironment env = context.getEnv();
Node n1 = getArg(0, args, context);
Node n2 = getArg(1, args, context);
if (n1.isLiteral() && n2.isLiteral()) {
Object v1 = n1.getLiteralValue();
Object v2 = n2.getLiteralValue();
Node sum = null;
if (v1 instanceof Number && v2 instanceof Number) {
Number nv1 = (Number)v1;
Number nv2 = (Number)v2;
int sumInt = nv1.intValue()+nv2.intValue();
sum = Util.makeIntNode(sumInt);
return env.bind(args[2], sum);
}
}
return false;
}
});
// NON SERVE
// final String exampleRuleString2 =
// "[mat1: equal(?s ?p )\n\t-> print(?s ?p ?o),\n\t (?s ?p ?o)\n]"+
// "";
final String exampleRuleString =
"[matematica:"+
"(?p http://www.semanticweb.org/prova_rules_M#totale_crediti ?x)"+
" -> " +
"(?p rdf:type http://www.semanticweb.org/prova_rules_M#:Persona)"+
"(?e rdf:type http://www.semanticweb.org/prova_rules_M#:Esame)"+
"(?p http://www.semanticweb.org/prova_rules_M#:haSostenutoEsameDi ?e)"+
"(?e http://www.semanticweb.org/prova_rules_M/persona#crediti_esame ?cr)"+
"mysum(?cr,2)"+
"]";
System.out.println(exampleRuleString);
/* I tend to use a fairly verbose syntax for parsing out my rules when I construct them
* from a string. You can read them from whatever other sources.
*/
final List<Rule> rules;
try( final BufferedReader src = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(exampleRuleString.getBytes()))) ) {
rules = Rule.parseRules(Rule.rulesParserFromReader(src));
}
/* Construct a reasoner and associate the rules with it */
// create an empty non-inferencing model
GenericRuleReasoner reasoner = (GenericRuleReasoner) GenericRuleReasonerFactory.theInstance().create(null);
reasoner.setRules(rules);
/* Create & Prepare the InfModel. If you don't call prepare, then
* rule firings and inference may be deferred until you query the
* model rather than happening at insertion. This can make you think
* that your Builtin is not working, when it is.
*/
InfModel infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
infModel.prepare();
infModel.createResource(RDFS.Class);
//write down the result in RDFXML form
infModel.write(System.out);
}
}
Using the code that you provided, and Apache Jena 2.11.1, I cannot replicate the exception you are getting. Do note that when you call BuiltinRegistry.theRegistry.register(...), you are telling the reasoner that the builtin exists.
Solution
The exception that you are getting is likely because, in your actual code, you are not calling BuiltinRegistry.theRegistry.register(...) prior to calling Rule.parseRules(Rule.rulesParserFromReader(src));, so as far as the rule parser is concerned, you are using a Builtin which doesn't exist. To fix it, merely call register before parsing your rules. The toy example provided does not have this problem.
Using the example provided
I also noted that the provided code example did not include anything that would actually stimulate the rule to fire, so, in lieu of infModel.createResource(RDFS.Class);, I added the following lines:
final Resource s = infModel.createResource();
final Property p = infModel.createProperty("http://www.semanticweb.org/prova_rules_M#totale_crediti");
final Resource o = infModel.createResource();
infModel.add(s,p,o);
This stimulated the rule to fire, and led to the following exception trace:
com.hp.hpl.jena.reasoner.rulesys.BuiltinException: Error in clause of rule (matematica) mysum: builtin mysum not usable in rule heads
at com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin.headAction(BaseBuiltin.java:86)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEConflictSet.execute(RETEConflictSet.java:184)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEConflictSet.add(RETEConflictSet.java:81)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEEngine.requestRuleFiring(RETEEngine.java:249)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETETerminal.fire(RETETerminal.java:80)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEClauseFilter.fire(RETEClauseFilter.java:227)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEEngine.inject(RETEEngine.java:469)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEEngine.runAll(RETEEngine.java:451)
at com.hp.hpl.jena.reasoner.rulesys.impl.RETEEngine.add(RETEEngine.java:174)
at com.hp.hpl.jena.reasoner.rulesys.FBRuleInfGraph.performAdd(FBRuleInfGraph.java:654)
at com.hp.hpl.jena.graph.impl.GraphBase.add(GraphBase.java:202)
at com.hp.hpl.jena.rdf.model.impl.ModelCom.add(ModelCom.java:1138)
at SO.test(SO.java:108)
As a note: my test class is SO.java and line 108 is where we call infModel.add(s,p,o).
The exception that I get is different than the exception you encountered, but it is worth explaining. The implementation that you provided implements Builtin#bodyCall(...), but not Builtin#headAction(...). We can see the exception is thrown from BaseBuiltin#headAction(...). This default behavior assumes that you didn't implement the method because your Builtin doesn't support it. In the toy problem, this is correct behavior because the example implementation cannot be used in rule heads.
I'm using QtWebkit to develop a webapplication framework. Now I've begun to ude the DOM and I tryed to use the QWebElement. But when I tried to compile it brought the following error:
symbol : class QWebElement
location: class test
QWebElement elem = new QWebElement();
Here is an example that doesn't work:
import com.trolltech.qt.gui.*;
import com.trolltech.qt.webkit.*;
import com.trolltech.qt.core.*;
import com.trolltech.qt.xml.*;
public class test {
public test() {
QWebElement elem = new QWebElement();
}
public static void main(String[] args) {
QApplication.initialize(args);
new test();
QApplication.exec();
}
}
Could anyone please tell me what I'm doing wrong?
Edit:
I forgot:
When I look in the javadoc, I cant find it! everything says that it doesn't exist. But I've seen other people using it.
Does it exist or not?
I create a form with Play framework. but I get a error: cannot find symbol
I reviewed the example codes in play directory, still can not figure it out. by the way, can I use Play to access PostgresSQL in heroku?
This is following code:
This is piece of code in /controllers/Application.java
final static Form<Geo> geoForm = form(Geo.class);
public static Result showDBpage(){
//get problem here :-<
Form<Geo> filledForm = geoForm.bindFormRequest();
Geo loc = filledForm.get();
return ok(database.render(loc));
}
This is conf/routes:
POST /database controllers.Application.showDBpage()
views/database.scala.html
#(loc: Geo)
#main("") {
<p>This is Database pages</p>
<p>#loc.longitute and #loc.latitute</p>
<a href=#routes.Application.index>Back to form</a>
}
models/Geo.java:
package models;
import java.util.*;
import javax.validation.*;
import play.data.validation.Constraints.*;
public class Geo
{
#Required
public String longitute;
#Required
public String latitute;
public Geo()
{
}
public Geo(String longitude,String latitute)
{
this.longitute = longitute;
this.latitute = latitute;
//this.length = length;
}
}
There is NO method bindFormRequest() but bindFromRequest() - you have a typo in your code.
Check the API http://www.playframework.org/documentation/api/2.0.2/java/play/data/Form.html