martes, 22 de noviembre de 2011

An example of Weka and Java Persistence API

For this example I'm using MacBook Pro with Lion, Netbeans 6.9, MySQL Database.
First of all, we have to create a database in MySQL to retrieve the data. You can use the following script:


CREATE DATABASE IF NOT EXISTS exampleWeka;
USE exampleWeka;
DROP TABLE IF EXISTS weather;
CREATE TABLE  weather (
    id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),
    outlook varchar(10),
    temperature varchar(10),
    humidity varchar(10),
    windy varchar(10),
    play varchar(10)
);
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','hot','high','FALSE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','hot','high','TRUE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','hot','high','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','mild','high','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','cool','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','cool','normal','TRUE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','cool','normal','TRUE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','mild','high','FALSE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','cool','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','mild','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','mild','normal','TRUE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','mild','high','TRUE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','hot','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','mild','high','TRUE','no');
commit;



Then you can download Weka. I downloaded the version 3.4.19 from  http://sourceforge.net/projects/weka/files/weka-3-4/3.4.19/weka-3-4-19.zip/download. Then you have to extract the file and add weka.jar to the libraries of your EJB project

Then you have to create an Enterprise Application project in Netbeans.




Add MySQL library to the EJB Project.

Add the library weka.jar to the EJB project. I'm using the version available at:http://sourceforge.net/projects/weka/files/weka-3-7/3.7.5/weka-3-7-5-monolithic.jar/download

After this, create a Datasource to the database created above.

Create an Entity class to use the weather table.

Create a Session bean with remote interface.

Create the following utility class in the package com.example.ejb.util of the EJB project



package com.example.ejb.util;

import com.example.ejb.entity.Weather;
import java.util.List;
import weka.classifiers.trees.J48;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;

public class UtilWeka {
    static Instances instances = null;

    private static FastVector createAttributes(boolean classification) {
        FastVector fvWekaAttributes = new FastVector(9);
        FastVector fvOutlook = new FastVector(3);
        fvOutlook.addElement("sunny");
        fvOutlook.addElement("overcast");
        fvOutlook.addElement("rainy");
        Attribute outlook = new Attribute("outlook", fvOutlook);
        fvWekaAttributes.addElement(outlook);

        FastVector fvTemperature = new FastVector(3);
        fvTemperature.addElement("hot");
        fvTemperature.addElement("mild");
        fvTemperature.addElement("cool");
        Attribute temperature = new Attribute("temperature", fvTemperature);
        fvWekaAttributes.addElement(temperature);

        FastVector fvHumidity = new FastVector(2);
        fvHumidity.addElement("high");
        fvHumidity.addElement("normal");
        Attribute humidity = new Attribute("humidity", fvHumidity);
        fvWekaAttributes.addElement(humidity);

        FastVector fvWindy = new FastVector(2);
        fvWindy.addElement("TRUE");
        fvWindy.addElement("FALSE");
        Attribute windy = new Attribute("windy", fvWindy);
        fvWekaAttributes.addElement(windy);


        if(!classification){
        FastVector fvPlay = new FastVector(2);
        fvPlay.addElement("no");
        fvPlay.addElement("yes");
        Attribute play = new Attribute("play", fvPlay);
        fvWekaAttributes.addElement(play);
        }

        return fvWekaAttributes;
    }

    private static Instances generateInstances(List list) {
        FastVector fvAttributes = createAttributes(false);
        Instances instances = new Instances("Rel", fvAttributes, 5);
        instances.setClassIndex(instances.numAttributes() - 1);
        for (Weather weather : list) {
            Instance iExample = new Instance(5);
            iExample.setValue((Attribute) fvAttributes.elementAt(0), weather.getOutlook());
            iExample.setValue((Attribute) fvAttributes.elementAt(1), weather.getTemperature());
            iExample.setValue((Attribute) fvAttributes.elementAt(2), weather.getHumidity());
            iExample.setValue((Attribute) fvAttributes.elementAt(3), weather.getWindy());
            iExample.setValue((Attribute) fvAttributes.elementAt(4), weather.getPlay());
            instances.add(iExample);
        }
        return instances;
    }

    private static Instance generateWeatherInstance(Weather weather) {
        FastVector fvAttributes = createAttributes(true);
        Instances instances = new Instances("Rel", fvAttributes, 9);
        instances.setClassIndex(instances.numAttributes() - 1);



        Instance iExample = new Instance(9);
        iExample.setValue((Attribute) fvAttributes.elementAt(0), weather.getOutlook());
        iExample.setValue((Attribute) fvAttributes.elementAt(1), weather.getTemperature());
        iExample.setValue((Attribute) fvAttributes.elementAt(2), weather.getHumidity());
        iExample.setValue((Attribute) fvAttributes.elementAt(3), weather.getWindy());
       // iExample.setValue((Attribute) fvAttributes.elementAt(4), weather.getPlay());

        instances.add(iExample);

        return instances.firstInstance();
    }

