July 6th, 2011  | Tags: , , , , ,

This is the second post about IOS that I am writing out. You can read the first one over here.
In this post I am going to talk about Object-C object oriented principles, such as: classes, interfaces, instance variables and methods. This is an important topic in object-c, therefore I advice you to read this post carefully.

Interfaces

As you should know, Object-C is Object Oriented. In any OO language, we can use interface implicitly or explicitly.
In Object-C the interface is implemented in a separated file with extension .h (header) and lives together with a class. To create an interface/class in XCode, simply right mouse click on Classes folder -> Add -> New File. On the new window, select Object-C class and subclass NSObject:
.
XCode is going to create two files, an interface (.h) and the class (.m).
Let’s see an interface example:

1
2
3
4
5
6
7
8
9
10
#import <Foundation/Foundation.h>
 
@interface Shape : NSObject {
@private
	NSString *color;
	CGPoint *position;
}
-(void)setColor:(NSString *)aColor;
-(void)drawShape;
@end

Let’s study the code above.
First of all, the interface has the directive @interface and ONLY on it we can create inheritance. In the example above, our interface Shape inherits from NSObject.
Note: 1 – Other languages, such as Java and C#, the inheritance occurs in the class. In Object C, only the interface has inheritance. 2 – NSObject is the most common object from Cocoa Touch Framework.
In the interface, we have the #import statement. In our example, we imported the Foundation.h interface that belongs to Cocoa framework.
Another weird behavior: Instance variables can be only defined in the interface and inside the { } signs. In our example, there are two instance variables (color and position). Also, both instance variables have the private visibility, in other words, nobody can access these variables outside of this interface/class.
Finally, the method signature is defined outside the { } signs. Our example has two methods.

Class

A class, also known as implementation in object-c, has the extension .m. It implements all methods from its interface. See the example below:

1
2
3
4
5
6
7
8
9
#import "Shape.h"
@implementation Shape
-(void)setColor:(NSString *)aColor {
	color = aColor;
}
-(void)drawShape {
	NSLog(@"Drawing a shape...");
}
@end

The implementation has the @implementation directive and imports the interface through #import “Shape.h” line. Different from other languages, if you do not implement ALL methods on the class, there will not be a compiler error.
As you can see, the class does not have the { } signs and instance variables definitions. Also, there is no inheritance. All of this behaviors are implemented in the interface.

Instance Variables

As already said, instance variables are defined in the interface and within the { } signs. Another important point here is the pointer sign (*). ALL instance variables must be defined as a pointer. Also, all instance variables go to memory HEAP when created (we’ll see how it works in this post yet).
Within the { } signs we also define the visibility. By default, the visibility is protected, but in OO, usually we define the instance variables as private and we use some methods to access those variables. If you have no idea what private, protected or public are, please, google about Object Oriented Visibility.

Methods

Certainly it is the weirdest thing in this topic. We’ve already showed two methods examples:

1
2
-(void)setColor:(NSString *)aColor;
-(void)drawShape;

The first one receives a parameter and the second has no parameter. To define a parameter for a method, we use the following syntax: method name : (parameter type) parameter name; Weird? not so far, but what about multiples parameters? Let’s see another example from a war game:

1
-(NSArray *)shipsAtPoint:(CGPoint *)bombLocation withDamage:(BOOL)damaged;

What’s the method name? How many parameters do we have? Looks like method’s name and parameters are messed up, right?. Yes, that’s right, you put the parameters inside the method name and read it directly. Thus the method’s name above is shipsAtPointWithDamage and it has two parameters.
The most languages has the full method name and then the parameters split by comma, like example below in Java:

1
public AnyObject[] shipsAtPointWithDamage(CGPoint point, Boolean damaged);

What about four parameters?

1
2
3
4
-(void)splitViewController:(UISplitViewController *) svc 
	willHideViewController:(UIViewController *) aViewController 
	withBarButtonItem:(UIBarButtonItem *) barButtonItem 
	forPopoverController:(UIPopoverController *) popoverController;

Man, that’s really weird. Honestly, I did not get used with this syntax yet.
Finally, let’s talk about the minus sign.
Minus sign means that the methods are instance methods, in other words, it can access the instance variables. Plus means that the methods are class methods. It cannot access instance variables. Usually used for global methods. You do not need a class instance to access it (Similar, but not identical, to static in Java).

