Friday, August 31, 2012

JDK7: NIO.2 - Getting Filesystem information

A filesystem is composed of a hierarchy of directories and files. There is a limited amount of information regarding a filesystem that is normally useful. For example, we may want to know whether the filesystem is read-only or who the provider is. In this recipe we will examine the methods available to retrieve filesystem attributes.

Getting ready
To access the method of a filesystem we need to:
  1. Obtain a reference to a java.nio.file.FileSystem object.

  2. Use the methods of this object to access filesystem information.

How to do it...
1- Create a new console application. Add the following code to the main method of the application.
This sequence displays several fileSystem attributes, including the filesystem provider, file open status, whether the file is available to be read-only, the root directories, and the names of the file stores:

2. Execute the application. Your output will depend upon the configuration of your system. However, it should mimic the output that follows:

How it works...
The getDefault method returned the default filesystem used by the JVM. Next, several methods were invoked against this object:
  • The provider method returned the provider, that is, implementer of the filesystem.
    In this case, it was a Windows filesystem provider that came bundled with the JVM.

  • The isOpen method indicated that the filesystem is open and ready for use.

  • The isReadOnly method returned false, meaning that we can read and write to the system.

  • We used the getRootDirectories method to create an Iterable object that permitted us to list each root directory.

  • The getFileStores method returned another Iterable object, which was used to display the names of the file stores.
There's more...
While we do not normally need to close a filesystem, the close method can be used to close the filesystem. Any subsequent methods executed against the filesystem will result in a ClosedFileSystemException being thrown. Any open channels, directory streams, and watch services associated with the filesystem will also be closed. Note that the default filesystem cannot be closed.

The FileSystems class' getFileSystem method can be used to access a specific filesystem. In addition, the overloaded newFileSystem method will create new filesystems. The close method can be used with these instances.

