Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Wednesday, August 31, 2011

How to create a new Content List Template for eXo Platform 3

Introduction

eXo Platform provide many powerful features to manipulate and expose any type of content on a page. This is due to the fact that eXo stores the all the content in its Java Content Repository (JCR) and render the content on a page using Groovy Templates.

In this how to you will learn how you can create and use template that are used in the "Content List" portlet. For example in the ACME sample site you can show the content in 1 or 2 columns just by selecting different templates.


One Column View

Two Columns View

Creating a new Content List Template

In this section you will learn how to create a new template using the eXo IDE. Before writing the new template it is important to learn where the templates are stored.

eXo Content Service: Template Storage

Like many things inside eXo Platform, the eXo JCR is used to stored the templates. Templates are just a special type of content. This allows developers to easily write and test code without having complex deployment process, but also it make the life easy to export a running configuration to another one. For this you just need to use the standard JCR export/import features.
All the template and eXo Content Service configurations are stored inside a specific JCR workspace named : dms-system.
Each template type (Document Type, Content List, ....) is stored in a specific location. In our case we want to work on the "Content List" portlet so the template are stored inside the following folder:
  • /exo:ecm/views/templates/content-list-viewer/list/

Just for the fun of it, let's inspect this folder using the eXo CRaSH utility. If you are not interested you can jump to the next section. CRaSH is a shell for Java Content Repositories, the source of CRaSH is available on Google Code. So in a terminal window:
  1. Connect to CRaSH using telnet client:
    telnet 127.0.0.1 5000

  2. Connect to the JCR workspace using the following command:
    connect -u root -p gtn -c portal dms-system
    Where: -u is the user, -p the password, -c the Portal Container, and dms-system the workspace to use

  3. Move the the folder that contains all the templates for the Content List portlet:
    cd /exo:ecm/views/templates/content-list-viewer/list/

  4. List all the templates using the ls command


You can see the list of all the templates available for the Content List portlet.

Create a new template using the eXo IDE

Let's now create a new template using the IDE. For this be sure you are connected with a user that is part of the /Developer group. For simplicity reason I am using the root user.

The first important step is to go the the template location using the following steps:
  1. Access the IDE: click on My Spaces > IDE.

  2. Switch dms-system workspace: In the IDE menu click My Spaces >on Window > Select Workspace. And select the dms-system location in the dialog box and click OK.

  3. In the file structure on the left navigate to the template location :
    /exo:ecm/views/templates/content-list-viewer/list/

  4. Create a new template : In the IDE Menu click on File > New > Groovy Template

  5. Save the file as "MyNewTemplate.gtmpl"

  6. Enter some basic code:
    <h1>This is my template</h1>
    The date is <= new Date()>
    


  7. Save the template

  8. Go back to the Home page of the Acme Site

  9. Switch to Edit more by selecting Edit in the top right drop down list.

  10. Move you mouse at the top of the list of news and click on the preference button:

  11. In the list of templates, select the "MyNewTemplate", and click save.
We have created our new template, and use it on a page. We should now add some more interesting code to the template to really loop over the content based on the portlet configuration. But before this it is important to talk about caching and code modification.

eXo Template and Cache

To improve performances and a running system, the compiled version of the template is by default cached. This is why when you are modifying a template you do not see any change. We have two ways to work around this:
  • Run eXo Platform in Debug mode, in this case nothing is cached
  • Invalidate the cache manually using JMX
Since working with no cache at all is not an option, here is the MBean you have to use to invalidate the Template Service cache:
  • exo:portal="portal",service=cache,name="TemplateService", then call the clearCache operation on it
I do use JConsole for this, but you can use any method to call your MBeans operation.

Do not forget to call this operation each time you modify your template to be sure eXo recompile the template.

Accessing Content in the template

The current code of the template is really simple, you need now to add code to print the content in the page. For this we will be using some eXo Content programming, once again in the IDE.
If you are not interested to have detailed explanation of the code you can go to the complete source code here.
The template used by the Content List portlet is based on the following Java class org.exoplatform.wcm.webui.clv.UICLVPresentation, this class is responsible to set the complete context that you can use in the template such as:
  • The folder or category that contains the content to show. The "Folder Path" field in the preference screen
  • The display settings: title, number of documents, elements to show, ...
Here is the code to access these preferences:
    // import all the classes need in the template
    import javax.jcr.Node;
    import org.exoplatform.wcm.webui.paginator.UICustomizeablePaginator;
    import org.exoplatform.wcm.webui.clv.UICLVPortlet;
    import org.exoplatform.wcm.webui.Utils;
    import org.exoplatform.services.wcm.core.NodeLocation;

    // get the portlet preferences
    def header = uicomponent.getHeader();
    def isShowRssLink = uicomponent.isShowRssLink();
    def isShowHeader = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_HEADER);
    def isShowRefresh = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_REFRESH_BUTTON);      

    def isShowTitle = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_TITLE);
    def isShowDate = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_DATE_CREATED);
    def isShowLink = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_LINK);
    def isShowReadmore = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_READMORE);
    def isShowImage = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_ILLUSTRATION) ;
    def isShowSummary = uicomponent.isShowField(UICLVPortlet.PREFERENCE_SHOW_SUMMARY);   

The uicomponent object is defined by the container class of the portlet that calls the template. This class contains many utility methods. In the code above I retrieve all the preferences of the portlet, since the name are self-explanatory it is not necessary to detail them, especially when you look at the preferences screen below:


Now that the template has all the preferences, it is time to loop on the content on print the information.
The eXo Content Service provides API to manipulate the content, including pagination of content. The idea behind this is to let the Content Service manage the JCR query, sorting, caching and pagination of data. So in your template you will mainly manage two classes to loop through the content to show:
  • uicomponent.getUIPageIterator() a paginator object that is configured based on the portlet preferences
  • uicomponent.getCurrentPageData() contains a list of the content (JCR Nodes) that should print on the current page
