Showing posts with label Naked Objects. Show all posts
Showing posts with label Naked Objects. Show all posts

Friday, November 12, 2010

Naked Objects Templates in NetBeans

Within the Naked Objects distribution you can find some Eclipse code templates that can speed up your work. Of course also in NetBeans you can have code templates, but I didn't know (and still don't) how to transform the lowercase property in a camel-case get or set method. After envying the Eclipse users for a while I decided to give it a try myself. I was quite deluded, as neither the Eclipse templates allow you to do it. This pushed me to implement the templates myself, and obviously to share my results.

The very first template is probably nop, which stands for Naked Objects Property. This basically creates a property with its setter and (annotated with @MemberOrder) getter. The problem is that I like to keep fields separated from setters and getters, so a template was not the best solution (at least not for me). The nop templates was then replaced with the ready-made ALT+INS, Add Property...


This opens a form that lets you specify the property name, type, and tweak the rest of the generated code a little bit.

And so much for the first template, as all I still need to do is to manually add the @MemberOrder annotation on the getter (but the autocompletion feature is of great help, as a simple @Mem followed by CTRL+space is normally enough).

To create a new code template you have to click on the Tools menu, select the Options item, and when the form opens click on the Code templates tab:


A click on the New button, some clickety clackety and a click on the OK button and there you have it: a brand new template all for you. The templates I've created so far:
  • noft (Naked Objects Factory Transient)
/** Creates a new transient ${Type} */
public ${Type} new${Type}(){
${Type} ${instance} = newTransientInstance(${Type}.class);
return ${instance};
}
  • noidicon (Naked Objects Identification Icon)
/** The name of the icon that represents the object */
public String iconName(){
return "${iconName}";
}
  • noidtitle (Naked Objects Identification Title)
/** A description of the object */
public String title(){
TitleBuffer buf = new TitleBuffer();
// TODO add properties
${cursor}
return buf.toString();
}
Note the use of the reserved ${cursor} property that positions the cursor where you are supposed to add your custom code.
  • nopval (Naked Objects Property Validation)
/** Validation for property ${property} */
public String validate${Property}(${Type} ${value}){
if ((${value} == null)) {
return null;
}
// TODO implement imperative rule
${cursor}
return null;
}
Last but not least
  • nopval (Naked Objects Property Validation)
/** Find all ${TypePlural} */
@Exploration
public List<${Type}> findAll${TypePlural}(){
return allInstances(${Type}.class);
}

I'm sure I can do better than this, e.g. there should be a way to automatically fix imports without the need for me to hit SHIFT+CTRL+I - which, anyway, is not all that work, moreover I'm more than used to combine it with ALT+SHIFT+F to format code and CTRL+S to save whenever I type something.

As with all code templates, use the Tab key to switch from a variable to the next one and hit Enter when you're done.

Maybe more on this will follow.

Saturday, April 17, 2010

Joda Time vs java.sql.Date

As Naked Objects does not (yet) support the Joda Time library, I'm using plain old java.sql.Date to model dates in a prototype I'm working on. I'm not used to it anymore, and that's awful. As an example, let's suppose we have to create an entity with two Date properties, say creationDate and dueDate: the former is asked to the Clock class from the app library, and the latter is derived adding two working days to the former one. For the sake of simplicity, let's only consider adding two days, regardless of the fact that they are working days or not (you always can take it as an exercise).


Calendar cal = Clock.getTimeAsCalendar();
Date creationDate = new Date(cal.getTimeInMillis());
cal.add(Calendar.DAY_OF_MONTH, 1);
Date dueDate = new Date(cal.getTimeInMillis());

Now, with Joda Time I would just write


LocalDate creationDate = new LocalDate(Clock.getTime());
LocalDate dueDate = creationDate.plusDays(2);

Does it compare to the traditional Date and Calendar approach? I think it doesn't...Moreover, should Joda Time be supported, we could also ask for a factory method:

LocalDate creationDate = Clock.getLocalDate;

Saturday, April 3, 2010

A faster start for your Naked Objects app

After discovering how to generate a Naked Object application in NetBeans with Maven I played with my freshly created project a little, as the way I suggested to start the application seemed to me quite slow.

After some investigation I managed to start the application in almost the same way I used to start the application built with Ant. Actually it's quite easy, once you get used to it. All you have to do is set the Run properties as follows:


The tricky part is that you have to set them for the Command Line project and not for the main one...

At this point, if you want to have an even faster start (by which I mean an easier one) you can set the Command Line project as main and then just press the F6 key.

Wednesday, March 31, 2010

How to create a simple Naked Objects Application in NetBeans with Maven

Despite all Marco's painstaking insistence, I have never been a great fan of Maven. I'm not criticizing it, it's just I'm used with the Ant build system embedded in NetBeans: that's why when I last wrote about Naked Objects in NetBeans I sticked to it.

Partially out of curiosity, partially solicited, I decided to give it a try, using this article as a reference. All procedures refer to version 6.8, other versions might be different (I know for sure 6.7.1 is).

The first thing to do is to create a new project:

Then select Maven from the categories tree and Maven Project from the projects list


In the next screen we have to choose the archetype we want to use; under the Archetypes from Local Repository node select the Naked Objects application archetype (4.0.0):


Complete the form with the informations you find in the aforementioned article...


...and there you go; NetBeans (through Maven, of course) has created one project for each pom file, the main one being highlited:


If you check the file section you'll find the recommended directory structure also quoted in the article. This approach might seem overwhelming at first, and probably overkill for just a simple test, but it actually separates different concerns in different projects.

