Calling java function from .py file in Pydev - java

I have a file.py as follows :
import unittest
from com.bahmanm import Greeter
class A(unittest.TestCase, Greeter):
def test_A(self):
self.greet("Bahman")
if __name__ == "__main__":
unittest.main()
In above case, Greeter is a java file as:
package com.bahmanm;
public class Greeter
{
private String msg;
public Greeter()
{
msg = "Hello, ";
}
public void greet(String name)
{
System.out.println(msg + name);
}
}
The code executes successfully, but I am not able to navigate from python code to java code (in PyDev) at line self.greet("Bahman") in the file.py code.
Though, I am able to view the contents of Greeter file from line
from com.bahmanm import Greeter. But unable to check the code flow at the function call.
I am using jython interpreter (grammar 2.5, default interpreter,jython.jar 2.5.3). I have also added the Java src path to PYTHONPATH in Eclipse. Also I have added Java project in the
PYTHON PROJECT->RIGHT CLICK->PROPERTIES-> PROJECT REFERENCES
Any suggestion regarding the above navigation will be of great help.

Related

Not able to read a file from other package in the same module

I am using Intellij Idea - 2021.2.4 and Java 8.
In Intellij, I am not able to read a file in another package in the same module. The file is under main and not resource folder. But in Eclipse, I am able to read.
For example. Below code prints different outputs in both eclipse and intellij.
import java.net.URL;
public class TestMain {
public static void main(String[] args) {
URL resource = TestMain.class.getResource("/org/files/input.txt");
if(resource == null) {
System.out.println("Resource is null");
} else {
System.out.println("Resource found!!");
}
}
}
In Intellij, the code prints "Resource is null", but in eclipse, the code prints "Resource found!!".
Is there any setting I need to enable/disable in intellij ? Why code is behaving different in Intellij Idea ?

Jython - Calling Python Class in Java

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.

ImportError: No Module named demiso in Jython

