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();
            }
      }
}

Tuesday, March 13, 2012

Creating Custom functions in JSP using JSTL

1. Create a tld file inside WEB-INF folder having declaration of the custom function as below
    <?xml version="1.0" encoding="UTF-8" ?>
      <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
          version="2.0">
   
          <description>JSTL 1.1 functions library</description>
          <display-name>JSTL functions</display-name>
          <tlib-version>1.1</tlib-version>
          <short-name>fn</short-name>
          <uri>http://java.sun.com/jsp/jstl/functions</uri>
        <function>
              <name>functionName</name>
              <function-class>anshul.project.vaidya.test.Anshul</function-class>
              <function-signature>
                java.util.ArrayList&lt;java.util.ArrayList&gt; functionName( java.lang.String )
          </function-signature>
        </function>
    </taglib>

2.     Configure this tld file in web.xml as
    <jsp-config>
          <taglib>
                <taglib-uri>$customURI</taglib-uri>
                <taglib-location>$Absolute path of tld file inside WEB-INF starting with / </taglib-location>
          </taglib>
      </jsp-config>

3.     Now to use the function in a jsp page add the taglib directive there as

    <%@ taglib uri="$customURI" prefix="$customPrefix"%> 
     
    Now you can use the function anywhere in the page like:-

    ${customPrefix:functionName(parameter)}

Monday, March 5, 2012

1. Right click project > Properties>Javasript>Javascript libraries>Add Runtime libraries> Internet Explorer Library> ok

SpringBoot Application Event Listeners

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