I am doing some debugging in an application (not applet) and have obtained the system's security manager via a call to System.getSecurityManager(). How can I print all configuration information that this SecurityManager was setup with? Looking at the Java 7 SE API it seems that all methods are interrogatory in nature and there is no way to get the permissions configuration. The toString() method also seems to inherit directly from Object and just prints the pointer.
Run the program with -Djava.security.debug=access,domain and you will see everything you need to see.
See it here. http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136007.html
There also exists another method of checking the permissions. Use a try catch block.
try{
} catch (Exception e){
if (e instanceof SecurityException){
// It's a security violation.
// Look for another possibility
}
}
Hope this helps.
Related
I have an interesting problem where I want to enable a specific Bukkit plugin first before any other plugins are enabled. This has proven a difficult task. I can't use the plugin.yml dependancy options because those assume I know what plugins are installed on any given server. I don't care if it doesn't load first, but I do need it to enable first.
I have tried several methods to accomplish this but with no luck:
Attempt 1:
static{
try {
Bukkit.getPluginManager().loadPlugin(plug);
Bukkit.getPluginManager().enablePlugin(plugin);
} catch (UnknownDependencyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidPluginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidDescriptionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Allow me to explain. The static seems to run before most anything, including plugin loadups. This means I also have to define when it loads as well. This normally wouldn't be a problem, except non static API like getDataFolder() for the file Path doesn't work.
public static File plug = new File("/plugins/Debugger");
So unless I'm doing my Paths wrong, I have no clue why this throws an Exception.
NOTE: Yes, I have tried multiple different paths such as "plugins/Debugger" or "Debugger.jar" and ECT.
Method 2:
public void onLoad(){
Bukkit.getPluginManager().enablePlugin(plugin);
console.info("[Debugger] loaded first!");
}
This seemed too good to be true and this method actually seemed to get me closer to solving my problem. This Method is called whenever the plugin loads, so by enabling the plugin within the onLoad Method, it actually caused the plugin to enable first; But there were issues when loading:
[00:15:08] [Server thread/ERROR]: null initializing Debugger v1.0.0 (Is it up to date?)
java.lang.NullPointerException
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:396) ~[craftbukkit.jar:git-Bukkit-0ebb9c7]
at me.doublehelix457.Debugger.Debugger.onLoad(Debugger.java:20) ~[?:?]
at org.bukkit.craftbukkit.v1_10_R1.CraftServer.loadPlugins(CraftServer.java:299) [craftbukkit.jar:git-Bukkit-0ebb9c7]
at org.bukkit.craftbukkit.v1_10_R1.CraftServer.reload(CraftServer.java:723) [craftbukkit.jar:git-Bukkit-0ebb9c7]
at org.bukkit.Bukkit.reload(Bukkit.java:548) [craftbukkit.jar:git-Bukkit-0ebb9c7]
at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:25) [craftbukkit.jar:git-Bukkit-0ebb9c7]
Somehow despite the weird null initializing Debugger (Debugger is the test plugin name) the plugin still managed to enable first?
So the line it is referring to is Bukkit.getPluginManager().enablePlugin(plugin);
Doing some research online I noticed certain API like getServer() was not working within that Method and I believe that maybe this means that Bukkit or PluginManager may not exist yet.
If that's the case, then is there a workaround to this?
That said, I'm willing to take improvements on my current attempts or even try new ones, whatever gets the job done. Please do not ask "Why do you need to enable the plugin first?" I should mention that this version of bukkit is on 1.10.
Any HELPFUL advice would be much appreciated.
So now I feel really stupid. Turns out all I had to do was make my
plugin variable non-static and define it. All that trouble just to change
public static Debugger plugin; to public Debugger plugin = this;
This change works with Method 2.
Well. I hope that this benefits someone as to how they can enable a plugin first.
I have used EMC Documentum Foundation Classes to perform some actions in documentum repository. The code was working fine. I exported the project as a runnable JAR and then tried to run it. However I got following error and I am not able to understand it.
And here is the code for DocMovementHandler.getSession()
Actually this is no new code but regular code for obtaining documentum session
public IDfSession getSession(String userName, String password)
{
DfClientX clientx = null;
IDfClient client = null;
IDfSession session = null;
try {
// create a client object using a factory method in DfClientX
clientx = new DfClientX();
client = clientx.getLocalClient(); //takes time
// call a factory method to create the session manager
IDfSessionManager sessionMgr = client.newSessionManager();
// create an IDfLoginInfo object and set its fields
IDfLoginInfo loginInfo = clientx.getLoginInfo();
loginInfo.setUser(userName);
loginInfo.setPassword(password);
// set single identity for all docbases
sessionMgr.setIdentity("xyz_repo", loginInfo);
session = sessionMgr.getSession("xyz_repo"); //takes time
//sessionMgr.beginTransaction();
System.out.println("Session obtaied.");
}
catch (DfServiceException dse)
{
DfLogger.debug(this, "Error while beginning transaction. ", null, dse);
dse.printStackTrace();
}
catch (Exception e)
{
DfLogger.debug(this, "Error while creating a new session. ", null, e);
e.printStackTrace();
}
return session;
}
And that line 38 is client = clientx.getLocalClient();
InvocationTargetException is a wrapper. It says, "an exception occurred behind this reflection call", and you use getCause() to get at the inner exception.
The stack trace contains the inner exception. It's an ExceptionInInitializerError. That's another wrapper. It says, "whatever you did caused a new class to be loaded, and that class's static initializer threw an exception".
The final exception in this chain is the NullPointerException. That's the one you need to solve. Which means you need to debug this com.documentum thing. As the comments pointed out, that's not going to be easy.
Here is the most likely problem:
The static initializer in one of the classes whose names you have struck is adding an entry with either a null key or a null value to a Hashtable, which does not allow null keys or values.
It is using the Hashtable as a place to store a bunch of persistent properties and all that, and my guess is that the value for one of the entries was the null (which is a perfectly reasonable way to indicate that some feature is unavailable or something like that).
The now deprecated Hashtable needs to be replaced with the more modern HashMap.
If it is a library, that you can't just modify, you should replace the whole library with an updated version.
Here are some clues may be helpful.
The NullPointerException is thrown by Hashtable#put, and this is normally because either the key or the value is null.
Hashtable#put is called by PreferenceManager.readPersistenceProperties, so most likely it's because something is missing in a properties file so the value is null.
This NPE caused the DfClient class could not be loaded.
DfPreferences is the class loading the DFC configuration file dfc.properties. There must be something wrong with it.
Ohkay I did not pin pointed the root cause, but found the solution that will definitely work everytime.
EMC provides a flavor of Eclipse called Documentum Composer to work with Documentum Projects. Since Eclipse variation we can create other types of projects like normal Java project, dynamic web project, web services in this. So I recreated my project in Documetnum Composer and exported it as JAR and whoaaaa it worked.
I tried this many times and this worked all time.
Some points to note:
You have to replace dfc.properties file in Composer installation folder with one in Content Server
The Export to JAR wizard in Composer is a bit different than one in Eclipse
This is usually caused by dfc.properties being incorrect.
Preferences are stored on the global registry repository and the connection details should be specified in dfc.properties. If not, this (or a similar error can occur).
Also, always try to clear cache and use the correct version of the dfc jar's (v6.7 content server requires 6.7 jars, etc...).
I'm currently dealing with a particular issue with my paid application. Internally it contains a licensing check. The app is patched by hackers by modifying the app apk/jar. They are adding a new class which helps bypass the licensing check.
My goal is to somehow check for this particular patch. If I find it I know my app has been compromised.
Any tips on how to know that something has been modified on the package? Doing a hash over the app is not really an option in my case.
I thought maybe checking if this class exists would help, but what if they change the name of the class? Then, another idea is somehow check for unexpected includes added to the class.
Any of these possible? Any suggestions would help :)
Not sure about android but in standard JDK you would do something like this:
try {
Class.forName( "your.fqdn.class.name" );
} catch( ClassNotFoundException e ) {
//my class isn't there!
}
Here is what I used in Android - standard Java:
public boolean isClass(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
Implementation example:
if (isClass("android.app.ActionBar")) {
Toast.makeText(getApplicationContext(), "YES", Toast.LENGTH_SHORT).show();
}
You can use
public static Class<?> forName (String className)
and check the ClassNotFoundException
http://developer.android.com/reference/java/lang/Class.html#forName%28java.lang.String%29
How does it get loaded if it's a random class in a random package?
That being said, see http://download.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties%28%29 and java.class.path. For normal java apps, you have to walk the classpath and then search the entries (for jars) or directories (for .class files). But in a container-class-loader environment, this will fail to work (and I'm not sure how that applies to an android environment).
So we are a few guys developing this product that is communicating with a really unstable server. It often returns very strange and corrupt data. During testing we want the resulting crashes to be loud, so we discover them. But every other day we need to demonstrate our product for a potential customer. To the customer the errors will go undiscovered if we just swallow them. I am thinking about implementing something like this around all server communication to quickly switch between swallowing exceptions and crashing:
try {
apiCall();
} catch (Exception e) {
if(!SWALLOW_EXCEPTION) {
throw e;
}
}
Is this an awesome idea, or can it be done in a better way?
I would recommend using a Logger like SLF4J, java.util.logging or Log4j. Any log messages that are 'debugging' but you still want tracked you can put to the DEBUG, INFO or WARN levels based on their severities. Real errors you can save for the 'Error' level.
When you do demos to customers, set your log level to Error so they don't see everything. When you are running normally though, set it to a level to capture the logging level you need.
Swallowing exceptions is never a good practice. By using a logger, you can hide them if it is giving you too much detail. You can always get access to them if you need without recompiling.
This is not pretty. How about implementing a top level (whatever that means in your context) error handler[s] that does that?
Did you intend your code to do this?
try {
apiCall();
} catch (Exception e) {
if(!SWALLOW_EXCEPTION) {
throw e;
} else {
e.printStackTrace();
}
}
If so, if this is the only place that this API is called, it seems ok to me, as long as you realize you will need to recompile for the change to take effect. You could abuse a logging framework to get that done without a recompile like this:
if (logger.isInfoEnabled()) {
throw e;
} else {
logger.error(e.getMessage(), e);
}
But I think most people looking at such a piece of code would be very taken aback. If you want to avoid the recompile, just use a System property:
if (Boolean.getBoolean("development")) {
throw e;
} else {
e.printStackTrace();//you should really use a logging framework anyway and not this.
}
You could use an 'uncaught exception handler' instead. Check out the code at http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/ and http://www.javapractices.com/topic/TopicAction.do?Id=229. You can also write your handler to put the exceptions into a logger.
As it was made clear in my recent question, Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).
I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property "webstart.version" is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.
Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)
When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists:
private boolean isRunningJavaWebStart() {
boolean hasJNLP = false;
try {
Class.forName("javax.jnlp.ServiceManager");
hasJNLP = true;
} catch (ClassNotFoundException ex) {
hasJNLP = false;
}
return hasJNLP;
}
This also avoids needing to include javaws.jar on your class path when compiling.
Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead:
private boolean isRunningJavaWebStart() {
try {
ServiceManager.getServiceNames();
return ds != null;
} catch (NoClassDefFoundError e) {
return false;
}
}
Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.
Use the javax.jnlp.ServiceManager to retrieve a webstart service.
If it is availabe, you are running under Webstart.
See http://download.java.net/jdk7/docs/jre/api/javaws/jnlp/index.html
As you mentioned, checking the System property as follows is probably the cleanest way:
private boolean isRunningJavaWebStart() {
return System.getProperty("javawebstart.version", null) != null;
}
In a production system I have used the above technique for years.
You can also try to check to see if there are any properties that start with "jnlpx." but none of those are really "guaranteed" to be there either as far as I know.
An alternative could be to attempt to instantiate the DownloadService us suggested by Tom:
private boolean isRunningJavaWebStart() {
try {
DownloadService ds = (DownloadService) ServiceManager.lookup("javax.jnlp.DownloadService");
return ds != null;
} catch (UnavailableServiceException e) {
return false;
}
}
Of course that does have the downside of coupling your code to that API.
I have no real experience with Java web start other than looking at it a few years back.
How about start your application with a parameter that you define than you set when the app is started via Java web start.
If you want to pass in arguments to your app, you have to add them to the start-up file (aka JNLP descriptor) using or elements.
Then check to see if these properties are set.
Again this is a suggestion I have not coded for JWS and it may not be this easy.
You can check whether the current classloader is an instance of com.sun.jnlp.JNLPClassLoader (Java plugin 1) or sun.plugin2.applet.JNLP2ClassLoader (Java plugin 2). Despite the "applet" package, an applet using JNLP with the Java plugin 2 uses another classloader, sun.plugin2.applet.Applet2ClassLoader. It works with OpenJDK too.