How to pass console arguments to application in eclipse? - java

I have the following line in a batch file.
java Client "127.0.0.1" 9876
It contains the name of my java class and two arguments. My application requires these arguments to run properly.
Is there any way to pass these arguments when running the application in eclipse? It would make debugging a lot easier. Of course I could resolve the problem by using the values of the arguments in the code but I'm curious.

Instead of just hitting the "Run" icon, select the dropdown box next to it, and choose "Run Configurations". Find your application (or create a Run Configuration for it) and put the command line arguments in the "Arguments" tab. See the docs for more information. It should look like this:

See the run configurations. You can specify arguments. You can even prompt the user for arguments, along with defaults:
${string_prompt:host:127.0.0.1} ${string_prompt:port:9876}
The first prompt is host, with default value 127.0.0.1 filled in. Second pop-up has the prmpt port, with 9876 filled in

Right-click on your project.
Go to Debug As > Debug Configurations or Run As > Run Configurations.
Click the tab that says Arguments.
Enter in your Program Arguments
Click Apply or Debug

Want to add something like, how to add multiple parameters.
Right-click on your project.
Debug > Debug Configurations
Go to Arguments tab.
Enter in your Program Arguments, each separated by a new line. (e.g 3 arguments in attached image)
Click Apply or Debug
Hope it helps.

From "Run" go to debug/run configurations. Click the tab called "Arguments". You can give the program arguments there.

Run configurations > Arguments tab. Just put "127.0.0.1" 9876 in the program arguments.

Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run
Ensure that the right project name and it's main method are selected under "the Main" tab under run configurations

this work for me, in public static void main method.
public static void main(String argv[]) throws Exception {
int port_com = 2;
boolean debugMode = true;
int socket = 6789;
HasarMain hasarMain = new HasarMain();
// Check if a command line argument exists
if(argv.length != 3){
System.out.println("Missing, Port - socket - debugMode!");
System.exit(0);
}
port_com = Integer.parseInt(argv[0]);
socket = Integer.parseInt(argv[1]);
debugMode = Boolean.parseBoolean(argv[2]);
Run-> Run Configurations->Arguments->Enter your arguments separated by tab->
${string_prompt:argv:"2" "6789" "true"}

Related

Possibility to disable the GUI?

I made a Java program that you can run :
1 - Only with the GUI by launching the .jar .
2 - With the GUI and a console by launching a .bat .
java -jar "app.jar"
PAUSE
But now I would like to add the possibility to launch it ONLY with the console, that means without the GUI, I searched but didn't found how to do that.
I understand your question like: the application could work console-only, but it starts the ui always.
In that sense, look into you main method /class and simply check for the command line args. Maybe you simply add some -nogui parameter which you then use to put a condition around the launching of any gui components.
And given your comment: you have to compare your args like:
.... void main(String args[]) {
for (String arg : args) {
if (arg.equals(...
See here for more details regarding command line options.

Specify Java command line options after jar execution

In an effort to make my app more OSX friendly, I am trying to set the dock name of my program to something like MyApp instead of a fully qualified class name (the default), such as myproject.mypackage.mysubpackage.myclass. Obviously, the first is much more appealing.
To do this, I use the OSX -Xdock:name command as a command line option when executing my .jar file. So to execute it, the command might look something like java -Xdock:name=MyApp -jar /mypath/myjar.jar. This works perfectly and sets the .jar's dock name to MyApp. But the issue is that this .jar will never be executed via command line and will be a double-clicked runnable .jar with a GUI display.
The only way I have thought of to set this command line option programmatically is to have a second class execute the class that actually starts the program. So something like this:
public class AppStarter {
public static void main(String[] args) {
String cmd = "java -Xdock:name=MyApp -cp myproject/mypackage/AppBuilder";
try {
Runtime runtime = Runtime.getRuntime();
runtime.exec(cmd);
} catch(IOException ex) {
//Display error message
}
}
}
public class AppBuilder {
public static void main(String[] args) {
//Start actual program and build GUI display
}
}
So here, AppStarter sets the command line options for AppBuilder, which when executed, has the dock name MyApp. The problem I see with this is that it is very tightly coupled. If for some reason the command line is inaccessible on the device or some IOException keeps getting thrown, literally nothing will happen with the program and it will be dead. There would be no way for the average computer user to recover from this.
So I'm wondering if it is possible to perhaps set these command line options after the .jar has already started executing. The old way to programmatically set the app's name has been ineffective for several OSX updates, so I'm stuck with only this command line option. Thanks for any advice.
Once the java command is executed, the command line arguments are parsed and set for the running JVM. You cannot change it any more.
This is usually handled by execution scripts (bash, etc.). If you cannot use them, you can use your approach, but the biggest disadvantage is that it will be running in a separate process.

How to create scheduler to run my script every night at 12.00- Selenium WebDriver

Currently working on Selenium WebDriver and using Java. I have a project called*Test*.
In that Project i have many Java Programs such as Login.java, Testing1.java etc.,.
The scenario is i want to run all my scripts daily morning at 12.00 a.m. Is there any possibility to create a scheduler to run my scripts automatically.
Create an testng.xml file say name as testsuite.xml.
Now follow below 2 steps:
Step 1: Create an batch file for scheduler:
use below code - modify it and paste in notepad. save the notepad in working directory as"run.bat"
set ProjectPath=C:\Selenium\Selenium_tests\DemoProject
echo %ProjectPath%
set classpath=%ProjectPath%\bin;%ProjectPath%\Lib\*
echo %classpath%
java org.testng.TestNG %ProjectPath%\testsuite.xml
a) First line is for setting project path .
b) second line is for verifying that path is set or not.
c) third
line is for setting classpath - lib folder contain all the jar
file added to project build path
d) fourth line is for verifying
whether classpath is set or not
e) fifth line is for executing
xml file having details of all test.
Step 2:
Go to control panel.
Administrative tool.
Task scheduler and create a task which will trigger run.bat file at the time you want.
It will work.
check with quartz scheduler.. http://quartz-scheduler.org/
I am currently working on a similar project where I have to check different web applications for their availability every ~5 minutes and report any errors via mail. I am also using TestNG ans the WebDriver together. I solved my "scheduling problem" by using the TimerTask class.
Here's a short code example: (Find more code examples here)
import java.util.Timer;
import java.util.TimerTask;
public class KeepMeAwake {
*
* #param args
*/
public static void main(String[] args) {
TimerTask action = new TimerTask() {
public void run() {
Beep b = Beep.getInstance();
b.beep();
}
};
Timer caretaker = new Timer();
caretaker.schedule(action, 1000, 5000);
}
}
Since it implements Runnable, you can run multiple threads with it.
Hope that helps.
If you have questions how to integrate it with your TestNG set up, just shoot.
Follow the above steps and in windows scheduler do the steps :
Creating .bat file steps
Task Scheduler in Windows > Create new Task>
'Action' settings - "Start in (Optional)" option.
Go the task properties --> Action tab --> Edit --> Fill up as below:
Action: Start a program
Program/script: path to your batch script e.g. C:\Users\beruk\bodo.bat
Add arguments (optional): <if necessary - depending on your script>
Start in (optional): Put the full path to your batch script location e.g. C:\Users\beruk\(Do not put quotes around Start In)
Then Click OK
It works for me. Good Luck!

