Monday, August 15, 2011

Attendance sample application in PlayFramework – Part 1

Hi,

Recently I found out a new Java framework which actually suck less than Java overall I think, because it uses the same kind of system as Rails in Ruby.

For now I won’t go in too much details, but if you’d like to see the bootstrapping process for a project, and how to integrate with Secure module from PlayFramework, Attendance app, the application I’m doing for my buddy Teejay from Nigeria, is a good example.

I've showed in this podcast how to create a sample PlayFramework application. Import a new site template into it, create a User model, import Secure module from PlayFramework and add authentication to the app. Set up the default database to MySQL.
Created sample Attendance page, and played with Groovy templates a little bit.
In the second part I will continue to work on Attendance page, and admin part.

 

Hope soon the second part of the application will be available too.

Monday, February 28, 2011

I hate Java #2: ClassNotFoundException ?! – Tomcat deployment

At least once per day I have this problem with Tomcat and Eclipse.

I have a library declared in my pom.xml but Tomcat strangely enough doesn’t deploy it, and at deploy I have this ClassNotFoundException, the problem is that sometimes when the stars are not arranged in one line Tomcat doesn’t deploy all the libraries into its webapps/{PROJECT_NAME} (deployment folder) folder.

image

Why ? I don’t know but I know instead how to solve it. First of all stop the server, remove all the apps from it. 

image

Click “Finish”.

image

Make a Tomcat clean.

image

After the clean is finished add  removed apps back to Tomcat and run the server.

As you can see I don’t have the problem now.

image

Another one why I hate Java, and yes it isn’t related to Java itself but to it environment, but still I don’t fee much happier about it. This shouldn’t be like this, guys. Dear clients, take a look at IIS. Do you see something like that ? No ? Than why do I still have to choose Java ?

Thursday, February 17, 2011

I hate Java #1: org.hibernate.MappingException: Unknown entity

Well, as you might know I started learning/coding Java because I will kinda be working in production and as you might know in my first month in Java I got the idea to write a book about it. Here is how the cover would look.

image

Anyway this is not the point of this particular post. So let’s see what we got. We got a very unusual exception: org.hibernate.MappingException: Unknown entity.

We tried to use annotated hibernate entities, everything seemed to be nice configured in hibernate.xml but it didn’t worked. Our Hibernate should work with Spring. So I’ll put some XML’s and classes before and than I’ll tell you the solution

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- Hibernate session factory -->


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/testh" />
        <property name="username" value="postgres" />
        <property name="password" value="postgres" />
    </bean>


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="entity" />
        
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- The Spring support for Hibernate calls -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

 

The property “packagesToScan” is used to indicate where the hibernate annotation entities are.

Now the entity java class was like this

package entity;

import java.io.Serializable;
import java.sql.Timestamp;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Entity;

@Entity
@Table(name = "emp", schema = "public")
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "emp_userid")
    private String id;

    @Column(name = "emp_link_date")
    private Timestamp date;

    @Column(name = "emp_logdel")
    private boolean logicalDelete;

    @Column(name = "emp_name")
    private String name;

    @Column(name = "employee_surname")
    private String surname;

    public Employee() {
        // TODO Auto-generated constructor stub
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Timestamp getDate() {
        return date;
    }

    public void setDate(Timestamp date) {
        this.date = date;
    }

    public boolean getLogicalDelete() {
        return logicalDelete;
    }

    public void setLogicalDelete(boolean logicalDelete) {
        this.logicalDelete = logicalDelete;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public boolean isLogicalDelete() {
        return logicalDelete;
    }

}

Well I got this error which was kind of stupid:

org.hibernate.MappingException: Unknown entity: entity.Employee
    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:597)
    at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:68)
    at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:879)
    at org.hibernate.impl.SessionImpl.get(SessionImpl.java:816)
    at org.hibernate.impl.SessionImpl.get(SessionImpl.java:809)
    at com.givaudan.persistence.UserDaoBean.getUserById(UserDaoBean.java:12)
    at com.givaudan.masterdata.service.UserRightsServiceBean.getUserById(UserRightsServiceBean.java:12)
    at service.UserRightsServiceTest.testGetUserById(UserRightsServiceTest.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.test.context.junit4.SpringTestMethod.invoke(SpringTestMethod.java:160)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runTestMethod(SpringMethodRoadie.java:233)
    at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:333)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
    at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

And I got to this blog post on the net. http://thejavablog.wordpress.com/2008/05/21/orghibernatemappingexception-unknown-entity/

Now that explained everything: I shoudn’t use org.hibernate.annotations.Entity, but  javax.persistence.Entity.

Isn’t that sweet ? For a newbie in Java it’s really hard to understand why Entity annotation which you do use at hibernate, shouldn’t be in org.hibernate.annotations.Entity, but instead in javax.persistence.Entity.

Well looks like java API coders don’t like logical and simple things. And another question when I should use org.hibernate.annotations.Entity? Do I really need it with the same name in this package?

Well may be someone on the Java side would explain this thing. That really would be nice.

