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

ShareThis

Video Bar

Loading...