Instantiating a Class

Probably you already heard this phrase: Object is a class instantiated. But how can we instantiate a class in object-c?
Usually we use a couple of methods: alloc and init. See example below:

1
shape = [[Shape alloc] init];

Do not worry about [ ] yet. Just see the alloc and init methods. To create an object, we must alloc it in the HEAP memory. It is done through the alloc message. Also, we need to initiate it. It is done through a method that starts with the first four letters “init”. It’s common see an init method called: initWithAnyValue…
Init works like constructor of languages such as Java and C#.

Sending message to a method

Unlike Java or plain C, Objective-C works with messages. You don’t invoke a method on an object, instead, you send a message to it (like the Ruby language). Supposing our example SHAPE, we have the object shape (it’s the receiver) and we want to send a message to it to draw something (remember, we’ve got a draw method).

[shape drawShape];

You send messages inside the brackets [ ].
What about the code below?

[shape transform]

We do not have the method transform, so we’ll get a compiler error, right? No, because we are not invoking a method to an object, we are sending a message to an object (or receiver). In this case, the message is “transform”, but we do not have the transform method, thus, the compiler will show up a warning, but not an error. (carefully with this behavior).

Hands on

Let’s create a simple example to practice the class creation, inheritance, instance variables and method. Actually, I’m not going to show up step-by-step, instead, I’m going to tell you what the exercise is and you’ll do it yourself alone (hopefully). In the end of this topic, there’s a link to download the exercise done. (Promise that you’ll download the exercise just for conference).
The exercise looks simple. First: create more two classes (Circle and Rectangle) that inherits from Shape. Both classes must implement the drawShape method and print out the string “Circle or Rectangle”, also, first print out the content of the drawShape from superclass. To print out a content, use the NSLog method like the drawShape example.
Note: To call a method in the superclass, send a message to it using [super drawShape];
Create an User Interface that has two buttons (Circle and Rectangle). Each on acts a different method on the Controller. The controller instantiates the Circle or Rectangle class and call the drawShape method.
To see the output of NSLog inside the Xcode, go to menu Run -> Console. A new window will be opened. Now, let’s get started.

Conclusion

Although there are many things to say about class, interface, instance variables and methods, I guess this topic is a good starting point. I advice you, look at Mac Developers site about these topics and read the official documentation carefully. Also, there’re many blogs on the web that talks about object-c.

The next topic we’re going to talk a little more about instance variables and methods. Actually, we’re going to talk about the @property and @synthesize directives. Also, we’re going to talk about another important concept: Dot Operation.

If you have any question, fell free to leave your comment below.

Download the exercise here.

June 27th, 2011  | Tags:

If you’re familiar with Android, probably you have already created a button on the user interface and implemented a controller method to respond to this button’s action. This can be done through the OnClickListener interface and its onClick(View) method. A example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class TesteApp extends Activity implements OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View view = findViewById(R.id.button1);
        view.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
    	//Implements the action over here.
    }
}

On line 1, we used OnClickListener interface. This interface provides us the onClick(View) method. Also, on line 6 and 7, we set up the Listener to the Button widget.
Since Android version 1.6 (API level 4), Android offers us an android:onClick UI Method. Using this approach, you do not need to implement the OnClickListener interface and also you do not need to implement the static onClick(View) method. Rather than, you can bind the android:onClick method directly to a method on the Activity. See the example below:
User Interface – main.xml

	<Button android:text="Click me" android:id="@+id/button1"
		android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="buttonPressed"></Button>

In the UI above, we set up the onClick to a method called buttonPressed.
Java class – Activity

1
2
3
4
5
6
7
8
9
10
public class TesteApp extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void buttonPressed(View v) {
    	//Implements the action over here.
    }
}

As you can see, the Activity above does not implement the OnClickListener. Also, the widget does not need to set up its Listener pragmatically. This way you write less code and your class get cleaner.

As far as I know, both ways work similar. There’s no performance issue or anything else. However the OnClickListener interface provides more methods than onClick. So, if you only need the onClick function, I advice you to use the android:onClick. If you need anything else, I advice you to implement the OnClickListener interface.

If you have any question, fell free to leave your comment below.

June 18th, 2011  | Tags: , , , , ,

