Showing posts with label Cloud. Show all posts
Showing posts with label Cloud. Show all posts

Thursday, September 5, 2019

Multi-Nodes Redis Cluster With Docker

Read this article on my new blog

As part of my on-boarding/training at RedisLabs I continue to play with the product, and I have decided today to install a local 3 nodes cluster of Redis Enterprise Server (RS); and show how easy is to move from a single node/shard database to a multi nodes highly available one.
Once your cluster is up & running, you will kill some containers to see how the system automatically fail-over to guarantee service continuity.
The deployment will look more or less like the schema below, (coming from RedisLabs documentation)

Go to the complete article here.

Thursday, July 11, 2013

Deploy your Node/Couchbase application to the cloud with Clever Cloud



Introduction

Clever Cloud is the first PaaS to provide Couchbase as a service allowing developers to run applications in a fully managed environment. This article shows how to deploy an existing application to Clever Cloud.




I am using a very simple Node application that I have documented in a previous article: “Easy application development with Couchbase, Angular and Node”.

Clever Cloud provides support for various databases MySQL, PostgreSQL, but also and this is most important for me Couchbase. No only Clever Cloud allows you to use database services but also you can deploy and host your application that could be developed in the language/technology of your choice : Java, Node, Scala, Python, PHP, … and all this in a secure, scalable and managed environment.

Setting up your Clever Cloud environment

Create your account

  1. Go to the Clever Cloud site : http://www.clever-cloud.com/
  2. Click on “Login” link and follow the steps to create your account.
  3. After few seconds you will received an email and be redirected to the Clever Cloud Console.

Create a Couchbase instance

The Clever Cloud Console allows you to create your Couchbase Bucket in few clicks:

1. Cick on “Services” in the left menu

