Database Reference
In-Depth Information
Listing 8-1. Use NTSystem to Get Windows User Identity
import com.sun.security.auth.module.NTSystem;
NTSystem mNTS = new NTSystem();
String name = mNTS.getName();
Now, wasn't that easy?
If you have UNIX clients, you can use a similar JAAS component through the UnixSystem class, as in
Listing 8-2.
Listing 8-2. Use UnixSystem to Get UNIX User Identity
import com.sun.security.auth.module.UnixSystem;
UnixSystem mUX = new UnixSystem();
String name = mUX.getUsername();
These classes are not both available on either client, and you can only compile the code shown
above on the system where the class exists. So you should only include one or the other calls to NTSystem
or UnixSystem in your application code. You can include each of these and comment one to compile the
other for distribution to those clients where appropriate.
There are other ways to use Java to read the current user identity from Windows Active Directory,
for example as a lightweight directory access protocol (LDAP) service; however, security and
configuration will be very specific to your corporate environment. I will not cover that approach here.
Do Cross-Platform-Specific Coding with Reflection
That approach of “pick your client platform” is not very satisfying, nor does it meet the Java goal of “run
anywhere.” But we have to deal with the fact that NTSystem and UnixSystem classes are not only platform-
specific, but also not available cross-platform. There is an approach that can solve this problem:
reflection . With reflection, we can forget those pesky either/or import statements and commenting the
platform-inappropriate code.
With reflection we can write code that is compiled with possibilities rather than specifics. It is
possible we will be running on a Windows platform, and in that case we want to use NTSystem . But it is
also possible we are running on a UNIX platform, in which case we want UnixSystem to run.
With reflection, we will load a platform-appropriate class, sight-unseen (like going on a blind date),
and then we will use the resources of that class. Reflection uses runtime type introspection to find and
use properties of a specific class.
Listing 8-3 shows the code to get the user identity from the Windows OS using reflection. The code
for UNIX is similar but uses the UnixSystem class rather than the NTSystem class.
Note You will find the code in Listing 8-3 in the file Chapter8/PlatformReflectTest.java.
 
Search WWH ::




Custom Search