Invoking Java main method with parameters from Eclipse - java

During development (and for debugging) it is very useful to run a Java class' public static void main(String[] argv) method directly from inside Eclipse (using the Run As context menu).
Is there a similarily quick way to specify command line parameters for the run?
What I do now is go to the "Run Dialog", click through the various settings to the tab where I can specify VM and program arguments and enter them there.
Too many steps, plus I do not want to mix the more permanent runtime configuration settings with the one-off invokation parameters.
What I want instead is to check a box somewhere (or have a separate menu item "Run as Java application with command line") and then be prompted for the commandline every time (with a nice history).

This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.
When selecting Run As..., go into the run configurations.
On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).
Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.

Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:
Run your class once as is.
Go to Run -> Run configurations...
From the lefthand list, select your class from the list under Java Application or by typing its name to filter box.
Select Arguments tab and write your arguments to Program arguments box. Just in case it isn't clear, they're whitespace-separated so "a b c" (without quotes) would mean you'd pass arguments a, b and c to your program.
Run your class again just like in step 1.
I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this.

If have spaces within your string argument, do the following:
Run > Run Configurations > Java Application > Arguments > Program arguments
Enclose your string argument with quotes
Separate each argument by space or new line

AFAIK there isn't a built-in mechanism in Eclipse for this.
The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.

I'm not sure what your uses are, but I find it convenient that usually I use no more than several command line parameters, so each of those scenarios gets one run configuration, and I just pick the one I want from the Run History.
The feature you are suggesting seems a bit of an overkill, IMO.

Another idea:
Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)).
So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...
Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...

Related

Call java program from Node.js application

