Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Java Drools Example

Drools is a open source Business Logic integration Platform based on java from JBoss and RedHat. Here is one simple example to execute business logics based on rules. see more about drools

1. Create a maven project and add below dependencies

 
  <dependencies>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>6.0.0.CR1</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-core</artifactId>
            <version>6.0.0.CR1</version>
        </dependency>
    </dependencies>

2. Create a .drl file to add our business logic (eligibility.drl)


import com.vinod.test.Customer
 
dialect "mvel"
 
rule "Customer eligibility rule"
    when
        $customer : Customer(age>=21)              
    then
        System.out.println($customer.name" Eligibile for benefits");
end

3. Create Customer pojo class

package com.vinod.test;

public class Customer {
    private String name;
    private int age;
    public Customer() {
    }
    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
 

4. Create a main class to load and fire rules

package com.vinod.test;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.io.KieResources;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class CustomerEligibilityRuleTest {

    public static void main(String[] args) {
        List<File> rules = new ArrayList<File>();
        File currentdir = new File(System.getProperty("user.dir"));
        File[] listFiles = currentdir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return (name.endsWith(".drl"));
            }
        });
        for (File listFile : listFiles) {
            System.out.println(listFile.getName());
            rules.add(listFile);
        }
        List<Customer> customers = new ArrayList<Customer>();
        customers.add(new Customer("Vinod k kumaran", 21));
        executeRules(rules, customers);
    }

    public static void executeRules(List<File> files, List<Customer> customers) {
        try {
            KieServices kieServices = KieServices.Factory.get();
            KieResources kieResources = kieServices.getResources();
            KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
            KieRepository kieRepository = kieServices.getRepository();
            for (File ruleFile : files) {
                Resource resource = kieResources.newFileSystemResource(ruleFile);
                kieFileSystem.write(resource);
            }
            KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
            kb.buildAll();
            KieContainer kContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
            KieSession kSession = kContainer.newKieSession();
            kSession.addEventListener(new CustomerRuleTracker());
            for (Object customer : customers) {
                kSession.insert(customer);
            }
            kSession.fireAllRules();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 

5. Add rule tracker class to listen all stages of firing rules 

This class is added in the KieSession already in the above main class

package com.vinod.test;

import org.drools.core.event.BeforeActivationFiredEvent;
import org.kie.api.event.rule.AfterMatchFiredEvent;
import org.kie.api.event.rule.BeforeMatchFiredEvent;
import org.kie.api.event.rule.DefaultAgendaEventListener;
import org.kie.api.event.rule.MatchCancelledEvent;
import org.kie.api.event.rule.MatchCreatedEvent;
import org.kie.api.event.rule.MatchEvent;
import org.kie.api.event.rule.RuleFlowGroupActivatedEvent;

public class CustomerRuleTracker extends DefaultAgendaEventListener {

    @Override
    public void afterMatchFired(AfterMatchFiredEvent event) {
        System.out.println("Executing afterMatchFired ");
    }
    @Override
    public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
        System.out.println("Executing beforeRuleFlowGroupActivated ");

    }
    @Override
    public void beforeMatchFired(BeforeMatchFiredEvent event) {
        System.out.println("Executing beforeMatchFired ");
    }
    public void beforeActivationFired(BeforeActivationFiredEvent event) {
        System.out.println("Executing beforeActivationFired ");

    }
    @Override
    public void matchCreated(MatchCreatedEvent event) {
        System.out.println("Executing matchCreated ");
        registerActions(event);
    }
    @Override
    public void matchCancelled(MatchCancelledEvent event) {
        System.out.println("Executing matchCancelled");

    }
    private void registerActions(MatchEvent event) {
        System.out.println("Executing registerActions");
    }
}

6. Run the main program.

We can see the customer name + eligible for benefits printed as per our rules..

eligibility.drl

Executing matchCreated
Executing registerActions
Executing beforeMatchFired
Vinod k kumaran Eligibile for benefits
Executing afterMatchFired

7. Download Example

https://github.com/kkvinodkumaran/drools

Servlet RequestDispatcher

The javax.servlet.RequestDispatcher interface class help your servlet to call another servlet, JSP file, or HTML file from inside another servlet.

There are two main method in this interfaces


1) forward(ServletRequest request, ServletResponse response)

                  —>> forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server

2) include(ServletRequest request, ServletResponse response)
                  —>> includes the content of a resource (servlet, JSP page, HTML file) in the response


Example

Servlet class

This servlet class will do the include or forward based on the action from the user interface
package com.vinod;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServletDispatcher
 */