So let's print all the content of the page as a simple HTML list:
    <% for (viewNode in uicomponent.getCurrentPageData()) { def title = viewNode.getProperty("exo:title").getString(); print("
  • $title
  • "); } %>
Just copy this code in your template, save it, refresh the cache... and go to your page. You should see the list of the content in a simple HTML list.
On each content (Node), eXo Content API provides some helper method to easily manipulate the content and avoid using the JCR API directly. In the following code you can see the most important methods accessing content properties:
        def itemName = viewNode.getName();
        def itemLink = uicomponent.getURL(viewNode);  
        def webdDavLink = uicomponent.getWebdavURL(viewNode);    
        def itemDateCreated = uicomponent.getCreatedDate(viewNode);
        def itemModifiedDate = uicomponent.getModifiedDate(viewNode);
        def itemAuthor = uicomponent.getAuthor(viewNode);     
        def imgSrc = uicomponent.getIllustrativeImage(viewNode);
        def itemTitle = uicomponent.getTitle(viewNode);
        def itemSummary = uicomponent.getSummary(viewNode);
One important point is the fact that these methods are responsible of many things, for example: formatting dates, returning complete URLs depending of the context of the portlet.
Based on these methods you can now work on the presentation of the information on the page. Let's for example print the image, the title and allow user to click on the title to go in the detail view of the article. This is done simply using the following code:
<%
  for (viewNode in uicomponent.getCurrentPageData()) {
    def itemName = viewNode.getName();
    def itemLink = uicomponent.getURL(viewNode);  
    def webdDavLink = uicomponent.getWebdavURL(viewNode);    
    def itemDateCreated = uicomponent.getCreatedDate(viewNode);
    def itemModifiedDate = uicomponent.getModifiedDate(viewNode);
    def itemAuthor = uicomponent.getAuthor(viewNode);     
    def imgSrc = uicomponent.getIllustrativeImage(viewNode);
    def itemTitle = uicomponent.getTitle(viewNode);
    def itemSummary = uicomponent.getSummary(viewNode);
    
    %> 

$itemTitle

$itemSummary
<% } %>
For simplicity reason, this code does not manage any null value. Also the template do not deal with the portlet preferences such as the "Header", "RSS" links and so on, do not hesitate to do it if you want. The Web site should look like the following image:


The last important point is to add the support for the in context editing that allows the user to edit the content directly from the template. Once again this is done with a method of the uicomponent object, that create a DIV around the content. Let's add this to the template:
<%
  for (viewNode in uicomponent.getCurrentPageData()) {
    def itemName = viewNode.getName();
    def itemLink = uicomponent.getURL(viewNode);  
    def webdDavLink = uicomponent.getWebdavURL(viewNode);    
    def itemDateCreated = uicomponent.getCreatedDate(viewNode);
    def itemModifiedDate = uicomponent.getModifiedDate(viewNode);
    def itemAuthor = uicomponent.getAuthor(viewNode);     
    def imgSrc = uicomponent.getIllustrativeImage(viewNode);
    def itemTitle = uicomponent.getTitle(viewNode);
    def itemSummary = uicomponent.getSummary(viewNode);
    
    %> 
<%=uicomponent.addQuickEditDiv("MyTemplateContentEditor", viewNode)%>

$itemTitle

$itemSummary < /div>
<% } %>
The lines 15 and 19 are new in this template and provide support for Quick Edit feature.

Done! We have created a new template for eXo Platform Content Service using embedded IDE.

Conclusion

In this article you have learned how to create a new template for eXo Content Service, with some basic steps:

  • Create a new Groovy Template using the eXo IDE
  • Edit this template using the eXo Java Content API
  • Configure your Content List portlet instance on a page to select the new template

You can now create your own templates and use your imagination to add cool features to your site (for example the carrousels you see on the eXo site are using custom CLV template.)

Tuesday, July 29, 2008

A month in eXo... busy, busy, busy...

I have been within eXo Platform for almost 2 months now.. As expected, it is crazy, and exciting. This is why I did not have lot of time to blog... Ideas are here, just time is not... So here a very quick post on my current work... We have been releasing new releases of products (Portal/Portlet Container, Collaboration Suite), deliver a training on eXo Portal, writing docs, articles, and many other exciting things... One of them is this nice example of integration of GWT Google Gadget in eXo WebOS. During this period, when I was not working with customers, prospects and partners, I have learned a lot about one of the most exciting and powerful features: eXo ECM coupled with eXo Portal/WebOS. eXo exposed using a powerful UI, and set of API, its JavaContent Repository on which you can build powerful sites/portal using eXo templating engine... and one other cool thing, at least for me, is the fact that most of the programming that you do, including rich Ajax based application is done using Groovy. (using GroovyServer Pages)... More to come about eXo features on this blog, but the best place to be is to follow our company/project blog at http://blog.exoplatform.org, where all the team is presenting new features, and events of the eXo community... Also, I have created, with Sebastien Roul a JUG in Nantes, here some information for French people:

Friday, May 16, 2008

JavaOne 2008: Groovy and Grails presentations and code

Andres and Guillaume have posted on the Groovy Users list the pointers to many (if not all) the Groovy and Grails sessions of JavaOne 2008... You want to learn more, this is a great opportunity to do it so:

Thanks to all of the authors... I would love to be there watching these session live... This post is the opportunity also to point you to this video from InfoQ of Jason Rudolph doing a very nice introduction to Grails during last year QCon conference...

Thursday, May 1, 2008

JavaOne 2008: my sessions choice...

I have attended or presented at JavaOne for the last 6 years when I was living in the SF Bay Area... But this year I won't be in San Francisco for JavaOne. As you can guess, I am sad about that... However, I still look at the schedule and events, and here what I would like to do:

  • Groovy/Grails meetup organized by G2One and NFJS
  • Sun and Oracle General Sessions: Tuesday, Wednesday and Friday at 8:30am. I am particularly interested to see the Oracle's one  talk about the Oracle/BEA deal... May be we will be able to learn more about the products roadmap
  • TS-6050 - Comparing JRuby and Groovy
  • TS-5274 - Groovy on a Cloud: Testing Java EE Platform Applications on Amazon EC2
  • BOF-5102 - Cooking Your Own Groovy Builder: A Step Forward into Domain-Specific Languages
  • TS-5793 - Groovy and Grails: Changing the Landscape of Java EE Platform Patterns
  • BOF-5101 - Boosting Your Testing Productivity with Groovy
  • TS-5764 - Grails in Depth
  • TS-6298 - Designing Graphical Model-Driven Applications: Lego MindStorm ... long time that I have not programmed/designed with my Legos...
  • BOF-4888 - Taming the Leopard: Extending OS X the Java Technology Way: would be great to see my ex-coworker talking about OS X and Java.. John and Tim are terrific developers
  • BOF-6400 - The Future of Guice. even if I have not used (yet) this API from Google I have been a big fan of Bob's work
  • TS-5657 - JavaFX Technology: Bring the Web with You--Multiple Interfaces to Games, Chat, and More
  • TS-4817 - The Java Platform Portlet Specification 2.0 (JSR 286)
  • TS-5343 - Enterprise JavaBeans (EJB) 3.1 Technology. As I am pushing more and more customer to use the standard JPA.. would be great to learn more about the next release of EJB
  • TS-6169 - Spring Framework 2.5: New and Notable... would like to see what will be said about SpringAppServer
  • TS-6072 - Advanced Enterprise Debugging Techniques
  • BOF-5634 - Java EE Platform Connector Architecture 1.6 Overview. I have been using J2CA a lot lately when dealing with SOA in large IT department... So quite cool to have an update on this spec.
  • TS-5318 - Dealing with Asynchronicity in Java Technology-Based Web Services. A feature in the WS Stack that I have been pushing a lot...
  • TS-5616 - JSR 303: From a World of Constraints to Constrain the World
  • TS-6339 - Top 10 Patterns for Scaling Out Java Technology-Based Applications
  • TS-5706 - SCA and Java Platform, Enterprise Edition (Java EE Platform): Integration Inside
  • BOF-5495 - Untangling the Asynchronous Web
  • TS-5425 - JAX-RS: The Java API for RESTful Web Services
  • LAB-4500LT - Develop AJAX Based Portlets With OpenPortal and GWT
  • TS-6574 - How to Implement Your Own OpenSocial Container on the Java Platform
  • TS-6807 - What’s New in Ajax
  • BOF-5661 - Comet: The Rise of Highly Interactive Web Sites
  • BOF-4922 - Writing Real-Time Web Applications, Using Google Web Toolkit and Comet
  • TS-5870 - The Best of Both Worlds with Java™ Business Integration and Service Component Architecture
  • TS-5152 - Overview of the JavaFX Script Programming Language
  • TS-5572 - Groovy, the Red Pill: Metaprogramming--How to Blow the Mind of Developers on the Java Platform
  • TS-5815 - Going Mobile with JavaFX Script Technology, Groovy, and Google Android
  • TS-5535 - Tying Java Technologies Together the RESTful Way
I have probably selected many conflicting sessions, not really an issue since I am not going there. That said, this year again JavaOne looks quite exciting and a lot of content again around Scripting Languages and Framework; Web2.0 related technologies and SOA. 
I hope that I will be there for the 2009 one ;)

Monday, April 21, 2008

Launch of Exo Enterprise WebOS

Last Friday (April 18th) I was attending the launch of "eXo WebOS" in Paris. Benjamin Mestrallet, creator of eXo has started the event with a presentation of the solution and its impact on the IT. Like any internet user, each time I see eXo Web OS and applications I am very very impressed. They have pushed very far the use of AJAX based applications to offer a complete virtualization of the OS/Desktop, not in a Virtual Machine, but simply in your favorite browser.

As you can see in this screenshot, eXo is launching in your browser, a complete desktop, where I run many applications provided by eXo: Calendar, Forum, Mail, but a also a calculator gadget attached to the desktop itself. The easiest is to try the product, go to eXoplatform site and download it. After the presentation of the eXo new features, and vision, two customers have presented their project based on eXo Portal and Collaboration Suite:
  • M6. M6 is one of the major French TV channel. M6 is using eXo for their new intranet. Some of the key point that I kept from this experience:
    • Flexibility/Agility of the platform: M6 IT has been able, with Business&Decision, to answer end user needs in term of design/look&feel. Quite important in media industry ;)
    • Extensibility: in addition to the pure publishing of personalized pages, eXo has showed lot of power. Creation of new services based on the core architecture of eXo (IoC based container), or simply by creation new Groovy script to capture events in the Java Content Repository. One example of such script, is the creation of a new script to automatically resize images when they are published in the repository.
  • Belgium Minister of Finances, with Bull Belgium In addition to the classical portal usage of eXo. They have chosen to put in place for their 30 000 users, the brand new eXo Collaboration Suite (Mail, Calendar, Contacts) and even more exciting use the real time collaboration tools provided by eXo LiveRoom. This extension to eXo provides using a Flex based architecture exciting tools for collaborative work:
    • Video and Voice over IP for Web conferences
    • Shared Whiteboard allowing multiple people to see and modify documents and graphics
    For me these tools in addition to the eXo chat (Ajax based) are really exciting, and this for many reasons:
    • it shows how the "Web 2.0" can really facilitate the collaborative work
    • eXo is a green product ;) because with the eXo CS people do not need to travel to meet and work together.
