Get Current Month Name

Calendar cale = Calendar.getInstance();

System.out.println(“Month Name: “+cale.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()));

Advertisements
Posted in J2SE | Leave a comment

Apache DBUtil Create-Insert-Select-Update-Delete program

 

public class PlayerData {

         private String id;
         private String name;
         private String team;
         private Long totalRuns;
         public String getId() {
                  return id;
         }
         public void setId(String id) {
                  this.id = id;
         }
         public String getName() {
                  return name;
         }
         public void setName(String name) {
                  this.name = name;
         }
         public String getTeam() {
                  return team;
         }
         public void setTeam(String team) {
                  this.team = team;
         }
         public Long getTotalRuns() {
                  return totalRuns;
         }
         public void setTotalRuns(Long totalRuns) {
                  this.totalRuns = totalRuns;
         }
         
         @Override
         public String toString() {
                  return “PlayerData [Id=” + id + “, Name=” + name + “, Team=” + team
                  + “, TotalRun=” + totalRuns + “]”;
         }         
}

——————————————————————————————————————-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

class DatabaseWorkController{
         private Connection connection = null;
         private QueryRunner queryRunner = null;

         long startTime = 0;

         DatabaseWorkController(){ }

         public void loadDriverAndMakeConnection(){
                  System.out.println(“Method loadDriverAndMakeConnection()\n”);
                  try
                  {
                  
                           Class.forName(“oracle.jdbc.driver.OracleDriver”);
                           connection = DriverManager.getConnection(“jdbc:oracle:thin:@192.168.8.87:1521:aaadb”, “netvertextrunk”,                                     “netvertextrunk”);
                           queryRunner = new QueryRunner();
         
                  }catch(Exception e) {
                                    System.out.println(“Error : “+e);
                  }
         }

         public void insertData(){
                  System.out.println(“\nMethod insertData()”);
                  try {
                           startTime = System.currentTimeMillis();

                           int result = queryRunner.update(connection, “INSERT INTO PLAYERS (ID, NAME, TEAM, TOTALRUNS) VALUES(?,                                     ?, ?, ?)”,”1″,”SACHIN”,”India”,46000);
                           result = queryRunner.update(connection, “INSERT INTO PLAYERS (ID, NAME, TEAM, TOTALRUNS) VALUES(?, ?,                                     ?, ?)”,”1″,”SAMSON”,”India”,1000);
                           System.out.println(“Inserted Rows: “+result);
                           System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                  } catch (SQLException e) {
                           e.printStackTrace();
                  }
}

public void selectAllData(){
                  System.out.println(“\nMethod selectAllData()”);

                  ResultSetHandler<List<PlayerData>> rsh = new BeanListHandler<PlayerData>(PlayerData.class);
                  try {
                           startTime = System.currentTimeMillis();
                           List<PlayerData> result = queryRunner.query( connection, “SELECT * FROM PLAYERS”,rsh);
                           for(PlayerData player: result){
                                    System.out.println(player);
                           }
                           System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                  } catch (SQLException e) {
                           e.printStackTrace();
                  }
         }

         public void oldWaySelectAllData(){
                  System.out.println(“\nMethod oldWaySelectAllData()”);
                  ResultSet rs = null;
                  try {
                           startTime = System.currentTimeMillis();
                           Statement stmt = connection.createStatement();
                           rs = stmt.executeQuery(“select * from players”);
                           while(rs.next()){
                                    int id = rs.getInt(“ID”);
                                    String name = rs.getString(“name”);
                                    String team = rs.getString(“team”);
                                    String totalRuns = rs.getString(“totalruns”);
                                    System.out.println(“PlayerData [Id=” + id + “, Name=” + name + “, Team=” + team
                                    + “, TotalRun=” + totalRuns + “]”);
                           }
                           rs.close();
                           System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }
                  }

                  public void selectParticularData(){
                           System.out.println(“\n\nMethod selectParticularData()”);
         
                           ResultSetHandler<PlayerData> rsh = new BeanHandler<PlayerData>(PlayerData.class);

                           try {
                                    startTime = System.currentTimeMillis();
                                    PlayerData player = queryRunner.query( connection, “SELECT * FROM PLAYERS WHERE ID = ? “,rsh, “1”);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                    System.out.println(player);
                                    } catch (SQLException e) {
                                             e.printStackTrace();
                                    }
                           }
                  
                           public void updateParticularData(){
                                    System.out.println(“\n\nMethod updateParticularData()”);
                                    try {

                                             startTime = System.currentTimeMillis();
                                              int result = queryRunner.update(connection,”UPDATE PLAYERS SET NAME = ? WHERE ID = ?                                                                “,”Sachin Tendulkar”,”1″);
                                             System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                             System.out.println(“Update Rows: “+result);
                                    } catch (SQLException e) {
                                             e.printStackTrace();
                                    }
         }

