Java commands in JRuby - java

I am adding jar files to my jruby code in the .rb file
I put the following:
import 'java'
import 'weather.jar'
import 'weatherStatus.WeatherStatus' #this is the package and class
Now I have classes in weather.jar that I need to use here but it keeps giving me errors. I don't know how to convert the following java lines to jruby and everytime I try something from the tutorials, it give me errors.
The following command lines are from java and I want to include them in my jruby file:
sunnyDay var1 = null;
var1 = new sunnyDay(var2, var3);
String var4 = var1.TimeOfDay(var5);
sunnyDay is from package called weatherStatus
How can I do that in Jruby?

I suggest you thoroughly read the following two links to have a better understanding of using JRuby :)
https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby
https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding

Related

Running Scala function from command line

I'm working on an exercise. I need to create a java project that can be run from the scala command line. The final output should be this:
scala> int2str(6)
res0: String = six
scala> int2str(65)
res0: String = sixty-five
How do I create a function that can be accessed by scala like that? I can create a Scala project in IntelliJ, but I don't know how to export that function to be used like that.
Any help is appreciated.
Thanks
Assuming you have the following scala code:
object A {
def int2str(i: Int): String = ""
}
You can just make a jar file from your scala project with a command
sbt package for instance, then run scala -cp <your jar>.
In the scala console just import your function:
import A.int2str

Issue while compilng java code from django