The event was closed by a very passionate Round Table, moderated by Christian Faure (Atos Origin) with Adobe (Michael Chaize), eXo (Benjamin Mestrallet), Google (Dave Armstrong), Microsoft ( Christophe Lauer), Mozzila (Tristan Nitot) and Sun (Eric Mahe) have discussed many topics around Web/Internet, Standards, Open Source, and Web OS... If you are french speaker I am inviting you to take a look to the recording of this event available on the eXo blog:

Friday, January 18, 2008

Infoq news: "Request: Sun, Drop Support for JRuby"

With the latest big news around Oracle-BEA and SUN-MySQL deals I have missed an interesting article on Infoq with the following title:
- Request: Sun, Drop Support for JRuby
I have to say that I do agree with Craig Wickesser asking Sun to Drop Support for JRuby.

Syntax Matters?
Yes syntax matters, not only for the "beauty" of it, but also because of the investment that enterprises have made into it. We should not force people to completely remodel their brain all the time, for no gain. 

I love Groovy language, and one of the main reason is because it gives me the most bang for my buck. Java people can immediately catchup with the syntax, and step by step leverage powerful features available by dynamic languages and domain specific languages. I was hoping to see a great adoption by SUN... It is one thing to support scripting with the JSR-223, but SUN has to "endorse" a scripting, and from what could be seen today it is not Groovy nor Javascript. When we see all the marketing noise it is Ruby with JRuby... And I do not think that is necessary good for the Java platform. 

