Sunday, 31 August 2014

URL Consuming, URL Calling and Reading Resource from URL

URL is acronym for Uniform Resource Locator. URL is the resource address on the internet. Java provides java.net package to interact with URLs.


Steps to follow while calling url.

1- Create URL object.
2- Open connection with url and get stream.
3- Hold stream.
4- Read returned stream.

URL class provides many methods to parse url like getProtocol(), getHost(), getPath(), getAuthority() and getFile() etc.

Following code snippets display two methods to read resources from URLs

First Method: This method uses openStream() method of URL class to get inputStream without opening connection.

package javaWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class URLCalling {

public static void main(String[] args) {

String urlStr="http://rsjavawrapper.blogspot.in/";
URL url=null;
BufferedReader br=null;
InputStream is=null;
InputStreamReader isr=null;
try {
                       //Creating URL object using StringURL.
url = new URL(urlStr);

//Opening url stream and holding Stream, it returns InputStream object.
is=url.openStream();

                       //Creating InputStreamReader object using returned InputStream to read content.
isr=new InputStreamReader(is);

                        //Creating BufferedReader object using InputStreamReader. 
br = new BufferedReader(isr);

                        //Reading returned content from url.
String content;
while ((content= br.readLine()) != null)
System.out.println(content);

                        //Closing BufferedReader.
br.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}





Second Method: This method uses openConnection() method of URL class to open connection which returns URLConnection class object and this object is further used to get InputStream object. URLConnection class provides many method that make working ease.

package javaWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLCalling {

public static void main(String[] args) {

String urlStr="http://rsjavawrapper.blogspot.in/";
URL url=null;
BufferedReader br=null;
InputStream is=null;
InputStreamReader isr=null;
URLConnection urlCon=null;
try {
//Creating URL object using StringURL.
url = new URL(urlStr);
//Opening connection with url.
urlCon = url.openConnection();
//Getting InputStream object and holding stream.
is=urlCon.getInputStream();

//Creating InputStreamReader object using returned InputStream.
isr=new InputStreamReader(is);

//Creating BufferedReader object using InputStreamReader. 
br = new BufferedReader(isr);

//Reading returned content from url.
String content;
while ((content= br.readLine()) != null)
System.out.println(content);

//Closing BufferedReader.
br.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


Output:



Saturday, 30 August 2014

Sending Email using mail server credential like IP or Host, Port, User and Password.

Java provide a mail API that supports mail working like sending and checking mail. This tutorial needs javax.mail.jar file.

Following tutorial sends email using a particular mail server details.

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {

public static void main(String[] args) {

String sendTo = "sendto@gmail.com";
String From = "noreply@blogspot.com";
String user="userName";
String password="password";
String senderName="rahul sharma";
Session session=null;
String host="30.140.200.100";//temporary address
String port="25";
String subject ="Test Mail";
String message="This is test mail.";
try{
//Setting authentication properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password);
           
// Creating Session object.
session = Session.getInstance(properties, null);

//Creating message and set addresses.
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(From,senderName));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sendTo));
msg.setSubject(subject);

//Creating Body parts.
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(message);
mbp1.setContent(message,"text/html");

//attaching body parts.
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
msg.setContent(mp);

//sending mail.
Transport.send(msg);

System.out.println("Email sent to ......"+sendTo);

}catch(AddressException ae) {
ae.printStackTrace();
}catch(MessagingException me) {
me.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
}

Sending Email using Gmail Server.

Java mail API provide support to send email using gmail server and other mail servers. This tutorial needs javax.mail.jar file. Following tutorial sends email using gmail server.




import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.UnsupportedEncodingException;

public class SendMailFromGmailServer
{
public static void main(String [] args){
                //Sender and Reciever user
String emailTo="emailto@gmail.com";
String senderName="Rahul Sharma";
final String userId = "emailfrom@gmail.com";
final String password = "password";

// Set mail server detail...
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");

// get authenticated.
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userId, password);
}
});

// Composing message.   
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userId,senderName));

//Adding recipient.
message.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTo));
message.setSubject("Email Subject");

//Creating message body.
BodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setText("Email body section content is here.");

//Attaching file.
MimeBodyPart bodyPart2 = new MimeBodyPart();
String filename = "C:\\1.48358393-20131211.pdf";
DataSource source = new FileDataSource(filename);
bodyPart2.setDataHandler(new DataHandler(source));
bodyPart2.setFileName(filename);

//Adding both bodypart to multipart.
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart1);
multipart.addBodyPart(bodyPart2);

//Creating final message to send.
message.setContent(multipart );

//Sending message.
Transport.send(message);

