Wednesday, December 05, 2007

Wicket HTML Table implementation

This is how you implement an html table using Wicket framework. For those of you who are new to wicket, Wicket is a component-oriented Java web application framework. It’s very different from action-/request-based frameworks like Struts, WebWork, or Spring MVC where form submission ultimately translates to a single action. In Wicket, a user action typically triggers an event on one of the form components, which in turn responds to the event through strongly typed event listeners. (See wicket.apache.org).

This example shows how you render an html table that display person's data. (e.g. first name, last name and age ).

1) First you need to define your HTML.


<form wicket:id="personListForm">
<table width="100%" border="0" >
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
<tr wicket:id="personList">
<td wicket:id="firstName">[first]</td>
<td wicket:id="lastName">[last]</td>
<td wicket:id="email">[email]</td>
</tr>
</table>
</form>



2) In your java code where you have to define the form. You will need the following:

a) Define a dataProvider - You can implement the IDataProvider interface, and define its functions. Normally, the IDataProvider is an object
that has access to your backend service.

b) Define a model - You can implement IModel, or you can use the subclasses available. ContactDetachableModel, DetachableContactModel, StringResourceModel.
Why can't we just use the POJO directly from the backend service? Well, wicket will sometimes serialized the object to save memory when you move from one page to the other, and go back. All
object that you will need to display, have to be wrapped/implemented IModel.




//This is the POJO that you retrieve from your service.
class Person implements Serializable {
private static final long serialVersionUID = 5934872279937101444L;
private String firstName;
private String lastName;
private String email;

//access methods here.
//getters and setters not define.

}


A detachable modelin Wicket is a model that can get rid of a large portion of its state to reduce the amount of memory it takes up and to make it cheaper to serialize when replicating it in a clustered environment. When an object is in the detached state, it contains only somevery minimal nontransient state such as an object ID that can be used to reconstitute the object from a persistent data store. When a detached object is attached, some logic in the object uses this minimal state to reconstruct the full state of the object. This typically involves restoring fields from persistent storageusing a database persistence technology


//This is the Wicket Model
public class DetachablePersonModel extends LodableDechableModel {
//make it transient, so that it will not get serialized.
private transient Person person;

@Override
public Object getObject() {
return this.person;
}
...

}



public class PersonDataProvider implements IDataProvider {

public Iterator<Person> iterator(int first, int count) {
Iterator<Person> iterator = null;
iterator = getPersonService().retrieveEntirePerson(first,count);
return iterator;
}

//Your model is used here.
public IModel model(Object object) { return new DetachablePersonModel((Person)object); }

public int size() {
int size = 0;
try {
size = getPersonService().retrieveEntirePerson().size();
} catch (ServiceException e) { //implement exception here.}
return size;
}

}


c) Define a DataView - Data views aim to make it very simple to populate your repeating view from a database by utilizing IDataProvider to act as an interface between the database and the dataview.


Normally, you will implement DataView as an anonymous class, or an inner class, because the chances of reusing the class is minimal.


//define as inner class

private class PersonDataView extends DataView {

...
@Override
protected void populateItem(Item item) {
Person person = (Person) item.getModelObject();
item.setModel(new CompoundPropertyModel(person));
item.add(new Label("firstName"));
item.add(new Label("lastName"));
item.add(new Label("emal"));

}
}


3) This is how you would define it in your page.


final Form persontListForm = new Form("personListForm");
final PersonDataProvider personDataProvider = new PersonDataProvider();
final DataView personDataView = new PersonDataView("personList", personDataProvider);
personDataView.setItemsPerPage(5);
persontListForm.add(contactListDataView);



For information regarding the objects used in this example visit:

http://people.apache.org/~tobrien/wicket/apidocs/index.html


Main wicket site:

wicket.apache.org

Tuesday, November 20, 2007

JavaScript Function Closure

Coming from a C++/JAVA background, it was hard for me to assimilate the concept of Function Closure in JavaScript. Now that I understand it, I'd like to share it here with you. Seriously, it's best explained by example than description. Here's an example.


var thingsToDo = {};

