Saturday, September 22, 2012

Dependable drop downs in Struts 2 using database


 JSP PAGE IS :-


<%@ include file="../others/includes.jsp"%>
<script type="text/javascript">
function populateCountries(){
    var selectedRegion = $('#register_region').val();
    $("#register_country").empty().append('<option value="0">Select your country</option');
    $("#register_state").empty().append('<option value="0">Select your state</option');
    $("#register_city").empty().append('<option value="0">Select your city</option');
    $.ajax({
        url: "../views/getCountries",
        type: "POST",
        async: true,
        data: {regionId: selectedRegion},
        cache: false,
        dataType: "json",
        success: function(result){
            if (result.length == 0){
                $('#register_country').append('<option value="0">No data found</option>');
            }
            else{
                for (var key in result) {
                    $('#register_country').append('<option value="'+result[key].countryId+'">'+result[key].countryName+'</option>');
                 }
            }
        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("An error occured: " + thrownError  +" "+ajaxOptions+" "+xhr.status + " " + xhr.statusText);
        }
    });  
}
function populateStates(){
    var selectedCountry = $('#register_country').val();
    $("#register_state").empty().append('<option value="0">Select your state</option');
    $("#register_city").empty().append('<option value="0">Select your city</option');
    $.ajax({
        url: "../views/getStates",
        type: "POST",
        async: true,
        data: {countryId: selectedCountry},
        cache: false,
        dataType: "json",
        success: function(result){
            if (result.length == 0){
                $('#register_state').append('<option value="0">No data found</option>');
            }
            else{
                for (var key in result) {
                    $('#register_state').append('<option value="'+result[key].stateId+'">'+result[key].stateName+'</option>');
                 }
            }
        },
        error: function(xhr){
            alert("An error occured: " + xhr.status + " " + xhr.statusText);
        }
    });  
}

function populateCities(){
    var selectedState = $('#register_state').val();
    $("#register_city").empty().append('<option value="0">Select your city</option');
    $.ajax({
        url: "../views/getCities",
        type: "POST",
        async: true,
        data: {stateId: selectedState},
        cache: false,
        dataType: "json",
        success: function(result){
            if (result.length == 0){
                $('#register_city').append('<option value="0">No data found</option>');
            }
            else{
                for (var key in result) {
                    $('#register_city').append('<option value="'+result[key].cityId+'">'+result[key].cityName+'</option>');
                 }
            }
        },
        error: function(xhr){
            alert("An error occured: " + xhr.status + " " + xhr.statusText);
        }
    });      
}
</script>
<body id="main" onload="document.formname.reset();">
<s:form action="getRegions" name="formname">
<s:select cssStyle="WIDTH:300px"  list="region" listKey="regionId" listValue="regionName" label="Select your region" headerKey="0" headerValue="Select your region" name="register_region" id="register_region" onchange="populateCountries();"></s:select>
<s:select cssStyle="WIDTH:300px" list="country" listKey="countryId" listValue="countryName" label="Select your country" headerKey="0" headerValue="Select your country" name="register_country" id="register_country" onchange="populateStates();" ></s:select>
<s:select cssStyle="WIDTH:300px" list="state" listKey="stateId" listValue="stateName" label="Select your state" headerKey="0" headerValue="Select your state" name="register_state" id="register_state" onchange="populateCities();"></s:select>
<s:select cssStyle="WIDTH:300px" list="city" listKey="cityId" listValue="cityName" label="Select your city" headerKey="0" headerValue="Select your city" name="register_city" id="register_city" onchange=""></s:select>

</s:form>
</body>


ACTION CLASS IS :-

package com.aih.projects.actions.sd;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import net.sf.json.JSONArray;

import com.aih.projects.beans.City;
import com.aih.projects.beans.Country;
import com.aih.projects.beans.Region;
import com.aih.projects.beans.State;
import com.aih.projects.beans.sd.Food;
import com.aih.projects.commons.sd.Constants;
import com.aih.projects.commons.sd.Parent;
import com.aih.projects.dao.sd.DBInteractionForFood;
import com.aih.projects.dao.sd.DBInteractionForMember;
import com.aih.projects.dao.sd.DBInteractionForWorldLocations;
import com.aih.projects.utility.SendEmail;
import com.aih.projects.utility.UtilityFunctions;