Do not get me wrong, I think that is a great idea, and need for Java to be able to execute many languages, for example we see a lot of IBM WAS and BEA WL administrator using Python to administer their application server instance with Jython. But once again the "default" one should be close to Java and integrate with it as close as possible to reduce the impact on scalability and performances, and I do think that Groovy did a great job on these topics.

What about RubyOnRails?
I am not a RoR expert, far far away from it, but I have learned it, and developed small applications with it, and I have to say that I love this framework.  And I am sure that like many Java developers that used RoR, I was thinking:  "If only I had the same productivity in my favorite platform: J2EE...".

I was not expecting to run RoR application as-it-is, but more hoping that JavaEE will learn from RoR to simplify development...  And... somebody did it, with Grails. Grails takes inspiration from RoR, but in a "real" JavaEE environment, since it leverages key pieces of the current Java applications such as Hibernate and Spring, using the power of Groovy to glue all this together.

In conclusion...
I do not know for you but yes I do think that SUN should drop support for JRuby, and in place push a language more natural for existing Java Developers, I vote for Groovy. In addition to the language itself, I also expect the JavaEE EG to provide a more productive way of developing "simple" Web applications. This is where I see Grails coming in the picture, but many other framework could do the job, taking advantage of some interesting concepts of RoR...

As Rick says, I (we?) am not looking for a Revolution but for an Evolution.

Thursday, November 8, 2007

A Groovier ADF with Oracle ADF 11

Steve Muench has published in Oracle Magazine an article about the use of Groovy in Oracle ADF. In this article you learn how you can do validation and calculation in you business service layer.

Tuesday, September 25, 2007

Derek Sivers's blog: 7 reasons I switched back to PHP after 2 years on Rails

The new post on the Ruby section of O'Reilly authored by Derek Sivers is quite interesting, starting with the title:

I am far away of being a PHP expert, or even a Ruby one, but I have the impression that I could post a similar title with Java instead of PHP. If this is true that Java EE could look a little complex for a start -this is probably less true today with the new JavaEE simplifications-. Yes... when you compare Rails and Java alone it is more complex but we should not forget that Java is now more a platform than a simple programming language. And many developers and companies have built very productive solution on this platform.

Since I am talking about Ruby on Rails here, it is important to mention again Grails and Groovy that provide on the Java platform a simple and productive way to develop applications, and time to get back to the different reasons mentioned by Derek in his post:

#1 - “IS THERE ANYTHING RAILS/RUBY CAN DO THAT PHP JAVA CAN’T DO? … (thinking)… NO.”
I believe that we will all agree on the fact that you can do anything you want in Java; Web applications, mobile applications, operating systems, rdbms, ... the only limit is your brain! -and your skills ;) -

#2 - OUR ENTIRE COMPANY’S STUFF WAS IN PHP JAVA: DON’T UNDERESTIMATE INTEGRATION
I think this is one of the key point here. Enterprise is using JavaEE a lot and it is part of the IT, moving to another technology will be expensive even if development is faster. In addition, the developers, administrators are used to develop and manage Java based applications.

And I do not want to talk about how complex it could be when you are building a Rails application on an existing database, designed from a pure Entity/Relation methodology....

#3, #4 #5 - I have nothing special to say here...

#6 - I LOVE SQL
I still see a lot of developers using SQL directly in Java programs. The nice thing about Java is the fact that based on your skills and what you like to do you can choose the way you want to access the database, simple SQL, powerful O-R Mappings, ...

#7 - PROGRAMMING LANGUAGES ARE LIKE GIRLFRIENDS: THE NEW ONE IS BETTER BECAUSE *YOU* ARE BETTER
I love this reason, but nothing special to say, I let you read the original post.

As you can see from the number of comments in Derek's blog -no times to read all of them- this entry generates lot of reactions.

Wednesday, April 18, 2007

Using Groovy within Oracle Data Integrator

As you may remember, Oracle acquired few months back a data integration solution from Sunopsis, and has integrated it in our product under the name "Oracle Data Integrator" (ODI).

One of the first thing that I look when we got this product was the support for Scripting technologies, since it makes lot of sense to have such support in any ETL. And yes ODI has support for Jython (thought BSF). So when the dev team joined Oracle, I've asked the following question "did you try to use Groovy?"... I personnaly did not take the time to test, but one of the developer did and document it in his blog: "Using Groovy and ODI" from Thierry. When I get a chance I will provide a more complete sample of using Groovy in Oracle Data Integrator.

Friday, March 23, 2007

Grails vs Rails Performance Benchmark

Graeme, the Grails Project Lead has published a very interesting benchmark of Grails versus Rails applications, that is available on the Grails wiki: I let you read and comment on the Wiki the results... Grails development team is open to comment and improvement of the bench to capture as much information as possible. It is also important to note that performances, productivity are very important when choosing a development environment; but something that is also key for enterprises, is the fact that Grails/Groovy "are" Java/J2EE based. This means that a Grails application is packaged, deployed, administered and monitored like any applications that already exist in the information system on J2EE application servers.

Thursday, February 22, 2007

The first International Grails eXchange 2007

Packed with presentations on Grails, Groovy, Ajax & Web 2.0 and JavaEE and the core technologies that support the Grails technology, the first Grails eXchange conference (London from May 30th to June 1st) will be the place to be for any member of the Groovy/Grails community... You can already register on the conference web site: http://www.grails-exchange.com

Come to see speakers including Grails project lead Graeme Rocher, Groovy project lead Guillaume LaForge, creator of Spring Rod Johnson, Dojo's Alex Russel and Dylan Schieman as well as speakers from technology-leading organisations such as Google, Interface 21, JBoss, Oracle & Sun Microsystems

