Monday, December 31, 2012

Java: Store/Load properties file in both XML and TEXT format.

Most of the time we created the properties file and modifying it in text editors like Notepad++ and notpad etc. We also can create and modifies the properties files from Java program as well. You will see in the following example XmlTextPropsReaderWriter.java how to do it.

The most common properties files are Log4j.properties that is used to configure Log4J system logging, and jdbc.properties which also used to control your program JDBC API connectivity parameters, and finally no web application working with internationalization (I18N) doesn’t have a resource bundle in form of properties file.

Let's see how to read and create properties file from java program in both formats (XML and TEXT).

Java API’s java.util.Properties class provides utility store() methods to store properties in either text or xml format. store() can be used to store property in text properties file and storeToXML() method can be used for creating a property file in XML format. On the other hand the load() reads a text format properties file while loadFromXML() reads XML format properties file.

The following example is streamlined using new JDK7 feature and NIO.2 capabilities.

Program source:

Running the above program produces the following output:

value1
value3

The created properties file text (users.properties) format is:

And the created properties file XML (user.xml) format is:

Note that: xml file created is governed by the following properties.dtd specification file:

Although most of us even me by default using the normal text format of the properties file and statically defined. Then the questions that may raise here are:

1- When to use the XML format?
2- When we can benefit from creating it dynamically?

for the first question, there are many areas that you can benefit from the xml format especially when you working with the same configuration file from many systems, and working with different languages to specific devices and need one configuration understood by all languages, readable, easy to secure, and retrieving data using xPath API is doable, all of these benefits leads to xml properties format.

The second part is, whenever you want to create a dynamic configuration, then you have the solution now.


Saturday, December 22, 2012

Database: Protecting your database using Database Firewall App.!

As Systems Architect I am responsible and involved in all security aspects of the system I am Architecting, and any other integrated systems or components.

When Architecting a financial products and also being related to government, then the security becomes a crucial part. One of the most important parts of protection is to protect data that resides in database.

In old days I did it manually by coding, hashing, encrypting, preventing any SQL-injection, vulnerabilities, logging, auditing ….etc. lot of time consuming and exposed to be hacked.

Nowadays, one of the amazing product I am using, to do all of the above for me beside another tremendous features is "Oracle Audit Vault and Database Firewall".

Well, what is "Oracle Audit Vault and Database Firewall" then?

Oracle Audit Vault and Database Firewall provide a first line of defense for databases and consolidate audit data from databases, operating systems, and directories.

A highly accurate SQL grammar-based technology monitors and blocks unauthorized SQL traffic before it reaches the database. Information from the network is combined with detailed audit information for easy compliance reporting and alerting.

With Oracle Audit Vault and Database Firewall, monitoring controls can be easily tailored to meet enterprise security requirements.

It secures databases by monitoring and blocking SQL statements according to the policies you define as well as collecting and reporting various configurable database audit data.

It contains many features and tools that provide ease of administration, monitoring and scaling.


The Database Firewall for Activity Monitoring and Blocking
-------------------------------------------------------------------------
Oracle Database Firewall provides a sophisticated next-generation SQL grammar analysis engine that inspects SQL statements going to the database and determines with high accuracy whether to allow, log, alert, substitute, or block the SQL.

Oracle Database Firewall supports white list, black list, and exception list based polices.

A white list is simply the set of approved SQL statements that the database firewall expects to see. These can be learned over time or developed in a test environment.

A black list includes SQL statements from specific users, IP addresses, or specific types that are not permitted for the database.

Exception list-based policies provide additional deployment flexibility to override the white list or black list policies.

Policies can be enforced based upon attributes, including SQL category, time of day, application, user, and IP address. This flexibility, combined with highly accurate SQL grammar analysis, enables organizations to minimize false alerts, and only collect data that is important.

Firewall events are logged to the Audit Vault Server enabling reports to span information observed on the network alongside audit data.