Saturday, January 22, 2011

ASP.NET MVC 3 Project with NUnit as Testing framework

[UPDATE] Marcus has been able to make a new Visual Studio Extension that add NUnit as an option when selecting test framework for ASP.NET MVC 3. You can get that from Visual Studio gallery for free.

Don’t you sometimes have this feeling when you need something that Microsoft could make out of the box?

I got the same kind of idea today when I was trying to create a new ASP.NET MVC 3 website with NUnit as test framework. And I could find this page How to: Add a Custom ASP.NET MVC Test Framework in Visual Studio but the whole thing wasn’t very easy and it was indicated that you should insert some keys and values into registry.

“Man, I don’t like that”, I thought, “Isn’t there an easier solution which could make it all work ?”.

I googled a little bit, and I found this blog post: ASP.NET MVC 3 with NUnit Testproject written by Marcus Kimpenhaus. In the bottom of this blog post there is a link via which you can download and install the NUnit template for ASP.NET MVC 3, this template worked for x64 bit machines, but I left a comment and he was nice to update it for x86 machines too. Thanks very much Marcus this project template is invaluable when need it. I also suggested to publish this template to NuGet feed, and if this will work it would be great and you could install it directly from your NuGet console.

So let’s resume what do you need to do in order to have a NUnit Test project template for your ASP.NET MVC 3 project:

  1. At the bottom of the blog post click the download link for the project template
  2. Run install.bat as administrator, now this bat will check the type of your machine : x64 or x86 and will edit registry accordingly to that, it will also update your Visual Studio 2010 cache so please wait a little bit there
  3. Go and thank Marcus for his work, and send a mail to ASP.NET team to include this project template in the Visual Studio SP1. After all the SP1 is coming in spring so they still have lots of time to include it.

Hope this will help someone.

Tuesday, January 18, 2011

Get used to Mercurial using TortoiseHg and VisualHg

Hi, guys today I’m gonna link a little video about another Distributed Versionning Control System (DVCS), Mercurial. If you don’t know that’s what I decided to use as a source control system for Pet Shelter – my learning experiment with ASP.NET MVC 3. Read more at http://lnkd.in/v5uARq.

Anyway today we’ll talk about Mercurial and TortoiseHg and a little bit about VisualHg which kinda integrates Mercurial into your usual IDE environment.

So first video is from vimeo:

Mercurial with TortoiseHG: The Basics from ragingmon on Vimeo.

Another excellent video is at Rob Conery Tekpub website. Here is the link

http://tekpub.com/view/dotnet-oss/7

Only a little problem to view it you need to be registered. And by the way registration literally takes 20 seconds. Please take a look at that wonderful video with the length of 34 minutes.

Hope you got it. No matter how far you go, you just need to know Git or Mercurial, and may be in your next project when you’ll be using these tools you could make another video and send to me it’s link and I will share it with the people who read my blog.

Take care.

Monday, January 10, 2011

Create a sample Rails 3 application running with JQuery

Hi guys,

Today I’m going to show you how to combine the power of Rails 3 with JQuery.

By default Rails 3 comes with Prototype, but let’s say I don’t know Prototype (I really don’t … a good topic for homework), but I still need to use Javascript in my brand new application and I know JQuery, or may be I need JQuery UI components, for example a DateTime picker,  than all I need to do is combine JQuery and Rails 3 right ? Yeah so let’s try it manually.

1.   First of al we need to create a brand new Rails 3 app :

$ rails new jquery_demo_app -J
      create
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  public/images
      create  public/images/rails.png
      create  public/stylesheets
      create  public/stylesheets/.gitkeep
      create  public/javascripts
      create  public/javascripts/.gitkeep
      create  public/javascripts/application.js
      create  script
      create  script/rails
      create  test
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  test/unit
      create  tmp
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  vendor/plugins
      create  vendor/plugins/.gitkeep

That “-J” option tells Rails that we don’t need Javascript stuff generated.

Application before adding jquery

2.   Next we need to download the latest Jquery version minified and put it under the public/javascripts folder.

      So all we need is to copy and paste the text from http://code.jquery.com/jquery-latest.min.js to jquery.js file.

3.   Next we need to copy latest Rails Jquery drivers and put it under public/javascripts too.

     So we go to https://github.com/rails/jquery-ujs/blob/master/src/rails.js click on raw link and copy it to rails.js file.

JQuery UJS driver

These 2 steps can be done in one shot using curl tool.

$ cd jquery_demo_app/
$ cd public/javascripts/
$ curl http://code.jquery.com/jquery-latest.min.js > jquery.js
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 78601  100 78601    0     0   181k      0 --:--:-- --:--:-- --:--:--  213k

$ curl https://github.com/rails/jquery-ujs/raw/master/src/rails.js > rails.js
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4150  100  4150    0     0   4429      0 --:--:-- --:--:-- --:--:--  5313

$ ls    
application.js  jquery.js  rails.js 

4.   And the last thing is to edit in config/application.rb file these lines