Tuesday, February 20, 2007

Groovy 101: Extracting XML from your database

In the previous entry I showed how you can easily take an XML feed and insert the content in the database. Let's do the opposite now, meaning taking the data out of your database as XML. In this post I am using the Sql Dataset again but to create an XML document, using the Groovy MarkupBuilder.

import groovy.sql.Sql;
import groovy.xml.MarkupBuilder;

def sql = Sql.newInstance("jdbc:oracle:thin:@//tgrall-linux:1521/XE",
                                      "HR", "HR", "oracle.jdbc.driver.OracleDriver")
def set = sql.dataSet("EMPLOYEES");

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.employees() {
  set.each { emp ->
    employee(first: emp.first_name , last: emp.last_name) {
      email( emp.email )
    }

  }
}

println writer.toString();
As you can see, I use the builder to create XML Elements and attributes employee(first: emp.first_name , last: emp.last_name), I do reference the current record of the dataset (emp), and all this in very simple and concise code. This will give a result like:
<employees>
<employee first="'Steven'" last="'King'">
  <email>SKING</email>
</employee>
<employee first="'Neena'" last="'Kochhar'">
  <email>NKOCHHAR</email>
</employee>
<employee first="'Lex'" last="'De">
  <email>LDEHAAN</email>
</employee>
...
</employees>

So once again quite simple.

Sunday, February 18, 2007

Groovy 101: Importing XML in your database

A friend of mine was looking for an easy way to import some XML content in his database. You have many ways to do it. But the easiest for a Java/Groovy developer is to use Groovy, and I have create this small example for him.

Groovy provides really simple solution to parse XML and manipulate your database. The following sample reads an RSS new feed and import the title and link in a table named NEWS that contains two columns TITLE and LINK.


import groovy.sql.Sql;

def rssFeed = "http://www.javablogs.com/ViewDaysBlogs.action?view=rss";
def xmlFeed      = new XmlParser().parse(rssFeed);

def sql = Sql.newInstance("jdbc:oracle:thin:@//tgrall-linux:1521/XE",
                         "GROOVY",
                         "GROOVY",
                         "oracle.jdbc.driver.OracleDriver")
def set = sql.dataSet("NEWS");

(0..< xmlFeed.channel.item.size()).each {
   def item = xmlFeed.channel.item.get(it);
   def title = item.title.value[0];
   def link = item.link.value[0];
   println("Importing $title ...");
   set.add(TITLE: title, LINK: link);
}

First I create a Groovy SQL object and a DataSet to manipulate my data. sql.dataSet("NEWS"). Do not forget, if like me you are using Oracle database, to add the Oracle JDBC driver to your classpath ;-)

Then I create a loop on each items of the RSS feed I am using: (0..> xmlFeed.channel.item.size()).each {...}. As you see, Groovy XML help me to parse, and navigate the XML document.

Like any Groovy iterator you have access to an implicit object available in the loop "it", so I can get the item using the Groovy XML : xmlFeed.channel.item.get(it)

Then you can get the different values you want of the element.Usingthe dataset.add method, you can insert them in the table.This is done using the value pairs notation column:value, this looks like: set.add(TITLE: title, LINK: link)

Wednesday, February 7, 2007

New Groovy Plugin for Oracle JDeveloper 10g

You can find a first release of the Groovy extension for JDeveloper on the Groovy site:
 http://groovy.codehaus.org/Oracle+JDeveloper+Plugin

The plugin creates a new JDeveloper library for Groovy 1.0, allows you to create and run scripts. I hope to be able to provide more feature such as syntax coloring, structure recognition, ... lot of ideas here...

Tuesday, January 2, 2007

Groovy 1.0 released

Groovy release 1.0 is here now ! You can find the release at the following location: - http://dist.codehaus.org/groovy/distributions/ Congratulations to all the Groovy developers, and users that have done a great job with this language that is here in production. And it is interesting to see that more and more projects are using Groovy as part of their infrastructure to simplify development: - SOAPUI - XWiki - Spring 2 integration - Grails - ... and many development teams in custom projects So once again happy new year to all... and enjoy it with Groovy !

Friday, December 22, 2006

A nice christmas present for Groovy and Grails project

The groovy project gets funding for its development. Big Sky is hiring Jochen Theodorou one of the Groovy commiter. For the people that do not know Big Sky, Big Sky is the company behind the the No Fluff Just Stuff symposium tour. Talking about this symposium, in 2007, Groovy and Grails will have a dedicated track.

More about this funding:


In addition to this very good news, here some other activities around Groovy and Grails:
  • Releases of Groovy 1.0 and Grails 0.4
  • Two books on Groovy and one on Grails.
  • A dedicated Groovy and Grails website: aboutGroovy.com
  • Also a dedicated Groovy and Grails conference: the Grails eXchange 2007
  • And the third Groovy Developer Conference in Paris at the end of January

Tuesday, December 5, 2006

Web Conference: Groovy & Grails UG London

The London Groovy and Grails User Group will be holding their next meeting on Wednesday, 6th December 2006 at Skills Matter in London and for the first time ever the meeting will be available via a live web conference, so don't worry if you are not in London! Speaking at this month's meeting will be Graeme Rocher, Grails Project Lead and CTO at Skills Matter. During his talk entitled; Grails Dynamic Tags: Making Tag Libraries Agile, Graeme will discuss Groovy Server Pages and its support for the creation of dynamic tag libraries without the need for configuration. John Wilson, Groovy Committer, will also be presenting at this meeting. During his talk, entitled; The MetaClass: How Groovy works Under the Hood, John will shed light on the MetaClass so you can better understand its' function and see how to use it to get your Groovy programs smaller, clearer and faster. For more information on attending this meeting or signing up for the web conference, please go to: http://skillsmatter.com/groovy-grails-ug

Tuesday, September 19, 2006

Choose a scripting language? Groovy or JRuby?

Last week I discussed dynamic languages with some consultants. This discussion was done in the context of integration of scripting technologies into Java EE environment. So the integration to the VM is important, I also think that the learning curve is a thing to consider.