Fine Grained, Customizable Reporting and Alerting
-----------------------------------------------------------------
Dozens of out-of-the-box reports provide easy, customized reporting for regulations such as SOX (Sarbanes-Oxley Act), PCI DSS (Payment Card Industry), GLBA (German-Leach-Bliley Act ), DPA (Data Protection Act), and HIPAA (Health Insurance Portability and Accountability Act).

The reports aggregate both the network events and audit data from the monitored systems. Report data can be easily filtered, enabling quick analysis of specific systems or events.

Security Managers can define threshold based alert conditions on activities that may indicate attempts to gain unauthorized access and/or abuse system privileges.

Fine grained authorizations enable the Security Manager to restrict auditors and other users to information from specific sources, allowing a single repository to be deployed for an entire enterprise spanning multiple organizations.


Enterprise Audit Data Consolidation and Lifecycle Management
-----------------------------------------------------------------------------
Native audit data provides a complete view of database activity along with full execution context irrespective of whether the statement was executed directly, through dynamic SQL, or through stored procedures.

In addition to consolidating audit data from databases, operating systems, and directories, the Audit Collection Plugin can be used to collect audit data from application tables or XML files, and transfer them to the Audit Vault Server.

Audit data from databases is automatically purged after it has been moved to the Audit Vault Server.

Audit Vault Server supports data retention policies spanning days, weeks, or years on a per source basis, making it possible to meet internal or external compliance requirements.


Deployment Flexibility and Scalability
--------------------------------------------------
Security controls can be customized with in-line monitoring and blocking on some databases and monitoring only on other databases. The Database Firewall can be deployed in-line, out-of-band, or in proxy mode to work with the available network configurations.

For monitoring remote servers, the Audit Vault Agent on the database server can forward the network traffic to the Database Firewall. Delivered as a soft appliance, a single Audit Vault Server can consolidate audit logs and firewall events from thousands of databases. Both Audit Vault Server and the Database Firewall can be configured in a HA mode for fault tolerance.


These are main components of the products, for more information visit product home page.

References:
---------------
1- Oracle Product Help.
2- All images from oracle web site.

Wednesday, December 19, 2012

Database: Oracle SQLPLUS command has vague behavior with comments.

In every project I am architecting, one of the main parts of architecture is the database architecture. Database architecture consists of developing ERD, meta-data document and finally the database script.

Database script is the organized and final set of files that allow DB administration, Testing team and Developers(runs script locally on their machines) to generate final database.

DB Scripts consist of a set of files. Each file contains related database types as separate .sql file. For example; tables has a file, triggers, types, packages, user and table space, views, and lookups ….. etc all of them has separate file.

The separation makes the final script maintainable.

Finally develop an OS (Windows, Mac, UNIX and Linux) specific script file to call all of the above described files in certain order the build final database from SQLPLUS.

One of interesting vague behavior I found while running the script is something like this:





This error "ERROR at line 1: ORA-00911: invalid character" prevents anything from being created, inserted, or compiled successfully.

To not fall in error like this again, which is inserting anything after the semicolon, don't code with the following code forms in the script (It will work from JDeveloper or SQL Developer):
  1. DDL OR DML STATEMENTS ; -- any comment.
  2. DDL OR DML STATEMENTS ; REM any comment.
  3. DDL OR DML STATEMENTS ; /*any comment.*/
The Solution is to put any comments before the semicolon as the following:
Bad example:
----------------


Good example:
------------------

Saturday, December 8, 2012

Glassfish3+ & ADF 11g: Developing ADF apps on Glassfish using Jdeveloper 11g

There was no opportunity before to develop an Oracle ADF (Application Development Framework) applications on any open source application server such as Tomcat, or Glassfish, while Glassfish is the Oracle reference implementation now for JEE specifications. The only way is to develop on Oracle Weblogic application server. Even using oracle enterprise pack (OEPE) for development on eclipse IDE.

Nowadays oracle releases the ADF essentials.With the new Oracle ADF Essentials which is offering you now the ability to deploy applications that leverage Oracle ADF on the open source Glassfish 3.1 server.

