Friday, 26 February 2016


DB Handler


package com.sollet.buzz.database;


import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.sollet.buzz.main.R;

public class DBHelper extends SQLiteOpenHelper {
/*
* 7 - 2.8.5
* 8 - 2.8.6
*
* */
private static String DATABASE_NAME ="SOLLETDB";
private static int DATABASE_VERSION = 8; // by shyam date:7/7/2015 for release 2.8.6
private Context mContext;
private String LOG_TAG = "DATABASE_LOG";
public static DBHelper INSTANCE = null;

private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}

/**
* Get Instance of DBHelper
*
* @param context
* @return
*/
public synchronized static DBHelper getInstanceDbHelper(Context context) {

if (INSTANCE == null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

String[] sql = mContext.getString(R.string.Database_onCreate).split("\n");
db.beginTransaction();
try {
execMultipleSQL(db, sql);
// System.out.println("Db Tables Created..");
db.setTransactionSuccessful();
} catch (SQLException e) {
// Log.e("Error creating tables and debug data", e.toString());
// Log.v(LOG_TAG,e.toString());
throw e;
} finally {
db.endTransaction();
}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

if(oldVersion<2) { db.beginTransaction(); try{ String sql = mContext.getString(R.string.Database_onUpgrade); db.execSQL(sql); // System.out.println("Db Tables Updated.."); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } }if(oldVersion<3){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v3).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<4){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v4).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<5){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v5).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<6){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v6).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<7){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v7).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<8){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v8).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } } /** * Execute all of the SQL statements in the String[] array * * @param db * The database on which to execute the statements * @param sql * An array of SQL statements to execute */ private void execMultipleSQL(SQLiteDatabase db, String[] sql) { for (String s : sql) if (s.trim().length() > 0){
// Log.v(LOG_TAG, s);
db.execSQL(s);
}
}

/**
* Execute the SQL statements to insert data
*
* @param sql
* An SQL statements to execute
*/
public void insert(String sql) {
getWritableDatabase().execSQL(sql);

// Log.v(LOG_TAG , sql);
}

/**
* Execute the SQL statements to update data
*
* @param sql
* An SQL statements to execute
*/
public void update(String sql) {
getWritableDatabase().execSQL(sql);
// Log.v(LOG_TAG, sql);
}

/**
* Execute the SQL statements to delete data
*
* @param sql
* An SQL statements to execute
*/
public void delete(String sql) {
getWritableDatabase().execSQL(sql);
// Log.v(LOG_TAG, sql);
}

}


Wednesday, 2 April 2014

Improve Performance of PhoneGap Application







PhoneGap when combined with jQuery Mobile sometimes exhibits sluggish performance. Overriding some css from Jquery can give you better performance in terms of page loading, page transitions etc. It may not give a 100% improvement but it will definitely improve your app by a great extent.


Add the following code in your css:


/* disable shadows for better android performance */
.ui-body-a,
.ui-bar-a,
.ui-btn-up-a,
.ui-btn-hover-a,
.ui-btn-down-a,

.ui-body-b,
.ui-bar-b,
.ui-btn-up-b,
.ui-btn-hover-b,
.ui-btn-down-b,

.ui-body-c,
.ui-bar-c,
.ui-btn-up-c,
.ui-btn-hover-c,
.ui-btn-down-c,

.ui-body-d,
.ui-bar-d,
.ui-btn-up-d,
.ui-btn-hover-d,
.ui-btn-down-d,

.ui-body-e,
.ui-bar-e,
.ui-btn-up-e,
.ui-btn-hover-e,
.ui-btn-down-e,

.ui-shadow-inset,
.ui-icon-shadow,
.ui-focus,
.ui-overlay-shadow,
.ui-shadow,
.ui-btn-active,
* {
text-shadow: none !important;
box-shadow: none !important;
-moz-box-shadow: none !important;
-webkit-box-shadow: none !important;
}


And add the following code in your onDeviceReady event function:


function onDeviceReady() {


// for performance boosting
$.mobile.autoInitializePage = false;
$.mobile.defaultPageTransition = 'none';
$.mobile.touchOverflowEnabled = false;
$.mobile.defaultDialogTransition = 'none';

}


Clear Application cache in android

There are two ways you can remove your application cache which piles up during the active state of application and free your device memory from running low on space.

1)One way you can delete cache on app exit using the following code.

@Override
    public void onDestroy() {
        super.onDestroy();

        try {
            trimCache(this);
           // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void trimCache(Context context) {
        try {
           File dir = context.getCacheDir();
           if (dir != null && dir.isDirectory()) {
              deleteDir(dir);
           }
        } catch (Exception e) {
           // TODO: handle exception
        }
     }

     public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
           String[] children = dir.list();
           for (int i = 0; i < children.length; i++) {
              boolean success = deleteDir(new File(dir, children[i]));
              if (!success) {
                 return false;
              }
           }
        }

        // The directory is now empty so delete it
        return dir.delete();
     }


2)Another way to manage cache is to listen for the ACTION_DEVICE_STORAGE_LOW broadcast through a &ltreceiver>.


Tuesday, 12 March 2013

Triple Des Encryption In J2me


Enter your pages Title here




TripleDes.java



import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;

/**
 *
 * @author Pradeep
 */
public class TripleDes {

    PaddedBufferedBlockCipher encryptCipher;
    PaddedBufferedBlockCipher decryptCipher;
    // Buffers used to transport the bytes from one stream to another
    byte[] key = null;              //secret key for secure encryption and decryption
 
     public TripleDes() {
     
        key = "MYTESTTRIPLEDESENCRYPTO".getBytes();
        // calling the InitCiphers() method to initilize the PaddedBufferedBlockCipher
        InitCiphers();
    }

 
    /**
     *
     * @param keyBytes      Key value
     */
    public TripleDes(byte[] keyBytes) {
        // TripleDES Key
        key = new byte[keyBytes.length];
        System.arraycopy(keyBytes, 0, key, 0, keyBytes.length);
        // calling the InitCiphers() method to initilize the PaddedBufferedBlockCipher
        InitCiphers();
    }
   /**
     *
     * Encrypt
     *
     * This method encrypt the plain text and returns the encrypted data in base64
     *
     * @param plainText
     * @return String
     * @throws Exception
     */
    public String encrypt(String plainText) throws Exception {

        byte[] input = plainText.getBytes();
        encryptCipher.init(true, new KeyParameter(key));
        byte[] cipherText = new byte[encryptCipher.getOutputSize(input.length)];
        int outputLen = encryptCipher.processBytes(input, 0, input.length, cipherText, 0);

        try {
            encryptCipher.doFinal(cipherText, outputLen);
        } catch (CryptoException ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } catch (Exception ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } finally {
           ResetCiphers();
        }
        return new String(Base64Coder.encode(cipherText)).trim();
    }
 
    /**
     * decrypt
     * Decrypt the encrypted string
     * @param enctryptedText
     * @return
     * @throws Exception
     */
    public String decrypt(String enctryptedText) throws Exception {

        byte[] input = Base64Coder.decode(enctryptedText);
        decryptCipher.init(false, new KeyParameter(key));
        byte[] cipherText = new byte[decryptCipher.getOutputSize(input.length)];
        int outputLen = decryptCipher.processBytes(input, 0, input.length, cipherText, 0);
        try {
            decryptCipher.doFinal(cipherText, outputLen);
        } catch (CryptoException ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } catch (Exception ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } finally {
           ResetCiphers();
        }
        return bytes2String(cipherText);
    }
 
    /**
     * Initilize the ciphers for encryption and decryption
     *
     */
    private void InitCiphers() {
        //Creates encryptCipher Object  DESEDE
        encryptCipher = new PaddedBufferedBlockCipher(new DESedeEngine());
     
//        encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));  //  DESEDE CBC MODE CIPHER
        //set Key parameters and Encrypt mode
        encryptCipher.init(true, new KeyParameter(key));
        //Creates decryptCipher Object
        decryptCipher = new PaddedBufferedBlockCipher(new DESedeEngine());
     
//        decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));  //  DESEDE CBC MODE CIPHER
        //set Key parameters and Encrypt mode
        decryptCipher.init(false, new KeyParameter(key));
    }
 
    /**
     * Reset the cipher Objects
     */
    private void ResetCiphers() {
        if (encryptCipher != null) {
            encryptCipher.reset();
        }
        if (decryptCipher != null) {
            decryptCipher.reset();
        }
    }
 
    /**
     * bytes2String
     * convert byte array to string
     * @param bytes
     * @return
     */
    private static String bytes2String(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append((char) bytes[i]);
        }
        return stringBuffer.toString();
    }
}





Note:Triple Des (DESede) Encryption in J2me


Source code Download Link

Tuesday, 27 November 2012

Select Image from gallery and display in lwuit Form

HelloMidlet.java
-----------------------
package main;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */

import com.sun.lwuit.*;
import javax.microedition.midlet.MIDlet;

public class HelloMidlet extends MIDlet {

    public static int dwidth;
    public static int dheight;
    public static javax.microedition.lcdui.Display lcduiDisplay;
    public static HelloMidlet midlet;
   
    public void startApp() {
        try {
            midlet = this;
            Display.init(this);
            lcduiDisplay = javax.microedition.lcdui.Display.getDisplay(this);
         
            dwidth = Display.getInstance().getDisplayWidth();
            dheight = Display.getInstance().getDisplayHeight();

            } catch (Exception ex) {
        }
        ImageClass imgform = new ImageClass();
        imgform.showLcduiImageForm(null);
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
    }
}


ImageClass.java
-------------------
package main;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */

public class ImageClass {
    public static Form imgForm;

    public void showLcduiImageForm(Object img) {
        try {
//            Display.init(HelloMidlet.midlet);
            imgForm = new Form("Hello World");

            Container middleContainer = new Container();
            middleContainer.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
            middleContainer.setUIID("middleContainer");
            middleContainer.setScrollableY(true);
            middleContainer.getStyle().setBgColor(0XDEDBDE);
            //

            Label empty2 = new Label("");
            empty2.setFocusable(true);
            middleContainer.addComponent(empty2);

            Button browse = new Button("browse");
            browse.setUIID("actionButton");
            browse.setHeight(25);
            browse.setAlignment(Button.CENTER);
            browse.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    ImgBrowser browser = new ImgBrowser();
                    browser.browseForImage(HelloMidlet.midlet);
                }
            });

            Container cp_details = new Container(new BoxLayout(BoxLayout.X_AXIS));
            Image img1 = null;
            try {
                img1 = Image.createImage(img);               
                Label l1 = new Label(img1.scaled(30, 30));
                cp_details.addComponent(l1);
            } catch (Exception ex) {
              //  Dialog.show("Error", "Error creating Image from lcdui", "OK", null);
            }

            cp_details.addComponent(browse);
            middleContainer.addComponent(cp_details);

            imgForm.addComponent(middleContainer);
            imgForm.show();
        } catch (Exception ex) {
            Dialog.show("Exception", "" + ex.getMessage(), "OK", null);
        }

    }
}


ImgBrowser.java
--------------------
package main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */

public class ImgBrowser implements CommandListener {

    private Image dirIcon;
    private Image fileIcon;
    private Image[] iconList;
    private String currDirName;
    /*
     * separator string as defined by FC specification
     */
    private static final String SEP_STR = "/";

    /*
     * separator character as defined by FC specification
     */
    private static final char SEP = '/';
    /*
     * special string that denotes upper directory accessible by this browser.
     * this virtual directory contains all roots.
     */
    private static final String MEGA_ROOT = "/";
    /*
     * special string denotes upper directory
     */
    private static final String UP_DIRECTORY = "..";
    private Command view = new Command("Select", Command.ITEM, 1);
    private Command cancel = new Command("Cancel", Command.ITEM, 2);
    private Command back = new Command("Back", Command.BACK, 2);
    MIDlet midletObj;

    public ImgBrowser() {
        currDirName = MEGA_ROOT;

        try {
            dirIcon = Image.createImage("/dir.png");
        } catch (IOException e) {
            dirIcon = null;
        }

        try {
            fileIcon = Image.createImage("/file.png");
        } catch (IOException e) {
            fileIcon = null;
        }

        iconList = new Image[]{fileIcon, dirIcon};
    }

    public void browseForImage(MIDlet midlet) {
        midletObj = midlet;
        try {
            showCurrDir();
        } catch (SecurityException e) {
            Alert alert =
                    new Alert("Error", "You are not authorized to access the restricted API", null,
                    AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);

            Form form = new Form("Cannot access FileConnection");
            form.append(new StringItem(null,
                    "You cannot run this MIDlet with the current permissions. "
                    + "Sign the MIDlet suite, or run it in a different security domain"));
//            form.addCommand(exit);
//            form.setCommandListener(this);
            Display.getDisplay(midletObj).setCurrent(alert, form);
        } catch (Exception e) {
        }
    }

    /**
     * Show file list in the current directory .
     */
    void showCurrDir() {
        Enumeration e;
        FileConnection currDir = null;
        List browser;

        try {
            if (MEGA_ROOT.equals(currDirName)) {
                e = FileSystemRegistry.listRoots();
                browser = new List(currDirName, List.IMPLICIT);
            } else {
                currDir = (FileConnection) Connector.open("file://localhost/" + currDirName);
                e = currDir.list();
                browser = new List(currDirName, List.IMPLICIT);
                // not root - draw UP_DIRECTORY
                browser.append(UP_DIRECTORY, dirIcon);
            }

            while (e.hasMoreElements()) {
                String fileName = (String) e.nextElement();

                if (fileName.charAt(fileName.length() - 1) == SEP) {
                    // This is directory
                    browser.append(fileName, dirIcon);
                } else {
                    // this is regular file
                    browser.append(fileName, fileIcon);
                }
            }

            browser.setSelectCommand(view);
            browser.addCommand(cancel);

            //Do not allow creating files/directories beside root
            if (!MEGA_ROOT.equals(currDirName)) {
//                browser.addCommand(prop);
//                browser.addCommand(creat);
//                browser.addCommand(delete);
            }

//            browser.addCommand(exit);
//
            browser.setCommandListener(this);

            if (currDir != null) {
                currDir.close();
            }

            Display.getDisplay(midletObj).setCurrent(browser);
        } catch (IOException ioe) {
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == view) {
            List curr = (List) d;
            final String currFile = curr.getString(curr.getSelectedIndex());
            new Thread(new Runnable() {

                public void run() {
                    if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)) {
                        traverseDirectory(currFile);
                    } else {
                        // Show file contents
                        showFile(currFile);
                    }
                }
            }).start();
        } else if (c == back) {
            showCurrDir();
        }
        else if (c == cancel) {
            com.sun.lwuit.Display.init(midletObj);
            ImageClass.imgForm.show();
        }
    }

    void traverseDirectory(String fileName) {
        /*
         * In case of directory just change the current directory and show it
         */
        if (currDirName.equals(MEGA_ROOT)) {
            if (fileName.equals(UP_DIRECTORY)) {
                // can not go up from MEGA_ROOT
                return;
            }

            currDirName = fileName;
        } else if (fileName.equals(UP_DIRECTORY)) {
            // Go up one directory
            int i = currDirName.lastIndexOf(SEP, currDirName.length() - 2);

            if (i != -1) {
                currDirName = currDirName.substring(0, i + 1);
            } else {
                currDirName = MEGA_ROOT;
            }
        } else {
            currDirName = currDirName + fileName;
        }

        showCurrDir();
    }

    void showFile(String fileName) {
//        Form mForm = new Form("Image");
        FileConnection fc = null;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
            int length = (int) fc.fileSize();//possible loss of precision may throw error
            byte[] data = null;
            if (length != -1) {
                data = new byte[length];
                in = new DataInputStream(fc.openInputStream());
                in.readFully(data);
            } else {
                int chunkSize = 512;
                int index = 0;
                int readLength = 0;
                in = new DataInputStream(fc.openInputStream());
                data = new byte[chunkSize];
                do {
                    if (data.length < index + chunkSize) {
                        byte[] newData = new byte[index + chunkSize];
                        System.arraycopy(data, 0, newData, 0, data.length);
                        data = newData;
                    }
                    readLength = in.read(data, index, chunkSize);
                    index += readLength;
                } while (readLength == chunkSize);
                length = index;
            }
            Image image = Image.createImage(data, 0, length);
            ImageItem imageItem = new ImageItem(null, image, 0, null);
            com.sun.lwuit.Display.init(midletObj);
            ImageClass imgForm=new ImageClass();
            imgForm.showLcduiImageForm(image);
//            mForm.append(imageItem);
//            mForm.setTitle("Done.");
//            mForm.addCommand(select);
//            mForm.addCommand(back);
//            mForm.setCommandListener(this);

            //fc = (FileConnection) Connector.open("file:///root1/x.PNG");
            if (!fc.exists()) {
                try {
                    fc.create();
                } catch (Exception ce) {
                    System.out.print("Create Error: " + ce);
                }
            }
            out = new DataOutputStream(fc.openOutputStream());
            out.write(data);
        } catch (IOException ioe) {
            StringItem stringItem = new StringItem(null, ioe.toString());
//            mForm.append(stringItem);
//            mForm.addCommand(back);
//            mForm.setCommandListener(this);
//            mForm.setTitle("Done.");
            com.sun.lwuit.Display.init(midletObj);
            ImageClass.imgForm.show();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (fc != null) {
                    fc.close();
                }
            } catch (IOException ioe) {
            }
        }
//        StringItem stringItem = new StringItem(null, "\nfile://localhost/" + currDirName + fileName);
//        mForm.append(stringItem);
//        Display.getDisplay(midletObj).setCurrent(mForm);
    }
}


icons:
-----------
file.png


dir.png




Next and Prev Date Selection in J2ME


public static String getPrevNextDay(boolean nextDay, String selectedDate) {
long dayMillies = 86400000; // no. of milliseconds per 1 day

// String to Date Convertion; selectedDate=2012-11-27  // YYYY-MM-DD
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(selectedDate.substring(8, 10)));
c1.set(Calendar.MONTH, Integer.parseInt(selectedDate.substring(5, 7)) - 1);
c1.set(Calendar.YEAR, Integer.parseInt(selectedDate.substring(0, 4)));
// // System.out.println("SSSS: " + c1.getTime());

Date d = c1.getTime();

if (nextDay) {
// next day
d.setTime(d.getTime() + dayMillies);
} else {
// previous day
d.setTime(d.getTime() - dayMillies);
}

Calendar c = Calendar.getInstance();
c.setTime(d);

int Curr_day = c.get(Calendar.DAY_OF_MONTH);
int Curr_month = (c.get(Calendar.MONTH) + 1);
int Curr_year = c.get(Calendar.YEAR);
String day = "" + Curr_day;
String Month = "" + Curr_month;
String Year = "" + Curr_year;

        if (Curr_day < 10) {
            day = "0" + Curr_day;
        }
        if (Curr_month < 10) {
            Month = "0" + Curr_month;
        }

//        String time = day + "-" + Month + "-" + Year;
        String time = Year + "-" + Month + "-" + day;
        // System.out.println("Next date:" + time);
        return time;
    }

Saturday, 14 July 2012

Schedule a Task(Upload Excel Data To Database) in a Specified Time Period



Schedule a Task(Upload Excel Data To Database) in a Specified Time Period




Get the source code form this path DOwnload Code

CallSchduler.java

//Main Class

package Scheduler;


import java.io.*;
import java.util.*;

public class CallSchduler {

UpdateSchduler upObj = null;

public void stopScheduler() {
upObj.cancelSchedule();
}

public static void main(String args[]) {
//        System.out.println("Scheduler is called by main method");
try {
File propertyFile = new File("D:\\Demo File\\Resources.properties");
if (propertyFile.exists()) {
Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream(propertyFile);
properties.load(fileInputStream);
int minutes = Integer.parseInt(properties.getProperty("Minutes"));
String uploadFilePath = properties.getProperty("myExcelPath").toString();
String failedRecordsPath = properties.getProperty("failedFiles").toString();
UpdateSchduler upObj = new UpdateSchduler(minutes);
upObj.updateFile(uploadFilePath, failedRecordsPath);
} else {
System.out.println("File not found!");
}

} catch (Exception ex) {
System.out.println("in Exception: " + ex.getMessage());
}
}
}





UpdateSchduler.java


package Scheduler;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

public class UpdateSchduler {

private final Timer timer = new Timer();
private final int minutes;
private String uploadFilePath = "";
private String FailedRecordsPath = "";

public UpdateSchduler(int minutes) {
this.minutes = minutes;
}

public void start() {
timer.schedule(new TimerTask() {

public void run() {
fileSelection(uploadFilePath, FailedRecordsPath);
}
}, 0, minutes * 60 * 1000);
}

public void cancelSchedule() {
timer.cancel();
}

public void updateFile(String uploadFilePath, String FailedRecordsPath) {
this.uploadFilePath = uploadFilePath;
this.FailedRecordsPath = FailedRecordsPath;
start();
}

public void stopUpdating() {
cancelSchedule();
}

public void fileSelection(String uploadRecordPath, String failedRecordsPath) {
System.out.println("Upload File Path:" + uploadRecordPath);
System.out.println("Failed Record File Path:" + failedRecordsPath);
String filesInTheUplaodPath = null;
File uplaodFile = new File(uploadRecordPath);
if (uplaodFile.exists()) {
if (uplaodFile.listFiles().length != 0) {
File[] listOfFiles = uplaodFile.listFiles();

System.out.println("No. Files In the UPload Record path:" + listOfFiles.length);
for (int i = 0; i < listOfFiles.length; i++) {

if (listOfFiles[i].isFile()) {
filesInTheUplaodPath = listOfFiles[i].getName();
//System.out.println("the files are " + files);
JavaSheet readObj = new JavaSheet();
readObj.javaSheet(uploadRecordPath + filesInTheUplaodPath, failedRecordsPath + filesInTheUplaodPath);
}
}

} else {
System.out.println("No files Found");
}
} else {
System.out.println("File Path Not Found");
}
}
}




JavaSheet .java



package Scheduler;

import java.sql.Statement;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
*
* @author Sravan
*/
public class JavaSheet {

StringBuffer sb = new StringBuffer();
int count = 0;
String EmpName = "";
String Dept = "";
String mobileNO = "";
String file_name = "";
String extension = "";
InputStream input = null;
Connection con = null;
FileItemFactory factory = new DiskFileItemFactory();
// System.out.println("1");
ServletFileUpload upload = new ServletFileUpload(factory);
//System.out.println("2");
List items = null;
CallableStatement insertQuery;
DataInputStream in;
private boolean isFileWrite = false;
private FileInputStream fis;
private File inputWorkbook;

public void javaSheet(String file_name1, String failedFIle) {

this.file_name = file_name1;

sb.append("Employee Name" + ",");
sb.append("Department" + ",");
sb.append("MobileNO" + ",");
sb.append("Reason" + ",");
sb.append("\n");

extension = file_name.substring(file_name.indexOf("."), file_name.length());
System.out.println("" + extension);
try {

if (extension.equalsIgnoreCase(".xls") || extension.equalsIgnoreCase(".xlsx")) {
inputWorkbook = new File(file_name);
fis = new FileInputStream(inputWorkbook);
Workbook w;
ResultSet rs = null;
w = Workbook.getWorkbook(fis);
Sheet sheet = w.getSheet(0);
String reason[] = new String[sheet.getRows() + 1];
String rowValues[] = new String[sheet.getColumns()];
System.out.println("no of rows :" + sheet.getRows());
if (sheet.getRows() > 1) {
for (int row = 1; row < sheet.getRows(); row++) {
for (int col = 0; col < sheet.getColumns(); col++) {
Cell cell = sheet.getCell(col, row);

rowValues[col] = cell.getContents();

}


String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String connectionURL = "jdbc:sqlserver://Ip:portNo;databaseName=Dbname;user=sa;password=xyz";



Class.forName(driver);
con = DriverManager.getConnection(connectionURL);
reason[row] = "";

EmpName = rowValues[0];
Dept = rowValues[1];
mobileNO = rowValues[2];


if (EmpName == null || EmpName.trim().equals("")) {
reason[row] = reason[row] + "Emp Name is Null";
}


if (Dept == null || Dept.trim().equals("")) {
reason[row] = reason[row] + "Department Value is Null";
}

if (mobileNO == null || mobileNO.trim().equals("")) {

reason[row] = reason[row] + "Mobile No is Null";

}

if (reason[row] == null) {

String insertQuery = "insert into EMPTable (EMP_Name ,EMP_Dept ,EMP_MobileNO) values ('" + EmpName + "','" + Dept + "','" + mobileNO + "')";
System.out.println(insertQuery);
Statement stmt = con.createStatement();
int res = stmt.executeUpdate(insertQuery);
stmt.close();
if (res == 0) {
reason[row] = "Failed When Inserting";
} else {
count++;
System.out.println("rows inserted:" + count);
}



} else {
System.out.println(" In Fail records");
//
//                            sb.append("Employee Name" + ",");
//                            sb.append("Department" + ",");
//                            sb.append("MobileNO" + ",");
//                            sb.append("Reason" + ",");
//                            sb.append("\n");

//END

isFileWrite = true;
if (EmpName == null || EmpName.equals("")) {
EmpName = "  ";
}
if (Dept == null || Dept.equals("")) {
Dept = "  ";
}
if (mobileNO == null || mobileNO.equals("")) {
mobileNO = "  ";
}



sb.append(EmpName + ",");
sb.append(Dept + ",");
sb.append(mobileNO + ",");
sb.append(reason[row] + ",");
sb.append("\n");
}


System.out.println("ZZZZZZZZZ" + isFileWrite);
System.out.println("" + sb.length());
System.out.println("" + sb);
if (isFileWrite || sb.length() != 0) {
new FailedRecords().getFialedRecords(failedFIle, sb.toString());
}

}
System.out.println("END");
} else {
System.out.println(" Empty XLS File");
}
} else {
System.out.println(" Invalid XLS File");
}

} catch (Exception e) {

System.out.println("Pls Select The Given format of xl file" + e.getMessage());
e.printStackTrace();

} finally {

try {
if (insertQuery != null) {
insertQuery.close();
}
if (con != null) {
con.close();
}
if (fis != null) {
fis.close();
inputWorkbook.delete();
}

} catch (Exception e) {
System.out.println("EXCEPTION IN CLOSING CONNECTION:" + e);
}
}
System.out.println("END");
}
}




FailedRecords.java




package Scheduler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;

/**
*
* @author Sravan
*/
public class FailedRecords {

public void getFialedRecords(String failedRecordsFile, String FailedRecords) {
System.out.println("Inisde Fialed Records");
String file_name = failedRecordsFile;

File file = new File(file_name);
System.out.println("Filename::::" + file_name);
String buffer = FailedRecords;
String date = "";
String filename = "";
SimpleDateFormat df1 = new SimpleDateFormat("dd-MMM-yyyy-kk.mm.ss");
date = df1.format(new java.util.Date());


try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(buffer);
out.close();

} catch (Exception e) {
System.out.println("Ex:" + e);
}
}
}