Angel “Java” Lopez on Blog

November 25, 2008

Agile Java Development with Spring, Hibernate and Eclipse

Filed under: Agile Software Devevelopment, Java — ajlopez @ 9:04 am

I’m reading the book Agile Java Development with Spring, Hibernate and Eclipse, by Anil Hemrajani. About the author:

Anil Hemrajani has been working with Java Technology since late 1995 as a developer, entrepreneur, author, and trainer. He is the founder of Isavix Corporation, a successful IT service company (now Inscope Solutions), and isavix.net (now DeveloperHub.com), an award-winning online developer community that grew to more than 100,000 registered members. He has 20 years of experience in the information technology community working with several Fortune 100 companies and also smaller organizations. He has published numerous articles in well-known trade journals, presented at conferences and seminars around the world, and received the “Outstanding Contribution to the Growth of the Java Community” award from Sun Microsystems, the “Best Java Client” award at JavaOne for BackOnline, a Java-based online backup client/server product, and was nominated for a Computerworld-Smithsonian award for a free online file storage service website. His more recent project is the visualpatterns.com website.

It’s an impressive book, covering logging, remote debugging, agile practices, JMX, JUnit, Ant, POJOs programming, JSP tag libraries, and more. But now, I’m interested in commenting some paragraphs from the preface. Hemrajani wrote:

I began working with Java technology in late 1995, shortly before the Java Development Kit (JDK) 1.0 was formally released. Prior to that, I was programming in C and C++ for many years. I was truly excited about the features that Java offered, such as cross-platform portability, simpler syntax (simpler than C++, for example), objectoriented, secure, rich API, and more.

I have a similar career. At some point at 1995, I learnt the Java language and part of the library, becoming a fan of the language. It was a relief of C++ programming (plagued with new vs delete issues), and Visual Basic (no inheritance, no real objects). But I must admit the GUI interface was based on an ugly AWT implementation .

Over my 20-year career, I have learned a few things. Among these, my favorite is simplicity; anytime I see complexity, I begin doubting whether the solution is correct. This is how I had begun to feel about Java right around 2000, when the Java 2 Enterprise Edition (J2EE) started becoming mainstream. Note that from this point on, I will refer to J2EE as JEE because the “2″ was recently dropped from the name by Sun Microsystems.

I agree. When Sun launched J2EE, it was a mess. For years, I thought they were right, but I didn’t understand the reasons for the underlying complexity of Enterprise Java Beans. Until I read Rod Johnson books on Java Enterprise development: then, I confirmed the crazy thing called EJBs.

