Saturday, October 5, 2013

Amazing Light - Beautiful piece of art


Brick laying machine


Tiger-Stone, the amazing machine can create an instant road wherever it travels, laying out bricks in formation to create perfect paving. Its secret lies in a smartly designed gravity-based system.


Virtual wall concept to protect pedestrians



Pedestrian/motor vehicle crashes are a serious problem throughout the world and the India has a particular problem with pedestrian deaths and injuries.
Almost two-thirds of the 1.2 million people killed annually in road traffic crashes worldwide are pedestrians.


The sequence of events in a car-pedestrian accident

Traffic accidents are among the major causes of death in India. Every year increased the pedestrian accidents at pedestrian crossing zone. And I thought that crossing zone is sharing space between pedestrian and driver. But drivers are never care which pedestrian’ safety in the real world. Even drivers are sometimes switching to pedestrian. And nowadays, urban sites got the problem that disturbance of traffic signal. We are surrounded such a crazy commercials and crowd environment near the road space.


That’s a one of reason that many drivers losing attention and difficulty of awareness into traffic signal. And, I’d like to make wall up on the car’ stop line at the moment. Virtual Wall, It’s really effective in driver awareness. Because Virtual Wall can get bigger image and better look.


the inventor of this concept is  Hanyoung  Lee, got  awarded for this  creation work. this can be implemented in all zones for a better safety of pedestrians the concept work like this : at the junctions some two poles are fixed and when the pedestrians crossing the road these poles produces some rays which are visible to naked eye looks like a wall infront of them so this will gives more safety for the pedestrians.

Saturday, June 1, 2013

Two Datasource in Spring/Hiberate

We can create two datasource in a single spring/hibernate application.

There are following steps required to implement this:-

Create JNDI Datasource while using Tomcat :- 
  1. Resource entry in server.xml under <GlobalNamingResources> for both datasources
    You can find server.xml in following path in Tomcat folder :-
     c://Tomcat/conf/server.xml
  2. <globalnamingresources>
        <resource name="jdbc/first"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="makecodeeasy" type="javax.sql.DataSource" url="jdbc:sqlserver://localhost:1433;DatabaseName=DataTest" username="makecodeeasy" validationquery="select 1">
        </resource>
    
     <resource name="jdbc/second"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="123" type="javax.sql.DataSource" url="jdbc:sqlserver://192.182.21.66:1433;DatabaseName=Second" username="sa" validationquery="select 1">
        </resource>
     </globalnamingresources>
    
    Note :- Database used here in MS Sql server 2008. You can use any database. You need to change driverClassname, url, username and password according to  database.
  3. Do the entry in web.xml for both resources
    You can find web.xml in WEB-INF folder of your application
  4. <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/first</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
    
    <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/second</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
  5. Use datasource in applicationContext or spring context file
  6. <bean id="firstDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/first" /> 
      <property name="resourceRef" value="true" /> 
    </bean>
    <bean id="secondDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/second" /> 
      <property name="resourceRef" value="true" /> 
    </bean> 
  7. Create two session factory for using two datasource.
    <bean id="firstSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="firstDataSource" p:configLocation="${hib.config}" p:packagesToScan="com.org.xyz.domain">
    </bean>
    <bean id="secondSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="secondDataSource" p:configLocation="${hib.config}" p:packagesToScan="com.org.abc.domain">
    </bean>

  8. Now these session factories can be used in Hibernate application.

Sunday, May 19, 2013

JNDI Datasource in spring

There are two sources of database connections - either a  DataSource or a  DriverManager.

JNDI
The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Create JNDI Datasource while using Tomcat :- 
  1. Resource entry in server.xml under <GlobalNamingResources>
    You can find server.xml in following path in Tomcat folder :-
     c://Tomcat/conf/server.xml
  2. <globalnamingresources>
        <resource name="jdbc/test"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="makecodeeasy" type="javax.sql.DataSource" url="jdbc:sqlserver://localhost:1433;DatabaseName=DataTest" username="makecodeeasy" validationquery="select 1">
        </resource>
    </globalnamingresources>
    Note :- Database used here in MS Sql server 2008. You can use any database. You need to change driverClassname, url, username and password according to  database.
  3. Do the entry in web.xml
    You can find web.xml in WEB-INF folder of your application
  4. <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/test</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
  5. Use datasource in applicationContext or spring context file
  6. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/test" /> 
      <property name="resourceRef" value="true" /> 
    </bean>
    
  7. Your Datasource is ready to use. It can also be used in hibernate.

Saturday, May 18, 2013

Browser CSS Hacks


CSS Hacks

/***** Selector Hacks ******/

/* IE6 and below */
* html #mydiv  { color: red }