2.  Click on “Add a Service” in the left menu 
    3. Click on “Couchbase” button.

    4. Select the size of the RAM quota for your bucket

    The size of the RAM Quota for your bucket will have an impact on performance but also on the pricing.

    5. Click “Add this Service”


    You are done, you should receive an email with all the information to access your newly created bucket.

    The mail from Clever Cloud contains the following information:

    db_host = xxxxxxxx.couchbase.clvrcld.netLocation of the database, this is where the endpoint is located.
    db_name = yyyyyyyyName of the Couchbase bucket
    db_username = xxxxxxxxNot used in Couchbase context
    db_password = zzzzzzzzPassword to connect to the Couchbase Bucket

    So you are now ready to use your bucket.

    Note: In the current version of the Clever Cloud Couchbase Service you do not have access to a management console. If you want to get some information about the database or create views you need to do it from you application code.

    Connect your Application to Couchbase@Clever-Cloud

    The first step is to get some code, so let’s clone the “Couchbase Ideas Sample Application”, and install the dependencies, using the following commands:

    git clone -b 03-vote-with-value https://github.com/tgrall/couchbase-node-ideas.git
    cd couchbase-node-ideas
    git branch mybranch
    
    git checkout mybranch
    
    npm install
    

    Open the app.js and edit the connection info to point your application to the Couchbase instance and modify the HTTP port of your application to 8080 - this is a mandatory step documented here :

    dbConfiguration = {
     "hosts": ["xxxxxxxxxxx.couchbase.clvrcld.net:8091"],
     "bucket": "xxxxxxxxxxx",
     "user": "xxxxxxxxxx",
     "password": "yyyyyyyyyyyyyyyyyyyyyyyyy"
    };
    ...
    ...
    
      appServer = app.listen(8080, function() {
     console.log("Express server listening on port %d in %s mode", appServer.address().port, app.settings.env);
      });
    
    

    Launch your application using
    
    
    node app.js
    

    Go to http://localhost:8080

    Your application is now using Couchbase on the cloud powered by Clever Cloud. Let’s now deploy the application itself on Clever Cloud

    Deploy your application on Clever Cloud

    The easiest way to deploy an application to Clever Cloud is using git. The first thing to do is to add your SSH public key into Clever Cloud Console. If you do not have any SSH yet, follow the steps described on Github : “Generating SSH Keys”.

    Add your SSH key

    Note: As you can guess this should be done only once
    Open the id_rsa.pub file with a text editor. This is your SSH key. Select all and copy to your clipboard.
    1. Go to the Clever Cloud Console
    2. Click on “Profile” entry in the left menu
    3. Click on “SSH Keys”
    4. Click on “Add a SSH Key”
    5. Enter a name (anything you want) and paste your key
    6. Click “Add” button
    You are now ready to deploy applications to Clever Cloud. The next thing to do, is to create a new node application in Clever Cloud.

    Create your Application

    1. Click “Add an app” in the Application menu in the top menu.
    2. Give a name and description to this application
    3. Select the Instance type, in this case “Node.js”
    4. Configure your instances, you can keep the default values for now, click “Next”
    5. Check the configuration, and click “Create”
    Your application is created, you are redirected to the generic information page, where you can find a Git URL that we will use to deploy the application.
    You can navigate into the entries in the left menu to see more information about your application. In addition to the Information page, you can look at the following entries:
    1. “Domain Names” to configure the URL to access your application
    2. “Logs” to view the application logs

    Deploy the Application

    So we are almost there!
    The deployment to Clever Cloud is done using a Git push command, so you need to add the deployment URL as a remote repository to your application, using the following command:
    
    
    git remote add clever git+ssh://git@push.clever-cloud.com/app_[your_app_id].git
    
    
    git commit -a -m “Couchbase on Clever Cloud connection”
    
    
    git push clever mybranch:master
    
    

    Once you have added the application as remote repository you can commit and push your application.

    The last command pushes the application  to Clever Cloud. It is important to note that Clever Cloud will always deploy the application on the “master” branch on the remote repository. The notation mybranch:master is used to mention it. If you work locally on your master branch just use “master”.

    You can now go to the Clever Cloud console and look in the log and click on the URL in the “Domain Names” section to test your application.

    You should be able to see your application, that is running on the Clever Cloud PaaS.

    When you update your application, you just need to do a  git push and git commit.

    Conclusion

    In this tutorial you have learned how to:
    • Create your Clever Cloud account
    • Create a Couchbase instance
    • Create and deploye a Node.js application

    Feel free to test this yourself, with Node or other technology, as you can see it is quite easy to setup.

    Sunday, February 19, 2012

    SAP Cloud Inside : Build and Run Applications in the Cloud

    Last week I was invited to present eXo Cloud IDE during the SAP Cloud Inside. This SAP Community event was a great opportunity to discuss about the cloud with an interesting point of view: the impact of the cloud for SAP customers (especially administrators and developers).

    During this presentation I have introduced the eXo Cloud IDE, and I did a demonstration in which O have built and deployed applications : Open Social Gadgets, Ruby on Rails and Java/Spring, and explain how it could be extended to SAP business services.

    Here the slides that I have used during this presentation:


    Remember that you can register yourself to the eXo Cloud IDE Service and start develop application from your browser.

    Saturday, January 21, 2012

    Google AppEngine Full Text Search with Cloud SQL

    Introduction

    Many Google AppEngine developers have been waiting for the Full Text Search feature, especially coming from Google the biggest search engine on the Web. I was quite happy to see that Google team is working on it as you can check in the Google I/O 2011 session : Full Text Search by Bo Majewski, Ged Ellis . As far as I know the very promising indexing service is not yet available.

    In this article I will explain how you can provide some kind of full text search in your application using services available App Engine services.

    In my specific use case I do not ask for a lot of feature, I just need to have simple search a string in various attributes of my entities independently of the case, and possible special characters (such as è,é, ... ). I am far of being an expert of Google Datastore API but I did not find any simple way to achieve this directly using the Java API. What I have done to solve this issue is to duplicate a part of my data into the Google Cloud SQL to use the MySQL fulltext search capabilities.

    Prerequisites
    To achieve the following tasks you need to :


    Content

    In the following paragraphs I will explain the basics of the integration of Cloud SQL for full text search, but you can, if you want, jump to :




    1. Create Articles Entities

    Start by creating some simple entities with some attributes for example, an entity name Article, with title and body attributes.


    import com.google.appengine.api.datastore.DatastoreService;
    import com.google.appengine.api.datastore.DatastoreServiceFactory;
    import com.google.appengine.api.datastore.Entity;
    
    //...
    //...
    
      Entity article = new Entity("Article");
      article.setProperty("title", "MySQL Tutorial");
      article.setProperty("body", "DBMS stands for DataBase ...");
      datastore.put(article);
    
      article = new Entity("Article");
      article.setProperty("title", "Datastore Index Selection and Advanced Search");
      article.setProperty("body", "Learn how recent improvements to the query planner ... function in your application");
      datastore.put(article); 
    

    If you look in the Datastore API, or even JDO or JPA you have no simple way to look for all the articles that are related to Triathlon, or Database, or Entities. Google DataStore does not support  clause where with a "OR" between different fields; and I do not want to mention the fact that it is not possible to ignore the text case in a simple way.

    This is why we need to have some full text features. Some of you are surely thinking about using Apache Lucene to do the trick, and yes it is possible. You can use for example the GAELucene project : http://code.google.com/p/gaelucene/. I use another approach, may be less advanced in term of "indexing/searching" options but sufficient for my use case:
    • I store the text values on which I want to do some search in Google Cloud SQL and use the Full Text features of MySQL.


    2. Create a SQL Table to store Text values (in development environment)

    When using Google AppEngine, the Cloud SQL instances are accessed using a specific driver and configuration that we will see later. For now, we are still in development environment, this is where you have to use your local MySQL instance.

    In this specific use case we will copy in a table the two fields and add a new unique key based on the entity key.  So here the SQL to create this:

    CREATE SCHEMA search_values DEFAULT CHARACTER SET utf8 ;
    
    USE search_values;
    
    
    CREATE TABLE articles  (
      entity_key varchar(250),
      title text,
      body text,
      PRIMARY KEY RESULTS_PK (entity_key),
      FULLTEXT (title,body)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
    
    
    
    Lines 1 and 3 are here to create the database schema and use it; then the script create a table that will contain a copy of the title and body from the entity. 

    3. Configure your development environment 

    This section is a short explanation of the Cloud SQL Documentation : Getting Started: Java

    1. Copy the MySQL JDBC driver into your Google App Engine SDK directory, under /lib/impl/. You can download the MySQL JDBC driver here.
    2. In Eclipse, select your Java package.
    3. Click Run > Run Configurations.
    4. Expand the Web Application menu item.
    5. Add the following lines into the VM Arguments pane:
      -Drdbms.server=local
      -Drdbms.driver=com.mysql.jdbc.Driver
      -Drdbms.url=jdbc:mysql://localhost:3306/search_values?user=username&password=password
      
    6. Click the Classpath tab.
    7. Select your project and click Add External JARs...
    8. Navigate to the Google App Engine SDK directory, then lib/impl, and select the JDBC driver JAR file. Click Open. The driver JAR is listed under User Entries.
    9. Click Apply.
    Your development environment is now ready to use your local MySQL database. Let's now, use this database.

    4. Use your MySQL table and copy the text values from Google Datastore to MySQL Table

    Copying the data from Datastore entity to the table is quite easy:

      Connection conn = null;
      try {
       DriverManager.registerDriver(new AppEngineDriver());
       conn = DriverManager.getConnection("jdbc:google:rdbms://[your db instance]/search_values");
       conn.setAutoCommit(false);  
       String statement = "REPLACE INTO articles (entity_key, title, body) VALUES( ? , ? , ? )";
       PreparedStatement stmt = conn.prepareStatement(statement);
    
       DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
       Query q = new Query("Article");   
       PreparedQuery pq = datastore.prepare(q);
    
       // loop on each entity and insert the values in the SQL Table
       for (Entity result : pq.asIterable()) {
        stmt.setString(1,  KeyFactory.keyToString(result.getKey())   );
        stmt.setString(2,  result.getProperty("title").toString() );
        stmt.setString(3,  result.getProperty("body").toString() );
        stmt.executeUpdate();
        conn.commit();
       }
    
    
    
      } catch (SQLException e) {
       e.printStackTrace();
      } finally {
       if (conn != null)
        try {
         conn.close();
        } catch (SQLException ignore) {}
      }
    



    Some specials things here, compare to standard Java Web Development:
    • I manage the connection directly in my code (I have not looked yet if I can use datasources/connection pool in the context of Google AppEngine)
    • Line #3: registering the AppEngine driver that is responsible of managing the connection, expecially work in development -local MySQL- or production mode -CloudSQL-.
    • Line #4 : Get the connection. It is interesting to mention that in development the connection URL is grabbed from the environment variable Drdbms.url you have set previously. We will see later how we move this to the cloud. This is the magical part of the AppEngineDriver that manages different connection types Local MySQL or CloudSQL depending of the context
    • After these lines, the code is quite simple :
      • Get all the Articles entities from the datastore and loop
      • "Upsert" the database record (REPLACE INTO syntax)
    • Line #15 is storing the Key of the entity in a safe string using the KeyFactory.keyToString() method.

    If you want to test this code just put this lines in a servlet to "sycnhronize" the data from datastore into the MySQL table. Obviously this code is just here for learning propose and should be integrated in a better way in a real application; starting with pushing the data in the database when entities are created/updated (and deleted ;) ). The sample code available from GitHub contains these methods.


    5. Implement a search method

    The goal is simple return a list of entities returned by a simple search criteria :
    • public Iterable searchEntities(String query)

    The logic is here quite simple:
    1. Execute a SQL query
    2. For each result, get the Entity using the Key
    3. Return the list of Entities

     public Iterable searchEntity(String query) {
      List  results = new ArrayList();
      Connection conn = null;
      try {
       DriverManager.registerDriver(new AppEngineDriver());
       conn = DriverManager.getConnection("jdbc:google:rdbms://[your db instance]/search_values");
       String statement = "SELECT entity_key FROM articles WHERE MATCH (title,body) AGAINST (? WITH QUERY EXPANSION);";
       PreparedStatement stmt = conn.prepareStatement(statement);
       stmt.setString(1, query);
       ResultSet rs = stmt.executeQuery();
       while (rs.next()) {
        String keyAsString = rs.getString(1);    
        Entity article = DatastoreServiceFactory.getDatastoreService().get( KeyFactory.stringToKey(keyAsString)  );
        results.add(article);
       }
    
      } catch (SQLException e) {
       e.printStackTrace();
      } catch (EntityNotFoundException e) {
       e.printStackTrace();
      } finally {
       if (conn != null)
        try {
         conn.close();
        } catch (SQLException ignore) {}
      }
      return results;
     }
    


    In this method, the system connect to the database and then execute a query to search data using any type of SQL/MySQL query. In this exampe I am using the full text function with the "WITH QUERY EXPANSION". You can obviously use any type of SQL queries for example simple LIKE statement if this is enough four your application.

    With this approach when I search for :
    • "database" : the method returns all the articles concerning database, mysql, RDBMS independently of the case.
    • "index" " the method returns all the articles talking about indexing/indexes or search.

    6.  Deploy to GAE 


    Once you have created your application, and activated and configure your CloudSQL instance (here), you can deploy your application and enjoy an easy way of using Full Text Search with GAE.


    Conclusion

    In this article I explained how you can use Google Cloud SQL to easily supports Full Text Search queries, based on the Full Text support of MySQL.

    The code snippets that I have shared in this article are really basic and not ready for real life usage but still a good starting point. For example I have been using this in my application with GAE Queues to manage my indexes on larger volume of data.

    As said before, you can test the application online at http://gae-fulltext-search.appspot.com/ and the source code is available on GitHub : https://github.com/tgrall/gae-full-text-search

    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.)

    Wednesday, March 16, 2011

    eXo Cloud IDE : develop for the Cloud on the Cloud

    Yesterday, eXo has launched a new cloud based service: the eXo Cloud IDE. This IDE is an online service that facilitates the development of gadgets and mashups that could be deployed directly to a PaaS.

    Before launching this service on the Cloud we, eXo team and customers, have used the IDE embedded in the eXo Platform to extend our intranet and customer deployments (some of the modules that we have developed live on our intranet are available as plugins on the eXo Resource Center).
    This IDE is the last mile between the users and the developers. It provides a way to add new services asked by business users at a lower cost with a good time to market. And all this based on standards that corporate and Web developers like : REST Services using JAX-RS and UI based on OpenSocial gadgets in which you can leverage all the cool and powerful features of HTML5.

    What eXo has launched yesterday is a big step for developers since you can now develop, test and deploy your gadgets and services online, and this in your "personal environment" using eXo Cloud IDE supports multi-tenancy. I won't go in all the features of the IDE since you can test it yourself by joining the beta program and look at this video:

    eXo Cloud IDE resources:

    Sunday, February 28, 2010

    Create and Deploy a JAX-RS REST service on Google App Engine

    In this article you will learn how to create a REST service using JAX-RS reference implementation (Jersey) and deploy it on Google AppEngine.

    Prerequisites

    For this tutorial you will need:
    • a Google AppEngine account : http://code.google.com/appengine/
    • Eclipse Galileo (3.5.x)
    • Google App Engine SDK for Java

      • Install the Google Plugin for Eclipse as documented here (Check that you are using the release 1.3.1 of the GAE Java SDK, if not download it and configure the plugin to use it)
      • it is also useful to have the AppEngine documentation locally, you can download it from here.
    • JAX-RS Reference Implementation, be sure you take the Jersey 1.1.5 release. You can download it from here.

      • Unzip the file in a directory that we will call $JERSEY_HOME
    • JAXB 2.2 Implementation to simplify the marshalling/unmarshalling of the XML, and also facilitate the JSON support. Download it from here 


      • Install it using thejava -jar JAXB2_20091104.jar command.  The installation directory of JAXB will be called $JAXB_HOME

    Creating new application

    To create a new App Engine project in Eclipse:
    1. Click on the "New Web Application Project" button in the toolbar . It is also possible to do it using the menu File > Web Application Project

    2. The "Create a Web Application Project" wizard opens:
    • Project Name: EmployeeService
    • Package : com.grallandco.employee.service
    • Uncheck "Use Google Web Toolkit"
    • Check that the SDK version your are using is "App Engine 1.3.0"; if not configure the project to use it.
    • The screen should look like the following screen :


    • Click Finish

    • The project should look like the following screen :



    Running the application

    The App Egine SDK, installed with the Eclipse plugin contains a Web server (based on Jetty), that could be used for testing and debugging. To test that your application has been created correctly select the menu Run > Run As > Web Application. I personnaly most of the time run my server using the debug command Run > DebugAs > Web Application. In debug mode you can change source code and test is without restarting the server.

    The web server is starting automatically, you should see the following message in the Eclipse console

    The server is running at http://localhost:8080/

    You can access the application, and the sample servlet that has been created using the URL: http://localhost:8080/employeeservice

    To stop the server, click on the terminate button in the Eclipse console.

    Configuring the REST support in the application

    To be able to create and run REST services in your application you need to:
    • Add the JAX-RS, JAXB Jars in your project and application
    • Configure the web application (web.xml) to handle REST requests
    Add JAX-RS, JAXB to your project
    1. Right click on the project and select menu entry Build Path > Configure Build Path...
    2. Click on the Add External JARs button

    3. Select all the JARs located in $JERSEY_HOME/lib  and $JAXB_HOME/lib folders. You can for better visibility and reuse create a user library with all these JARs
    4. You also need to copy the JARs in the web-inf/lib directory of your application, this step is mandatory to be sure that the JARs are included in the application when deployed to App Engine.
      Note: I do not like this step. I would prefer to do that by configuration of the build path, to automatically add the JARs to the WEB-INF/lib directory when executing/deploying the application. Unfortunately I did not find the way to do it, so if you know it, feel free to post a comment and I will update the article.

    Configure the web application

    In this step you will register a new URI to handle REST requests. To do that you need to register a new servlet that is using the Jersey API and configure it to a specific URI (eg: /ressources  and/or /rest) and configure what are the Java packages that contain the REST implementation classes. So you need to modify the web.xml of your application with the following entries:

      <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
         <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
         <init-param>
         <param-name>com.sun.jersey.config.property.packages</param-name>
         <param-value>com.grallandco.employee.service.rest.impl</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/resources/*</url-pattern>
      </servlet-mapping>
       <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
      </servlet-mapping>
    


    This servlet that will answer to the /resources/ and /rest/ URL. The configuration parameter com.sun.jersey.config.property.packages is used by Jersey to list the packages where REST services implementation are located.Note that you can put as many package as you need to, you just need to separate the package names by a ; .


    Creating a simple REST Service to test the environment

    The project is now ready to contain REST service. It is time to create one.Create for example the class com.grallandco.employee.service.rest.impl.HelloWorldResource, be sure to use the package name that you have configured in the web.xml for the Jersey servlet, based on the configuration we have made in previous step the package is com.grallandco.employee.service.rest.impl

    Here a sample class with the JAX-RS annotations:
    package com.grallandco.employee.service.rest.impl;
    import javax.ws.rs.Path;
    import javax.ws.rs.GET;
    import javax.ws.rs.Produces;
    @Path("/hr/")
    public class EmployeeResource {
     
     @GET
     @Produces("text/plain")
     @Path("/employee") 
     public String getEmployee() {
            return "Hello World!";
        }
    }
    
    You should be able to test it, stop the server and run it again, enter the following URL in your browser:
    http://localhost:8080/resources/hr/employee
    or
    http://localhost:8080/rest/hr/employee


    Deploying the application to Google App Engine

    Before deploying the application you need to register a new application in Google App Engine using the Administartion Console, see the documentation here. In my example I have used "tugdual" as Application ID.
    You can easily now deploy the application to Google App Engine by clicking on the  "Deploy App Engine Project" button Deploy App Engine Project Button available in the Eclipse toolbar.
    To be able to deploy your application to Google App Engine, you need to check that your application can be registered, the application ID is stored in the WEB-INF/lib/appengine-web.xml.
    <?xml version="1.0" encoding="utf-8"?>
    <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
     <application>[your-application-id]</application>   
     <version>1</version>    
     <!-- Configure java.util.logging -->
      <system-properties>
       <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
     </system-properties>    
    </appengine-web-app>

    The App Engine deploy button prompts you for multiple informations: username (your Google account) and password.

    When the deployment is complete you can access your application using the following URL:
    http://[your-application-id].appspot.com/resources/hr/employee
    or
    http://[your-application-id].appspot.com/rest/hr/employee

    Ading XML and JSON support to the service

    Let's now add new method to manipulate an "Employee" object using the service, and the data format should be based on JSON and XML. This is where JAXB is useful, since it allows easily to transform marshall/unmarshall Java objects in XML -obviously- and JSON (cool isn't!)

    Creating an Employee Class

    Start with the creation of a new class to manipulate Employee data, this is a very simple Java class that could look like the following code:

    package com.grallandco.employee.service.model;
    import java.util.Date;
    
    public class Employee {
        private String firstName;
        private String lastName;
        private Date hireDate;
        private String email;   
        public Employee(String firstName, String lastName, Date hireDate, String email) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.hireDate = hireDate;
            this.email = email;
        }
        public Employee() {}
        public String getFirstName() {
     return firstName;
     }
        public void setFirstName(String firstName) {
     this.firstName = firstName;
     }
        public String getLastName() {
     return lastName;
     }
        public void setLastName(String lastName) {
         this.lastName = lastName;
     }
        public Date getHireDate() {
     return hireDate;
     }
        public void setHireDate(Date hireDate) {
     this.hireDate = hireDate;
     }
        public String getEmail() {
            return email;
     }
        public void setEmail(String email) {
            this.email = email;
       }
        public String toString() {
            StringBuffer sb = new StringBuffer();
            sb.append("First: ").append(getFirstName());
            sb.append(" - Last: ").append(getLastName());
            sb.append(" - Date: ").append(getHireDate());
            sb.append(" - Email: ").append(getEmail());
            return sb.toString();
        }
    }
    
    When implementing your "real" application with some persistence layer this POJO is the one as JDO/JPA entity.

    Create a Converter class for your entity

    I usually encapsulate all the transformation in some converter class, like that I do not directly couple my business class to the serialisation mechanism. (So I do that for classes and lists of classes). So instead of adding the JAXB annotations to the Employee class itself, let's create an EmployeeConverter class that will be responsible of the transformation and used by your REST service.

    package com.grallandco.employee.service.converter;
    
    import java.util.Date;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import com.grallandco.employee.service.model.Employee;
    
    @XmlRootElement(name = "employee")
    public class EmployeeConverter {
     private Employee entity = null;
     public EmployeeConverter() {
     entity = new Employee();
     }
    
     public EmployeeConverter(Employee entity) {
     this.entity = entity;
     }
    
     @XmlElement
     public String getFirstName() {
     return entity.getFirstName();
     }
    
     @XmlElement
     public String getLastName() {
     return entity.getLastName();
     }
    
     @XmlElement
     public Date getHireDate() {
     return entity.getHireDate();
     }
    
     @XmlElement
     public String getEmail() {
     return entity.getEmail();
     }
    
     public Employee getEmployee() {
     return entity;
     }
    
     public void setFirstName(String firstName) {
     entity.setFirstName(firstName);
     }
    
     public void setHireDate(Date hireDate) {
     entity.setHireDate(hireDate);
     }
    
     public void setLastName(String email) {
     entity.setEmail(email);
     }
    
     public void setEmail(String lastName) {
     entity.setLastName(lastName);
     }
    }
    
    You can now update your service to use this utility/converter class to return XML or JSON ojbect based on the content type of the request.

    Add support to JSON and XML to your REST service

    You need to change the EmployeeRessource class, to change the signature and add new annotations of the getEmployee() method.
    The annotation you are adding:
    • @Produces({"application/xml", "application/json"}) : indicates which type of content will be produced by the service. Based on the type of the request.
    • @Path("/employee/{employeeEmail}/") :    change the Path to indicate a Path parameter, here for example the URL can accept an email in the URI - not the best example, but you get the point...
    • public EmployeeConverter getEmployee( @PathParam ("employeeEmail") String email)  : change the type returned by the method and take a parameter as String that match the Path param defined in the @Path annotation
    Here the complete class code:
    package com.grallandco.employee.service.rest.impl;
    
    import javax.ws.rs.Path;
    import javax.ws.rs.GET;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import com.grallandco.employee.service.converter.EmployeeConverter;
    import com.grallandco.employee.service.model.Employee;
    
    @Path("/hr/")
    public class EmployeeRessource {
    
     
     @GET
     @Produces({"application/xml", "application/json"})
     @Path("/employee/{employeeEmail}/") 
     public EmployeeConverter getEmployee( @PathParam ("employeeEmail") String email) {
     //dummy code
     Employee emp = new Employee();
     emp.setEmail(email);
     emp.setFirstName("John");
     emp.setLastName("Doe");
     EmployeeConverter converter = new EmployeeConverter(emp);
     return converter;
     } 
    }


    Test the service

    You can now run the server locally and test the service
    http://localhost:8080/resources/hr/employee/tug@grallandco.com
    This will return an XML document.
    If you want to test the JSON call you have multiple choice:
    • Using following command
    tgrall$ curl -H "Accept: application/json" http://localhost:8080/resources/hr/employee/tug@grallandco.com
    {"email":"tug@grallandco.com","firstName":"John","lastName":"Doe"}
    • Using an HTTP client that allows your to configure/set the HTTP request completely, I am using the Poster Firefox Plugin
    • Using some Javascript code in an application
    You can repeat the test on your deployed application on Google App Engine.

    Conclusion

    In this article you have learned how to create and deploy a new REST Service on Google App Engine. This service has been created with the JAX-RS Reference Implementation the Jersey project. In the next article you will learn how to add persistence and create a CRUD Rest service on Google App Engine.