If you want to build Iphone,IPad or IPod touch applications, this can be a start pointing for you.
I’m gonna write a series of posts about IOS as long as I am studying this platform. For a complete material, take a look at the apple’s developer area.
In this first post, I’m gonna show you how to get started with IOS, such as: showing the pre-requirements, downloading the tools and finally a simple example binding the User Interface (UI) and the controller (Object-c classes).

Pre Requirement

First of all, if you wanna build applications using IOS, you MUST have a MAC computer.
For coding and designing, we’re gonna use the following tools: Xcode for coding and Interface Builder for designing. Basically you can choices either Xcode 3.2.6 for free or Xcode 4.0 Free for Mac Developer or purchase it from AppStore. In both, one single download will get Xcode and Interface Builder (Xcode 4 brings Interface Builder integrated within Xcode). In this topic, I’m gonna use version 3.2.6.
Real Iphone, Ipad or IPod touch is not required, because Xcode has an emulator inside it. Furthermore, if you want to deploy your application on a real device, you must become a Mac Developer, otherwise you will test your application only on the emulator.

Concepts

IOS uses object-c as programming language. It is an OO language, but its structure looks weird for whom comes from another OO language such Java. Also, Object-C has some features similar to C and C++, such as: pointer, memory management and so on.
By default, IOS uses the Cocoa Touch Framework. It’s obvious that all my posts are gonna talk just about this framework.
IOS programming is based on MVC pattern (model – view – controller). If you have no idea what it is, please, google it.

Creating a new project

Click on Xcode icon to launch Xcode. Yo’re gonna see a splash screen like below:

Choose the “Create a new Xcode Project”. On the next screen, choose “View Based Application” and click on Choose button. For this example, I have chosen the name “Class1″ as project name.
After these steps, the Xcode will be opened and some default files created. Image below show up the Xcode interface and the project files.

For this post, we’re gonna work on in the following files: Class1ViewController.h, Class1ViewController.m and Class1ViewController.xib. Class1 is the name of my project, because of this Xcode has created the classes using this Class1* nomenclature.

Editing the interface and implementations

When you start a new application, you can start by different parts of the software. Someone prefer starting by the model, other by designing and so on. Usually I like starting by model, but for this example I’ll start by designing the UI. Thus, the first task to do is to create the objects within the Controller that will represent the UI widgets.
Our first application is gonna be really simple. There will be one TextField where the user can put his name, a button to submit an action and a label that will print the name of the user. So, let’s get started it.

Open up the Class1ViewController.h file. It is the interface file. Write the following lines of code.

#import 
 
@interface Class1ViewController : UIViewController {
	IBOutlet UITextField *fieldName;
	IBOutlet UILabel *displayName;
}
-(IBAction) submitPressed;
@end

Different from other languages, such as Java, the interface is the unique local where you can define your instance variables (inside the { }). Everything out from { } are method signature. We’re gonna talk about interface, classes, methods and attribute in another post.
In the code above, the important is to see that we have two instance variables that represent a TextField and Label from User Interface. Furthermore, there is a method called submitPressed. Note: both attributes uses pointer as well as all objects in Object-C must use too.
What about IBOutlet and IBAction? Both are empty object that Interface Build can recognize them. Without this objects, would be impossible to binding the UI widget with our controller.

Building Interface

Before implement the controller (we just coded the controller’s interface), let’s draw our interface using Interface Builder. To do that, double click on Class1Controller.xib file. Interface Builder will be launched.

As you can see, some windows are opened. The Library window contains the UI widgets. The View window is the place where you are gonna draw the interface. Class1ViewController.xib window is where the bind occurs, as well as the View Attributes window is where you can change the UI widget behavior.
Let’s create a screen using only the UITextField, UILabel and UIButton. Look at the image below:

As I said, really simple.

Binding the UI widgets and the Controller’s object

This section is the main goal of the post. If you are familiar with Android, you’re gonna see that IOS is simpler than Android for binding.
First, on Class1ViewController.xib window, click and hold the “File’s Owner” icon, hold Control button and go to the UITextField widget. A blue arrow will appear. When you release the mouse and control button, a pop-up will appear with the available options for binding. Choose the attribute “fieldName”.
Repeat the process for the UILabel “Your name is” and binding it to the attribute “displayName”.