public class DatabaseAction extends Parent implements SessionAware{   
    private static final long serialVersionUID = 1L;
    private JSONArray jArray;
    private String dbHitCounter;
    private String noOfRecords;
    private String email;
    private String password;
    private String zip;
    private InputStream inputStream;
    private Map<String, Object> session;
    private String text;
    private ArrayList<Region> region;
    private ArrayList<Country> country;
    private ArrayList<State> state;
    private ArrayList<City> city;
    private String regionId;
    private String countryId;
    private String stateId;
    private String cityId;
   
    private JSONArray jArrayRegions;
    private JSONArray jArrayCountries;
    private JSONArray jArrayStates;
    private JSONArray jArrayCities;
   


    public JSONArray getJArrayRegions() {
        return jArrayRegions;
    }

    public void setJArrayRegions(JSONArray arrayRegions) {
        jArrayRegions = arrayRegions;
    }

    public JSONArray getJArrayCountries() {
        return jArrayCountries;
    }

    public void setJArrayCountries(JSONArray arrayCountries) {
        jArrayCountries = arrayCountries;
    }

    public JSONArray getJArrayStates() {
        return jArrayStates;
    }

    public void setJArrayStates(JSONArray arrayStates) {
        jArrayStates = arrayStates;
    }

    public JSONArray getJArrayCities() {
        return jArrayCities;
    }

    public void setJArrayCities(JSONArray arrayCities) {
        jArrayCities = arrayCities;
    }

    public String getCountryId() {
        return countryId;
    }

    public void setCountryId(String countryId) {
        this.countryId = countryId;
    }

    public String getStateId() {
        return stateId;
    }

    public void setStateId(String stateId) {
        this.stateId = stateId;
    }

    public String getCityId() {
        return cityId;
    }

    public void setCityId(String cityId) {
        this.cityId = cityId;
    }

    public String getRegionId() {
        return regionId;
    }

    public void setRegionId(String regionId) {
        this.regionId = regionId;
    }

    public ArrayList<Region> getRegion() {
        return region;
    }

    public void setRegion(ArrayList<Region> region) {
        System.out.println("Here");
        this.region = region;
    }

    public ArrayList<Country> getCountry() {
        return country;
    }

    public void setCountry(ArrayList<Country> country) {
        this.country = country;
    }

    public ArrayList<State> getState() {
        return state;
    }

    public void setState(ArrayList<State> state) {
        this.state = state;
    }

    public ArrayList<City> getCity() {
        return city;
    }

    public void setCity(ArrayList<City> city) {
        this.city = city;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }
   
    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public void setJArray(JSONArray jArray) {
        this.jArray = jArray;
    }

    public JSONArray getJArray() {
        return jArray;
    }
    public String getNoOfRecords() {
        return noOfRecords;
    }

    public void setNoOfRecords(String noOfRecords) {
        this.noOfRecords = noOfRecords;
    }
   
    public String getDbHitCounter() {
        return dbHitCounter;
    }

    public void setDbHitCounter(String dbHitCounter) {
        this.dbHitCounter = dbHitCounter;
    }

    public String populateFoods(){
        ArrayList<Food> foods = null;
        String dbQuery = null;
        try{
            foods = DBInteractionForFood.getAllAvailableFoods(Integer.parseInt(dbHitCounter), Integer.parseInt(noOfRecords));
        }catch (Exception e) {
            e.printStackTrace();
            SendEmail.postMail(new String[]{Constants.errorMail}  , "Error from "+Constants.projectName, "Query is "+dbQuery+"  and Method name is "+Thread.currentThread().getStackTrace()[2].getMethodName()+"\n\n\nError is" +UtilityFunctions.stackTraceToString(e));
        }
        jArray = UtilityFunctions.getListAsJsonArray(foods);
        //System.out.println(jArray);
        return SUCCESS;
    }
   
    public String registerMember(){
        inputStream = DBInteractionForMember.registerMember(email, password, zip);
        return SUCCESS;
    }
   
    public String logIn(){
        inputStream  = DBInteractionForMember.logIn(email, password);
        session.put("anshul", inputStream);
        return SUCCESS;
    }
   
