switching between console mode and graphical mode - java

I just wanted to know if there is some way to switch between console mode and graphical mode. I am using java on swing.
I'd like to know if I can type something in the shell to go to a console mode, then type something to go back to the desktop. Or if I can press some key at boot time, or something.
The idea is to make my server run in console mode, but have desktop available when I want to easier make my tasks.

You can use java.awt.GraphicsEnvironment.isHeadless() to check whether the environment where your program is running supports GUIs or not:
public static void main(String[] args){
if (GraphicsEnvironment.isHeadless()){
// Run console mode
} else {
// Start in GUI mode
}
}
If I were you, though, I'd make this a command-line switch so you can use the console mode in graphic environments, too. For maximum convenience, this would be a non-mandatory option which defaults to some kind of "auto" option, which uses the isHeadless check, like:
public static void main(String[] args){
final List<String> arguments = Arrays.asList(args);
final int modeIndex = arguments.indexOf("-mode");
final String mode = modeIndex == -1 ? "auto" : argument.get(modeIndex);
if ("auto".equals(mode)) runAuto();
else if ("console".equals(mode)) runConsole();
else if ("gui".equals(mode)) runGui();
else System.err.println("Bad mode: " + mode);
}
private static void runGui(){ ... }
private static void runConsole(){ ... }
private static void runAuto(){
if (GraphicsEnvironment.isHeadless()) runConsole();
else runGui();
}
(TODO: Add error handling, remove magic string literals, etc.)
So, start your program with java YourMainClass or java YourMainClass -mode auto and it makes an educated guess whether you want GUI or console, use java YourMainClass -mode console to force console mode, or java YourMainClass -mode gui to force GUI mode.

You can divide the project in two: the server and the GUI. You can run your server as a service (Windows) o daemon (Linux) and when you want the GUI, you have to launch and operate with it.
It´s like applications as MlDonkey, Ettercap, etc.

You can pass parameters on the command line and examine them in main(String[] args). They'll end up in args. So the most simply way is to check for args.length > 0 && "-c".equals (args[0]) to tell the program to run in console mode and to open a UI otherwise.
Another option is to write two main() methods (in different classes) and use the right one.

In the program you can define commands to hide the GUI. Something like gui.setVisible(false) should do the trick, it hides the window referenced by gui and all elements of it.

You could create a command line command that starts a GUI wizard that enables you to easily create the components/ configuration you want, and then enable the GUI to pass the complicated instruction back into your single application thread. Whether it is useful to have the GUI component destroyed after you have used it, or just hidden, is a decision you will have to make, regarding how often you will be using the GUI component.

Related

Preventing java agents from attaching at runtime

Reposting this here as advised by security.stackexchange
How can I prevent Java Agents from attaching to my running java application at runtime?
I am able to prevent users from launching my application with a javaagent at startup by scanning the command line arguments:
List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments();
for(String arg : args)
{
if(arg.contains("-javaagent"))
{
System.out.println("Detected Java Agent: " + arg);
logIncident(0x01);
Runtime.getRuntime().exit(0);
}
}
However this does not prevent people from attaching at runtime visualvm style.
I heard that you can use the -XX:+DisableAttachMechanism flag to disable this, however when I tried to use jinfo -flag +DisableAttachMechanism <PID> I got an exception telling me that it is not possible to modify this argument at runtime.
Another possibility I considered was modifying the system security manager to disallow all AttachPermission's (I believe that this needs to be allowed for java agents to attach), but I'm not sure where to start.
Would really appreciate any guidance on how to implement the ideas Ive already come up with, as well as suggestions for any new ideas.
Edit:
I created a custom security manager to deny all AttachPermissions however it appears to not be triggered in the jar being attached to but rather the agent itself. Now I am looking to enable DisableAttachMechanism at runtime, but I cant seem to find any references to this in OpenJDK source?
Exit if this returns true:
private static boolean acceptsJavaAgentsAttachingToThisJvm() {
HotSpotDiagnosticMXBean vm = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
VMOption opt = vm.getVMOption("DisableAttachMechanism");
return "false".equals(opt.getValue()) || opt.isWriteable();
}
which should defend against casual usecases.

Debugging in Java - Eclipse [duplicate]