My growing lack of interest in Java was a result of what I saw as unnecessary complexity in JEE introduced by layers of abstraction. I began to believe that Sun Microsystems (inventor of Java) was focusing Java and JEE on solving the most complex enterprise applications, but somewhat ignoring the relatively less complex, small- to medium-sized applications. Furthermore, I saw the hype take over people’s common sense because I ran across projects in which Enterprise JavaBeans (EJB) were used for nondistributed processing, such as local logging. I felt strongly enough about this subject to write a short article for JavaWorld.com in 2000 (http://www.javaworld.com/javaworld/jw-10-2000/jw-1006-soapbox.html) titled, “Do You Really Need Enterprise JavaBeans?” (About five years later, we saw EJB 3.0 specifications being rewritten to become more simplified, to ease the development.) This brings us to this book and the reason I wrote it.

EJBs are the works of devil. POJOs programming, Hibernate ORMs, and Spring framework, are examples of good design created by the Java community. Sun people saw the light, and adopted many ideas in the EJB 3.0 specification, but I think “too few, too late”. EJBs programming was a nightmare, that deserve to be erased from humankind memory.

At the beginning of each chapter, there is an illustration, describing a fictional story throughout the book. I can’t resist to include one from chapter 2 (more at visualpatterns.com):

More info about the book, at

http://www.visualpatterns.com/agilejava.php

That page has the TOC, and forewords by Scott W. Ambler, and Rod Johnson.

Another book aligned to these ideas:

Better, Faster, Lighter Java O’Reilly Media

Angel “Java” Lopez
http://www.ajlopez.com/en
http://twitter.com/ajlopez

September 12, 2008

Layered architecture in Domain-Driven Design

This time, let explore the concepts of a layered architecture, as proposed by Eric Evans in its classic book Domain-Driven Design, Tackling Complexity in the Heart of Software. In the chapter four of the book, Evans presents this diagram:

 

Evans writes:

For a shipping application to support the simple user act of selecting a cargo’s destination from a list of cities, there must be program code that (1) draws a widget on the screen, (2) queries the database for all the possible cities, (3) interprets the user’s input and validates it, (4) associates the selected city with the cargo, and (5) commits the change to the database. All of this code is part of the same program, but only a little of it is related to the business of shipping.

He proposes that the domain model resides in a layer, the Domain Layer. In this way, the domain model is protected from technicalities as concrete persistence implementation, and presentation duties. I like to say that the domain is as an organism, that receives stimula, actions from the outside, and reacts to such commands. The domain should run without detailed knowledge of the rest of the application. Serialization between physical tiers, presentation details and database access, should be clearly separated from the domain implementation.

The layers could be described as:

UI (User Interface): the easiest to understand, this layer is the responsible of displaying information to the user, and accept new data. It could be implemented for web, desktop, or any presentation technology, present or future. For example, it could be a voice application, that interacts with the user via a phone. The acid test for our design is that a radical change in user interface should have minimal (or controled, at least) impact in the rest of the system.

Application Layer: it’s in charge of coordinating the actions to be performed on the domain. There are no business rules or domain knowledge here. No business state resides in this layer. It delegates all domain actions to the domain. It could coordinate many actions (possibly in many domains). It could prepare the infrastructure to be ready to work with the domain for an specific action (for example, preparing transaction scopes).

Domain Layer: In this layer resides the heart of software, according to Evans. Business rules and logic lives inside this layer. Business entity state and behavior is defined and used here. Communication with other systems, persistence details, are forwarded to the infrastruture layer. Evans discuss the patterns he uses in this layer, as Entities, Value Objects, Services, Repositories and Factories. We would explore the patterns and implementations in future posts.

Infrastructure Layer: God and devil are in the details, and in the infrastructure layer. Its main responsability is the persistence of the business state, most frequently, using a relational database.

My idea is to take an example (possibly a domain from Jimmy Nilsson), and develop it using these ideas, showing concrete code in Java and .NET. At some point, I will discuss about code generation from an abstract model, but it will not be the focus of these posts.

Sources:

Domain-Driven Design, Tackling Complexity in the Heart of Software, by Eric Evans.
Applying Domain-Driven Design and Patterns: With Examples in C# and .NET, by Jimmy Nilsson
.NET Domain-Driven Design with C#, Problem, Design, Solution, by Tim McCarthy. (There is a section in Tim’s blog dedicated to this book).

You can download freely

Domain-Driven Design Quickly

from InfoQ.

Angel “Java” Lopez
http://www.ajlopez.com/en

April 19, 2008

Code Generation as a Service with AjGenesis

I’m back! I want to write in this post about the new features I’ve added to my code generation project AjGenesis. The main points are:

- A new interactive way to use it, a web based application

- Examples with that new interface, to generate C#, VB.Net, Java and PHP applications, all from the same abstract model

These features were published last January at release 0.5 in CodePlex

Using AjGenesis

Years ago, I began to work in this project. Those days, the only way to execute and use it were the console, with commands. Later, I adopted NAnt, and NAntGui, as interfaces to launch the system and execute tasks and transformations. The project can be used as a set of .DLLs, referenced from custom application. Carlos Marcelo Santos has published posts (in Spanish) about how to use AjGenesis from NAnt

Cómo generar código con AjGenesis sirviéndonos de NAnt
Cómo generar código con AjGenesis sirviéndonos de NAnt – Parte II

Last year, 2007, Jonathan Cisneros wrote a great Windows interface, named AjGenesis Studio:

AjGenesis Studio: una IDE para AjGenesis
AjGenesis Studio at CodePlex

As an exercise at the end of year 2007, I wrote a new project in the original solution, and I published last January inside the last release 0.5 at CodePlex.

It’s a new web project, that I called, inspired by the work of Jonathan, AjGenesis Web Studio

The main point is, with this project, to show that the functionality from the AjGenesis core can be used and exposed in our applications, this time from a web interface, using ASP.NET. With this approach, we can put a server in our internal network or at Internet, and create, edit, upload and download user defined models, generate source code, and download the results. We could call this, Code Generation as a Service.

Let’s look the project, its functions and some inners.

The project

It’s a web project, named AjGenesis.WebStudio.

To launch it, load the AjGenesis.sln solution (located at src directory inside the version 0.5 from CodePlex) with Visual Studio 2005, and build the complete solution.

(If you have errors in the AjGenesis.WebStudio project, probably you must add a reference to a .DLL that manages the file compressions. Add as reference to the project the file src\Libraries\Ionic.Utils.Zip.dll. This library generates .zip files, and expand them).

In the web solution, I used Master Pages, and a default Theme. It doesn’t manage a database, only files and directories. We’ll see below that the project has a mini wiki, to write help pages that can be defined by the user.

The look and feel is simple, but you can change the theme and master page to obtain a better result.

The system can generate code in the fly, and download it as a .zip file. You can use the classic AjGenesis system, as I explained in past post, but now, we can use it from any browser. You don’t need .NET in your client machine, and you can work from other operating systems.

After the build of the solution, click right mouse button on the file \Default.aspx in project AjGenesis.WebStudio, and choose View in browser…:

This is preferred to launch the project in debug mode: if you debug the project, it will execute the code generation task in very slow way.

Working Directory

The system uses a working directory, with a structure that resembles the examples at AjGenesisExamples3.zip (to download from examples at CodePlex). The default working directory is AjGenesis.WebStudioWorkingDirectory:

Some directories:

Projects: There is a directory here for each project model.
Templates: Containing the template files to process during the code generation phase
Build: The code generated code resides in this directory.

The working directory can be changed using the left menu option Working Directory and then, choosing the option Change Working Directory:

Generating Hello World

As I used to comment in my speeches, the acid test of all code generation system is to help us to model and produce the most simple and universal software system, the reknowed Hello World example. There is an explanation on how to do this with classic AjGenesis in my post

Code Generation with AjGenesis- A Hello World application

In AjGenesis Web Studio, select the left menu option Generate. This is the result page

There are two dropdown list. We’ll see how they are filled. At the first list, there are the defined projects:

Choose HelloWorld. Then, go to technology list, showing:

In this project, only Java and Net20 are the defined technologies. Other projects have more technologies. Choose Java and the press the Generate button. After a while, the page shows a result.

How this works?

First point, the system manage a working directory, the default is AjGenesis.WebStudioWorkDirectory, a syster directory of the web project. There is a Projects project, cointaining more directory, each one is a project for the system.

The directory AjGenesis.WebStudioWorkDirectory\Projects\HelloWorld has a Project.xml file that describes the free model we use in this case:

<Project> <Name>HelloWorld</Name> <Description>HelloWorld Example</Description> <GenerateTask>GenerateHelloWorld</GenerateTask> <Message>Hello World</Message> </Project>

Inside the directory project, there is a Technologies directory. Each XML file that is found there it’s managed as a technology model in the system. Again, as I explained in my posts on AjGenesis , this file has a free model, you can put here anything to process from code generation process. The concepts of project and technology is not mandatory, but AjGenesis Web Studio takes them as special directories, and read them to obtain the list of project and associated technologies.

The technology Java.xml file contains:

<Technology> <Name>Java</Name> </Technology>

and Net20.xml contains:

<Technology> <Name>Net20</Name> </Technology>

Nothing special. The value Name inside Technology drives what steps to execute during code generation phase.

After press the generate button, the system loads the project and technology model in memory. Then, it executes the file GenerateCode.ajg located in directory Tasks. But if the project file contains a  GenerateTask tag, as in this project, that file is executed instead the default one. This is the content of Tasks\GenerateHelloWorld.ajg:

 

PrintLine "Generating HelloWorld..." if not Project.BuildDir then Project.BuildDir = "${WorkingDir}Build/${Project.Name}" end if if not Project.Title then Project.Title = Project.Name end if if not Project.Version then Project.Version = "1.0.*" end if if not Project.Language then Project.Language = "en" end if if not Project.SystemName then Project.SystemName = Project.Name end if PrintLine "Creating Directory ${Project.BuildDir}" FileManager.CreateDirectory("${Project.BuildDir}") Include "Tasks\BuildHelloWorld${Technology.Name}.ajg"

This file is written in an scripting language, a pillar of AjGenesis, affectously named AjBasic. The Project variable is the representation in memory of the tag <Project> loaded from the Project.xml file, described above. In memory, it is as an object, with properties. It’s not an static object: you can add properties in runtime, as Project.Version in the above text. If in an if sentence we asks the value of  Project.Version and this doesn’t exist, it’s not an error, the result is simply Nothing and that value is treated as false for boolean evaluations (like in other languages, notably PHP).

Finally, the last line includes an additional file to process dinamically. The string contants in AjBasic have expression expansion: all between ${ and } is evaluated. Using the value of Technology.Name (obtained from loading in memory the XML technology file), it executes BuildHelloWorldJava.ajg or BuildHelloWorldNet20.ajg. The first one contains the steps to generate a .java file:

<# PrintLine "Generating Solution ${Project.Name}" if not Project.Title then Project.Title = Project.Name end if if not Project.Version then Project.Version = "1.0.*" end if PrintLine "Creating Directories" FileManager.CreateDirectory("${Project.BuildDir}") FileManager.CreateDirectory("${Project.BuildDir}\${Technology.Name}") TransformerManager.Transform("Templates\HelloWorld\ClassJava.tpl", "${Project.BuildDir}\${Technology.Name}\HelloWorld.java", Environment) #>

This code uses inner AjGenesis utilities that create directories and expand a template file. ClassJava.tpl contains:

// // Automatically generated by AjGenesis // http://www.ajlopez.com/ajgenesis // public class HelloWorld { public static void main(String[] args) { System.out.println("${Project.Message}"); } }

All this produces the directory Build\HelloWorld\Java:

If we choose the Net20 technology, more files would be generated:

This is a more complete result. It has a VS 2005 solution file, two project directories, one in VB.NET and the other in C#, with source code and project files:

To see the generated code, its files and directories, go to left menu option Builds:

There is a directory for each project. You can download a complete directory, as a .zip file. We can create a file, download a directory, upload and expand a .zip file, and consult a help page. We can read, edit, and delete each file, in this case readme.txt.

Go to the View at HelloWorld directory:

You can browse directories, upload and download files. You can move a directory, or make a copy, to experiment without loosing the original content.

Generating C# and VB.NET solutions

After this simple example, let’s go for more. For more information about the next examples and their models, read:

Application Generation using AjGenesis

Go again to left menu Generate option. Now, we choose a project, AjSecondExample. Its technology list is more complete:

Choose CSharp2 and generate. This process creates a complete solution inside Builds\AjSecondExample\CSharp2. There is an Sql directory with DDL script to create a MS SQL Server database. Inside the Src directory, you’ll find the solution, composed of a set of projects:

This projects follows a layered archictecture, that you can modify from the templates. They use a data access layer, based on my AjFramework project, but you can change to access Enterprise Library or your own data services.

You must create the database using the generated scripts, and modify the connection string in the web.config to match your environment. The application can be compiled and executed:

The administration page shows:

Back to generate page, execute the VbNet2 technology, obtaining a directory with the same structure, now with Visual Basic.NET code:

All these depend of the specified technology inside the files at Projects\AjSecondExample\Technologies. The content of VbNet2.xml is:

<Technology> <Programming> <Dialect>VbNet2</Dialect> </Programming> <Database> <Dialect>MsSql</Dialect> <Name>AjSecondExample</Name> <Username>sa</Username> <Prefix>ajse_</Prefix> <Host>(local)</Host> </Database> </Technology>

and CSharp2.xml:

<Technology> <Programming> <Dialect>CSharp2</Dialect> </Programming> <Database> <Dialect>MsSql</Dialect> <Name>AjSecondExample</Name> <Username>sa</Username> <Prefix>ajse_</Prefix> <Host>(local)</Host> </Database> </Technology>

These data are used during the code generation process.

Note: inside Tasks\BuildTechnology.ajg file, you’ll find a new variable, injected from the web project:

if not Project.BuildDir then Project.BuildDir = "${WorkingDir}Build/${Project.Name}/${Technology.Programming.Dialect}" end if

This is the WorkingDir variable that points to the working directory we selected in AjGenesis Web Studio.

Genarating Java and JSP applications

Many projects (AjFirstExample, AjSecondExample, AjTest….) can be generated in Java with JavaServer Pages. A build.xml file is generated to be modified and used to compile the generated code using the ant utility (you can use this file from an IDE, like Eclipse or NetBeans).

The target build  makes a .war deploy file. You can browse and modify the build.xml file to install the .war in a Tomcat web container.

The generated code is composed of .jsp files (web pages in Java) and Java code to compile that implements a service layer and a data access layer, exchanging simple JavaBeans between layers. The DDL script, in these examples, is a MySql one.

If you build and deploy the application, and install the database in a MySql server, you can see it working fromn a Tomcat server:

Generating application using Domain-Driven Design ideas and Hibernate, NHibernate

Many example projects (AjFirstExample, AjSecondExample, AjTest…) have defined technologies CSharp2DDDNh, JavaDDDHb, VbNet2DDDNh, and even VbNet2Nh. The DDD ones implement some concepts from Domain-Driven Desigg, as Application, Domain and Infrastructure layer, but the templates could be improved. The *Nh projects generate code for entities using NHibernate mapping. The *Hb projects use Hibernate.

An example of NHibernate generated mapping:

 

<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"> <class name="AjFirstExample.Domain.Customer, AjFirstExample.Domain" table="ajfe_customers"> <id name="Id" column="Id" type="Int32" unsaved-value="0"> <generator class="native"/> </id> <property column="Name" type="String" name="Name" length="255"/> <property column="Address" type="String" name="Address" length="255"/> <property column="Notes" type="String" name="Notes" length="255"/> </class> </hibernate-mapping>

These solution can be built as the previous examples. You’ll see better generator templates for NHibernate in the AjOmar example at CodePlex. Post (in Spanish) explaining the process at

Generando código para NHibernate (Parte 1)
Generando código para NHibernate (Parte 2)
Generando código para NHibernate (Parte 3)

Generating PHP applications

If you choose PHP technology, web page with PHP code are generated, using MySql as database. The generated code can be copied to a directory in a web site that supports PHP, Apache, or IIS. AjTest example running in a IIS with PHP4:

Other directories

In the working directory, there are other directories:

SourceCode: Containing some source code that is copied into the solution during code generation.

Libraries: Additional .dlls, to copy and use in the generated applications.

The larger subdirectory  is Templates:

In previous posts I described in detail the creation and use of a template file. This is the content of a template that generate a C# entity:

<# rem Entity Generator rem for C Sharp include "Templates/CSharp2/CSharpFunctions.tpl" message "Processing Entity ${Entity.Name}" include "Templates/CSharp2/Prologue.tpl" #> /* * Project ${Project.Name} * ${Project.Description} * Entity ${Entity.Name} * ${Entity.Description} * */ using System; namespace ${Project.SystemName}.Entities { public class ${Entity.Name} { // Private Fields <# for each Property in Entity.Properties message "Processing Field ${Property.Name}" #> private ${CSharpType(Property)} ${CSharpFieldName(Property)}; <# end for #> // Default Constructor public ${Entity.Name}() { } // Public Properties <# for each Property in Entity.Properties message "Processing Property ${Property.Name}" #> public ${CSharpType(Property)} ${Property.Name} { get { return ${CSharpFieldName(Property)}; } set { ${CSharpFieldName(Property)} = value; } } <# end for #> } }

Help pages

I’m testing some ideas in this web project. There are code to create “wiki” pages, that can be used as help pages in the system.

You can edit this kind of pages:

There is a way to insert links to other wiki pages and to external ones. The page data is represented as a .NET object in memory, and that object is serialized in an XML file in Pages application directory. There is no database to store page: each one is an object, serialized in a .xml file.

Conclusions

I hope this system helps to a better understanding of AjGenesis project features and potential. With a more user friendly interface, the project can be used by more people. We can generate code from command line, or using NAnt utility, or AjGenesis Studio.

I ever remark a point: all these are examples, AjGenesis is not limited to generate only this kind application. You are in charge: you can define the model that matches your project requirements, using any technology you choose. You can codify DDD ideas in a different and better way. You can generate Hibernate/NHibernate mappins using other patterns and mapping idioms. You can use other ORM utilities, and generate code for them. You can generate PHP5 pages that use Prado, instead of plain PHP4. You can generate stored procedures for Oracle, instead of my examples that use MS SQL Server. Or write better ones. You can generate WinForms code, instead of ASP.NET page. You can generate JavaServer Faces pages, views, beans, and abandon JavaServer Pages. You can generate the code or text you want: e.g., unit tests, or documentation pages. I recommend that the generated code resembles the code you could generate manually.

I invite anyone that uses this system, to post his/her work, or leave comments here. You can participate in the Spanish list:

http://groups.google.com/group/codegeneration?hl=es

Next steps

Back to develop, I have some ideas:

- Improve the templates to generate more technologies, as VS 2008 projects, solutions, templates for Struts 1/2, Spring, better mapping for Hibernate, NHibernate, and code generation for the new ASP.NET MVC.

- Write posts about these templates

- Publish the new examples

- Write down a useful documentation (now, it’s minimal: you can found more details in this posts)

Enjoy the project!

Angel “Java” Lopez
http://www.ajlopez.com/en

January 18, 2008

QCon London 2008

I’ve received an email, from Floyd Marinescu, announcing this “mega” conference. They’ll cover all-about-software-development: agile, DSLs, SOA, SaaS, Cloud computing (I guess grid computing related), .NET, Java, Ruby, Rich Client, Scrum, XP, F#, REST…. It will be the DisneyWorld of all software developers! ;-)

Here’s the announce:

You are receiving this email because you opted-in to receive notifications related to QCon London, from the QCon London website. QCon London is taking place in just 8 weeks, March 12-14 and the conference editorial is nearing final. Since our last update in December, a number of important changes have been made to the conference:

  • Google, Yahoo!, Amazon, Salesforce.com now presenting in the Cloud Computing Track
  • MySpace.com, eBay, Magus confirmed in the Architectures you’ve always wondered about Track
  • XP founder Kent Beck, and Analysis Patterns & Refactoring Author Martin Fowler keynoting
  • Banking Architectures Track adds sessions from Merrill, Betfair, Credit Suisse
  • GoF Patterns Author & Eclipse Architect Erich Gamma presenting
  • and much more…

QCon is an enterprise software development conference for team leads, architects, and project managers covering Architecture & Design, Java, .NET, Ruby, SOA, Agile methodologies and other timely topics such as DSLs, cloud computing, and bank/finance architectures. Last year’s QCon London had almost 500 registrants, and was covered very heavily in blog space see QCon London blogger coverage & key take aways).  