Now we should execute the package phase, which is not defined in NetBeans yet. To bind a custom action to the phase right click the main project and click on Custom - Goals...


In the Goals textfield you specify what goal you want Maven to execute:


You can also tell NetBeans to remember your instructions; for the most curious, this actually creates a nbactions.xml file in the same directory in which the pom resides.

After Maven has finished his stuff all you have to do is run the application. I'm not sure whether there is a different way to do it, but this one works and it's not too weird: switch to the Files view and locate the startup script, right click on it and select Run from the dropdown menu:


Et voila... here's your login form. Enter username and password...


And there you go!


If you read up to here, I owe you a (reiterated) disclaimer: I am not a Maven expert, nor a Naked Object expert, but this tutorial should help the rubber hit the road.

How does this compare to my previous procedure? Even if it was quite hard to come to an end due to my lack of knowledge of Maven, to which I owe the mixed bag of feelings I have about this, I must admit that someone that is already proficient with it gets a faster start than with the Ant approach. The projects structure generated in NetBeans is more complex, but that is not necessarily a bad thing (actually it is, if you are only trying to write a plain vanilla CRUD application that operates on just a few tables).

Which road should you follow? Right at the moment I am not even able to say which one I should follow, so I won't express myself :-)

A very interesting feature is the possibilty to use customized templates in Eclipse to speed up your development; now I'm looking forward to something like this in NetBeans...

Wednesday, February 24, 2010

How to create a simple Naked Objects Application in NetBeans

Naked Objects is an open source application framework that lets you concentrate on domain objects and automagically generates a GUI for interacting with them. This sounds (and actually is) very interesting, as the domain is what we should most interested in, instead of boilerplate, as everybody who is fond of DDD knows.

Being NetBeans my favourite IDE, as you might have suspected, I'll try to jot down some notes on how to use it to create a very simple Naked Objects application.

First things first, you have to download the Naked Objects framework; you have various options, I chose to download the zip file for Ant. After unzipping the file you should find a folder named lib that contains - o great wonder and surprise - all the necessary libs.

As I suppose I could use all this stuff in more than one project, I created a new library in NetBeans:


Click on the New Library... button and you'll be prompted a library name and type


Then click on the Add Jar/Folder... button and add all the jars in the lib folder. You should get something like this:


Ok, now we can proceed to creating a new application. As a disclaimer, this is not necessarily the best way to do it, but it is how my inner cogs work (or don't work). If yours are different, you'll have to compose all the pieces of the puzzle in a different order.

Let's suppose we want to use the DnD GUI, so I go with a new Java Application:


Click on the Next> button and enter a name for your project; don't use a dedicated folder for libraries and don't have the IDE create a main class for you.


Click on the Finish button. Ok, now we should instruct our project to be a Naked Object Application. Right click the Libraries node to add all necessary references:


Select the library you've previosly created and you're almost ready to go.

Now, if you try to run the application NetBeans complains because you have not chosen a Main Class. Right click the project node and the Run node in the Categories tree, and insert org.nakedobjects.runtime.NakedObjects as the Main Class.


Click on the OK button. Ok, now we can try to run the application... just to get another complain


Exception in thread "main" org.nakedobjects.metamodel.commons.exceptions.NakedObjectException: failed to load 'nakedobjects.properties'; tried using: [file system (directory 'config'), file system (directory 'src/main/webapp/WEB-INF'), context loader classpath]

It seems fair... after all we have to provide some configuration. Create a new properties file, name it nakedobjects and put it in the config folder. Obviously this is not enough, and you can check it yourself trying to run the application: NetBeans will complain again (don't shoot the messenger) about the lack of services.

To define services, we have to write some code. Let's suppose we want to deal with all Walt Disney characters - I hope there are no legal issues with this - so let's create a class that represents one:


package it.moz.noapp;

import org.nakedobjects.applib.AbstractDomainObject;
import org.nakedobjects.applib.annotation.DescribedAs;
import org.nakedobjects.applib.annotation.MemberOrder;

@DescribedAs("Character")
public class Character extends AbstractDomainObject {

private String firstname;
private String lastName;

@MemberOrder(sequence = "1")
public String getFirstname() {
resolve(firstname);
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
objectChanged();
}

@MemberOrder(sequence = "2")
public String getLastName() {
resolve(lastName);
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
objectChanged();
}

public String title() {
return getFirstname() + " " + getLastName();
}
}

Notice how this class, that is a domain object, extends the class AbstractDomainObject provided by the framework. The annotation @DescribedAs tells you how the object will be referred to in the GUI, while @MemberOrder defines the order in which members are presented. You can find every detail on the Naked Objects website.

The next step is telling our application that such a domain object exists, so we'll add the following line in our nakedobject.properties file:

nakedobjects.services=repository#it.moz.noapp.Character

Ok, let's start the application...


uh oh... User name and password? ehrm... let's provide the application with them! The problem is that if you want to add an empty file - unlike for properties files - NetBeans asks you whether you want to add it to the src folder or to the test folder, i.e. the folders (already) defined in the project. As you want neither, you must manually add an empty passwords file to the config folder. Before complaining about NetBeans, keep in mind that you can always define the config folder as a new source package folder, but let's skip this option.

Fill in a username and a password...
user:pass
And that's it, you can start your application!


To create a new instance you right-click the Characters icon and select the appropriate item from the drop down list, insert the desired values and here's your brand new character. Rinse and repeat and you'll get something like this:


As you can see, you now have a Disney Character directory without having written a single line of code but your domain class.

Unluckily, if you close your application all your efforts have been vain, so you should add the support for persistence. But this will be the subject for another post...