# JavaScript files you want as :defaults (application.js is always included).
config.action_view.javascript_expansions[:defaults] = %w()

We need to include jquery.js and rails.js into defaults. And optionally you could specify CDN network but this isn’t always required.

config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
config.action_view.javascript_expansions[:cdn] = %w(https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js rails)

As you can see there are a lot of steps which should be repeated for each application where we want to use JQuery.

Fortunately enough we have another solution.

Gem “jquery-rails”

jquery-rails

There is a gem created https://github.com/indirect/jquery-rails which will help us to avoid repeating these steps over and over again.

Let’s experiment with another new application.

Add jquery-rails into our Gemfile.

And run bundle install command. And you could also commit it to a git repo, so if something goes wrong you could revert to initial version.

$ rails new another_jquery_app

# In Gemfile add this line
gem 'jquery-rails'

$ bundle install
Fetching source index for http://rubygems.org/
.
.
.
Using jquery-rails (0.2.6)
.
.
.
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

$ git init
$ git add .
$ git commit -am "Initial commit"

Now let’s install jquery

$ rails generate jquery:install
      remove  public/javascripts/controls.js
      remove  public/javascripts/dragdrop.js
      remove  public/javascripts/effects.js
      remove  public/javascripts/prototype.js
    fetching  jQuery (1.4.4)
      create  public/javascripts/jquery.js
      create  public/javascripts/jquery.min.js
    fetching  jQuery UJS adapter (github HEAD)
c:/Ruby192/lib/ruby/1.9.1/net/http.rb:677:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate
ed (OpenSSL::SSL::SSLError)
        from c:/Ruby192/lib/ruby/1.9.1/net/http.rb:677:in `connect'
        from c:/Ruby192/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
        from c:/Ruby192/lib/ruby/1.9.1/net/http.rb:626:in `start'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:306:in `open_http'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:769:in `buffer_open'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:203:in `block in open_loop'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:201:in `catch'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:201:in `open_loop'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:146:in `open_uri'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:671:in `open'
        from c:/Ruby192/lib/ruby/1.9.1/open-uri.rb:33:in `open'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/actions/file_manipulation.rb:77:in `get'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/jquery-rails-0.2.6/lib/generators/jquery/install/install_generator.rb:34:in `download_ujs
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/task.rb:22:in `run'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/invocation.rb:118:in `invoke_task'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/invocation.rb:124:in `block in invoke_all'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/invocation.rb:124:in `each'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/invocation.rb:124:in `map'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/invocation.rb:124:in `invoke_all'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/group.rb:226:in `dispatch'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/thor-0.14.6/lib/thor/base.rb:389:in `start'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.3/lib/rails/generators.rb:163:in `invoke'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.3/lib/rails/commands/generate.rb:10:in `<top (required)>'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:239:in `require'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:239:in `block in require'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:225:in `block in load_dependency'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:596:in `new_constants_in'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:225:in `load_dependency'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:239:in `require'
        from c:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.3/lib/rails/commands.rb:17:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

 

Because I use Windows I got this “certificate verify failed (OpenSSL::SSL::SSLError)”. If you don’t have this error skipped to  I made a little research and found out that I need to point Rails to a certificate to use when dealing with HTTPS. To see more about this issue follow this link:  jQuery, GitHub, SSL. Thanks to 19th comment author. He indicated a solution.

So all we need to do is copy file from https://github.com/Shopify/active_merchant/blob/master/lib/certs/cacert.pem somewhere locally and than indicate this URI in C:\Ruby\Ruby192\lib\ruby\1.9.1\open_uri.rb around line 289

http.use_ssl = true
http.verify_mode = options[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER
http.ca_file = 'C:\Ruby\certs\cacert.pem' # you should indicate where you’ve set your file locally
store = OpenSSL::X509::Store.new

Now let’s try again. Before we try again we’ll need to checkout the version before error occurred.

$ git checkout -f

$ rails generate jquery:install
      remove  public/javascripts/controls.js
      remove  public/javascripts/dragdrop.js
      remove  public/javascripts/effects.js
      remove  public/javascripts/prototype.js
    fetching  jQuery (1.4.4)
   identical  public/javascripts/jquery.js
   identical  public/javascripts/jquery.min.js
    fetching  jQuery UJS adapter (github HEAD)
    conflict  public/javascripts/rails.js
Overwrite d:/rails_tutorial_projects/another_jquery_app/public/javascripts/rails
.js? (enter "h" for help) [Ynaqdh] Y
       force  public/javascripts/rails.js

Now your application is using JQuery instead of Prototype and all we needed to do is use this little useful gem and I encourage you to use it also.

By the way if you need JQuery ui installed just use

$ rails generate jquery:install --ui

So that is how you can use Rails 3 with JQuery instead of Prototype. Take care.

Thursday, January 6, 2011

Git in Action

Hi, guys found this amazing and quite simple video about using Git. Take a look.

Git Screencast: Git in Action from Ralf Ebert on Vimeo.

Give thumbs up to this post if you liked it and please comment about what do you also want to see in my blog.