I'm new to the Jython and I'm trying to run a python class using Jython in Java. But I'm running into some issues.
The Java class that I've defined:
public class DemistoCalls {
PythonInterpreter interpreter = null;
public DemistoCalls()
{
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[] args) {
DemistoCalls demistoCalls = new DemistoCalls();
demistoCalls.execfile("C:\\Users\\AlokNath\\Desktop\\Demisto_Project\\demisto-py-master\\demisto\\SimpleConnect.py");
}
}
The SampleConnect.py file that I'm trying to run:
import sys
sys.path.append("C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-
master\demisto")
import demisto
While Running the java file, I'm getting this error:
File "C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-master\demisto\SimpleConnect.py", line 3, in <module>
import demisto
ImportError: No module named demisto
Although I've defined the "demisto" module in the system path and checked that the system path in python contains the appropriate path to Jython 2.7.lb2 Library. I'm not sure where am I going wrong. Any help is appreciated.
Regards,
Alok
I found a solution to the import error problem. We need to copy the missing module to the “site-packages” folder under "modeler-installation/lib/jython/Lib". This will resolve the dependency problem.

groovy win cmd line class and script

I'm trying to run a groovy(2.4.3) script on windows that calls a goovy class xxxxx.groovy. I've tried a number of variations using classpath and various scripts, some examples below, always getting MultipleCompliationErrorsException.... unable to resolve class
classfile is firstclass.groovy
import org.apache.commons.io.FilenameUtils
class firstclassstart {
def wluid, wlpwd, wlserver, port
private wlconnection, connectString, jmxConnector, Filpath, Filpass, Filname, OSRPDpath, Passphrase
// object constructor
firstclassstart(wluid, wlpwd, wlserver, port) {
this.wluid = wluid
this.wlpwd = wlpwd
this.wlserver = wlserver
this.port = port
}
def isFile(Filpath) {
// Create a File object representing the folder 'A/B'
def folder = new File(Filpath)
if (!org.apache.commons.io.FilenameUtils.isExtension(Filpath, "txt")) {
println "bad extension"
return false
} else if (!folder.exists()) {
// Create all folders up-to and including B
println " path is wrong"
return false
} else
println "file found"
return true
}
}
cmd line script test.groovy
import firstclass
def sample = new firstclass.firstclassstart("weblogic", "Admin123", "x.com", "7002")
//def sample = new firstclassstart("weblogic", "Admin123", "x.com", "7002")
sample.isFile("./firstclass.groovy")
..\groovy -cp "firstclass.groovy;commons-io-1.3.2.jar" testfc.groovy
script test.groovy
GroovyShell shell = new GroovyShell()
def script = shell.parse(new File('mylib/firstclass.groovy'))
firstclass sample = new script.firstclass("uid", "pwd", "url", "port")
sample.getstatus()
c:>groovy test.groovy
script test.groovy v2 put firstclass.groovy in directory test below script
import test.firstclass
firstclass sample = new script.firstclass("uid", "pwd", "url", "port")
sample.getstatus()
c:>groovy test.groovy
just looking for a bullet proof, portable way to oranize my java classes, .groovy classess, etc. and scripts.
Thanks
I think that you can do using for example your first approach:
groovy -cp mylib/firstclass.groovy mylib/test.groovy
However I see some problems in your code which are probably causing MultipleCompliationErrorsException.
Since you're including firstclass.groovy in your classpath, you've to add the import firstclass in the test.groovy.
Why are you using script.firstclass in test.groovy? you're class is called simply firstclass.
In your firstclass.groovy you're using import org.apache.commons.io.FilenameUtils and probably other, however you're not including it in the classpath.
So finally I think that, you've to change your test.groovy for something like:
import firstclass
firstclass sample = new firstclass("uid", "pwd", "url", "port")
sample.getstatus()
And in your command add the remaining includes for apache Commons IO to the classpath.
groovy -cp "mylib/firstclass.groovy;commons-io-2.4.jar;" mylib/testexe.groovy
Hope this helps,
UPDATE BASED ON OP CHANGES:
After the changes you've some things wrong, I try to enumerate it:
If your file is called firstclass.groovy your class must be class firstclass not class firstclassstart.
In your test.groovy use new firstclass not new firstclass.firstclassstart.
So the thing is, your code must be:
class file firstclass.groovy:
import org.apache.commons.io.FilenameUtils
class firstclass {
def wluid, wlpwd, wlserver, port
private wlconnection, connectString, jmxConnector, Filpath, Filpass, Filname, OSRPDpath, Passphrase
// object constructor
firstclass(wluid, wlpwd, wlserver, port) {
this.wluid = wluid
this.wlpwd = wlpwd
this.wlserver = wlserver
this.port = port
}
def isFile(Filpath) {
// Create a File object representing the folder 'A/B'
def folder = new File(Filpath)
if (!org.apache.commons.io.FilenameUtils.isExtension(Filpath, "txt")) {
println "bad extension"
return false
} else if (!folder.exists()) {
// Create all folders up-to and including B
println " path is wrong"
return false
} else
println "file found"
return true
}
}
script test.groovy:
import firstclass
def sample = new firstclass("weblogic", "Admin123", "x.com", "7002")
sample.isFile("./firstclass.groovy")
Finally the command to execute it:
groovy -cp "firstclass.groovy;commons-io-1.3.2.jar" test.groovy
With this changes your code must works, I try it and works as expected.

Compiled a class, but where is it?

I'm not an expert in Java and I'm pretty new to the whole concept of compiling and running dynamic generated code, which is so simple in other languages, expecially script languages like Javascript and PHP.
I'm following this snippet of code:
http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm
and I made something like this:
private final String = "GeneratedClass_" + Long.toHexString(random.nextLong());
private Method compileCode(String code) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) return null;
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaFileObject source = new JavaSource(className, code);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(source);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
if (!task.call()) return null;
try {
return Class.forName(className).getDeclaredMethods()[0];
} catch (ClassNotFoundException e) {}
return null;
}
private class JavaSource extends SimpleJavaFileObject {
final String code;
JavaSource(String name, String code) {
super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {return code;}
}
Just imagine that the string code is something like
"public class GeneratedClass_65ce701239c32ce0 {
public String hello() {
return "Hello, world!";
}
}"
It works well until that Class.forName which throws a ClassNotFoundException. I'm puzzled since it doesn't seem I cut something important from the snippet: so, the class was compiled but where has it gone?
I read something about using a different class loader, but since, like I said, I'm pretty new to all this stuff I don't know where to head and how to use it, and how should I define my own extension of ClassLoader.
The only thing I know is that everything seems quite complicated to me...
Using Eclipse Indigo in Windows 7 and JDK 1.7.
One important thing you cut was all the error output and diagnostic information. You'd never know if something went wrong. However, everything looks correct. Your problem is most likely just that you didn't send any options to the compiler, so it'll write the class file out to wherever it feels like (current working directory is the default, I believe), and that's probably not on your classpath, especially in an IDE. Try running it from the command line to prove to yourself it works. This should work:
mkdir tmp
javac -d tmp <path your main class .java file>
java -cp .;tmp <your main class name>
If you're not familiar with the command-line tools, the argument to javac has to be a file system path to the .java file, and the argument to java needs to be the .-separated, fully-qualifed class name, like com.foo.Main. Doing that should:
Compile your class to the tmp directory.
Write your dynamically-generated class to the current directory.
Successfully load the newly compiled class from the current directory because it's on the classpath.

Categories

Resources