    public String activateMember(){
        inputStream = DBInteractionForMember.activateMember(email);
        return SUCCESS;
    }
   
    public String getRegions(){
        region =  DBInteractionForWorldLocations.getRegions();
        country =  DBInteractionForWorldLocations.getCountries("0");
        state = DBInteractionForWorldLocations.getStates("0");
        city = DBInteractionForWorldLocations.getCities("0");
        jArrayRegions = UtilityFunctions.getListAsJsonArray(region);
        return SUCCESS;
    }
   
    public String getCountries(){
        country =  DBInteractionForWorldLocations.getCountries(regionId);
        jArrayCountries = UtilityFunctions.getListAsJsonArray(country);
        return SUCCESS;
    }
   
    public String getStates(){
        state = DBInteractionForWorldLocations.getStates(countryId);
        jArrayStates = UtilityFunctions.getListAsJsonArray(state);
        return SUCCESS;
    }
   
    public String getCities(){
        city = DBInteractionForWorldLocations.getCities(stateId);
        jArrayCities = UtilityFunctions.getListAsJsonArray(city);
       
        return SUCCESS;
    }
   
    public static void main(String args[]){
        DatabaseAction a = new DatabaseAction();
        System.out.println(a.getRegions());
    }

}


STRUTS.XML is:-

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="test" namespace="/views" extends="struts-default, json-default">
           <action name="getRegions" class="com.aih.projects.actions.sd.DatabaseAction" method="getRegions">
            <result name="SUCCESS">test1.jsp</result>
           </action>
           <action name="getCountries" class="com.aih.projects.actions.sd.DatabaseAction" method="getCountries">
            <result type="json" name= "SUCCESS"><param name="root">jArrayCountries</param></result>
           </action>
           <action name="getStates" class="com.aih.projects.actions.sd.DatabaseAction" method="getStates">
            <result type="json" name= "SUCCESS"><param name="root">jArrayStates</param></result>
           </action>
           <action name="getCities" class="com.aih.projects.actions.sd.DatabaseAction" method="getCities">
            <result type="json" name= "SUCCESS"><param name="root">jArrayCities</param></result>
           </action>
    </package>

</struts>

Tuesday, August 14, 2012

LOG4J

1. Log4j simply inserts a log statement in the application code and manage them externally without going back to its application source code.
2. Programmer's can control the logging message with the help of external configuration file e.g. log4.xml or log4j.properties file.
3. The external properties file can be used to set the log format as well as the level of logging.
4. Three main component of Log4J are :-
        Logger
        Appender
        Layout
5. LOGGER:- It is responsible for capturing the logging information.
   There are few levels of logger:
        DEBUG : Most useful to debug an application.
        INFO  : It provides informational messages.
        WARN  : It provides that application may have harmful events.
        ERROR : It provides that application having error events but that might allow it to continue running.
        FATAL : It denotes the severe error events which lead the application to abort.
        ALL   : It is intended to turn on all logging.
        OFF   : It is intended to turn off all logging.
6. APPENDERS:- It is responsible for publishing the log to a destination. It controls how the logging provides the output.
   There are few list of appenders listed below:
        ConsoleAppender
        DailyRollingFileAppender
        FileAppender
        RollingFileAppender
        WriterAppender
        SMTPAppender
        SocketAppender
        SocketHubAppender
        SyslogAppendersends
        TelnetAppender
7. LAYOUT:- It is responsible for formatting the log output in different layouts. User can control the output format by modifying the Log4J configuration file.
   There are basically three types of Layout:
        HTMLLayout : It formats the output in the HTML table
        PatternLayout : It formats the output in the conversion pattern
        SimpleLayout : It formats the output in a simple manner, it prints the level then place a dash and then the user specified log message.
8. CONFIGURING LOG4J:- Put log4j.properties and log4j.xml in classpath i.e. directly under src folder of the application.
    Log4j looks for log4j.xml file first and then go for log4j.properties hence you must place both the files in your folder. We use log4j.xml since properties file does not provide some advanced configuration options such as Filter, some of ErrorHandlers, and few advanced Appenders.
  


STORED PROCEDURES IN MYSQL

http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx

A stored procedure is a segment of declarative SQL code, which is stored in the database catalog. A stored procedure can be invoked by a program, a trigger or even another stored procedure.

Declarative programming is where you say what you want without having to say how to do it. With procedural programming, you have to specify exact steps to get the result.

ADVANTAGES:-
    Stored procedure increases performance of application. Once created, stored procedure is compiled and stored in the database catalog. It runs faster than uncompiled SQL commands which are sent from application.
    Stored procedure reduces the traffic between application and database server because instead of sending multiple uncompiled lengthy SQL commands statements, the application only has to send the stored procedure's name and get the data back.
    Stored procedure is reusable and transparent to any application which wants to use it. Stored procedure exposes the database interface to all applications so developers don't have to program the functions which are already supported in stored procedure in all external applications.
    Stored procedure is secured. Database administrator can grant the access right to application which wants to access stored procedures in database catalog without granting any permission on the underlying database tables.

SIMPLE STORED PROCEDURE:-
    CREATE PROCEDURE getALL()
    BEGIN
    select * from update_commands;
    END//
    DELIMITER ;

PARAMETERS IN STORED PROCEDURES:-
    In MySQL, a parameter has one of three modes IN, OUT and INOUT.
   
IN :-
    send an input parameter only

    DELIMITER //
    CREATE PROCEDURE getAll(IN commandName varchar(50))
    BEGIN
    select * from update_commands where command_name = commandName;
    END//
    DELIMITER;
   
    call getAll('send_me')
   
OUT:-

    send an input parameter AND get back another output parameter.
   
    DELIMITER //
    CREATE PROCEDURE getAll(IN commandName varchar(50), OUT total int)
    BEGIN
    select count(*) into total from update_commands where command_name like orderStatus ;
    END//
    DELIMITER;

    call getAll(1,@set);
    select @set as total


INOUT:-

    send an input parameter AND get back the same as output parameter after modification.
   
    DELIMITER //
    CREATE PROCEDURE getAll(INOUT a varchar(50))
    BEGIN
    select password into a from login where username = a;
    END//
    DELIMITER ;
   
    set @username = 'a';
    call getAll(@username);
    select @username as passsword
   
DECLARING A VARIABLE:-

    DECLARE variable_name datatype(size) DEFAULT default_value;
    e.g. DECLARE total_sale INT DEFAULT 0

VARIABLE SCOPE:-

    A variable has its own scope. If you declare a variable inside a stored procedure, it will be out of scope when the END of stored procedure reached. If you defined a variable inside block BEGIN/END inside a stored procedure it will be out of scope if the END reached. You can declare two variables or more variables with the same name in different scopes; the variable only is effective in its scope.

    A variable with the ‘@’ at the beginning is session variable. It exists until the session end.
   
CONDITIONAL CONTROL:-

    The IF Statement:-
        IF expression THEN commands
            ELSEIF expression THEN commands
            ELSE commands
        END IF;

    The CASE Statement:-
        CASE case_expression
            WHEN when_expression THEN commands
            WHEN when_expression THEN commands
            ELSE commands
        END CASE;
       
    The WHILE Statement:-
        WHILE expression DO
           Statements
        END WHILE
       
    The REPEAT Statement:-
        REPEAT
            Statements; UNTIL expression
        END REPEAT
   
    The LOOP loop, LEAVE and ITERATE Statment:-
       

Saturday, July 21, 2012

JQuery

JQuery

 $.ajax() function parameters are as below:-

async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions).
contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context Specifies the "this" value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object

Difference between Struts 1 and Struts 2

Struts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces. 

While in Struts 2, an Action class implements an Action interface, along with other interfaces use optional and custom services. Struts 2 provides a base ActionSupport class that implements commonly used interfaces. Although an Action interface is not necessary, any POJO object along with an execute signature can be used as an Struts 2 Action object. 
                                                      

Friday, July 20, 2012

Scroller in JQuery

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="../../scripts/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
var c;
var data=["A","B","C","D","E","F", "G","H","I", "J","K","L", "M","N","O", "P","Q","R", "S","T","U"];
$(document).ready(function(){
      setInterval("asd(c)",1000);
});

function asd(c){
      if(!asd.c)asd.c = 1;
      for (var i = 1; i <= asd.c ; i++){
            for (var j = i ; j > 0 ; j-- ){
                  $("#div"+j).html(data[i-j]);
            }
      }
      asd.c++;
      if (asd.c > data.length){
            asd.c =1;
            $("#div5").html('');
            $("#div4").html('');
            $("#div3").html('');
            $("#div2").html('');
            $("#div1").html('');
      }
}
</script>
</head>
<body>
<input id ="v" value="1" style="display: none;"/>
<table border="1" cellpadding="1" cellspacing="1">
<tr><td height="30px" width="30px"><div id="div5"></div></td></tr>
<tr><td height="30px" width="30px"> <div id="div4"></div></td></tr>
<tr><td height="30px" width="30px"><div id="div3"></div></td></tr>
<tr><td height="30px" width="30px"><div id="div2"></div></td></tr>
<tr><td height="30px" width="30px"><div id="div1"></div></td></tr>
</table>
</body>
</html>

Tuesday, April 10, 2012

JNDI

http://docs.oracle.com/javase/jndi/tutorial/

JNDI
Java Naming and Directory Interface

Naming service It is a mean by which names are associated with objects and objects are found based on their names.The naming system determines the syntax that the name must follow. This syntax is sometimes called the naming system's naming convention.

Bindings
The association of a name with an object is called a binding.

Context
A context is a set of name-to-object bindings. Every context has an associated naming convention. A context provides a lookup (resolution) operation that returns the object and may provide operations such as those for binding names, unbinding names, and listing bound names. A name in one context object can be bound to another context object (called a subcontext) that has the same naming convention.
    For example, a file directory, such as /usr, in the UNIX file system is a context. A file directory named relative to another file directory is a subcontext (some UNIX users refer to this as a subdirectory). That is, in a file directory /usr/bin, the directory bin is a subcontext of usr. In another example, a DNS domain, such as COM, is a context. A DNS domain named relative to another DNS domain is a subcontext. For example, in the DNS domain Sun.COM, the DNS domain Sun is a subcontext of COM.

Naming system
A naming system is a connected set of contexts of the same type (they have the same naming convention) and provides a common set of operations.
For example, a system that implements the DNS is a naming system. A system that communicates using the LDAP is a naming system.

Namespace
A namespace is the set of names in a naming system.

How to use JNDI
To use the JNDI, you must have the JNDI classes and one or more service providers. The Java 2 SDK, v1.3 includes three service providers for the following naming/directory services:
Lightweight Directory Access Protocol (LDAP)
Common Object Request Broker Architecture (CORBA) Common Object Services (COS) name service
Java Remote Method Invocation (RMI) Registry



LDAP

http://docs.oracle.com/javase/jndi/tutorial/ldap/index.html

LDAP
The Lightweight Directory Access Protocol (LDAP) is a network protocol for accessing directories. It is based on the X.500

X.500
The X.500 directory service is a global directory service. Its components cooperate to manage information about objects such as countries, organizations, people, machines, and so on in a worldwide scope. It provides the capability to look up information by name (a white-pages service) and to browse and search for information (a yellow-pages service).

The information is held in a directory information base (DIB). Entries in the DIB are arranged in a tree structure called the directory information tree (DIT). Each entry is a named object and consists of a set of attributes. Each attribute has a defined attribute type and one or more values. The directory schema defines the mandatory and optional attributes for each class of object (called the object class). Each named object may have one or more object classes associated with it.

The X.500 namespace is hierarchical. An entry is unambiguously identified by a distinguished name (DN). A distinguished name is the concatenation of selected attributes from each entry, called the relative distinguished name (RDN), in the tree along a path leading from the root down to the named entry.

Web Server V/S Application Server

http://www.javaworld.com/javaworld/javaqa/2002-08/01-qa-0823-appvswebserver.html

Tomcat, or officially named Apache Tomcat is a light-weight web container used for deploying and running web application based on Java

Web Server handles HTTP requests.It responds with static pages like HTML pages and can use other programs such as JSP,servlets,CGI,ASP etc to generate dynamic response.

Application Sever handles business logic for use by client applications and supports various protocols including HTTP.

Friday, March 30, 2012

Insert google map in application

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
</script>
</head>
<body onload="initialize()">
  <div>
    <input id="address" type="text" value="Sydney, NSW">
    <input type="button" value="Geocode" onclick="codeAddress()">
  </div>
<div id="map_canvas" style="width:400px; min-width:400px; height:400px; min-height:400px; top:30px; border: solid red 3px;">
</div>
</body>
</html>

Google API's

URL to search place using zip code

http://maps.googleapis.com/maps/api/geocode/json?address=17611&sensor=true

Thursday, March 29, 2012

DAO Layer for applications


package com.anshul.projects.drfirst.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import com.anshul.projects.drfirst.commons.Constants;

public class LocalDBConnection implements Constants{
                private static Connection conn = null;
                private static Statement stmt = null;
                private static PreparedStatement pstmt = null;
                private static String url = "";
               
                public static Connection getConnection(String dbName) {
                                try {
                                                if (conn != null && !conn.isClosed()) {
                                                                return conn;
                                                }
                                } catch (SQLException e) {
                                                System.out.println("Unable to estalish Connection because of "+e.getLocalizedMessage());
                                }
                                conn = makeAConnection(dbName);
                                return conn;
                }
               
                private static Connection makeAConnection(String dbName){
                                try {
                                                String username = null;
                                                String password = null;
                                                Class.forName(Drivers.MY_SQL);
                                                if (dbName.trim().equalsIgnoreCase(Databases.LOCAL_DB_NAME)) {
                                                                url = URLs.LOCAL_DB_URL;
                                                                username = Users.LOCAL_DB_USERNAME;
                                                                password = Passwords.LOCAL_DB_PASSWORD;                                               
                                                }
                                                conn = DriverManager.getConnection(url, username, password);
                                                System.out.println("Connection successful");
                                                return conn;

                                } catch (Exception e) {
                                                e.printStackTrace();
                                }
                                return null;
                }
               
                public static void closeConnection() {
                                if (conn != null) {
                                                try {
                                                                conn.close();
                                                                System.out.println("Connection closed.");
                                                                conn = null;
                                                } catch (SQLException e) {
                                                                e.printStackTrace();
                                                }
                                }
                                if(stmt !=null){
                                                try {
                                                                stmt.close();
                                                                System.out.println("Connection stmt closed.");
                                                                stmt = null;
                                                } catch (SQLException e) {
                                                                e.printStackTrace();
                                                }
                                }
                }
                public static Statement getStatement(String dbName) {
                                if (stmt != null) {
                                                return stmt;
                                }
                                try {
                                                stmt = LocalDBConnection.getConnection(dbName).createStatement();
                                                return stmt;
                                } catch (SQLException e) {
                                                e.printStackTrace();
                                }
                                return null;

                }
               
                public static PreparedStatement getPreparedStatement(String dbName, String query) {
                                if (pstmt != null) {
                                                return pstmt;
                                }
                                try {
                                                pstmt = (PreparedStatement) LocalDBConnection.getConnection(dbName).prepareStatement(query);
                                                return pstmt;
                                } catch (SQLException e) {
                                                e.printStackTrace();
                                }
                                return null;

                }
               
                public static void main(String args[]){
                                String query = "select * from update_commands";
                                try {
                                                ResultSet st = LocalDBConnection.getStatement(Databases.LOCAL_DB_NAME).executeQuery(query);
                                } catch (SQLException e) {
                                                e.printStackTrace();
                                }
                }
               
}



package com.anshul.projects.drfirst.test;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.anshul.projects.drfirst.commons.Constants.Databases;
import com.anshul.projects.drfirst.dao.LocalDBConnection;

public class TestMe {
      public static void main (String args[]){
            String query = "insert into login (username, password) values (?,?)";
            PreparedStatement pstmt = LocalDBConnection.getPreparedStatement(Databases.LOCAL_DB_NAME, query);
            try {
                  pstmt.setString(1, "A'nshul");
                  pstmt.setString(2, "S\"ood");
                  int j = pstmt.executeUpdate();
                  System.out.println(j);
                  LocalDBConnection.closeConnection();
            } catch (SQLException e) {
                  e.printStackTrace();
            }
      }
}

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...