Wednesday, July 27, 2011

How to create Auto Generated Transaction ID in java ( Unique key )



Note : This auto generated Transaction unique key is in this format : eg : ( DASARI_1212121212  )
Note : where DASARI IS PREFIX AND 1212121212 IS DateTime in Milliseconds.

Instance Variables :

   private static long m_nMaxTID = 1000;
    private static long m_nMinTID = 0;
    private static long m_iCount = 0;
    private static String m_strTmp = "000";
    private static int m_nTmpLen = 3;





public static synchronized String generateTID(String strPrefix) {
        strPrefix = strPrefix + "_" + (new java.util.Date()).getTime();
        System.out.println("");
        String strSuf = m_strTmp + m_iCount;
        m_iCount++;
        if (m_iCount >= m_nMaxTID) {
            m_iCount = m_nMinTID;
        }
        return strPrefix + strSuf.substring(strSuf.length() - m_nTmpLen);
    }

Note : simply call String transactionID=generateTID("DASARI");

Cheers
Dasari

Thursday, July 21, 2011

How to Write and Call Store Procedures in java using MYSQL Database

Scenarios :

Note : for one table only..............

1 @ Scenario :  Updating Specific Rows based on Where Condition and several fields.

'update tablename(dasari) set columnname= ? where column_name in (?)  and column_name in (?) and column_name =curdate() and column_name is null  limit ? ';

2 @ Scenario :  For Retrieving all the Rows Based on Specific Column_name :

' select * from tablename(dasari)  where column_name=?';

Below is the Example Program  for Employee Information : Passing only IN Parameters

Step -1 : Create Table Name with following fields.

                CREATE TABLE `alerts` (      
                       `id` bigint(20) NOT NULL auto_increment,
                       `inserted_on` date default NULL,        
                       `msisdn` varchar(50) default NULL,      
                       `op_id` smallint(6) default NULL,        
                       `spid` int(11) default NULL,            
                       `flag` bigint(10) unsigned default NULL,
                       PRIMARY KEY  (`id`),                    
                       KEY `idx_insertedon` (`inserted_on`),    
                       KEY `idx_spid` (`op_id`)                
                     ) ENGINE=InnoDB DEFAULT CHARSET=latin1    

Step -2   Create a procedure


DELIMITER $$

DROP PROCEDURE IF EXISTS `databasename`.`dasari_procedure`$$

CREATE DEFINER=`username`@`localhost` PROCEDURE `dasari_procedure`(in strSpids varchar(512),in strOpid varchar(512),
 in nLimit int, in nFlag bigint)
BEGIN
  declare nLimit1 int(10);
  declare nFlag1 bigint;
  declare strOpid1 varchar(512);
  declare strSpids1 varchar(512);
  if (nLimit <= 0) then
  set @nLimit1 = 100;
  else
  set @nLimit1 = nLimit;
  end if;
  set @nFlag1 = nFlag;
  set @strOpid1 = strOpid;
  set @strSpids1 = strSpids;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
  start transaction;
 
  prepare stmt from 'update alerts set flag = ? where op_id in (?) and spid in (?) and inserted_on = curdate() and flag is null limit ?';
  execute stmt using @nFlag1,@strOpid1,@strSpids1,@nLimit1;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
  deallocate prepare stmt;
  commit;
  prepare stmt from 'select * from alerts where flag = ?';
  execute stmt using @nFlag1;
  deallocate prepare stmt;
     END$$

DELIMITER ;


