Saturday, October 20, 2007

Windows Vista Screen Flicker

Well, this post has nothing to do with java, but I though it would be important, since this issue caused me a lot of frustration. I recently bought a laptop with Windows Vista Home Premium, and I was frustrated at what seemed to me that it was a hardware problem. Well, it wasn't. It was a windows "feature" ;-)

The "feature" that annoyed me was that the screen blinked a couple of times when I was logging in, in a matter that seemed as if the screen is faulty. The same thing happened when I wanted to do something that windows think that I shouldn't do, like moving a read only file, or run an executable program (yet another windows "feature"). When I tried to do any of those actions that would cause a security problem, I got a prompt to ask me if I allow this action, with the desktop disabled, and with an occasional screen blink (totally random).

Well, after some googling, I found the causes of those two really annoying "features". The first "feature" was the Transient Multimon Manager (TMM). This TMM is "a Microsoft Windows Vista operating system feature" responsible for detecting your monitors as you connect/disconnect them to/from your mobile PC. You may regard TMM as a good feature in case you use multiple displays (external monitor, projector, etc.) especially that "TMM persists the user's settings on a per-display basis when possible".

When you seldom use multiple displays (like me), TMM is of no value. So, how do we turn it off? Simple. Go to task scheduler (present under "Accessories/System Tools"), then go to "Task Scheduler Library/Microsoft/Windows/MobilePC", and you'll find a TMM task. Disable it, and you're done (of course you'll have to restart your system for the change to take effect, because the task will already be running). You can also disable the trigger of the task. I do not recommend deleting the task altogether, since you might need it in the future.

Now for the second "feature". Windows vista has what's called "secure desktop". Well, it is a good feature to be frank. When you try to do an action that Vista thinks that it might be the result of a malicious action, it will prompt you whether you allow this action or not. This is not "secure desktop" by the way. Secure desktop is responsible for locking all the processes running in the background so that if the action was really performed by a piece of malicious software, it wouldn't give this piece of software the ability to mimic the user allowing the action to be performed.

So, if you think that you will never have malicious software, and you don't want secure desktop, all you have to do is to run your registry editor (just type "regedit" in the "run" screen), and go to "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/
CurrentVersion/Policies/System", and change the value of the "PromptOnSecureDesktop" to "0" (that's a zero not an O) instead of "1". This will remove secure desktop (hence the occasional blinking) but will not remove the prompting. I recommend that you keep secure desktop for the security reasons, but that's just me.

Edit on 6/1/2008:
I would like to thank Matt for supplying this link in his comment. I think that the screen shot woul give you a little help. Thanks Matt

Saturday, October 13, 2007

Commons Logging may be harmful to your health

All of us know that decoupling your code from the frameworks you use is a really great thing. This is why bridge libraries like commons logging are really wonderful. Just imagine how much code you will be changing if you are using log4j APIs in all of you application classes, and then a decision was made to start using the java APIs instead. Think of how much code would be changed. But with commons logging, the code changes would be minimal. Another thing, look at how many open source projects that are using commons logging. This must mean that commons logging is a good thing, right? WRONG!

First, let us define the meanings of "good" and "bad" concerning libraries such as commons logging. I think, that a "good" library would be able to bridge your logging requests to the logging framework of your preference with minimum interference and a very small overhead. I don't have to mention here that it should be stable and bug free of course. Another thing, which I personally think that it's very important, is that it should be as simple as possible.

If we take a look at JCL (Jakarta Commons Logging), we'll find that a lot of those aspects are not met. JCL works in a quiet complex way. It has a discovery mechanism to see which logging library you have in your application, and then uses class loading to load the logger that will be used. Even though this does the job, this class loading solution has its drawbacks. First of all, this may cause a lot of problems if your application is in a strict class loading environment (like OSGI for example). Another thing, JCL has a bad history with it's class loading solution.

Version 1.04 of JCL that was released on the 16th of June 2004 had some serious problems with its class loading mechanism. Ceki Gülcü (the original author of log4j) wrote a marvelous article on the subject. He also wrote a great piece on JCL, but might be a little outdated. Even though version 1.1 of JCL, released about 2 years after 1.04, claims that the bug is fixed, it's still a risk to use it, especially for the complexity of this library.

Another thing that needs to be mentioned here is that Rod Waldhoff, the author of commons logging, wrote a blog entry in 2003, titled "Commons Logging was my fault", where, in the last part of it, he says where to use and, more importantly, not to use JCL. To conclude it, JCL should be used in small and tiny components that are intended to be used by other developers in their projects. Even with that, Erik van Oosten created a project called "Version 99 Does Not Exist", which is an empty JAR with a pom file and maven meta data, so that you would put it in your maven repository, so that libraries that depend on JCL would not download it from the net, since the empty JAR is version 99.

So what else should we use? Well, I think that SLF4J is a great project. It's a simple facade for various logging APIs. The beauty of it is that instead of the class loading solution, it is just a simple facade, where you just plug in the desired implementation at deployment time. It's a very simple solution, "perhaps even laughably so" as stated in their FAQ.

SLF4J is wonderful, simple, stable and can be used in strict class loading environments like OSGI. It can be used with log4j, jdk1.4 logging, SimpleLogger, logback and x4juli (the latter 2 provide native implementation of SLF4J APIs). It's very simple to migrate to SLF4J from JCL. Simply download "jcl104-over-slf4j.jar", and it will delegate JCL calls to SLF4J.

SLF4J also has a couple of great features, parameterized logging and MDC support. Parameterized logging can cause a significant increase in the performance. One last thing that I have noticed, which is quiet funny really, several apache projects use SLF4J instead of commons logging. This sure shows that SLF4J is on the right track.

Saturday, September 15, 2007

Complete Java 2 Certification Study Guide (Sybex)

This is my second review, and again, it's a java certification book. This was the book I studied from for my certification exam, and thanks to God, I did pretty well.

The book is well constructed, with a lot of info, and a lot of great exercises at the end of each chapter, plus a mock exam, and four sample exams on the accompanying CD. Unfortunately, the book is full of typos, and there are several mistakes with the exam and the review questions, which is quiet a shame. Those mistakes turn this book from a great book, to a "just quiet satisfactory" book. Some of the mistakes are clearly due to lack of revision of the changes done to this edition, so conflicts show up in a couple of places.

An example to what I mean is that starting from Java 5.0, the return type of the overriding method could be a child of the return type of the overridden method, and it's stated clearly in the middle of the chapter, but in the summary at the of the chapter, it's mentioned that the return type of the overriding method must be exactly the same as the overridden method, and can't even be a subclass of it (which is true for pre-5.0). This is clearly something that was in previous editions of the book, and wasn't changed where it was supposed to be. Several mistakes like this occur in the book.

The book is worth it's price, but only if you are going to be careful while studying from it, and check other sources, whether they are other books, or freely available resources on the internet. If you are going to study from one book, and one book only, and will not rely on any other resources, then this is not the book for you. The book is not a bad choice, but there are several other better study guides in the market, like Katherine's Sierra's and Bert Bate's SCJP Sun Certified Programmer for Java 5 Study Guide from Osbourne. I checked it out, and it looks great.

Buy Complete Java 2 Certification Study Guide from amazon
Buy SCJP Sun Certified Programmer for Java 5 Study Guide from amazon


Saturday, August 11, 2007

Dynamic roles management in acegi security: Part 2

Last time we stopped at a problem, and that was the fact that the bean holding the secure URL patterns is loaded only once at application startup. Now, when we need to alter the access rights of roles, we will need to restart the application, and this is really not very flexible.

There are a couple of solutions to this problem. The first is to reload the filter invocation interceptor, and set the object definition source in it with an instance that holds the new values, like the following example:






UrlPatternRolesDefinitionSource myRoles = (UrlPatternRolesDefinitionSource) applicationContext.getBean ("objectDefinitionSource");



FilterSecurityInterceptor filterSecurityInterceptor = (FilterSecurityInterceptor) applicationContext.getBean ("filterInvocationInterceptor");



filterSecurityInterceptor.setObjectDefinitionSource (myRoles);



Only here we have a trick that should be done. The bean objectDefinitionSource should be declared as non-singleton in the XML configuration, either by specifying its scope="prototype" or by specifying singleton="false". This solution has a problem, and it is that the whole list of roles and secure URL patterns will be reloaded from the database (or whatever your datasource is).

The other solution is to create your own ConfigAttributeDefinition that extends the one supplied by acegi. The main reason for doing this is that the one supplied by acegi doesn't have a removeAttribute method.I suggest overriding this implementation to add a removeAttribute method. I also prefer if you would use an ArrayList or a Map instead of the Vector used by the acegi implementation to represent the configAttributes

This ConfigAttributeDefinition should be the one you use in the UrlPatternDefinitionSource that we created in part one of this article.

In the class(es) that will be manipulating the the roles, you should inject the UrlPatternDefinitionSource instance that acegi creates (using spring's configuration files). You then get the ConfigAttributeDefinition for your role using the lookupAttribute method in the UrlPatternDefinitionSource class. A code snippet is shown below.






UrlPatternRolesDefinitionSource uprds = definitionSource;


ConfigAttribute config = new SecurityConfig(role.getName());


Set patternsSet = role.getUrlPatterns();


List list = urlPatternDao.listUrlPatternsOfRole(role);


List oldUrlPatternsOfRole = new ArrayList();


//get list of old url patterns of role


for (UrlPattern urlWithRole : list) {


oldUrlPatternsOfRole.add(urlWithRole);
}


//update role in database


roleDao.updateRole(role);


//do not allow the role to access old url patterns


for (UrlPattern pattern : oldUrlPatternsOfRole) {


MyConfigAttributeDefinition configDefinition = (MyConfigAttributeDefinition) uprds.lookupAttributes(pattern.getUrlPattern());


configDefinition.removeConfigAttribute(config);


}


//allow the role to access the new set of url patterns


for (UrlPattern pattern : patternsSet) {


//get the pattern itself from DB, since all we have is the id of the pattern only


pattern = urlPatternDao.retrieveUrlPattern(pattern.getId());


MyConfigAttributeDefinition configDefinition = (MyConfigAttributeDefinition) uprds.lookupAttributes(pattern.getUrlPattern());


configDefinition.addConfigAttribute(config);


}




The previous code may need some optimization, but it was just to give you a general idea about how to implement dynamic role management.

I hope that this article was useful, and I apologize once more for the delay.

Tuesday, August 7, 2007

Apology

I just want to apologize for being late with the second part of the ACEGI security article, but I had some work pressure, and a lot of traveling between Cairo, Dubai and Abu Dhabi lately, which made it quiet hard to complete the article, but I promise that I'll try my best to finish the article before the beginning of next week, in spite of the fact that I'm still traveling between Dubai and Abu Dhabi every weekend. I apologize again.

Wednesday, July 11, 2007

Dynamic roles management in acegi security: Part 1

Acegi security is a great powerful and flexible security solution. What I don't like about it is the lack of documentation and samples provided, and this is why I thought of writing about this subject today.

The example that comes with acegi security, and the one that comes with appfuse define secure URL patterns, and the roles that can access them in the XML configuration file, which is not a very flexible solution. It is a good approach if you have predefined roles and access rights , that are never going to change (or the changes are very rare). In case you have a security module, where you define which role can access which URL patterns, this method is the worst thing you could do.

The solution to this problem is to define your own data source, which loads the secure URL patterns and the corresponding roles that can access it from somewhere (database for example). A simple way to do that is by extending PathBasedFilterInvocationDefinitionMap and loading the secure URL patterns and the roles that can access them in an initialization method or in the constructor. Here's an example:

public class UrlPatternRolesDefinitionSource extends PathBasedFilterInvocationDefinitionMap {

public void init(){
Session session = sessionFactory.openSession();
try{

List urlPatternsList = urlPatternDao.listUrlPatterns(session);

for (UrlPattern pattern : urlPatternsList) {

ConfigAttributeDefinition configDefinition = new ConfigAttributeDefinition();

for(Role role: pattern.getRoles()){

ConfigAttribute config = new SecurityConfig(role.getAuthority());

configDefinition.addConfigAttribute(config);
}

addSecureUrl(pattern.getUrlPattern(), configDefinition);

}
}
catch (FindException e) {
// Handle exception
}
finally {
session.close();
}
}
}


In this example I used a Hibernate DAO I created (urlPatternDao) to retrieve the secure URL patterns which is defined and initialized with the sessionFactory somewhere else in the code (using spring's dependency injection). You can implement it anyway you like (JDBC, with any other ORM framework, or any other method you like).

In this example, each URL pattern can has a set roles that can access it, so I loop over this set to create the ConfigAttributeDefinition. I prefer if you have your own implementation of the ConfigAttributeDefinition, but this is going to be discussed in part 2 of this article. Of course the Role class used in this code implements the GrantedAuthority interface.

As for the XML configuration of this entry, it's shown below:
<bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web. FilterSecurityInterceptor">

<property name="authenticationManager" ref="authenticationManager"/>

<property name="accessDecisionManager" ref="accessDecisionManager"/>

<property name="objectDefinitionSource" ref="objectDefinitionSource"/>

</bean>


<bean id="objectDefinitionSource" class= "net.jnassef.security.UrlPatternRolesDefinitionSource" init-method="init">

<property name="convertUrlToLowercaseBeforeComparison">
<value type="boolean">false</value>
</property>

<property name="urlPatternDao" ref="urlPatternDao"/>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>


As for the first bean in the previous snippet, this definition is the default that comes with the sample acegi application and with appfuse, except to the reference to the objectDefinitionSource bean which was added by us, to allow dynamic role management. The second bean maps to the class we created, and defines the initialization method, that will load the secured URL patterns, and the roles associated with them. This definition also sets the DAO and the hibernate session factory used by the class. Of course you don't need those if you want to have any other implementation.

The previous implementation seems good as a solution for dynamic role management, but if we look more closely, it's not a very good solution (or to be more accurate, it's not a complete solution). The problem that is going to face us here is that secure URL patterns are loaded only ONCE at the application start up, and any change done to the role access rights will not effective until the application is started, and this is not dynamic at all. In fact, there is no difference between this solution, and having the access rights in the XML configuration file, except that you will not need to redeploy your application, but you will need to restart it. There are several solutions to this problem, and this will be the main focus of the next part of this article.

Tuesday, June 12, 2007

Head First Servlets & JSP

Studying is never fun for a lot of people, and reading technical books is always taken as a boring task by a lot of people. This will never be the case with any of the head first series of books.


The head first approach depends on a lot of images, since an image says more than a thousand words. It also depends on repeating the information in different styles, and dialogue like text.

Even though this might seem as if it's a very simple approach, but the result is amazing. The book is fun to read, full of information, and yet very simple. Never thought I would love to study that much again.

Now enough about the head first approach, and into the book itself. The book is very informative, and covers nearly everything in the exam. Very few subjects were not covered, but most of them are covered in the questions at the end of each chapter, with a reference to the place of the information in the specs.

Few mistakes are there (like any book in the market), but most of them are spelling mistakes. The O’Reilly website has a great errata page covering every single mistake in the book (even spelling and grammar mistakes).

A lot of topics covered in the book do not even appear in other books, and a lot of those come in the exam. I studied from that book, and got 94% in the exam. Great book, and really fun to read.


Buy the book from amazon.com