This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 4 years ago.
How can we pass a batch variable as parameter to a Java class main method using command line? I want to pass the contents of a text file as an argument to a Java class using command line. for eg : Java -jar TestJar.jar %BATCH_VAR%
I have tried the below code and it doesnt seem to work :
echo "starting"
echo off
set keyvalue=^&Type TestDoc.txt
echo %keyvalue% /// This is printing the right value.
pause
java -jar ErrorUpdate.jar "%keyvalue%" //// This does not pass anything to the Java class :(
pause
I suspect that you may have a misconception about what value is stored in your variable. So let me clarify exactly what is going on in your batch file.
set keyvalue=^&Type TestDoc.txt
echo %keyvalue% /// This is printing the right value.
That is not printing the right value. What you have done is assigned the value &Type TestDoc.txt to the variable. When you then type echo %keyvalue%, this line gets expanded to the following line:
echo &Type TestDoc.txt
This is actually two separate commands. The first, echo, simply queries if the echo setting is currently on or off. The second command, Type TestDoc.txt, is then executed.
At no point does the variable keyvalue ever contain the contents of the file.
So when you have this line in your batch:
java -jar ErrorUpdate.jar "%keyvalue%"
It gets expanded to:
java -jar ErrorUpdate.jar "&Type TestDoc.txt"
This time, the & is enclosed in quotes, so it does not act as a statement separator, but instead is passed to your java class's main method. Your main method just sees the string "&Type TestDoc.txt" passed in as args[0].
If you want the java application to receive the full contents of the file, you need to make your java application read the contents itself.
I'm looking for a flexible/generic way to build up conditions using metadata stored in a Database and then validate incoming requests at runtime
against the conditions and concatenate value(s) if the condition is met.
My use case looks something like this:
1) A business user selects an operation from a UI i.e. (IF condition from a dropdown), then selects an appropraite field to evaluate i.e. ("language")
then selects a value for the condition i.e. "Java" followed by some values to concatenate i.e "Java 9" and "is coming soon!"
2) This metaData will get stored in a Database (lets say as a List for the moment) i.e ["language","Java","Java 9","is coming soon"]
When my application starts I want to build the appropriate concatenation conditions:
private String concatenateString(String condition, String conditionValue, String concatValue1, String concatValue2){
StringBuilder sb = new StringBuilder();
if (condition.equals(conditionValue)){
sb.append(concatValue1);
sb.append(concatValue2);
}
return sb.toString();
}
3) so at runtime when I receieve a request, i want to compare the values on my incoming request to the various conditions that got built at start up:
if language == "Java" then the output would look like => "Java 9 is coming soon"
While the above might work for 2 String concatenations, how can achieve the same for a variable number of conditions and concatenation values.
So you want user to create a program by selecting options from a GUI which will be stored in a DB. When the options are read back from the DB you want to parse this into a compileable program and run it?
Use StringBuilder to build a string of the code from the data gotten back from the DB, something like this:
"if (language == '"Java"') { doSomething() }" (you'll need to take care to escape strings inside your string if you are storing strings in the DB.
You can then use Compiler class to compile the string to a program which yo can run (all in runtime, google dynamically compiling c# at runtime).
However, you'll probably want to question why you are thinking of going down that route... I've been there before, dynamic compilation has a very narrow use case.
You could, for instance, create a Dictionary which maps selected languages to some output string and simply use this to get your output like:
Dictionary<string, string> langaugeOutputMap = new Dictionary<string, string>();
languageOutputMap.Put("Java", "Java9 is coming soon");
private string concatString(string: userChosenString) {
if (languageOutputMap.containsKey(userChosenString) {
return languageOutputMap.getValue(userChosenString);
}
return string.Empty()
}
If you then want to manage multiple conditions, you could have multiple Dictionaries for each condition type and enumerate them in a collection, iterate over them when given a variable sized set of conditions and make sure that all the conditions evaluate through the use of containsKey().
Also, you can use params to specify variable length function arguments like so:
public string manyArgs(params string[] stringArgs) {
}
Also, look at PredicateBuilder:
http://www.albahari.com/nutshell/predicatebuilder.aspx
I am working on a program that is supposed to take one required command line argument and one optional command line argument. The first argument is the name of an output file where data will be written to, and the second is a number that will be used to calculate the data to be written to the output file. If the user does not enter a number, then it should just use a default value to calculate the data. For example, if the user entered command line arguments "Foo.csv 1024" the program would use 1024 to calculate the data and write it to Foo.csv, but if the user only used the command line argument "Foo.csv" then the program would use a default value of 2048 to calculate the data and write it to Foo.csv. I am creating/running this program using the Intellij IDE. How would I do this? Any advice/suggestions would be much appreciated.
Your program seems to be simple, so the solution is also simple for this particular case. You can test how many arguments were passed to the program checking the argument args of your main function:
public static void main(String[] args){...}
args is an array that contains the arguments passed to your program. So if your program is called prog and you run it with prog Foo.csv 1024, then args will have:
args[0] = "Foo.csv";
args[1] = "1024";
With this, you know which arguments were passed to your program and by doing args.length, you can know how many they were. For the example above, args.length=2 If the user didn't indicate the last argument ("1024"), then you would have args.length=1 with the following in args:
args[0] = "Foo.csv";
So your program would be something like:
public static void main(String[] args){
//The default value you want
int number = 2048
if(args.length==2){
number = Integer.parseInt(args[1]);
}
//'number' will have the number the user specified or the default value (2048) if the user didn't specify a number
}
To supply arguments to your program you must run it on a console or some kind of terminal. Using IntelliJ (or any other IDE) it's also possible to run the program with arguments, but you specify those in the Run Settings.
If you want a more complex treatment of arguments, usually what you want is done by argument parsers. These are usually libraries that take you argv and help you reading arguments to your program. Among other things, these libraries usually support optional arguments, arguments supplied via flags, type checking of arguments, creating automatic help pages for your commands etc. Consider using an argument parser if your argument requirements are more complex or if you just want to give a professional touch to your program :)
For java i found this particular library: http://www.martiansoftware.com/jsap/doc/
I am trying to get the current foreground window title using JNA and Jython. My code is just a translation of a Java code to accomplish the same. Code in Java works - I have tested it - and was taken from here: https://stackoverflow.com/a/10315344/1522521
When I call GetLastError() I get 1400 code back, which is ERROR_INVALID_WINDOW_HANDLE - stating that the window handle is invalid. I am sure that window handle is correct, because I can successfully call GetWindowTextLength(); ShowWindow(handle, WinUser.SW_MINIMIZE); and ShowWindow(handle, WinUser.SW_MAXIMIZE); to get the length of the title (seems correct) and manipulate the window.
I have a hunch, that the problem is with how I use variable text as argument for GetWindowText(). According to JNA's Javadoc it suppose to be char[] buffer for JNA to copy the text. As I simply pass 'string' it may be incorrect. This is my code:
def get_current_window_text():
"""
Get current foreground window title.
"""
handle = User32.INSTANCE.GetForegroundWindow()
if User32.INSTANCE.IsWindowVisible(handle):
print "Text lenght:", User32.INSTANCE.GetWindowTextLength(handle)
max_length = 512
text = ''
result = User32.INSTANCE.GetWindowText(handle, text, max_length)
print "Copied text length:", result
if result:
print "Window text:", text
return result
else:
last_error_code = Kernel32.INSTANCE.GetLastError()
if last_error_code == Kernel32.ERROR_INVALID_WINDOW_HANDLE:
print "[ERROR] GetWindowText: Invalid Window handle!"
else:
print "[ERROR] Unknown error code:", last_error_code
else:
print "[ERROR] Current window is not visible"
My hunch was correct, the problems was with incorrect argument when calling GetWindowText(). It suppose to be char[] - not a Jython variable. This lead me to research more and find something I wasn't aware before - Java arrays in Jython. As stated in Jython documentation http://www.jython.org/archive/21/docs/jarray.html :
Many Java methods require Java array objects as arguments. The way that these arguments are used means that they must correspond to fixed-length, mutable sequences, sometimes of primitive data types. The PyArray class is added to support these Java arrays and instances of this class will be automatically returned from any Java method call that produces an array. In addition, the "jarray" module is provided to allow users of Jython to create these arrays themselves, primarily for the purpose of passing them to a Java method.
The documentation has the mapping table as well. The working code would be something like this:
import jarray
text_length = User32.INSTANCE.GetWindowTextLength(handle)
max_length = 512
text = jarray.zeros(text_length, 'c')
result = User32.INSTANCE.GetWindowText(handle, text, max_length)
print 'Copied text:', result
There are a lot of questions about null and in java.
What I am failing to grasp is what people mean by null is pointing to nothing or why to use null at all.
I can't understand the difference between
String thing = null;
and
String thing = "";
This question has detailed answers What is null in Java?, but I just can't wrap my head around it.
What am I missing?
languages I've studied (no expert)
Python, vb (vb.net), web programming (html, css, php, bit of js), sql
I should add, it is this answer https://stackoverflow.com/a/19697058/2776866 which prompted me to write this.
String str = null;
means a String reference, named str, not pointing to anything
String str = "";
means a String reference, named str, pointing to an actual String instance. And for that String instance, it is a zero-length String, but it is still an actual object.
Just a little update with some diagram which hopefully can help you visualize that:
assume I have
String nullStr = null;
String emptyStr = "";
String myStr = "ab";
What it conceptually is something look like:
// String nullStr = null;
nullStr ----------> X pointing to nothing
// String emptyStr = "";
+------------------+
emptyStr ---------> | String |
+------------------+
| length = 0 |
| content = [] |
+------------------+
// String myStr = "ab";
+------------------+
myStr ------------> | String |
+------------------+
| length = 2 |
| content = [ab] |
+------------------+
(of course the internal structure of the String object is not the real thing in Java, it is just for giving you an idea)
More edit for the rationale behind NULL:
In fact in some language they do not provide concept of NULL. Anyway, in Java (or similar language), Null means semantically different from "empty" object. Use String as an example, I may have a People class with a String preferedTitle attribute. A Null preferedTitle means there is NO preferred title for that people (so that we need to derive and show the title for it, maybe), while a preferedTitle being an empty string means there IS a preferred title, and that's showing nothing.
Btw, although a bit off topic: concept of Null is seen as problematic for some people (because all those extra handling it need etc). Hence some languages (e.g. Haskell) are using some other ways to handle the situation where we used to use Null.
String str is a reference to an object. That is, it's not an actual object, but a variable which can contain the address of an object. When you assign a value to str you are changing the address stored within and changing which object it addresses.
null is reference value which points to no object. It's about as close to nothing as you can get. If you assign null to a String reference (String str = null;), you cannot then invoke any method of String using that reference -- all attempts will result in NullPointerException.
"" is a character String which contains no characters -- zero length. It is still an object, though, and if you assign its address to your String reference variable (String str = "";) you can then take its length, compare it to another String, extract its hashCode, etc.
Java doesn't really expose pointers, instead it deals with references.
When you say
String thing = null;
You are saying that there is a reference (of type string) called thing, which isn't referencing anything.
When you say
String thing = ""
This is shorthand for,
String thing = new String("");
Now you have an actual object initialized and ready to be used. You told the compiler to create a string and now your "thing" references the new string.
If you want to know the length of your initialized string, you can go;
thing.length
Which is zero. The string exists, but is zero length.
Trying string.length on the null version causes a NullReferenceException, which is the compiler saying
"I tried to find out about the length of your string, but I couldn't find it!"
Practically speaking, null means "not available for calling methods". If an object is allowed to be null, you must always check it for null before calling method on it.
An attempt to call any method on a null object is unconditionally an error. In nearly all cases it's a programming error, too, because you are supposed to either
Ensure that a variable is always non-null, or
Check a variable that could legally be null before calling methods on it.
On the other hand, an empty object lets you call methods. For example, you can find the length of an empty string - it is zero. You could also iterate a string, pass it to methods that expect non-null strings, and so on.
To visualize this, consider a Boolean object instead of a String. Unlike the primitive boolean that has only two states, namely true ("yes") and false ("no"), the Boolean object has three states:
Yes
No
Don't know
This third "don't know" state corresponds to null. It's neither true nor false state. Your program can use this third state to its advantage - for example, you can use comparison to null to see if a value has been set, or set a value to null to "unset" its value.
In Java null and an empty String are two different things.
If an String is null then you can not access its methods as it will throw a NullPointerException, however if a String is "" then the String object is valid and you can access its methods.
For example
String a = null;
String b = "";
System.out.println (a.length()); // No Good
System.out.println (b.length()); // Prints 0
Let's compare this to Python. In Python, the equivalent to null is None.
>>> test = ""
>>> test1 = None
This is setting an empty string and a "null" string.
>>> test
''
>>> test1
None
In Python we can test nullity using is
>>> test is None
False
>>> test1 is None
True
We can test for empty strings using ==
>>> test == ""
True
>>> test1 == ""
False
null (like None) is the absence of a value.
Conceptually null is a special value which means that the variable points to an invalid object, so it doesn't refer to anything valid in the sense that you can't access its content (variables or methods).
You can see it as a sort of special condition which has been added to languages because it was useful to be able to have pointers that refer to nothing. But there is some discordance here, in fact some languages prevent the necessity of a null value by forcing you to have just inizialized (meaningful) values.
There is difference in your example, "" is a valid object: it's an empty string while null is not a valid object.
Although many object-oriented frameworks implement references with pointers, it is better to think of references not as "pointing to" objects, but rather as "identifying" them [personally, I like the term "object identifier" to describe references, since the term "reference" is somewhat overloaded in different contexts]. Although object identifiers are not human readable, one can imagine the system as giving each object an associated number starting at 1, and each class-type variable as either having an object number or a zero written on it. Since class-type variables and array slots default to holding zero, and there will never be a zeroth object, there's no danger that the default-valued variable of an uninitialized variable or array slot will identify a valid object.
I prefer using the concept of containers/boxes to understand this concept
Let's start with this
String thing = "";
Imagine you have a container/box where you can store any value as long as you put the value between double quote marks "", if you decide to just put the double quotation mark without a value inside the box there is absolutely nothing wrong with that and any time you open your box you still see something inside (The double quotation mark )
Now This big man over here called null
String thing = null;
In simple terms look at null as being absolutely nothing
What does all this mean?
When you open the first box you see the double quotation ""
When you open the second box you see nothing (it's just an empty box)