A cool chat example created with Ruby On Rails and Juggernaut

Versão em portugues aqui
Before we start with the chat, you need to have the requisites installed, juggernaut need the gems json and eventmachine installed, so, run the following command before reading the rest of this example …

  • gem install -y json eventmachine

Ok, now we are ready to go!
First of all, create a rails application, and install the Juggernaut plugin with this commands:

  • rails -d sqlite3 chattest
  • cd chattest
  • script/plugin install svn://rubyforge.org//var/svn/juggernaut/trunk/juggernaut

Juggernaut uses an external Flash XML Push Server to do the reverse ajax magic, and we’ll need to configure that server, so, let’s edit the file: config/juggernaut.yml
I’ve put in the snipet bellow just the lines I changed in the file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PUSH_PORT: 8080
...
DEFAULT_CHANNELS: 
- "chat"
...
PUSH_HELPER_HOST: "localhost"
...
SECRET: "481516232342edededededed"
...
LOGIN_GET_URL: "http://localhost:3000/session/login"
LOGOUT_GET_URL: "http://localhost:3000/session/logout"
...
SESSION_ID: "_chattest_session_id"
...
BASE64: true

I had to change the PUSH_PORT because I’m using a linux box and the application does not run as root, so I was not able to use the default 443 port, and I do not think that 443 is a good port choice because it is the default HTTPS port.
Make sure you change the PUSH_HELPER_HOST to the same host name as the one you are using to access the application, localhost will do the job in the development environment, but remember to change it when you publish your site in a production environment.
the LOGIN_GET_URL and LOGOUT_GET_URL are used to notify the application about clients arriving and leaving, we will really use only the leaving notification.
the SESSION_ID must be the same as the defined cookie name for your application, it is defined in the application controller for rails 1.2.x and will be moved to environment.rb for rails 2.0
and BASE64 must be set to true if we want to use the rails helpers to generate the javascript for us.

Now let’s start the layout for the application. Create a file named pubic/stylesheets/public.css with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
body {
  background-color: white;
}
#users {
  float: left;
  width: 200px;
  height: 400px;
  border-style: inset;
  overflow: auto;
  color: white;
  background-color: gray;
}
#dasd {
  height: 400px;
  margin-left: 5px;
  border-style: inset;
  overflow: auto;
  color: white;
  background-color: gray;
}
#controls {
  clear: both;
  padding: 0 0 0 0;
  height: 55px;
  vertical-align: top;
  border-style: inset;
  overflow: auto;
  color: white;
  background-color: gray;
}

and a file named: app/views/layouts/application.rhtml with the following content.

1
2
3
4
5
6
7
8
9
10
<html>
  <head>
    <title>Chat Test</title>
    <%= stylesheet_link_tag 'public' %>
    <%= javascript_include_tag :defaults %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

in this file it is important to add the stylesheet and the default javascript includes.

With the layout ready (ok, I know it is pretty ugly, but I’m a developer not a webdesigner so, for production, ask a designer in your team for a new layout :D ) let’s generate the needed files and database tables with the following four commands.

  • script/generate model online_user username:string session_id:string last_seen:date online:boolean
  • script/generate controller session
  • script/generate controller chat index
  • rake db:migrate

Every thing ready, we just need to edit some files …
Open the OnlineUser model (app/model/online_user.rb) and change the content to something like the following

1
2
3
4
class OnlineUser < ActiveRecord::Base
	validates_presence_of :username, :session_id, :last_seen
	validates_uniqueness_of :username, :if => Proc.new {|user| user.online }
end

It is just a few validations, not really needed, this was my first idea for the chat, I’ve changed it a little but still works.

Now let’s code the main view of the application in the file:app/views/chat/index.rhtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- Register with Juggernault -->
<%= listen_to_juggernaut_channels [:generic],session.session_id %>
<!-- The Users List -->
<div id="users">
  <ul id="users_list"></ul>
</div>
<!-- The messages pane -->
<div id="dasd"></div>
<!-- The controls pane (login and send messages) -->
<div id="controls"><%= render :partial => 'login' %></div>
<!-- An util javascript to scroll the messages window -->
<script type="text/javascript">
  function scrollMessages(){
    $('dasd').scrollTop = $('dasd').scrollHeight;
  }