It is true that, like any developer Iike to learn things everyday, this is why I have done some development with PHP, with Ruby On Rails, and obviously with Groovy, Javascript and many other dynamic languages.

The discussion moved quickly to an argument about which language is the best... Hard to say, but I would expect that to be more productive in enterprise it is better to use a "Java Like" syntax that allows you to leverage the power of scripts. Based on this comment it is for me a no brainer to say that Groovy is more interesting to a core Java developer than JRuby (or other Jython, Jacl, ...). I do not even want to go in the details about VM integration, performances and so on...

So in this context, A. Sundararajan has posted a very interesting comparison of Java, Groovy and JRuby syntaxes.

Wednesday, May 3, 2006

Grails on Oracle (OracleAS and OracleXE)

OTN (Oracle Technology Network) Readers have noticed, that Oracle has published an article from Richard Monson-Haefel about Ruby On Rails on Oracle. This article introduces the Ruby On Rails framework and explains how to use it to access an Oracle database. (Oracle 10g Express Edition to be exact) If you are not familiar at all with Ruby On Rails, it is important to notice that it has nothing to do with Java, J2EE. It is a Ruby based framework. So yes Ruby On Rails is really interesting, powerful and so on... but for me as a Java developer I would like to do the same using Java (or equivalent) leveraging the investment that I have done in J2EE; also important I want to be able to deploy and manage applications that are developed this way using my tools such as Oracle Enterprise Manager Application Server Control. The paradigm "coding by convention" that is the driver of Ruby on Rails has been leveraged to developed a new framework: GRAILS. Grails uses Groovy as the underlying language, so it runs on a JVM and can leverage any existing Java API. If you are a Java developer you will find very interesting to use this framework to accelerate the development of Web applications. If you are not yet a Java developer but need to develop Web application faster, and deploy the to your J2EE application server, Grails is also a very good tools. Since I have started with Richard's article I will use the same application/database schema to develop my first GRAILS application, and also use the same structure in my article...(is it what we call lazy loading?)

What is Groovy? What is Grails?

Groovy is a dynamic language that leverage features from other languages such as Ruby, Jython, and Smalltalk. Groovy is running at the top of a Java VM and makes available any existing Java objects (so all the API) to Groovy. Groovy is currently under standardization with the JSR-241. You can learn more about Groovy on the Groovy site and is project leader's (Guillaume Laforge) blog. GRAILS is to Groovy what Ruby On Rails is to Ruby. Originally named "Groovy On Rails", this name has been dropped in favor of Grails to avoid confusion/competition. Like Ruby on Rails, Grails is designed to create CRUD (Create Read Update Delete) Web applications. You can learn more about Grail on the Grails site and is project leader's (Graeme Rocher) blog. Let's now dive in the sample application, for this, as stated earlier I am using the sample application described in the OTN articles.

Example: The product Catalog

Step 1: Set up the Oracle database

If you have not set up the schema and table from the article you just need to create the following objects:
CREATE TABLE comics (
id NUMBER(10) NOT NULL,
title VARCHAR2(60),
issue NUMBER(4),
publisher VARCHAR2(60),
PRIMARY KEY (id)
);
CREATE SEQUENCE comics_seq;
Based on the OTN article I have created this table in the ruby schema.

Step 2: Install Grails

Grails installation is straight forward and explained in the Installation guide, basically:
  1. Download the binaries (I used Grails 0.2)
  2. Setup the different environment variable (GRAILS_HOME, JAVA_HOME, PATH), I used Java 5.
You are done !

Step 3: create the Web Application

Now we have installed the product, the next step is to create the application itself. Create the application The create-app command is creating the full project, with the template with placeholder for the different components of your application such as configuration, MVC, and library and much more. To do it enter the following command, in your command line interface:
> grails create-app .... ..... create-app: [input] Enter application name: comics_catalog .....
As you will see, Grails uses Ant intensively, the create-app command will ask you for an application name, enter for example comics_catalog. The created application contains now a list of directory allowing developer to start to build the application using Groovy, Grails and any Web components. Add the Business Logic and Model: Domain Classes One of the biggest differences between Grails and RoR, is the fact that the main components of your application development is not the Table like you have in RubyOnRails but the "Domain Class". The domain class are the core of the business application, they contains the state and the behavior of your application. So the next step is to create a Domain Class for the Comics, to do that you just need to go in the home directory of your project, eg cd comics_catalog and run the create-domain-class.
> cd comics_catalog > grails create-domain-class .... create-domain-class: [input] Enter domain class name: comics ....
When the command ask you to enter the class name, enter comics. Grails, will not use the same naming convention that RoR has, so you need to use the same name for the class and the table you want to map your object on. The persistence layer is made using GROM (Grails Object Relational Mapping) that leverage hibernate. Note: In our case what we are doing is to leverage an existing database object and create the domain class at the top of it. Usually, Grails uses a different approach where everything is driven by the application, so you create the domain class first and then Grails will create the different database objects. The Comics class does not have any information related to the mapping itself, so you have to create the different attributes in the domain class. This is where you you start to use Groovy, the domain class is located in the following location:
  • ./comics_catalog/grails-app/domain/Comics.groovy