public class MyServletDispatcher extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */

    public MyServletDispatcher() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
        if (request.getParameter("action") != null) {
            String action = request.getParameter("action");
            if (action.equalsIgnoreCase("include")) {
                rd.include(request, response);
            } else if (action.equalsIgnoreCase("forward")) {
                rd.forward(request, response);
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}


Test jsp (Dispatcher.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form name="input" action="http://localhost:8081/MyServletDispatcher"
        method="get">
        Enter Action: <input type="text" name="action"><input
            type="submit" value="Submit">
    </form>
</body>
</html>

index.JSP
 
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

Deploy and run the Dispatcher.jsp ( In this example using jetty server, so used jetty:run maven command to start the jetty server)
 


Download complete Example

https://github.com/kkvinodkumaran/myj2ee

Java EE WebSocket Simple example

WebSocket is a protocol which allows for communication between the client and the server/endpoint using a single TCP connection. The advantage WebSocket has over HTTP is that the protocol is full-duplex (allows for simultaneous two-way communcation).

Here is one simple example to create a WebSocket endpoint and communicate it from a client.

Softwares Used

Java 1.7, Apache Tomcat, Eclipse

1. Create a Maven project with webapp archetype.

image

2.Create a WebSocket end point.

package com.pretech.test.websockets;
 
import java.io.IOException;
 
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
 
@ServerEndpoint("/websocket")
public class WebSocketTest {
 
    @OnMessage
    public void onMessage(String message, Session session) throws IOException,
            InterruptedException {
        System.out.println("User input: " + message);
        session.getBasicRemote().sendText("Hello world Mr. " + message);
        // Sending message to client each 1 second
        for (int i = 0; i <= 25; i++) {
            session.getBasicRemote().sendText(i + " Message from server");
            Thread.sleep(1000);
 
        }
    }
 
    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }
 
    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }
}

@ServerEndpoint annotation is used at type level and defines the current class as a websocket server endpoint. The value used in this annotation represents the URL where the endpoint will be listening for client connections

3. Create an html page

<!DOCTYPE html>
<html>
<head>
<title>Pretech blog testing web sockets</title>
</head>
<body>
    <div>
        <input type="text" id="userinput" /> <br> <input type="submit"
           value="Send Message to Server" onclick="start()" />
    </div>
    <div id="messages"></div>
    <script type="text/javascript">
        var webSocket = new WebSocket(
                'ws://localhost:8080/pretech-websocket-example-1.0-SNAPSHOT/websocket');

        webSocket.onerror = function(event) {
            onError(event)
        };

        webSocket.onopen = function(event) {
            onOpen(event)
        };

        webSocket.onmessage = function(event) {
            onMessage(event)
        };

        function onMessage(event) {
            document.getElementById('messages').innerHTML += '<br />'
                    + event.data;
        }

        function onOpen(event) {
            document.getElementById('messages').innerHTML = 'Now Connection established';
        }

        function onError(event) {
            alert(event.data);
        }

        function start() {
            var text = document.getElementById("userinput").value;

            webSocket.send(text);
            return false;
        }
    </script>
</body>
</html>

4. Build and deploy the war

Build the maven project and deploy the war in to tomcat server. Once the server is started hit the blow url.

http://localhost:8080/pretech-websocket-example-1.0-SNAPSHOT/hello.html

We will see the connection established message in the screen, now enter your name and submit the request.

image

image

 

5. Download this example

 

Download WebSoket Example

 

Ref: Netbeans

How to upload file using Servlet 3.0 ?

javax.servlet.http.Part class represents a part as uploaded to the server as part of a multipart/form-data request body. The part may represent either an uploaded file or form data. Here is one simple example to upload file using Servlet 3.0

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form method="post" action="/FileUploadServletExample/fileupload" enctype="multipart/form-data">  
        Choose file <input type="file" name="file">
        <input type="submit" value="submit">
    </form>
</body>
</html>

FileUploadServlet.java

package com.pretech;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@MultipartConfig         
@WebServlet("/fileupload")
public class FileUploadServlet extends HttpServlet {
 
	private static final long serialVersionUID = -7205406034336084784L;
	protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Part filePart = request.getPart("file");
        System.out.println("filename"+ filePart.getName());
        String fileName = getFileName(filePart);
        String fileLocation="c:/temp/";
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File outputFilePath = new File(fileLocation + fileName);
            inputStream = filePart.getInputStream();
            outputStream = new FileOutputStream(outputFilePath);
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        } catch (FileNotFoundException fne) {
            fne.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } 
        response.setContentType("text/html;UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("File upload completed");     
        writer.close();
    }
 
    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim()
                        .replace("\"", "");
            }
        }
        return null;
    }
}

Output



image


image


Java Database Connection Pooling example

Creating a connection to the database server is expensive. It is even more expensive if the server is located on another machine. Connection pool contains a number of open database connections which we can configure as minimum and maximum. There are lot of APIs available to create connection pooling also we can depend application server if it supports this feature, generally all the applications servers support connection pools. It creates the connection pool on behalf of you when it starts.

