November 2011 Posts

How to Create a Simple Servlet to Handle JSon Requests

On this example, im trying to create a simple servlet to handle JSon request. Im using this servlet to handle JSon request from my front end such as web or even desktop application. Thanks to GSon library, it really helped on simplifying javabean convert to json strings and the other way around.

First as usual, a simple java bean to handle request and response format

package com.edw.bean;

public class Student {
 
    private String name;
    private int age;
    private byte gender;

	// other setter and getter
}
package com.edw.bean;

public class Status {
    private boolean success;
    private String description;
	
	// other setter and getter
}

And this is my servlet,

package com.edw.servlet;

import com.edw.bean.Status;
import com.edw.bean.Student;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonParserServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");        
        Gson gson = new Gson();

        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }

            Student student = (Student) gson.fromJson(sb.toString(), Student.class);

            Status status = new Status();
            if (student.getName().equalsIgnoreCase("edw")) {
                status.setSuccess(true);
                status.setDescription("success");
            } else {
                status.setSuccess(false);
                status.setDescription("not edw");
            }
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            Status status = new Status();
            status.setSuccess(false);
            status.setDescription(ex.getMessage());
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        } 
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

This is a screenshot on how my message actually look like

Have Fun (H)

Google+

Creating a Simple Yahoo Messenger Auto Response with Java and OpenYMSG Library

Hi, several days ago someone asked me to help him on his assignment related to Yahoo Messenger Application with Java. That’s why today im trying to help him by creating a simple example on auto response and message sending using one of the best open source Yahoo Messenger API implementation, OpenYMSG.

It’s actually quite easy, only several lines of codes. This is how i do it

package com.edw.yahoo;

import java.util.Scanner;
import org.apache.log4j.Logger;
import org.openymsg.network.FireEvent;
import org.openymsg.network.ServiceType;
import org.openymsg.network.Session;
import org.openymsg.network.event.SessionEvent;
import org.openymsg.network.event.SessionListener;

/**
 *  com.edw.yahoo.YahooLogin
 *
 *  @author edw
 */
public class YahooLogin implements SessionListener {

    private Logger logger = Logger.getLogger(YahooLogin.class);
    private Session session = new Session();

    public static void main(String[] args) {
        YahooLogin yahooLogin = new YahooLogin();
        yahooLogin.doLogin();
    }

    public YahooLogin() {
    }

    private void doLogin() {
        try {
            // insert your yahoo id
            // as for this example, im using my yahoo ID "dombaganas"
            session.login("dombaganas", "MyYahooPassword", true);
            session.addSessionListener(this);
            Scanner scanner = new Scanner(System.in);

            while (true) {
                System.out.println("please insert your message : ");
                String message = scanner.nextLine();

                // logout if message equals to "bye"
                if (message.equalsIgnoreCase("bye")) {
                    break;
                }
                // send message to targeted yahoo id
                session.sendMessage("TargetYahooID", message);
            }

            // logout from YM
            session.logout();
        } catch (Exception e) {
            logger.error(e, e);

        }
    }

    /*
     *  this is my listener method
     *  it listen for YM message request
     */
    @Override
    public void dispatch(FireEvent fe) {
        ServiceType type = fe.getType();
        SessionEvent sessionEvent = fe.getEvent();

        if (type == ServiceType.MESSAGE) {
            try {
                // log request message
                logger.debug("message from " + sessionEvent.getFrom() + " \nmessage " + sessionEvent.getMessage());

                // give an automatic response
                session.sendMessage(sessionEvent.getFrom(), "hi, you are sending " + sessionEvent.getMessage());
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
    }
}

These are some screenshots related to this application.

To my friend, i hope this tutorial can help you getting started with your assignment. As the wise man once said “Answering one good question is like feeding a hungry person one meal, but teaching them research skills by example is showing them how to grow food for a lifetime.”

YNWA
(I)

ps. if somehow you found a NoClassDefFoundError, such as :
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
you need to include apache common logging lib into your project classpath.

Google+

How to Send Emails With Java Using Gmail Accounts

It’s actually quite simple on how to send emails using java, only need several lines of codes. This is how i do it


import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

public class MailTestSend {

    private static Logger logger = Logger.getLogger(MailTestSend.class);

    public static void main(String[] args) {
        try {

            // setup the mail server properties
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");

            // set up the message
            Session session = Session.getInstance(props);

            Message message = new MimeMessage(session);

            // add a TO address
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xxxxx@gmail.com"));

            // add a multiple CC addresses
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("yyyyy@gmail.com,zzzzzz@yahoo.com"));
            
            message.setSubject("Welcome to Java");
            message.setContent("Hi, im testing a new way to send emails via java.", "text/plain");

            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com", 587, "yourgmailusername", "yourgmailpassword");
            transport.sendMessage(message, message.getAllRecipients());
            logger.error("successfully send email");
        } catch (Exception e) {            
            logger.error(e, e);
        }
    }
}

Please dont forget to include mail.jar into your project. This is the screenshot of my netbeans libraries and my email inbox.

:-[

Google+

Error “Communications link failure” When Connecting Glassfish v3 to MySQL

Today i spent a ridiculously amount of time finding out why suddenly my application cannot connect to database. Im using Glassfish 3 connected to MySQL via connection pool on an Ubuntu server with an IP public. What makes it difficult is that it can connect smoothly before but suddenly an error happened.

This is the detail exception from my Glassfish’s log.

[#|2011-11-07T15:26:24.411+0700|WARNING|glassfish3.0.1|javax.enterprise.resource.resourceadapter.com.sun. enterprise.connectors.service|_ThreadID=30;_ThreadName=http-thread-pool-4848-(5);|RAR8054: Exception while creating an unpooled [test] 
connection for pool [ dbepay ], Connection could not be allocated because: Communications link failure

Last packet sent to the server was 0 ms ago.|#]

[#|2011-11-07T15:26:30.982+0700|WARNING|glassfish3.0.1|javax.enterprise.resource.resourceadapter.com. sun.enterprise.resource.pool|_ThreadID=31;_ThreadName=http-thread-pool-4848-(2);|RAR8023: 
Flush Connection Pool did not happen as pool - dbepay is not initialized|#]

After some browsing i found out that it’s due to mysql’s binding issue. Exception happened because MySQL server and Glassfish are installed on the same host, and in MySQL configuration on my.cnf have binded to a public ip address instead of localhost.
This is my ifconfig looks like

root@portal:~/edw/glassfishv3/glassfish/modules# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:50:56:01:00:0e  
          inet addr:xxx.xx.xxx.xx  Bcast:xxx.xx.xxx.xx  Mask:255.255.255.128
          inet6 addr: xxxxx :e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2082924 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1065587 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:668840899 (668.8 MB)  TX bytes:222095600 (222.0 MB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:4888314 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4888314 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:406280073 (406.2 MB)  TX bytes:406280073 (406.2 MB)

All i do is edit MySQL’s my.cnf, adding a new bind address to 127.0.0.1 and remarking previous binding.

[mysqld]
#
# * Basic Settings
#

#
# * IMPORTANT
#   If you make changes to these settings and your system uses apparmor, you may
#   also need to also adjust /etc/apparmor.d/usr.sbin.mysqld.
#

user		= mysql
socket		= /var/run/mysqld/mysqld.sock
port		= 3306
basedir		= /usr
datadir		= /var/lib/mysql
tmpdir		= /tmp
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#this is my previous value, binded to a public ip address
#bind-address		= xxx.xxx.xxx.xxx 

#this is my new value
bind-address		= 127.0.0.1

restart both of mysql and glassfish and suddenly, my application run smoothly again.
Thanks uncle Google, you’ve helped me alot.

Google+