/* IE7 */
*:first-child+html #dos { color: red }

/* IE7, FF, Saf, Opera  */
html>body # mydiv  { color: red }

/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body # mydiv  { color: red }

/* Opera 9.27 and below, safari 2 */
html:first-child # mydiv  { color: red }

/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #mydiv  { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #mydiv  {  color: red }

/* saf3+, chrome1+ */

@media screen and (-webkit-min-device-pixel-ratio:0) {

 #mydiv  { color: red  }
}

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
 #mydiv  { color: red  }
}


/* Safari 2 - 3.1 */
html[xmlns*=""]:root #mydiv  { color: red  }

/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #mydiv  { color: red  }

/* Everything but IE6-8 */
:root *> #mydiv  { color: red  }

/* IE7 */
*+html #mydiv  {  color: red }

/* Firefox only. 1+ */
#mydiv ,  x:-moz-any-link  { color: red }

/* Firefox 3.0+ */
#mydiv ,  x:-moz-any-link, x:default  { color: red  }

/* FF 3.5+ */
body:not(:-moz-handler-blocked) #mydiv { color: red; }


/***** Attribute Hacks ******/

/* IE6 */
#mydiv { _color: blue }

/* IE6, IE7 */
#mydiv { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#mydiv { color/**/: blue }

/* IE6, IE7, IE8 */
#mydiv { color: blue\9; }

/* IE7, IE8 */
#mydiv { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#mydiv { color: blue !ie; } /* string after ! can be anything */

/* IE8, IE9 */
#mydiv  {color: blue\0/;} /* must go at the END of all rules */


Some More Hacks :-

#mydiv {
    width:89px; (common for all)
    margin-left/*\**/:90px\9; ( For IE8)
    margin-top/*\**/:-31px\9;
}

#
mydiv  {
    width:89px;
    margin-left/*\**/: 180px\9;
    margin-top/*\**/:-32px\9;
   
}
(only IE6)
* html #
mydiv  {
    margin-left:95px;
    margin-top:-33px;
}

*html #
mydiv  {
    margin-left:186px;
    margin-top:-30px;
}
(only IE7)
*:first-child+html #
mydiv  {
    margin-left:90px;
    margin-top:-30px;
}

*:first-child+html #
mydiv  {
    margin-left:180px;
    margin-top:-27px;
}

(SAFARI)
body:last-child:not(:root:root) #
mydiv  {
    margin-left:90px;
    margin-top:-31px;
}

body:last-child:not(:root:root) #
mydiv  {
    margin-left:180px;
    margin-top:-31px;
}

/* body:first-of-type #
mydiv  {
    margin-left:90px;
    margin-top:-31px;
}

body:first-of-type #
mydiv  {
    margin-left:180px;
    margin-top:-31px;
}
*/

/*::root #
mydiv  {
    margin-left:90px;
    margin-top:-31px;
}

::root #
mydiv  {
    margin-left:180px;
    margin-top:-31px;
}
*/

/* @media screen and (-webkit-min-device-pixel-ratio:0){
    #
mydiv  {
        margin-left:90px;
        margin-top:-31px;
    }
    #
mydiv  {
        margin-left:180px;
        margin-top:-31px;
    }

}
*/




Sunday, May 5, 2013

JNDI

The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Example of creating JNDI Datasource.

Tuesday, April 30, 2013

Iterate a HashMap


HashMap is an object that stores both “key/value” as a pairs.
It is one of the most useful data structures in the Java programming language.

Step by Step Iterating a HashMap :- 

Method 1 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}

Method 2 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Saturday, March 23, 2013

Logger in Spring web application


The logging API is designed to let a Java program, servlet, applet, EJB, etc. produce messages of interest to end users, system administrators, field engineers, and software developers. Especially in production situations, where things can't be run in a debugger, or if doing so masks the problem that is occurring (because it is timing related, for example), such logs are frequently the greatest (and sometimes the only) source of information about a running program.

Step by Step implementing Logger in Spring Web Application:-

  1. Download log4j jar and put to application build path / put to WEB-INF lib folder.
    Download JAR link
  2. Create a file name Log4js.properties
  3. log4j.rootCategory=INFO,S,rollingFile
    
    log4j.appender.S =org.apache.log4j.ConsoleAppender
    log4j.appender.S.layout =org.apache.log4j.PatternLayout
    log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
    log4j.appender.rollingFile = org.apache.log4j.DailyRollingFileAppender
    
    #provide path to your location where you want logs created. For now its logs folder of tomcat.
    log4j.appender.rollingFile.File = ${catalina.home}/logs/loggerDemo.log
    log4j.appender.rollingFile.Append = true
    log4j.appender.rollingFile.Threshold = ALL
    log4j.appender.rollingFile.DatePattern = '.'yyy-MM-dd
    log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.rollingFile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
    
    
      Here ${catalina.home} :- The Tomcat Web container uses a file system directory, called the catalina home directory, to hold files that are common to the entire container.
      You can also give other path for generating log file.
  4. Entry in web.xml file
  5.  
          log4jConfigLocation
          /WEB-INF/resources/log4j.properties
        
    
         
            org.springframework.web.util.Log4jConfigListener
        
    
  6. JAVA Code for logger.
  7. import org.apache.log4j.Logger;
    public class LoggerController {
    
    	private static final Logger LOGGER = Logger.getLogger(LoggerDemo.class);
    
    	@RequestMapping(method=RequestMethod.GET, value="/login/{id}")
    	@ResponseBody public void getUserName(@PathVariable String id) {
    		LOGGER.info("Calling service User authentication" + id);
    	}
    
    }
    
    
  8. Enjoy :)

Sunday, January 6, 2013

Extract a list of filtered files in Java

Sometimes, we need to get a list of files exist within a directory as per our criteria like filename, file extension, last modified date or other attributes. It reduces the overhead to filter them after getting the list using our code. To achieve this, Java provides an interface - FileFilter which has a single method prototype as boolean accept(File file). To apply our filtering criteria, we have to override this method and if our logic returns true for a file then only the file will be included in the list otherwise not. 

Example :- 

import java.io.*;
import java.util.*;
 
public class FilteredFileList {
    public static File[] getFilteredFileList(File folder, final String filenameFilter, Date lastModifiedDateFilter) {
        File[] listOfFiles = folder.listFiles(new FileFilter(){
                                public boolean accept(File file) {
                                    //file is the object against which we are applying our logic.
                                    //You can put your logic using filenameFilter and check whether
                                    //the file's name comes under your criteria or not.
                                    //To check against the lastmodified date you can use lastModifiedDateFilter.
                                    return true;
                                }});
        return listOfFiles;
    }
}

JDBC Connection in Java

JDBC (Java DataBase Connectivity) is an API for the Java programming language through which the databse can be accessed using methods for querying and updating data.


Example :- 

import java.sql.*;
 
public class ConnectionInfo {
 
    public Connection getConnection() {
        Connection conn = null;
        // the below properties should be read from a properties file based on the Database used
        String url = "jdbc:mysql://localhost:3306/"; // url = jdbc:[subprotocol]://[hostname]:[portnumber]/
        String dbName = "jdbctutorial"; // database name
        String driver = "com.mysql.jdbc.Driver"; //Driver class name
        String username = "root"; // username
        String password = "root"; // password
        try {
          Class.forName(driver); // Dynamic loading based on database used.
          conn = DriverManager.getConnection(url + dbName, username, password);
          System.out.println("Connection Established");
        } catch (SQLException e) {
          e.printStackTrace();
        } finally {
            return conn;
        }
    }
 
    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Java Multithreading


Process can be further divided into small tasks which refer as a Thread. If two or more tasks of a process executes concurrently, then this scenario refers as aMultithreading environment. Every thread has it's own independent path of execution. In java, there are two ways to implement multithreading -

Through implementation of Runnable interface - To create a thread, we can implement Runnable interface. This interface has a single run() method declaration, so we have to override that method. Actually, in this approach, we write a wrapper over Thread class. The objects of the class which implements Runnable interface, work as a thread of the program and run on their own execution paths.

Example :- 
public class RunnableExample implements Runnable {
    private Thread thread;
    public RunnableExample(String name) {
        //here we pass the reference whose run method should be called.
        thread = new Thread(this, name);
        //creating thread
        thread.start();
    }
     
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}
 
public class RunnableMain {
    public static void main(String[] args) {
        //Creating three objects
        Runnable run1 = new RunnableExample("Thread-1");
        Runnable run2 = new RunnableExample("Thread-2");
        Runnable run3 = new RunnableExample("Thread-3");
    }
}



2. Using Thread class extension - This is another approach of thread creation. But, it restricts the class to extend other classes (if required). In this approach, we extend our class to Thread class so that it's objects work as threads and run on their own separate execution paths.

Here is the sample code -
public class ThreadExample extends Thread {
 
    public ThreadExample(String name) {
        super(name);
    }
     
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}
 
public class ThreadMain {
    public static void main(String[] args) {
        //Creating three objects
        Thread t1 = new ThreadExample("Thread-1");
        Thread t2 = new ThreadExample("Thread-2");
        Thread t3 = new ThreadExample("Thread-3");
        creating threads
        t1.start();
        t2.start();
        t3.start();
    }
}

ShareThis