We do not have a attribute for the Submit button, however we have a method signature. Thus, we binding a button with its action, in this case, a method.
Simply repeat the process, however clicking first in the button Submit and then go to the File’s owner.

After that, the binding between the UI and the Controller is done.

Implementing the Controller

Now it is time to implement our controller. Open up the Class1ViewController.h file and implement the method “submitPressed” like code below:

#import "Class1ViewController.h"
 
@implementation Class1ViewController
-(IBAction) submitPressed
{
	//Get the text from UIText
	NSString *yourName = [fieldName text];
	//Prepare a static phrase
	NSString *staticPhrase = @"Your name is: ";
	//Put the staticPrase + yourName in the UILabel content
	[displayName setText:[staticPhrase stringByAppendingString:yourName]];
}
@end

It is not the goal of this topic explain how object-c works, however let’s take a look at the code above.
First, only the method implementation is inside the class. As I said earlier, the attributes/instance variables stay in the interface.
NSString is the String type used in the Cocoa Touch Framework. Also, as I said, all objects use pointer.
The messages are send out through brackets ([ ]) in a object. It looks weird, but I promise, you will get used to it.
Finally, the NSString API has a lot of useful methods. Different from other languages that uses the plus sign to concatenate two strings, NSString has a method called “stringByAppendingString”. If you want to create real applications for IPhone, Ipad or Ipod touch, you MUST take a deep look at the NSString API.

Running the application

Make sure you’re using the proper emulator. For this example, we’re using IPhone. Look at the right up corner of XCode.

After that, click on “Build and Run” button and the emulator will launch. It looks a Iphone device with its features. Now, you can test your first application.

Conclusion

The major goal of this topic is to present you how to get started in IOS development. After read this topic, you will be able to create a new IPhone,Ipad,Ipod Touch application, create a simple UI and binding the widgets to the controller.
In the next post, I’ll talk more about object-c, such as: interface, class, method, attributes, messages and so on.

If you have any question, fell free to leave your comment below. I hope this topic be useful for anyone.

November 16th, 2010  | Tags: , ,

This is a short and useful link for whom wants to resize multiples images on Ubuntu. First of all, back up your images file before read/run the tips from this tutorial.

The simplest way to resize multiples files is through command line using a tool called mogrify. On Ubuntu 10.04 this tool is installed by default, however if you’re using an older version, you can install it through the command

sudo apt-get install imagemagick

After that, the command to resize multiples files is really simple:

mogrify -resize 1024 *.jpg

Of course you can use more parameters, however the command above will resize all pictures to 1024 pixels.

If you have any comment or question about this topic, fell free to leave your comment below. I hope this topic be useful for anyone else.

September 26th, 2010  | Tags: , , , ,

After a long time, I have decided to write a simple but useful post for whom is working in a WEB 2 application using PHP as script language.
Certainly you have already heard about JQuery. In this topic we’re going to show up how to use AJAX with PHP. Furthermore, we’re going to show up an example using JQuery + AJAX + PHP + JSON.

First Example – JQuery + AJAX + PHP

In the first example, we’re going to create a simple page (index.php) with a single text field and a button. When the user clicks on the button, an ajax call will be fired.
The content of the text field will be sent out to a PHP file (ajaxExample.php) and it will return the content in uppercase. Finally, the new content will be displayed in the first page (index.php).
All of those actions are going to be performed in an AJAX way. Hands on.

index.php

As said, there will be a text field and a button in the index.php. Check it out the code below:

<html>
<head>
	<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
	<h2>JQuery + AJAX + PHP - First Example</h2>
	<form>
		Name: <input type="text" name="name" id="name" /><br />
		<input type="button" id="button" value="Click me" />	
	</form>
        <div id="loading">Loading...</div>
	<div id="result" />
</body>
</html>

Nothing special on the code above. On line 3 we have added the JQuery file. Also, we have the form with the text field and the button and two DIVs: one to show the loading string and the other one to show the result. Now, go to the next step.

ajaxExample.php

This is the simplest file. Basically it gets the value from the name attribute, wait for 2 seconds and return the name in uppercase mode.

<?php
$name = $_POST['name'];
sleep(2);
echo strtoupper($name);
?>

JQuery and AJAX Code