Eclipse command line arguments

I understand how to run my application with command line arguments using the run configuration menu.
The problem I have is that no matter what I update these command line arguments to, eclipse does not reflect these updates when I execute the code.
so far I have set the arguments to:
test1.txt test2.txt dfs
and this will print:
args[0] = test1.txt
args[1] = test2.txt
args[2] = dfs
but if I update the arguments and re-run it, the arguments won't update
How can I "reset" the arguments and re-run the application using the updated arguments.
The above and below both function correctly and it was in fact eclipse that was causing me issues. The problem was resolved with a simple restart of eclipse.
Thanks all.
Click on Run -> Run Configurations
Click on Arguments tab
In Program Arguments section , Enter your arguments.
Click Apply
It is sure to work cause I tried it in mine right before I wrote this answer
There is a situation (bug) where modifying the Run -> Run Configurations arguments does not work, since the actual run configuration being executed is actually hidden from you.
So updating the visible one will not be reflected in your actual run.
Example:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class EclipseRunConfigurationTest {
#Test
public void test() {
assertEquals("foo", System.getProperty("runProperty"));
}
}
Run it - it will fail.
Modify the run configuration using the method specified by Little Child. add "-DrunProperty=foo" VM parameter
Run it again - it will pass
Debug it, then switch to the debug view,
RClick the Junit launch -> Edit Rerun EclipseRunConfigurationTest...
Change the VM parameter to "-DrunProperty=bar"
Apply and Debug - it will fail
Open the Run/Debug manager again
Note that 'Rerun EclipseRunConfigurationTest' is not listed.
Note that the VM parameter is still "-DrunProperty=foo"
No amount of changing it makes the slightest bit of difference.
I shall file a bug report.
The above was run on Eclipse Kepler running on Fedora 20.
A small update in the solution given by Little Child above, to make it work with arguments having spaces in them.
e.g. first argument - abc def
second argument - ghi
third argument - jkl mno pqrs
In Program Arguments, give them like this using double quotes
"abc def"
"ghi"
"jkl mno pqrs"
If you don't give spaces it will take abc as first argument and def as second argument and ghi as thrid argument and so on..
For Eclipse Neon Users
Step 1: Click Run -> Run Configurations
Step 2: Click on arguments Tab.
Step 3: insert required arguments in VM Arguments.
Step 4: Click Apply
Step 5: Click Run.

How to input a file in this code?

I am still a Java newbie and I have this code. I don't know how to pass the input file to the code. I am using Eclipse Juno.
public static void main(String[] args) {
In in = new In(args[0]); // input file
int N = in.readInt(); // N-by-N percolation system
// turn on animation mode
StdDraw.show(0);
// repeatedly read in sites to open and draw resulting system
Percolation perc = new Percolation(N);
draw(perc, N);
StdDraw.show(DELAY);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
perc.open(i, j);
draw(perc, N);
StdDraw.show(DELAY);
}
}
Whenever I run it I get this exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at PercolationVisualizer.main(PercolationVisualizer.java:42)
What might cause this exception? Could you please be patient with me and explain the process of how to call the input file in the code?
Refer to this guide for adding arguments to your program. Alternatively, you could specify the file name directly in the code instead of reading it from the args.
Basically, the guide instructs the user to go to the Run menu, then "Run..." (actually "Run Configurations..." in recent Eclipse versions), select the appropriate run configuration for the desired project, click the Arguments tab, and enter the arguments (such as file name) in the "Program arguments" section, separated by spaces.
For those using IntelliJ you can set the program arguments via Run->Edit Configuration. Look down about the middle of the window to locate the "Program Arguments" field. Then add the path to the test file and save.

Categories