Note hat by default Grails create the class with 2 attributes: id and version, keep them in place, and add title, issue and publisher.
class Comics { @Property Long id @Property Long version // new properties for the Comics class @Property String title @Property Long issue @Property String publisher String toString() { "${this.class.name} : $id" } }
We are all set, we are ready to run the magic command that will create the different screens and flow. Create the different screens from the domain class You can now run the generate-all command to create all the different screens.
> grails generate-all .... input-domain-class: [input] Enter domain class name: comics ....
This command creates the different Views and Controllers, you can take a look to the directories:
  • ./comics_catalog/grails-app/controllers
  • ./comics_catalog/grails-app/views
Configure the database access What we have to do is now to configure the application to use the Oracle database and schema. Grails uses a configuration file for data source:
  • ./comics_catalog/grails-app/conf/ApplicationDataSource.groovy
Let's edit this file to connect to our Oracle database.
class ApplicationDataSource { @Property boolean pooled = true @Property String dbCreate = "update" // one of 'create', 'create-drop','update' @Property String url = "jdbc:oracle:thin:@localhost:1521:XE" @Property String driverClassName = "oracle.jdbc.OracleDriver" @Property String username = "ruby" @Property String password = "ruby" }
Nothing special concerning the properties such as URL, DriverClassName, username and password. The one that is interesting is the dbCreate, that allows you to configure the behavior on the schema to create or not objects.In our sample the table exists, so we want to reuse the object, but we want to be sure that we have all the mandatory objects, columns too, so I selected update. The next thing to do is to add the Oracle JDBC driver to the application, to make it available. To make it available you just need to copy the JDBC driver into the lib directory of your application. In my case I am using Oracle XE so I copy the file from the following location:
  • ORACLE_XE_HOME/app/oracle/product/10.2.0/server/jdbc/lib/ojdbc14.jar to
  • ./comics_catalog/lib/

Step 4: Run the application

Grails provide a way to run the application in stand alone mode, the command is run-app. This command starts an Web container (based on Jetty) with the application deployed.
> grails run-app
Note: Jetty will start on port 8080, in order to start in on a different port like e.g. 9090 use: grails -Dserver.port=9090 run-app You can now access the application using the following URL:
http://localhost:8080/comics_catalog/comics/
Your browser should show the list of comics from the Comics table.
List of Comics
You can create a new entry by clicking on the "New Comics" tab, and view/edit/delete existing record by clicking on the "Show" link.
Edit/Create entry
As you see the creation of an application is really easy. The next step is to deploy the application in your application server.

Step 5: Deploy the application

Grails provides a command to package the application as a WAR ready to be deployed, so in the root directory of your project you can run the following command:
> grails war
When you run this command you end with a WAR with the name of your application located in the root of your project, in our case: comics_catalog.war If you take a look to this WAR you'll see that it is quite big ~10Mb, this is because all the libraries are included in the Lib directory of the web application. You can see the exact structure of the WAR in the ./tmp (./comics_catalog/tmp/war) directory of the application. You can deploy the application as it is to Oracle Application Server 10g, but to avoid the issue with the class loader you should configure the Web application to load the local classes first. It can be done during deployment with the class loader configuration screen:
You can also save this configuration in a deployment plan to facilitate later deployment.
When the deployment is done you can access the application using the OracleAS host and port, something like:
http://localhost:8888/comics_catalog/comics/list
You can now administer and monitor the application like any other J2EE application deployed in OracleAS 10g. Better Deployment Options
  • I personally do not like the idea of shipping all the Jar files in the WAR file, so instead you can use the OracleAS Shared Libraries to create a Grails library by uploading and configuring all the Jars. And package the War without all these libraries.
  • Also you should be able to configure Hibernate/Spring to use a standard define Data source and use the JNDI name to lookup the connections.

Conclusion

GRAILS like Ruby On Rails are really interesting frameworks allowing developers to create quickly Web application that access relational database and especially the Oracle Database. Grails is quite new (release 0.2), but the documentation is really nice and complete. I will encourage all developers that are interested by such framework to use it and provide feedback to the development team. I will try provide other post about deployment of Grails on OracleAS, but also related to other interesting features of this framework, for example Ajax support, Validations etc etc.

Resources

Wednesday, April 12, 2006

Grails on Oracle (OracleAS and OracleXE)

OTN (Oracle Technology Network) Readers have noticed, that Oracle has published an article from Richard Monson-Haefel about Ruby On Rails on Oracle. This article introduces the Ruby On Rails framework and explains how to use it to access an Oracle database. (Oracle 10g Express Edition to be exact)

If you are not familiar at all with Ruby On Rails, it is important to notice that it has nothing to do with Java, J2EE. It is a Ruby based framework.  So yes Ruby On Rails is really interesting, powerful and so on... but for me as a Java developer I would like to do the same using Java (or equivalent) leveraging the investment that I have done in J2EE; also important I want to be able to deploy and manage applications that are developed this way using my tools such as Oracle Enterprise Manager Application Server Control.

The paradigm "coding by convention" that is the driver of Ruby on Rails has been leveraged to developed a new framework: GRAILS. Grails uses Groovy as the underlying language, so it runs on a JVM and can leverage any existing Java API.

If you are a Java developer you will find very interesting to use this framework to accelerate the development of Web applications. If you are not yet a Java developer but need to develop Web application faster, and deploy the to your J2EE application server, Grails is also a very good tools.

Since I have started with Richard's article I will use the same application/database schema to develop my first GRAILS application, and also use the same structure in my article...(is it what we call lazy loading?)

What is Groovy? What is Grails?

Groovy is a dynamic language that leverage features from other languages such as Ruby, Jython, and Smalltalk. Groovy is running at the top of a Java VM and makes available any existing Java objects (so all the API) to Groovy. Groovy is currently under standardization with the JSR-241.  You can learn more about Groovy on the Groovy site and is project leader's (Guillaume Laforge) blog.

GRAILS is to Groovy what Ruby On Rails is to Ruby. Originally named "Groovy On Rails", this name has been dropped in favor of Grails to avoid confusion/competition. Like Ruby on Rails, Grails is designed to create  CRUD (Create Read Update Delete) Web applications.  You can learn more about Grail on the Grails site and is project leader's (Graeme Rocher) blog.

Let's now dive in the sample application, for this, as stated earlier I am using the sample application described in the OTN articles.

Example: The product Catalog

Step 1: Set up the Oracle database


If you have not set up the schema and table from the article you just need to create the following objects:
CREATE TABLE comics (
id NUMBER(10) NOT NULL,
title VARCHAR2(60),
issue NUMBER(4),
publisher VARCHAR2(60),
PRIMARY KEY (id)
);
CREATE SEQUENCE comics_seq;
Based on the OTN article I have created this table in the ruby schema.

Step 2: Install Grails

Grails installation is straight forward and explained in the Installation guide, basically:
  1. Download the binaries (I used Grails 0.2)
  2. Setup the different environment variable (GRAILS_HOME, JAVA_HOME, PATH), I used Java 5.
You are done !

Step 3: create the Web Application

Now we have installed the product, the next step is to create the application itself.

Create the application

The create-app command is creating the full project, with the template with placeholder for the different components of your application such as configuration, MVC, and library and much more. To do it enter the following command, in your command line interface:

> grails create-app
....
.....
create-app:
    [input] Enter application name:
comics_catalog
.....
As you will see, Grails uses Ant intensively, the create-app command will ask you for an application name, enter for example comics_catalog.

The created application contains now a list of directory allowing developer to start to build the application using Groovy, Grails and any Web components.

Add the Business Logic and Model: Domain Classes

One of the biggest differences between Grails and RoR, is the fact that the main components of your application development is not the Table like you have in RubyOnRails but the "Domain Class".  The domain class are the core of the business application, they contains the state and the behavior of your application.

So the next step is to create a Domain Class for the Comics, to do that you just need to go in the home directory of your project, eg cd comics_catalog and run the create-domain-class.
> cd comics_catalog
> grails create-domain-class
....
create-domain-class:
    [input] Enter domain class name:
comics
....
When the command ask you to enter the class name, enter comics. Grails, will not use the same naming convention that RoR has, so you need to use the same name for the class and the table you want to map your object on. The persistence layer is made using GROM (Grails Object Relational Mapping) that leverage hibernate.

Note: In our case what we are doing is to leverage an existing database object and create the domain class at the top of it. Usually, Grails uses a different approach where everything is driven by the application, so you create the domain class first and then Grails will create the different database objects.

The Comics class does not have any information related to the mapping itself, so you have to create the different attributes in the domain class. This is where you you start to use Groovy, the domain class is located in the following location:
  • ./comics_catalog/grails-app/domain/Comics.groovy
Note hat by default Grails create the class with 2 attributes: id and version, keep them in place, and add title, issue and publisher. 
class Comics {
    @Property Long id
    @Property Long version