From what I read, there are a couple of ways to run java files in a node.js application. One way is to spawn a child process: (the java code is packaged with dependencies in an executable jar.)
var exec = require('child_process').exec, child;
child = exec('java -jar file.jar arg1 arg2',
function (error, stdout, stderr){
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null){
console.log('exec error: ' + error);
}
});
The other way is to use the java - npm module (link), a wrapper over JNI (this will let me create objects, set and get attributes, run methods).
In a production environment, when I want my node.js (Express) server to call a java program (it just saves an image to the local directory), please advise me on which would be the better way to accomplish this (in terms of best practices). Also, there is a long list of arguments that I need to pass to the main class and doing that on the command line is a bit of a struggle. Should I make the java program read from an input file instead?
1) If you use exec, you will run an entire program, whereas if you use a JNI interface, you'll be able to directly interact with the libraries and classes in the jar and do things like call a single function or create an instance of a class. However, if you don't need anything like that, I think using exec is far simpler and will also run faster. Sounds like you just want to run the Java application as a standalone process, and just log whether the application finished successfully or with errors. I'd say it's probably better to just use exec for that. Executing a child process this way is also far better for debugging, debugging JNI errors can be very difficult sometimes.
2) As for whether or not to read arguments from a file, yes, it's usually better to read from some sort of file as opposed to passing in arguments directly. It's less prone to human error (ie. typing in arguments every time), and far more configurable. If someone like a QA engineer only needs to edit a config file to swap out options, they don't need to understand your entire codebase to test it. Personally I use config files for every Java program I write.
You can use deployment toolkit and run the jar through jnlp. https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/deployment_toolkit.html
Advantage of running jars through jnlp is the ability to pass parameters from javascript to your jar. In this way you can dynamically customize your java program.
For this kind of problem you'd want to approach it in the following way:
Is there a decent way to run processes with arguments in my language/framework
Is there a decent way to deal with the programs output?
From experience, a decent way to deal with arguments in a process is to pass them as an (string) array. This is advantageous in that you do not have to resort to unnecessary string interpolation and manipulation. It is also more readable too which is a plus in this problem setting.
A decent way to deal with output is to use a listener/event based model. This way, you respond appropriately to the events instead of having if blocks for stderr and stdout. Again, this makes things readable and let's you handle output in a more maintainable manner.
If you go a bit further into this, you will also have to solve a problem of how to inject environment variables into your target program. As an example, you might want to run the java with a debugger or with less memory in the future, so your solution would also need to cater for this.
This is just one way of solving this kind of problem. If node is your platform, then have a look at Child Process which supports all of these techniques.
We can run the whole java project by making .jar file of it and run it using the command in the shell and run that shell file. In order to run java code from nodejs project as we know project could be a mix of java, js modules.
Call exec() function in node to create a child process to execute the shell file having a command to run .sh file and can also pass some argument in it from use.eg;
let fileName = 'someFile.txt';
let userName = 'Charlie Angle';
exec(`sh run.sh --context_param
paramFilePath="./storage/${fileName}" --context_param userName="${userName}"`, (error, stdout, stderr) => {// Some code based on execution of above command})
You can simply call a java command , with classpath & arguments, using module node-java-caller, it embeds the call to spawn and will also automatically install java if not present on the system
https://github.com/nvuillam/node-java-caller

Moving static code analysis from a separate process to an Eclipse plug-in

I am currently working on an Eclipse plug-in for a static code analyzer. The analyzer is written in Java. Until now, the Eclipse plug-in used an own launch configuration type as well as a subclass of JavaLaunchDelegate to execute the code analyzer in a separate process. The Eclipse plug-in and the code analyzer communicated via stdin and stdout of the new process. It was quite ugly :-P
Now, we aim to clean this up. First, we converted the code analyzer to be not only a jar file, but also an Eclipse plug-in. Second, we replaced the stdio based communication by a proper Java interface: The code analyzer offers an API to the Eclipse plug-in. This all works fine.
However, the Eclipse plug-in still uses its own launch configuration type with its subclass of JavaLaunchDelegate to run the analyses. This means, since the code analyzer itself is now an Eclipse plug-in, the analysis is done in the same process. However, the Eclipse plug-in still launches the extra process with the code analyzer without using it.
Question
What do we still need from the old setup?
I am quite sure, we can convert the JavaLaunchDelegate to a simple LaunchConfigurationDelegate. This should prevent the Eclipse plug-in from launching the useless process.
Next, in the plugin.xml, we declare the own launch configuration type like so:
<extension
point="org.eclipse.debug.core.launchConfigurationTypes">
<launchConfigurationType
delegate="com.example.LaunchDelegate"
id="com.example.launch.config"
modes="run,debug"
name="Launch"
sourceLocatorId="org.eclipse.jdt.launching.sourceLocator.JavaSourceLookupDirector"
sourcePathComputerId="org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer">
</launchConfigurationType>
</extension>
Here, I am not sure whether we can remove the sourceLocatorId and sourcePathComputerId attributes: The launch configuration still launches Java code, but it is no longer launched in a separate process. Do these attributes make sense when they are used with a launch delegate that is not a JavaLaunchDelegate?
Finally, I don't know whether it is a good idea to still use a launch configuration at all. This is because we don't really launch an extra process, but an operation that is executed in the Eclipse process. Is it appropriate to use a launch configuration for this use case? Also, we currently use a subclass of the AbstractLaunchConfigurationTabGroup to configure the parameters of the analysis. Is there an alternative to the own launch configuration type that allows us to launch an operation in the Eclipse process and to provide parameters via a GUI for this operation?
Question Summary
Can we replace the JavaLaunchDelegate with a simple LaunchConfigurationDelegate?
Can we remove the sourceLocatorId and sourcePathComputerId attributes from the own launch configuration type declaration?
Is it appropriate to use a launch configuration to execute a static code analysis that runs in the Eclipse process?
If it is not, is there an alternative to the own launch configuration type that allows us to launch an operation in the Eclipse process and to provide parameters via a GUI for this operation?
We now use a simple LaunchConfigurationDelegate and we removed the sourceLocatorId and sourcePathComputerId attributes from the own launch configuration type declaration. This does indeed prevent the unnecessary process. Also, we did not notice any issues with the debugging. Thus, I consider question 1 and 2 as solved. Regarding question 3 and 4: The simple launch configuration now works fine for us, so we stick with it.

Find all instances of a class while debugging in Eclipse

I was wondering if the way Java/JVM works means debugging tools like Eclipse can show me a list of all instances of a given class? I suppose one could write some reflection code but I don't want to break execution at the same place every time... rather I;d like to break execution and bring up a list of all MyClass123 objects in a debug window.
Is this even possible? Is it provided in Eclipse or any plugin?
Yes, it's possible in the standard eclipse debugger. See here. While debugging, right-click on a variable entry in the 'Variables View' and then click on 'All Instances':
This will open a list like this:
You may want to instatall Eclipse Test & Performance Tools Platform plugin in your application and perform MemoryAnalysis. This gives you details around all different objects in memory and their references.
You will not need to put any breakpoint in the code. It will gather the required data on its own.

How to run multiple consoles from one class?

I have three classes which all make different works but I need to run them together. When I run all of them in one class I just get one console and cant change this console. What I want is to run them in one class and see each console . How can I do that ?
To be more clear ,
when I run first class, I get --> console 1
when I run secondclass, I get --> console 2
when I run third class, I get --> console 3
but instead of doing it seperatly, when I do it;
Run 1,2,3 ----> I get console 1
The thing I want is
Run 1,2,3 ----> I get console 1, 2 and 3
Thank you all
EDIT 1 : Sorry for not-enough info I use Eclipse to run my code, and I am talking about Eclipse console.
A certain way to do it would be to open 3 separate terminals and do java Class<n> (without .class extension) in each terminal.
I don't think you can do it in Eclipse with a single workspace (it could be possible though ...), one way to do it is to create separate projects for each class and open each project in a separate workspace simultaneously, but this is too much work IMO. 1. is probably the easiest/fastest way to do it.
You have to invoke java command separately for each class in different console. With one java invocation, i think, there will be only one console associated.
Obscure question. But it seems that you need separate console outputs for your classes. I don't think it is possible. That is operating system restriction. If operating system supported that you could somehow create additional consoles.
As a solution you can give your classes PrintStream object which they will use to output data.
You could run a server-like application which would accept messages and then display them in the console. The class would start each of your other main methods in new Threads, and then wait indefinitely for messages, ending when the other three threads close.
INMO, if your underlying OS is Windows then you need to handle console and use JNA or JNI that allows you to call win32APIs from java, but if your underlying OS is Unix-like then you need to find a way to communicate with syscall APIs in java. by calling native APIs you can call native console and if you know how to create a native console then you can create multiple instances of native console.

How to add arguments to a Java application

I want to add arguments to my Java application before i run it. I want to be able do somthing like:
public static void main(String args[])
{
String document = args[0];
new DocumentViewer(document);
}
I want to do somthing like when you click on a Word document it opens up the document by itself, you dont have to open word and then click open. Does anyone know how to add arguments? All relevant answers are appriciated!
java YourClass yourfile.xtx
To associate your program with a file extension, so that it is automatically called, you have to configure your Desktop Environment (Linux) or Windows (Windows) (I don't know for OSX).
I don't have it in my head, but as far as I remember, you combine the extension, xtx for example, with a starting command, like
java -cp C:\Programs\yourlibs\your.jar YourClass %1%
If you have or can have more arguments (mark multiple files, and drag them to your starter) you can, afaik, go up to %9%:
java -cp C:\Programs\yourlibs\your.jar YourClass %1% %2% %3%
%1% is for the first param and so on.
There is nothing you can do from Java, except catching those parameter, what you already do.
On Linux, your starter is very similar:
java -cp /usr/local/lib/your.jar YourClass $1 $2 $3
If you're launching your app from the command line you could just pass the arguments separated by a blank space right after the application name like this:
java name_app arg1 arg2 etc...
//the code above passes to name_app 3 strings: "arg1", "arg2", and "etc..."
Not sure about what you want to do with Word but I hope this was helpful.
Java Web Start
..JWS provides many appealing features including, but not limited to, splash screens, desktop integration, file associations, automatic update (including lazy downloads and programmatic control of updates), partitioning of natives & other resource downloads by platform, architecture or Java version, configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.), easy management of common resources using extensions..
For a demo. of the file associations, see the JNLP API file service demo.
The application that you are trying to create is a GUI application while the arguments that main method take is meant for Command Line interface input.
Where string [] args is the String array that can story many arguments from CLI. Of course you can implement the feature with a mix of CLI and GUI program but then you will be limited to launch your application from CLI, which doesn't make sense.
Another workaround can be. Create a demo frame that appears in the beginning have some textboxes and let users enter what you want to take as an argument, pass that value in the method, or data types you like. In that way you can have a full blown GUI application.

Categories