Wednesday, August 21, 2013

JPA2: Forcing JPA "Query" to get fresh data Rather Than Cached data.

Problem

The default behavior of EntityManager is using cached results from a database query, and you want to force a query to be executed each time a table is loaded, rather than allowing the results of the cache to be displayed.

Especially when you are working with database stored procedures, which changes the data on database server, but when you query this data, cached one is displayed, instead of new changed data.

There was a solutions by
  1. Disabling the cache from persistence.xml or

  2. Calling EntityManagerFactory.getCache().evictAll(); method in an Interceptor, I was using this solution.

Nevertheless, these solutions works but with problem, which is the performance and bandwidth is hurt, because you load all fresh and read only data such as lookups and configuration data, from database to application.

But I need to get a fresh data instead of cached ones but for specific query, so let's dive into the solution.

Solution
After the javax.persistence.Query instance is created, set a hint, javax.persistence.cache.retrieveMode, to bypass the cache and force the query to be executed. In the following lines of code, the Book entity is queried, and the cache is bypassed by setting the hint:

Upon execution, the query will be forced to execute, returning the most current results from the underlying database table.

Working mechanism
There are often occasions when an application requires the most current table data to be displayed or used for performing a given task. For instance, if you were to write a Stock Exchange application, it would not make sense to cache the current stock results since old data would not be very useful to investors.

In such cases, it is imperative to force queries to be executed and bypass any caching. This is possible via the use of hints that can be registered with javax.persistence.Query instances.

By setting the javax.persistence.cache.retrieveMode hint to CacheRetrieveMode.BYPASS, the JPA is told to always force the execution of a query. When the query is executed, it will always return the most current results from the database.

References:
More on cache disabling mechanisms could be fund on Java EE 6 Tutorial Specifying the Cache Mode Settings to Improve Performance

Monday, August 19, 2013

Mac: How to reset your Mac OS X administrator password without a system disk.

One of my friends has faced a problem, on how to access his Macbook Air, because he did not remember the password, the following are the steps to do that.

I hope that its operating system version either Lion Or Mountain Lion, so you can reset the password without any external disk.

On Lion or Mountain Lion, you use the following technique to reset the Administrators password:
  1. Boot to your Recovery Partition, by holding down the Option key while starting, and then selecting the Recovery HD as the boot choice.

  2. Once booted, at the top of the screen is a menu ..., select Utilities --> Terminal from the menu bar.

  3. In the Terminal window, type “resetpassword” (without the quotes) and press return.

  4. A “Reset Password” window will open. Select your boot volume (your SSD (Solid State) drive) if it is not already selected.

  5. Select your administrators username from the menu labeled “Select the user account” if it is not already selected.

  6. Follow the prompts to reset the password.

  7. Restart the computer from the apple menu.

  8. Ta-Da you are done.
Note:
If you are using the Keychain, you will lose your existing one, and have to start a new one, unless you remember the old password.

If your version is older than Lion, you will absolutely need a system disk. If yours is lost, then contact Apple parts or an authorized dealer ordering for a replacement.

Conclusion:
My friend has confirmed that this method works successfully.

Wednesday, August 14, 2013

Why not jQuery? it is Fast, powerful, cross browsers and easy to use framework.

jQuery, jQuery then jQuery, yeah it simplifies the way you touch the HTML via JavaScript.

On jQuery site, its definition as the following:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
Yes, I agree totally with this statement, I make use of the JavaScript framework, jQuery. jQuery simplifies common tasks and provides a single interface to actions that are implemented inconsistently in different browsers. Perhaps the most common use of jQuery in my development is reading in files (XML, JSON, text …etc) or other data from web services, but it also make it easy for traversing the DOM and applying CCS to components in easy way.

The following section is meant to give a quick introduction to using jQuery, and making your hands dirty with code to get the idea. For advanced features of the framework, you can branch to jQuery documentation and API references.

But, wait here for a second, be patient, before you can use jQuery, you need to include it in your web page. You can do so by downloading the latest version at http://jquery.com/ or by grabbing a Google-hosted version by adding the following to the <head> section of your HTML file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
As of time of this writing, the latest version of jQuery is 2.0.3, and also there are Other CDNs could be used, and are listed on jQuery home page, I have used here Google one.

After adding the library to your page lets, get in touch with jQuery functionality and development.

Once you have included jQuery in your document, you can use its functions via two global variables: jQuery and its shorthand, $.

Demo page structure:
We will use this page in our journey, for the sake of clarity of how to use jQuery.
<head>

jQuery Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
.content
{
 padding: 20px;
 width: 200px;
 height: 200px;
 background-color: #CCC;
}

#eventInfo
{
 width: 420px;
 height: 20px;
 background-color: #000;
 color: #CCC;
 font-weight: bold;
 margin-top: 10px;
}
</style>