I am new to django web development currently i am trying to create online java compiler using django which consists of two fields i.e code(we can write our own logic) and inputfield(we can provide our own input field) in this process i am facing issue while executing java program
with below code
here is my code
and i am using python 2.7 and django 1.8
import re
import os
from django.shortcuts import render
from django.http import HttpResponse
from .forms import GetForm
import subprocess
def index(request):
if request.method=="GET":
form=GetForm()
return render(request,'compile.html',{'form':form})
else:
form =GetForm(request.POST)
if form.is_valid():
main_class_name=""
text=form.cleaned_data["code"]
// here main_class_name holds main class java name
for i in re.split('class ',text)[1:]:
if re.search('public static void main',i):
main_class_name=re.search('(\w*)',i).group(1)
os.chdir('/home/username/Desktop/onlineproject/projectCompiler/javacompile/')
sd=open(main_class_name+".java","a")
sd.write(text)
proc =
subprocess.Popen(['javac',main_class_name+'.java'],stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
cmd=['java', main_class_name]
output =subprocess.check_output(cmd,shell=True,
stdin=subprocess.PIPE,stderr=subprocess.PIPE)
form.save()
return render(request,'compile.html',{'form1':text})
#My issue
My issue is i am able to compile and generate the .class file using above python script but i am unable to run the java code using "java classname" using above python script
and also i am not getting any error while executing the above code
please help me

Is it possible to convert this Java code to Jython for a Minecraft Plugin?

I was looking at this video to find some information on making Minecraft Plugins. https://youtu.be/r4W4drYdb4Q
All plugins are made with Java. Since I program with Python I was wondering if it is possible to make a Plugin similar to the one seen in the video but with Jython. I am not sure if this is possible but I started trying.
When programming Java most people use Eclipse and there is a button that says "Add external Jar" and that is where you input the spigot jar file. From what I understand I can do that with:
import sys
sys.path.append("spigot-1.15.2.jar")
in Jython. Then there comes the tricky part. How would I go about converting this:
Code Part 1
Code Part 2
From what I thought I needed to do was something like:
from org.bukkit.plugin.java import JavaPlugin
class Main(JavaPlugin):
def onEnable():
pass
#what do I put here?
def onDisable():
pass
#what do I put here?
But I don't think I am properly converting the Java code to Jython. What would be the proper way to convert the code from Java to Jython?
Thanks very much!
From my understanding you want to interact from your Jython code with a Java class which extends JavaPlugin.
For this I suggest you write a thin wrapper in Java which then calls your Jython code where you do the heavy lifting in your familiar language. A skeleton of the wrapper could look like this:
package {$GroupName}.{$ArtifactName};
import org.bukkit.plugin.java.JavaPlugin;
import org.python.util.PythonInterpreter;
public final class {$ArtifactName} extends JavaPlugin {
#Override
public void onEnable() {
PythonInterpreter pi = new PythonInterpreter();
pi.execfile("enable.py"); // enable.py is the Jython file with the enable stuff
}
#Override
public void onDisable() {
PythonInterpreter pi = new PythonInterpreter();
pi.execfile("disable.py"); // enable.py is the Jython file with the disable stuff
}
}
Be aware that instantiating PythonInterpreter is rather slow, so you'd be better off with a pattern where you do this only once. Plus then you can share data between enable and disable!
For more details and other options (like having the Jython stuff in one file and calling into it via pi.exec) look at Chapter 10: Jython and Java Integration in the Jython Book.
Also keep in mind when coding away: Jython is only Python 2.7!!!

Running a Python program in Java using Jython

I wrote a Python program that consists out of five .py script files.
I want to execute the main of those python scripts from within a Java Application.
What are my options to do so? Using the PythonInterpreter doesn't work, as for example the datetime module can't be loaded from Jython (and I don't want the user to determine his Python path for those dependencies to work).
I compiled the whole folder to .class files using Jython's compileall. Can I embed these .class files somehow to execute the main file from within my Java Application, or how should I proceed?
Have a look at the ProcessBuilder class in java: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html.
The command used in the java constructor should be the same as what you would type in a command line. For example:
Process p = new ProcessBuilder("python", "myScript.py", "firstargument").start();
(the process builder does the same thing as the python subprocess module).
Have a look at running scripts through processbuilder
N.B. as for the Jython part of the question, if you go to the jython website (have a look at the FAQ section of their website www.jython.org). Check the entry "use jython from java".
I'm also interested in running Python code directly within Java, using Jython, and avoiding the need for an installed Python interpreter.
The article, 'Embedding Jython in Java Applications' explains how to reference an external *.py Python script, and pass it argument parameters, no installed Python interpreter necessary:
#pymodule.py - make this file accessible to your Java code
def square(value):
return value*value
This function can then be executed either by creating a string that
executes it, or by retrieving a pointer to the function and calling
its call method with the correct parameters:
//Java code implementing Jython and calling pymodule.py
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class ImportExample {
public static void main(String [] args) throws PyException
{
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from pymodule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
}
Jython's Maven/Gradle/etc dependency strings can be found at http://mvnrepository.com/artifact/org.python/jython-standalone/2.7.1
Jython JavaDoc
It is possible to load the other modules. You just need to specify the python path where your custom modules can be found. See the following test case and I am using the Python datatime/math modules inside my calling function (my_maths()) and I have multiple python files in the python.path which are imported by the main.py
#Test
public void testJython() {
Properties properties = System.getProperties();
properties.put("python.path", ".\\src\\test\\resources");
PythonInterpreter.initialize(System.getProperties(), properties, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(".\\src\\test\\resources\\main.py");
interpreter.set("id", 150); //set variable value
interpreter.exec("val = my_maths(id)"); //the calling function in main.py
Integer returnVal = (Integer) interpreter.eval("val").__tojava__(Integer.class);
System.out.println("return from python: " + returnVal);
}

jpype+pdfbox class not found

I'm attempting to use JPype to call Apache Pdfbox from Python, and am having some difficulty actually importing the classes. It doesn't seem to be able to read them from the jar file in the class path.
from jpype import java, startJVM, shutdownJVM, JPackage, JClass, getDefaultJVMPath, nio
import sys, os, codecs
pdfbox_lib = "lib/pdfbox-1.6.0.jar"
classpath = '-Djava.class.path=' + pdfbox_lib + os.pathsep + '.'
startJVM(getDefaultJVMPath(), '-Xmx512m', classpath)
stream = java.io.FileInputStream(java.io.File("test.pdf"))
pdfparser = JPackage('org.apache.pdfbox.pdfparser')
parser = JClass('org.apache.pdfbox.pdfparser.PDFParser')
At this point, the script errors out with the following:
java.lang.ExceptionPyRaisable: java.lang.Exception: Class org.apache.pdfbox.pdfparser.PDFParser not found
I'm running on Linux with Python 2.7, and I know there's nothing wrong with the JPype installation (if there were, the stream declaration would error out). I've also tried various permutations of the class path statement and the JPackage/JClass statements, and nothing seems to matter. Any suggestions would be greatly appreciated!
I figured it out. Three additional jars need to be added to the class path: fontbox-x.x.x.jar, jempbox-x.x.x.jar, and commons-logging.jar.

Categories

Resources