Filesystems are thread-safe. However, if one thread attempts to close the filesystem while another thread is accessing the filesystem object, the close operation may be blocked until the access is complete.

  1. java.nio.file.FileSystem
  2. Java 7 New Features ebook
  3. The power of java 7 NIO.2 (JSR 203) (important concepts

Saturday, August 25, 2012

Software: Why is virtualization useful?

  • Running multiple operating systems simultaneously.
    virtualization software allows you to run more than one operating system at a time.

    This way, you can run software written for one operating system on another (for example, Windows software on Linux or a Mac) without having to reboot to use it.

    Since you can configure what kinds of “virtual” hardware should be presented to each such operating system, you can install an old operating system such as DOS or OS/2 even if your real computer’s hardware is no longer supported by that operating system.
  • Easier software installations.
    Software vendors can use virtual machines to ship entire software configurations.
    For example, installing a complete mail server solution on a real machine can be a tedious task.

    With virtualization software, such a complex setup (then often called an “appliance”) can be packed into a virtual machine. Installing and running a mail server becomes as easy as importing such an appliance into virtualization software.
  • Testing and disaster recovery.
    Once installed, a virtual machine and its virtual hard disks can be considered a “container” that can be arbitrarily frozen, woken up, copied, backed up, and transported between hosts.

    On top of that, with the use of another virtualization software feature called “snapshots”, one can save a particular state of a virtual machine and revert back to that state, if necessary.

    This way, one can freely experiment with a computing environment. If something goes wrong (e.g.after installing misbehaving software or infecting the guest with a virus), one can easily switch back to a previous snapshot and avoid the need of frequent backups and restores.

    Any number of snapshots can be created, allowing you to travel back and forward in virtual machine time. You can delete snapshots while a VM is running to reclaim disk space.
  • Infrastructure consolidation.
    Virtualization can significantly reduce hardware and electricity costs. Most of the time, computers today only use a fraction of their potential power and run with low average system loads. A lot of hardware resources as well as electricity is thereby wasted. So, instead of running many such physical computers that are only partially used, one can pack many virtual machines onto a few powerful hosts and balance the loads between them.

Some terminology:
  • When dealing with virtualization, it helps to acquaint oneself with a bit of crucial terminology, especially the following terms:

    1. Host operating system (host OS).
      This is the operating system of the physical computer on which virtualization software was installed.

    2. Guest operating system (guest OS).
      This is the operating system that is running inside the virtual machine. Theoretically, virtualization software can run any x86 operating system (DOS, Windows, OS/2, FreeBSD, OpenBSD), but to achieve near-native performance of the guest code on your machine, we had to go through a lot of optimizations that are specific to certain operating systems.

      So while your favorite operating system may run as a guest, the support and optimize can be applied.

    3. Virtual machine (VM).
      This is the special environment that virtualization software creates for your guest operating system while it is running. In other words, you run your guest operating system “in” a VM.

      Normally, a VM will be shown as a window on your computer’s desktop, but depending on which of the various frontends of virtualization software you use, it can be displayed in full screen mode or remotely on another computer.

      In a more abstract way, internally, virtualization software thinks of a VM as a set of parameters that determine its behavior. They include hardware settings (how much memory the VM should have, what hard disks virtualization software should virtualize through which container files, what CDs are mounted etc.) as well as state information (whether the VM is currently running, saved, its snapshots etc.).

    4. Guest Additions.
      This refers to special software packages which are shipped with virtualization software but designed to be installed inside a VM to improve performance of the guest OS and to add extra features.

Wednesday, August 22, 2012

JDK7: Changes done in existing IO/NIO classes to adapt NIO.2 APIs

Changes to existing classes
    Is updated with a toPath() method that returns a java.nio.file.Path object constructed from the abstract path.

    Is updated to support an action that grants the ability to read a symbolic link.

  3. java.util.Scanner
    Is updated with new constructors that create a text scanner for scanning files located by a java.nio.file.Path.

  4. java.nio.channels.SocketChannel
    Is updated to implement java.nio.channels.NetworkChannel and additionally defines the methods: shutdownInput(), shutdownOutput(), and getRemoteAddress().

  5. java.nio.channels.ServerSocket
    Is updated to implement java.nio.channels.NetworkChannel and additionally defines the method bind(SocketAddress,int).

  6. java.nio.channels.DatagramChannel
    Is updated to implement java.nio.channels.MulticastChannel and additionally defines the methods open(ProtocolFamily) and getRemoteAddress().

  7. java.nio.channels.FileChannel
    Is updated to implement java.nio.channels.SeekableByteChannel and additionally defines new static methods to open/create the file.

  8. java.nio.channels.FileLock
    Is updated to define a new protected constructor for when the lock is acquired via an AsynchronousFileChannel.
    FileLock is also updated to define the method acquiredBy().

  9. java.nio.channels.Channels
    Is updated with two methods for interoperation between AsynchronousByteChannel types and streams.

Thursday, August 16, 2012

JDK7: Part 2 - Java 7, The "Dolphin" new features & enhancements.

Java 7 was released in July of 2011 and introduced a number of new features. In the Java SDK documentation, you may see it referred to as Java 1.7, it streamline the development process and has a great and improved enhancements in many areas specially IO and concurrent processing.

In this article I will address a variety of topics involved in JDK 7 as new features and enhancements on two parts.

Part 1 introduces the core language and JVM enhancements, IO operations from using paths for locating, managing the files & directories and getting there information. Also I will introduce the managing of the files Systems and finally streaming of new IO2.

While this part covers the remaining topics including GUI enhancements and its event handling, Database, security and system enhancements. And finally the great enhancement and huge improvement had done in the threading and concurrency API.

Table of contents:

1.       Language Improvements.

2.       Using Paths to Locate Files and Directories.

3.       Obtaining File and Directory Information.

4.       Files and Directories Management.

5.       Managing Filesystems.

6.       Stream IO in Java 7.

7.       Graphical User Interface (GUI) Improvements.

8.       GUI events handling.

9.       Database, Security, and System Enhancements.

10.   Threading & concurrent processing.

11.   References.

7.      Graphical User Interface (GUI) Improvements.

The ability to develop applications that have a Graphical User Interface (GUI) interface has been enhanced in Java 7. Some of these are minor improvements and others are major, such as using the javax.swing.JLayer decorator class.

It is now possible to mix heavyweight and lightweight components in an application without adding special code to make it work as desired. This improvement is largely transparent to users of Java 7.

To ease the development of applications, three basic window types have been introduced. These should simplify the creation of certain types of applications. The JFrame class supports a setType() method, which configures the general appearance of a window to one of the three types. This can simplify the setting of a window's appearance.

To set the window type, use the setType() method with one of the three window types, as found in the java.awt.Window class:

         Type.NORMAL: This represents a normal window and is the default value for windows.

         Type.POPUP: This is a temporary window intended to be used for small areas, such as tool tips.

         Type.UTILITY: This is also a small window for objects, such as a palette.

The overall appearance of an application may include such characteristics as its opacity and shape. You can manage and control a window's opacity and creating a varying gradient translucent window. Controlling the shape of a window, such as making it round or some irregular shape, is also controllable.

The translucency-related capabilities were added originally as part of the Java 6 Update 10 release. However, they were implemented as part of the private com.sun.awt.AWTUtilities class. This capability has been moved to the java.awt package. Javax.swing.JComponents has borders whose appearance can be controlled. In Java 7, several new borders have been added.

Improvements have also been made in the use of the file dialog and print dialog boxes. These enhancements are the Handling multiple file selection in the FileDialog class and Controlling the print dialog box type.

The ability to draw over a JComponent has been added. This allows the use of special effects, which were not easily achieved in earlier versions of Java. You can use the new JLayer decorator for a password field and also create a watermark for windows.

The following is the code used to develop a minimal window-based application. An ApplicationRunner class is used to start and display the JFrame-derived ApplicationWindow class. The ApplicationRunner class is shown as follows:

The invokeLater method uses an inner class to create and then display the ApplicationWindow. This window is set up in its constructor. It is a simple window that has an Exit button, which we will use to close the application and you can enhance and customize it to suite your application :

When this code is executed, the output should appear as shown in the following screenshot:

There are a number of minor improvements introduced in Java 7. For example, the protected static java.awt.Cursor array has been deprecated. Instead, use the getPredefinedCursor method. This method takes an integer argument and returns a Cursor object.

A new HSV tab was introduced to the java.swing.JColorChooser dialog box. It appears as shown in the following screenshot:

Also in Java 7, it is possible to customize a dragged JApplet's title and to specify whether it should be decorated or not. This is accomplished from a script tag as follows:

<script src="http://javascript source file"></script>
    var attributes = { code:'AppletName', width:100, height:100 };
    var parameters = {jnlp_href: 'appletname.jnlp',java_decorated_frame: 'true', java_applet_title: 'A Custom Title'};
    deployJava.runApplet(attributes, parameters, '7'7);

The java_decorated_frame parameter is set to true to specify that the window should be decorated. The title of the window is specified using the java_applet_title parameter. This example is adapted from More details on how to create draggable applets can be found at that site.

A couple of miscellaneous changes need to be noted. The Nimbus Look and Feel has been moved from the package to the javax.swing package. The isValidateRoot method has been added to the Applet class to indicate that the container is a valid root. Lastly, a new Java2D graphics pipeline based upon the X11 XRender extension has been added to provide better access to Graphical Processing Units (GPU).

8.      GUI events handling.

There have been several additions to Java 7 that address events or are related to events. This includes the handling of mouse events where enhanced support is provided for the detection of mouse buttons and for using high resolution mouse wheels.

When a window is made visible with either the setVisible or toFront methods, we now have the ability to control whether they should gain focus or not. Some windows may be displayed for informational or status purposes and do not necessarily need or warrant focus.

You should be familiar with the behavior of modal dialog boxes. Essentially, the modal dialog box will not return focus to the main window until it is closed. There are times when it is desirable to mimic this behavior without using a dialog box. For example, the selection of a button that performs a relatively long running calculation may benefit from this behavior.

While not common, spurious interrupts can occur when using the wait method. The java.awt.event.InvocationEvent class' isDispatched method can be used to handle spurious interrupts.

Applets have also been enhanced with regards to their ability to communicate with JavaScript code. So JavaScript code can be made aware of and take advantage of knowing when an applet loads.

Other minor event-related improvements in Java 7 are the availability of accessing extended key codes and the implementation of the java.awt.iamg.ImageObserver interface for the JSlider class.

The KeyEvent class has been augmented with two new methods: getExtendedKeyCode and getExtendedKeyCodeForChar. The first method returns a unique integer for a key, but unlike the getKeyCode method, its value depends on how the keyboard is currently configured. The second method returns the extended key code for a given Unicode character.

The imageUpdate method has been added to the JSlider class. This permits the class to monitor the status of an image being loaded, though this capability is probably best used with classes that are derived from JSlider.

9.      Database, Security, and System Enhancements.

This topic covers database, security, and system type enhancements that have been made to Java 7.

Some of these enhancements are minor and will be addressed in this article. Others are more significant and will be detailed in other articles. Due to the rather specialized nature of some topics, such as those typified by some of the security enhancements, they will be mentioned but not explained here.

Java Database Connectivity JDBC 4.1:

Multiple enhancements have been made to JDBC in Java 7, which now supports JDBC 4.1.

Note: Some of the improvements depend on third party driver support not available in early driver versions. When this happens, you may receive an AbstractMethodException. When testing the database, ensure that you are working with a driver that supports the JDBC 4.1 functionality.

Drivers can be found at

The Using the RowSetFactory recipe deals with the use of the javax.sql.rowset.RowSetFactory interface and the javax.sql.rowset.RowSetProvider class, which permits the creation of any row sets as supported by a given JDBC driver.

There are a number of other improvements in database's support included in Java 7, and include such issues as determining the name of the current schema and providing access to hidden columns.

In addition to these database enhancements, the try-with-resource statement can be used with any object that implements the java.sql package's Connection, ResultSet, or Statement interfaces.

This language improvement simplifies the process of opening and closing resources. The general use of the try-with-resource statement is to improve exception handling.

The Statement interface has been enhanced with two new methods. The first method, closeOnCompletion, is executed to specify that the Statement object will be closed when result sets that use the connection are closed. The second method, isCloseOnCompletion, returns a Boolean value indicating whether the statement will be closed when this criteria is met.


Network enhancements to Java 7 include the addition of two methods to the class:

         close: This method will close the current URLClassLoader, so that it is no longer able to load classes or resources. This addresses a problem found on Windows, as detailed at

         getResourceAsStream: This method returns an InputStream for the resource specified by its String argument

Assistance is also provided to support stream connections using the InfiniBand (IB). This technology uses Remote Direct Memory Access (RDMA) to move data directly between the memories of different computers. This support is provided through the Sockets Direct Protocol (SDP) network protocol. The specialized nature of this technology precludes further discussion.

the improvements also made in the support of MXBeans. This includes different methods for accessing these management type beans.

Language libraries:

The java.lang.ProcessBuilder class has improved redirect capabilities as introduced by the ProcessBuilder.Redirect class. Which is the Redirecting input and output from operating systems processes.

Java 7 has also improved the way applets can be embedded in an HTML page.


The Java Secure Socket Extension (JSSE) is used to secure Internet communications using Secure Sockets Layer (SSL) and Transport Layer Security (TLS). JSSE assists in data encryption, authentication, and maintaining message integrity. In Java 7, several enhancements have occurred.

Security enhancements include the incorporation of Elliptic Curve Cryptography (ECC) algorithms. This class of encryption algorithms is more resistant to brute force attacks. A portable implementation of the algorithm has been provided. New exception classes have been added or enhanced to enhance security.

The new, when thrown, means that an X.509 certificate has been revoked. The class has been enhanced with the addition of a new constructor that takes a CertPathValidatorException.Reason object. This object implements the CertPathValidatorException.BasicReason enumeration that enumerates the reason for the exception. The CertPathValidatorException class's getReason method returns a CertPathValidatorException.Reason object.

Java 7 also supports TLS 1.1 and 1.2 specifications and improves upon this support. The Sun JSSE provider supports TLS 1.1 and TLS 1.2 as defined in RFC 4346 ( and RFC 5246 ( respectively. These include support to protect against cipher block chaining attacks and new cryptographic algorithms.

In addition, there are a few other TKS-related enhancements:


         The SSLv2Hello protocol has been removed from the list of protocols that are enabled by default.

         A flaw relating to TLS renegotiation has been fixed in Java 7. Details regarding this flaw can be found at

         During TLS 1.1/1.2 handshaking, Java 7 has improved the process of version number checking.

Weak cryptographic algorithms can be disabled using the jdk.certpath.disabledAlgorithms property for the Sun provider. By default, the MD2 algorithm is disabled. This property is specified in the jre/lib/security/ file.

The default setting is shown as follows:



It is also possible to specify not only the algorithm, but restrictions on the key size.

Algorithm restrictions can also be placed at the TLS level. This is accomplished using the jdk.tls.disabledAlgorithms security property in the jre/lib/security/ file. Anexample is as follows:

jdk.tls.disabledAlgorithms=MD5, SHA1, RSA keySize < 2048

Currently, this property is specific to the Oracle JSSE implementation and may not be recognized by other implementations.

The Server Name Indication (SNI) JSSE extension (RFC 4366) enables TLS clients to connect to virtual servers, that is, multiple servers with different network names that use the same supporting network address. This is enabled to true by default, but can be set to false for systems where the extension is not supported.

The jsse.enableSNIExtension system property is used to control this setting. It can be set using the –D java command option shown as follows:

java –D jsse.enableSNIExtension=true ApplicationName

It is also possible to set this property using the setProperty method shown as follows: System.setProperty("jsse.enableSNIExtension","true");

Note that the property name may change in the future.

10.      Threading & concurrent processing.

Support for concurrent applications has been improved in Java 7. Several new classes have been introduced that support the parallel execution of tasks. The ForkJoinPool class is used for applications, which use the divide-and-conquer technique to solve a problem. Each sub problem is forked (split) as a separate thread and later joined, if necessary to provide a solution. The threads used by this class are normally subclasses of the java.util.concurrent.ForkJoinTask class and are lightweight threads.

In addition, the java.util.concurrent.Phaser class has been introduced to support the execution of a collection of threads in a series of phases. A group of threads are synchronized, so that they all execute and then wait for the completion of the others. Once they have all completed, they can be re-executed for a second phase or subsequent phase.

Two new classes designed to work safely with multiple threads The java.util.concurrent.ConcurrentLinkedDeque class safely with multiple threads and the java.util.concurrent.LinkedTransferQueue class, examples of their use in support of the producer/consumer framework.

The java.util.concurrent.ThreadLocalRandom class is new and provides better support for random number generation used between multiple threads.

Two new constructors have been added to the java.util.ConcurrentModificationException class. They both accept a Throwable object used to specify the cause of the exception. One of the constructors also accepts a string that provides a detail message regarding the exception.

Java 7 has improved the use of class loaders by modifying the locking mechanism to avoid deadlocks. In multi-threaded custom class loaders prior to Java 7, certain custom class loaders were prone to deadlocks, when they used a cyclic delegation model.

Consider the following scenario. Thread1 tries to use a ClassLoader1 (locking ClassLoader1) to load class1. It then delegates the loading of class2 to ClassLoader2. At the same time, Thread2 uses ClassLoader2 (locking ClassLoader2) to load class3, and then delegates the loading of class4 to ClassLoader1. Since both class loaders are locked and both the threads need both loaders, a deadlock situation occurs.

The desired behavior of a concurrent class loader is to load different classes from the same instance of the class loader concurrently. This requires locking at a finer level of granularity, such as locking a class loader by the name of the class being loaded.

Synchronization should not be done at the class loader level. Instead, a lock should be made on a class level, where the class loader allows only a single instance of the class to be loaded at a time by that class loader.

Some class loaders are capable of loading classes concurrently. This type of class loader is called parallel capable class loaders. They are required to register themselves during their initialization process using the registerAsParallelCapable method.

If the custom class loader uses an acyclic hierarchal delegation model, no changes are needed in Java. In a hierarchal delegation model, delegation is first made to its parent class loader. Class loaders that do not use the hierarchical delegation model should be constructed as parallel capable class loaders in Java.

To avoid deadlock for custom class loaders:

         Use the registerAsParallelCapable method in the class initialization sequence. This indicates that all instances of the class loader are multi-thread safe.

         Make sure that the class loader code is multi-thread safe. This involves:

§ Using an internal locking scheme, such as the class name locking scheme used by java.lang.ClassLoader.

§ Removing any synchronization on the class loader lock.

§ Ensuring that critical sections are multi-thread safe.

         It is recommended that the class loader overrides the findClass(String) method.

         If the defineClass methods are overridden, then ensure that they are only called once per class name.

More detail about this problem can be found at

11.      References.


2. Java SE Technical Documentation

3. Description of Java Conceptual Diagram

4. The Java Tutorial


6. Java 7 Cookbook book.

7. Java 7 Recipes A Problem-Solution Approach book.

8. Beginning Java 7 book.

9. The Java™ Language Specification (JLS) Java SE 7 Edition.

10. The Java Virtual Machine Specification Java SE 7 Edition.

Finally thanks for reading, for full article check Part 1.

Saturday, August 4, 2012

Quartz: java.lang.ClassNotFoundException: org.slf4j.Logger while running embedded Weblogic on JDev

VIP: The post is updated with the original cause.

After working on Oracle Jdeveloper for a while, today when I am running my application on embedded Weblogic.
Suddenly I have stuck with the following error in Weblogic deployment stage of my application:

There is no other applications could run. So what is the solution?

I have deleted the embedded Weblogic defaultDomain folder of jdeveloper, and created it again via jdeveloper, but this procedure not succeeds.

The other option is to uninstall jdeveloper and install it again, but this issue is time consuming, it is expanded from installing jdeveloper, configuring the libs, and your applications (There is a work around for this by coping the o.ide and o.jdeveloper folders of your jdeveloper system11.x.x.x.x.x.x.x folder, and past them again in newly created folder.), and I have critical delivery time and I didn’t to this procedure.

After googleing for the problem and reason for a while, I didn't find exact or reason or solution for problem.

So after investigation, the slf4j-api library is not available anymore for Weblogic to start normally, I don't know the reason, but any way here is the solution:

Note: While writing this post the slf4j api library version is 1.6.6.

  1. Download the library from the following site

  2. Extract the zip, to C:\ slf4j-1.6.6

  3. In slf4j-16.6 folder locate the following 2 libs: slf4j-api-1.6.6.jar and slf4j-nop-1.6.6.jar.

  4. Locate the folder called "system11.". On windows it will be in the following path: "C:\Users\mohamed_taman\AppData\Roaming\JDeveloper\system11."

  5. Inside this folder locate folder called " DefaultDomain " inside it locate " lib " folder.

  6. Copy and paste in lib folder the previously mentioned 2 jars "slf4j-api-1.6.6.jar and slf4j-nop-1.6.6.jar".

  7. You can past then in any folder that is visible to Weblogic classpath.

  8. Run your application and it will run now and Weblogic will be happy now.

VIP: Update: the original cause:

After working for another day I found the team has the same error after updating from SVN, and then I realized that the problem is not in JDeveloper, there is a certain library that needs this lib.

I have scanned my project and reviewed what is newly added to the project and libs used, I found that the Quartz Scheduler API lib is used in web by injecting the following line into the web.xml:

I have reverted the above solution to get stuck with the original error.

I went to folder " C:\Users\mohamed_taman\AppData\Roaming\JDeveloper\system11.\o.j2ee\drs " and delete my application.

I tried to run other applications, they are runs successfully. So the problem is in my application not JDeveloper.

Note: I used the quartz 2.0.2 this this happens after migration from version 1.x.x to 2.x.x.

Another VIP note: I used Quartz 2.x in normal scheduling and it works normal, the problem raised when I used it in the web.

Note: While writing this post the Quartz library version is 2.0.2.

  1. Under your extracted Quartz folder; for example if you extracted the folder like this: " E:\Utilities\Quartz 2.0.2 ", locate folder called " lib (E:\Utilities\Quartz 2.0.2\lib)".

  2. In " lib " folder locate the following 3 libs: slf4j-api-1.6.1.jar , slf4j-log4j12-1.6.1.jar and log4j-1.2.14.jar.

  3. When you add quartz-all-2.0.2.jar to your web project as library, add also all the 3 libs located in step 2.

  4. Run your application and it will run now, and Weblogic will be happy now.

For any help just leave your comment.