function initializeThingsToDo() {
var food= {
name: "Ramen",
type: "Tokatsu"
};
thingsToDo.eat = function() {
alert("I'm going to eat: " + food.name);
}
}

//Execute
initializeThingsToDo();
thingsToDo.eat();


Okay, what did I do here? First, I created an empty (global) Object called "thingsToDo", then I added a global function called "initializeThingsToDo". Inside this function I defined food object. I referenced the global object "thingsToDo" and attached a dynamic function called "eat" in the object.

After the code definitions, I ran the global function initializeThingsToDo, and called the method thingsToDo.eat().

I know you would say that this is crazy because when I ran thingsToDo.eat(), the method uses the food object but it's already out of scope.


//Execute
initializeThingsToDo();
thingsToDo.eat(); // When this is executed,
// the food object is already out of scope!


Na ah?! Not in JavaScript. You see, when you run the code, JavaScript will create a closure to the food object. After that, it saves it in the memory. The interpreter knows that it will be used for later. (It doesn't deallocate the food object in the memory. )

The power of function closure is well executed when you use AJAX. When you define your AJAX callback function, it gets called asynchronously. It creates a closure and call the objects/functions when it's ready.

If you are not familiar with JavaScript Object and Functions, you can read these links:

Java vs. JavaScript object
JavaScript usign Prototype.js
JavaScript Function

Monday, November 05, 2007

JavaScript function/procedure using Prototype.js framework

Prior to web2.0 and AJAX, I only use javascript for front end validation and some front end calculations.

When I started using Prototype.js, I learned a lot more about javaScript, particulary with functions/procedure.

If you are a java programmer, you probably write functions the traditional way.

e.g.
function sayHello() {
return "hello there!";
}

But there's an alternative. You can define functions this way:

var sayHello = function() {
return "hello there!";
}

Here we declared a global variable called sayHello, to which we have assigned a value. The value is, in this case, an anonymous function defined using the function() keyword.

Take note, that the effect of both ways are the same. (The second one is similar to C/C++ pointer to a function. wink-wink ).

In JavaScript, a Function is a first-class object that exists in its own right, unlike the method of an object in an object-oriented language.

To give an example about Function being a first-class object, let me explain about how to call the functions.

To call a function, you would use parenthesis.
e.g.

sayHello();

if you dont put the "()" it will return a reference to a function. You use that if you want to assign another name to call your function.

var sayHelloFxn = sayHello;

How does javascript function deal with input parameters? Consider this example

var animalCreator = function(species,color) {
return { species:species, color:color }
}


I created a function that returns a object (HashMap or associative array depending on how you want to call it ). What happened if I do call it like this?

1) var whale = animalCreator("mammal" );
2) var frog = animalCreator("amphibian", "green");
3) var eagle = animalCreator("bird", "white", "bald eagle" );

You would probably think that 1) and 3) will generate error. According to the declaration of the function "animalCreator" it accepts two arguments, called species and color. It is obviously designed to be called with two arguments, but in JavaScript (and unlike Java or C/C++/C#) this is nothing more than a guideline.

For 1), since there's only one argument, the second one will be set to null. and for 3) we pass a third argument. That will simply be ignored.

Okay, so much for function call. Let me explain about function as first-class object and how function changes its context. I know its weird, but the function object itself has its own function. You can use Function.call() or Function.apply() to execute a function.
e.g.

var food = { meal:"bread and egg", drink: "green tea" };
var person = {
meal:"bacon and rice",
drink: "coffee",
eat: function () {
return "I'd like to eat " + this.meal + " and drink " + this.drink;
}
};

1) person.eat();
2) person.eat.call(food);


Here we define 2 objects (food and person). Person has a function called "eat". The first one will return:

I'd like to eat bacon and rice and drink coffee.

while the second one, since you are using call, and passing an object as an argument. The function context will use the context of food. It will return:

I'd like to eat bread and egg and drink green tea.

As you noticed, the "this" changes context. This concept is very important in javaScript, because this is unlike java and C/C++/C#.