Finally, let’s the see cool part, where the JQuery call the ajax function. Let’s see the code:

	$(function() {
		$("#loading").hide();
		$("#button").click(function() {
			$.ajax({
				type: 'POST',
				data: 'name=' + $("#name").val() ,
				url: 'ajaxExample.php',
				success: function(data) {
					$("#loading").hide();
					$("#result").text(data);
				},
				beforeSend: function() {
					$("#loading").show();
				}
			});		
		});
	});

The code above makes the ajax call. As you can see, the code is straightforward, but If you need more information about the parameters, please check the JQuery AJAX API.
Now, run the application and you’re gonna see how the code works.

If you prefer, you can download the example above here.

JSON

If you’re not familiar with JSON, please check this site out.
JQuery handles JSON usando the JSON.parse method. In the PHP side, there are two methods: encode_json and decode_json. Let’s see another example:

index.php

<html>
<head>
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript">
		$(function() {
			$("#result").hide();
			$("#json_anchor").click(function() {				
				json_call();
			});
		});	
 
		function json_call() {
			$.ajax({
				type: 'POST',
				url: 'json.php',
				success: function(data) {										
					var myObject = JSON.parse(data);
					$("#name").text(myObject.name);
					$("#age").text(myObject.age);			
					$("#result").show();		
				}
			});
		}
	</script>
</head>
<body>
	<h2>Hello JSON + PHP World</h2>
	<a href="#" id="json_anchor">Click here</a>
	<div id="result">
		<table border="0">
			<tr>
				<td width="50px"><strong>Name</strong></td>
				<td id="name"></td>		
			</tr>
			<tr>
				<td><strong>Age</strong></td>
				<td id="age"></td>		
			</tr>
		</table>
	</div>
</body>
</html>

json.php

<?php
	require_once('Customer.class.php');
	$customer = new Customer('Jair',28);
	echo json_encode($customer);
?>

See above, we’re using the json_encode method to transform an object (Customer) into a JSON object.

Customer.class.php

<?php
class Customer {
 
	public $name;
	public $age;
 
	function __construct($name, $age) {
		$this->name = $name;
		$this->age	= $age;
	}
}
?>

Running the example you’re gonna see a link. When the user clicks on the Link a table with the name and age will be displayed. This call is made by AJAX.
You can download this example here.

As you can see, use JQuery is useful for AJAX call. The biggest advance of JQuery, is that you can use JQuery with almost any language: PHP, Ruby, Java and so on. I hope this topic be useful for anyone.
If you have any question or comment, fell free to let your message below

March 13th, 2010  | Tags: , , , , , ,

This is the third part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
Part three is gonna use the same example than Part 1, but now we’re going to use the query mechanism to retrieve values from database.

Requirement

  • Understand JPA concepts – If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed – If you have another one, make sure you have the JDBC driver
  • Read Part 1 and have the database and POJO already created.

Querying strategy

The most common way to retrieve values from relational databases is through an SQL Select Query, probably you have already wrote a lot of them. JPA has this ability and much more.
Since version one, JPA allows you to retrieve values from native query, JPA-QL and NamedQuery, which uses JPA-QL. In version 2, JPA brings us another great API, Criteria API.

Native Query

Let’s get started with the most popular, but less used in JPA: Native Query.
This kind of query must be used only when you need a specific command/resource from the database. Creating many specific queries, your application is going to be dependent from the database, it can be a disadvantage.
To use the native query, simply use the createNativeQuery method from EntityManager. Let’s see the same example from part 1, but using the Native Query.

    public static void main(String[] args) {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JPAExample01PU");
        EntityManager em = emFactory.createEntityManager();
        List<Products> listProducts = em.createNativeQuery("select * from products", Products.class).getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }

The change happened on line 4. We have added the createNativeQuery method. The first parameter is the Select Query itself and the second one is the class where the result must be mapped.

JPA-QL

This is the query language for JPA. It is similar than SQL, but it uses object approach. There is a method called createQuery that returns a list of objects. See the example

List<Products> listProducts = em.createQuery("select p from Products p").getResultList();

The example above seems similar than the NativeQuery, but the biggest difference appear when you use JOIN. Supposing our Products table has a relationship with another table called Categories. We could create a JPA Query like this:

List<Products> listProducts = em.createQuery("select p from Products p inner join p.categories").getResultList();

We’re going to talk about relationship in Part 5.

NamedQuery