System.out.println("Email sent to email Id : "+emailTo);

}catch (MessagingException ex){
ex.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

Tuesday, 19 August 2014

Java Wrapper: Exception Throwing Handling with Method Overriding...

Java Wrapper: Exception Throwing Handling with Method Overriding...: Exception handling is the process of handling exception raised by a block of code. We can handle exception by using try catch block or it more...

Exception Throwing Handling with Method Overriding


Exception handling is the process of handling exception raised by a block of code. We can handle exception by using try catch block or it can be thrown to the calling method.

Now the question is How to throws exception in case of method overriding? 

In case of method overriding, overriding method always throws same exception or sub-class of what overridden method is throwing. Throwing exception is always remain same or downgraded in case of overriding. Following snippet of code demonstrates it deeply.

package javawrapper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

//Used as SuperClass.
class Super1Class{

//Throwing IOException.
void printFile() throws IOException
{

}

//Throwing IndexOutOfBoundsException
protected void readArrayElements() throws IndexOutOfBoundsException
{

}

//Throwing StringIndexOutOfBoundsException
public void throwSameException() throws StringIndexOutOfBoundsException
{

}
}


//Sub-class of Super1Class.
public class ExceptionHandlingWithOverriding extends Super1Class {

    //overriding method printFile throwing exception sub-class of, what overridden method is throwing.
protected void printFile() throws FileNotFoundException
{
File file=new File("file.txt");
FileReader fr=new FileReader(file);
}

//overriding method readArrayElements throwing exception sub-class of, what overridden method is throwing.
public void readArrayElements() throws ArrayIndexOutOfBoundsException
{
Integer [] intArr={1,2,3,4,5};
System.out.println(intArr[5]);
}

   //overriding method throwSameException throwing same exception as overridden method is throwing.
public void throwSameException() throws StringIndexOutOfBoundsException
{

}

   public static void main(String[] args) {

  ExceptionHandlingWithOverriding objExpHand=new ExceptionHandlingWithOverriding();
  
  // Handling FileNotFoundException.
  try {
objExpHand.printFile();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException : "+e+" \n");
}
  
  //Handling ArrayIndexOutOfBoundsException.
  try {
  objExpHand.readArrayElements();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException : "+e);
}
 
          // Calling throwSameException method.
  objExpHand.throwSameException();
  
}

}

Output:









Sunday, 17 August 2014

Java Wrapper: Lexical order, dictionary order, alphabetical orde...

Java Wrapper: Lexical order, dictionary order, alphabetical orde...: The  lexicographic  or  lexicographical order  ( also known as  lexical order ,  dictionary order , alphabetical order  or  lexicographic more...

Java Wrapper: Generic method

Java Wrapper: Generic method: In method overloading , name of the method remain same but with different parameter and method is bounded to handle call with limited more...

Java Wrapper: Stack and it's important methods

Java Wrapper: Stack and it's important methods: Stack is a collection and it is like a bucket in nature, it works like a bucket to store or retrieve data. Only one end is open to push more...

Java Wrapper: Queue and it's important methods

Java Wrapper: Queue and it's important methods: Queue is a collection of objects. PriorityQueue is new with Java 5. The purpose of a PriorityQueue is to create a "priority-in, prior more...

Java Wrapper: Arrays utility class and it's method (sort, copyof...

Java Wrapper: Arrays utility class and it's method (sort, copyof...: Arrays utility class is provided in java.util package. It provides some utility methods to performs more operation with arrays like copy more...

Java Wrapper: Multiple way to Iterate HashMap

Java Wrapper: Multiple way to Iterate HashMap: Map is a collection of key and value pair. There are multiple way to iterate a map. In this code snippet, four ways to iterate a map are more...

Java Wrapper: Array To List and List to Array

Java Wrapper: Array To List and List to Array: Following code snippet contains some different way to convert array into List and List into array . package coreCollection; import more...

Java Wrapper: Access Specifier(public, protected, default and pr...

Java Wrapper: Access Specifier(public, protected, default and pr...: Access Specifier -:-   Access specifier defines the accessibility of classes , methods and variables. There are four types of access  more...

Java Wrapper: Exception Handling with Multiple Catch Blocks

Java Wrapper: Exception Handling with Multiple Catch Blocks: When a single try block throws multiple exception in the same hierarchy, in this case we can handle those exception with catch having more...

Java Wrapper: Method Overloading and Overriding

Java Wrapper: Method Overloading and Overriding: Method Overloading :-   It is a part of static polymorphism. Overloading means writing multiple methods with same name but with different more...

Method Overloading and Overriding



Method Overloading :-  It is a part of static polymorphism. Overloading means writing multiple methods with same name but with different parameters. In case of overloading return type of a method is not concerned, but sequence of parameter, number of parameter and type of parameter is concerned.

Following code snippet displays the demo for method overloading.


package coreCollection;

public class Overloading extends SuperClass {

//Method with no parameter.
public void show(){
System.out.println("call for show with out prms");
}

       //medhod for int parameter and look at the return type.
        public int show(int a){
System.out.println("Call for show with Int prm : "+a);
return a;
}
    
    //method with different type and number of parameter.
    public void show(long a, int b){
    System.out.println("Call for different type and number of parameter. : int : "+a+", long : "+b);
}
    
    //method with different sequence of parameter.
    public void show(int a,long b){
    System.out.println("Call for different sequence of parameter : int : "+a+", long : "+b);
    }
    
    // Overloading from SuperClass.
    public void display(String str){
System.out.println("Overloading from SuperClass : "+str);
}

    
public static void main(String[] args) {

Overloading oao=new Overloading();
//calling without parameter.
oao.show();

//calling of int type of parameter. int a=oao.show(2); System.out.println("value return from method with int type parameter : "+a);

//calling with int and long type parameter.
oao.show(2, 12l);

//calling with long and int type parameter.
oao.show(12l,2);

// calling SuperClass overloading method.
SuperClass sc=new Overloading();
((Overloading)sc).display("stringParam");

}

}

//Super Class
class SuperClass{

public void display(){
System.out.println("Super Class medhod.");
}
}

Output:










Method Overriding :- It is a part of dynamic polymorphism. Overriding means sub-class should contain method with the same name and parameters. Return type of method should be same or sub-class of the super-class's method's return type. Accessibility of overriding method should be higher than overriden method.


package coreCollection;

class SuperClass1{
//method having void return type and default access specifier.
void show(){
System.out.println("Super Class show method.");
}

//method having return type as number.
Number display(){
System.out.println("Super Class display method.");
return 1;
}
}

//Sub-class
public class Overriding extends SuperClass1{

 //access specifier is higher than super method.
   public void show(){
System.out.println("show method of sub-class.");  
   }
  
  // overriding method having return type as subtype of supermethod's return type.
  protected Integer display(){
System.out.println("display method of sub-class.");
return 2;
  } 


   public static void main(String[] args) {
    
  //calling methods of sub-class.
  Overriding ovr=new Overriding();
  ovr.display();
  ovr.show();
  
  //calling method of super-class.
  SuperClass1 sc=new SuperClass1();
  sc.display();
  sc.show();
  
  //calling method of sub-class with the reference of super-class.
  SuperClass1 ssc=new Overriding();
  ssc.display();
  ssc.show();

   }
}


Output : 


Saturday, 16 August 2014

Exception Handling with Multiple Catch Blocks


When a single try block throws multiple exception in the same hierarchy, in this case we can handle those exception with catch having Exception class only. But it is not a good idea and it's not a perfect way to handle exception. The perfect way is to maintain the hierarchy of exceptions. When ever you are required to perform such operation, first of all handle with the sub-class and then super-class and then more super-class of exceptions.

Following code snippet displays the same with three small demos.

public static void main(String[] args) {

  //demo 1 with fileNotfoundException.
File f=new File("abc.txt");
try {
FileReader fr=new FileReader(f);

} catch (FileNotFoundException fnfe) {
System.out.println("FileNotFoundException : "+fnfe);

}catch(IOException ioe){
System.out.println("IOException : "+ioe);

}catch (Exception e) {
System.out.println("Exception : "+e);
              }


    // demo 2 with ArrayIndexOutOfBoundsException.
try{
String [] strArr={"one","two","three","four"};
System.out.println(strArr[4]);

}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException : "+e);

}catch (IndexOutOfBoundsException ebe) {
System.out.println("IndexOutOfBoundsException : "+ebe);

}catch (Exception e) {
System.out.println("Exception : "+e);
}

 
 // demo 3 with StringIndexOutOfBoundsException.
try{
String str="one";
System.out.println(str.substring(4));

}catch(StringIndexOutOfBoundsException sibe){
System.out.println("StringIndexOutOfBoundsException : "+sibe);

}catch (IndexOutOfBoundsException ebe) {
System.out.println("IndexOutOfBoundsException : "+ebe);

}catch (Exception e) {
System.out.println("Exception : "+e);

}
   }

Output:


Access Specifier(public, protected, default and private)


Access Specifier -:-  Access specifier defines the accessibility of classes, methods and variables. There are four types of access specifier(public, protected, default, private) are provided in java programming language. By default, default is applied.

Public :- public means accessible and visible to every one in the package and outside the package. Classes, methods, constructors and variables can be accessed from every where.

Protected :- protected means accessible and visible to every one in the same package and only to sub-classes out side the package.

Default :- default is applied by default. It is package friendly. When we do not apply any access modifier than it is applied. It means accessible only in the same package.

Private :- private means accessible only to the same class. Methods, variables and constructors declared as private only visible to the same class.



Array To List and List to Array

Following code snippet contains some different way to convert array into List and List into array.



package coreCollection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArraytoList {

/**
* @param args
*/
public static void main(String[] args) {

String [] arr={"one","tow","three","four","five"};

/* Array To List. */

//first Way
List<String> ll=Arrays.asList(arr);
System.out.println(ll);

//Second Way
List<String> list=new ArrayList<String>();
for(String s:arr){
list.add(s);
}
System.out.println(list);

/* List To Array */

//First way.
String []strArr=(String[]) ll.toArray();
printMe(strArr);

   //Second way.
String [] stArr=new String[ll.size()];
for(int i=0;i<ll.size();i++){
stArr[i]=ll.get(i);
}
printMe(stArr);

}

/* generic method. */
private static <T> void printMe(T [] arr){
for(T s:arr){
         System.out.print(s+", ");
}
System.out.println();
}

}


Output:


Multiple way to Iterate HashMap


Map is a collection of key and value pair. There are multiple way to iterate a map. In this code snippet, four ways to iterate a map are displayed.


package coreCollection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class IterateMap {

/**
* @param args
*/
public static void main(String[] args) {

Map<Integer, String> map=new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");


//first way.
Set<Integer> keySet=map.keySet();
Iterator<Integer> itr=keySet.iterator();
while(itr.hasNext()){
Integer key=(Integer)itr.next();
System.out.println("value : "+map.get(key));
}
System.out.println("\n");


//second way.
Collection<String> col=map.values();
Iterator ir=col.iterator();
while(ir.hasNext()){
 System.out.println("value : "+ir.next());
}
System.out.println("\n");


//third way.
Set kySet=map.entrySet();
Iterator itrr=kySet.iterator();
while(itrr.hasNext()){
Map.Entry<Integer, String> entry=(Entry<Integer, String>) itrr.next();
System.out.println("Value : "+entry.getValue());
}
System.out.println("\n");


//Fourth way.
Set s=map.keySet();
List ll=new ArrayList(s);
for(int i=0;i<ll.size(); i++){
System.out.println("value : "+map.get(ll.get(i)));
}
System.out.println("\n");
}
}

Output:



Collections utility class and it's methods(sort, fill, addAll, binarySearch, frequency, min, max, copy etc.)

Collections utility class is provided in java.util package. It is used to perform some more operation with java collections. It's methods like sort, fill, addAll, binarySearch, frequency, min, max, replaceAll, reverse, swap etc are provides respected specific functionality with collections.
This article uses some important methods of Collections utility class.

Some important methods are used in this code snippet.

public static void main(String[] args) {

List<String> list=new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
list.add("five");

//Add some more elements in the list
        Collections.addAll(list, "hi","fg");
        System.out.println("added some more elements in the list \n "+list);

       //Sort element of a list
        Collections.sort(list);
        System.out.println("sorted list. \n "+list);
        
        //search any element in the list.
        int a=Collections.binarySearch(list, "hi");
        System.out.println("search element get index. \n "+a);
        
        //get list of a particular type, but this type should be available in the list.
        List ll;
        ll = Collections.checkedList(list, String.class);
        System.out.println(ll);
        
       // Copy a list elements in another list.
        List<String> list2=new ArrayList<String>();
list2.add("apple");
list2.add("orange");
list2.add("mango");
        Collections.copy(ll, list2);
        System.out.println(ll);
        
        //Create an empty object of enumeration and Iterator, available but not required.
        Collections.emptyEnumeration();
        Collections.emptyIterator();
        
        //all are used to create a new object of particular type.
        Collections.emptyList();
        Collections.emptyListIterator();
        Collections.emptyMap();
        Collections.emptySet();
        
        //check the frequency of a particular element.
        int aa= Collections.frequency(list2, "mango");
        System.out.println(aa);
       
        //replace all elements of this list with a single object.
        Collections.fill(list2, "newOne");
        System.out.println(list2);
        
       //get last element of list. 
       System.out.println(Collections.max(list));
       
       //get first element of list.
       System.out.println(Collections.min(list));
       
       //replace any element with another value.
       Collections.replaceAll(list, "apple", "grapes");
       System.out.println(list);
       
       //Swap element of list with each other.
       Collections.swap(list, 2, 0);
       System.out.println(list);
      
       //List in reverse order.
       Collections.reverse(list);
       System.out.println(list);
       
       //check if any element is common in both list.
       System.out.println(Collections.disjoint(list2, ll));
       
}

Output: