Java - Passing arguments as key value pairs during programm start alternative - java

I hope someone can help me with this one... It's kind of a rookie question, but unfortunately I'm kind of stuck right here.
Currently I'm starting my java application like (cmd):
Now this is the calling part after all the classpath stuff.
%JAVA_HOME%bin\java.exe -cp %CLASSPATH%;%SCRIPTROOT%jar* -XX:MaxPermSize=1024M view.Main C:\temp\MyDatabase c:\temp\MyFile.xml
First arg:
C:\temp\MyDatabase
Second arg:
C:\temp\MyFile.xml
public static void init(String[] args){
try {
mydatabase = args[0];
} catch (Exception ex) {
}
try {
myfile = args[1];
} catch (Exception ex) {
}
}
Now in this case the order of the arguments is relevant.
With only two arguments this might be just fine, but what am I supposed to do, if I have like 10 arguments and some of them were optional? That would be a problem, right?
What if I do something like this:
%JAVA_HOME%bin\java.exe -cp %CLASSPATH%;%SCRIPTROOT%jar* -XX:MaxPermSize=1024M view.Main database:/C:\temp\MyDatabase myfile:/c:\temp\MyFile.xml
Now within my code the order would not matter anymore, because I have like a "key-value pair" of arguments and the key identifies the actual "use" of value. This works, but it don't feels right.
Is there a better way of doing this?
Maybe like java.exe does it with -cp? If yes, how can I implement this?
Thank you.

You need java.util.Properties.
Pass them to java process adding -D:
java -jar my-app.jar -Dfile=C:\temp\MyFile.xml -Ddatabase=C:\temp\MyDatabase
Order now does not matter. Get you args inside with System.getProperties() static method, it also has its satellites System.getPropery(String key) and System.getPropery(String key, Object default).
For advanced options take a look at Apache Commons CLI and libs like such.

Related

Linux using a method from a jar file (Java Code)

I am trying to write a program that prints out a statement through Linux. The catch is that most of the statement must come from a method from a jar file. Basically. my code looks like this
public class identification {
public static void main(String[] args){ // Main method with print statement
System.out.print("I am " + person());
}
}
The person() method comes from the jar file. It should give something like "I am bob on a computer," but I can't quite figure out how to set up the CLASSPATH environment variable in the .bash_profile so it reads the method from the jar file. Any ideas? I am sure this is a simple task.
Thank you for your time.
use cp command to add a jar file
java -cp lib/myJar.jar myPackage.Program
also I believe you may need to import class where method person is in. I don't know how your hierarchy is so I can't help you with that.
You can add a jar to your classpath like this:
export CLASSPATH=$CLASSPATH:/path/to/your/myJar.jar

Packaging a jar with preconfigured command line arguments

I am wondering if there's a way to create a jar that includes some command line arguments in it, the arguments that are usually passed in the command line when one tries to start up the jar (these parameters are then passed on to the main function). Basically instead of starting my app with
java -jar myapp.jar "arg1" "arg2", I want to start my app with
java -jar myapp.jar
and have "arg1" and "arg2" passed to the main function.
The reason behind this is that I want to deploy this to different environments, and I want my jar to contain different parameters according to the environment it's being deployed at.
Maybe there's another way to achieve similar results ??
Cheers.
PS: Looking for a maven solution.
Edit: I'll add a complete example to make this a bit more clear:
Let's say I have 2 environments: "Production" and "Test". I want to run the jar in the same way no matter in what environment I deploy it. So I always want to run it with:
java -jar myapp.jar
But! In order for my 2 environments to run ok, I need the Production environment jar to start it's main method with an argument "prod" and I need the Test environment jar to start it's main method with an argument "test".
If I correctly understood your problem, in your main() you could define a simple logic to handle the case where you do not specify any input parameter; the logic could retrieve the desired values according to the correct platform/env.
As an example:
public class Test01
{
public static void main(String... aaa)
{
// Check input
if(aaa.length == 0) {
/* Insert logic to retrieve the value you want, depending on the platform/environment.
* A trivial example could be: */
aaa = new String[2];
aaa[0] = "First value";
aaa[1] = "Second value";
}
// Processing, e.g. print the 2 input values
System.out.println(aaa[0] + ", " + aaa[1]);
}
}
Fyi, I created a runnable jar using eclipse, and start the application by either
java -jar Test01.jar
or
java -jar Test01.jar arg1 arg2
Hope this helps!
One solution is to change main(String[] args) to get values from env var if they are not present in the passed arguments.
String user;
String password;
if(args.length < 2)
{
user = System.getenv("appUser");
password = System.getenv("appPassword");
} else {
user = args[0];
password = args[1];
}
You can also create another class with a main function that will call the real one.
public class CallerMyApp{
public void main(String[] args) {
String[] realArgs = {System.getenv("appUser"), System.getenv("appPassword")};
MyApp.main(realArgs);
}
}
Then to execute its something like
java -cp myapp.jar CallerMyApp