I want to change the logging level depending if I'm debbugging or not, but I can't find a code snippet to check if the application is running in debug mode.
I'm using eclipse to debug the application, so if the solution only works within Eclipse it will be fine.
Found the answer on how-to-find-out-if-debug-mode-is-enabled
boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().
getInputArguments().toString().contains("-agentlib:jdwp");
This will check if the Java Debug Wire Protocol agent is used.
You could modify the Debug Configuration. For example add a special VM argument only in the Debug Configuration. You can use System.getProperties() to read the supplied arguments.
Even better, modify the configurations (Run and Debug) to load a different logging configuration file. It isn't good if you need to write code to determine the logging level. This should only be a matter of configuration.
There is not an officially sanctioned way to reliably determine if any given JVM is in debug mode from inside the JVM itself, and relying on artifacts will just break your code some time in the future.
You will therefore need to introduce a methology yourself. Suggestions:
A system property.
An environment variable (shell variable like $HOME or %HOME%)
Ask the JVM about the physical location of a given resource - http://www.exampledepot.com/egs/java.lang/ClassOrigin.html - and based on it, make your decision (does the path contain the word "debug"? is it inside a jar or an unpacked class file? etc).
JNDI
The existance or content of a particular resource.
Have you tried add a vm argument in the eclipse run config?
Pass this as a VM Argument
-Ddebug=true
then you can do Boolean.getBoolean("debug") to check this.
If you are setting the debug level from your own program, may be a line like:
public static final boolean DEBUG_MODE = System.getProperty("java.vm.info", "").contains("sharing");
would do the trick.
Just tested it in eclipse3.5:
package test;
public class Test
{
/**
* #param args
*/
public static void main(String[] args)
{
System.out.println(System.getProperty("java.vm.info", ""));
}
}
will display:
mixed mode, sharing
if launched without debug
mixed mode
if executed with debug launcher
Joachim Sauer comments:
This is highly system depending.
I assume the "sharing" indicates that cross-VM class-sharing is active.
This is a very new feature and is only available on some platforms.
Furthermore there can be many possible reasons to en- or disable it, so I wouldn't use this for debug-mode detection.
(Note: I tested it with the latest jdk1.6b14. I leave this as a CW answer.)
Have a look here:
http://wiki.eclipse.org/FAQ_How_do_I_use_the_platform_debug_tracing_facility%3F
Moreover, I think you can't know if your app is run in debug mode. The only thing you can do is to pass an argument to your JVM when you debug.
Manu
If using socket (e.g. 9999) you can call netstat to check if connection was established:
Process p = new ProcessBuilder("netstat", "-n").start();
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
Then scan in stdout for 127.0.0.1:9999.*ESTABLISHED

Cannot send keystrokes to VM on hyper-V using JAVA

I have to send keystrokes to virtual machine. Task is repetitive(I have to do it 3-4 times a day), but can be easily simulated by sending keystrokes. Actually my VMs have only terminal window (linux based) with SSH session running.
I wrote a small java test program to send the keystrokes.
public class TestRobot1 {
static int keyInput[] = {
KeyEvent.VK_H, KeyEvent.VK_E,
KeyEvent.VK_L, KeyEvent.VK_L,
KeyEvent.VK_O, KeyEvent.VK_ENTER,
};
public static void main(String[] args) throws InterruptedException, AWTException {
Thread.sleep(5000);
Robot robot = new Robot();
for(int i = 0; i < keyInput.length; i++){
robot.keyPress(keyInput[i]);
robot.delay(10);
robot.keyRelease(keyInput[i]);
robot.delay(10);
}
}
}
This program runs successfully on Notepad, VM started in Oracle Virtual Box, and accessed through SSH Session. But it doesn't run when VM is started from hyper-V, though I can SSH to that, and then I can run the program.
I have to select the window, on which this should run, that's why I have included 5 sec wait, so that I can select the correct window in the time. I know that is not very good but, it's a test program.
I have not worked with hiper-v, but I worked with regular remote desktop. I however performed click that makes focus on window using the robot itself. Try this technique. For reference take a look on https://github.com/alexradzin/TypeToPaste
Here is the TypeToPaste site: https://sites.google.com/site/typetopaste/
I recommend to download this application and try it. If it works, examine its code. Otherwise I am sorry...
Please let me know how is it going anyway. I am very curious...

IntelliJ and getting user input

so I'm new to using IntelliJ and I've tried googling but to no avail.
I'm creating a simple java program that basically prints hello and gets the user input (name) and prints it... Just to get the ball rolling. Normal Hello World prints fine..
But as soon as I add any [args] in it just crashes? Is there a way I can type the input in?
public class Main {
public static void main(String[] args) {
System.out.println("Hello, " + args[0] + "!");
}
}
You need to provide at least 1 argument if you access args[0] otherwise you get ArrayIndexOutOfBoundsException.
Why ? because the args[] is empty without any arguments passed so accessing the first one will throw the exception
How do you input commandline argument in IntelliJ IDEA?
There's an "edit configurations" item on the Run menu. In that panel, you can create a configuration and then you can choose the Class containing main().
add VM parameters and command-line args, specify the working directory and any environment variables.
you are done.
Sorry guys figured it out:
Go to Run
Edit Configurations > on the left side make sure you're in your Main class or whatever class you're using
Enter what you want in the program arguments. i.e. "James"

Console class in java Exception in reading password

i am trying to use Console class in java. with this code
import java.io.Console;
public class ConsoleClass {
public static void main(String[] args){
Console c=System.console();
char[] pw;
pw=c.readPassword("%s","pw :");
for(char ch:pw){
c.format("%c",ch);
}
c.format("\n");
MyUtility mu =new MyUtility();
while(true){
String name=c.readLine("%s", "input?: ");
c.format("output: %s \n",mu.doStuff(name));
}
}
}
class MyUtility{
String doStuff(String arg1){
return "result is " +arg1;
}
}
here i am getting NullPointerException when i tried to run in netbeans but i am not getting any Exception when tried to run in cmd with out netbeans IDE.Why?
static Console console()
Returns the unique Console object associated with the current Java virtual machine, if any.
If any.
http://download.oracle.com/javase/6/docs/api/java/lang/System.html
Consoles are typically associated with processes that run independently of frameworks. They are a means of interfacing a process's standard input and output with a shell. If your classes are running as a component of a larger framework, the framework may own the console, and your program might not have a console at all.
There are other conditions and techniques to launch a program without a console. They are typically used when the destruction of the console is guaranteed to occur, but you want the program detached in such a manner that the console's destruction doesn't signal the program's termination.
As such, you cannot guarantee the existence of a console; but, if you are going to run your program in an environment where the console is likely to be present, you should take advantage of it.
System.console() returns a Console instance if a console is associated with the process. - Running under NetBeans you likely don't have an associated console.

Categories