Debugging in Java - Eclipse [duplicate] - java

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

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.

In the startup scripts generated by gradle's application plugin, how can I have the program name passed in to the application?

Executing the gradle application plugin's installDist task creates a directory build/install/my-application-name/bin that contains wrapper scripts, my-application-name and my-application-name.bat. Running either of these scripts runs the application, and arguments passed to these scripts are passed to the underlying application.
In UNIX shell scripts you can access the name that was used to execute the program as $0. In fact, the UNIX version of the gradle-generated startup script uses $0 several times.
How can I configure the gradle application plugin such that these scripts will pass the value of $0 (and whatever the Windows equivalent is on Windows) into the underlying application, perhaps as a Java system property?
Since parameter for obtaining the name of the script being run is referenced differently in Linux($0) and in Windows(%0), the most straightforward way to generate custom scripts would be to use separate custom templates for the respective start script generators:
startScripts {
unixStartScriptGenerator.template = resources.text.fromFile('unixStartScript.txt')
windowsStartScriptGenerator.template = resources.text.fromFile('windowsStartScript.txt')
}
The default templates are easy to obtain invoking e.g. unixStartScriptGenerator.template.asString()
Documentation on customizing the start scripts can be found here.
This is what I ended up doing, based on jihor's answer. I'm posting it here just so that there's a working answer for anyone else interested:
startScripts {
def gen = unixStartScriptGenerator
gen.template = resources.text.fromString(
gen.template.asString().replaceFirst('(?=\nDEFAULT_JVM_OPTS=.*?\n)') {
'\nJAVA_OPTS="\\$JAVA_OPTS "\'"-Dprogname=\\$0"\''
})
// TODO: do something similar for windowsStartScriptGenerator
}
This uses replaceFirst is instead of replace so we can match a pattern. This is a little less brittle, and also lets us use lookahead so we don't have to actually replace what we're looking for. (This is groovy's variant of replaceFirst that takes a closure, by the way. This requires far less escaping than the version that takes a replacement string in this case.)
Also, instead of:
JAVA_OPTS="$JAVA_OPTS -Dprogname=$0"
we actually need something like:
JAVA_OPTS="$JAVA_OPTS "'"-Dprogname=$0"'
This is because $0 may contains special character (like spaces), and the startup script removes one level of quoting in the value of $JAVA_OPTS using eval set --.
(If anyone knows how to make this work on Windows, pleas feel free to update this answer.)
I took an alternative approach. According to the documentation, as far back as Gradle 2.4 and all the way through Gradle 4.8, we should be able to set the following properties within the startScripts task:
applicationName
optsEnvironmentVar
exitEnvironmentVar
mainClassName
executableDir
defaultJvmOpts
appNameSystemProperty
appHomeRelativePath
classpath
Unfortunately, this is not true for the following properties, which seem to have never been exposed:
appNameSystemProperty
appHomeRelativePath
If appNameSystemProperty were exposed as the documentation describes, then we should be able to simply do the following:
startScripts {
applicationName = 'foo'
appNameSystemProperty = 'appName'
}
This would then result in the addition of -DappName=foo to the Java command constructed within both of the start scripts.
Since this is not the case, I took the following approach, which is a bit more verbose than the earlier solution to this question, but is perhaps less brittle because it does not rely on tweaking the out-of-box templates. Instead, it results in the documented behavior.
startScripts {
mainClassName = '...'
applicationName = 'foo'
unixStartScriptGenerator =
new CustomStartScriptGenerator(generator: unixStartScriptGenerator)
windowsStartScriptGenerator =
new CustomStartScriptGenerator(generator: windowsStartScriptGenerator)
}
class CustomStartScriptGenerator implements ScriptGenerator {
#Delegate
ScriptGenerator generator
void generateScript(JavaAppStartScriptGenerationDetails details,
Writer destination) {
details = new CustomDetails(details: details)
this.generator.generateScript(details, destination)
}
static class CustomDetails implements JavaAppStartScriptGenerationDetails {
#Delegate
JavaAppStartScriptGenerationDetails details
#Override
String getAppNameSystemProperty() { 'appName' }
}
}

vertx LoggerHandler not adding logback

I am trying to use LoggerHandler to log all incoming requests. I am using logback.xml to specify appenders. I am setting system property for logging.
System.setProperty("org.vertx.logger-delegate-factory-class-name",
"org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");
Still it is logging everything in console not in file.
This worked for me with Vert.x 3.4.1:
import static io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME;
import io.vertx.core.logging.LoggerFactory;
// ...
setProperty (LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName ());
LoggerFactory.getLogger (LoggerFactory.class); // Required for Logback to work in Vertx
The key is to get a logger, which I guess initializes the Logging subsystem, the class that you use to get a Logger seems irrelevant as I tried with two different ones.
I run these lines as the first ones of the program in production code and in the tests to work properly in both contexts.
I was able to get it to work by setting the VM options as such:
-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.Log4jLogDelegateFactory
Then in my log4j.properties, I had to add this:
log4j.category.io.vertx = TRACE
I know this question is getting a bit old, but the only way I was able to get the vertx LoggerHandler to not use JUL was to call LoggerFactory.initialise() after setting the system property as described in the question.
Even better, I set the property in my build.gradle, like so:
run {
systemProperty(
"vertx.logger-delegate-factory-class-name",
"io.vertx.core.logging.SLF4JLogDelegateFactory"
)
args = ['run', mainVerticleName, "--redeploy=$watchForChange", "--launcher-class=$mainClassName", "--on-redeploy=$doOnChange",
"-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory" ]
}
And then at the very top of my MainVerticle::start I have:
LoggerFactory.initialise()
And, boom. Everything is now formatted correctly, including all the startup output.

Unable to set log level in a Java web start application?

Some logging levels appear to be broke?
I run a Java web start (which I will begin to call JWS from now on) application straight from a GlassFish 3.1.2.2 instance. The client has a static logger like so:
private final static Logger LOGGER;
static {
LOGGER = Logger.getLogger(App.class.getName());
// Not sure how one externalize this setting or even if we want to:
LOGGER.setLevel(Level.FINER);
}
In the main method, I begin my logic with some simple testing of the logging feature:
alert("isLoggable() INFO? " + LOGGER.isLoggable(Level.INFO)); // Prints TRUE!
alert("isLoggable() FINE? " + LOGGER.isLoggable(Level.FINE)); // ..TRUE
alert("isLoggable() FINER? " + LOGGER.isLoggable(Level.FINER)); // ..TRUE
alert("isLoggable() FINEST? " + LOGGER.isLoggable(Level.FINEST)); // ..FALSE
My alert methods will display a JOptionPane dialog box for "true GUI logging". Anyways, you see the printouts in my comments I added to the code snippet. As expected, the logger is enabled for levels INFO, FINE and FINER but not FINEST.
After my alert methods, I type:
// Info
LOGGER.info("Level.INFO");
LOGGER.log(Level.INFO, "Level.INFO");
// Fine
LOGGER.fine("Level.FINE");
LOGGER.log(Level.FINE, "Level.FINE");
// Finer
LOGGER.finer("Level.FINER");
LOGGER.log(Level.FINER, "Level.FINER");
LOGGER.entering("", "Level.FINER", args); // <-- Uses Level.FINER!
// Finest
LOGGER.finest("Level.FINEST");
LOGGER.log(Level.FINEST, "Level.FINEST");
I go to my Java console and click on the tab "Advanced", then I tick "Enable logging". Okay let's start the application. Guess what happens? Only Level.INFO prints! Here's my proof (look at the bottom):
I've done my best to google for log files on my computer and see if not Level.FINE and Level.FINER end up somewhere on the file system. However, I cannot find the log messages anywhere.
Summary of Questions
Why does it appear that logging of Level.FINE and Level.FINER does not work in the example provided?
I set the logging level in my static initializing block, but I'd sure like to externalize this setting to a configuration file of some sort, perhaps packaged together with the EAR file I deploy on GlassFish. Or why not manually write in some property in the JNLP file we download from the server. Is this possible somehow?
Solution for problem no 1.
After doing a little bit more reading on the topic, I concluded that a logger in Java uses a handler to publish his logs. And this handler in his turn has his own set of "walls" for what levels he handles. But this handler need not be attached directly to our logger! You see loggers are organized in a hierarchical namespace and a child logger may inherit his parents handlers. If so, then By default a Logger will log any output messages to its parent's handlers, and so on recursively up the tree (see Java Logging Overview - Oracle).
I ain't saying I get the full picture just yet, and I sure didn't find any quotes about how all of this relates to a Java Web Start application. Surely there has to be some differences. Anyways, I did manage to write together this static initializing block that solves my immediate problem:
static {
LOGGER = Logger.getLogger(App.class.getName());
/*
* This logic can be externalized. See the next solution!
*/
// DEPRECATED: LOGGER.setLevel(Level.FINER);
if (LOGGER.getUseParentHandlers())
LOGGER.getParent().getHandlers()[0].setLevel(Level.FINER);
else
LOGGER.setLevel(Level.FINER);
}
Solution for problem no 2.
The LogManager API docs provided much needed information for the following solution. In a subdirectory of your JRE installation, there is a subdirectory called "lib" and in there you shall find a "logging.properties" file. This is the full path to my file on my Windows machine:
C:\Program Files (x86)\Java\jre7\lib\logging.properties
In here you can change a lot of flavors. One cool thing you could do is to change the global logging level. In my file, this was done on row 29 (why do we see only a dot in front of the "level"? The root-parent of all loggers is called ""!). That will produce a hole lot of output; on my machine I received about one thousand log messages per second. Thus changing the global level isn't even plausible enough to be considered an option. Instead, add a new row where you specify the level of your logger. In my case, I added this row:
martinandersson.com.malivechat.app.App.level = FINER
However, chances are you still won't see any results. In solution no 1, I talked about how loggers are connected to handlers. The default handler is specified in logging.properties, most likely on row 18. Here's how my line reads:
handlers= java.util.logging.ConsoleHandler
Also previously, I talked about how these handlers in their turn use levels for what should trouble their mind. So, find the line that reads something like this (should now be on row 44?):
java.util.logging.ConsoleHandler.level = INFO
..and in my case I swapped "INFO" to "FINER". Problem solved.
But!
My original inquiry into this matter still hasn't provided an answer how one can set these properties closer in par with the application deployment. More specifically, I would like to attach these properties in a separate file, bundled with the application EAR file I deploy on GlassFish or something like that. Do you have more information? Please share!

Using Inline::Java in perl with threads

I am writing a trading program in perl with the newest Finance::InteractiveBrokers::TWS
module. I kick off a command line interface in a separate thread at the
beginning of my program but then when I try to create a tws object, my program
exits with this message:
As of Inline v0.30, use of the Inline::Config module is no longer supported or
allowed. If Inline::Config exists on your system, it can be removed. See the
Inline documentation for information on how to configure Inline. (You should
find it much more straightforward than Inline::Config :-)
I have the newest versions of Inline and Inline::Java. I looked at TWS.pm and it doesn't seem to be using Inline::Config. I set 'SHARED_JVM => 1' in the 'use Inline()' and 'Inline->bind()' calls in TWS.pm but that did not resolve the issue...
My Code:
use Finance::InteractiveBrokers::TWS;
use threads;
use threads::shared;
our $callback;
our $tws;
my $interface = UserInterface->new();
share($interface);
my $t = threads->create(sub{$interface->runUI()});
$callback= TWScallback->new();
$tws = Finance::InteractiveBrokers::TWS->new($manager); #This is where the program fails
So is Inline::Config installed on your system or not? A cursory inspection of the code is not sufficient to tell whether Perl is loading a module or not. There are too many esoteric ways (some intentional and some otherwise) to load a package or otherwise populate a namespace.
The error message in question comes from this line of code in Inline.pm:
croak M14_usage_Config() if %main::Inline::Config::;
so something in your program is populating the Inline::Config namespace. You should do what the program instructs you to do: find out where Inline/Config.pm is installed on your system (somewhere in your #INC path) and delete it.

Categories