Wednesday 16 March 2016

7 HTML 5 Tags and Attributes you must know!

Its been a year and half since I last posted any tips or tutorial so today I decided to post something that currently I am using and learning that is HTML 5 technology.

About HTML 5, is a revision of the Hypertext Markup Language (HTML), the standard programming language for describing the contents and appearance of Web pages. HTML 5 was developed to solve compatibility problems that affect the current standard, HTML 4. One of the biggest differences between HTML 5 and previous versions of the standard is that older versions of HTML require proprietary plugins and APIs. (This is why a Web page that was built and tested in one browser may not load correctly in another browser.) 
HTML 5 provides one common interface to make loading elements easier. For example, there is no need to install a Flash plugin in HTML 5 because the element will run by itself.

1. A new DOCTYPE declaration.

Having problem remembering long and complicated HTML 4 / XHTML 1.0 doctype like below?

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

If so, then you will surely love the new doctype by HTML5, which looks simple, clean and easy to memorize. Here it is:


1 <!DOCTYPE html>


2. No more Type attribute for script and link.
This is how you define your <script> and <link> tags in HTML 4.


1 <link rel="stylesheet" type="text/css" href="style.css" />
2 <script type="text/javascript" src="script.js"></script>

In HTML 5, you don’t have to specify the MIME type value for your <script> and <link> tag. All scripts and styles are assumed to be type="text/javascript" and type="text/css". You can simply write your code as:


1 <link rel="stylesheet" href="style.css" />
2 <script src="script.js"></script>

3. Semantic Structure – header , footer & nav
Previously, we added an id or classes to HTML structure and perhaps, it can be serve as pseudo-semantic structure. But by nature, div have no semantic structure even after added an id.


1 <div id="header">
2    ...
3 </div>
4 <div id="nav">
5    <ul>...</ul>
6 </div>
7 <div id="footer">
8    ...
9 </div>

New HTML5 tags like <header>, <nav> and <footer> can be used to replace the mark-up above, with provide semantic structure to content.


1 <header>
2    ...
3 </header>
4 <nav>
5    <ul>...</ul>
6 </nav>
7 <footer>
8    ...
9 </footer>
 

4. Semantic Structure – article vs section.

HTML5 also offers new <article> and <section> tags to help us create semantic content.



1 <section>
    ...
2 </section>
3 <section> tag defines sections in a HTML such as headers, footers, or any other sections of content.


1 <article>
2   ...
3 </article>

The <article> tag is used to specify independent and self-contained content.

 

5. New HTML5 Form Input Types and Attributes
HTML5 has introduced 13 new input types and several new attributes for <form> and <input> tags. However, not all browsers are fully support HTML5 new input types and attribute. By the way, you might have to try out these amazing HTML5 form, some new features has been added for instance the browser-based validation, build-in placeholder and new input types.


1 <form id="myform">
2    Name: <input name="name" required placeholder="Your name" pattern="[A-z]{7}" />
3    <br/>
4    Email: <input type="email" name="email" required placeholder="email@inwebson.com"/>
5    <br/>
6    URL: <input type="url" name="url" placeholder="Homepage URL"/>
7    <br/>
8    Age: <input type="number" name="age" min="18" max="99" />
9    <br/>
10   Description: <textarea name="desc" placeholder="Describe yourself here..."></textarea>
11   <br/>
12   <input type="submit" value="Submit" />
13 </form>


6. Editable HTML5 Content

HTML5 has offers another cool new attribute – contenteditable. You can make your content editable with adding the contenteditable attribute to it. This feature will be more useful if paired with HTML5 Local Storage (will be explain in below).


1 <div contenteditable="true">
2    Any content here will be editable...
3 </div>


7. HTML5 Fix for Internet Explorer

Internet Explorer up to version 8.0 can’t read HTML5 tags properly, you can’t style them. Thankfully, Remy Sharp and John Resig have found a fix for this.


1 <!--[if lt IE 9]>
2    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
3 <![endif]-->

Simply include this script in the <header> tag and you will be able to style the HTML5 elements in IE.





Saturday 14 June 2014

Introduction to JavaBeans

Every Java user interface class is a JavaBeans component. Understanding JavaBeans will help you to learn GUI components.JavaBeans is a software component architecture that extends the power of the Java language by enabling well-formed objects to be manipulated visually at design time in a  pure Java builder tool, such as NetBeans and Eclipse.

JavaBean Rules :
  • A JavaBean must have a public, no-argument constructor (a default constructor). This is required so that Java frameworks can facilitate automated instantiation.
  • The JavaBean class attributes must be accessed via accessor and mutator methods that follow a standard naming convention (getXxxx and setXxxx, isXxxx for boolean attributes). It’s important to note that an “attribute” is a named memory location that contains a value, while a “property” refers to this set of methods used to access an attribute. This allows frameworks to automate operations on attribute values.
  • The JavaBean class should be serializable. This allows Java applications and frameworks to save, store, and restore the JavaBean state.That means a bean must implement the Serializable interface to ensure a persistent state.
package player; 
// The class is serialized for IO operations
public class PersonBean implements java.io.Serializable {
 // attributes declared as private
 private String name;
 private boolean counter;
 

 // Default Constructor
 public Person() { }

 // getXxx to access the name attribute
 public String getName() {
  return this.name;
 }

 // setXxxx to mutate the name attribute
 public void setName(String name) {
  this.name = name;
 }

 // isXxxx to access boolean attribute
 public boolean iscounter() {
  return this.counter;
 }

 // setXxx to mutate boolean attribute
 public void setCounter(boolean counter) {
  this.counter = counter;
 }
}
 
import player.PersonBean;
 
/**
 * Class TestPersonBean
 */
public class TestPersonBean {
    /**
     * Tester method  for class PersonBean
     */
    public static void main(String[] args) {
        PersonBean person = new PersonBean();
 
        person.setName("Bob");
        person.setcounter(false);
 
        // Output: "Bob [alive]"
        System.out.print(person.getName());
        System.out.println(person.isCounter() ? " [counter]" : " [alive]");
    }
} 
Advantages:
  • The properties, events, and methods of a bean that are exposed to another application can be controlled.
  • A bean may register to receive events from other objects and can generate events that are sent to those other objects.
  • Auxiliary software can be provided to help configure a java bean.
  • The configuration setting of bean can be saved in a persistent storage and restored at a later time.
 Disadvantages:
  • A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler can’t detect such a problem, and even if it’s documented, there’s no guarantee that the developer will see the documentation.
  • Having to create a getter for every property and a setter for many, most, or all of them can lead to an immense quantity of boilerplate code.

Monday 9 June 2014

Singleton Design Pattern in java

Singleton pattern in Java is one of the most common patterns available and it’s also used heavily in core Java libraries.
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern.
Java has several design patterns Singleton Pattern being the most commonly used.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it."
That means this design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
The key is not the problem and definition. In singleton pattern, tricky part is implementation and management of that single instance.
There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:

 1.Java.lang.Runtime with getRuntime() method
 2.Java.awt.Toolkit with getDefaultToolkit()
 3.Java.awt.Desktop with  getDesktop()

There are at least four ways to implement Singleton pattern in Java.
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums
This article is an attempt to explain the basics on singleton design pattern.If you want more insight on singleton then i will explain it in detail later.

Monday 2 June 2014

What is DatabaseMetaData?

DatabaseMetaData is used to know which type of driver we are using and whether is it compatable or JDBC complaint or not. It is used to know all details about database provider as well.Here is the example--
 
package com.rexofcyber.jdbc;
 
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class MyDatabaseMetadata {
 
    public static void main(String a[]){
         
        Connection con = null;
        try {
            con = DriverManager.
                getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
                        ,"user","password");
            DatabaseMetaData dm = con.getMetaData();
            System.out.println(dm.getDriverVersion());
            System.out.println(dm.getDriverName());
            System.out.println(dm.getDatabaseProductName());
            System.out.println(dm.getDatabaseProductVersion());
        } catch (SQLException e) {
         
            e.printStackTrace();
        } finally{
            if(con != null){}
                try {
                    con.close();
                } catch (SQLException e) {
            
                    e.printStackTrace();
                }
            }
        }
    }
}

How to execute any type of query in JDBC?

The Statement.execute() method allows us to execute any kind of query like select, update. It returns boolean. If the return value is true, then it executed select query, get the ResultSet object and read the resulted records. If it returns false, then it can be update query, call getUpdateCount() method to get total records updated.
package com.rexofcyber.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class MyExecuteMethod {
 
    public static void main(String a[]){
         
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.
                    getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
                        ,"user","password");
            Statement stmt = con.createStatement();
            //The query can be update query or can be select query
            String query = "select * from emp";
            boolean status = stmt.execute(query);
            if(status){
                //query is a select query.
                ResultSet rs = stmt.getResultSet();
                while(rs.next()){
                    System.out.println(rs.getString(1));
                }
                rs.close();
            } else {
                //query can be update or any query apart from select query
                int count = stmt.getUpdateCount();
                System.out.println("Total records updated: "+count);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            try{
                if(con != null) con.close();
            } catch (Exception ex){}
        }
    }
}


Saturday 24 May 2014

Puzzle 1: Hello, Goodbye

This program adds an unusual twist to the usual Hello world program. What does
it print?

public class HelloGoodbye {
public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(0);
} finally {
System.out.println("Goodbye world");
}
}
}
Solution :
The program contains two println statements: one in a try block and the other in the corresponding finally block. The try block executes its println and finishes execution prematurely by calling System.exit. At this point, you might expect control to transfer to the finally block. If you tried the program, though, you found that it never can say goodbye: It prints only Hello world.
It is true that a finally block is executed when a try block completes execution whether normally or abruptly. In this program, however, the tryblock does not complete execution at all. The System.exit method halts the execution of the current thread and all others dead in their tracks.The presence of a finally clause does not give a thread special permission to continue executing.
When System.exit is called, the virtual machine performs two cleanup tasks before shutting down. First, it executes all shutdown hooks that have been registered with Runtime.addShutdownHook. This is useful to release resources external to the VM. Use shutdown hooks for behavior that must occur before the VM exits.The following version of the program demonstrates this technique,
printing both Hello world and Goodbye world, as expected:

public class HelloGoodbye {
public static void main(String[] args) {
System.out.println("Hello world");
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
System.out.println("Goodbye world");
}
});
System.exit(0);
}
}

The second cleanup task performed by the VM when System.exitis called concerns finalizers. If either System.runFinalizersOnExitor its evil twin Runtime.runFinalizersOnExit has been called, the VM runs the finalizers on all objects that have not yet been finalized. These methods were deprecated a long time ago and with good reason. Never call System.runFinalizersOnExitor Runtime.runFinalizersOnExit for any reason: They are among the most
dangerous methods in the Java libraries. Calling these methods can result in finalizers being run on live objects while other threads are concurrently manipulating them, resulting in erratic behavior or deadlock.
In summary, System.exit stops all program threads immediately; it does not cause finally blocks to execute, but it does run shutdown hooks before halting the VM. Use shutdown hooks to terminate external resources when the VM shuts down. It is possible to halt the VM without executing shutdown hooks by calling System.halt, but this method is rarely used. 

Extract a zip file using Java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
/**
 * This utility extracts files and directories of a standard zip file to
 * a destination directory.
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
   

    public void unzip(String zipFilePath, String destdirectory)throwsIOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
 
    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}