Issue while compilng java code from django - java

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

Related

GraalVM - embedding python multi-file project in java

I couldn't find a solution create a polyglot source out of multiple files in GraalVM.
What exactly I want to achieve:
I have a python project:
my-project:
.venv/
...libs
__main__.py
src/
__init__.py
Service.py
Example sourcecode:
# __main__.py
from src.Service import Service
lambda url: Service(url)
# src/Service.py
import requests
class Service:
def __init__(self, url):
self.url = url
def invoke(self):
return requests.get(self.url)
This is very simple example, where we've got an entry-point script, project is structured in packages and there is one external library (requests).
It works, when I run it from command-line with python3 __main__.py, but I can't get it work, when embedding it in Java (it can't resolve imports).
Example usage in java:
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import java.io.File;
import java.io.IOException;
public class Runner {
public static void main(String[] args) throws IOException {
Context context = Context.newBuilder("python")
.allowExperimentalOptions(true)
.allowAllAccess(true)
.allowIO(true)
.build();
try (context) {
// load lambda reference:
Value reference = context.eval(Source.newBuilder("python", new File("/path/to/my-project/__main__.py")).build());
// invoke lambda with `url` argument (returns `Service` object)
Value service = reference.execute("http://google.com");
// invoke `invoke` method of `Service` object and print response
System.out.println("Response: " + service.getMember("invoke").execute());
}
}
}
It fails with Exception in thread "main" ModuleNotFoundError: No module named 'src'.
The solution works for javascript project (having similar index.js to __main__.py, its able to resolve imports - GraalVM "sees" other project's files, but somehow it doesn't, when using python.
I found out, that python is able to run zip package with project inside, but this also doesn't work with GraalVM.
Is there any chance to accomplish it? If not, maybe there is a similar tool to webpack for python (if I could create a single-file bundle, it should also work).
Btw, I don't know python at all, so I may missing something.
Thanks for any help!

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);
}

Java commands in JRuby

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

PyDev Jython module_not_found_in_the_pythonpath, autocomplete not working

I've been searching for two days now trying to get PyDev to recognize my external .JAR (It's obfuscated for protection), however no matter what I do it doesn't want to work. I've read over the documentation for nearly a hour straight trying to get it to work.
I'm helping to work on an emulation server which uses Jython for scripting. I can compile and run the emulation server with the scripts working just fine however, without using autocompletion for the methods inside the engine part of the server which is obfuscated in a external .jar.
Here is an example code of a script which uses methods from the obfuscated .JAR (which isn't working with autocomplete, so I have to navigate through the package explorer to find the method I want to use):
import sys
def CreateStartingCharacter(core, object):
testObject = core.objectService.createObject('object/weapon/ranged/rifle/shared_rifle_t21.iff', object.getPlanet())
testObject.setCustomName('This is a Jython Rifle')
testObject.setStringAttribute('crafter', 'Light')
inventory = object.getSlottedObject('inventory')
inventory.add(testObject)
testClothing = core.objectService.createObject('object/tangible/wearables/cape/shared_cape_rebel_01.iff', object.getPlanet())
testClothing.setCustomName('Test Cape')
testCloak = core.objectService.createObject('object/tangible/wearables/robe/shared_robe_jedi_dark_s05.iff', object.getPlanet())
testCloak.setCustomName('Test Cloak')
inventory.add(testClothing)
inventory.add(testCloak)
return
This script is executed by the following command in Java (core is the class inside the external JAR, obfuscated)
core.scriptService.callScript("scripts/", "demo", "CreateStartingCharacter", object);
object is...
CreatureObject object = (CreatureObject)core.objectService.createObject(sharedRaceTemplate, core.terrainService.getPlanetList().get(0));
Like I said above, all of those methods that I used in the script were from the obfuscated JAR which isn't working with autocomplete. However, I can use a method that isn't in that JAR just fine such as:
from resources.common import RadialOptions
from services.sui import SUIWindow
from services.sui.SUIWindow import Trigger
from java.util import Vector
import sys
def createRadial(core, owner, target, radials):
radials.clear()
bank = owner.getSlottedObject('bank')
if bank:
radials.add(RadialOptions(0, 21, 1, ''))
radials.add(RadialOptions(0, 7, 1, ''))
radials.add(RadialOptions(1, RadialOptions.bankTransfer, 3, '#sui:bank_credits'))
radials.add(RadialOptions(1, RadialOptions.bankitems, 3, '#sui:bank_items'))
if owner.getBankCredits() > 0:
radials.add(RadialOptions(1, RadialOptions.bankWithdrawAll, 3, '#sui:bank_withdrawall'))
if owner.getCashCredits() > 0:
radials.add(RadialOptions(1, RadialOptions.bankDepositAll, 3, '#sui:bank_depositall'))
return
... and using RadialOptions. control+space will show me all the methods.
Help would be much appreciated. At this point I feel that it's not working because the JAR file is obfuscated or something like that. And yes, I've already added it to my PYTHONPATH and updated the interpreter, just like with the bin folder for my project.

Categories

Resources