Thursday, 10 April 2014

Notify Popup using jQuery

Hi we may have seen notify popup in various websites like displaying messages to user for couple of seconds and disappears automatically. Its pretty simple by using notify.js file and just need to call notify method with message text along with its type as parameter (optional).  Different messages types and notify styles are "success", "info", "warn" and "error". 
Apart from basic notification we can get elements position notifications also with their different positions like left, right, top, bottom etc., For complete API details you can their official site http://notifyjs.com/

Lets see simple example for using notify in our web application.


SAMPLE CODE:

<html>
<head>
<script src="jquery-1.10.2.js"></script>
<script src="notify.min.js"></script>
</head>
<body>

<ul style="list-style:none;line-height:40px;">
<li><div onclick='$.notify("Steve Success Story...", "success");'>Click for SUCCESS</div></li>
<li><div onclick='$.notify("Get detail information on legal battle...", "info");'>Click for INFO</div></li>
<li><div onclick='$.notify("Carefull on public internet...", "warn");'>Click for WARNING</div></li>
<li><div onclick='$.notify("Oops, Page not found !!!", "error");'>Click for ERROR</div></li>
</ul>
</body>
</html>



OUTPUT:


Notify Popup using jQuery



read more.. "Notify Popup using jQuery"

Java Enumeration with example

Enumeration is an interface similar to Iterator where the Object implements the Enumeration interface generates a series of elements, one at a time. There are 2 methods like
Java Enumeration with example

  • hasMoreElements() - Checks whether enumeration contains more elements.
  • nextElement() - Returns next element from enumeration if elements present in it. 
Functionality wise its similar to Iterator interface, but by using Iterator we will get additional option like remove operation. Lets see simple example for using Enumeration on Vector Object. 


import java.util.Enumeration;
import java.util.Vector;

public class EnumerationTest {
 
 public static void main(String[] args) {
  
  Vector<String> vec = new Vector<String>();
  vec.add("java");
  vec.add("discover");
  vec.add("Enumeration");
  vec.add("interface");
  
  Enumeration<String> enumer = vec.elements();
  while(enumer.hasMoreElements()){
            System.out.println(enumer.nextElement());
        }
 }
}

OUTPUT:


java
discover
Enumeration
interface

read more.. "Java Enumeration with example"

Tuesday, 8 April 2014

Creating custom error pages and handling exceptions in JSP

We all know how to handle exception in java code. But if there are any exception occurred at client side jsp files then how we can handle?
Basically Exception is an Object thrown at compile or run-time. When we talk about web application and handling exceptions in JSP files then there are 2 ways to handle it
1. By adding <error-page> element in web.xml for different error codes and exceptions.
2. By errorPage and isErrorPage attributes in page directives. 

First lets see simple example by adding <error-page> element in web.xml for handling error codes.

1. Install Eclipse IDE and Apache Tomcat 
2. Create Dynamic Web Application in Eclipse IDE and add these files

  • web.xml
  • error404.jsp
  • expError.jsp
  • test_exception.jsp


Folder Structure:
TestApp
|-> WEB-INF
|-> web.xml
|-> error404.jsp
|-> expError.jsp
|-> test_exception.jsp


web.xml:


<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Error Code Test Application</display-name>
 <description>Test Application for Error codes and Exceptions</description>
 <error-page>
  <error-code>404</error-code>
  <location>/error404.jsp</location>
 </error-page>
 <error-page>
  <error-code>500</error-code>
  <location>/error500.jsp</location>
 </error-page>
 <error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/expError.jsp</location>
 </error-page>
</web-app>

Here we have configured <error-page> elements for 404 error page and exception types. 


