I am trying to call a function from a java class in my Ruby on Rails project using RJB (Ruby Java Bridge).
The Java class is
public class HelloWorld {
int fifty(){
return 50 ;
}
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
System.out.println("Hello, World");
}
}
and in the controller I have
require "rjb"
def home
myclass = Rjb::load(classpath ='\\home\\mennatallah\\TopicalClusteringofTweets\\lib\\java_libs\\helloworld.class', jvmargs=[])
myclass_instance = myclass.new
#output = myclass_instance.fifty
end
It gives " undefined method `new' for nil:NilClass "
How can I do this ?
you can try the following. it might help:
Rjb::add_jar( Dir.glob("#{Rails.root}/lib/java_libs/*.jar").join(':'))
Rjb::load(Dir.glob("#{Rails.root}/lib/java_libs/*.jar").join(':'))
test = Rjb.import('HelloWorld')
instance_class = test.new
Related
I want to call my Python class in Java, but I get the error message:
Manifest
com.atlassian.tutorial:myConfluenceMacro:atlassian-plugin:1.0.0-SNAPSHOT
: Classes found in the wrong directory
I installed Jython on my pc via jar. And added it in my pom (because I am using a Maven Project). What am I doing wrong? How can I call a python method inside my java class?
I am using python3.
POM
<!-- https://mvnrepository.com/artifact/org.python/jython-standalone -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.1</version>
</dependency>
JAVA CLASS
package com.atlassian.tutorial.javapy;
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class InterpreterExample
{
PythonInterpreter interpreter = null;
public InterpreterExample()
{
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main( String gargs[] )
{
InterpreterExample ie = new InterpreterExample();
ie.execfile("hello.py");
PyInstance hello = ie.createClass("Hello", "None");
hello.invoke("run");
}
}
Python Class
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print ('Hello world!')
Thank you!
You have wrong indentation in your Python class. Correct code is:
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print ('Hello world!')
so that __init__() and run() are methods of your Hello class, not global functions. Otherwise your code works nicely.
And please remember that the latest version of Jython is 2.7.1 - it is not Python3 compatible.
So it might seem like a trivial question, but I cannot find any information out there that answers my question. Nonetheless, it is a very general coding question.
Suppose you have a java program that reads a file and creates a data structure based on the information provided by the file. So you do:
javac javaprogram.java
java javaprogram
Easy enough, but what I want to do here is to provide the program with a file specified in the command line, like this:
javac javaprogram.java
java javaprogram -file
What code do I have to write to conclude this very concern?
Thanks.
One of the best command-line utility libraries for Java out there is JCommander.
A trivial implementation based on your thread description would be:
public class javaprogram {
#Parameter(names={"-file"})
String filePath;
public static void main(String[] args) {
// instantiate your main class
javaprogram program = new javaprogram();
// intialize JCommander and parse input arguments
JCommander.newBuilder().addObject(program).build().parse(args);
// use your file path which is now accessible through the 'filePath' field
}
}
You should make sure that the library jar is available under your classpath when compiling the javaprogram.java class file.
Otherwise, in case you don't need an utility around you program argument, you may keep the program entry simple enough reading the file path as a raw program argument:
public class javaprogram {
private static final String FILE_SWITCH = "-file";
public static void main(String[] args) {
if ((args.length == 2) && (FILE_SWITCH.equals(args[0]))) {
final String filePath = args[1];
// use your file path which is now accessible through the 'filePath' local variable
}
}
}
The easiest way to do it is using -D, so if you have some file, you could call
java -Dmy.file=file.txt javaprogram
And inside you program you could read it with System.getProperty("my.file").
public class Main {
public static void main(String[] args) {
String filename = System.getProperty("my.file");
if (filename == null) {
System.exit(-1); // Or wharever you want
}
// Read and process your file
}
}
Or you could use third a party tool like picocli
import java.io.File;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
#Command(name = "Sample", header = "%n#|green Sample demo|#")
public class Sample implements Runnable {
#Option(names = {"-f", "--file"}, required = true, description = "Filename")
private File file;
#Override
public void run() {
System.out.printf("Loading %s%n", file.getAbsolutePath());
}
public static void main(String[] args) {
CommandLine.run(new Sample(), System.err, args);
}
}
You can pass file path as argument in two ways:
1)
public class Main {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("File path plz");
return;
}
System.out.println("File path: " + args[0]);
}
}
2) Use JCommander
Let's go step by step. First you need to pass the file path to your program.
Lets say you execute your program like this:
java javaprogram /foo/bar/file.txt
Strings that come after "javaprogram" will be passed as arguments to your program. This is the reason behind the syntax of the main method:
public static void main(String[] args) {
//args is the array that would store all the values passed when executing your program
String filePath = args[0]; //filePath will contain /foo/bar/file.txt
}
Now that you were able to get a the file path and name from the command-line, you need to open and read your file.
Take a look at File class and FileInputStream class.
https://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream/
That should get you started.
Good luck!
I want to call a function from a python module from Java using "PythonInterpreter" and here's my Java code
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");
PyObject someFunc = interpreter.get("helloworld.getName");
PyObject result = someFunc.__call__();
String realResult = (String) result.__tojava__(String.class);
System.out.println(realResult);
and the Python code (helloworld.py) is below:
from faker import Factory
fake = Factory.create()
def getName():
name = fake.name()
return name
The problem I'm facing is while I'm calling interpreter.get when it returns a null PyObject.
Any idea what's going wrong? The python code runs fine from IDLE
EDIT
I just did a bit of change in the code as below
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");
PyInstance wrapper = (PyInstance)interpreter.eval("helloworld" + "(" + ")");
PyObject result = wrapper.invoke("getName()");
String realResult = (String) result.__tojava__(String.class);
System.out.println(realResult);
and I introduced a class in my python module
from faker import Factory
class helloworld:
def init(self):
fake = Factory.create()
def getName():
name = fake.name()
return name
Now am getting the error below
Exception in thread "main" Traceback (innermost last):
File "<string>", line 1, in ?
TypeError: call of non-function (java package 'helloworld')
You cannot use python attribute access in PythonInterpreter.get. Just use attribute name to get the module, and retrieve attribute from it.
(EDIT PART) Python code is totally broken. Please see the proper example below. And, of course, www.python.org.
(EDIT PART) First parameter of PyInstance.invoke should be method name.
Below you can find working code sample for both cases
Main.java
import org.python.core.*;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
test1();
test2();
}
private static void test1() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import hello_world1");
PyObject func = interpreter.get("hello_world1").__getattr__("get_name");
System.out.println(func.__call__().__tojava__(String.class));
}
private static void test2() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from hello_world2 import HelloWorld");
PyInstance obj = (PyInstance)interpreter.eval("HelloWorld()");
System.out.println(obj.invoke("get_name").__tojava__(String.class));
}
}
hello_world1.py
def get_name():
return "world"
hello_world2.py
class HelloWorld:
def __init__(self):
self.world = "world"
def get_name(self):
return self.world
Why does my code (compiles fine) gives me the following error?
Main method not found in class ImageTool, please define the main method as: public static void main(String[] args)
Code:
public class ImageTool {
public static void main(String[] args) {
if (args.length <1) {
System.out.println("Please type in an argument");
System.exit(-1);
}
if (args[0].equals("--dump")) {
String filename = args[1];
int[][] image = readGrayscaleImage(filename);
print2DArray(image);
} else if (args[0].equals("--reflectV")) {
String filename = args[1];
int[][] image = readGrayscaleImage(filename);
int[][] reflect = reflectV(image); //reflectV method must be written
String outputFilename = args[2];
writeGrayscaleImage(outputFilename,reflect);
}
}
Your main method looks fine.
1) Probably your .class file does not correspond to your .java file.
I would try to clean up my project (if I was using an IDE and getting this).
That is: delete the .class file, regenerate it from the .java file.
2) Seems you're not running ImageFile but some other class,
even though you think you're running ImageFile. Check what
your IDE is running behind the scenes.
I hope one of these two suggestions would help.
We use Mercury Quality Center 9 for storage tests and test results.
I need to read test data from Test Plan and to write test result into Test Lab via java.
I tried to find about this in google but I have not found anything.
UPDATE:
I tried to use qctools4j for working with MQC 9 with the following code:
public void connect() {
try{
IQcConnection conn = QcConnectionFactory.createConnection("http://qc/qcbin");
conn.connect("login", "password", "DEFAULT","project");
TestClient tc = conn.getTestClient();
System.out.println("Connection success!!!");
}
catch (QcException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
I got the following exception message:
*org.qctools4j.exception.QcException: Can't co-create object
at org.qctools4j.clients.QcConnectionImpl.initConnection(Unknown Source)
at org.qctools4j.clients.QcConnectionImpl.<init>(Unknown Source)
at org.qctools4j.QcConnectionFactory.createConnection(Unknown Source)
at automation_framework1.automation_framework1.QCWorker.connect1(QCWorker.java:38)
at automation_framework1.automation_framework1.Main.main(Main.java:12)
Caused by: com.jacob.com.ComFailException: Can't co-create object
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at org.qctools4j.clients.QcConnectionImpl.initConnection(Unknown Source)*
What am I doing wrong?
I took part in developping QC 9 and I am not sure there is Java API. However, there is a COM interface or OTA API. You can use some library that helps to call COM API from Java.
For example:
Jacob it is open source and here are some examples.
Nevaobject - it is commercial but more stable.
Good luck!
EDIT:
just saw qctools4j (it is based on Jacob) - never tried it.
I found how to solve the problem. I used groovy scriptom with the following code (may be it will help somebody):
def tdc;
public QualityCenterController(){
static{
System.load("C:\\WINDOWS\\system32\\OTAClient.dll");
System.load("D:\\Work\\automation_framework\\libs\\lib\\jacob-1.16-M2-x86.dll");
}
public void connect(){
tdc = new ActiveXObject ("TDApiOle80.TDConnection");
tdc.InitConnectionEx("http://qc/qcbin");
tdc.Login("username", "password");
tdc.Connect("DEFAULT","PROJECT");
System.out.println("login is success");
}
//ReqFactory Object
public void getRequirements(){
def requironmetns = tdc.ReqFactory();
def listReq = requironmetns.NewList("");
for (def iterReq : listReq) {
getRequirement(iterReq);
}
println listReq.count();
}
//Req Object
public void getRequirement(def itemReq){
println 'ID: '+itemReq.ID();
println 'Name:' + itemReq.Name();
println 'Path:' + itemReq.Path();
println 'Reviewed:' + itemReq.Reviewed();
println 'Author:' + itemReq.Author();
println 'Priority: ' + itemReq.Priority();
println 'Comment: '+removeHtmlTag(itemReq.Comment());
println 'Type: ' + itemReq.Type();
}
public Test getTestsFromTestLab(String path){
Test resultTest = new Test();
def labFolder = tdc.TestSetTreeManager.NodeByPath(path);
def tsList = labFolder.FindTestInstances("");
for (def iterable_element : tsList){
Test test = getTestData(iterable_element);
def steps = iterable_element.Test().DesignStepFactory();
TestStep testStep = getTest(steps);
}
return resultTest;
}
public TestStep getTest(def testData){
TestStep testStep = new TestStep();
def listSteps = testData.NewList("");
for(def item1 : listSteps){
testStep = getTestStepData(item1);
showTestStep(testStep);
}
return testStep;
}
private TestStep getTestStepData(def stepData){
TestStep testStep = new TestStep();
testStep.setId(stepData.ID());
testStep.setName(stepData.StepName());
testStep.setDescription(removeHtmlTag(stepData.StepDescription()));
testStep.setExpected(removeHtmlTag(stepData.StepExpectedResult()));
testStep.setStepOrder(stepData.Order());
return testStep;
}
public Test getTestData(def testData){
Test test = new Test();
test.setId(Integer.parseInt(testData.Id()));
test.setName(testData.Name());
test.setExecStatus(testData.Status());
showTest(test);
return test;
}
private String removeHtmlTag(String html){
String result = "";
result = Jsoup.parse(html).text();
return result;
}
public void showTestStep(TestStep testStep){
println testStep.getId();
println testStep.getName();
println testStep.getDescription();
println testStep.getExpected();
println testStep.getStepOrder();
}
public void showTest(Test test){
println test.getId();
println test.getName();
println test.getExecStatus();
}