         public void deleteTable(){
                  System.out.println(“\n\nMethod deleteTable()”);
                           try {
                                    startTime = System.currentTimeMillis();
                                    int result = queryRunner.update(connection,”DROP TABLE PLAYERS”);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                    System.out.println(“Table deleted successfully: “+result);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }

                  }

                  public void destroyConnection(){
                           System.out.println(“\n\nMethod destroyConnection()”);
                           try {
                                    startTime = System.currentTimeMillis();
                                    DbUtils.close(connection);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }
                  }

                  public void createTable() {
                                    System.out.println(“\n\nMethod createTable()”);
                           try {
                  
                                    startTime = System.currentTimeMillis();
                                    int result = queryRunner.update(connection,”CREATE TABLE PLAYERS ( ID int, Name varchar(255), Team                                              varchar(255), TotalRuns varchar(255))”);
                                    System.out.println(“Total Time taken: “+(System.currentTimeMillis()-startTime)+” ms”);
                                    System.out.println(“Table created successfully: “+result);
                           } catch (SQLException e) {
                                    e.printStackTrace();
                           }
                  }
         }

         public class DBUtilFlight {

         public static void main(String[] dataBag)
         {
                  DatabaseWorkController controller = new DatabaseWorkController();
                  controller.loadDriverAndMakeConnection();
                  
                  controller.createTable();
                  controller.insertData();
                  controller.selectAllData();
                  controller.oldWaySelectAllData();

                  controller.selectParticularData();
                  controller.updateParticularData();
                  controller.selectParticularData();

                  controller.deleteTable();
}
}

 

Posted in J2SE | Leave a comment

TLD to display Logo (Image)

Note: Put your Image Under the  (contextPath of your App/images/) folder

TLD FILE

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>
<!DOCTYPE taglib PUBLIC “-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN” “http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd”&gt;

<taglib>
<tlibversion>1.5</tlibversion>
<jspversion>1.1</jspversion>
<shortname>NetvertexSM</shortname>
<uri>http://https://javacircles.wordpress.com/myprojects/tags</uri&gt;
<info>I am JavaCirle</info>

<tag>
<name>logoImage</name>
<tagclass>com.raj.myproject.util.MyLogo</tagclass>
<bodycontent>empty</bodycontent>
<info>Logo Image</info>
</tag>

</taglib>

================================

CLASS FILE

—————–

 

package com.raj.myproject.util;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyLogo extends TagSupport {
private static final long serialVersionUID = 1L;
private static final String MODULE = ElitecoreLogo.class.getSimpleName();

public int doStartTag() throws JspException {

JspWriter painter = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
StringBuffer results = new StringBuffer();
results.append(“<input type=\”image\” src=\””+request.getContextPath()+”/images/jisp.jpg\” width=\”101\”                                                         height=\”113\” />”);
try {
painter.write(results.toString());
} catch (IOException e) {
Logger.logError(MODULE, “Exception reason : “+e.getMessage());
e.printStackTrace();
}
return EVAL_PAGE;
}
}

Posted in J2EE | Leave a comment

ENUM vs CONSTANTS

Programs that use the int enum pattern are brittle. Because int enums are
compile-time constants, they are compiled into the clients that use them. If the int
associated with an enum constant is changed, its clients must be recompiled. If
they aren’t, they will still run, but their behavior will be undefined.
There is no easy way to translate int enum constants into printable strings. If
you print such a constant or display it from a debugger, all you see is a number,
which isn’t very helpful. There is no reliable way to iterate over all the int enum
constants in a group, or even to obtain the size of an int enum group.
You may encounter a variant of this pattern in which String constants are
used in place of int constants. This variant, known as the String enum pattern, is
even less desirable. While it does provide printable strings for its constants, it can
lead to performance problems because it relies on string comparisons. Worse, it
can lead naive users to hard-code string constants into client code instead of using
field names. If such a hard-coded string constant contains a typographical error, it
will escape detection at compile time and result in bugs at runtime.

Posted in J2SE | Leave a comment

JAVA DEEP CLONING PROGRAM

import java.io.Serializable;
class Ant implements Serializable,Cloneable{
       public String sms;
       public Ant(String name){
              this.sms = “Help me ,”+ name +” is eating me”;
       }

       public void printSMS(){
              System.out.println(“Ant SMS : “+sms);
       }

