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