NamedQuery is the kind of querying that we used in part 1 of this guide. The NamedQuery is written using JPA-HQ and we use the createNamedQuery method to call it. The NamedQuery lives in the Entity class and has the annotation @NamedQuery.
If you understand JPA-QL, certainly you’ll not find any problem to use NamedQuery.

Criteria

Criteria API is the newest API in JPA 2. If you’re familiar with Hibernate, like me, certainly you liked this API in JPA 2.
As Criteria API is new, it deserves an unique post for it. Part 4 of this guide is exclusive for Criteria.

Best Practices

One of the most common question regarding querying in JPA is where to use them. The simple answer could be:

  • Native Qurery: When you need a specific command/resource from the database that a JPA-QL doesn’t offer
  • JPA-QL: When you have a static query
  • NamedQuery: When you have a static query that doesn’t change, use it instead Criteria
  • Criteria: When you have a dynamic query

This post ends here, but in the Part 4 we’re going to keep talking about querying, but we’re only talk about Criteria API.
If you have any question or comment, fell free to leave your message below. I hope this topic be useful for anyone else.

February 28th, 2010  | Tags: , , , ,

This is the second part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
Part two is gonna use the same example than Part 1, but now we’re going to work on a web environment.

Requirement

  • Understand JPA concepts – If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed – If you have another one, make sure you have the JDBC driver
  • Read Part 1 and have the database and POJO already created.

Creating the project within Netbeans

Let’s getting started through the project creation. Within Netbeans, go to File -> New Project -> Java Web -> Web Application. Choose a name, like JPAWebExample01 and Glassfish v3 as Server. On third screen, select JavaServer Faces and accept the default.

Note: don’t worry if you aren’t familiar with JSF. For this example we’ll focus on JPA only.

Creating the DataSource

Different than Stand-Alone application, in web application we could create a datasource to obtain and manage the database connection. This datasource lives in the Server, in our case, Glassfish.
Fortunately we can create it directly inside Netbeans in an easy way. Let’s do that now.
Similar than the post 1, let’s open the screen to create a entity class from the database. To do that, right mouse click on the project name and go to New -> Other -> Persistence -> Entity Classes from Database. On the new screen, you’re gonna see the Data Source field. Click on it and select New Data Source.

On the JNDI Name, fill up the field with the value jdbc/MySQL_jpatutorial. Database Connection select the previous connection you’ve done in Part 1. Click OK and the DataSource will be created.

Creating the Model and persistence.xml

After you have created the datasource, you should see the table products listed. Now, you can follow exactly the same step from Part 1 to create the persistence.xml and the model.

Creating a Manged-Bean

Our application uses JSF 2.0 and because of this we can create a Managed Bean to handle the requests coming from view. If you don’t know what Managed Bean is, think he is a Java class that handles requests from view. It is similar a Controller from MVC, but it is directly binding with the view.
In our example, the ManagedBean will obtain the EntityManager and call the NamedQuery.
To create a ManagedBean with Netbeans, follow the following steps:
Right mouse click on the project’s name New -> Other -> JavaServer Faces -> JSF Managed Bean. In the Class Name put JPATutorialBean and the Package put mbeans.

In th JPATutorialBean.java, let’s add a method called listAllProducts. The content looks like:

package mbeans;
 
import entities.Products;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
@ManagedBean(name="jpaTutorialBean")
@RequestScoped
public class JPATutorialBean {
 
    @PersistenceContext
    private EntityManager em;
 
    public void listAllProducts() {
       List<Products> listProducts = em.createNamedQuery("Products.findAll").getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }
}

The method listAllProducts has no mistery. It is similar than the first post. Simply create a named query and prints out the result. However, pay attention on the lines:

    @PersistenceContext
    private EntityManager em;

We’ve used an annotation called @PersistenceContext. Different than StandAlone application, where we had to obtain a EntityManagerFactory and after that create the EntityManager, in a web based application, the container is responsible to inject the EntityManager for us. Really simple, doesn’t it?

Editing the index.xhtml

How can we call the method listAllProducts from ManagedBean? We can do that editing the index.xhtml and creating a link to access this method. Edit the current index.xhtml and add the following:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        Hello from Facelets
        <h:form>
            <h:commandLink action="#{jpaTutorialBean.listAllProducts}">
                <h:outputText value="List All Products" />
            </h:commandLink>
        </h:form>
    </h:body>