The apply() method operates similarly, except that it expects all arguments to the function invocation to be bundled as an array that is passed in as the second argument to apply(). Subsequent arguments are ignored.

Function Closures

What is function closures?

Friday, November 02, 2007

Free Directory Assistance?

If you need a phone number of a certain establishment you normally dial 411. It cost you about $1 (depending on your cellphone carrier).

411 is old school now. There's a way to get this information (and more) for free. Call 1-800-GOOG-411 or 1-800-466-4411, and you can ask not only for the numbers, but even for address, direction, etc. You can also request to deliver it to you via SMS (text message).

Kudos to Google!

Now what are you waiting for? Try it out! and save it in your phone's contact!

Check video below for more information.

Tuesday, October 30, 2007

The Last Supper

One of the best paintings we have in this world is the "Last Supper" by Leonardo Da Vinci. The painting is about Jesus's last meal with his 12 apostles before his death. It depicts the bread and the wine and when Jesus tells his disciples, "Do this in remembrance of me", (1 Corinthians 11:23–25).

What is interesting is that Leonardo Da Vinci was a member of a hidden society called Prior of Scion (which is also related to the "Illuminati" ), and the painting has more to it than just it's religious theme.

I'm not claiming that what I'm saying here is true. (So don't judge me) It maybe just a conspiracy theory. But If you look at the painting there's actually no grail in it.

The theory explains that the grail (the holy cup) holds the blood of Jesus is the same cup that supposedly contains the blood of his crucifixion; This is seen by many as a Christian metaphor. However, many people actually believe that the grail is more than just an idea - it represents a human being that holds the child of Jesus (and possibly the merovingian blood line).

To some, the latter theory is considered blasphemy - a made up story to destroy Christianity. Whatever the real story is, we may never know. In the end, it all boils down to your beliefs and convictions.

Here's a link to a 16-billion pixel image of the last supper (worlds highest resolution). This is the only image that the Italian government allowed (and there will never be another one )

The Last Supper Painting (click me)

Sunday, October 28, 2007

Watch TV anywhere, anytime

I came across this device by Sling Media. Its called "Slingbox". SlingBox is device that you connect your cable/satellite and your internet connection, and it streams the signal to your computer or mobile phone. So technically, you can watch your favorite TV show to your computer anytime, anywhere and its live!

What do you need?

1) Broadband cable or DSL high-speed Internet connection (Minimum Upstream Network Speed of 256 kbps);
2) Home Network Router;
3) If your TV cable connection is located in a different place than your Internet connection, you will also need a SlingLink or Ethernet bridge, which brings network connectivity to any electrical outlet;
4) Windows or Mac based PC and/or a Windows Mobile or Palm OS Powered PDA or phone with a 3G Data Connection or WiFi for your remote TV viewing.

What solution can it provide you? Well, for example, I can setup my slingbox in Japan, then if I'm abroad I can watch my favorite show live as it is broadcasted live. Another advantage of Slingbox is that, it has no monthly fee.

So, if you are subscribing to some cable company like TFC (The Filipino Channel), you can save a lot of money if you use Slingbox, that is assuming that you have internet connection and computer.

Slingbox site:
http://www.slingmedia.com/go/slingbox-pro

Thursday, October 25, 2007

Javascript using Prototype.js framework

Prototype is a JavaScript Framework that aims to ease development of dynamic web applications. One of the objects they provided is the class object. Class is object for class-based OOP. (You can learn more about Prototype.js in Prototype.org )

In my last post, I explained the difference between javascript object and java object. Now, I will explain how to define a class with the use of Prototype.js.

To use Prototype, first you must include the framework. You can either download the prototype.js file or reference from it directly, like this:

&lt;script type="text/javascript" src="http://www.prototypejs.org/assets/2007/6/20/prototype.js">&lt;/script>

Prototype’s Class object contains a single useful helper method which is create(), that allows us to move the body of the constructor into the prototype definition. (No need to specify the prototype directly, like what I did in prev post.)

The create() method does this for us by defining a constructor automatically that delegates to an initialize() method, which we then define manually.


