Java to Python with Java2Python - java

I am using Java2Python package to translate a Java project to Python, and I've got an error.
[root#localhost Desktop]# j2py ConfigurationManager.java ConfigurationManager.py
File "/usr/bin/j2py", line 113
except (IOError, ), exc:
^
SyntaxError: invalid syntax
File /usr/bin/j2py, line 113
try:
if filein != '-':
source = open(filein).read()
else:
source = sys.stdin.read()
except (IOError, ), exc:
code, msg = exc.args[0:2]
print 'IOError: %s.' % (msg, )
return code
If there is any information needed, please tell me.
update
File "/usr/bin/j2py", line 115
print 'IOError: %s.' % (msg, )
^
SyntaxError: invalid syntax

Try this :
except (IOError) as exc:
for arg in exc.args:
print(str(arg))
code = exc.args[0]
return code
Here I assume that you want to return 1st value in exc.args

Related

how to get an output python from java input?

actually, i'm new in python. Here, i want to get an output from class of python. but here, i input String from java.
here's the java code:
String word;
Scanner in = new Scanner(System.in);
System.out.println("input: ");
word = in.nextLine();
TryinPythonToJavaAgain ie = new TryinPythonToJavaAgain();
ie.execfile("~\\hello.py");
PyInstance hello = ie.createClass("Hello", word);
hello.invoke("run");
python code:
class Hello:
def __init__(self, abc):
self.abc = abc
def run(self):
print(self.abc)
if i input : "hello"
i have an error like this:
input:
hello
Exception in thread "main" Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
Java Result: 1
and if i input >2 word (e.g "hello world"), i have an error like this:
input:
hello world
Exception in thread "main" SyntaxError: ("no viable alternative at input 'world'", ('', 1, 12, 'Hello(hello world)\n'))
Java Result: 1
what should i fix in this code? thanks
If the code in your createClass method looks anything like this ...
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
... then I think you need to add quotes round the opts variable. The code above is from here which works since "None" gets turned into this.interpreter.eval(className(None)) which is valid whereas yours becomes this.interpreter.eval(className(hello world)) which isn't.
I've not tried it, but this.interpreter.eval(className("hello world")) would seem more likely to work.

How to query eXist db from java

I'm trying to query a file based on the eXist database.
Through a simple function to display the contents of the file, no problem:
XMLResource res = (XMLResource) col.getResource(resourceName);
System.out.println(res.getContent());
But when I try against making a request impossible.
String xQuery = "for $x in doc(\"" + resourceName + "\")." + "return data($x).";
ResourceSet result = service.query(xQuery);
ResourceIterator i = result.getIterator();
I have the following errors:
Exception in thread "main" org.xmldb.api.base.XMLDBException: Failed to invoke method queryP in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.StaticXQueryException: exerr:ERROR org.exist.xquery.XPathException: exerr:ERROR err:XPST0003 in line 1, column 58: unexpected token: .
at org.exist.xmldb.RemoteXPathQueryService.query(RemoteXPathQueryService.java:114)
at org.exist.xmldb.RemoteXPathQueryService.query(RemoteXPathQueryService.java:71)
at ExistAccess.main(ExistAccess.java:45)
Caused by: org.apache.xmlrpc.XmlRpcException: Failed to invoke method queryP in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.StaticXQueryException: exerr:ERROR org.exist.xquery.XPathException: exerr:ERROR err:XPST0003 in line 1, column 58: unexpected token: .
at org.apache.xmlrpc.client.XmlRpcStreamTransport.readResponse(XmlRpcStreamTransport.java:197)
at org.apache.xmlrpc.client.XmlRpcStreamTransport.sendRequest(XmlRpcStreamTransport.java:156)
at org.apache.xmlrpc.client.XmlRpcHttpTransport.sendRequest(XmlRpcHttpTransport.java:143)
at org.apache.xmlrpc.client.XmlRpcSunHttpTransport.sendRequest(XmlRpcSunHttpTransport.java:69)
at org.apache.xmlrpc.client.XmlRpcClientWorker.execute(XmlRpcClientWorker.java:56)
at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:167)
at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:158)
at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:147)
at org.exist.xmldb.RemoteXPathQueryService.query(RemoteXPathQueryService.java:99)
... 2 more
[B#105081caorg.apache.xmlrpc.XmlRpcException: Failed to invoke method queryP in class org.exist.xmlrpc.RpcConnection: org.exist.xquery.StaticXQueryException: exerr:ERROR org.exist.xquery.XPathException: exerr:ERROR err:XPST0003 in line 1, column 58: unexpected token: .
I checked all my .jar file, and all of them are present... I really need help ! Thanks in advance!
Your query:
String xQuery = "for $x in doc(\"" + resourceName + "\")." + "return data($x).";
The core of the error:
err:XPST0003 in line 1, column 58: unexpected token: .
As the error message states, eXist-db recognizes an error with the "."; this period/dot is invalid XQuery. Remove the dot from the query, and you should be fine. The query text itself should look like this:
for $x in doc("/db/mycollection/mydocument.xml") return data($x)
Also, it appears your FLWOR loop is iterating over a single item - the resource. Therefore, the FLWOR is extraneous. You could refactor this as:
data(doc("/db/mycollection/mydocument.xml"))
I think you string concat make this issue, why not try to add a space after ".". Change your code like
String xQuery = "for $x in doc(\"" + resourceName + "\"). " + "return data($x).";

How to collect directory listing along with each file CRC checksum?

I use the following command to get dir listing in nix(Linux, AIX, Sunos, HPUX) platforms
Command
ls -latr
Ouput
drwxr-xr-x 2 ricky support 4096 Aug 29 11:59 lib
-rwxrwxrwx 1 ricky support 924 Aug 29 12:00 initservice.sh
cksum command is used for getting CRC checksum.
How can the CRC Checksum be appended after each file something (including directory listing too) like below, maintaining the below format in these nix(Linux, AIX, Sunos, HPUX) platforms?
drwxr-xr-x 2 ricky support 4096 Aug 29 11:59 lib
-rwxrwxrwx 1 ricky support 924 Aug 29 12:00 initservice.sh 4287252281
Update Note : No third party application, I am using java/Groovy to parse the output ultimately into a given format which forms a xml using groovy XmlSlurper (XML's get generated around 5MB sized)
"permission","hardlink","owner","group","fsize","month","date","time","filename","checksum"
All Suggestions are welcome! :)
Update with my code
But here I am calculating md5hex which gives a similar output as md5sum command from linux. So it's no longer cksum as I cannot use jacksum bcz of some licensing issue :(
class CheckSumCRC32 {
public def getFileListing(String file){
def dir = new File(file)
def filename = null
def md5sum = null
def filesize = null
def lastmodified = null
def lastmodifiedDate = null
def lastmodifiedTime = null
def permission = null
Format formatter = null
def list=[]
if(dir.exists()){
dir.eachFileRecurse (FileType.FILES) { fname ->
list << fname
}
list.each{fileob->
try{
md5sum=getMD5CheckSum(fileob.toString())
filesize=fileob.length()+"b"
lastmodified=new Date(fileob.lastModified())
lastmodifiedDate=lastmodified.format('dd/MM/yyyy')
formatter=new SimpleDateFormat("hh:mm:ss a")
lastmodifiedTime=formatter.format(lastmodified)
permission=getReadPermissions(fileob)+getWritePermissions(fileob)+getExecutePermissions(fileob)
filename=getRelativePath("E:\\\\temp\\\\recurssive\\\\",fileob.toString())
println "$filename, $md5sum, $lastmodifiedDate, $filesize, $permission, $lastmodifiedDate, $lastmodifiedTime "
}
catch(IOException io){
println io
}
catch(FileNotFoundException fne){
println fne
}
catch(Exception e){
println e
}
}
}
}
public def getReadPermissions(def file){
String temp="-"
if(file.canRead())temp="r"
return temp
}
public def getWritePermissions(def file){
String temp="-"
if(file.canWrite())temp="w"
return temp
}
public def getExecutePermissions(def file){
String temp="-"
if(file.canExecute())temp="x"
return temp
}
public def getRelativePath(def main, def file){""
return file.toString().replaceAll(main, "")
}
public static void main(String[] args) {
CheckSumCRC32 crc = new CheckSumCRC32();
crc.getFileListing("E:\\temp\\recurssive")
}
}
Output
release.zip, 25f995583144bebff729086ae6ec0eb2, 04/06/2012, 6301510b, rwx, 04/06/2012, 02:46:32 PM
file\check\release-1.0.zip, 3cc0f2b13778129c0cc41fb2fdc7a85f, 18/07/2012, 11786307b, rwx, 18/07/2012, 04:13:47 PM
file\Dedicated.mp3, 238f793f0b80e7eacf5fac31d23c65d4, 04/05/2010, 4650908b, rwx, 04/05/2010, 10:45:32 AM
but still I need a way to calculate hardlink, owner & group. I searched on the net it looks like java7 has this capability & I am stuck with java6. Any help?
Take a look at http://www.jonelo.de/java/jacksum/index.html - it is reported to provide cksum - compatible CRC32 checksums.
BTW, I tried using java.util.zip.CRC32 to calculate checksums, and it gives a different value than cksum does, so must use a slightly different algorithm.
EDIT: I tried jacksum, and it works, but you have to tell it to use the 'cksum' algorithm - apparently that is different from crc32, which jacksum also supports.
Well, you could run the command, then, for each line, run the cksum and append it to the line.
I did the following:
dir = "/home/will"
"ls -latr $dir".execute().in.eachLine { line ->
// let's omit the first line, which starts with "total"
if (line =~ /^total/) return
// for directories, we just print the line
if (line =~ /^d/)
{
println line
}
else
{
// for files, we split the line by one or more spaces and join
// the last pieces to form the filename (there must be a better
// way to do this)
def fileName = line.split(/ {1,}/)[8..-1].join("")
// now we get the first part of the cksum
def cksum = "cksum $dir/$fileName".execute().in.text.split(/ {1,}/)[0]
// concat the result to the original line and print it
println "$line $cksum"
}
}
Special attention to my "there must be a better way to do this".

Try/catch in JSP fails

A try/catch statement in my Java code (embedded in JSP) fails with the following error:
An error occurred at line: 26 in the jsp file: /template/tampabay/includes/omniture-footer.jsp
Syntax error on token "}", delete this token
I am unable to determine why the following code produces that error:
<%!
/*
* Map the DTI categories to the appropriate SiteCatalyst category
* structure.
*/
ArrayList<HashMap> mapDTIToSiteCatalystCategories( ArrayList<HashMap> dti_categories ) {
ArrayList<HashMap> site_catalyst_categories = new ArrayList<HashMap>();
ArrayList<Integer> dti_category_ids = new ArrayList<Integer>();
for ( int i = 0; i < 4; i++ ) {
try {
dti_category_ids.add( Integer.parseInt( (String)dti_categories.get( i ).get( "id" ) ) );
}
catch ( NumberFormatException e ) {
dti_category_ids.add( -1 );
}
}
// - Snip -
}
The error corresponds to the twelfth line above ( the closing brace of the try statement ). However, the code looks syntactically correct to me. Aside from breach of protocol by embedding a scriptlet in JSP, can you help point out the error?
I have tried using variations of this code (removing the for loop and declaring separate variables) but the error persists whenever I try to use the try/catch statement.
EDIT:
I uploaded the complete code listing here.
EDIT 2:
I also receive the following error:
An error occurred at line: 44 in the jsp file: /template/tampabay/includes/omniture-footer.jsp
Syntax error, insert "}" to complete Block
This error corresponds to the fourth line below:
"", "Baseball",
"", ""
);
break;
case 120: // Baseball: Minors
site_catalyst_categories = addElements(
dti_category_ids.get( 0 ), "Sports",
I did not include it before because I assumed it was caused by the earlier error. However, in light of the comments, it may be relevant.
According to my IDE and my visual inspection, all of the braces are properly paired. However, the compiler disagrees.
It looks like, on line 131/132, there's a missing close curly for the try statement.
case 131:
try {
switch ( dti_category_ids.get( 2 ) ) {
case 252: // Colleges: Bulls ..snip..
case 253: // Colleges: Bulls ..snip..
case 254: // Colleges: Bulls ..snip..
default: // Log all others to the "College" section
}
break;
// HERE ... THERE'S NO } TO CLOSE THE try {
catch ( NumberFormatException e ) {
// Log all others to the "College" section
site_catalyst_categories = addElements(
dti_category_ids.get( 0 ), "Sports",
"", "College",
"", "",
"", ""
);
}

Parse a task list

A file contains the following:
HPWAMain.exe 3876 Console 1 8,112 K
hpqwmiex.exe 3900 Services 0 6,256 K
WmiPrvSE.exe 3924 Services 0 8,576 K
jusched.exe 3960 Console 1 5,128 K
DivXUpdate.exe 3044 Console 1 16,160 K
WiFiMsg.exe 3984 Console 1 6,404 K
HpqToaster.exe 2236 Console 1 7,188 K
wmpnscfg.exe 3784 Console 1 6,536 K
wmpnetwk.exe 3732 Services 0 11,196 K
skypePM.exe 2040 Console 1 25,960 K
I want to get the process ID of the skypePM.exe. How is this possible in Java?
Any help is appreciated.
Algorithm
Open the file.
In a loop, read a line of text.
If the line of text starts with skypePM.exe then extract the number.
Repeat looping until all lines have been read from the file.
Close the file.
Implementation
import java.io.*;
public class T {
public static void main( String args[] ) throws Exception {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream( "tasklist.txt" ) ) );
String line;
while( (line = br.readLine()) != null ) {
if( line.startsWith( "skypePM.exe" ) ) {
line = line.substring( "skypePM.exe".length() );
int taskId = Integer.parseInt( (line.trim().split( " " ))[0] );
System.out.println( "Task Id: " + taskId );
}
}
br.close();
}
}
Alternate Implementation
If you have Cygwin and related tools installed, you could use:
cat tasklist.txt | grep skypePM.exe | awk '{ print $2; }'
To find the Process Id of the application SlypePM..
Open the file
now read lines one by one
find the line which contains SkypePM.exe in the beginning
In the line containing SkypePM.exe parse the line to read the numbers after the process name leaving the spaces.
You get process id of the process
It is all string operations.
Remember the format of the file should not change after you write the code.
If you really want to parse the output, you may need a different strategy. If your output file really is the result of a tasklist execution, then it should have some column headers at the top of it like:
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
I would use these, in particular the set of equal signs with spaces, to break any subsequent strings using a fixed-width column strategy. This way, you could have more flexibility in parsing the output if needed (i.e. maybe someone is looking for java.exe or wjava.exe). Do keep in mind the last column may not be padded with spaces all the way to the end.
I will say, in the strictest sense, the existing answers should work for just getting the PID.
Implementation in Java is not a good way. Shell or other script languages may help you a lot. Anyway, JAWK is a implementation of awk in Java, I think it may help you.

Categories