Welcome JAVIAN

Play Java LogoJava Addicted !

https://playjava.wordpress.com

Advertisements

Extract List of Property / Field from List of Objects

Objective: To get list of a property from list of objects

Case:
Many times while working with database entities or beans we have a list of beans/entities though we need only list of ids or list of other field.
So we need to iterate from list and populate desired list.

To reduce these effort, a generic method that will do this job.

We have to pass list of beans and name of field we need.

Important: Bean class must have getter method for field need to be extracted

Here is simple method:

Continue reading

Websocket in Java Part 1: Before JAVA EE7

Learn Recipe: WebSocket using Java

In this first article on websocket we will learn what is websocket and its implementation in JAVA EE6.
In part2 we will see new Java websocket API JSR356

So lets KICKSTART Websockets.

Precook : Few tech facts

What is Websocket ? A brief introduction

  • New protocol introduced in HTML5 specification (RFC 6455)
  • Leverages HTTP upgrade technology
  • Upgrade HTTP to Websocket
  • Once connection established no headers, cookies required
  • A full duplex communication
  • Independent¬† message can be sent in both direction (server-client).
  • Supports binary data
  • Since uses TCP/HTTP, thus work on same port
  • Also support secure connection ie both ws:// or wss:// supported.
  • Intended to use for: Chat Applications,Interactive games,Media Streaming, Notifications,server push…
  • Browser Support : (All leading browser supports)Firefox,Chrome,Safari,IE10,etc…
  • Server support: Apcahe Tomcat 7,Oracle Glassfish3,Oracle Glassfish4
  • JAVA API:
    • For JAVA EE 6: Third party API available.( Tomcat7 /Glassfish3 /Jwebsocket / Lightstramer )
    • For JAVA EE7: Implemented (JSR356) Java API for Web Socket.

Let’s Cook : Simple Eco application

Continue reading

Compile and Run java file from Notepad++

Just like to share old trick , used to compile and run java file
using notepad++.

To cook recipe: To compile and run java file using Notepadd++.

Ingredients:
Notepad++ Application
Installed JDK on system

Environment:
Windows

Procedure:

1> Make sure java path is properly set in windows environment variable.
To check go to command prompt and test java and javac commands working.

2>In notepad++, open any simple java file to test.

3>Press F5. Paste following in input box.
cmd /k cd $(CURRENT_DIRECTORY) && javac -cp . $(FILE_NAME)

3>Click save. Give Commad name say "Compile Java ".
Select shortcut combination. say Ctrl+Alt+2

4>Click Ok.Click Run to compile java file.

5>Now in Notepad++ again press F5. Paste following in input box.
cmd /k cd $(CURRENT_DIRECTORY) && java -cp . $(NAME_PART)

6>Click save. Give Command name say "Run Java File".

Select shortcut combination. say Ctrl+Alt+1

7>Click Ok. Click Run to run java file.

