How to find the containing egg file from Python class? - java

From Python 2.6 it is possible to run an egg file directly from python command line, by incorporating a main.py file.
Now... is it possible to detect in runtime if the current executing python code is running directly from an egg and obtain the path of it ?
I'm trying to mirror similar Java functionality where it is possible to get the containing jar from a class through Java's ClassLoader.

I didn't find a nicer pythonic way to do this otherwise by hand:
puria#spaghetti:~$ cat __main__.py
import zipfile, os
module_path = os.path.dirname(__file__)
print "Is this an egg? ", zipfile.is_zipfile(module_path)
puria#spaghetti:~$ python __main__.py
Is this an egg? False
puria#spaghetti:~$ zip example.egg __main__.py
adding: __main__.py (deflated 15%)
puria#spaghetti:~$ python example.egg
Is this an egg? True
Hope this is useful and I actually understood your question.

Related

-usedefaultlisteners treated as file when supplied as command line argument to testNG

Sorry if this question has already been answered some where, I have not had any luck turning up a solution. This is my first SO post, if information is missing/unclear, or the formatting sucks, let me know, I will update the post.
I am using TestNG version 6.13.1 (also tested with 7.0.0-beta1). I am running this command (not the full command, the class path is massive, and there are multiple -D options)
java -cp <classpath stuff...> -DappiumPort=30000 org.testng.TestNG -usedefaultlisteners false /Users/.../adbservice/test-results/3567/test_config/Test_Suite_testT13googleMaps.xml
expecting that testNG will recognize the first argument as a switch, and turn the default listeners off. This is based on reading Turning off test-output in TestNG and http://testng.org/doc/documentation-main.html#testng-xml, and other less relevant documents.
What actually happens is testNG appears to treat all the arguments as if they are file paths, and I get a very helpful error message
ProcessResults(exitCode=0, output=java.io.FileNotFoundException: /Users/.../adbservice/-usedefaultlisteners false testng.xml (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:139)
at org.testng.xml.Parser.parse(Parser.java:148)
at org.testng.xml.Parser.parse(Parser.java:233)
at org.testng.TestNG.parseSuite(TestNG.java:290)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:334)
at org.testng.TestNG.initializeEverything(TestNG.java:974)
at org.testng.TestNG.run(TestNG.java:988)
at org.testng.TestNG.privateMain(TestNG.java:1330)
at org.testng.TestNG.main(TestNG.java:1299)
The command itself is issued from Java, using a wrapper around a ProcessExecutor. The code looks like
new ProcessExecutor()
.command(cmd)
.readOutput(true)
.timeout(waitForTimeMs, TimeUnit.MILLISECONDS)
.execute();
I can get the same error if I capture the command input and paste it into the shell, so it seems that it is not a problem with the java code itself, but I figured I would include that information for completeness.
My question is, how can I make this call to testNG work using the command line arguments? There seem to be few alternatives because I have packaged tests which are executed in a shell process.
Edit
Since this is such a common case, I am convinced there is something wrong on my side. I tested that theory out by creating a really simple java project with a smoke test, and then ran it with
java -cp .:testng-6.13.1.jar:jcommander-1.72.jar:build/libs/test-1.0-SNAPSHOT.jar org.testng.TestNG -usedefaultlisteners false testng.xml
which worked exactly as described in the documentation. Therefore I think there is something going on with the input to java and how it is being processed that is causing the error with testNG.
Edit 2
Did some further investigation on my side, eventually I tried the original generated java command with the parameters ( -usedefaultlisteners false) on the command line, and lo and behold it worked, or at least, it did some stuff before bombing out, instead of complaining about the parameters being invalid file paths, which was my original result when running on the command line. Maybe I had the wrong directory or some such the first time, but this suggests that it is a problem with handling the command with this ProcessExecutor.
Edit 3
Paydirt. It turns out the ProcessExecutor library does not handle command line input with spaces as one might expect, so for example,
Lists.newArrayList(
"java", "-cp", ".:", "org.testng.TestNG", "-enabledefaultlisteners false", "testng.xml"
)
will error, but
Lists.newArrayList(
"java", "-cp", ".:", "org.testng.TestNG", "-enabledefaultlisteners", "false", "testng.xml"
)
works. It seems like that should be documented in the ProcessExecutor library docs.