</head>
<body>
</body>
Query Document Objects
Among its many uses, jQuery is very helpful at quickly and easily extracting elements from your HTML page into JavaScript code. You can query by id, tag name, CSS class, or combinations of these factors. jQuery makes this task easier, so you can focus on what you want to do with those elements.

To grab a single piece of the page, such as the content <div>, you call it by its id. Much of jQuery’s syntax is borrowed from CSS, which may look familiar.

Here is how you would call an object with an id of content:
Notice:
I am using the dollar-sign shorthand. Then I add parentheses because $ is a variable and a function (jQuery stretches the bounds of JavaScript in ways that you and I probably will not). Inside the function, we pass a string with the CSS we would use to style the map div, #content.

Let us see how to add a text to this div content, just use one of the following snippets of code:
Or simple chaining one
You have now used your first jQuery function to query for a specific element and add a text to it. You can achieve the same result with JavaScript’s standard document.getElementById function, but jQuery’s method is faster to type. Plus, the result using $ allows you to chain other jQuery functions, such as visual effects, binding events or applying values and css as we have made in the previous code.

Notice:
Every jQuery function returns a jQuery object wrapping the queried element(s). Therefore, we can use the functions call-chaining mechanism, this pattern is called builder design pattern.

jQuery can also do more than just query individual elements; it can gather multiple elements in a single call. Here are a few examples:
Each of these examples shows a different type of querying—and many more are possible. You can learn about what jQuery calls selectors at http://api.jquery.com/category/selectors/.

Use jQuery to fire browser events
jQuery provides a lean way to use and fires browser events, such as clicking, double clicking or dragging. You can also react to events anywhere in the browser, and jQuery makes reacting a simple process for us.

To respond to an event, you first need to be listening for it. To do so when your page first loads, you register your intention to react to an event. You can do this by adding a JavaScript function to the onload attribute of your <body> tag. Or you can do this with a special jQuery ready event.

Although creating an event to register other events may seem counterintuitive, but believe me it works. Here is an example that waits until the page is ready:
Notice:
That the element we are querying for is a little different from in the past. Instead of a string inside the parentheses, we have inserted a standard JavaScript object, document. When enough of the page has loaded that the browser knows all the objects it contains, we call the register_events function.

That register_events function does not exist, however, so we need to write it. Or, instead, we could react to the same event with an anonymous function:
As with most anonymous functions, you usually want to keep it to just a few lines. If you have many events to register, you are probably best served with a named function.

Note
A big difference exists between using your browser’s onload attribute and jQuery’s ready event. With onload, you wait until the entire page is loaded, including images and other external files. With $(document).ready, you can run code, such as registering events and hiding objects, the moment the browser is ready. Using jQuery here often translates to a better user experience.
Now that you have waited for the browser to be ready to register other events, let us register them. Here is the basic pattern for jQuery events:
The element portion is usually a selector, such as an element’s id (though it can also be any browser object, as shown in the ready example). The event piece is the name of the function, as declared by jQuery. Finally, function is the function reference, either an anonymous function or the name of the function to call.

Here is how you would listen for a particular element to be double clicked:
If you are familiar with JavaScript events included in HTML, you might be wondering where the on, as in onDblClick, went. In jQuery, events are referenced with only the action so it is dblclick.

You can also get additional information about the event. The information available may be a little different depending on the event. Here is how you find out where the user has double-clicked on a page:
I used a dblclick event. Because we want more information about the event, I included an optional parameter e to the anonymous function. Within the function, I can use that variable to get information, such as where the user double clicked. This data comes in two pieces:

The number of pixels from the left side of the page X and the number from the top of the page Y. You can see a sampling of available events in Table 1, along with the additional information that is passed in the optional parameter to each event.

Tip: Try also to double click inside content1 div, at different location and watch how X and Y
value changes.
Table 1: Some Useful jQuery Events

Event Name

Objects Available

Additional Information

click

Any


Page location: pageX, pageY

dblclick

Any

Page location: pageX, pageY

mousemove

Any

Page location: pageX, pageY

keydown

document, window

Key code

focus

Form elements

 
Events will make your web pages much more interactive. For a full list of events (and additional event information available), see jQuery’s documentation at http://api.jquery.com/category/events/.

Insert and Hide Content

Once you have one or more elements from the page using jQuery, you need to do something to them. Here, I will show you a way to add or replace the content inside a page element. In addition, I will also demonstrate an effect that will hide the content, so later, you can make it reappear.

Let us say you want an element on your page where you can show the event information raised from previous double click event such as event type and the event source id. You can add the element with HTML using something like this:
When you are ready to add the event information, you can use jQuery to find the element and then display the event information. If you want to display the content of a variable called info, you could use this single line of jQuery:
This line will find the element on the page with the id of eventInfo and then replace its inner HTML with the value in the info variable. If you just want to add additional content to the element, use this line instead:
Alternatively, use can use chaining feature as the following.
Now the eventInfo div content will look something like this:

Event Info: Event type is: dblclick, raised from: content1

You have seen how to insert content, but what about making that same content disappear? For example, before adding the event Information, a page with just Results: without anything after it looks a bit funny. So when the page loads, run the following code to hide the results element:
Moreover, when you are ready to display the results to the user, include this code:
On the other hand, append it to the last of your chaining command as the following:
These two functions are simple (and very useful) examples of jQuery effects. Many more effects are listed on the jQuery website at http://api.jquery.com/category/effects/.

Final code


jQuery Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
.content
{
 padding: 20px;
 width: 200px;
 height: 200px;
 background-color: #CCC;
}

#eventInfo
{
 width: 420px;
 height: 20px;
 background-color: #000;
 color: #CCC;
 font-weight: bold;
 margin-top: 10px;
}
</style>
<script type="text/javascript" language="javascript">
   //Use ready function to execute all code after browser parse and build DOM tree.
   $(document).ready(function(e) {
     
  // Hideing div with id eventInfo
  $('#eventInfo').hide(); 
  
  // Setting dive text and applying css value for the text to be of color red
  $('#content').text('My name is Mohamed Taman').css('color','red').append('

');
  
   //Get the first span wrapped inside the div with css class 'content' and set its text 
  $('.content span:first').text('Number of divs in the document are: ' + $('div').length);
  
  
  // Register div with id content1 to double click event
  $('#content1').dblclick(function(e) {
        alert('I am double clicked with and event location at, X: '+ e.pageX +', and Y: '+ e.pageY);
 
  var info = 'Event type is: '+ e.type +', raised from: '+ e.target.id;

  $('#eventInfo').html('Event Info: ').append(info).show();
    });
});
</script>

<body>
</body>
Let's wrap up

By now, we have reached to the end of the article, and I hope you enjoyed and find it useful.

In the next part, I will demonstrate an important issue, which is loading and reading data files using jQuery either it is JSON or XML data files. So If you want to interact with data outside of your current HTML file, jQuery has some excellent tools for doing these sorts of Ajax calls. Though Ajax is short for Asynchronous JavaScript And XML, you can access any type of data with Ajax.

Tuesday, July 23, 2013

Web: Faulty HTML, JS, and CSS code, hurts your page Performance, Quality and Debugging.

HTML page is the core

Yes, it is the core of every web project. Therefore, it is very important to code your HTML page properly since it forms the foundation for everything else. Because it is the core of every web page, so without a solid foundation, the stuff you build upon it will easily break.

All web browsers are very forgiving and will often render a page correctly even if the HTML is slightly faulty, and your page finally will render, but you should get your attention for such behavior. I do, however, recommend that you make sure the HTML is coded properly, for a number of reasons:

  • Performance
    Correct HTML code renders faster than incorrect HTML.

    How it comes? Okay let us see, if your code done properly, the browser will interpret the HTML in strict mode, in which it assumes that you know what you are doing. Incorrectly done, and it will switch to quirks mode, in which it is a lot more forgiving in its interpretation of the code.

    This means that you can get away with sloppy code, but since the browser has to guess what you mean, the page takes longer to render.

  • Quality
    Naturally, you want to look professional, and you just don’t look good with HTML that doesn’t validate. Invalid code is the sign of a developer who doesn’t know what he’s doing.

  • Debugging

    In addition, if you don’t have the HTML right, strange errors may occur in your CSS or JavaScript that are really hard to find.

    Both the CSS and a lot of the JavaScript code relies on the HTML being correct, so to make it easier for yourself, make sure that your HTML is correct by validating it frequently.

    This will save you a lot of time and grief.

How do you know that you have a correct HTML code?

It is a simple answer, fortunately W3C (World Wide Web Consortium) provides a tool which validate your code, whether it is a live page by providing its URL, or resides on your computer by uploading the file or past the code.

You will find this validator at W3C markup validation service.

Also your browsers are bundled with validation and inspection tools such as developer tools, alongside a bunch of extensions you can add to your browser for validation process.

Some of Firefox browser tools:

  1. Page Validator: https://addons.mozilla.org/en-US/firefox/addon/2250
  2. Html Validator: https://addons.mozilla.org/en-US/firefox/addon/249
  3. Web Developer Toolbar: https://addons.mozilla.org/en-US/firefox/addon/60

With these tools at your disposal, you are more than ready to get started.


Thursday, July 18, 2013

Oracle: Feel the fun of Oracle Weblogic & JDeveloper 12c on Mac OS X

Oracle fusion middleware 12c stack is now completed and ready for use and supports cloud platform technology stack. The story Begins by releasing Oracle Weblogic 12c last year 2012, then followed by Oracle database 12c this year 2013, and by this month of July the development IDE JDeveloper 12c (2.1.2.0.0) has been released.

WebLogic 12.1.2 is now available. Moreover, is also bundled with the new JDeveloper 12c. WebLogic 12.1.2 comes in two flavors one of size 179MB zip distribution offers Java EE 6 Full Profile development and includes WebLogic Server and Coherence. The generic installer also includes WebLogic Server and Coherence and is patchable via OPatch.

There are two interesting supported components available in WebLogic 12.1.2 out of the box, that already part of JEE 7, one of them is the Websockets protocol support, and the other is JSON Binding via EclipseLink 2.4.2 MOXy's JSON-binding.

JDeveloper 12c comes with a big bunch of enhancements and technology support, one of interesting components is the support for Java EE and Web Development as the following:

  • Java EE 6 Support: JDeveloper wizards and editors have been updated to work with Java EE 6 specifications, including EJB 3.1, Servlet 3.0, CDI, JPA 2.0, EL 2.2, and more.
  • EJB 3.1 Support: JDeveloper provides support for new EJB 3.1 features including:
    • Singleton Session Bean
    • Simplified No Interface Client View
    • Asynchronous Session Bean Invocations
  • TopLink/JPA 2.0:
    • TopLink supports the following JPA 2.0 features:
    • JPA 2.0 project type and JPA 2.0 persistence unit properties
    • Delimited and derived identifiers
    • Mixed access
    • Unidirectional one-to-many mappings
    • Validation mode
    • Element collection
    • Embeddable mapping
  • HTML5, MathML and CSS3 Support: Updated editors for working with latest HTML5 and CSS3 content.
  • CSS editor: Added ability to invoke Quick doc feature for CSS properties and skinning keys, and other editor improvements.
  • JSP to Facelets conversion: User may optionally choose to convert a project's JSP/JSPX content to Facelets.

For more about all new features of JDeveloper 12c, visit what's new in JDeveloper 12c.

The new abbreviation that sticks to the version 12c (is c for Cloud),and it means that the JDeveloper is an enabled Cloud development IDE.

One of the most interesting features of the JDeveloper 12c that worthwhile is its installer, it is very easy to install and runs on mac OS X operating system rather than its previous 11g versions series, avoiding much of boilerplate system configurations to just install it.

So let's see how we can install it on Mac OS, but first let us get the required software to complete the installation process successfully.

Pre-requests software:

  1. Java Development kit 7 update 25+ or less, it is a critical piece of software that allows the installer to pass the prerequisites successfully. It could be downloaded from here.
  2. Download the JDeveloper 12c Generic installer the works on all platforms (it is a jar package).

That's all; let's now go through the installation process.

Installation process
  1. First open your terminal, and type the following command:

    You should make sure that your java version is version 7 pointed out in your system class path, if version is different, you should make your system class path includes the java 7 version.

    If everything is okay then you will see output like the following:


  2. From the same terminal, change your directory to your JDeveloper downloaded jar file, for example I have downloaded the jar file inside a folder named “Oracle JDeveloper 12c (12.1.2.0.0) (Build 6668)” on my mac desktop. To begin installing the JDeveloper issue the following commands:

    Then followed by:

    If everything is going okay then you should see the following output:


    Then the following screen will popped up, and the installation process begins. Choose your inventory, which will, includes your JDeveloper system preferences folder, and OS group permission. I have changed it from stuff to be everyone, and clicked Ok button.(This screen will appear only on mac OS, but if you are using windows OS, the wizard will pop up for the installation and the process will begin from the next step):


  3. On the next screens “Oracle JDeveloper studio installer”, it includes five wizard steps, click next on each of them till finishing the installation, and seeing the following screen:


  4. Click next and the summary page comes with all installation log, including three options as in the following figure, for me I have choose the first option.

  5. Click finish and JDeveloper will start with new splash screen as the following:


  6. After splash screen finished preparing JDeveloper components, the main IDE should open with a new and neat look and feel:


  7. From Tools menu item, click check for update menu, you can make your new JDeveloper 12c, most updated with required components, one of recommended components is jUnit component.


  8. After finished the updates, we need to create a default domain of Weblogic 12.1.2 bundled server, from run menu click "Start server instance":


  9. The Weblogic configuration dialog will appears to provide password, and other configurations:


  10. Click Ok button and the JDeveloper log, will contains all creation and running conversation entries, wait till you find your log ends with the following entries:

Hence, we are here, than we have finished the installation process of JDeveloper 12c, and created a Weblogic 12c domain, so you can rock and give your hand the touch of JEE6 on the new release.

Happy coding :)