Search This Blog

Loading...

Monday, August 26, 2013

jQuery: Loading, parsing and processing external data files, streamlined with jQuery.

Using jQuery
One of my concerns when developing mobile web applications, is the static data that should be loaded every time application is opened via web services and read from database which affects the performance of application and eat much bandwidth of user connection, especially if it large contents. One of simple and easy way to process data files is using jQuery in development, which streamlined the loading, parsing and manipulating the data files on client side.

In my previous article "Why not jQuery? it is Fast, powerful, cross browsers and easy to use framework.", I have introduced and described how to use jQuery in development and how it make easy to traverse, apply (CSS, effects), and binds actions to DOM element. While in this article, I will explain loading data from external files for more processing, so let us get started.

Loading external data files
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.

Example html file structure:

Loading text Data:
To load a file with jQuery, you use the get function. jQuery.get() needs at least two parameters: the URL you want to load and the function to which you want jQuery to send the results to be handled. Here is a simple example for loading a text file:

The URL I have provided ("Data/Data.txt") is just the name of a file, which resides in Data folder. In this case, the file is text, but it could be a bit of HTML code or another type of content (XML or JSON).

Text data file contents:

Code:

Note:Every ".append("<rb />");" should be ".append("<br />");".

Final results:
Text Data Contents:
My Name is Mohamed Taman.
I am Systems Architect And Design Supervisor.
A JCP member, Speaker, Consultant, and Trainer.
Also I am Photographer

Loading & parsing XML or HTML Data:
The single principle behind jQuery is to write less code. The hard work is left to the library. When it comes to fetching and parsing XML, jQuery keeps things predictably simple.

Like the plain JavaScript example, we will be parsing the XML in an otherwise empty HTML file. However, in this case, we will load our XML straight from a file, which is a common situation. Make sure you have a file named data.xml containing the XML lines as the following inside Data directory:

To load and parse an XML or HTML file with jQuery, you use the get function. jQuery.get() needs at least two parameters: the URL you want to load and the function to which you want jQuery to send the results to be handled, as we did with text file. Here is a simple example for loading a xml file:

The URL I have provided ("Data/Data.xml") is just the name of a file, which resides in Data folder. In this case, the file is xml.

Code
<!doctype html>
  <html>
   <head>
   <meta charset="utf-8">
   <title>jQuery Files loading Example</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">
   </script>
   <script language="javascript" type="text/javascript">
   $(document).ready(function(e) {
  
      var spn = $('span').css("color","blue");
  
      $.get("Data/Data.xml",function(xml){
           
        spn.text("XML Data Contents:");
     
        $("child", xml).each(function(i){ 
            $('div').append(this.getAttribute("data")).append("<rb />");
        });
      });
  });
  </script>
 </head>
 <body>
  <span></span>
  <div></div>
 </body>
</html>
Final results:
XML Data Contents:
My Name is Mohamed Taman.
I am Systems Architect And Design Supervisor.
A JCP member, Speaker, Consultant, and Trainer.
Also I am Photographer

Loading & Parsing JSON Data:
You are not restricted to only loading simple files. You could include directory names or even a full URL. Whatever you load needs to be on the same domain that you are making the call on. For security reasons, browsers will not let you retrieve data from someone else’s site, even if that data is meant to be public. You can get around this by loading the file server-side and then accessing the local copy.

A special case exists that allows you to load data from another site. If the site provides JSON data and it allows you to specify a callback function in the URL, then you can load the data remotely using jQuery’s getJSON function. Here is the basic structure:

The URL I have provided ("Data/Data.json") is just the name of a file, which resides in Data folder. In this case, the file is xml.

The URL you send to the getJSON function needs to contain a question mark in place of the name of a function. Then jQuery will create a function and call your anonymous function (or named function, if you choose) from its new function.

Another way getJSON is different from get is in the type of data passed in the parameters to your callback function. Rather than the plain text returned to the URL, jQuery passes you parsed JSON in the form of a JavaScript object.

JSON data file contents

Code

Final results:
JSON Data Contents:
My Name is Mohamed Taman.
I am Systems Architect And Design Supervisor.
A JCP member, Speaker, Consultant, and Trainer.
Also I am Photographer

Conclusion
Building on top of jQuery can save you time and allow you to focus on higher-level issues with your mapping projects. You also get an added layer of complexity because you have one more piece of JavaScript to include in your HTML. Hopefully its benefits make up for this minor cost in loading time.

References
jQuery.get() method specification
jQuery.JSON() method specification
jQuery API Documentation


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.