Use BerkeleyParser.jar in django (views.py), but get a empty output file

I use the following code in a views.py
def berkeleyParser(infile,outfile):
cmd="java -Xmx1024m -jar nlptools/BerkeleyParser/berkeleyParser-1.7.jar -gr nlptools/BerkeleyParser/chn_sm5.gr < "+infile+" > "+outfile
os.system(cmd)
and then call this function to use berkeley parser.
I think the file path is ok, because the jar can successfully create the output file.
Meanwhile, I use a independent .py code to run the code above (with path modified), and got correct result in output file.
So, I don't know what's wrong with it.

Migrating OmniDriver from Matlab to Octave. Need to find librarypath.txt for Octave?

I currently use Matlab and the Ocean Optics Omnidriver (http://oceanoptics.com/faq/controlling-usb-spectrometers-omnidriver-matlab/) to control a USB spectrometer on a windows 7 machine, and I'm trying to migrate to Octave.
Omnidriver is written in Java, and there is reasonable documentation for Matlab. After installing the driver the relevant Matlab commands are:
>> javaaddpath('C:\Program Files\Ocean Optics\OmniDriver\OOI_HOME\OmniDriver.jar');
>> wrapper = com.oceanoptics.omnidriver.api.wrapper.Wrapper();
>> wrapper.openAllSpectrometers();
the first line seems to translate directly once the '\' are replaced with '/', and I can see the file added to the dynamic java path.
The second line directly throws "error: 'com' undefined", but replacing with;
>> wrapper = javaObject ("com.oceanoptics.omnidriver.api.wrapper.Wrapper")
seems to work.
The third line directly then throws the error;
"error: [java] java.lang.NoClassDefFoundError: Could not initialize class com.oceanoptics.uniusb.UniUSB"
which is where I'm stuck at the moment (UniUSB.jar is a file in OOI_HOME).
On the OceanOptics page linked above, what I'm assuming is the same error is listed as a common problem caused by Matlab failing to find the required DLLs, and the solution is given as adding the path to OOI_HOME to matlabroot/toolbox/local/librarypath.txt
I'm assuming that if I can find the equivalent octave file then adding the path should solve my problem, but I can't find the file.
Any advice would be greatly appreciated!
The code
>> javaaddpath('C:\Program Files\Ocean Optics\OmniDriver\OOI_HOME\OmniDriver.jar');
>> wrapper = com.oceanoptics.omnidriver.api.wrapper.Wrapper();
>> wrapper.openAllSpectrometers();
translates better with:
wrapper = javaObject ("com.oceanoptics.omnidriver.api.wrapper.Wrapper");
javaMethod ("openAllSpectrometers", wrapper);
Note that this is also valid Matlab syntax.
Another thing is that Octave handles java classes better if they are on the static classic path. So I'd recommend you add the path to OmniDriver.jar to your javaclasspath.txt file. See the manual for details.

slurping /proc/cpuinfo with clojure

(Clojure newbie)
On my linux machine, slurping /proc/cpuinfo raises an error:
user=> (slurp "/proc/cpuinfo")
java.io.IOException: Invalid argument (NO_SOURCE_FILE:0)
Anybody knows why that is? (is the /proc filesystem some kind of second-class citizen in Java?)
Edit: the following code, adapted from nakkaya.com, works flawlessly:
(with-open [rdr (java.io.BufferedReader.
(java.io.FileReader. "/proc/cpuinfo"))]
(let [seq (line-seq rdr)]
(apply print seq)))
I wonder why this difference ?
I've had a similar problem with files in /proc. The solution is simple though:
(slurp (java.io.FileReader. "/proc/cpuinfo"))
the problem is that java cannot open a DataInputStream on /proc so the slurp function isnt going to help you here, sorry :(
/proc/cpuinfo is a little strange because it has a file size of zero and produces bytes when read. this upsets the smarter java file handling classes.
ls -l /proc/cpuinfo
-r--r--r-- 1 root root 0 2012-01-20 00:10 /proc/cpuinfo
see this thread for more http://www.velocityreviews.com/forums/t131093-java-cannot-access-proc-filesystem-on-linux.html
you are going to have to open it with a FileReader. I'll add an example in a bit

How can I execute a Java program within a php script?

I am writing a simple web upload script.
The goal is to upload a file using php, and then calling a java program to process this file.
I have done the work for uploading the file, but I cannot get a java program to be successfully run from within the php script.
I have tried exec(), shell_exec(), and system() with no results.
For the command, I have used "java Test", "java < directory >/Test", "/usr/bin/java < directory >/Test", I have even set up the application as a jar file with no results. The actual line of code I have used is:
echo shell_exec("java Test");
Usually there is no output. However, if I have just shell_exec("java"), then the last line of the help from java ("show splash screen with specified image") is displayed, which shows that the command has been executed. If I use, for example, shell_exec("whoami") I get "nobody" returned, which is correct. The only thing the java file does is create a file so that I can see that the application has been successfully run (the application runs successfully if I run it on the command line). I have set the permissions for the java file to 777 to rule out any possibility of permission errors. I have been struggling with this for a while trying all sorts of options with no results - the file is never created (the file is created with an absolute path so it's not being created and I just can't find the file). Does anyone have any ideas?
Thanks.
I have been struggling with this for a
while trying all sorts of options with
no results - the file is never created
(the file is created with an absolute
path so it's not being created and I
just can't find the file). Does anyone
have any ideas?
What I think the problem is. Apache runs as "nobody" group??(apache user??) which will execute the java script which will try to create a file on disc somewhere. I assume it does not have permission to write to that location. you should chown that folder so that apache user can write to that folder.
==
First off I would like to point out to you that calling exec() from a script could really blow up your server. I would advice you to use something like redis(see below) instead.
==
Second I think I know what the problem is. You should first try to run the simple example below which worked fine for me.
==
First be sure permission are set right. Because apache runs as nobody(most of the times).
I tried this simple test myself on ubuntu with php installed from repo.
test.java
class test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
test.php
echo exec('java test');
Ran test.php
$ php test.php
Hello World!
==
Or you could try 1 of the following solutions(which would even be a better solution):
Write your java program as a webservice for example on top of atmosphere-spade-server(simple/embedded jar). This could be written insanely fast. But on high load this will not be best option I guess. Still I think this will be more than fast enough for you probably. Even this way it will be much faster as executing it, because you won't have the overhead running JVM. Could blow up your server, not as fast as exec()
Do a blocking pop/push from a redis(*nix) list structure. This will be pretty easy to write on *nux because there are client libraries for both java/php. The speed will best I guess because redis is written in C. I use redis myself.
Use a JMS like for example activemq. Also pretty easy to write because good library support. I have not used a JMS myself. I use redis solution. The speed I guess would be a little less then with redis solution.
I dont realy know, but i came a cross PHP-JAVA bridge maybe it can help
http://php-java-bridge.sourceforge.net/pjb/
Update:
I tested this with Jasper Reports, and it is working really nice. It will allow you to Extend Java classes with PHP or just use Java class lik it was PHP.
use java\lang\String as JString;
require_once("javabridge/java/Java.inc");
class String extends JString {
function toString () {
return "hello " . parent::toString();
}
}
$str = new String("Java");
echo $str->toString();
or
$temp = new Java('java.sql.Timestamp');
$javaObject = $temp->valueOf('2007-12-31 0:0:0');
$params = new Java("java.util.HashMap");
$params->put("text", "This is a test string");
$params->put("date",$javaObject);
More examples: http://php-java-bridge.sourceforge.net/pjb/FAQ.html
It's possible it has to do with the path that the exec is defaulting to. You may need to explicitly define your classpath with an absolute path to your .class or jar files when calling java.
<?php
$PATH="C:\Program Files\Java\jdk1.7.0_09\bin";
echo exec("javac theNameOfYourJavaProgram.java 2>&1");//shows # of errors
echo "<br />";
echo exec("java theNameOfYourJavaProgram 2>&1");//this line executes it
echo "<br />";
echo shell_exec("javac theNameOfYourJavaProgram.java 2>&1 ");//compiles it
?>

Categories

Resources