Argument option using JCommander

I'm new with JCommander and I'm trying to use it in my JAVA Command Line Application.
Fisrt thing I did is I've created my CommandLineArguments class.
Now, I'm trying to print options given with arguments in command line. But I think I'm missing something.
Here is my main class :
public static void main(String[] args) {
String[] argv={"-h","host"};
CommandLineArguments arguments=new CommandLineArguments();
JCommander commands= new JCommander(arguments);
try {
commands.parse(argv);
System.out.println(commands.getParsedCommand());
} catch (Exception e) {
System.out.println(e.getMessage());
commands.usage();
}
}
Once I run this class, I got : null as output. Seems like getParsedCommand() is not used as it should.
Can someone tell me how to use JCOmmmander methods correctly so I can see options given with arguments?
What I'm trying to do here is, once the user runs java -jar myApp.jar -port portNumber -h hostname -d database -c collection I wanna be able to get portNumber hostname database and collection value so I can establish a connexion and send queries.
Hope I was clear enough.
Ismail
You need to make a distinction between commands and parameters. In the example you give, you only need parameters.
The first chapter of the JCommander documentation provides a clear enough example of how to handle parameters. If your CommandLineArguments class is annotated as in the example, the parameter values should be correctly set in that class after calling parse(argv).
Commands are explained in a later chapter dealing with more complex command-line syntaxes.

Using command line Interface app as library

I want to create a GUI app in java for signing j2me app which is done by JadTool.jar but it is a Command Line Interface Apps. So I just want to use it as library and pass the parameters in program. How it can be done?
Check out Runtime. It will allow you to execute a command. You can use this to start your command line interface library.
Edit:
Ah, I didn't read care carefully earlier. If you're using a Java library starting a separate process is not the best solution.
Just reference the JadTool jar from your project. If the functionality you need isn't accessible in the library, edit the source and recompile. Make sure JadTool's license allows this.
If you're against editing the source (or not allowed) try using reflection to invoke the private run method you need.
A jar is just a library of classes, the fact that it can be run from the command line is caused by the presence of a main method in a class. As jadtool's source is available it's easy to see its very simple main:
public static void main(String[] args) {
int exitStatus = -1;
try {
new JadTool().run(args);
exitStatus = 0;
} catch (Exception e) {
System.err.println("\n" + e.getMessage() + "\n");
}
System.exit(exitStatus);
}
Unfortunately, that run() method is private, so calling it directly from another class won't work, leading to a reduced set of options:
#WilliamMorrison 's solution of going via Runtime - not really a library call, but it would work.
see Any way to Invoke a private method?

Adding parameters to Runtime.getRuntime()?

void restartWeb() {
try {
String[] command = new String[] {"webRestarter.exe" , ">>","webLog.log"};
Runtime.getRuntime().exec(command);
} catch (java.io.IOException err) {
webServer.logError(err.getMessage());
}
}
Why doesn't this work? How could I fix it so it does work like I want it to?
-- Executes webRestarter.exe with parameters >>webLog.log
So it'd spit out something like this:
webRestarter.exe>>webLog.log
You simply can't use pipes in a exec call. Pipes are a functionality of the shell and not of the operating system. So we have to call the shell executable and pass the command. Try this instead:
String[] command = new String[] {"cmd.exe", "/c", "start webRestarter.exe", ">>","webLog.log"};
Parameters are passed directly to the webRestarter.exe command. You can't use parameters to redirect standard output to a file, as this is usually done by your command line interpreter.
However, the exec() method returns a Process object, which you could use to retrieve standard output and write it to a file.
Sources:
http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec%28java.lang.String%29
http://download.oracle.com/javase/6/docs/api/java/lang/Process.html
If I'm not mistaken, pipes, redirects etc are a function of a shell. In this context, these are just arguments. You could handle this as simply as using cmd.exe with a /c switch as part of your command, I believe it'll handle this correctly, or handle the standard input/output yourself (though that's notoriously fraught with problems, I prefer something like commons-exec).
Just thought I'd mention two things that might be handy for working with Processes.
ProcessBuilder
is a good way to obtain a Process (in
code intended to run in a 1.5+ JRE).
It is recommended to carefully
read and implement all the
recommendations of When
Runtime.exec() won't.

Categories

Resources