/**
 * Projet myplayapp
 * Entité Game
 */
package models;

import javax.persistence.Entity;

import play.data.validation.Required;
import play.db.jpa.Model;

/**
 * Game Classe modélisant un jeu vidéo de la bibliothèque
 * @author frederic
 * 
 */
@Entity
public class Game extends Model {
@Required
public String title;
@Required
public String platform;
@Required
public String description;
public Boolean publish;
public String testContent;
public String developerStudio;
public String editor;
@Required
public Integer yearOfPublication;
public Integer note;
public String cover;

public Game(String title, String description, Boolean publish,
String testContent, String developerStudio, String editor,
Integer yearOfPublication, Integer note, String cover) {
this.title=title;
this.description=description;
this.publish = publish;
this.testContent=testContent;
this.developerStudio=developerStudio;
this.editor=editor;
this.yearOfPublication = yearOfPublication;
this.note = note;
this.cover = cover;
}

}
Voilà une première étape de faite.

Mais avant de pouvoir tester cette chose, codons justement un test unitaire de la classe de persistance et de sa DAO, géré par le framework.

Créons donc une classe de test dans le répertoire de source test et nommons le EntitiesTest:
Notre petite classe est destinée à tester la persistance de nos entitée:

public class EntitiesTest extends UnitTest {

  @Test
  public void testGame(){
    Game game = new Game("MyGame", 
             "X360", 
             "My Description game", 
             true,
             "Test of the game",
             "My Studio", 
             "My Editor",
             2010,
             8,
             "public/images/x360/my_game/cover/mygame-cover.jpg");
    game.save();

    Long id = game.getId();
    assertNotNull(id);
  }
}

Ok,maintenant, testons notre test ;)  et lançons dans la sessions de commandes précédemment ouverte, la ligne suivante:

play test

nota: depuis Eclipse, via la bar d'icônes de debug, cliquez sur le bouton "Run Configurations...", et dans le groupe "Java applications", lancer "Test myplayapp".

Et ouvrez votre navigateur (Firefox, Chrome, Safari, IE ?) sur l'url http://localhost:9000/@tests !
Vous pouvez alors lancer le ou les tests que vous avez créés.

La page appraissant à l'écran vous propose de lancer les tests souhaités. choisissez EntitiesTest et cliquez sur "Start !".
Capture-06-play_-_tests_runner

figure 6 - Lancement des tests unitaires via l'interface Web de Play!

Le test choisi déroulé, le résultat de celui-ci apparait dans la même page:
Capture-07-play_-_tests_runner

figure 7 - Résultat du test unitaire exécuté

Vous pouvez aussi choisir de lancer l'intégralité des tests unitaires proposés nativement par Play!, ainsi que vos tests "custom".
Pour cela rappelez la page des tests et cliquer sur le lien "select all" puis sur "Start !". Tous les tests natifs sont appelés, y compris un test via Sélénium vérifiant le bon affichage de la page d'accueil de l'application.

Capture-08-play_-_tests_runner

figure 8 - Tous les tests ont été lancés et exécutés avec succès
Conclusion
Nous voilà avec les prémices d'une belle application Play! Nous avons découvert a travars ces premiers pas, la richesse technique et la complétude proposées par ce fabuleux framework Java. Nous découvrirons au prochain épisode notre première page bien à nous et la mis en place des modules CRUD et Security, natif eux aussi à Play! mais non activés par défaut.

Vous trouverez ci-joint, l'archive du code correspondant à cet article.

