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

Monday, February 13, 2012

Write File in java

private static void writeFile(String stringToWrite, String pathResponse) {
        FileWriter fw = null;
        BufferedWriter out = null;
        try {
            fw = new FileWriter(pathResponse,true);
            out = new BufferedWriter(fw);
            out.write(stringToWrite);   
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
    }

Read a File Using JAVA

public class ReadFile {
  
    public static void main(String args[]){
        String pathRequest = "SupportFiles\\Test\\"+apiName+".txt";
        readFile(pathRequest);
    }

    private static void readFile(String pathRequest) {
        FileInputStream fis = null;
        DataInputStream in = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(pathRequest);
            in = new DataInputStream(fis);
            isr = new InputStreamReader(in);
            br = new BufferedReader(isr);
            String strLine;
            while ((strLine = br.readLine()) != null){
                  System.out.println (strLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                br.close();
                isr.close();
                in.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Sunday, February 12, 2012

SQL JOINS

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

SpringBoot Application Event Listeners

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