var AnimalObj = Class.create();

AnimalObj.prototype = {

initialize:function() {
this.sound = "grr!";
},
playSound: function() {
alert(this.sound);
}
}


With prototype, you don't need a constructor (which in javascript a public global function ). You can define everything in the initialize method it provided.

Another cool feature about Prototype.js is the Object.extend() functionality. Object.extend() copies all properties from the source to the destination object. Used by Prototype to simulate inheritance (rather statically) by copying to prototypes.

The inheritance with Object.extend() works differently if you are used to java. For example, if we want to create Horse that extends Animal. It would be like this:

      
var Horse = Class.create();

Object.extend(Horse.prototype,AnimalObj.prototype);

Object.extend(Horse.prototype, {
initialize:function() {
this.sound = "neigh!!";
}
});


Looks weird huh? Well, first you create a class. Then you extend the methods in Animal to your Horse object. Then you define your initialization. Take note that you have to use Object.extend() in defining the initialize() method, otherwise it will override your previous object.

Monday, October 22, 2007

Phishing: beware

5 of my friends have been victimized by phishing in their yahoo! instant messenger. But what is phishing really? According to wikipedia, phishing is an attempt to criminally and fraudulently acquire sensitive information, such as usernames, passwords and credit card details, by masquerading as a trustworthy entity in an electronic communication. eBay, PayPal and online banks are common targets. Phishing is typically carried out by email or instant messaging, and often directs users to enter details at a website, although phone contact has also been used. Phishing is an example of social engineering techniques used to fool users. Attempts to deal with the growing number of reported phishing incidents include legislation, user training, public awareness, and technical measures.

What damage can it do to you? Well, first is that you lose your account (in this example you lose your yahoo email ). Your private information get exposed to the hacker and your friends account can potentially be hacked as well, because the hacker will use your account to continue the phishing process. Unfortunately, this time, the hacker have trust factor, because the hacker is pretending to be you.

How to detect and prevent this?


1) Make sure never to login or put your account to any URL link that they gave. No matter how real it is. Take note, that sometimes, you will receive a fake email stating that you need to renew your password. If this happens, make sure to contact the website itself. (This actually happened to me. I received a fake Amazon email ).

2) If a friend tries to chat with you, make sure to ask your friend's information to know if its really your friend. Hacker doesn't know you, so he/she will rely on your email for information regarding you, to victimize others.

3) Always make a habit to sign-out everything you're done with your account.

Saturday, October 20, 2007

Flex & Java

Flex (particularly Flex 2 and Flex 3 ) is a development language for RIA (Rich internet application) that run cross-platform in a ubiquitous Flash Player 9. You write code using Actionscript 3.0 and XML-based language called MXML that supports the declarative programming of GUI component targeting designers.

Flex (2 and 3 ) = Actionscript 3.0 + MXML

If you are a web developer, and experienced in javascript, you will not find it hard to study FLEX.

I just started learning FLEX this year, and the application I develop are cool and easier to write.

I will post some cool examples in here once I finalize them.

The book that recommend you to read, if you want to learn FLEX are:

1) Rich Internet Application with Adobe FLEX & JAVA
2) Oreilly Essential Actionscript 3.0

Saturday, October 13, 2007

The ringnig cedar

There's this movie (based on a book) entitled As far as my feet will carry me that I watched recently that is really intriguing. The story is about a Nazi soldier POW who were sent to Russian prison camp in east Siberia, who escaped and was able to return home in Germany after 3 years.

What struck me most is the part when he was saved by a young yakuts girl, which later on he was given a ringing cedar pendant.

Actually, I never heard about ringing cedar at all, until my brother-in-law told me about it.

In Siberia, if a cedar tree is about to die ( because of old age - 300-500 years old ), the tree emits a ringing sound. The shamans believe that once you cut that tree, and take a part of it with you. The energy and oil of that wood can make you feel stronger, makes your aura colorful, than any person you meet will like you.

The ringing cedar idea is actually in the book of Vladimir Migre called "The ringing cedar series". Book 1 is called Anastasia (click the link for details). This a must read book.