Here is one simple example which creates a connection pool maximum of size 5.

Prerequisites- mysql-connector-java-5.1.5-bin.jar should be there in the project class path.

Example (DatabaseConnectionPool.java)

package com.pretech;
 
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
 
public class DatabaseConnectionPool {
 
    private String driverName;
    private String password;
    private String url;
    private String user;
    private Driver driver;
    private Vector freeConnections;
    private int maxConn;
    private int count;
 
    /**
     * DatabaseConnectionPool constructor.
     *
     * @param drivername
     * @param conUrl
     * @param conuser
     * @param conpassword
     * @throws SQLException
     */

    public DatabaseConnectionPool(String drivername, String conUrl,
            String conuser, String conpassword) throws SQLException {
        freeConnections = new Vector();
        driverName = drivername;
        url = conUrl;
        user = conuser;
        password = conpassword;
        try {
            driver = (Driver) Class.forName(driverName).newInstance();
            DriverManager.registerDriver(driver);
        } catch (Exception _ex) {
            new SQLException();
        }
        count = 0;
        maxConn = 5;
    }
 
    /**
     * Method to destroy all connections.
     */

    public void destroy() {
        closeAll();
        try {
            DriverManager.deregisterDriver(driver);
            return;
        } catch (Exception e) {
            e.printStackTrace();
 
            return;
        }
    }
 
    /**
     * Method to add free connections in to pool.
     *
     * @param connection
     */

    public synchronized void freeConnection(Connection connection) {
        freeConnections.addElement(connection);
        count--;
        notifyAll();
    }
 
    /**
     * Method to get connections.
     *
     * @return Connection
     */

    public synchronized Connection getConnection() {
        Connection connection = null;
        if (freeConnections.size() > 0) {
            connection = (Connection) freeConnections.elementAt(0);
            freeConnections.removeElementAt(0);
            try {
                if (connection.isClosed()) {
                    connection = getConnection();
                }
            } catch (Exception e) {
                print(e.getMessage());
 
                connection = getConnection();
            }
            return connection;
        }
        if (count < maxConn) {
            connection = newConnection();
            print("NEW CONNECTION CREATED");
 
        }
        if (connection != null) {
            count++;
        }
        return connection;
    }
 
    /**
     * Method to close all resources
     */

    private synchronized void closeAll() {
        for (Enumeration enumeration = freeConnections.elements(); enumeration
                .hasMoreElements();) {
            Connection connection = (Connection) enumeration.nextElement();
            try {
                connection.close();
            } catch (Exception e) {
                print(e.getMessage());
            }
        }
        freeConnections.removeAllElements();
    }
 
    /**
     * Method to create new connection object.
     *
     * @return Connection.
     */

    private Connection newConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            print(e.getMessage());
            return null;
        }
        return connection;
    }
 
    private void print(String print) {
        System.out.println(print);
    }
}

Test Connection Pool(ConnectionPoolTest.java)

The above connection pool class we set the maximum number of connections as 5, in this test class we will create first 5 connections and release one connection and creates 6th connection ..see below example

package com.pretech;
 
import java.sql.Connection;
import java.sql.ResultSet;
 
public class ConnectionPoolTest {
    public static void main(String[] argv) {
        String dburl = "jdbc:mysql://localhost:3306/pretech";
        String driver = "com.mysql.jdbc.Driver";
        String sUser = "root";
        String sPwd = "root";
        java.sql.PreparedStatement pstmt;
        String select_sql = "select name,address from customer";
        ResultSet rs;
 
        DatabaseConnectionPool dbConnectionPool;
        // create database connection pool
        try {
            dbConnectionPool = new DatabaseConnectionPool(driver, dburl, sUser,
                    sPwd);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Connection c1, c2,c3,c4,c5,c6;
        c1 = dbConnectionPool.getConnection();
        c2 = dbConnectionPool.getConnection();
        c3 = dbConnectionPool.getConnection();
        c5 = dbConnectionPool.getConnection();
        c5 = dbConnectionPool.getConnection();
        dbConnectionPool.freeConnection(c5);
        c6 = dbConnectionPool.getConnection();
 
        try {
            pstmt = c6.prepareStatement(select_sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println("output value =>" + rs.getString(1) + ""
                        + rs.getString(2));
            }
            rs.close();
            pstmt.close();
            c1.setAutoCommit(true);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        // return first connection to the pool
        dbConnectionPool.freeConnection(c1);
        // release resources
        dbConnectionPool.destroy();
 
    }
 
}

Output

NEW CONNECTION CREATED
NEW CONNECTION CREATED
NEW CONNECTION CREATED
NEW CONNECTION CREATED
NEW CONNECTION CREATED
output value =>Vinod  Bangalore
output value =>Santhosh  Kannur
output value =>Shiva  Mysore

 

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts