Tuesday, 16 September 2014

VARIABLE ARGUMENTS - VARARGS -JAVA 5 FEATURE

VARIABLE ARGUMENTS:

It is a feature introduced in Java version 5. It is very handy feature in some situation where you don't know the exact number of arguments for methods.


It is generally known as VARARGS. It is represented by a symbol
ellipsis(...)

example:


class CountMarks{

//create a static method inorder to access in the main method

static void add(int... params){
          int result=0;
          for(int i:params){
             result=result+i;
          }
          System.out.println("sum of marks: "+result);
      }
    public static void main(String args[]){
        m(10);
        m(10,20,30,23,23,23,23,23);
    }
    } 


output:

sum of numbers: 10
sum of numbers: 175



Rules for varargs:


  1.  There should be only one variable argument in a method.
  2.  The variable argument must be the last argument.
Violating these rules leads to COMPILE TIME ERRORS;

Examples: 

Legal:

void sumUp(int... x) {}
//expects from 0 to many ints as parameters

void sumUp(char chr,int... x) {}
//expects first a char, then 0 to many ints

void sumUp(Salary... sal) {}
//expects 0 to many salary objects


ILLEGAL:

void sumUp(int x...) { }
 //Bad syntax

void sumUp(int... x,char... y) {}
 //too many varargs - rule 1 violated

void sumUp(String... s,char b){} 
// var-arg must be last argument-rule 2 
//violated 


Note:  In the above example, We can pass as many numbers as we need, to do the same thing earlier we used to do method overloading. 

JAVA EXCEPTION - IllegalArgumentException

Java Exception -> IllegalArgumentException

IllegalArgumentException is a Runtime Exception.

Class Hierarchy is as follows: 






 IllegalArgumentException thrown to indicate that a method has been passed an Illegal Argument.


Example:

public class Voters {

 String voter_name;
 int voter_age;


//u can throw this exception like this
//rule: age should be > 18 years

 private void checkAge(int voter_age){
     if(voter_age<18)
     {
      throw new IllegalArgumentException();
     }
 }
 //constructor
 public Voters(String voterName,
                 String voterAge) {
   checkAge(voterName,voterAge);
   voter_name=voterName;
   voter_age=voterAge;
 }

           .
           .
           .

  Like this you can throw this exception.



Monday, 15 September 2014

HOW TO SEND MAIL USING JAVAMAIL API

JAVAMAIL API

In order to send e-mail using javamail api,
you need an SMTP server, which is responsible for send your email.

In this example, I am using a gmail SMTP server configuration. In fact, we can also use any other companies SMTP server such as yahoo or a JangoSMTP server.

Through out the example, I am gonna use different javax.mail.* and javax.mail.internet.* package classes.

To use these classes in your program, download the required jars such as mail.jar, activation.jar


Let's see some of the classes used javax.mail.* package & javax.mail.internet.* package classes used in this example.


javax.mail.Session 

javax.mail.Message

javax.mail.Address

javax.mail.Authenticator

javax.mail.Transport

javax.mail.Store

javax.mail.Folder

javax.mail.internet.MimeMessage

javax.mail.internet.InternetAddress


Note:

change the code in these string with your
own details
image-file-location
sender-gmail-address-password
sender-gmail-address
receiver-gmail-address

Example:

package com.javamail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



public class SimpleMail {


public static void main(String[] args) {

String mail_to ="receiver-gmail-address";
String mail_from ="sender-gmail-address";


//These are details of SMTP server - gmail smtp server 
//and sender gmail authentication details

final String username="sender-gmail-address";
final String password="sender-gmail-address-password";  
String host="smtp.gmail.com"; 

Properties props=new Properties();

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");

/*here are details of Jango SMTP server - need to register 
 in JangoSMTP. In this example I am using gmail smtp server 
 so - just commented Jango details But you can try this 
final String username="jangosmtp-username";
final String password="jangosmtp-password";  
String host="relay.jangosmtp.net";
props.put("mail.smtp.port", "25");*/

/*In order to use javamail api need to get the 
 Session object proper sender credentials -
 username & password needs to be given
otherwise, transfer of mail - fails*/
Session session=Session.getInstance(props, 
 new javax.mail.Authenticator() { 
  protected PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(username,password);
  }
 });
 
 try {
  //create a default MimeMessage object.
 
 //Message models the message that you want to send
 //Message is an abstract class, so MimeMessage 
 //class provide the implementation
 Message message=new MimeMessage(session);
 
 message.setFrom(new InternetAddress(mail_from));
 
 //set the receviers and type of sending
 
 //you can send as cc: bcc:
 //use Message.RecipientType.CC or Message.RecipientType.BCC
 message.setRecipients(Message.RecipientType.TO, 
   InternetAddress.parse(mail_to));
 
 //set subject   
 message.setSubject("Testing mail through Java");
 
 /*set the message body- a message body can be multipart message
    this means we can send mail text and attachment also*/
 BodyPart messageBodyPart = new MimeBodyPart();
 messageBodyPart.setText("This is the message body ");
 
 
 Multipart multipart =new MimeMultipart();
 
 //adding message body part - part1
 multipart.addBodyPart(messageBodyPart);
 
 //adding attachment -part2
 messageBodyPart=new MimeBodyPart();
 
 String filename="image-file-location";
 
 DataSource source=new FileDataSource(filename);
 messageBodyPart.setDataHandler(new DataHandler(source));
 messageBodyPart.setFileName(filename);
 
 multipart.addBodyPart(messageBodyPart);
 
 //send complete message parts
 message.setContent(multipart);   

 Transport.send(message);

 //a confirmation to your mail program
 System.out.println("Sent message Successfuly");
 
} catch (MessagingException e) {
 throw new RuntimeException(e);
}
}

}



Saturday, 13 September 2014

Two Ways of Accessing Enterprise Beans -JEE 7

Two ways to get an enterprise bean's Instance:

Clients of an enterprise beans obtains a reference to an instance of an enterprise bean through 


  • Dependency Injection
  • JNDI lookup
Dependency Injection- Java Annotations

Supported for Clients running in a J2EE server managed environment, JavaServer faces web applications, JAX-RS web services,other enterprise beans or J2EE application clients.

Dependency injection using javax.ejb.EJB 

JNDI- Java Naming and Directory Interface

Applications running out of J2EE server such as J2SE application can get an instance for the enterprise bean through a explicit JNDI lookup.

JNDI supports a global syntax for all J2EE Components to perform explicit lookup.



Types of Enterprise Beans J2EE-7





Enterprise Beans(Jee-7)



An Enterprise Bean is a server-side component that encapsulates business logic.

Types of Enterprise Beans:



There are 2 types of Enterprise beans:



  • Session Bean 
  • Message-Driven Bean
    A session Bean is used to perform a task for a client optionally as a web service, which is again classified as 

  1. Stateless session bean
  2. Stateful session bean
  3. Singleton session bean

1. stateless session bean:

A stateless session bean does not maintain a conversational state with the client. The bean's instance variables may contain a state but only during the method invocation.

use stateless session bean if you want the bean to perform a common task for all the clients. For example, sending an email for conforming a shopping order.

2. Stateful session bean:

A stateful session bean maintains a conversational state with a specific client during the session, until client terminates the session. Once the client terminates the session then the state is no longer maintained.

use stateful session bean if a user/client information is needed across methods invocations. Stateful session beans also manages the workflow of several enterprise beans.

A stateful session bean cannot implement a web service.

3. Singleton session bean:

A singleton session bean is instantiated once per application and exists for a life-cycle of the application.

Applications implementing singleton session bean is allowed to be instantiated at the application start-up, which performs any initialization tasks required for the application. It can also be used at the shutdown of the application since it can be available and accessed through out the life-cycle of the application. 

A singleton can implement a web service.

Message-Driven Beans: 

Message-Driven Beans listens for messaging types, such as Java Messaging Service API.