</script>

That is all, just tree DIVs, the tag to initialize juggernaut and a simple javascript to scroll the messages DIV to the last sent message.
the messages DIV is named dasd because I was testing some conflicts and forgot to change it back :D

As seen in the page above, we need a login partial, and we’ll need a controls partial too, so let’s code the controls partial (app/views/chat/_controls.rhtml) with the following code:

1
2
3
4
5
6
<% form_remote_tag(
      :url => { :action => :say },
      :complete => "$('message').value = '';$('message').focus();" ) do %>
      <%= text_field_tag( 'message', '', { :size => 90, :id => 'message'} ) %>
      <%= submit_tag "Send" %>
  <% end %>

It has only a remote form tag and two fields, after the form is submited the message field is cleared and the focus os placed back in that field so the user can type another message.

And the login partial (app/views/chat/_login.rhtml):

1
2
3
4
5
6
7
<%= "#{@message}<br/>" if @message %><% form_remote_tag(
      :url => { :action => :login },
      :complete => "$('username').value = ''",
      :after => "$('login').disabled = true" ) do %>
      <%= text_field_tag( 'username', '', { :size => 90, :id => 'username'} ) %>
      <%= submit_tag "Join", :id => 'login' %>
  <% end %>

Very similar to the controls partial, but it shows a message to the user if the chosen nick name is already taken.

the views are all set, and now we need the application logic, as seen in the views, we need a chat controller with two methods: login and say
Let’s take a look at the chat controller (app/controllers/chat_controller.rb):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class ChatController < ApplicationController
  #this method does not need to exist, but I like to see it here, it only needs to render the index.rhtml view
  def index
  end
  def login
    #creates a new OnlineUser record, this is used to store who are the users that are online now
	@user = OnlineUser.new
	@user.username = Juggernaut.html_and_string_escape params[:username]
	@user.session_id = session.session_id
	@user.online = true
	@user.last_seen = Time.now
        #if we can save, it means that there is no other user with the same nick online, so this user can join the chat
	if @user.save
          #let's save the username in the session for future reference
	  session[:username] = @user.username
          #if there are online users, fill the users box for the new user know who is online
	  @users = OnlineUser.find(:all, :conditions => ["online = true and id != ?", @user.id]) 
          if @users.size >0 
            data = render_to_string(:update) do |page|
              @users.each {|u|
                page.insert_html :bottom, :users_list, %Q{<li id="user_#{u.username}">#{u.username}</li>}
              }
	    end
            #send the javascript only to the new user
            Juggernaut.send_to(@user.session_id, data)
          end
          #create a javascript call to add the new user to the end of the online users list
          data = render_to_string(:update) do |page|
            page.insert_html :bottom, :users_list, %Q{<li id="user_#{@user.username}">#{@user.username}</li>}
            page.insert_html :bottom, :dasd, "<b>user #{@user.username} just joined the chat</b><br/>"
          end
          #add the new user to the chat channel
          Juggernaut.add_channel(@user.session_id, 'chat')
          #send the javascript to all users in the chat channel
          Juggernaut.send_data(data, 'chat')
	  render(:update) do |page|
	    page.replace_html 'controls', :partial => "controls"
          end
	else
          @message = 'This nick name is already in use, please choose another'
	  render(:update) do |page|
	    page.replace_html 'controls', :partial => "login"
	  end
	end
  end
 
  def say
    #escape the message, that way the user can not harm others sending HTML ot JavaScript commands
    message = "#{session[:username]}: #{Juggernaut.html_and_string_escape(params[:message])}"
    #create a javascript to add the new message to the end of the messages screen and scroll the div to the bottom
    data = render_to_string(:update) do |page|
      page.insert_html :bottom, :dasd, "#{message}<br/>"
      page.call "scrollMessages"
    end
    #send the message to all users
    Juggernaut.send_data(data, 'chat')
    render :nothing => true
  end
end

The method say is really simple, so we’ll start explaining it:
It first build a new message appending the escaped original message to the user name, then it creates the javascript to add the message to the bottom of the messages div using the Rails JavaScriptBuilder and the render_to_string method, that returns a string instead of rendering the code directly to the client.
then it sends the message to all users subscribed to the “chat” channel, and all the users will execute that javascript.

Now a little about the login method:

  • from the line 7 to 11 we just configure the new OnlineUser model.
  • if the user is saved to the database it means that there is no other user with the same nick name, so we can proceed with the logic
  • from line 17 to 23 we just create a javascript to populate the users DIV for the new user with the users already online
  • and in the line 25 we send this javascript just for the new user.
  • from line 28 to 31 we create a javascript adding the new user to the users DIV and add a message to the messages window telling all users that a new user joined the chat.
  • in the line 33 we add the new user to the “chat” channel
  • in the line 35 the generated javascript is sent to all users (now including the new arriver)
  • and in from the line 36 to 38 the traditional rails ajax helper is used to change the content of the controls DIV to the “controls” partial (the one that enables the user to send messages to other users.

This is almost all logic needed for this chat application, the only missing thing is removing the nick of users that are no more online from the users DIV from the other users, and we’ll do that in the session controller (app/controllers/session_controller.rb)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class SessionController < ApplicationController
  #Called when a user disconnect (a refresh in the browser causes this to be called too)
  def logout
    #search for the user record using the session_id
    @u = OnlineUser.find_by_session_id(session.session_id)
    reset_session
    #if a user was found
    if @u
      username = @u.username
      #remove it from the database
      @u.destroy
      #remove from the online users list from all users, and tell others this user left the chat
      data = render_to_string(:update) do |page|
        page.remove "user_#{username}"
        page.insert_html :bottom, :dasd, "<b>User #{username} left the chat</b><br/>"
      end
      Juggernaut.send_data(data,'chat')
    end                
    render :nothing => true
  end
 
  def login
    render :nothing => true
  end
end

The login method does nothing, but we have some code in the logout method …

  • in the line 5 we lookup the user record from the database
  • if a user is found
  • we destroy it in the line 8
  • from line 13 to 17 we create a javascript to remove the user from the users DIV and send a message to all users telling that the user has left the chat

That is all folks, we just need to run the application
to run this application we need to start the rails application server as usual, and then start the push server.
to do this, just run the following two commands:

  • script/server
  • script/push_server

and access your newly build chat with the URL: http://localhost:3000/chat and play a little around.
I’ve built this example while studding the juggernaut lib, so it is possible that there is a easy way to do this, but I think this is a good start point :D
The start idea was not to use a database, but I could not find anything like the ServletContext in java for rails (an application context), I’ll try to use ENV to store the online user names, but I could not make it work until now.
Any tips for improving this example will be very welcome.

If you enjoyed this post, make sure you subscribe to my RSS feed!

A very simple login example with JSF

Following the very simple example line, as in the “login example with Rails“, now we’ll see a very simple login example with Java Server Faces.
I’m writing this sequence of short howto posts because in the forums I read one of the recurrent question from the beginners is “how to implement a login with X”, so, let’s go to the JSF login example.

Of course there are many ways to implement a login in a JSF aplication, you can use JAAS, you can use a Servlet Filter, but this one I think is one of the best approaches, of course, in a real application, I usually combine it with some AOP and annotations, but AOP and annotations are out of the scope of this tutorial …

First, write a web.xml for your application, with the faces servlet in it …

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>java.lang.SecurityException</exception-type>
<location>/login.jsf</location>
</error-page>
</web-app>

In this web.xml we are using the servlets 2.5 specification, and I’m using JSF 1.2, for this example you can use other versions without problem.
The servlet container is configured to show a login page if at any time the application throws a java.lang.SecurityException, this is a important point for the example.

And now a backing bean for the application, here is where we’ll validate the user’s login, in this example there is no need for database access, but in a real application you’ll search this data in your user repository (database, ldap, …)

package br.com.urubatan.jsfjpasec;
public class Login {
private boolean loginOk;
private String userName;
private String password;
public boolean isLoginOk() {
return loginOk;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public  String validateLogin(){
if(userName!=null &&   password!=null && !userName.equalsIgnoreCase(password)){
loginOk = true;
return "secpage";
}else return "login";
}
}

It is a very simple backing bean, with only 3 properties:
name and password for the user, and a property telling the application that a user has already logged in.
probably this last property will be replaced by a list of groups filled by the validateLogin method …

Now a bean with some static data for the example:

package br.com.urubatan.jsfjpasec;
import java.util.List;
import java.util.ArrayList;
public class SomeData {
private List<String> data = new ArrayList<String>();
private List<String> securedData = new ArrayList<String>();
private boolean loginOk;
public SomeData() {
for(int i=0;i<10;i++){
data.add("Simple data " + i);
securedData.add("Secure data " + i);
}
}
public void setLoginOk(boolean loginOk) {
this.loginOk = loginOk;
}
public List<String> getSecuredData() {
if(!loginOk)
throw new SecurityException();
return securedData;
}
public List<String> getData() {
return data;
}
}

This one has only the getters for two properties, and in the secureData property, if there is no logged in user, the application throws a java.lang.SecurityException, this will redirect the user to the login page.

Now some XML tricks in the faces-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version='1.0' encoding='UTF-8'?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd" version="1.2">
<managed-bean>
<managed-bean-name>login</managed-bean-name>
<managed-bean-class>br.com.urubatan.jsfjpasec.Login</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>mdata</managed-bean-name>
<managed-bean-class>br.com.urubatan.jsfjpasec.SomeData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>loginOk</property-name>
<property-class>java.lang.Boolean</property-class>
<value>#{login.loginOk}</value>
</managed-property>
</managed-bean>
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/login.jsp</to-view-id>
<redirect/>
</navigation-case>
<navigation-case>
<from-outcome>secpage</from-outcome>
<to-view-id>/secureView.jsp</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
</faces-config>

In this file we have two navigation cases, if “login” is returned from a backing bean, it shows the login page, if “secpage” is returned, the secureView.jsp page is shown …
The first lines are used to declare the backing beans, pay attention to the line 15, where we are reading the property “loginOk” from the login bean.
The login bean is session scoped, and the mdata is request scoped.

With this written we have all the needed logic for this application, the only missing part is the “view”, or the JSP files …
So, let’s write them …
login.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<html>
<head><title>System Login</title></head>
<body>
<f:view> <h:form>
<h:panelGrid columns="2">
<h:outputLabel value="User Name" for="un"/>
<h:inputText id="un" value="#{login.userName}"/>
<h:outputLabel value="Password" for="pw"/>
<h:inputText id="pw" value="#{login.password}"/>
</h:panelGrid>
<h:commandButton value="Login" action="#{login.validateLogin}"/>
</h:form>
</f:view>
</body>
</html>

This is only a simple JSF page with two fields and a commandButton …

dataView.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<html>
<head><title>Unsecured Data Page</title></head>
<body>
<f:view>
<h:dataTable value="#{mdata.data}" var="v">
<h:column>
<f:facet name="header">
<h:outputText value="Data List"/>
</f:facet>
<h:outputText value="#{v}"/>
</h:column>
</h:dataTable>
<h:panelGrid columns="3">
<h:outputLink value="dataView.jsf">
<h:outputText value="Data that every one can access"/>
</h:outputLink>
<h:outputLink value="secureView.jsf">
<h:outputText value="Data that you can view after login"/>
</h:outputLink>
<h:outputLink value="login.jsf">
<h:outputText value="Login"/>
</h:outputLink>
</h:panelGrid>
</f:view>
</body>
</html>

This is simple page with a dataTable rendering the “data” property from “mdata” bean and two links.

secureView.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<html>
<head><title>Secured Data Page</title></head>
<body>
<f:view>
<h:dataTable value="#{mdata.securedData}" var="v">
<h:column>
<f:facet name="header">
<h:outputText value="Data List"/>
</f:facet>
<h:outputText value="#{v}"/>
</h:column>
</h:dataTable>
<h:panelGrid columns="3">
<h:outputLink value="dataView.jsf">
<h:outputText value="Data that every one can access"/>
</h:outputLink>
<h:outputLink value="secureView.jsf">
<h:outputText value="Data that you can view after login"/>
</h:outputLink>
<h:outputLink value="login.jsf">
<h:outputText value="Login"/>
</h:outputLink>
</h:panelGrid>
</f:view>
</body>
</html>

And this is almost a copy from the previous page, but now reading the “secureData” property from “mdata” bean.

And just to avoid the “404″ error when running the application, an “index.jsp” with a link to “dataView.jsf”

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Entry Page</title></head>
<body>Entry Page, this could redirect to the JSF Index, but for now, click here: <a href="dataView.jsf">JSF Index</a>
</body>
</html>

That is all folks!

to run this application you need the following jar files: jstl.jar, jsf-api.jar e jsf-impl.jar
They can be found in the JSF-RI distribution, and are already present in containers with JSF support.

And now, some questions:

  1. How would you improve this example?
  2. Do you see any problem with this approach?
  3. Are you already using JSF?

Versão em portugues aqui

If you enjoyed this post, make sure you subscribe to my RSS feed!

A very simple login example with Rails

This is just a little step by step on how to create a simple login with Rails, of course you can use a plugin to do it for you, but this way you can understand what the plugin is doing.

Let’s start creating a new Rails application:

$rails applicationName

Then we create a controller with a view for the login:

$script/generate controller login login

The code for the login_controller.rb will be the following:

class LoginController < ApplicationController
def index
render :action => 'login'
end
def login
end
def do_login
username = params[:username]
password = params[:password]
if username.nil? || password.nil? || username==password
redirect_to :action => "login"
flash[:notice] = 'Unknown user or invalid password'
else
session["user_id"] = username
redirect_to :controller => "secure", :action => "index"
end
end
end

Basically the controller has to implement only the do_login method, this is the one that will authenticate the user, in this example it only validates if the user filled the username and password fields, but later you can search the database for it.

The login view will have the following code:

<% form_tag :action => 'do_login' do %>
<table class="loginForm" align="center"><tbody>
<tr>
<td>Login</td>
<td><input name="username" type="text" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name="password" type="password" /></td>
</tr>
<tr>
<td colspan="2"><%= submit_tag "Login" %></td>
</tr>
</tbody></table>
<table><% end %>

It is a simple view, with only two fields and since we do not have a user model I did not used the rails form helpers …

Ok, perfect until now, but how do I use it?

let’s change the application.rb file, the code will be the following:

class ApplicationController < ActionController::Base
# Pick a unique cookie name to distinguish our session data from others'
session :session_key => '_untitled6_session_id'
before_filter :authorize
protected
# Override in controller classes that should require authentication
def secure?
false
end
private
def authorize
if secure? &amp;&amp; session["user_id"].nil?
session["return_to"] = request.request_uri
redirect_to :controller => "login", :action => "login"
return false
end
end
end

The code above adds a before filter to every method of every controller in your application (since all controllers extends ApplicationController), this method will intercept the calls and if the controller is “secure” and the user did not authenticated yet, the user will be redirected to the login page, otherwise the filter will do nothing. To secure a controller you just need to override the “secure?” method and return true.

Now let’s create a simple controller that will need authentication …

$script/generate controller secure index

This line above creates a new controller with only an index action.

Now let’s edit the secure_controller.rb file

class SegureController < ApplicationController
def index
end
protected
def secure?
true
end
end

Overriding the “secure?” method to return true we tell the application that all actions in this controller need authentication.

But if we and only a few actions to need authentication? Than we can use some thing like the code bellow!

protected
def secure?
["secureMethod","anotherSecureMethod"].include?(action_name)
end

This way only the “secureMethod” and the “anotherSecureMethod” will need authentication.

Every thing ready, now we have a login implemented in a rails application …

Try starting the server (ruby script/server from the application’s directory) and access http://localhost:3000/secure and you will see the login screen instead of the index.rhtml contents.

Of course we can improve this example in many ways, for example:

  • in the method do_login we can use the session[”return_to”] to redirect the user to the first requested page.
  • We can create a users/groups structure and implement the authorization using that

And you, how would you improve the example above?

Do you see any problem in this example?

If you enjoyed this post, make sure you subscribe to my RSS feed!