Click here to download:
myplayapp-part1.zap (262 KB)

  • Hobo: Step 4 - adding a cover image

    As we've now get a running web application to manage our library, I propose you to add an image field management to our Book model.
    To manage this part, we are going to need 3 things:
    • an imaging tool like mini_magick or image_magick,
    • the paperclip plugin for rail
    • and the paper_clip_with_hobo to be used with Hobo framework.
    1. The image tool
    My choice go to imagemagick, but i know that this is working well with others tools like

    2. Paperclip plugin
    You will find very interesting infoirmation about this plugin usage at this page: http://jimneath.org/2008/04/17/paperclip-attaching-files-in-rails/
    And you  will be able to download it from http://github.com/thoughtbot/paperclip

    To install this small plugin, just go to your hobo application root path and run the following command:

    script/plugin install git://github.com/thoughtbot/paperclip.git
    Now you have downloaded it, you are ready to use it.

    3. Get the paperclip_with_hobo
    Just fololowing the same process, you have to download/install this rails plugin from git:

    script/plugin install git:http://github.com/tablatom/paperclip_with_hobo.git ok. let's apply some model modification to our Book modelisation.Book.rbwe need to add some new field to our app/model/book.rb class Book < ActiveRecord::Base hobo_model # Don't put anything above this  fields do title :string  author :string year :integer  resume :text note :integer  timestamps end   has_attached_file :cover, :styles => {                   :full=>"600x600>",                  :medium => "300x300>",                   :thumb => "100x100>",                  :mini => "60x60>" },                  :path => " :rails_root/public/media/books/covers/:id/:style.:extension",                 :url => "media/books/covers/:id/;style.:extension"  ...end Adding such "has_attached_file" field to our Book model add in reality 4 fields to our database model after running the rake db:migrate standard rails operation : see db/migrate/20100221172242_add_attachements_cover_to_book.rb migration fileclass AddAttachmentsCoverToBook < ActiveRecord::Migration  def self.up add_column :books, :cover_file_name, :string  add_column :books, :cover_content_type, :string add_column :books, :cover_file_size, :integer  add_column :books, :cover_updated_at, :datetime end  def self.down remove_column :books, :cover_file_name  remove_column :books, :cover_content_type remove_column :books, :cover_file_size  remove_column :books, :cover_updated_at end endOk, now our model is updated, database too. we are ready to modify some dryml file to show this image. Go to app/views/taglibs/application.dryml and add the following declaration:At file beginning in existing "include" lines:<include src="paperclip" plugin="paperclip_with_hobo"/> And at end of file :<extend tag="form" for="Book">        <old-form merge multipart>                 <field-list fields="title, author, year, resume, note, cover, category" param/>         <div param="actions">  <submit label="#{ht 'books.actions.save', :default=>['Save']}" param/><or-cancel param="cancel"/>  </div>        </old-form> </extend>This is a view modifier for a Book, adding the cover field and removing the 4 database fields. Then, modify the card dryml for Book model, in the same previous file (application.dryml) :<extend tag="card" for="Book">   <card>    <h5>     

       

                <view:resume />     </p>    <p>       <%= I18n.t :uploaded_label %><br />      <view:created_at format="%B %d, %Y" /> by <you:user />.     </p>    <delete-button class="actions" />      </card> </extend>Let's test our new cover field !

  • Hobo: step2 and 3, add categories and some relation

    Ok, we have just created the first step of our library.
    Now we have hundreds of books, maybe we can dispatch all these books in some categories ?
    Ok, l'est add categories to our web app "My Library"
     script/generate hobo_model_resource category name:string sorder:integer
    And we hjev to update the databse with our new model:
     script/generate hobo_migration
    don't forget the 'm' option to run the migration right now !
    ok, just for fun, run the application with a 
     script/server
    browse to http://localhost:3000/ and go to the "Categories" tab..  
    1.View the Category tab
    Hobo_07_add_categories
    2.and add a new "Novel" category
    Hobo_08_add_a_category
    yes ok, nothing really new here.  It's working just like Books.
    Let's dye into the code:
    We are going to add the link between Book and Category, knwoing that a category can have many book, and one book belong to one category.
    Open the file book.rb and just after fields declaration, add the following "belongs_to": 
     class Book < ActiveRecord::Base

      hobo_model # Don't put anything above this

      fields do
        title  :string
        author :string
        year   :integer
        resume :text
        note   :integer
        timestamps
      end

      belongs_to :category
      ...
     end
    Open now the category.rb and add the small "has_many" property:
     class Category < ActiveRecord::Base

      hobo_model # Don't put anything above this

      fields do
        name   :string
        sorder :integer
        timestamps
      end

      has_many :books
      ...
     end
    we have to generate a small migration to add this field into the Book data model.
     script/generate hobo_migration
    note: choose the 'm' option to apply modifications.
    and start the server to test !
     script/server
    let's browse the Books page
    Hobo_09_add_links_category_boo
    And choose one of the created book, you can see the new "Category" field at end of page.
    Click the "edit book" link and you will be invited to change the value for category wich is currently set with the default "(No category)".
    Hobo_10_link_book_to_category
    ok, back to your code editor and open the file category_hints.rb. and replace all the commented lines by the following single line. 
     class CategoryHints < Hobo::ViewHints

       children :books

     end
    Telling that Category has Books has children will modify automatically the Category page, showing the number of book attached to a category.
    1. What's new in the "Categories" page
    Hobo_11_add_category_hints_boo
    2. Let's see the detail of a Category
    Hobo_12_showing_category_detai
    3. And on the Book side, a new top/left link appear "<<Novel"
    Hobo_13_book_details_about_cat
    you can see that with  very small add to the generated code, you considerably inflect the default behaviour of the application and the links in the model.
    Even if model link declaration and manipulation already exists in Rails, Hobo brings the corresponding mechanisms for the UI side.
    Next, more to be discover in the dryml taglib and tags personalization.
    Hobo man.
    Note: please find attached bellow the project in each step state, from step 1 to step 3.

    Click here to download:
    MyLibrary-step-1.tar.gz (120 KB)

    Click here to download:
    MyLibrary-step-2-categories.tar.gz (122 KB)

    Click here to download:
    MyLibrary-step-3-hints.tar.gz (128 KB)