Showing posts with label requirement. Show all posts
Showing posts with label requirement. Show all posts

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>
<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);
</script>

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 http://download.oracle.com/javase/tutorial/deployment/applet/draggableApplet.html. 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 com.sun.java.swing 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 http://developers.sun.com/product/jdbc/drivers.


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.


Networking:


Network enhancements to Java 7 include the addition of two methods to the java.net.URLClassLoader 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 http://download.oracle.com/javase/7/docs/technotes/guides/net/ClassLoader.html


         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.


Security:


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 java.security.cert.CertificateRevokedException, when thrown, means that an X.509 certificate has been revoked. The java.security.cert.CertPathValidatorException 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 (http://tools.ietf.org/html/rfc4346) and RFC 5246 (http://tools.ietf.org/html/rfc5246) 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 http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html.


         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/java.security file.


The default setting is shown as follows:


jdk.certpath.disabledAlgorithms=MD2

 


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/java.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 http://openjdk.java.net/groups/core-libs/ClassLoaderProposal.html.


11.      References.


1. http://docs.oracle.com/javase/tutorial/index.html.


2. Java SE Technical Documentation http://docs.oracle.com/javase/index.html.


3. Description of Java Conceptual Diagram http://docs.oracle.com/javase/7/docs/technotes/guides/desc_jdk_structure.html.


4. The Java Tutorial http://docs.oracle.com/javase/tutorial/index.html.


5. http://tamanmohamed.blogspot.com/2012/03/jdk7-part-1-power-of-java-7-nio2-jsr.html


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, June 23, 2012

JDK7: Part 1 - 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 will introduce 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.

Part 2 will cover 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.

1- Language Improvements.
----------------------------------

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. This topic will focus on those that have been grouped as part of the Project Coin (http://openjdk.java.net/projects/coin/).

Project Coin refers to the small language changes in Java 7 that are designed to make programs more readable by removing extra text when possible. The changes to the language do not involve modifying the Java Virtual Machine (JVM). These new features include:

  • The use of strings in switch statements.
  • The addition of binary literals and the ability to insert underscores into numeric literals
  • The use of a multi-catch block
  • The try-with-resources block
  • Improved type inferences using the diamond operator
  • Improvements in the use of methods with a variable number of arguments

Since the inception of Java, only integer values could be used to control a switch statement. Strings can now be used and can provide a more convenient technique for controlling the execution flow that is based on a string.

Underscores can now be used with literals to improve code readability. These can make a program more readable and maintainable. In addition, binary literals can now be used. Instead of using a hexadecimal literal, for example, the literal bit pattern can be used.

New to Java 7 are the improved try-catch block mechanisms. These include the ability to catch more than one exception from a single catch block, and improvements in how exceptions can be thrown.

Another improvement in exception handling involves the automatic closure of resources. In earlier versions of Java, when multiple resources were opened in a try block, it could be difficult to effectively close the resources, when an exception occurs. Java 7 provides a new technique in using the try-with-resources block to improve exception handling.

To take advantage of this technique, a class representing a resource must implement the new java.lang.AutoCloseable interface. This interface consists of a single method, close which, when implemented, should release resources as needed. Many core Java classes have been augmented to do this.

Java 7 provides the capability to re-throw exceptions in a flexible manner. It provides a more precise way of throwing exceptions, and more flexibility in how they can be handled in a try/catch bock.

When generics were introduced in Java 1.5, it became easier to write code to address a number of similar problems. However, its usage at times could become somewhat verbose. The introduction of the diamond operator has eased this burden.

When a method uses a variable number of generic arguments, sometimes an invalid warning is generated. The @SafeVarargs annotation has been introduced to flag a method as safe. This issue is related to heap pollution.


2- Using Paths to Locate Files and Directories.
--------------------------------------------------------

A filesystem is a way of organizing data on a computer. Normally, it consists of one or more top-level directories, each of which contains a hierarchy of files. The top-level directory is frequently referred to as the root. In addition, the filesystem is stored on a media, which is referred to as the file store.

Java 7 introduces a number of new classes and interfaces to make working with filesystems easier and more efficient. These have largely supplemented older classes found in the java.io package.

In this and subsequent topics, I will explain how a filesystem can be managed using the directory structure, as shown in the following diagram:


The ovals represent a directory/folder, while rectangles represent files. Unix-based systems and Windows systems differ in their support of a root node. Unix systems support a single root node, while Windows systems permit more than one root node. The location of a directory or file is described using a path. The elements, directories and files of the path are separated by either a forward or backward slash. In Unix, a forward slash is used. In Windows, a backward slash is used.

The music files were obtained from http://www.music.com/. The others.txt is intended to hold simple status information, while the users.txt is assumed to hold a list of users. The users.txt file in the music directory is a symbolic link to the actual file in the docs directory as reflected with the red line.

Symbolic links are more common in Unix-based platforms. To create a symbolic link for the users.txt file in the music directory, use the following command in the command console:

mklink users.txt c:\home\docs\users.txt. This requires administrator privileges to execute.

The management of paths as represented by the java.nio.file.Path class. A Path object is used extensively by classes in the java.nio package and is composed of several parts that are as follows:

  • A root which is the base of the path, such as a C drive.
  • A separator used to separate the names that make up directories and files of the path.
  • The names of the intermediate directories.
  • A terminal element, which can be a file or directory.

Also the following are the classes dealing with files and directories:

  • java.nio.file.Paths contains static methods for the creation of a Path object.
  • java.nio.file.Path interface contains numerous methods for working with paths.
  • java.nio.file.FileSystems is the primary class used to access a filesystem.
  • java.nio.file.FileSystem represents a filesystem, such as the /on a UNIX system or the C drive on a Windows platform.
  • java.nio.file.FileStore represents the actual storage device and provides device-specific information.
  • java.nio.file.attribute.FileStoreAttributeView provides access to file information.

To gain access to a file or directory, we will typically use the FileSystems class' getDefault method to retrieve a reference to the filesystem accessible by the JVM. To get access to a specific drive, we can use the getFileSystem method with a Uniform Resource Identifier (URI) object representing the drive or directory of interest.

The FileSystems class provides techniques to create or access a filesystem. FileSystems class supports the creation of Path objects. Once we have reference to a file system object, we can obtain a Path object using any one of several methods:

  • getPath: This uses a system-dependent path to obtain a Path object. The Path object is used to locate and access the file.
  • getPathMatcher: This creates a PathMatcher. It performs various matching type operations on a file.
  • getRootDirectories: This is used to obtain a list of root directories.

The creation and general use of Path objects is introduced in this topic, is used in subsequent recipes and other topics, so be sure to understand the basic processes.

You can still use the older java.io package elements. A path representing a java.io.File object can be created using the File class's toPath method. This is the Interoperability between java.io.File and java.nio.file.Files and can be useful when maintaining older code.

Paths can be either relative or absolute.

Paths can contain redundancies and extraneous elements. Removal of these elements is called normalization. This technique is available to simplify these types of paths.

Paths can be combined to form a new composite path. This is known as resolving a path. This technique can be useful for creating new paths, where parts of the path are available from different sources.

When a reference is needed for a file, that path is sometimes relative to the current location or some other location. The Creating a path between two locations is called relativizing.

Not only are there relative and absolute paths, but there are also other ways of representing a path such as with a java.net.URI object. When a Path object is created, it is not necessary that the actual path exists. For example, the Path may be created to create a new filesystem element.

Paths are system-dependent. That is, a path on one system such as UNIX is different from one found on a Windows system. Comparing two paths found on the same platform may or may not be the same.


3- Obtaining File and Directory Information.
------------------------------------------------------

Many applications need access to file and directory information. This information includes such attributes as whether the file can be executed or not, the size of the file, the owner of the file, and even its content type. In this topic, I will explain the various techniques available for obtaining information regarding a file or directory.

There are five general approaches to obtaining file and directory information using the java.nio.file.Files class that are as follows:

  • Obtaining a single attribute at a time using the Files class' specific methods, such as the isDirectory method.
  • Obtaining a single attribute at a time using the Files class' getAttribute method.
  • Returning a map of attributes using the readAttributes method using a String to specify which attributes to return.
  • Using the readAttributes method with a BasicFileAttributes derived class to return an attribute class for that set of attributes.
  • Using the getFileAttributes method to return a view that provides access to a specific set of attributes

Dynamic access to attributes is supported through several methods and allows the developer to specify an attribute using a String. The Files class' getAttribute method typifies this approach.


Java 7 introduces a number of interfaces that are based on a file view. A view is simply a way of organizing information about a file or directory. For example, the AclFileAttributeView provides methods related to the file's Access Control List (ACL). The FileAttributeView interface is the base interface for other interfaces that provide specific types of file information. Sub-interfaces found in the java.nio.file.attribute package include the following:

  • AclFileAttributeView: This is used to maintain the file's ACL and ownership attributes.
  • BasicFileAttributeView: This is used to access basic information about a file and to set time-related attributes.
  • DosFileAttributeView: This is designed to be used with the legacy Disk Operating System (DOS) file attributes.
  • FileOwnerAttributeView: This is used to maintain the ownership of a file.
  • PosixFileAttributeView: This supports Portable Operating System Interface (POSIX) attributes.
  • UserDefinedFileAttributeView: This supports user-defined attributes for a file The relationships between the views are shown as follows:


The readAttributes method's second parameter specifies the type of attributes to be returned. Three attribute interfaces are supported and their relationship is illustrated in the following figure. These interfaces provide a means of accessing their corresponding view interfaces:


4- Files and Directories Management.
----------------------------------------------

It is often necessary to perform file manipulations such as creating files, manipulating their attributes and contents, or removing them from the filesystem. The addition of the java.lang.object.Files class in Java 7 simplifies this process. This class relies heavily on the use of the new java.nio.file.Path interface, which is discussed in Using Paths to Locate Files and Directories topic. The methods of the class are all static in nature, and generally assign the actual file manipulation operations to the underlying filesystem.

 

Many of the operations described here are atomic in nature, such as those used to create and delete files or directories. Atomic operations will either execute successfully to completion or fail and result in an effective cancellation of the operation. During execution, they are not interrupted from the standpoint of a filesystem. Other concurrent file operations will not impact the operation.

 

There are basic file management methods required for the creation of files, creation of temporary files and and the creation of linked files using symbolic links. Also there are options available for copying, moving and deleting files and directories.

 

You can assign time attributes to a file. Related to this effort are other attributes, such as file ownership and permissions, managing ACL file permissions and Managing POSIX file permissions.


5- Managing Filesystems.
--------------------------------

A filesystem is one or more top-level root directories containing a hierarchy of files. A filesystem is supported by a file store that is the provider for the storage of the files. This topic is concerned with obtaining information about these entities and typical filesystem tasks, such as determining the contents of a directory or monitoring filesystem events.

 

A file store represents a unit of storage. For example, it might represent a device, such as a C drive, a partition of a drive, or a volume. The java.nio.file.FileStore class supports file stores and provides several methods to this end.

A filesystem supports access to a hierarchy of directories and files. It is represented in Java 7 with the java.nio.file.FileSystem class. This includes how to obtain a list of root directories for a filesystem and the underlying file stores.

 

Traversing a directory hierarchy is useful for many applications. The Using the SimpleFileVisitor class to traverse filesystems is the basic approach. This approach is used in the Deleting a directory using the SimpleFileVisitor class and Copying a directory using the SimpleFileVisitor class.

 

When an operation is restricted to a single directory, the java.nio.file.DirectoryStream interface provides a convenient technique for examining each element in the directory as a java.nio.file.Path object. It is very easy to use a for each loop to process these paths.

 

Sometimes we don't need the entire contents of a directory, but rather a subset of its elements. Java 7 provides a few approaches to filtering the contents of a using globbing and Writing your own directory filter. Globbing is a pattern-matching technique that is similar to regular expressions but is easier to use.

 

In the Monitoring file events using WatchEvents we see how Java 7 supports the detection of file creation, modification, and deletion within a directory by external processes. This can be very useful when it is necessary to know when changes to a directory are made.

 

With Java 7, it is now possible to treat the contents of a ZIP file as a filesystem. This makes it easier to manage the contents of a ZIP file and to manipulate the files contained within the ZIP file.


6- Stream IO in Java 7.
---------------------------------

In Java 7, I found that there are numerous improvements to its IO capabilities. Most of these are found in the java.nio package, which has been dubbed as NIO2. In this topic, we will focus on the new support for streaming and channel-based IO. A stream is a contiguous sequence of data. Stream IO acts on a single character at a time, while channel IO works with a buffer for each operation.

 

I start with the new techniques used to work with simple files. These are supported by the Files class and Buffered IO is usually more efficient to be used in reading and writing data.

 

The java.nio.channels package's ByteChannel interface is a channel that can read and write bytes. The SeekableByteChannel interface extends the ByteChannel interface to maintain a position within the channel. The position can be changed using seek type random IO operations.

 

Java 7 has added support for asynchronous channel functionality. The asynchronous nature of these operations is that they do not block. An asynchronous application can continue executing without the need to wait for an IO operation to complete. When the IO completes, a method of the application is called. There are four new java.nio.channels package asynchronous channel classes:

  • AsynchronousSocketChannel
  • AsynchronousServerSocketChannel
  • AsynchronousFileChannel
  • AsynchronousChannelGroup

The first two AsynchronousServerSocketChannel and AsynchronousSocketChannel are used together in a server/client environment to managing asynchronous communication using them.

 

The AsynchronousFileChannel class is used for file manipulation operations that need to be performed in an asynchronous manner, the methods supporting the write and read operations.

 

The AsynchronousChannelGroup class provides a means of grouping asynchronous channels together in order to share resources.

 

The java.nio.file package's SecureDirectoryStream class provides support for more secure access to directories. However, the underlying operating system must provide local support for this class.

 

When opening a file, some of these open methods that will use an enumeration argument to specify how the file should be opened. The java.nio.file package's OpenOption interface specifies how the file is opened and the StandardOpenOption enumeration implements this interface. The values of the enumeration are summarized in the following table:

 

Enumeration

Meaning

APPEND

Bytes are written to the end of the file

CREATE

Creates a new file if it does not exist

CREATE_NEW

Creates a new file only if the file does not exist

DELETE_ON_CLOSE

Deletes the file when it is closed

DSYNC

Every update to a file is written synchronously

READ

Open for read access

SPARSE

Sparse file

SYNC

Every update to the file or metadata is written synchronously

TRUNCATE_EXISTING

Truncates the length of a file to 0 when opening a file


The java.nio.channels package's NetworkChannel interface was introduced in Java 7. This represents a channel to a network socket. Several classes including the AsynchronousServerSocketChannel and AsynchronousSocketChannel classes that are discussed in this topic implement it. It has a bind method that binds a socket to a local address, allowing the retrieval and setting of various query socket options. It permits the use of operating system-specific options, which could be used for high performance servers.


The java.nio.channels package's MulticastChannel is also new to Java 7. It is used to support multicast operations for a group. It is implemented by the DatagramChannel class. Methods of this interface support the joining and leaving of members from a group.


The Sockets Direct Protocol (SDP) is a network protocol, which supports stream connections using InfiniBand (IB). The IB technology supports point-to-point bi-directional serial links between high-speed peripherals, such as disks. A significant part of IB is its ability to move data from the memory of one computer directly to the memory of another computer.


SDP is supported in Java 7 on Solaris and Linux operating systems. Several classes in the java.net and java.nio.channels packages support it transparently. However, SDP must be enabled before it can be used.


Details on how to enable IB and then create a SDP configuration file are found at http://download.oracle.com/javase/tutorial/sdp/sockets/index.html.


11- References.
------------------------
  1. http://docs.oracle.com/javase/tutorial/index.html.
  2. Java SE Technical Documentation
  3. Description of Java Conceptual Diagram.
  4. The Java Tutorial
  5. http://tamanmohamed.blogspot.com/2012/03/jdk7-part-1-power-of-java-7-nio2-jsr.html
  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, and we will meet in Part 2.


Saturday, April 21, 2012

Architecture: Modeling & Designing Software Projects Architecture

When I model and design the architecture of software project, first thing I consider is what is the software project type?

My experience in this field of projects architecture has taught me that most applications fails into seven software types, each type has its own technology's, communication patterns, architectural patterns and design steps.

The software categories are:

1. Object oriented Software:
The object-oriented design uses the concepts of information hiding, classes, and inheritance. This results in the design of a sequential object-oriented software architecture, which would be implemented as a sequential program with one thread of control.
2. Client / Server Software.
In these systems, a client is a requester of services and a server is a provider of services. Typical servers are file servers, database servers, and line printer servers. Client/server architectures are based on client/service architectural patterns, the simplest of which consists of one service and multiple clients. This pattern has several variations, which will be described next. In addition, certain decisions need to be considered about the design of client/server architectures, such as whether the server should be designed as a sequential or concurrent subsystem, what architectural structure patterns to use for the design of the client/server architecture, and what architectural communication patterns to use for interaction between the clients and the services.

Also differentiates between a server and a service. A server is a hardware/ software system that provides one or more services for multiple clients. A service in a client/server system is an application software component that fulfills the needs of multiple clients. Because services execute on servers, there is sometimes confusion between the two terms, and the two terms are sometimes used interchangeably. Sometimes, a server will support just one service or perhaps more than one; on the other hand, a large service might span more than one server node. In client/server systems, the service executes on a fixed server node(s) and the client has a fixed connection to the server.
3. Service-Oriented Architecture.
SOA is a distributed software architecture that consists of multiple autonomous services. The services are distributed such that they can execute on different nodes with different service providers. With a SOA, the goal is to develop software applications that are composed of distributed services, such that individual services can execute on different platforms and be implemented in different languages. Standard protocols are provided to allow services to communicate with each other and to exchange information. In order to allow applications to discover and communicate with services, each service has a service description; the service description defines the name of the service, the location of the service, and its data exchange requirements.

A service provider supports services used by multiple clients. Usually, a client will sign up for a service provided by a service provider, such as an Internet, email, or Voice over Internet Protocol (VoIP) service. Unlike client/server architectures, in which a client communicates with a specific service provided on a fixed server configuration, this chapter describes SOAs, which build on the concept of loosely coupled services that can be discovered and linked to by clients (also referred to as service consumers or service requesters) with the assistance of service brokers. This document describes how to design SOAs, how to design services, and how to reuse services.
4. Distributed Component-Based Software.
In the design of software architectures for a distributed component-based software design; the component-based software architecture for the distributed application is developed. The software application is structured into components, and the interfaces between the components are defined. To assist with this process, guidelines are provided for determining the components. Components are designed to be configurable so that each component instance can be deployed to a different node in a geographically distributed environment.

Components are initially designed using the subsystem structuring criteria. Additional component configuration criteria are used to ensure that components are indeed configurable – in other words, that they can be effectively deployed to distributed physical nodes in a distributed environment.
5. Concurrent Real-Time Software.
The real-time software is a concurrent architecture usually, having to deal with multiple streams of input events. They are typically state-dependent, with either centralized or decentralized control.

Real-time software architectures are concurrent architectures that usually have to deal with multiple streams of input events. They are typically state-dependent, with either centralized or decentralized control. Thus, the design of finite state machines, state-dependent interaction modeling, and the control patterns, are very important in the design of real-time software architectures.
6. Software Product Line.
It is architectures for families of products that need to capture both the commonality and variability in the family.

A software product line (SPL) consists of a family of software systems that have some common functionality and some variable. Software product line engineering involves developing the requirements, architecture, and component implementations for a family of systems, from which products (family members) are derived and configured.

The problems of developing individual software systems are scaled upwards when developing SPLs because of the increased complexity due to variability management.

As with single systems, a better understanding of a SPL can be obtained by considering the multiple views, such as requirements models, static models, and dynamic models of the product line. A graphical modeling language such as UML helps in developing, understanding, and communicating the different views. A key view in the multiple views of a SPL is the feature modeling view. The feature model is crucial for managing variability and product derivation because it describes the product line requirements in terms of commonality and variability, and defines the product line dependencies. Furthermore, it is desirable to have a development approach that promotes software evolution, such that original development and subsequent maintenance are both treated using feature-driven evolution.
7. Framework Software.
A software framework is an abstraction in which software providing generic functionality can be selectively changed by user code, thus providing application specific software. It is a collection of software libraries providing a defined application programming interface (API). It is a universal, reusable software platform used to develop applications, products and solutions.

Software Frameworks include support programs, compilers, code libraries, an application programming interface (API) and tool sets that bring together all the different components to enable development of a project or solution.

Frameworks contain key distinguishing features that separate them from normal libraries:

7.1. Inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.

7.2. Default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.

7.3. Extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.

7.4. Non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.
-----------------------------------------------------------------------
Last thing is very important should be considered when architecting any project. It is Non-Functional requirements and should be taken into consideration when designing such software types from the modeling and design stage not when implementing the project.

In my architecture document I called it Software quality attributes.

Software quality attributes:
Refer to the nonfunctional requirements of software, which can have a profound effect on the quality of a software product. Many of these attributes can be addressed and evaluated at the time the software architecture is developed. Software quality attributes include maintainability, modifiability, testability, traceability, scalability, reusability, performance, availability, and security.

Some software quality attributes are also system quality attributes because they need both the hardware and software to achieve high quality. Examples of these quality attributes are performance, availability, and security. Other software quality attributes are purely software in nature because they rely entirely on the quality of the software. Examples of these quality attributes are maintainability, modifiability, testability, and traceability.