At Oracle ADF Essentials home page you can check what are supported in comparison with the full ADF library, and also there are a lot of tutorials for learning the framework.

Now will get an introduction on how to setup the development environment, then we will develop a small application using Jdeveloper 11g and deploy it on the Glassfish 3.1.2.2 application server.

  • Setting up the environment:

    1. Download the following if you don’t have any of them:ADF essential library (11.1.2.3), JDeveloper 11g (11.1.2.3.0) and Glassfish 3.1.2.2.
    2. Install Jdeveloper 11g and Glassfish server and check that everything is up and running.
    3. Once ADF essential library downloaded, we need to unzip it inside the lib folder of Glassfish domain1 (or any domain you have created) this will get you an adf-essentials.zip file.

    4. To install ADF essentials:

      1. Copy the adf-essentials.zip file into the lib(on a default windows install this would be: "C:\glassfish3\glassfish\domains\domain1\lib\ext") folder of your glassfish domain.
      2. In lib folder open command window and issue a "unzip -j adf_essentials.zip"


      3. Note: you should use "-j" option with unzip (JDK program) command or you will ends up with folders not the jar files, try it and you will see.

    5. After successful extraction of the ADF libraries to the directory. Now you can start the Glassfish server (you can start your domain by the following command inside "bin" folder of your "domain" "asadmin start-domain domain1" from command line console, wait for domain to start then you should ends up with message "Command start-domain executed successfully.").

    6. We need to configure the glassfish to work with application of ADF type:
      1. Invoke the admin console of glassfish (http://localhost:4848) and log into your admin account.
      2. Go to Configurations->Server-config->JVM Settings and choose the JVM Options tab
      3. Add the following entries:
        1. -XX:MaxPermSize=512m (note this entry should already exist so just make sure it has a big enough value)
        2. -Doracle.mds.cache=simple
    7. There is a new extension ("Glassfish 1.3" as time of writing) that allows you to start and stop an external GlassFish instance, as well as start it in debug mode (which will allow JDeveloper to remotely debug your application as it runs on the server. Also a button that will invoke the web admin console of Glassfish.

    8. After installing Jdeveloper, open it, the extension is available from help->check for updates, or you can download it directly from here, and then use help->check for updates pointing to the local zip file (Thanks Shay Shmeltzer's who developed this extension).

    9. After the Jdeveloper finished download and the installation of the extension, you should find 4 glassfish buttons in the menu.


    10. Go to Tools -> Preferences -> Glassfish Preferences, here you can configure the glassfish paths and configurations you like.

  • Developing and deploying the ADF application:

    1. Creating and configuring the application to work with Glassfish:

      1. In JDeveloper choose File -> new, the New Gallery window will pop up, from right hand menu choose General-> Applications, and then from left hand choose Fusion Web Application.


      2. After successful application creation.
      3. Go into the project properties of your viewController project, under the deployment section click to edit the deployment profile that is defined there.
      4. Go to Platform and choose Glassfish 3.1 from the drop down list. Click ok to go back to your project properties.
      5. Under Java EE Application section in project properties change the Java EE web application name and context to the same value "ADFGF" (for ease of access when deploy the application).
      6. Go to Application -> Application Properties-> Deployment
      7. Go to Platform and choose Glassfish 3.1 from the drop down list. Click ok to go back to your project.
      8. This step will make sure that JDeveloper will automatically add the necessary ADF libraries to the EAR file that is being generated for deployment on Glassfish.

    2. Developing and Deploying the application:

      1. Right click on viewController project and choose new.
      2. Under Web Tier -> JSF/Facelets -> Page -> Ok.
      3. File name: TestADFGF.jsf, under the managed bean tab name: testADFGF leave the others with default values. Click ok.
      4. The page will be opened in visual editor.
      5. Drag and drop any components you like as a command button, check box, choose date and choose color component.
      6. We need to create application server connection.
      7. Start the application server from glassfish start icon in the JDeveloper menu.
      8. From Application servers Navigator, right click on application servers -> new. From New Gallery windows choose General-> Connections -> Application Server Connection -> ok.
      9. In the new windows Connection name: Glassfish3122, type: Glassfish 3.1 next.
      10. Provide your application server username and password then next.
      11. Configure your ports and host name, next.
      12. In the final step with glassfish running hit test connection button and the four testing steps should succeed.
      13. Go to your Application->Deploy and deploy either to an EAR file or directly to a Glassfish server connection that you created.
      14. After successful deployment you should get the following message:
      15. Open you browser and type the following URL (http://localhost:9090/ADFGF/faces/TestADFGF.jsf), you should see the following result:
      16. Things should just work, but if they don't then look up the server.log in the log directory and check out what error is in there.

Congratulations, you did it, now you are have the capabilities to develop any JSF/ADF applications from JDeveloper and host it on Glassfish 3.1.2.2.

Glassfish 3.1.2.2: The server exited prematurely with exit code 0

While I am issuing the following command "asadmin start-domain domain1" which yields running the glassfish 3.1.2.2 application server, after the following message "Waiting for domain1 to start ....." I have got the following error after a long time of …………….:

I was wandering what is the cause of this error; I have tried 4 times but failed with the same error, I decided to delete the old domain and create a new once, but before going to this panic way, after investigation of what is the last thing I did on my machine that might cause this error, I found that I have installed Oracle XE 11g edition which takes the same port 8080 and it was up and running.

I have stopped all the database services and tried to start the Glassfish again but this time it succeeds to run. The problem is that the glassfish port was registered by oracle database, but the error was vague and misleading somehow.

Finally I have changed my glassfish ports settings from admin console.


Friday, December 7, 2012

Database: How to uninstall Oracle database 11g Enterprise edition?

I wanted to work on database 11g XE release 1 instead of 10g for evaluating the new features, especially those ones introduced in PL/SQL, but the main problem is from 5 months I tried to install XE on windows 7 x64 bit and oracle release only x86 bit version, and when I tried to install it I have got an error indicating that a registry key file is not located and installation doesn't continue, after a while I have downloaded Oracle database 11g release 2 enterprise edition and install it, but with the time I have found that it tooks a lot of memory and disk space on my local development laptop.

Today I have downloaded and installed the express edition 11g release 2 for small foot print in memory and disk as well, the installation goes successfully this time even the error raised but this time the installation continues till the end. After successful installation of XE edition I decided to remove the enterprise one.

By the way when check uninstall program tool in windows control panel, you will not find any installation entry for enterprise edition, for xe version only.

By convenience Oracle remove its database when you run the installer again and choose to remove the installed version from there, but with 11g the story is totally different this option isn't there! Oh then how to uninstall the database?

After some search in my local oracle installation home directory I have found the solution and here is it:
  1. Navigate for your oracle home directory on the path it was installed for example "C:\Oracle\database\product\11.2.0\dbhome_1\deinstall".
  2. Inside the de-install folder right click on "deinstall.bat" run as Administrator.
  3. Wait till the tool runs and you should be asked about the version you want to de-install.
  4. Select your option and hit enter.
  5. Then you will be asked about the single listener list to be de-configured just hit enter key.
  6. Then you will be asked on database names to be also de-configured type all and hit enter.
  7. You will see message indicating that the database cleaning is in progress.
  8. After a while the tool will give you some checks and confirms that you would like to continue removing the database, type "y" and hit enter.
  9. After some minutes, all services should be removed and all major product folders will be deleted, if there are still any remaining folders, indeed you can delete it safely.
  10. Congratulation you are done.

Friday, November 23, 2012

JDK7: Part 2- The power of java 7 NIO.2 (JSR 203) (Code Examples)

Get educated with the new file I/O mechanism introduced in the JDK 7 release.

In Part 1 I introduced the important concepts about new JSR 203 shipped and delivered with the latest release of Java development kit 7.

Here I am covering the important aspects involved in developing NIO.2-based applications by examples and case studies for the concepts introduced in part 1, this will spice up your Java 7 applications with the new I/O capabilities. You will learn to develop NIO.2 applications, beginning with simple but essential stuff and gradually moving on to complex features such as sockets and asynchronous channels.

In this second part I shipped it with fully coding examples for the following topics:
  1. Working with the new Path Class.
  2. Metadata File Attributes.
  3. Working with Symbolic and Hard Links.
  4. New API for Files and Directories.
  5. The FileVisitor Interface.
  6. Monitoring via Watch Service API.
  7. New powerful Random Access Files.
  8. Networking with the Sockets APIs.
  9. The Asynchronous Channel API.
  10. Production tips.
In the link below find the code as Netbeans project, divided into sections based on topics above, and also includes the material that guides you in details from software pre-requisite to compile and run the code, full explanation of every line of code and testing scenarios.

NIO2 project code and material.


Monday, November 19, 2012

EGJUG: "Power of Java 7 NIO.2" session in FCI-CU, Egypt

This is a free invitation for my session about The "power of Java 7 NIO.2" that will be held in Cairo university, faculty of computer science and information system FCI-CU, Egypt, at December 22/2012 from 12:00 P.M to 2:00 PM, which is managed by EGJUG(Egypt Java User Group, check the link below for more details about registration, date and place.

If you are coding with any language, in my session I am going to explore the most of I/O concepts useful for all levels and it not related to Java, I just will explore how these concepts implemented in the Java.

And If you would like to know in deep how stuff are going behind the concepts in Java, get ready for 2 days course that will give you the most of the concepts and final working project contains the reference implementation for NIO.2 examples in real world.

Go to the below link to register your seat.

looking forward to see you all my dear friends.

"Power of Java 7 NIO.2" session Facebook event page


Saturday, November 17, 2012

Mac: Alternatives to notepad++ on Mac OS X

For long time I have been working on windows platform sine first time I have touched the computer. Over the time I become in the development environment. After becoming team leader and then Systems Architect, I have reached to the point that I have a certain applications which I familiar with and know all of its features; one of the most interesting nifty notepad applications is Notepad++.

The default Notepad editor comes in very handy to quickly note down some important notes. However, the lack of potential features is realized when you are forced into the situation where you’ve to compare two text files or edit HTML document for instance. In such situations Notepad++ is a more than adequate alternative to native Notepad app.

Notepad++ is an open source project and is completely written in C++ language. Not only does it provide simple text editing option but also wide range of native add-ins and third-party plugins to make it the best Notepad alternative on Windows PC. It has a large swathe of features that makes it a developer's favorite alternative. It includes multi tab document support, easy comparison, syntax highlighting, syntax folding, document map, auto completion, macros support and many others, But how about such functionality on Mac? Is there any Notepad++ for Mac?

Recently (from 4 years) I worked on Linux and Mac, but I admired with Mac and decided to buy a Mac pro laptop, and for sure I searches for the same applications I used to use before on windows, sometimes you find and other you didn't, therefore you should get alternatives.

Since Notepad++ is not available on Mac, I will cover some of the worthy alternatives of Notepad++ for Mac.

  • TextWrangler
    TextWrangler is a powerful and richly featured tool for composing, modifying, and transforming text stored in plain-text files. and in my opinion it is a great alternative Text Editing and Manipulating, Programming, OS Platform Integration and Other Useful Features it has like Notepad++ and even more.

    The following are some of its features but not limited to those, there are more.

    Features of TextWrangler

    • Powerful single and multi-file search & replace
    • Flexible ‘grep’ style pattern-based search and replace based on PCRE (Perl-Compatible Regular Expression)
    • Sort Lines and Process Duplicate Lines commands offer grep pattern support for sorting, extracting, and handling text
    • Find Differences to compare two versions of a text file and merge the differences
    • Support for rectangular text selections
    • Built-in text transformations: Zap Gremlins, Change Case, Entab/Detab, and more
    • Open and save files in a variety of character sets, including Unicode (UTF-8 and UTF-16) files
    • Supports editing of multi-byte and Unicode text
    • Live Search for incremental, in-window searches
    • Open and save files in Mac, Unix, and Windows line-ending formats
    • Integrated support for Mac OS X’s spelling service
    • Hard or soft wrap text however you prefer
    • Quoted text rewrapper
    • Multiple Undo
    • Multiple Clipboards
    • Splittable editing windows
    • Auto-Indent

  • jEdit
    jEdit is written in Java, so it virtually runs on any OS out there including Mac OS. There are already few paid text editors or advanced editors available on Mac, but unlike other jEdit is a free open source project. This is the best alternative available on Mac.

    Features of jEdit
    • Built on Java
    • Unlimited undos/ redos
    • Syntax highlighting for more than 200 languages
    • Auto indent
    • Plugin repository with more than 200 plugins
    • Word wrap
    • Kill ring
    • Open any number of files simultaneously
    • File system browser
    • and more

  • Editra
    Editra, an open source program build using wxWidgets supports major platform like Windows, Mac and Linux. It supports over 60 programming language and has all the features users crave to have in their favorite editor. The project is in early stage of development so you may encounter few hiccups during your journey. Editra is visually appealing editor which comes with icons themes and loads of plugins.

    Editra could be the next big thing in code and text editor segment. Here are some of the features of Editra.

    Editra Features
    • Supports over 60 programming language
    • Syntax highlighting
    • Code folding
    • Auto completion
    • Auto indent
    • Drag and drop feature
    • Export to HTML/LaTeX/ RTF and other formats
    • File history
    • Multilingual interface
    • Undo/ Redo
    • Tabbed windows
    • Plugins supports
    • and more

In my opinion it is arguably the best Notepad++ alternative on Mac. The community is extremely supportive and active.

Saturday, November 3, 2012

ADF: JSF- ADF Backing beans life cycle

Backing (also referred to as managed) beans are Java beans referenced by JSF pages in an ADF Fusion web application through Expression Language (EL). They are usually dedicated to providing specific functionality to the corresponding page.

They are part of the ViewController layer in the Model-View-Controller architecture. Depending on their persistence in memory throughout the lifetime of the application, managed beans are categorized based on their scope: from request (minimal persistence in memory for the specific user request only) to application (maximum persistence in memory for the duration of the application).

They can also exist in any of the session, view, pageFlow, and backingBean scopes.

Managed bean definitions can be added to any of the following ADF Fusion web application configuration files:
  • faces-config.xml:
    The JSF configuration file. It is searched first by the ADF framework for managed bean definitions. All scopes can be defined, except for view, backingBean, and pageFlow scopes, which are ADF-specifc.

  • adfc-config.xml:
    The unbounded task flow definition file. Managed beans of any scope may be defined in this file. It is searched after the faces-config.xml JSF configuration file.

  • Specific task flow definition file:
    In this file, the managed bean definitions are accessed only by the specific task flow.

Additionally, if you are using Facelets, you can register a backing bean using annotations.

Many times I see people called it Baking, it is "Backing not Baking".

Friday, November 2, 2012

Saying: Failure is my key to success........

Failure is the first step to your success, and believe me you should watch every chance you got it. Study it well and see what is good you did to keep and enhance it, and what is bad and missed to neglect and improve it in your second try.

No success without a lot of work, doing your best, is not a success, and God will never waste your hard work. (this is what he says, "Great God")

one of my experience and very hard lessons, which I exposed to it from life, taught me this hardly.

Thanks God.

Thursday, October 18, 2012

Weblogic: Enable JPA 2 on WebLogic Server Version: 10.3.5.0

I worked on JDeveloper 11.1.2.2.0 then 11.1.2.3.0 but the two versions bundled with Weblogic Server Version 11g (10.3.5.0).

I decided to work with JPA version 2, but when you use the eclipselink_v2 and use specific features in the API that is related to version 2, you will get the following error:

After a while I found a work around to enable the JPA2 on Weblogic Server Version 11g (10.3.5.0).

Follow the following steps and the server will be happy with the JPA2:
  1. Stop the Weblogic server if it is running.

  2. Navigate to <%SERVER_INSTALLATION_PATH%>\wlserver_10.3\common\bin

  3. Edit commEnv.cmd

  4. Search for the line 'set JAVA_USE_64BIT=false'.

  5. Add the following line under it

    set PRE_CLASSPATH=%MODULES_DIR%\javax.persistence_1.0.0.0_2-0-0.jar;%MODULES_DIR%\com.oracle.jpa2support_1.0.0.0_2-0.jar

  6. Start the server

  7. Test your JPA2 implementation and the server should be happy now.

Tuesday, October 9, 2012

JavaOne 2012: NIO.2 Session and HOL lab announced at Oracle sites

Here is the links for CON2718 - The Power of Java 7 NIO.2, and HOL2846 - The Power of Java 7 NIO.2 by Example, materials, media and presentations for the conference sessions.

Here is the links
--------------------
1- The announced blog entry: JavaOne 2012 - The Power of Java 7 NIO.2

2- The CON2718 - The Power of Java 7 NIO.2 media and presentation.

3- The HOL2846 - The Power of Java 7 NIO.2 by Example, material and instruction documents.

Thursday, October 4, 2012

JavaOne 2012: HOL 2846-NIO2 code and material

First of all I would like to thank all attendees for their attendance to my session and HOL.

It was not easy day, there was a lot of pepole from all over the world attending the session & HOL, so I hope that all of you get what you want and finds the session and HOL lab useful to.

For session presentation and also HOL lab document they will be published by oracle after the conference ends.

And based on requests for the HOL "code and material" please find the following link contains:

1- the project source code.
2- HOL material and instructions documents.

If there are any questions you are welcome by comments or mail.

Link: JavaOne 2012: HOL 2846-NIO2 code and material


Friday, September 28, 2012

Apple: iPhone 5 comparing to iPhone 4s after trial in App Store SF, CA.

I have seen the "iPhone 5" and try it hardly in Apple San Francisco retail store, but i didn't admire with it i did't feel the Wow, In my comparing with iPhone 4s there is no difference between them except few things:
  1. Bigger screen 4" instead of 3.5" which is not the big deal.

  2. Processor A6 instead A5.

  3. Lighter than 4s by 40 Gm.

  4. All software features are in iOS 6 are the same for both phones.

  5. New EarPods witch could be bought separately and works with 4s.

lastly front camera is 1.4 m instead of VGA in 4s.

for me those changes is not the big deal that makes me changing my mind to buy iPhone 5.

Saturday, September 22, 2012

JDeveloper: Ability to perform ODL log analysis

A possibly lesser known feature of JDeveloper is its ability to perform ODL(Oracle Diagnostic Log) log analysis, known as the Oracle Diagnostic Log Analyzer.

This feature allows you to open a diagnostics log file (or use the log file currently in the Log window in JDeveloper) and do a limited yet useful log analysis. For the Standalone WebLogic Server, diagnostics log files are produced by applications running on the specific WebLogic Server instance.

The log files are produced and saved by WebLogic in a directory configured by the WebLogic administrator. This directory defaults to the logs directory under the servers directory for the specific server instance; that is, for a server instance called ManagedServer1 they can be found in servers/ManagedServer1/logs.

The servers directory is located under the specific domain directory. In this blog, we will see how to analyze a diagnostics log produced when running an ADF Fusion web application on a Standalone WebLogic Server. Alternatively, you can run the application in JDeveloper and analyze the log produced in the Log window.

Getting ready
-----------------
You will need a Standalone WebLogic Server domain configured and started. You will also need your Fusion web application deployed to the Standalone WebLogic Server.

How to do it…
-----------------
  1. Run the application deployed on the Standalone WebLogic Server, so that a diagnostics log file is generated. Alternatively, if you already have a diagnostics log file to analyze, you can ignore this step.

  2. In JDeveloper, select Tools | Oracle Diagnostic Log Analyzer from the main menu.


  3. Click on the Browse Log Files button (the search icon) to locate the diagnostics file and open it.

  4. Click on the By Log Message tab and specify the search criteria in the Search section. Press the Search button to commence with the search.


  5. In the Results table, click on a value inside the Related column for a log entry of interest and select Related By Request from the context menu.


How it works…
---------------------
Steps 1 through 5 give the details of the process of analyzing a diagnostics log file using the Oracle Diagnostics Log Analyzer feature in JDeveloper.

The Oracle Diagnostics Analyzer is accessible via the Tools | Oracle Diagnostic Log Analyzer menu selection. Once started, you will need to load the specific diagnostics log file to analyze. We have done this in step 3.

You can search the diagnostics log entries using either the By ADF Request or the By Log Message tab and specifying the search criteria. The By ADF Request tab will display only the log entries related to ADF requests made when a page is submitted.

On the other hand the By Log Message tab will search all log entries in the log file by their log level. Moreover, the search criteria in both tabs allow you to search for diagnostic log entries based on their Log Time and based on the message content (Message Id, User, Application, Module, and so on).

The results of the search are displayed in the Results table. The results data are sortable by clicking on the column headers. To display all related log entries, click inside the Related column for a log entry of interest and select any of the choices available in the context menu.

These choices are:
  1. Time:
    Filter diagnostic log entries to view all log entries leading up to the specific entry. You can refine the time before the entry using the dropdown.

  2. Request:
    Filter diagnostic log entries to view all log entries for the same web request.

  3. ADF Request:
    Switches to the By ADF Request tab to display the diagnostic log entries in a hierarchical arrangement to show their execution dependencies.

Tuesday, September 18, 2012

JDK7: When Using the SecureDirectoryStream class

The java.nio.file package's SecureDirectoryStream class is designed to be used with applications that depend on tighter security than that provided by other IO classes.

It supports race-free (sequentially consistent) operations on a directory, where the operations are performed concurrently with other applications.

This class requires support from the operating system. An instance of the class is obtained by casting the return value of the Files class' newDirectoryStream method to a SecureDirectoryStream object. If the cast fails, then the underlying operating system does not support this type of stream.

Getting ready
-----------------
To get and use a SecureDirectoryStream object:
  1. Create a Path object representing the directory of interest.

  2. Use the Files class' newDirectoryStream method, and cast the result to a SecureDirectoryStream.

  3. Use this object to affect SecureDirectoryStream operations.

How to do it
-----------------
  1. Create a new console application.
    In the main method, add the following code. We will create a Path object for the docs directory and then obtain a SecureDirectoryStream object for it.
    This will be used to view the POSIX permissions for the directory.

  2. Execute the application on a system that supports the SecureDirectoryStream class.
    The following output was obtained by running the application on an Ubuntu/Mac system:

    GROUP_EXECUTE OWNER_WRITE OWNER_READ OTHERS_EXECUTE GROUP_READ OWNER_EXECUTE OTHERS_READ
How it works
-----------------
A Path object for the docs directory was obtained and then used as the argument of the Files class' newDirectoryStream method.
The result of the method was cast to a SecureDirectoryStream class. The getFileAttributeView method was then executed to obtain a view, which was used to display the POSIX file permissions for the directory.

References
---------------
1- JDK7: Part 1- The power of java 7 NIO.2 (JSR 203) (important concepts)

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.

Refrences
-----------------
  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
  1. java.io.File
    Is updated with a toPath() method that returns a java.nio.file.Path object constructed from the abstract path.

  2. java.io.FilePermission
    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>
<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.