Step -3  Calling Stored Procdeure

   String sqlQuery ="{call dasari_procedure(?,?,?,?)}";
   CallableStatment cstmt=con.prepareCall(sqlQuery);
   cstmt.setString(1,1);
   cstmt.setString(1,1);
   cstmt.setInt(3,100);
   cstmt.setInt(4,12121212);
   cstmt.executeUpdate();  // flag will be update instead of null replace with 12121212 based on where flag is     null in stored procedure.

 // Retrieval of Resultset in same Stored Procedure.. after updating the records

   ResultSet rs=cstmt.getResultSet();

 while(rs.next())
{
   String name=rs.getString("column_name');
  -------------------------------------------  etc,,,,,,,,,

}



Happy Learning !!!

Cheers
Dasari








How to Create .bat file in java







@Title OBDMonitorDishnet [ %date% %time% ]

@set path=%path%;C:\Program Files\Java\jdk1.6.0_19;

@set classpath=%classpath%;C:\filename.jar;D:\filename.jar;E:\filename.jar;F:\filename.jar;

java -Duser.timezone="Asia/Calcutta" -Xmx1024M  [Your Class Name ] [C://filename.properties]

pause


#Step-1 : Provide Title as your wish eg: your application name. you can provide date and time also .
#Step-2 : set java path
#Step-3 : Here we will Store all our libaries under classpath
#Step-4 : This is final Step repalce [Your Class Name eg: DasariClass ] with your Application Class Name
#Step-5 : Save this Text as filename.bat and run ...enjoy
#Note: [c://filename.properties] u can pass your properties at command line level.














Monday, July 11, 2011

File Upload Workaround Solution in Java Web Application :

1) Example program for How to upload .csv file or .txt or .jpeg......etc.......




Here one thing we need to observee carefully , when we want to upload a specific file in web application.


 we should know about compatibility of browsers.


 1 ) IE 7 and IE 8 :
 Note : if we upload a file in web using below html tag
 syn : <input type="file" name="fileupload" accept=""/>


for example : the file location is at D:/Folder1/Folder2/filename.csv


so when u upload a file from this location , IE browser will take the path as : D:\Folder1\Folder2\filename.csv


observe carefully , if we test with the file upload functionality in  below  browsers


  2) firefox , opera , chrome , Netscape


  here , these browsers will take the path as     :  filename.csv


 these above browsers have not take  complete path when we upload a file from specific directory.




conclusion :
IE : will take full path eg: D:\folder1\folder2\filename.csv
firefox,chrome..etc : the take only specific file name eg : filename.csv


so,  if u are completely following IE compatibility web browser , i suggest everyone please


use java replace() method , for replacing the backword (\) slash with forward slash (/). otherwise java will not accept backword (\) charcter for reading the file .....


eg:       String filename="D:\filename.csv ": we cant read this file in java.


            correct way :      filename=filename.replace("\\","/");


          then the path will convert in to this format : D:/filename.csv , so we can easily read the file ..


for other browsers except IE,
                     we can  confiure the path in static way .


for example :       String dir="D:/";


                      path : "filename.csv";


                 String filename=dir+path;




Hope u may get some idea, how to make workaround solution for this..


it would  be very grateful for your feedback, if u find any errors........


u can test sample  example from below code snippet :





Step 1:  please paste this code in html or jsp ..
<form action="servletClassName" method=post/ enctype="multipart/form-data>
 <input type="hidden" name="_paramArgument"  vaule="fileupload"/>
 <input type="submit" value="upload" />  
 <input type="file"  name="_PARAM_FILEUPLOAD" id="sno" size="20"  accept="text/csv" />
</form>
Step 2: 
Business logic: Here u can use servlet or jsp ?copy the below code either in servlet or jsp.
  public class UploadServlet extends HttpServlet
   { 
     String param=request.gerParameter("_paramArgument");
        dospost(){  //dopost()method of servlet 
            try{
                   if(param.equals("fileupload"))
{
String data=request.getParameter("_PARAM_FILEUPLOAD");  
 data = data.replace("\\", "/");
if (data.endsWith(".csv") && data.contains("/")) {
File f = new File(data);
                      
    boolean path = f.exists();  // if path exits then true otherwise false
                        if(path)
                       { 
   //your Database logic to insert the file.csv in to database.....upload success 
  uploadCSVFile(data);  // this method will insert the csv data in to database....
                        }
else {invalid upload}
    }
                                            
            }
catch(Exception e)
{}
}}    


step 3:
       
    DAO Logic :
      public int uploadCSVFile(String path) {
      
      int status = 0;
    
         try {
            String query = "LOAD DATA INFILE '" + path + "' IGNORE INTO    TABLE tbl_voicetocrbt_content FIELDS  TERMINATED BY   
          ',' LINES TERMINATED BY '\n'";
            PreparedStatement pst = getJDBCConnection().prepareStatement(query);
           status= pst.executeUpdate();
            
          } catch (Exception e) {
            e.printStackTrace();
          }
         return status;
        }







 :

Cheers and Fun
Dasari...

Tuesday, June 28, 2011

Hello India !!!

Hi Friends !!  This is Dasari Vaass , Greetings to you all who are reading this blog.

   I would like to share my Software Development Experience , hope everyone like this Code Snippets in which
  i am gonna to post good stuff.


  it would be very grateful for your feedback , if you find any errors.


   Cheers and Rock
     Dasari