8>Now try with shortcut combinations. Shortcut will not work if it isn`t unique.


String Reaplce All Method with Ignore case

The core String class does not provide replace all method with ignore case.

I have written a method replaceAllIgnoreCase().This method take three parameter as:

 /**
 * @param original: Original string to be modified. Must not be null.
 * @param regex: String to be discarded.
 * @param replacement: String to be replaced with.
 * @return
 */

This is ready to use method copy class to your project and call method as:

<p style="text-align: center;"><code>
.
.
.
String result=EString.replaceAllIgnoreCase(org,regex,replacement);
.
.
.

Here is source code:

/**
*
* @author abhishek.anne@gmail.com
* @publish @ playjava.wordpress.com
*
*/
public class EString {

public static void main(String[] args) {
String test = "SUN Rise and sun Set.";
String result = replaceAllIgnoreCase(test, "SUN", "Moon");
System.out.println("Original String :" + test);
System.out.println("Result String :" + result);
}

/**
* @param original: Original string to be modified. Must not be null.
* @param regex: String to be discarded.
* @param replacement: String to be replaced with.
* @return
*/
static String replaceAllIgnoreCase(String original, String regex,
String replacement) {
String r = null;

int repl = replacement.length();
int regl = regex.length();
int dif = repl - regl;
int cnt = 0;
String regLc = regex.toLowerCase();
String repLC = replacement.toLowerCase();
String buf = original.toLowerCase();
int index;
while ((index = buf.indexOf(regLc)) &gt;= 0) {
buf = buf.substring(index + regl);
if (r != null) {
if (dif == 0) {
r += original.substring(r.length() + dif, r.length()
+ dif + index);
r += replacement;
} else {
r += original.substring(r.length() - (dif * cnt),
r.length() - (dif * cnt) + index);
r += replacement;
cnt++;
}
} else {
if (index != 0) {
r = original.substring(0, index) + replacement;
cnt++;
} else {
r = replacement;
cnt++;

}
}
}
if(dif==0)
{
r += original.substring(r.length() + dif, original.length());
}
else
{
r += original.substring(r.length() - (dif * cnt),original.length());

}
return r;
}
}

Share your experience and any bug or performance issue if detected.

One other option is provided as:

String sentence = "The sly brown Fox jumped over the lazy foX.";
String result = sentence.replaceAll("(?i)fox", "dog");
System.out.println("Input: " + sentence);
System.out.println("Output: " + result);

But this was not working all the time for me.

Example : Database Pooling With Tomcat7 and SQLServer


This is an step by step guide to create Database Pooling for java web based application which is recommended for preformance.
Ingredients:
Container used : Tomcat v7
Databse used : MS SQL Server 2008
IDE used : Eclipse

Get latest Microsoft JDBC Driver 4.0 for SQL server from here
Use sqljdbc4.jar for Java6.

Step 1:
Create dynamic web project in Eclipse say DBPoolingSample.

Step 2:

Create XML file in WebContentMETA-INFcontext.xml



<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Specify a JDBC datasource -->
<Resource name="jdbc/testdb" auth="Container"
type="javax.sql.DataSource" username="<username>" password="<password>"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1434;DatabaseName=connectpool_db"
maxActive="10" maxIdle="4" />
</Context>

Note: Check IP for SQL server instance.
Note: Change username password.

Step 3:

Create a java class to retrieve Connection object.
package db.;

package db;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
*
* @author abhishek.anne
*
*/
public class DBConnect {
private DataSource dataSource;
private Connection connection;
private static DBConnect moDbConnect;

private DBConnect() {

try {
// Get DataSource
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/testdb");

} catch (NamingException e) {
e.printStackTrace();
}
}

public static Connection getConnection() throws NullPointerException{
if (moDbConnect != null) {
try {
moDbConnect.connection = moDbConnect.dataSource.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return moDbConnect.connection;
} else {
moDbConnect = new DBConnect();
try {
moDbConnect.connection = moDbConnect.dataSource.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return moDbConnect.connection;
}
}

}

Step 4:
Create anyservlet to use connection obejct to perform db operation.

package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBConnect;

public class DBServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

Connection connection=null;
Statement statement=null;
ResultSet resultSet = null;
try {
connection = DBConnect.getConnection();
statement = connection.createStatement();
String query = "SELECT * FROM [coonectpool_db].[dbo].[user]";
resultSet = statement.executeQuery(query);

PrintWriter out=resp.getWriter();

while (resultSet.next()) {
out.println(resultSet.getInt(1) + resultSet.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (null != resultSet)
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != statement)
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != connection)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Step 5:

Sample web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TomcatConnectionPooling</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>
servlet.DBServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/servlet/test</url-pattern>
</servlet-mapping>
</web-app>

Step 6:

Deploy Application and browse
http://localhost:<port>/DBPoolingSample/servlet/test

By making driver change you can connect to respective Database server
like:
MY SQL:com.mysql.jdbc.Driver
Oracle :oracle.jdbc.driver.OracleDriver

 

JDBC Connection using MDB file

/* Program:

* Setup database driver manager to understand and use ODBC MS-ACCESS data source.

*

* Compile as: javac dbAccess.java

*/
/**
*
* @author abhishek.anne@gmail.com
* @publish @ playjava.wordpress.com
*
*/

import java.sql.*;

public class dbAccess

{

public static void main(String[] args)

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database =

"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=myDB.mdb;";

Connection conn = DriverManager.getConnection(database, "", "");

Statement s = conn.createStatement();

// create a table

String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));

String createTable = "CREATE TABLE " + tableName +

" (id Integer, name Text(32))";

s.execute(createTable);

// enter value into table

for(int i=0; i&lt;25; i++)

{

String addRow = "INSERT INTO " + tableName + " VALUES ( " +

String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " +

String.valueOf(Math.random()) + "')";

s.execute(addRow);

}

// Fetch table

String selTable = "SELECT * FROM " + tableName;

s.execute(selTable);

ResultSet rs = s.getResultSet();

while((rs!=null) &amp;&amp; (rs.next()))

{

System.out.println(rs.getString(1) + " : " + rs.getString(2));

}

// drop the table

String dropTable = "DROP TABLE " + tableName;

s.execute(dropTable);

// close and cleanup

s.close();

conn.close();

}

catch(Exception ex)

{

ex.printStackTrace();

}

}

}