The track themes for QCon London & track hosts are as follows:
Architectures You’ve Always Wondered About -  Hosted by Redmonk’s James Governor
The last 2 QCon’s featured: Amazon, Linked-In, Yahoo!, eBay, Second Life, and Orbitz architecture case studies
Domain Specific Languages in Practice – Hosted by ThoughtWorks’ Neal Ford
Takes DSLs to the next level by practical applications and tools that are useful today.
Effective Design
Translate a set of abstract ideas into working and functional software in an effective way.
Architectures in Agile – Hosted by POSA author Kevlin Henney
How to integrate the trade-offs related to aspects such as performance, security, scalability and modifiability into an agile process
Banking: Complex high volume/low latency architectures  – Hosted by John Davies & Alexis Richardson
The latest innovations as well as time-proven best practices that architects of banking & finance systems need to know.
The Cloud as the New Middleware Platform – Hosted by EAI Patterns Author Gregor Hohpe
Is the internet becoming the computer?
Implementing Scrum and XP- Hosted by Patterns Almanac author Linda Rising
Leading practitioners will present and explain how Scrum and XP are implemented in the most effective way.
Java Emerging Technologies – Hosted by Java Concurrency Author/spec lead Brian Goetz
The previous QCon covered: JRuby, Grails, Server-side OSGi, DSL development, Batch Processing
.NET in the Enterprise – Hosted by Matt Deacon
.NET has brought Microsoft’s platforms into many business-critical applications, back-office, and server-side solutions.
Programming Languages of Tomorrow
Erlang, F#,, Intentional and Scala. How can we best leverage them in our next software project?
SOA, REST and the Web – Hosted by InfoQ’s Lead SOA Editor Stefan Tilkov
REST & SOA, Internet Scale Integration, REST & WS Myths
Browser & Emerging Rich Client Technologies – Hosted by InfoQ lead RIA/Java editor Scott Delap
Silverlight vs. JavaFX/Consumer JRE vs. Adobe Flex/AIR vs. Google’s Ajax RIA stack
The Rise of Ruby
Learn how to best take advantage of what Ruby has to offer
The first two QCon were well received, below are some comments from bloggers who attended our most recent QCon:

  • David Forbes – Exhilirated after gorging on brain candy this week, I have a moment to reflect on what just happened. QCon was the right place to be. I can’t imagine where else I would have rather been. If I had the week to do again, I would probably march right down to the Westin…again.
  • Denis Bregeon – I was very happy with it. Most of the talks tickled my imagination and that is the primary thing I was looking for. Many others gave me details on more technical subjects that I wanted to learn about.
  • Srini Penchikala – I was at the QCon conference in San Francisco last week. It was a great experience to be there. I learned a lot not only from the presentation speakers and panelists but also from the attendees who came from different countries (England, Syria, Australia to name a few) and companies.
  • Alex Olaru – Great conference: excellent speakers, very relevant topics, just enough product pushing without it becoming annoying. All in all a conference I would highly recommend to any architect or project manager.
  • Ola Bini – Last week I attended QCon San Francisco, a conference organized by InfoQ and Trifork (the company behind JAOO). It must admit that I was very positively surprised. I had expected it to be good, but I was blown away by the quality of most presentations.
  • Martin van Vliet – All in all, this was a good conference and more than enough reason to look forward to the next QCon, next year in London.
  • Pete Lacey – A wonderful conference made better by being able to meet many people face to face for the first time…

See also past QCon/JAOO talks available online on InfoQ:

Registration for the 3 day conference is 1180£ until Feb 22nd, and 1220£ after March 11th. The conference will be held at the Queen Elizabeth II Center, like last year.  Join us at QCon London!

Angel “Java” Lopez
http://www.ajlopez.com/en

November 12, 2007

Application Generation using AjGenesis

These days, I wrote new examples for my open source project AjGenesis

http://www.ajlopez.com/ajgenesis
http://www.codeplex.com/ajgenesis

Using AjGenesis, we can produce, starting from our own model, applications for ASP.NET 1.x/2.x, JSP, using SQL Server in .NET, with ADO.NET or NHibernate, or MySql with Java and Hibernate. The sample generated applications use a layered architecture (but remember: these are sample applications, you can write and use your own models, tasks, and templates). Other option: it can generate layers following ideas from Eric Evans’ Domain-Driven Design.

I’m still writing those examples, but now, you can download the current version from

AjGenesisExamples3New.zip

The examples require the use of AjGenesis last release:

AjGenesis Version 0.4.3

but you can try the current version under development:

AjGenesis Version 0.5

In this post, I want to comment how AjGenesis works and some of its inner structure, using one of those examples. Although I will concentrate in producing VB.NET code, you’ll find that the example is able to produce C Sharp and Java/JSP solutions, as well.

First, let’s review first some points about the project. The big picture:

AjGenesis Version 0.4.3 is written using VB.NET V1.x, but version 0.5 is the current version under development, and it was rebuilt using .NET 2.0. The project is open source, and has a BSD-like license, that allows to use it in any project what you want: you only need to comply with the license (in short, put some reference to the original project). It is possible to be used like a library, invoked from your own project, or it is possible to be invoked from command line, or even it can be used from using NAnt (this tool gives you a better organization of the code generation tasks).

There are several samples in the page of the project (inside the project zip source file and in additional files). They generate code from a model, invoking tasks and processing templates. The samples generate code PHP, Java, JSP, VB.NET, C#, ASP.NET, and even scripts of procedure and data base stored. I want to emphasize two points:

- The model to use is totally definible by you. It’s a free model, it’s not a fixed one. You can model what you want to model.

- The tasks and templates to apply are totally programmable and controlable. You are in charge. 

That’s make a difference from other generators. We can create our own model, and its own templates and tasks, to generate any text artifacts. Other systems start from the data base, and they only generate a group of predefined text files (as POJOs, plain old java objects, or DAOs, Data Objects Access). But with AjGenesis you can generate any text file you need.

In order to better understandind the free model concept, read a previous post:

Generating Code Hello World with AjGenesis

In that post, the initial steps are described, using a free model, totally oriented to the domain to represent: a typical Hello World application, implemented in different technologies.

Creating an application

Let’s do something more complete in this post. Suppose we need to create a simple solution simple, with two tables, in a MS SQL Server databse, source code in VB.NET 2,0, web interface, layer of services, layer of data, business components and business entities a la Microsoft. We want to generate the solution, the projects, scripts for database creation, and stored procedures. This example is included in the examples AjGenesisExamples3New.zip. First step: to write the model.

The project

In a directory of projects of the examples that accompany this article, there is a Projects/AjFirstExample directory.

In that directory it is the Project.xml file that contains the model.

<Project>
    <Name>AjFirstExample</Name>
    <Description>First Example
    using AjGenesis</Description>
    <Prefix>AjFE</Prefix>
    <Domain>com.ajlopez</Domain>
    <CompanyName>ajlopez</CompanyName>
    <Model>
        <Entities>
            <Entity
            Source="Entities/Customer.xml"/>
            <Entity
            Source="Entities/Supplier.xml"/>
        </Entities>
    </Model>
</Project>

Remember: the model is free. Here we define the templates that we are going to use. The model contains two simple entities: customers and suppliers.

The entities

The XML file is not terribly long: AjGenesis allows that any node of the model is specified apart in a file. This is a criterion that I have used to define how the model is written: the resulting XML does not have to hurt at sight, must be understandable and abarcable in a reading.

In the Project.xml, that feature is used in the case of the entities, with the Source attribute. Let us examine an entity, written in Entities/Customer.xml:

<Entity>
    <Name>Customer</Name>
    <Description>Customer Entity</Description>
    <SetName>Customers</SetName>
    <Descriptor>Customer</Descriptor>
    <SetDescriptor>Customers</SetDescriptor>
    <SqlTable>customers</SqlTable> 

    <Properties> 

        <Property>
            <Name>Id</Name>
            <Type>Id</Type>
        </Property> 

        <Property>
            <Name>Name</Name>
            <Type>Text</Type>
            <SqlType>varchar(200)</SqlType>
        </Property> 

        <Property>
            <Name>Address</Name>
            <Type>Text</Type>
            <SqlType>text</SqlType>
        </Property> 

        <Property>
            <Name>Notes</Name>
            <Type>Text</Type>
            <SqlType>text</SqlType>
        </Property> 

    </Properties>
</Entity> 

There are attributes of the entities, like its name and description, in plural and singular. This data serve to name them in the resulting pages, or within the code. The properties are the fields to maintain in each entity..

Aside from the entities, in another directory, Technologies, specifies the dependent model of the technology, like VbNet2:

The templates

The templates to use are at the Templates/VbNet2 directory:

They are the templates for generation of code VB.Net 2.0. Also we will find groups for C# 1/2, Vb.NET 1,2, Java (although I’m thinking to drop templates for .NET 1.x: I don’t see any reason to maintain these). There are templates to use Nhibernate, Hibernate, JSP, MySql, and concepts of Domain-Driven Design, too. Let’s review a template as an example, the one that generates the organization in Visual BASIC, EntityVb.tpl:

<# 

message "Generating Entity ${Entity.Name}" 

include    "Templates/VbNet2/VbFunctions.tpl" 

include    "Templates/VbNet2/Prologue.tpl"
#> 

'
'    Project ${Project.Name}
'        ${Project.Description}
'    Entity    ${Entity.Name}
'        ${Entity.Description}
'    
'

Public Class ${Entity.Name} 

'    Private Fields

<#
for each Property in Entity.Properties
    message    "Procesando Campo ${Property.Name}"
#>
    Private m${Property.Name} as ${VbType(Property)}
<#
end for
#> 

'    Default Constructor

    Public Sub New()
    End Sub 

'    Public Properties

<#
for each Property in Entity.Properties
    message    "Procesando Propiedad ${Property.Name}"
#>
    Public Property ${Property.Name}() as ${VbType(Property)}
        Get
            Return m${Property.Name}
        End Get
        Set(ByVal Value As ${VbType(Property)})
            m${Property.Name} = Value
        End Set
    End Property
<#
end for
#> 

End Class 

Like before, control structures are used. XML is the serialized format of the model. During the code generation process, the model is loaded in memory, ready to be accesible via dynamic variables.

The steps

We have more files to generate: from the pages ASPX, and their associated code, the projects of facade on watch, organizations, access to data, the file of solution, and more. In order to automate this generation, the example has several files of tasks, in the Tasks directory, where the steps are described to execute. There are two great tasks: the steps to execute independently of the chosen technology, like completing the model, reviewing it, and the employees of the technology, like generating such file JSP or ASPX, depending on if we want Java or .NET.

The task of completing the model is in charge of Tasks\BuildProject.ajg, that begins with:

'
' Build Project
'    Complete the Project Data
'    Project must be loaded in global variable Project
'

PrintLine "Completing Project ${Project.Name}" 

include "Templates/EntityFunctions.tpl"
include "Templates/Utilities.tpl" 

if not Project.Title then
    Project.Title = Project.Name
end if 

if not Project.Version then
    Project.Version = "1.0.*"
end if 

if not Project.SystemName then
    Project.SystemName = Project.Name
end if 

The template includes some auxiliary functions, and then, it begins to complete the model that resides in the Project variable. For example: if the project lacks Project.Title the program set Project.Name as Project.Title. The program continues:

for each Entity in Project.Model.Entities
    PrintLine "Entity " + Entity.Name 

    for each Property in Entity.Properties
        PrintLine "Property " & Property.Name
        if Property.Type="Id" and not Property.SqlType then
            Property.SqlType="int"
        end if
        if Property.SqlType and not Property.SqlColumn then
            Property.SqlColumn = Property.Name
        end if
        if Property.Type="Id" and not Entity.IdProperty then
            Entity.IdProperty = Property
        end if
        if Property.Reference then
...

After that process, the technology tasks are executed. The example use Tasks\BuildVbNet2.ajg, here a fragment:

<# 

include "Templates/Utilities.tpl"
include "Templates/VbNet2/UtilitiesVb.tpl" 

message "Creating Directories..." 

FileManager.CreateDirectory(Project.BuildDir)
FileManager.CreateDirectory("${Project.BuildDir}/Sql")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Entities")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Entities/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Data")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Data/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Services")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Services/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Business")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Business/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/App_Themes")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/App_Themes/Default")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/Admin")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/Controls")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/MasterPages")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebServices")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.RemoteServices") 

message "Defining Solution and Projects..." 

...

In this fragment, the directories necessary are created to lodge the solution. The name of the directory is extracted of the model from Project.BuildDir. Note that ${ } in a string is used to expand the inside expression into the string value.

Technology Model

Under the directory Project\AjFirstExample\Technologies they are some models that describes the technology parameters to use:

 

Let’s examine VbNet2.xml:

<Technology>
    <Programming>
        <Dialect>VbNet2</Dialect>
    </Programming>
    <Database>
        <Dialect>MsSql</Dialect>
        <Name>AjFirstExample</Name>
        <Username>sa</Username>
        <Prefix>ajfe_</Prefix>
        <Host>(local)</Host>
    </Database>
</Technology>

These data is used during the template generation phase. It indicates the language, and the database to use.

Generating the solution

We could send the tasks from the command line, but we have a .build file for Nant, one for each technology to generate. We execute the tasks build, buildsql, and deploysql of AjFirstExampleVbNet2.build with the command line:

nant -buildfile:AjFirstExampleVbNet2.build build buildsql

(You must adjust the line

<property name=”ajgenesis.dir” value=”…./AjGenesis-0.5″/>

to reflect your AjGenesis installation directory)

Note the following lines in the build file:

    <target name="loadtasks" description="loads AjGenesis tasks">
        <loadtasks assembly="${nanttasks.dir}/AjGenesis.NAnt.dll" />
    </target> 

    <target name="init" depends="loadtasks" description="init the AjGenesis model, create build directory">
        <mkdir dir="${build.dir}"/>
        <loadmodel model="${project.dir}/Project.xml"/>
        <loadmodel model="${project.dir}/Technologies/${technology}.xml"/>
        <executetask task="${tasks.dir}/BuildProject.ajg"/>
        <executetask task="${tasks.dir}/BuildTechnology.ajg"/>
    </target> 

These tasks load an AjGenesis NAnt tasks, load the models, and execute the tasks.

In the Build/AjFirstExample/VbNet2/Sql directory they are left scripts of creation of the base and stored procedures. And in the directory Src brother, surprise! We’ll have the generated solution:

There were generated several projects, into a solution. We can load the solution into the Visual Studio 2005:

Using another NAnt file, AjFirstExampleCSharp2.build, we can generate the same solution in CSharp:

You will find other projects and examples of .build files, that generate solutions using NHibernate, Hibernate use, JSP, and concepts of Domain-Driven Desing a la Eric Evans.

Reflections

Sure, everything cannot be generated automatically. It is important to remember always that fact. But in the day to day, we recognize that we have amount of repetitive text, tasks that we can well delegate to software.

A key point: the model in AjGenesis is free. The presented examples are only examples: we can general the model that we want, and to write the templates we need. It is important to write the templates so that the generated code is similar to what we had manually generated. If we don’t feel comfortable with the generated code, if it does not have our style, our experience, we’ll end up generating something that we do not understand.

Another thinking: the model must be independent of the technology. In the final example, we have seen how, from the same model, we can generate solutions for VB.NET, CSharp and other technologies.

Software can help us to generate software. More: it MUST help us. Our experience counts: what we learned to make applications, we can overturn it in this species of expert system, code generation tools. In the future, I hope to be able to incorporate to the project, in the templates and tasks, more decision making: as well as we gain experience in writing of applications, we can incorporate our accumulated knowledge on patterns, architecture and styles of programming.

And as it is an open source project, AjGenesis allows us extend it, to our taste and necessity.

Suggestions, use case stories, comments are welcome. You can write as comments to this post, or write directly to me. Thanks to all that tested and adopted this project, and helped me to write it.

Angel “Java” Lopez
http://www.ajlopez.com/en

September 16, 2007

Interview preparation

Filed under: .NET, ASP.NET, C Sharp, Java, Programming Languages, Software Development — ajlopez @ 11:24 pm

Augusto Alvarez (a good guy that shares his knowledge, and who deserves to be in the NBA, he’s doubles me in height…. ;-) , sent me this interesting link:

http://interviewhelper.blogspot.com/

a blog that contains most common interview questions from different fields:

SQL Server Interview Questions
.NET Interview Questions
JAVA Interview Questions
Database
SQL Server
Software Testing
Basic .NET Framework
SAP Interview Questions
ABAP Interview Questions
C++ interview Questions
C Interview Questions
PHP Interview Questions
ASP.net Interview Questions
Java Interview Questions

I liked the “less technical” posts:

Points to remember
Salary Negotiation
Resume Preparation Guidelines

In my opinion, you must prepare a blog, where you must post about your knowledge, researchs, studies, interesting things you found, and more. You are you and your blog.

Just curious:

The Bloggers Business School

Angel “Java” Lopez
http://www.ajlopez.com/en

March 4, 2007

Call for Papers Object Oriented Technologies 2007

Filed under: .NET, Java, Programming, Software Development — ajlopez @ 10:23 am

I’ve received this information, looks interesting:

Call for Papers
=========
5th Object Oriented Technologies 2007
(Recently .NET Technologies)
International Conference in Central Europe on Object Oriented Technologies
http://OOT.zcu.cz
—————— CUT HERE ——————–
5th Object Oriented Technologies’2007
——————————————-
International Conference in Central Europe on Object Oriented Technologies
http://OOT.zcu.cz/
May 28 – 31, 2007
to be held at
University of West Bohemia
Campus-Bory, Plzen (Pilsen)
close to Prague – the Golden European city
Czech Republic
Conference Co-Chairs
————————
Jens Knoop, Vienna University of Technology, Austria
Vaclav Skala, University of West Bohemia, Czech Republic
Keynote Speakers
——————–
Kenneth Tan,Terry Moreland: Technical and Scientific Computing Performance: Today and Tomorrow, Optima Numerics Ltd., U.K.
Other agreements pending
MAIN TOPICS
—————
* SOFTWARE ENGINEERING software components, large-scale software, multi-language programming
* PARALLEL AND DISTRIBUTED COMPUTING multithreading, distributed applications, high-performance computing, web services
* PROGRAMMING LANGUAGES AND TECHNIQUES object-oriented techniques, programming paradigms, assertion support
* EDUCATIONAL ASPECTS teaching object-oriented paradigm, educational software
* ASPECT ORIENTED PROGRAMMING AND DEVELOPMENT
* VIRTUAL MACHINES and BYTECODE etc.
* HUMAN COMPUTER INTERFACES – computer graphics, visualization, virtual reality using Object Oriented Technologies
* ALGORITHMS AND DATA STRUCTURES
* SOFTWARE SECURITY
* Object Oriented Technologies DEVELOPMENT ON DIFFERENT PLATFORMS
* GRID Computing and its applications
* INDUSTRIAL APPLICATIONS of Object Oriented Technologies
* all relevant research/application papers relevant to Object Technology
Deadlines EXTENDED
———–
Paper submission:  March 15, 2007 13:00 GMT (London time)
Acceptance notification (expected): April 17, 2007
Final upload (expected): April 30, 2007 13:00 GMT (London time)
Venue: May 28 – 31, 2007
Submitted papers (FULL SIZE) will be peer-to-peer anonymously reviewed by at least three referees. Presented full, short communication papers and posters will be published in conference proceeding with ISBN.
The best selected papers will be published in the Journal of Object Oriented Technologies, printed version ISSN 1802-3126, electronic version ISSN 1802-3134.
The conference proceedings and the Journal of Object Oriented Technologies will be sent to INSPEC (IEE), ISI and others for citations index and other purposes.
Information on previous and forthcoming Object Oriented Technologies
(recently .NET Technologies) events can be found at:
http://OOT.zcu.cz
Conference Office and Contact
———————————-
Vaclav Skala, c/o University of West Bohemia, Computer Science Department
Univerzitni 8, CZ 306 14 Plzen, Czech Republic
skala@kiv.zcu.cz http://herakles.zcu.cz   FAX: +420-37-78 22 578
Conference supported by
—————————-
* Sun Microsystems Czech http://cz.sun.com/about/czech.html
* Microsoft Czech Rep. http://www.microsoft.com/cze/
* University of West Bohemia, Faculty of Applied Sciences, Dept.of Computer Science and Engineering http://www.kiv.zcu.cz
* Vienna University of Technology http://www.complang.tuwien.ac.at
* Center of Computer Graphics&Visualization, Microsoft Laboratory of Excellence http://herakles.zcu.cz

January 29, 2007

Code Generation with AjGenesis: A Hello World application

Filed under: .NET, AjGenesis, Code Generation, Java, Software Development — ajlopez @ 10:02 pm

My favourite project is AjGenesis, and I’m improving its examples every month. AjGenesis is a code generation engine, written in VB.NET. It’s an open source project, with a BSD-like license. The license allows you to use in any of your projects, commercial or not. It can be used as a library, invoked from your own application, or it can be run from the command line. It can be launched with NAnt tasks, so you can write powerful scripts to generate, compile, and deploy solutions in different technologies (not only .NET).

At the project page http://www.ajlopez.com/ajgenesis (and in the project .zip itself), there are lot of examples, that generates text artifacts and source code, starting from a free-form model. The generation process uses templates, written in an interpreted language, affectously named AjBasic. The examples generate PHP, Java, JSP, VB.NET, C#, ASP.NET code, and database scripts, with stored procedures and more. You can modify or create your own templates, at any moment. I want to stress two points:

- The model is form-free: you can define in any way you want

- The tasks and templates to run and apply are totally programmable and under your full control

This makes a difference with other code generation tools. You can define your own model, your own templates, to generate the text artifacts of your preference. Other tools start from the database schema, only to produce few code, as entities and DAOs. But with AjGenesis, sky (a textual sky) is the limit! :-) .

Lets take an example. This post is dedicated to model an application, as a proof on concept for the power of this tool. The target is to produce the most citated application: a Hello World app (my first encounter with such app was with the mytical book “The C Programming Language”, by Kernighan and Ritchie).

The example can be download from HelloWorld1.zip

First, the model. The model is a simplification of reality. A model, for example, a map, is not the territory, the reality. For AjGenesis, we need to write a model that manages the variable part of our system. In this case, a Hello World-like application, we want to model the message as variable. Then, create in a working directory, the file Project.xml:

<Project>
<Message>Hello World, by AjGenesis</Message>
</Project>

This is the first step, in a long journey. We didn’t use a predefined model. It’s simpler: we just write the model, in a well-formed XML file. No schemas, no DTDs, or weird things. Only our idea.

Second step: choose the target technology (programming language, platform, frameworks to use, databases….), to use in our example. Then, write (or reuse) templates. Now, we’ll use a VB.NET example, a simple console app. The template to write resides in the file HelloVb.tpl


‘ Hello World demo
‘ generated by AjGenesis
http://www.ajlopez.com/ajgenesis

Module HelloWorld
 Public Sub Main()
  System.Console.WriteLine(“${Project.Message}”)
 End Sub
End Module

Here, a feature from the templates: in the code, you can access and use in the output, the model data. If you write Project.Message between ${ and }, the AjGenesis processor will replace that text by the value of that branch of the model. You don’t use the XML syntax or something like XPath to access the model. The initial model was serialized in an XML file, but during processing, it’s brought to memory, as an object model, accesible via the familiar property syntax.

We would write the model as

<Project Message=”Hello World, by AjGenesis”/>

The memory model would be the same. Altough now Message is an attribute, for our template it’s still a Message property in the Project object.

Well, now we have the model, and the template. We must download and expand AjGenesis-0.4.3.zip (version currently under development, other versions are under the source code directory at the SourceForge project). In this version, there is a bin directory containing libraries and executables. The program AjGenesis.Console.exe can be invoked to load the model and to read the template, then, it generates a source code file. We enter at command line and run:

AjGenesis.Console Project.xml HelloWorldVb.tpl HelloWorld.vb

The paramaters can be:

An .xml file: when AjGenesis process a parameter that refers to an XML file, the represented model is loaded in its variable environment. The name of the root node is used as the name of the variable that contains the model. In our example, the variable is Project.

A .tpl file: it’s used as a template, is processed, generating a file with name equals to the next parameter.

The bin directory of AjGenesis distribution must be included in the path environment variable of your system.

The parameters are processed in order. We could have more than a model, using two or more XML files as input. For example, a second XML file could be used to describe the database technology to use, or the enterprise name and information to put in the generated source code, or anything else you want to model. In this case, the second XML file should have a different root node (not a Project one), so it will be loaded in a different global variable. We could put many template files with its corresponding generate files, in the same invocation, to generate more than one text artifact in one run.

After running the above command (we need a .NET framework installed in our system, remember that AjGenesis is written in VB.NET)), the file HelloWorld.vb is generated, with content:


‘ Hello World demo
‘ generated by AjGenesis
http://www.ajlopez.com/ajgenesis

Module HelloWorld
 Public Sub Main()
  System.Console.WriteLine(“Hello World, by AjGenesis”)
 End Sub
End Module

Well, it’s not a “Wow, what an application!!”, :-) , but it’s a first success.

Move forward. Now, with the same model, we want to generate our big system in Java. The market pressures, our customer needs, all point to use Java for the next version of our killer application. AjGenesis is here to help us! Lets go, create a file HelloWorldJava.tpl with

/**
* Hello World demo
* generated by AjGenesis
*
http://www.ajlopez.com/ajgenesis
*/

public class HelloWorld {
 public static void main(String [] args) {
  System.out.println(“${Project.Message}”);
 }
}

and run at the command line

AjGenesis.Console Project.xml HelloWorldJava.tpl elloWorld.java

Voilá! The file HelloWorld.java is generated:

/**
* Hello World demo
* generated by AjGenesis
*
http://www.ajlopez.com/ajgenesis
*/

public class HelloWorld {
 public static void main(String [] args) {
  System.out.println(“Hello World, by AjGenesis”);
 }
}

We’re in the road. Go for a more flexible example: we want to create the VB.NET program, and the Java file. We make the class and file name a variable (in the preceding templates, the name was fixed to HelloWorld).

The files for this second example can be download from HelloWorld2.zip.

To do that, in other working directory, create a file Project.xml with content:

<Project>
 <Name>HelloWorld</Name>
 <Description>Hello World Demostration</Description>
 <Message>Hello World, by AjGenesis</Message>
</Project>

Then, write the templates ModuleVb.tpl


‘ ${Project.Description}
‘ generated by AjGenesis
http://www.ajlopez.com/ajgenesis

Module ${Project.Name}
 Public Sub Main()
  System.Console.WriteLine(“${Project.Message}”)
 End Sub
End Module

and ClassJava.tpl

/**
* ${Project.Description}
* generated by AjGenesis
*
http://www.ajlopez.com/ajgenesis
*/

public class ${Project.Name} {
 public static void main(String [] args) {
  System.out.println(“${Project.Message}”);
 }
}

We’ll use another feature of AjGenesis: the capability to execute an script, in an interpreted language informally named AjBasic. I think that this a powerful feature, that open a new horizon, beyond the command line. With that feature, we can programmaticaly manipulate the model, and the tasks to execute. In the available examples, this capability is used at any point, producing complete solutions, with dozens of auto generated files. But, back to our example

The program is written in the file Build.ajg

PrintLine “Generating ${Project.Name}”

TransformerManager.Transform(“ModuleVb.tpl”, “${Project.Name}.vb”, Environment)
TransformerManager.Transform(“ClassJava.tpl”,”${Project.Name}.java”, Environment)

The AjBasic language has some predefined verbs, like the autodescriptive PrintLine. You must take note that, as in other scripting language, this one has expression expasion inside the strings. That is, when a text is between double quotes (a string constant), an expression inside ${ and } is located, and replaced by the corresponding value in the model. You can recognize her a behaviour similar to others languages, like Unix scripting languages, PHP, or JSP Expression Language.

The variable TransformerManager is one of a few predefined ones. I didn’t define a lot, and you can add new variables, if needed. The TransformerManager object is used to programmaticaly invoke what we used to run from the command line. Then, the first parameter of its Transform method is the template file name, the second is the file name to generate, and the third and last is the variable collection, known as the AjGenesis environment (Environment is a predefined variable that points to the current environment).

We run the above file with the command line

AjGenesis.Console Project.xml Build.ajg

The console program is prepared to execute each parameter that refers to an .ajg file, as an AjBasic program.

Lets go forward. During 2005 (AjGenesis project has years in development), I added NAnt support. That is, I wrote AjGenesis tasks that can be invoked from that great tool. Additionally, I use the NAnt-GUI utility to execute the .build files from a graphic interface.

Write a default.build file with the content (update the ajgenesis.dir property to point to your AjGenesis installation directory):

<?xml version=”1.0″?>
<project name=”Example 1″ default=”build”>
<property name=”ajgenesis.dir” value=”c:/ajlopez/dev/AjGenesis-0.4.3″/>
<property name=”nanttasks.dir” value=”${ajgenesis.dir}/bin”/>

<target name=”clean” description=”cleans build directory”>
   <delete dir=”${build.dir}” verbose=”true” if=”${directory::exists(build.dir)}” />
</target>
<target name=”loadtasks” description=”loads AjGenesis tasks”>
   <loadtasks assembly=”${nanttasks.dir}/AjGenesis.NAnt.dll” />
</target>

<target name=”init” depends=”loadtasks” description=”init the AjGenesis model”>
   <loadmodel model=”Project.xml”/>
</target>

<target name=”build” depends=”init”>
   <executetask task=”Build.ajg”/>
</target>
</project>

Then, invoke from the command line:

nant

If we configured the NAnt tool, this utility process the default target from the build.xml file. You can use the NAnt-GUI utility, that shows a window like this:

I hope this article helps you to a quick start up in AjGenesis development. In a future post, I’ll explain more examples, model manipulation in memory, intensive use of NAnt, and complete solution generation, in different platforms and technologies.

If you find this utility useful, you can collaborate spreading the word, writting some comment or post about your AjGenesis experience.

Suggestions, and ideas, welcome!

Thanks for all!

Angel “Java” Lopez
http://www.ajlopez.com/en
http://www.ajlopez.com/ajgenesis

Java on the Client side, and Swing Look and Feel

Filed under: Java — ajlopez @ 1:35 pm

I’ve just discovered a blog, with tons of information about using Java on the client side:

http://www.clientjava.com

You must use the search box, apparently, the normal navigation isn’t working now. I found that site, searching resources about changing the look and feel of a Swing application. Then, that blog has this old, but useful entry:

http://www.clientjava.com/blog/2004/07/07/1089221149000.html

For more information about Swing Look and Feel, you can visit:

http://java.sun.com/products/jfc/tsc/articles/lookandfeel_reference/index.html
http://www17.homepage.villanova.edu/william.pohlhaus/is/doc/Java%20Look%20and%20Feel.htm
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-LAF.html
http://gtkswing.sourceforge.net/
http://javootoo.l2fprod.com/

Angel “Java” Lopez
http://www.ajlopez.com/
(yes!! it’s my sabbatical week!!!…. http://ajlopez.wordpress.com/2007/01/27/sabbatical-week/ )

January 14, 2007

Source code examples: Java, ASP.NET, C Sharp, VB.Net, Spring, Hibernate…

Filed under: .NET, ASP.NET, Books, Java, Software Development — ajlopez @ 9:26 pm

I just discovered the site

http://www.java2s.com

It has lots of source code in Java, ASP.NET, C#, VB.Net. It has examples for Swing, Tomcat, Spring, Hibernate, JavaServer Faces. It includes examples for JavaScript, Cascading Style Sheets, Dynamic HTML. It has applications of Patterns, JavaServer Faces, JavaServer Pages, DataSets, and… The list is big.

And book examples, like:

Spring Live

and

Struts

A lot of resources.

Angel “Java” Lopez
http://www.ajlopez.com/en

Older Posts »

Blog at WordPress.com.