       public Ant clone() throws CloneNotSupportedException{
              return (Ant)super.clone();
       }
}
class Bird implements Serializable,Cloneable{
       public Ant ant = null;
       public String name;
       public String sms;

       public Bird(String name){
              ant = new Ant(name);
              this.name = name;
              this.sms = “Welcome to “+ name +” World”;
       }
       public void printSMS(){
              System.out.println(“Bird SMS : “+sms);
       }

       public Ant getAnt(){
              return this.ant;
       }

       @Override
       public Bird clone() throws CloneNotSupportedException{
       Bird cloneBird = (Bird)super.clone();
              cloneBird.ant = ant.clone();
              return cloneBird;
       }
}

class CloneFlight {

       public static void main(String[] args) {
       System.out.println(“—-Bird1 detail—–“);
       Bird bird1 = new Bird(“Sparrow”);
       bird1.printSMS();
       bird1.getAnt().printSMS();
       try{
              System.out.println(“\n\n —-Bird2 detail—–“);
              Bird bird2 = bird1.clone();
              bird2.printSMS();
              bird2.getAnt().printSMS();
              bird1.getAnt().sms = “please”;
              bird1.getAnt().printSMS();
              bird2.getAnt().printSMS();
              bird1.sms=”hi”;
              bird2.sms=”hello”;
              bird1.printSMS();
              bird2.printSMS();
       }catch(Exception ex){
              System.out.println(“Error : “+ex.getMessage());
       }
       }
}

Posted in Uncategorized | Leave a comment

HIBERNATE flush(), commit(), clear() methods

 

About Hibenate flush(), commit() and clear() methods

The flush process synchronizes database state with session state by detecting state changes and executing SQL statements.

flush() sends SQL instructions to the database like INSERT, UPDATE etc. It will not send a COMMIT, so if you have an exception after a flush(), you can still have a complete rollback

Commit() and flush()

Commit will make the database commit

– Flushing is the process of synchronizing the underlying persistent

store with persistable state held in memory.

ie. it will update or insert into your tables in the running

transaction, but it _may_ not commit those changes (this depends on

your flush mode). When you have a persisted object and you change a

value on it, it becomes dirty and hibernate needs to flush these

changes to your persistence layer. It may do this automatically for

you or you may need to do this manually, that depends on your flush

mode

 

 

First level cache: always active and relates to a unit of work, i.e. mostly to a service call as it is attached to the current session.

 

Second level cache: can be configured for certain entities. In this case, the objects are deposited in a cross-transaction cache. The key to this deposit is the primary key of the entity. The cache can be configured cluster-wide or within a JVM.

 

Query cache: stores the result of an HQL/EJB-QL query in a cache. For this, only the primary keys of the result objects are stored which are then loaded via second level cache. Thus the query cache works only together with the second level cache.

 

 

 

session is not a thread safe object – cannot be shared by multiple threads. You should always use “one session per request” or “one session per transaction”

 

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context – you don’t need to close this.

 

A session is opened whenever getCurrentSession() is called for the first time. This creates a brand new session if one does not exist or uses an existing one if one already exists. In tomcat this associates a session with a thread which is created using the underlying ThreadLocal object. But since Tomcat uses thread pooling it is entirely possible that a request may receive a thread with a session already associated with it, thus introducing the possibility of not even creating a brand new session. The method openSession() on the other hand creates a new session but does not attempt to associate it with a thread. But remember openSession() introduces another hitch in that it expects users to handle the closing and flushing of sessions themselves, instead of letting Hibernate do it automatically for us.

Posted in Hibernate | Leave a comment

JAVA CODE TO CONVERT BYTES TO SUITABLE UNIT

private static DecimalFormat twoDecimalForm = new DecimalFormat(“#.##”);
private static final double BYTE = 1024, KB = BYTE, MB = KB*BYTE, GB = MB*BYTE;

public static String convertBytesToSuitableUnit(long bytes){
String bytesToSuitableUnit= bytes + ” B”;

if(bytes >= GB) {
double tempBytes = bytes/GB;
bytesToSuitableUnit = twoDecimalForm.format(tempBytes) + ” GB”;
return bytesToSuitableUnit;
}
if(bytes >= MB) {
double tempBytes = bytes/MB;
bytesToSuitableUnit = twoDecimalForm.format(tempBytes) + ” MB”;
return bytesToSuitableUnit;
}
if(bytes >= KB) {
double tempBytes = bytes/KB;
bytesToSuitableUnit = twoDecimalForm.format(tempBytes) + ” kB”;
return bytesToSuitableUnit;
}
return bytesToSuitableUnit;
}

 

🙂 Hey Buddy Write your Comment 🙂

Posted in J2SE | Leave a comment