Dll function returns 1 - java

Im using Java (JNA) to use a function in a third party .dll file. The functions I'm calling are returing the integer value 1.
After reading, I've discovered that this return value is traditionally 0 if everything runs correctly.
Was wondering if this is always the case or if theres any way to determine what it should be?
In the .h file bundled with the .dll it has the comment
// rc: EXIT_SUCCESS means NO ERROR
After the function.

Check actual dll documentation, there should be the way to tell what's wrong.
If nothing helps try calling GetLastError() WinAPI - some meaningful error code might be reported.
Also try to look at debug output during function call - some traces might be there even in Release build

Yes, zero typically means success in the C/C++ world.
In the days before exception handling you had to have a way to indicate failure and the return value was pretty much reserved for failure/success. As for what '1' means, you will have to look in the header of the dll for the function that is returning '1' and see if they included anything about error conditions. There are too many possibilities without seeing the code or knowing more about the dll to provide any easy answers.
What is the name of the function? What is it attempting to do? What can you do if you know the function failed?

Related

How to set a hostname in a jsonnet file?

I am trying to get the hang of jsonnet files. So far all I have is hard-coded values but what if I wanted to get the hostname for a Java application. For example in Java I would just do:
String hostName = System.getenv("HOSTNAME");
But obviously I can't just have a key-value pair like the following JSON in a jsonnet file.
{name: "hostname", value:System.getenv("HOSTNAME")}
I need a bit of help in understanding how I can do this.
I have looked up std.extvar(x) but the examples I look at just arent clear to me for whatever reason. Is this method relevant? Otherwise, I'm not really sure.
Jsonnet requires all parameters to be passed explicitly. To use a hostname in your Jsonnet code, you need to pass it to the interpreter. For example you can run it as follows:
❯ jsonnet --ext-str "HOSTNAME=$HOST" foo.jsonnet
foo.jsonnet:
std.extVar('HOSTNAME')
You can also use top-level-arguments mechanism to a similar effect (top-level-arguments are passed as function arguments to the evaluated script.
Please see: https://jsonnet.org/learning/tutorial.html#parameterize-entire-config for more in-depth explanation of these features.
FYI not being able to just grab any environment variable or access the system directly is very much by design. The result of Jsonnet evaluation depends only on the code and explicitly passed parameters. This has a lot of benefits, such as the following:
You can easily evaluate on another machine, even on a completely different platform and get exactly the same result.
You are never locked in to configuration on any particular machine – you can always pass any parameters on any machine (very useful for development and debugging).
Avoiding surprises – the evaluation won't break one day, because some random aspect of local configuration changed and some deep part of the code happens to depend on it – all parameters are accounted for.

Catching java exception in Jython

I have an exception I'm trying to catch whenever my VNC connection is killed (whenever I restart my VM) and I'm trying to ignore it to continue my Jython script. I'm not sure how to write a try catch statement to catch the exception since it's originating from Java. This is for a sikuliX script.
Exception in thread "Thread-7" com.tigervnc.rdr.EndOfStream: EndOfStream
at com.tigervnc.rdr.FdInStream.readWithTimeoutOrCallback(FdInStream.java:192)
at com.tigervnc.rdr.FdInStream.overrun(FdInStream.java:142)
at com.tigervnc.rdr.InStream.check(InStream.java:37)
at com.tigervnc.rdr.InStream.check(InStream.java:44)
at com.tigervnc.rdr.InStream.check(InStream.java:45)
at com.tigervnc.rdr.InStream.readS8(InStream.java:55)
at com.tigervnc.rdr.InStream.readU8(InStream.java:64)
at com.tigervnc.rfb.CMsgReaderV3.readMsg(CMsgReaderV3.java:50)
at com.tigervnc.rfb.CConnection.processMsg(CConnection.java:67)
at org.sikuli.vnc.VNCClient.processMessages(VNCClient.java:246)
at org.sikuli.vnc.VNCScreen$1.run(VNCScreen.java:82)
at java.lang.Thread.run(Unknown Source)
#abarnert You really saved my day. I have encountered the same problem as OP posted. The jython code is as following:
################################################################
# CONFIG DEFINITIONS
################################################################
#GOOD_IMAGE_URL = "http://192.168.1.15/11111111.png"
BAD_IMAGE_URL = "http://192.168.1.15/111111112222.png"
def exceptionDemo(urlPath):
try:
print "exceptionDemo is starting"
myImg = imageio.ImageIO.read(URL(urlPath))
if myImg is None:
print "Img is None"
else:
print "Img is OK"
return myImg
#except Exception, err:
except java.lang.Exception as err:
print "Exception is here"
print err
finally:
print "Finally is here"
the purpose of this code is to download the image file specified by urlPath. when the ulrPath is bad(in this case, the 111111112222.png does not exist.), I would like to catch the exception in order to handle this issue properly.
If I simply use the normal "except Exception, err" to catch the exception, the program will just abort without any information. The print statements in except and finally section are supposed to execute, however, that didn't happen. What I get is nothing after seeing "exceptionDemo is starting".
I spent days on dealing with this problem, searching on google again and again, leaving no stone unturned. After days of investigation, I get the idea that there are two sorts of exceptions when you programming in jython, one is python exception, the other is java exception. The reason for this problem is that either jython or SikuliX in this case, has suppressed the java throwables. I am not very familiar with jython, so it's just my guess and it has not been verified(I am more familiar with native Python and Java).
At first, I doubt it's ImageIO - the native java package's problem. I wrote a simple java demo to test ImageIO by giving the bad image url, it worked great, a nice "javax.imageio.IIOException: Can't get input stream from URL" had been thrown out. Then, I know that my guess is right. The java exception somehow did not well handled in jython or SikuliX. The point here is that even if this is the root cause, I still need a simple and elegent way to deal with this problem. I tried some other workarounds, but nothing is as good as I've expected. The essential part of this problem is not about downloading the image, it's about catching the exception.
It was not until I simply replace "except Exception, err“ with "except java.lang.Exception as err" that the code is working like a charm. I got all the printouts that I expected.
Your posts really saved my day. Good job and many thanks.
The following references are very helpful in my investigation:
javax.ImageIO methods fail silently
trap exceptions comprehensively in Jython
https://www.jython.org/jythonbook/en/1.0/ExceptionHandlingDebug.html
Finally, If there were any tips I would like to offer to people who find this post, it should be "STAY AWAY FROM THIS KIND OF HALF-BAKED SHODDY HYBRID LANGUAGE", You will get neither the expediency of Python, nor the robustness of Java, the only thing that you eventually will get is a big waste of your time.
=================================================================
Update on 2019-08-02:
As a follow-up of this post, I offer you a "buy one get more free" deal. It contains a heck of surprise brought you by Jython and Sikuli X.
1, DO NOT USE ANYTHING DEPENDS ON Netty in Jython. This includes httplib and urllib2, etc. It will fail if you try to GET/POST something in a loop, use Requests or java.net instead.
for details, please refer to this post: Why does this Jython loop fail after a single run?
2, DO NOT USE type() function in Sikuli X. This function is normally used in python to determine the type of an object, however, Sikuli X use it to mimic the keyboard input function. If you insist, you should import builtin first, then call it like this:
# -*- encoding: utf-8 -*-
import __builtin__
if __name__ == '__main__':
a=10
print __builtin__.type(a)
for details, please refer to these:
How to check variable type using “type” function in Sikuli
https://answers.launchpad.net/sikuli/+question/239574
These are some pitfalls that I have experienced in jython and Sikuli X, if you have to work with these two things, good luck and wish you have fun.
As explained in Exception Handling and Debugging, you handle Java exceptions in Jython the same way you handle Python exceptions:
As stated previously, it is a common practice in Jython to handle Java exceptions. Oftentimes we have a Java class that throws exceptions, and these can be handled or displayed in Jython just the same way as handling Python exceptions.
A Java exception is, as far as your code is concerned, just an instance of some Exception subclass.
Of course that subclass happens to live in, e.g., java.lang instead of builtins or another stdlib module, and it will (almost?) always have java.lang.Exception as an intermediate ancestor before getting all the way back to Exception, but generally, you don't care about that.
So, wherever you're calling the Java code that's throwing this exception… just put a try: / except Exception as e: or except java.lang.Exception as e: or more specific type, the same way you would when calling Python code.

Call Minizinc model from Java

How to call a Minizinc model from a Java program with arrays as passed-on parameters?
Is there any special command for doing this?
I frequently do the same but in python. There is probably not any module or extension that can integrate the call in any convenient way but it is quite easy to just call another program.
Since I have not tried it in Java, I will let another stack overflow post guide you: Execute external program in java.
You can pass the parameters either as -D "var_int_name=10;var_int_array=[1,2,3];" or you can supply a data file as the last argument in the call to MiniZinc.
A general tip is to make the output from your MiniZinc model very easy to recognise and parse since many solvers print extra stuff and not just the solution. For example does MiniZinc itself print ---------- between solution. Surround the answer with & or any other sign that is easy to find and parse by a computer. You might also want to verify that you indeed got a solution back.

Returning values from a java program back to a batch file

In the good old days of C you had int main(...) as the entry function and you could call the executable from a batch file and check %errorlevel% in that batch file which would contain the return value.
In java I compile my java application to something.jar and mark a function like public static void main(String[] rawArgs) as the entry point. I then call java -jar something.jar from the batch file. I can even append command line arguments if I want to.
But now I can't check %errorlevel% since my main function is returning a void.
I suppose this is all perfectly logical given that everything is running in a virtual machine and that is the actual executable rather than something.jar.
I can use System.exit(...) to achieve my original aim.
My question is this: Is there a better way of doing this? Killing off the virtual machine seem heavy handed. What if the code runs server side? Am I missing a cute function like Runtime.SetErrorLevel which does what I want?
System.exit() is the correct way to do what you want - a process can only return an error condition when it exits anyway, so what would be the point in specifying that code anywhere else?
Simply use System.exit() with a non zero parameter to indicate the error level - there's no need to look for an alternative way. If you try to work around it you're just going to end up with horrible native hacks that aren't portable yet accomplish the same thing as System.exit().
Place a call to System.exit() just before the end of your main function.
Declare a native function in java, static native void SetErrorLevel(int level);, generate the JNI headers using javah.exe and implement the function in C which sets the %errorlevel% environment variable in your process.
Then terminate normally.

Faster or cleaner way to find out if a package is installed on Android

I know that I can either catch the NameNotFoundException from a call to PackageManager.getPackageInfo or loop through the PackageInfo list returned by PackageManager.getInstalledPackages to know whether a particular package is installed, but both of these seem either long winded or ugly. On my personal phone, I have more than 300 packages installed, so I'd hate to have to do that operation every time I need to check. And catching an exception as a means of performing application logic just makes me feel wrong all over. Am I missing the isPackageInstalled method somewhere, or do I just need to implement it myself using one of the above mentioned techniques? And if the latter, which would be considered the faster and less resource intensive option?
Since PackageManager.getInstalledPackages() returns a List, you don't need to loop through it manually. You can use List.contains() or List.containsAll() to accomplish the task in one line of code. Of course, this doesn't change the efficiency since both methods likely contain a loop themselves.
If using the API really bugs you then you might look into a hack involving the following
Bash shell expression that gets the PM list
Java Runtime expression
Java Pipes and buffers and streams
Java NIO
Java grep
So the bash expression would be :
pm list packages -f | sed 's/^package.//' | awk -F"=" ' { print $2" "$1 } ' | sort
and of list of references for handling stdout from the 'pm list' in a way that might wind up being faster...
PipedBuffers
NIO/grep
Runtime/streams
Handling a NameNotFoundExcepetion should not make you feel "wrong all over" IMHO. According to the documentation this exception will be thrown if the package does not exist since api level 1. Using try/catch statement is very similar to using an if/then statement to test for a null value.
In this case it should not be considered a workaround or a hack as you are using the documented and expected return value of an exception to determine if a package exists.
I would assume this method to be faster than iterating through the List returned by getInstalledPackages(). However, I don't know what steps android takes prior to returning a NameNotFoundExcepetion. This would make an interesting benchmark test.
I'm not aware of any other practical method to test for an installed package.
I wrote some benchmarks and tested catching the exception vs a few different ways of fetching the installed packages and looping through them. Here is my result
Calling PackageManager.getPackageInfo and catching the NameNotFoundException took between 1 and 4 ms in all cases whether the requested package was installed or not, and I made sure to also include cases where this was the first call to the PackageManager for a particular run of the app and as a subsequent call just in case the framework does any caching of this information per app launch.
Calling PackageManger.getPackageInfo took between 1 and 1.5 seconds in all cases as well.
Calling getPackageInfo and catching the exception to determine if the package isn't installed is by far the faster way to check.

Categories

Resources