    public static void initJ48Tree(List list) {
        instances=generateInstances(list);
        try {
            J48 j48 = new J48();
            instances.setClassIndex(instances.numAttributes() - 1);
            j48.buildClassifier(instances);
            System.out.println(j48.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void classifyInstanceJ48(Weather weather) {
        double val=0;
        try {
            J48 j48 = new J48();
            instances.setClassIndex(instances.numAttributes() - 1);
            j48.buildClassifier(instances);
            val=j48.classifyInstance(generateWeatherInstance(weather));
            if(val==1){
                System.out.println("We can play");
            }else{
                System.out.println("We can't play");
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
 

Change SessionBean to: 


package com.example.ejb.session;

import com.example.ejb.entity.Weather;
import com.example.ejb.util.UtilWeka;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import weka.core.Instances;

@Stateless
public class SessionBean implements SessionBeanRemote {

    @PersistenceContext
EntityManager em;
Instances instances =null;
    public void initWeatherData() {
        Query query=em.createNamedQuery("Weather.findAll");
        UtilWeka.initJ48Tree((List)query.getResultList());
}

    public void classifyJ48(Weather weather) {
        UtilWeka.classifyInstanceJ48(weather);
    }
   
}
 


Modify the client with an injection to the Session Bean.

package mavenwekaapp;

import com.example.ejb.entity.Weather;
import com.example.ejb.session.SessionBeanRemote;
import javax.ejb.EJB;

public class Main {
    @EJB
    private static SessionBeanRemote sessionBean;


    public static void main(String[] args) {
        sessionBean.initWeatherData();
        Weather wheater=new Weather();
        wheater.setHumidity("normal");
        wheater.setOutlook("overcast");
        wheater.setTemperature("hot");
        wheater.setWindy("FALSE");
        sessionBean.classifyJ48(wheater);
    }
}



Run the Enterprise Project.


These are functions,which implement ID3 and NBTree algorithms.
public static void initId3Tree(List list) {
        instances=generateInstances(list);
        try {
            Id3 id3 = new Id3();
            instances.setClassIndex(instances.numAttributes() - 1);
            id3.buildClassifier(instances);
            System.out.println(id3.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void classifyInstanceId3(Weather weather) {
        double val=0;
        try {
            Id3 id3 = new Id3();
            instances.setClassIndex(instances.numAttributes() - 1);
            id3.buildClassifier(instances);
            val=id3.classifyInstance(generateWeatherInstance(weather));
            if(val==1){
                System.out.println("We can play");
            }else{
                System.out.println("We can't play");
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    public static void initNBTree(List list) {
        instances=generateInstances(list);
        try {
            NBTree nbTree = new NBTree();
            instances.setClassIndex(instances.numAttributes() - 1);
            nbTree.buildClassifier(instances);
            System.out.println(nbTree.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void classifyInstanceNBTree(Weather weather) {
        double val=0;
        try {
            NBTree nbTree = new NBTree();
            instances.setClassIndex(instances.numAttributes() - 1);
            nbTree.buildClassifier(instances);
            val=nbTree.classifyInstance(generateWeatherInstance(weather));
            if(val==1){
                System.out.println("We can play");
            }else{
                System.out.println("We can't play");
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }






jueves, 17 de noviembre de 2011

How to use Facebook Graph API with Javascript

For this example I'm using: MacBook Pro with Lion(10.7.1) as operative system, Netbeans 7.0 and a Facebook account.

This is a quick example of Facebook Graph API. This code allows Facebook users to publish information in their walls, retrieve friends and send message to their friends. To test this code you have to create a Facebook application in https://developers.facebook.com/apps
I named the application as TestGraphAPI:
Enter the captcha value:

Then you have to register the URL of your application, pg: http://localhost:8080/TestGraphAPI.
I created a web java application in Netbeans and pasted the following code in the index jsp page:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Facebook Example</title>
    </head>
    <body>
        <div id="fb-root">
            <script type="text/javascript">

                window.fbAsyncInit = function() {
                    FB.init({appId: 'XXXXXXXXXXXXXXX', status: true, cookie: true, xfbml: true});
                    FB.getLoginStatus(function(response) {
                        if (response.session!=null) {
                            alert("Welcome, you have been logged to Facebook");
                        }else{
                            alert("To use this application you have to be logged at Facebook");
                     
                        }
                    });
                };
                (function() {
                    var scriptFacebook = document.createElement('script');
                    scriptFacebook.type = 'text/javascript';
                    scriptFacebook.src = document.location.protocol +
                        '//connect.facebook.net/en_US/all.js';
                    scriptFacebook.async = true;
                    document.getElementById('fb-root').appendChild(scriptFacebook);
                }());
         
                function obtenerAmigos(){
                    document.getElementById("imagenes").innerHTML="Click on the images to send a message<br/>";
                    FB.api('/me/friends',function(response){
                        for(i=0;i<response.data.length;i++){
                            document.getElementById("imagenes").innerHTML+="<img src='https://graph.facebook.com/"+response.data[i].id+"/picture' onclick='enviarMensaje(\""+response.data[i].id+"\",\""+response.data[i].name+"\")'/>";
                        }
                    });
                }
         
                function escribirMuro(){
                    var mensaje=prompt("What is your message?");
                    FB.api('/me/feed', 'post', { message: mensaje }, function(response) {
                        if (!response || response.error) {
                            alert('A problem ocurred');
                        } else {
                            alert('The message was sent to your wall');
                        }
                 
                    });
                }
             
                function enviarMensaje(id,name){
                    var mensaje=prompt("Enter the message to "+name);
                    FB.api('/'+id+'/feed', 'POST', { message: mensaje }, function(response) {
                        if (!response || response.error) {
                            alert('A problem ocurred');
                        } else {
                            alert('The message was sent to '+name);
                        }
                    });
                 
                }
             
            </script>
        </div>
    <fb:login-button autologoutlink="true" scope="email,status_update,publish_stream,sms"></fb:login-button><br/>
    <input type="button" value="Post on your wall" onclick="escribirMuro()"/>
    <input type="button" value="Get Friends" onclick="obtenerAmigos()"><br/>
    <div id="fb-root">
        <div id="imagenes">

        </div>
    </div>
</body>
</html>

Finally replace the APP ID in XXXXXXXXXXXXXXX





and test the application.