</html>

The code above is HTML and JSF stuff. Look at the h:commandLink and you’re gonna see where we bind the link with the method. JSF also makes our life easier.

Running and Testing the code

Now all changes are done, right mouse click on the project and select the Run option. A new page is gonna be opened in your browser and then click on the link.
Look at Netbeans console and you should see an output like below:

INFO: Product: product 1
INFO: Price: 100.0
INFO: ---------------------------------------
INFO: Product: product 2
INFO: Price: 200.0
INFO: ---------------------------------------
INFO: Product: product 3
INFO: Price: 200.5
INFO: ---------------------------------------

Conclusion

Doesn’t matter if you’re in a standalone or web application, the model (entity) is gonna be the same and the code to handle the JPA also, the biggest diffrence is the way to obtain the EntityManager. In a web application, the container is responsible to inject the EntityManager for us.

In the next topic we’re going talk about the strategies to retrieve values from JPA, such as: NamedQuery (already used), JPAQL and the newest feature, Criteria.

If you have any comment or question about this post, fell free to leave your message below.

February 23rd, 2010  | Tags: , , , ,

This is the first part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
This part one is going to show up the steps to create your first application that access the database using JPA 2 (Stand alone application). Using Netbeans 6, this process is easy and takes less than five minutes.

Requirement

  • Understand JPA concepts – If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed – If you have another one, make sure you have the JDBC driver

Preparing the database

Before we get started with Netbeans, let’s prepare our database. The instructions below are regarding MySQL, but if you’re using another database, you may need to change the scripts to work out.
Firstly, connect to your database:

mysql -u root -p

Then, create the database and select it. Let’s call it as “jpatutorial”

create database jpatutorial;
use jpatutorial;

Now, run the script below. Basically it creates a table called “products” and insert three products by default.

create table products (id int not null auto_increment, description varchar(40), price double, primary key(id));
insert into products (description, price) values ('product 1',100); 
insert into products (description, price) values ('product 2',200); 
insert into products (description, price) values ('product 3',200.50);

Creating the project within Netbeans

Now the “magic” starts. Open up Netbeans and create a simple Java program called “JPAExample01″. Netbeans also creates a “Main” class for you.

Creating the Model and persistence.xml

After the project is created, right mouse click on it and go to New -> Other -> Persistence -> Entity Classes from Database. On next screen, select Database Connection -> New Database Connection and type the information from your database. After that, the table “products” should appear on the screen.

Select “products” and click on “Add” and then “Next”.
On third screen, you must create our “Persistence Unit”. Click on Create Persistence Unit… button. Now, we must select the provider we want. By default, Netbeans brings the EclipseLink, but you’re free to change it. Also, you can change the Unit name and table generation strategy, but let’s keep the default so far.

The persistence.xml file has created, now click next until the end and finish the process (you can accept all the default options).
Take a look at the Project and you’re gonna see a new folder called “META-INF” with the file persistence.xml and the file “Products.java” created.

Examining the Products.java

Usually a model is a simple POJO. With JPA, the POJO has annotations that define the primary key, columns, relationship and so on. Netbeans has already done these annotations for us. Open the Products.java and have a look.

@Entity
@Table(name = "products")
@NamedQueries({
    @NamedQuery(name = "Products.findAll", query = "SELECT p FROM Products p"),
    @NamedQuery(name = "Products.findById", query = "SELECT p FROM Products p WHERE p.id = :id"),
    @NamedQuery(name = "Products.findByDescription", query = "SELECT p FROM Products p WHERE p.description = :description"),
    @NamedQuery(name = "Products.findByPrice", query = "SELECT p FROM Products p WHERE p.price = :price")})
public class Products implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "description")
    private String description;
    @Column(name = "price")
    private Double price;

Attention: The netbeans has already generated some NamedQueries for us too, Thanks Netbeans team :)

Running and testing the JPA

To test JPA, we must a EntityManager. In a stand-alone application, to get it, we must a EntityManagerFactory. Let’s change our Main class and initialize a EntityManager and call a simple NamedQuery. The Main class looks like:

package jpaexample01;
 
import entities.Products;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
public class Main {
 
