I have taken a written sample from this link to write my Python + Java integration code.
http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html
The code looks like below.
package org.jython.book.interfaces;
import org.jython.book.interfaces.JythonObjectFactory;
import org.python.core.Py;
import org.python.core.PyString;
import org.python.core.PySystemState;
public class Main {
public static void main(String args[]) {
String projDir = System.getProperty("user.dir");
String rootPath = projDir + "/src/org/jython/book/interfaces/";
String modulesDir = projDir + "/src/org/jython/book/interfaces/";
System.out.println("Project dir: " + projDir);
PySystemState sysSt = Py.getSystemState();
JythonObjectFactory factory = new JythonObjectFactory(sysSt, BuildingType.class, "Building", "Building");
BuildingType building = (BuildingType) factory.createObject();
building.setBuildingName("BUIDING-A");
building.setBuildingAddress("100 MAIN ST.");
building.setBuildingId(1);
System.out.println(building.getBuildingId() + " " +
building.getBuildingName() + " " +
building.getBuildingAddress());
}
}
When I run this code, it throws an error that it did not find the python module. I have kept the .py and .pyc files under the path provided as 'modulesDir'.
The literature says that "the requested module must be contained somewhere on the sys.path"; however, I did not understand how this can be set from this Java program. Can someone please provide some help?
Project dir: /Users/eclipsews/PythonJava
Exception in thread "main" ImportError: No module named Building
Hi found the answer to this issue!
Added the PySystemState.initialize method where I explicitly provide the "python.path" property, which is initialized to my project's path, where python modules are available.
private static Properties setDefaultPythonPath(Properties props) {
String pythonPathProp = props.getProperty("python.path");
String new_value;
if (pythonPathProp == null) {
new_value = System.getProperty("user.dir") + "/src/org/jython/book/interfaces/";
}
props.setProperty("python.path", new_value);
return props;
}
Properties props = setDefaultPythonPath(System.getProperties());
PySystemState.initialize( System.getProperties(), props, null );
This produces the correct output as follows:
module=<module 'Building' from '/Users/eclipsews/PythonJava/src/org/jython/book/interfaces/Building$py.class'>,class=<class 'Building.Buildin
g'>
1 BUIDING-A 100 MAIN ST.
Related
I am new to geb, spock and groovy. The script I am working on is I have a groovy class containing my json. In my groovy class I count how many objects are there in the json and for each object I read key values and then I have another unit testSpec in spock and Geb where I have create my login test script to login to the application which is very simple.
The scenario I am trying to achieve is I want to generate data table in spock test based on data present in json file.
Here what I have achieved till now
My InputDataJson.groovy file
package resources
import geb.spock.GebSpec
import groovy.json.JsonSlurper
import spock.lang.Shared
class InputDataJson extends GebSpec{
#Shared
def inputJSON,
idValue, passwordValue, jsonSize
#Shared
def credsList = []
def setup() {
inputJSON = '''{
"validLogin":{
"username" : "abc",
"password" : "correcttest"
},
"invalidLogin":{
"username" : "xyz",
"password" : "badtest"
}
}'''
def JsonSlurper slurper = new JsonSlurper()
def TreeMap parsedJson = slurper.parseText(inputJSON)
jsonSize = parsedJson.size()
Set keySet = parsedJson.keySet()
int keySetCount = keySet.size()
for(String key : keySet){
credsList.add(new Creds(username: parsedJson[key].username,password:
parsedJson[key].password))
}
}
}
and here is my sample spock geb test
package com.test.demo
import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import pages.LoginPage
import resources.InputDataJson
/**
* See the API for {#link grails.test.mixin.support.GrailsUnitTestMixin} for usage instructions
*/
#TestMixin(GrailsUnitTestMixin)
class SampleTest1Spec extends InputDataJson {
def credentialsList = []
def setup() {
credentialsList = credsList
}
def cleanup() {
}
void "test something"() {
}
def "This LoginSpec test"() {
given:
to LoginPage
when:'I am entering username and password'
setUsername(username)
setPassword(password)
login()
then: "I am being redirected to the homepage"
println("Hello")
where:
[username,password]<< getCreds()
//credsList[0]['username'] | credsList[0]['password']
}
def getCreds(){
println(" CREDS inside " + credsList)
println(" credentialsList : " + credentialsList)
}
}
The problem is when I run this test in debug mode (I understand in spock test first where clause is executed first) my credsList and credentialsList both are coming null and when execution mode reaches to "when" section it fetches the correct user name and password. I am not sure where I am making mistake.
Any help is well appreciated.
Leonard Brünings said:
try replacing setup with setupSpec
Exactly, this is the most important thing. You want something that is initialised before any feature method or iteration thereof starts. So if you want to initialise static or shared fields, this is the way to go.
Additionally, credsList contains Creds objects, not just pairs of user names and passwords. Therefore, if you want those in separate data variables, you need to dereference them in the Creds objects. Here is a simplified version of your Spock tests without any Grails or Geb, because your question is really just a plain Spock question:
package de.scrum_master.stackoverflow.q71122575
class Creds {
String username
String password
#Override
String toString() {
"Creds{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'
}
}
package de.scrum_master.stackoverflow.q71122575
import groovy.json.JsonSlurper
import spock.lang.Shared
import spock.lang.Specification
class InputDataJson extends Specification {
#Shared
List<Creds> credsList = []
def setupSpec() {
def inputJSON = '''{
"validLogin" : {
"username" : "abc",
"password" : "correcttest"
},
"invalidLogin" : {
"username" : "xyz",
"password" : "badtest"
}
}'''
credsList = new JsonSlurper().parseText(inputJSON)
.values()
.collect { login -> new Creds(username: login.username, password: login.password) }
}
}
package de.scrum_master.stackoverflow.q71122575
import spock.lang.Unroll
class CredsTest extends InputDataJson {
#Unroll("verify credentials for user #username")
def "verify parsed credentials"() {
given:
println "$username, $password"
expect:
username.length() >= 3
password.length() >= 6
where:
cred << credsList
username = cred.username
password = cred.password
}
}
The result in IntelliJ IDEA looks like this:
Try it in the Groovy web console
I have a newbie problem with taking the Cplex library in Eclipse,
Error: Could not find or load main class Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
Caused by: java.lang.ClassNotFoundException: Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
I added cplex.jar from external libraries and also added the native path by editing it,
CPLEX library path error in eclipse
under VMArguments I added,
-Djava.library.path=C:\Program Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
where cplex12100.dll stands. I managed to work with it before but I couldn't find why it is not working right now.
Everything is 64bit.
Thanks in advance!
Your error message references the following path:
Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64
Notice that it does not start with "C:Program Files". My guess is that you need to put quotes around the path you are providing, like so:
-Djava.library.path="C:\Program Files\IBM\ILOG\CPLEX_Studio1210\cplex\bin\x64_win64"
This should allow Java to handle your path which includes a space character.
thanks for the answer,
Unfortunately, I forgot to add that I already tried that, but it gives another error when I try like that.
Error: Unable to initialize main class model(my package name).model(my class name)
Caused by: java.lang.NoClassDefFoundError: ilog/concert/IloException
Here is part of my code, I cut half of it(after ...) since I guess it is unrelated to the question.
package model;
import ilog.concert.*;
import ilog.cplex.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.*;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
public class model {
public static void main(String[] args) throws Exception {
long startTime = Instant.now().toEpochMilli();
int a = 45; //matrisin boyutu
int b = 45; //matrisin 2. boyutu
int maxdistance = 90; //mesela 90 dan küçük deðerler
int depot = 0;
double alfa = 0.9;
double beta = 0.1;
float[][] distance = new float[a][b]; // bunu scanner dan çektik
int m = 3;
int C = 1200;
System.out.println();
System.out.println("m : " + m + " C : " + C );
System.out.println();
ArrayList<ArrayList> Nlist = new ArrayList<ArrayList>();
Scanner reader = null;
File burdurData = new File("burdur45.txt");
...
try {
long timeElapsed = endTime - startTime;
System.out.println("Execution time in milliseconds: " + timeElapsed);
System.out.println("Execution time in seconds: " + timeElapsed/1000);
} // try'ýn parantezi
catch (IloException exc) {
System.out.println(exc);
System.out.println("sýkýntý");
}
}
}
surely you should edit your question. In fact, for getting error:
java.lang.NoClassDefFoundError: ilog/concert/IloException
I had this error before and I solved it just by importing cplex.jar in ClassPath section of my project Java Build Path not in ModulePath. Also set Native Library Location path to cplex's dlls folder too. Furthermore you can check your details in java configuration->show command line too.
I am creating a Twitter Sentiment Analysis tool in Java. I am using the Twitter4J API to search tweets via the hashtag feature in twitter and then provide sentiment analysis on these tweets. Through research, I have found that the best solution to doing this will be using a POS and TreeTagger for Java.
At the moment, I am using the examples provided to see how the code works, although I am encountering some problems.
This is the code
import org.annolab.tt4j.*;
import static java.util.Arrays.asList;
public class Example {
public static void main(String[] args) throws Exception {
// Point TT4J to the TreeTagger installation directory. The executable is expected
// in the "bin" subdirectory - in this example at "/opt/treetagger/bin/tree-tagger"
System.setProperty("treetagger.home", "/opt/treetagger");
TreeTaggerWrapper tt = new TreeTaggerWrapper<String>();
try {
tt.setModel("/opt/treetagger/models/english.par:iso8859-1");
tt.setHandler(new TokenHandler<String>() {
public void token(String token, String pos, String lemma) {
System.out.println(token + "\t" + pos + "\t" + lemma);
}
});
tt.process(asList(new String[] { "This", "is", "a", "test", "." }));
}
finally {
tt.destroy();
}
}
}
At the moment, when this is run, I receive an error which says
TreeTaggerWrapper cannot be resolved to a type
TokenHandler cannot be resolved to a type
I will be grateful for any help given
Thank you
I am trying to make some SPARQL queries using vc-db-1.rdf and q1.rq from ARQ examples. Here is my java code:
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.query.* ;
import com.hp.hpl.jena.query.ARQ;
import com.hp.hpl.jena.iri.*;
import java.io.*;
public class querier extends Object
{
static final String inputFileName = "vc-db-1.rdf";
public static void main (String args[])
{
// Create an empty in-memory model
Model model = ModelFactory.createDefaultModel();
// use the FileManager to open the bloggers RDF graph from the filesystem
InputStream in = FileManager.get().open(inputFileName);
if (in == null)
{
throw new IllegalArgumentException( "File: " + inputFileName + " not found");
}
// read the RDF/XML file
model.read( in, "");
// Create a new query
String queryString = "PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> SELECT ?y ?givenName WHERE { ?y vcard:Family \"Smith\" . ?y vcard:Given ?givenName . }";
QueryFactory.create(queryString);
}
}
Compilation passes just fine.
The problem is that the query is not even executed, but I am getting an error during creating it at line
QueryFactory.create(queryString);
with the following explanation:
C:\Wallet\projects\java\ARQ_queries>java querier
Exception in thread "main" java.lang.NoSuchMethodError: com.hp.hpl.jena.iri.IRI.
resolve(Ljava/lang/String;)Lcom/hp/hpl/jena/iri/IRI;
at com.hp.hpl.jena.n3.IRIResolver.resolveGlobal(IRIResolver.java:191)
at com.hp.hpl.jena.sparql.mgt.SystemInfo.createIRI(SystemInfo.java:31)
at com.hp.hpl.jena.sparql.mgt.SystemInfo.<init>(SystemInfo.java:23)
at com.hp.hpl.jena.query.ARQ.init(ARQ.java:373)
at com.hp.hpl.jena.query.ARQ.<clinit>(ARQ.java:385)
at com.hp.hpl.jena.query.Query.<clinit>(Query.java:53)
at com.hp.hpl.jena.query.QueryFactory.create(QueryFactory.java:68)
at com.hp.hpl.jena.query.QueryFactory.create(QueryFactory.java:40)
at com.hp.hpl.jena.query.QueryFactory.create(QueryFactory.java:28)
at querier.main(querier.java:24)
How can i solve this? Thank you.
It looks like you're missing the IRI library on the classpath (the IRI library is separate from the main Jena JAR). Jena has runtime dependencies on several other libraries which are included in the lib directory of the Jena distribution. All of these need to be on your classpath at runtime (but not necessarily at compile time).
I'm trying to invoke a Ruby method from Java using the example code from:
https://github.com/tc/call-jruby-from-java-example
Here is what the java code looks with the embedded Ruby script:
#Service
public class ProcessorImpl extends RubyObject implements IProcessor {
private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
private static final RubyClass __metaclass__;
static {
String source = new StringBuilder(
"require 'java'\n" +
"require 'resque'\n" +
"\n" +
"class SaveData\n" +
" #queue = :general\n" +
"end\n" +
" \n" +
"class JRubyResqueImpl\n" +
" include Java::IProcessor\n" +
" \n" +
" java_signature 'void enqueue( Object )'\n" +
" def enqueue( data )\n" +
" Resque.enqueue( SaveData, data )\n" +
" end\n" +
"end\n" +
"").toString();
__ruby__.executeScript(source, "JRubyResqueImpl.rb");
RubyClass metaclass = __ruby__.getClass("JRubyResqueImpl");
metaclass.setRubyStaticAllocator(ActProcessorImpl.class);
__metaclass__ = metaclass;
}
public ActProcessorImpl(Ruby runtime, RubyClass metaClass)
{
super(runtime, metaClass);
}
public static IRubyObject __allocate__(Ruby ruby, RubyClass metaClass)
{
return new ActProcessorImpl(ruby, metaClass);
}
public ActProcessorImpl()
{
this(__ruby__, __metaclass__);
}
#Override
public void enqueue(Object obj)
{
ObjectMapper mapper = new ObjectMapper();
OutputStream os = new ByteArrayOutputStream();
try {
mapper.writeValue(os, obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
String json = os.toString();
IRubyObject rbJson = JavaUtil.convertJavaToRuby(__ruby__, json);
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), this, "enqueue",rbJson);
}
}
When the Spring Framework IoC module is doing the autowiring it tries to instantiate this class which fails with the following error message:
org.jruby.exceptions.RaiseException: (LoadError) no such file to load -- resque
I don't see any errors when I take the embedded Ruby script and run it via the CLI using the command:
jruby -S JRubyResqueImpl.rb
Where the content of JRubyResqueImpl.rb is:
require 'java'
require 'resque'
class SaveData
#queue = :general
end
class JRubyResqueImpl
include Java::IProcessor
java_signature 'void enqueue( Object )'
def enqueue( data )
Resque.enqueue( SaveData, data )
end
end
I've configured the environment variables GEM_HOME, GEM_PATH and set JRUBY_OPTS=--1.9.
Using Oracle Java 1.6.0_25, JRuby 1.6.4 and Resque 1.19.0 running under Ubuntu 11.10.
Thanks in advance.
I was able to make some progress by explicitly loading the dependencies in the embedded ruby script like so:
//java code
String source = new StringBuilder(
"require 'java'\n" +
"load '/usr/local/jruby/jruby-1.6.4/lib/ruby/1.9/singleton.rb'\n" +
"load '/usr/local/jruby/jruby-1.6.4/lib/ruby/gems/gems/monitor-0.1.3/lib/monitor/controller.rb'\n" +
"load '/usr/local/jruby/jruby-1.6.4/lib/ruby/gems/gems/monitor-0.1.3/lib/monitor.rb'\n" +
"load'/usr/local/jruby/jruby-1.6.4/lib/ruby/gems/redis-2.2.2/lib/redis.rb'\n" +
"load '/usr/local/jruby/jruby-1.6.4/lib/ruby/gems/redis-namespace-1.0.3/lib/redis-namespace.rb'\n" +
"load '/usr/local/jruby/jruby-1.6.4/lib/ruby/gems/resque-1.19.0/lib/resque.rb'\n" +
"\n" +
etc...
But now I see the following error from Spring IoC:
org.jruby.exceptions.RaiseException: (LoadError) no such file to load -- singleton
Still stuck...