    // new properties for the Comics class
    @Property String title
    @Property Long issue
    @Property String publisher

    String toString() { "${this.class.name} :  $id" }
}

We are all set, we are ready to run the magic command that will create the different screens and flow.

Create the different screens from the domain class

You can now run the generate-all command to create all the different screens.
> grails generate-all
....
input-domain-class:
    [input] Enter domain class name:
comics
....
This command creates the different Views and Controllers, you can take a look to the directories:
  • ./comics_catalog/grails-app/controllers
  • ./comics_catalog/grails-app/views

Configure the database access

What we have to do is now to configure the application to use the Oracle database and schema.

Grails uses a configuration file for data source:
  • ./comics_catalog/grails-app/conf/ApplicationDataSource.groovy
Let's edit this file to connect to our Oracle database.
class ApplicationDataSource {
   @Property boolean pooled = true
   @Property String dbCreate = "update" // one of 'create', 'create-drop','update'
   @Property String url = "jdbc:oracle:thin:@localhost:1521:XE"
   @Property String driverClassName = "oracle.jdbc.OracleDriver"
   @Property String username = "ruby"
   @Property String password = "ruby"
}
Nothing special concerning the properties such as URL, DriverClassName, username and password.

The one that is interesting is the dbCreate, that allows you to configure the behavior on the schema to create or not objects.In our sample the table exists, so we want to reuse the object, but we want to be sure that we have all the mandatory objects, columns too, so I selected update.

The next thing to do is to add the Oracle JDBC driver to the application, to make it available. To make it available you just need to copy the JDBC driver into the lib directory of your application. In my case I am using Oracle XE so I copy the file from the following location:
  • ORACLE_XE_HOME/app/oracle/product/10.2.0/server/jdbc/lib/ojdbc14.jar
    to
  • ./comics_catalog/lib/

Step 4: Run the application

Grails provide a way to run the application in stand alone mode, the command is run-app. This command starts an Web container (based on Jetty) with the application deployed.
> grails run-app
Note: Jetty will start on port 8080, in order to start in on a different port like e.g. 9090 use:
 grails -Dserver.port=9090 run-app

You can now access the application using the following URL:
http://localhost:8080/comics_catalog/comics/
Your browser should show the list of comics from the Comics table.


List of Comics

You can create a new entry by clicking on the "New Comics" tab, and view/edit/delete existing record by clicking on the "Show" link.


Edit/Create entry

As you see the creation of an application is really easy. The next step is to deploy the application in your application server.

Step 5: Deploy the application

Grails provides a command to package the application as a WAR ready to be deployed, so in the root directory of your project you can run the following command:
> grails war
When you run this command you end with a WAR with the name of your application located in the root of your project, in our case: comics_catalog.war

If you take a look to this WAR you'll see that it is quite big ~10Mb, this is because all the libraries are included in the Lib directory of the web application. You can see the exact structure of the WAR in the ./tmp (./comics_catalog/tmp/war) directory of the application.

You can deploy the application as it is to Oracle Application Server 10g, but to avoid the issue with the class loader you should configure the Web application to load the local classes first. It can be done during deployment with the class loader configuration screen:



You can also save this configuration in a deployment plan to facilitate later deployment.

When the deployment is done you can access the application using the OracleAS host and port, something like:
http://localhost:8888/comics_catalog/comics/list

You can now administer and monitor the application like any other J2EE application deployed in OracleAS 10g.

Better Deployment Options
  • I personally do not like the idea of shipping all the Jar files in the WAR file, so instead you can use the OracleAS Shared Libraries to create a Grails library by uploading and configuring all the Jars. And package the War without all these libraries.
  • Also you should be able to configure Hibernate/Spring to use a standard define Data source and use the JNDI name to lookup the connections.


Conclusion

GRAILS like Ruby On Rails are really interesting frameworks allowing developers to create quickly Web application that access relational database and especially the Oracle Database.

Grails is quite new (release 0.2), but the documentation is really nice and complete. I will encourage all developers that are interested by such framework to use it and provide feedback to the development team.

I will try provide other post about deployment of Grails on OracleAS, but also related to other interesting features of this framework, for example Ajax support, Validations etc etc.

Resources