error404.jsp:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error Page</title>
</head>
<body>

 Sorry !!!
 <br> 404 Error - Page not found :(

</body>
</html>

If user tries to open page which not found then automatically error404.jsp page will be called. We will try to access page which not present in the path like test.jsp.

404 Error Page test through custom error page creation in JSP



expError.jsp:


<%@page import="java.io.PrintWriter"%>
<%@page import="java.io.StringWriter"%>
<%@ page isErrorPage="true"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error Page</title>
</head>
<body>

 Sorry !!!
 <br>
 <B>Exception occurred : </B><%=exception.getMessage()%>

 <br>
 <b>StackTrace: </b>
 <%
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  exception.printStackTrace(pw);
  out.println(sw);
  pw.close();
  sw.close();
 %>

</body>
</html>

Next we will test for exceptions in Jsp file. expError.jsp file is a generic file to handle all types of run-time exceptions based on <exception-type> element in web.xml. Here we printing exception type and its stack trace.

test_exception.jsp:

test_exception.jsp page will be used to test exceptions. Here we are generating divide by Zero exception which will automatically thrown to expError.jsp page.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Exception Page</title>
</head>
<body>

 <%
  int val = 100;
  val = val / 0;
 %>
</body>
</html>


Handling exceptions in JSP




2. By errorPage and isErrorPage attributes in page directives. 

2nd type is by adding errorPage attribute of page directive in actual pages and isErrorPage attribute in error pages as like below.

<%@ page errorPage="expError.jsp" %>  

<%@ page isErrorPage="true" %>  

To test without web.xml, remove <error-page> elements from web.xml and just add <%@ page errorPage="expError.jsp" %> page directive in top of test_exception.jsp and test through browser which will redirect to expError.jsp page.

read more.. "Creating custom error pages and handling exceptions in JSP"

Saturday, 5 April 2014

Using Java RegEx Pattern and Matcher

Using pattern matcher in java is very easy and simple to identify a specific word or text from the given input String. Also we can check for case insensitive formats also by using Java RegEx. In that case lets see simple example for finding specific text from the multiple String inputs and return whether given text or (Pattern) matches from the given input.
Using Java RegEx Pattern and Matcher



import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatcherTest {

 public static void main(String[] args) {
  
  String str = "The listener interface for receiving text events. " +
    "The class that is interested in processing a text event implements this interface. " +
    "The object created with that class is then registered with a component using the " +
    "component's addTextListener method. When the component's text changes, " +
    "the listener object's textValueChanged method is invoked.";
  
  PatternMatcherTest obj = new PatternMatcherTest();
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "interface"));
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "EVENTS"));
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "Java"));
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "Method"));
 }

 public boolean checkPatternMatch(String str, String regex) {
  Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
  Matcher match = pattern.matcher(str);
  if (match.find())
   return true;
  else
   return false;
 }
}


OUTPUT:


PRESENT : true
PRESENT : true
PRESENT : false
PRESENT : true



read more.. "Using Java RegEx Pattern and Matcher"

Friday, 4 April 2014

Change file permission using java

Changing file permission using GUI is an end user easy operation. Same thing if we need to change multiple files like around hundreds or thousands of file then its difficult. But we can achieve this easy by using Java code. So lets see simple example for reading file permissions and then changing file to full permission (Read, Write and Execute).
Change file permission using java



import java.io.File;

public class FilePermissionTest {

 public static void main(String[] args) {
  
  String testFile = "D://testfile.txt";
  
  File file = new File(testFile);
  System.out.println("Current File Permissions : ");
  System.out.println("\t Read     : "+file.canRead());
  System.out.println("\t Write    : "+file.canWrite());
  System.out.println("\t Execute  : "+file.canExecute());
  
  System.out.println("\nLets change file to full permission ");
  
  file.setReadable(true);
  file.setWritable(true);
  file.setExecutable(true);
  
  System.out.println("\nChanged File Permissions : ");
  System.out.println("\t Read     : "+file.canRead());
  System.out.println("\t Write    : "+file.canWrite());
  System.out.println("\t Execute  : "+file.canExecute());
 }
}

OUTPUT:


Current File Permissions : 
  Read     : true
  Write    : false
  Execute  : true

Lets change file to full permission 

Changed File Permissions : 
  Read     : true
  Write    : true
  Execute  : true

read more.. "Change file permission using java"

Read and Write Objects from a file

Sometimes we may thinking of writing Objects into file and reading from other class or may need for future purpose. Basically we need to store the state of Object in a file and need to retrieve. For this we need to use Serializable interface to Serialize all class variables and by using ObjectInputStream and ObjectOutputStream class can be read and write from a file. Lets see simple example how to Serialize Object and same Object can to written into file. Next by another Java file we will read same Object from the file.
Read and Write Objects from a file



import java.io.Serializable;

public class Student implements Serializable {

 private static final long serialVersionUID = 1L;

 private String name;
 private int marks[] = new int[5];

 public Student(String name, int marks[]) {
  this.name = name;
  this.marks = marks;
 }

 public String getName() {
  return name;
 }

 public int[] getMarks() {
  return marks;
 }
}



In next program we will create Student Object and write to a file. 


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class WriteToFile {

 public static void main(String[] args) {

  String name = "Steve";
  int marks[] = new int[] { 89, 86, 94, 78, 91 };

  Student obj = new Student(name, marks);

  new WriteToFile().writeStudentObjectToFile(obj);
 }

 public void writeStudentObjectToFile(Student obj) {

  OutputStream os = null;
  ObjectOutputStream oos = null;
  
  try {
   os = new FileOutputStream("D://student.txt");
   oos = new ObjectOutputStream(os);
   oos.writeObject(obj);
   oos.flush();
   System.out.println("Object written successfully to file");
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally {
   try {
    if (oos != null) oos.close();
   } catch (Exception ex) {}
  }
 }
}

OUPTUT:


Object written successfully to file


In next program we will read same file and extract Student Object from the file and print the values. 


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class ReadFromFile {

 public static void main(String[] args) {

  new ReadFromFile().readStudentObjectFromFile();
 }

 public void readStudentObjectFromFile() {
  InputStream is = null;
  ObjectInputStream ois = null;
  
  try {
   is = new FileInputStream("D://student.txt");
   ois = new ObjectInputStream(is);
   
   Student obj = (Student) ois.readObject();
   
   System.out.println("Student Name : " + obj.getName());
   System.out.print("Marks        : ");
   for (int mark : obj.getMarks()) {
    System.out.print(mark+", ");
   }
  
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (ois != null) ois.close();
   } catch (Exception ex) {}
  }
 }
}

OUTPUT:


Student Name : Steve
Marks        : 89, 86, 94, 78, 91, 




read more.. "Read and Write Objects from a file"

Tuesday, 1 April 2014

How to change File Modified Date and Time in Java

As a fun some times we may be thinking of changing file modified date and time from its original modified date and time. We may be thinking of changing date and time and need to puzzle our surrounding. Yes we can achieve this through Java code and lets see how to change it. Lets have fun.


import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileModifyDateAndTime {

 public static void main(String[] args) {
  try{
    
   File file = new File("F:\\testing\\Fool.txt");
  
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
   System.out.println("Original Modified Date and Time : " + sdf.format(file.lastModified()));
  
   //Modifying date and time
   Date newDateAndTime = sdf.parse("24/12/1980 12:59:59");
   file.setLastModified(newDateAndTime.getTime());
  
   System.out.println("Newly Modified Date and Time : " + sdf.format(file.lastModified()));
  
      }catch(ParseException e){ 
       e.printStackTrace(); 
      }
 }
}


OUTPUT:


Original Modified Date and Time : 01/04/2014 19:45:51
Newly Modified Date and Time : 24/12/1980 12:59:59


BEFORE:


How to change File Modified Date and Time in Java

AFTER:


How to change File Modified Date and Time in Java


read more.. "How to change File Modified Date and Time in Java"

Friday, 28 March 2014

Does Java pass by value or pass by reference?

Java does only pass by value and doesn't pass method arguments by reference, instead it passes Object reference by its value as method parameter. Java copies and passes the reference by value, not the object, hence if we modify Object values in method then original objects will get modified, since both references point to the original objects. 
Below are the 2 diagrams which we can see how primitive types work when we pass to another methods and how Objects work when we pass to another methods. Basically primitive types will create new variable in stack and it manipulates on it, but when we pass Objects it creates new reference and its passes the value of reference. Again Java does only pass by value and doesn't use pass by reference. 

When we pass primitive datatype to another method.
Does Java pass by value or pass by reference?
When we pass Object to another method.


Now lets see simple example in java as how it works. Lets create Employee class for Object passing.


public class Employee{
 
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 } 
}

Next we will create main class which will initiate Employee Object and pass to another method along with integer primitive datatype.


public class MyTest {
 
 public static void main(String[] args) {
  
  Employee obj = new Employee();
  obj.setName("JAVA");// IMP
  
  int _int = 100;
  
  MyTest ob1 = new MyTest();
  ob1.changeValue(obj, _int);
  
  System.out.println("Inside Main Method : "+obj.getName()+ " : "+_int);
 }
 
 public void changeValue(Employee mObj, int mInt){
  
  mObj.setName("DISCOVER");
  
  mInt = 99;
  
  System.out.println("Inside another Method : "+mObj.getName() + " : "+mInt);
 }
 
}

OUTPUT:


Inside another Method : DISCOVER : 99
Inside Main Method : DISCOVER : 100

read more.. "Does Java pass by value or pass by reference?"

Wednesday, 26 March 2014

Character Array to String in Java

We may seen lot of arrays like Integer, Character, Float and Double or even String array. In this tutorial we will see about converting Character array to String in Java code. We can achieve this by 2 ways like given below,
Character Array to String in Java


public class CharToString {

 public static void main(String[] args) {
  
  char[] myArray = new char[]{'j','a','v','a',' ','d','i','s','c','o','v','e','r'};
  
  //By 2 ways we can convert char[] to String and lets see both ways
  
  String type1 = String.valueOf(myArray);

String type2 = new String(myArray);
  
  
  System.out.println("TYPE 1 : "+type1);
  System.out.println("TYPE 2 : "+type2);
 }
}

OUTPUT:

TYPE 1 : java discover
TYPE 2 : java discover

read more.. "Character Array to String in Java"