    public static void main(String[] args) {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JPAExample01PU");
        EntityManager em = emFactory.createEntityManager();
        List<Products> listProducts = em.createNamedQuery("Products.findAll").getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }
}

Pay attention on main method. We get a EntityManagerFactory, then an EntityManager, we call a NamedQuery already done and finally we iterate over the list and print out the description and price of the product.
Before run the code, you must add the JDBC driver into the project’s classpath. To do that right mouse click on the project Properties -> Libraries -> Add Library -> MySQL JDBC Driver
Now you can run the application and if everything is fine, you are gonna see in the console:

Product: product 1
Price: 100.0
---------------------------------------
Product: product 2
Price: 200.0
---------------------------------------
Product: product 3
Price: 200.5
---------------------------------------

Conclusion

As you can see, Netbeans has a great support for JPA 2. You were able to create your first application in few minutes.

This post finishes here, in the next one we are going to talk about JPA 2 in a web environment. You’re gonna see the code is similar, but the way to obtain the EntityManager is different.
If you have any comment or question about this post, fell free to leave your message below.

February 21st, 2010  | Tags: , , ,

Sun VirtualBoxVirtualMachine is a reality nowadays. If you have a base operating system (called host) and want to use another one on the base (called guest), you can use a VM to do that.
Downloading the Sun VirtualBox directly from its website.For Ubuntu, there’s a .deb file. Simply download it and double click on it install it. After that the VirtualBox is installed. Now, you can install the Operating system that you want.

Setup Ubuntu

If you have already run Sun VirtualBox, probably you notified that USB didn’t appear. It happens because you need to make some changes on Ubuntu. Let’s do that now.
First, open the terminal and type the following:

grep vboxusers /etc/group

Memorize the number that appear for you. In my example, the number is 121.

Now, go to System -> Administration -> Users and Groups. After that, click on “Change button” and enter your password.

After that, click on Manage Groups. Find and select the vboxusers and click on Properties button. On the screen, select your user and type the Group ID that you picked early.

The changes are done. Now restart the Ubuntu and in the next time you run VM, the USB are gonna appear for you.

PS: When you start the USB on guest machine, the USB port on host machine is closed and vice-versa.

This is a simple post but I hope it be helpful for anyone else. If you have any question or comment, fell free to leave your comment below.

February 12th, 2010  | Tags:

O meu último post no blog foi no dia 12 de Novembro de 2009, ou seja, exatos 3 meses sem escrever aqui.
Certamente os meses de Novembro, Dezembro e início de Janeiro foram os mais desafiadores dentro da IBM para mim. Tinhamos algumas atividades monstruosas para desenvolvermos em tempo recorde. Eu fiz o papel de liderar o time técnico e felizmente, graças ao grande trabalho do meu time (Gustavo Oliva, Victor, Gisele, Renato, Gustavo Castellano e Marcela), conseguimos atingir o objetivo com excelente qualidade.
Esse foi um dos motivos que não tive tempo para postar novidades no blog, mas isso não significa que nesse tempo eu não tenha acompanhado as novidades no mundo de TI.
Cheguei a fazer alguns exemplos do JSF 2.0 e JPA 2.0, a princípio gostei bastante de ambos. Dentro do projeto fiz algumas coisas com o Hibernate que nunca tinha feito antes, utilizei alguns design patterns que ajudaram muito no projeto, implantamos testes unitários úteis utilizando JUnit e EasyMock, enfim foram meses de pura tecnologia.
2010 começa e eu vou tentar ser mais ativo no blog. Alguns posts já estão na cabeça, mas ainda falta pique para iniciá-los. No próximo dia 22 eu tiro férias de 13 dias e isso certamente vai servir para carregar as pilhas e ter mais um ano cheio de desafios.
Uma coisa que já voltei a fazer com mais frequência é acessar o GUJ.com.br diariamente.
Esse ano vou voltar de fato estudar Ruby e Scala, duas grandes linguagens que eu abandonei um tempo atrás. Internamente na empresa será o ano de entregar o segmento 1 do projeto e também pretendo tirar a certificação interna de IT Specialist.
Enfim, 2010 será cheio de desafios, mas nós da área de TI sempre temos que arrumar tempo para estudar tecnologias novas e também compartilhar nosso conhecimento, seja através de blog, fórum, palestras, eventos, etc etc etc
Bom 2010 para todos.

TOP