package sendmail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username@gmail.com","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-address@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-address@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Testing through SSL");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Thursday, February 27, 2014
Sending e-Mail with GMail using SSL connection
Sending e-Mail with GMail using TLS
To run this application you need mail.jar library. Download JavaMail.jar of new version available here and extract the file, where you will mail.jar file. Add mail.jar to the CLASSPATH.
package sendmail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author sudeep
*/
public class SendMailTLS {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session;
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-address.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-address@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Wednesday, February 26, 2014
Implementing Sinlge Linked List in Java
Linked List :
Linked list is a dynamic data structure whose length can be increased or decreased at run time.How Linked lists are different from arrays? Consider the following points :
- An array is a static data structure. This means the length of array cannot be altered at run time. While, a linked list is a dynamic data structure.
- In an array, all the elements are kept at consecutive memory locations while in a linked list the elements (or nodes) may be kept at any location but still connected to each other.
When to prefer linked lists over arrays?
Linked lists are preferred mostly when you don’t know the volume of data to be stored. For example, In an employee management system, one cannot use arrays as they are of fixed length while any number of new employees can join. In scenarios like these, linked lists (or other dynamic data structures) are used as their capacity can be increased (or decreased) at run time (as an when required).How linked lists are arranged in memory?
A node class in Java can be created as :
class Node
{
int data;
Node link;
}
Operations on Single Linked List :
- Insert : Add/Insert node into the list.
- Delete : Delete a node/element from the list
- Search : Search for an element in the list
- Display : Display the list
- Sort : Sort the list.
- Length : Finding the length of the list i.e., number of elements in the list.
import java.util.Scanner;
interface SllAdt{
public void insert();
public void delete();
public void display();
public int len();
public void search();
public void sort();
}
class SNode{
int data;
SNode link;
}
public class SLL extends SNode implements SllAdt {
SNode first;
Scanner s=new Scanner(System.in);
public SLL(){
first=null;
}
public void insert(){
System.out.println("Enter the position to insert a node: ");
int pos=s.nextInt();
System.out.println("Enter the data into a node");
int ele=s.nextInt();
SNode p=new SNode();
p.data=ele;
p.link=null;
if(pos<&eq;1||pos>len()+1)
System.out.println("Invalid position and insertion is not possible");
else if(pos==1){
p.link=first;
System.out.println("found at position 1 and p.link is :"+p.link+" and first is :"+first);
first=p;
System.out.println("now first is :"+first);
System.out.println("Entered position is(1st):"+pos);
}
else{
SNode temp;
temp=first;
for(int i=1;i<pos-1;i++)
temp=temp.link;
p.link=temp.link;
temp.link=p;
System.out.println("ENtered position is:"+pos);
}
}
public void delete(){
System.out.println("Enter the positon to delete a node:");
int pos=s.nextInt();
SNode p,temp;
if(pos<1||pos>len()+1)
System.out.println("Invalid position and deletion is not possible");
else if(pos==1){
temp=first;
first=first.link;
System.out.println("Deleted element is :"+temp.data);
}
else{
temp=first;
for(int i=1;i < pos-1;i++)
temp=temp.link;
p=temp.link;
temp.link=p.link;
System.out.println("Deleted element is :"+p.data);
}
}
public void display(){
SNode temp;
if(first==null)
System.out.println("Linked list is empty:");
else{
System.out.println("List of elements:");
System.out.print("First->");
for(temp=first;temp!=null;temp=temp.link)
System.out.print(temp.data+"-->");
System.out.print("End");
}
}
public int len(){
int count=0;
SNode temp;
for(temp=first;temp!=null;temp=temp.link)
count++;
return count;
}
public void search(){
System.out.println("Enter the element to search :");
int ele=s.nextInt();
int pos=1;
SNode temp;
for(temp=first;temp!=null;temp=temp.link){
if(temp.data==ele)
System.out.println("Element "+ele+" is found at position: "+pos);
else
System.out.println("Element "+ele+" is not found");
pos++;
}
}
public void sort(){
SNode temp1,temp2;
for(temp1=first;temp1!=null;temp1=temp1.link)
for(temp2=temp1.link;temp2!=null;temp2=temp2.link)
{
if(temp1.data>temp2.data)
{
int t=temp1.data;
temp1.data=temp2.data;
temp2.data=t;
}
}
}
public static void main(String[] args){
System.out.println("Single Linked List ADT");
Scanner s=new Scanner(System.in);
SLL s1=new SLL();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("\nStack Operations:\n1. Insert 2. Delete 3. Display 4. Length 5. Search 6. Sort 7. Exit :");
System.out.println("Enter the option :");
int opt=s.nextInt();
switch(opt){
case 1:s1.insert();break;
case 2:s1.delete();break;
case 3:s1.display();break;
case 4: System.out.println("Length of SLL is :"+s1.len());break;
case 5:s1.search();break;
case 6:s1.sort();break;
case 7:System.exit(0);
default:System.out.println("Invalid option");
}
}
}
}
Introduction to Web Services!
What are Web Services?
Web service is a way of communication that allows interoperability between different applications on different platforms, for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.
Web services are browsers and operating system independent service, which means it can run on any browser without the need of making any changes. Web Services take Web-applications to the Next Level.
The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”
A web service has special behavioral characteristics:XML Based
By using XML as the data representation layer for all web services protocols and technologies that are created, these technologies can be interoperable at their core level. As a data transport, XML eliminates any networking, operating system, or platform binding that a protocol has.
Loosely coupledA consumer of a web service is not tied to that web service directly; the web service interface can change over time without compromising the client's ability to interact with the service. A tightly coupled system implies that the client and server logic are closely tied to one another, implying that if one interface changes, the other must also be updated. Adopting a loosely coupled architecture tends to make software systems more manageable and allows simpler integration between different systems.
Coarse-grainedObject-oriented technologies such as Java expose their services through individual methods. An individual method is too fine an operation to provide any useful capability at a corporate level. Building a Java program from scratch requires the creation of several fine-grained methods that are then composed into a coarse-grained service that is consumed by either a client or another service. Businesses and the interfaces that they expose should be coarse-grained. Web services technology provides a natural way of defining coarse-grained services that access the right amount of business logic.
Ability to be synchronous or asynchronousSynchronicity refers to the binding of the client to the execution of the service. In synchronous invocations, the client blocks and waits for the service to complete its operation before continuing. Asynchronous operations allow a client to invoke a service and then execute other functions. Asynchronous clients retrieve their result at a later point in time, while synchronous clients receive their result when the service has completed. Asynchronous capability is a key factor in enabling loosely coupled systems.
Supports Remote Procedure Calls (RPCs)Web services allow clients to invoke procedures, functions, and methods on remote objects using an XML-based protocol. Remote procedures expose input and output parameters that a web service must support. Component development through Enterprise JavaBeans (EJBs) and .NET Components has increasingly become a part of architectures and enterprise deployments over the past couple of years. Both technologies are distributed and accessible through a variety of RPC mechanisms. A web service supports RPC by providing services of its own, equivalent to those of a traditional component, or by translating incoming invocations into an invocation of an EJB or a .NET component.
Supports document exchangeOne of the key advantages of XML is its generic way of representing not only data, but also complex documents. These documents can be simple, such as when representing a current address, or they can be complex, representing an entire book or RFQ. Web services support the transparent exchange of documents to facilitate business integration.
Web Services Technologies
Simple Object Access ProtocolSOAP is a communication protocol which is used to exchange messages between applications over the Internet, irrespective of the platforms and the technology the applications are built on.
Web Service Description Language (WSDL)WSDL is an XML technology that describes the interface of a web service in a standardized way. WSDL standardizes how a web service represents the input and output parameters of an invocation externally, the function's structure, the nature of the invocation (in only, in/out, etc.), and the service's protocol binding. WSDL allows disparate clients to automatically understand how to interact with a web service.
Universal Description, Discovery, and Integration (UDDI)It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery. UDDI provides a worldwide registry of web services for advertisement, discovery, and integration purposes.
Monday, February 24, 2014
Dequeue (Double Ended Queue) using Arrays ADT
Double Ended Queue :
Program :
package adsa;
import java.util.Scanner;
interface DQArrADT{
void linsert();
void rinsert();
void ldelete();
void rdelete();
void display();
}
public class DQArr implements DQArrADT{
int dq[],size,front,rear;
Scanner s=new Scanner(System.in);
public DQArr() throws Exception
{
System.out.println("Enter the Deque size");
size=s.nextInt();
dq=new int[size];
front=-1;rear=-1;
}
public void linsert()
{
if(((front==0)&&(rear==dq.length-1))||(rear==front-1))
System.out.println("Deque is full");
else if(front==-1)
{
front=0;
rear=0;
}
else if(front==0)
front=(dq.length-1);
else
front=front-1;
System.out.println("Enter the element into deque at left end :");
int item=s.nextInt();
dq[front]=item;
}
public void rinsert()
{
if(((front==0)&&rear==dq.length-1)||(rear==front-1))
System.out.println("Deque is full");
else if(front==-1)
{
front=0;
rear=0;
}
else if(rear==dq.length-1){
rear=0;
System.out.println("rear is changed to "+rear);}
else
rear=rear+1;
System.out.println("Enter the element into the Deque at right end :");
int item=s.nextInt();
dq[rear]=item;
}
public void ldelete()
{
if(front==-1)
System.out.println("Deque underflow");
else
{
System.out.println("Deleted item at leftend is :"+dq[front]);
if(front==rear)//one element
{
front=-1;rear=-1;
}
else if(front==dq.length-1)
front=0;
else front=front+1;
}
}
public void rdelete(){
if(front==-1)System.out.println("Deque underflow");
else
{
System.out.println("Deleted item at right end :"+dq[rear]);
if(front==rear){//one element
front=-1;rear=-1;
}
else if(rear==0){
rear=dq.length-1;
}
else rear=rear-1;
}
}
public void display()
{
if(front==-1)
System.out.println("Deque empty");
System.out.println("Deque elements are:");
if(front<=rear)
{
for(int i=front;i<=rear;i++)
System.out.print(" "+dq[i]);
}
else{
for(int i=front;i<dq.length;i++)
System.out.print(" "+dq[i]);
for(int i=0;i<=rear;i++)
System.out.print(" "+dq[i]);
}
}
public static void main(String args[]) throws Exception{
System.out.println("Linear Dequeu Array ADT");
Scanner s=new Scanner(System.in);
DQArr d=new DQArr();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("Deque operations :");
System.out.println("1. DQ LInsert 2. DQ RInsert 3. DQ LDelete 4. DQ RDelete 5. Display 6.Exit :");
System.out.println("Enter the option :");
int opt=s.nextInt();
switch(opt){
case 1: d.linsert();
break;
case 2:d.rinsert();
break;
case 3:d.ldelete();
break;
case 4:d.rdelete();
break;
case 5:d.display();
break;
case 6:System.exit(0);
default:System.out.println("Invalid option!!!");
}
System.out.println("Do you want to continue(y/N) :");
ch=s.next();
}
}
}
Sunday, February 23, 2014
Enhanced for loop (for each loop) in Java
for (data_type variable: array_name)Here array_name is the name of array.
Java enhanced for loop integer array
public static void main(String[] args)
{
int even[]= { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
for(int t: even)
{
System.out.println(t);
}
}
}
Circular Queue ADT using arrays in Java!
Circular Queue :
- In Circular Queue the last node is connected back to the first node to make a circle.
- Elements are added at the rear and deleted at front of the queue.
- Both the front and rear pointers point to the beginning of the array.
- Circular Queue is also called as Ring Buffer.
- Items can be inserted and deleted from a queue in O(1) time.
Circular Queue can be created in three ways they are :
- Using arrays (In this post)
- Using single linked list
- Using double linked list
Program :
interface CQArrAdt{
void insert();
void delete();
void display();
}
class CQArr1 implements CQArrAdt{
int cq[],size,front,rear;
Scanner s=new Scanner(System.in);
public CQArr1()throws Exception{
System.out.println("Enter the size of the Circular Queue :");
size=s.nextInt();
cq=new int[size];
front=-1;rear=-1;
}
@Override
public void insert() {
if(((front==0) && (rear==cq.length-1))||(rear==front-1)){
System.out.println("Circular Queue is full!!!");
}
else if(front==-1){front=0;rear=0;}
else if(rear==cq.length-1)rear=0;//rotate/override cq
else
rear++;
System.out.println("Enter the element into the circular queue :");
int ele=s.nextInt();
cq[rear]=ele;
System.out.println("At this point rear= "+rear++);
}
@Override
public void delete() {
if(front==-1)
System.out.println("CQ is underflow!!");
else
{
System.out.println("Deleted item is :"+cq[front]);
if(front==rear)//array contains only one element
{
front=rear=-1;
}
else if(front==cq.length-1){//rotate in the array!!!
front=0;
}
else
front--;
}
}
@Override
public void display() {
if(front==-1){
System.out.println("CQ is empty");
}
else if(front<=rear){
for(int i=front;i<=rear;i++)
System.out.print(" a"+cq[i]);
}
else{
for(int i=front;i<cq.length;i++)
System.out.print(" b"+cq[i]);
for(int i=0;i<=rear;i++)
System.out.print(" c"+cq[i]);
}
}
}
public class CQArr{
public static void main(String args[]) throws Exception{
System.out.println("Circular Queue ADT");
Scanner s=new Scanner(System.in);
CQArr1 c=new CQArr1();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("Circular Queue operations\n1. Insert 2. Delete 3. Display 4. Exit\nEnter your choice :");
int opt=s.nextInt();
switch(opt){
case 1:c.insert();break;
case 2:c.delete();
break;
case 3:c.display();break;
case 4:System.exit(0);
default :System.out.println("Invalid operation!!!");
}
System.out.println("Do you want to continue (y/N):");
ch=s.next();
}
}
}
Linear Queue ADT using Arrays!
Queue :
A queue is a linear collection, where something to be added to the queue must be placed at the end of the queue. Items are removed from the queue from the front. To keep with the analogy, when you walk into the bank you go to the end of the queue. When the teller is ready to help the next person, the person at the beginning of the queue is removed from the queue. Each person then moves one position closer to the beginning of the queue. Eventually, you will be the first person in the queue and the teller will call you up causing you to be removed from the queue.A queue is referred to as a FIFO data structure: First In, First Out.
Operations on Queue :
Applications :
- For implementing any "natural" FIFO service, like telephone enquiries, reservation requests, traffic flow, etc.
- For implementing any "computational" FIFO service, for instance, to access some resources. Examples: printer queues, disk queues, etc.
- For searching in special data structures (breadth-first search in graphs and trees).
- For handling scheduling of processes in a multitasking operating system.
Program :
package adsa;
import java.util.Scanner;
interface LQueADT{
void insert() throws Exception;
void delete();
void display();
}
public class QueueArr implements LQueADT {
int q[],size;
int front,rear;
Scanner s=new Scanner(System.in);
public QueueArr() throws Exception {
System.out.println("Enter the size of the Linear Queue :");
size=s.nextInt();
q=new int[size];
front=-1;rear=-1;
}
public void insert() throws Exception {
if(rear==q.length-1){
System.out.println("Linear Queue overflow");
}
else{
System.out.println("Enter the element into the queue :");
int ele=s.nextInt();
rear++;
q[rear]=ele;
if(front==-1) front=0;
}
}
public void delete() {
if(front==-1 || front>rear){
System.out.println("Linear Queue underflow");
}
else{
System.out.println("Deleted Element is :"+q[front]);
front++;
}
}
public void display() {
if(front==-1 || front>rear){
System.out.println("Linear Queue is Empty");
}
else{
System.out.println("Linear Queue elements are....");
for(int i=front;i<=rear;i++)
System.out.println(""+q[i]);
}
}
public static void main(String args[]) throws Exception{
System.out.println("Linear Queue Array ADT ");
Scanner s=new Scanner(System.in);
QueueArr qa=new QueueArr();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("Linear Queue operations :\n1. Insert 2. Delete 3. Display 4. Exit\nEnter the option :");
int opt=s.nextInt();
switch(opt){
case 1:qa.insert();break;
case 2:qa.delete();break;
case 3:qa.display();break;
case 4:System.exit(0);
default : System.out.println("Invalid Option");
}
System.out.println("Do you want to continue (y/N):");
ch=s.next();
}
}
}
Stack Program using Arrays in Java!
Stack :
A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: pushthe item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.Applications :
- The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack.
- Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack.
- Infix to Postfix conversion.
Operations :
- Push : To push an element into the stack.
- Pop : To pop an element from the stack.
- Peek : Shows the top most element in the stack.
- isEmpty : Determines whether the stack is empty or not.
Java Program!
package adsa;
import java.util.Scanner;
interface StackAdt{
void push() throws Exception;
void pop();
void display();
}
public class StackArr implements StackAdt{
int top;
int stack[];
int size;
Scanner s=new Scanner(System.in);
public StackArr() throws Exception{
System.out.println("Enter the stack size :");
size=s.nextInt();
stack=new int[size];
top=-1;
}
public void push() throws Exception{
if(top==stack.length-1)
System.out.println("Stack is full!!");
else{
System.out.println("Enter the element into the stack :");
int ele=s.nextInt();
top++;
stack[top]=ele;
}
}
public void pop(){
if(top==-1)
System.out.println("Stack underflow!!");
else{
System.out.println("Popped item is :"+stack[top]);
top--;
}
}
public void display(){
System.out.println("The elements in the stack are...");
if(top==-1){
System.out.println("No elements to display!!");
}else
{
for(int i=top;i>=0;i--){
System.out.print(stack[i]);
}
}System.out.println();
}
public static void main(String args[])throws Exception{
Scanner s=new Scanner(System.in);
StackArr st=new StackArr();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("1. Push 2. Pop 3. Display 4. Exit\n Enter the option :");
int opt=s.nextInt();
switch(opt){
case 1:st.push();
break;
case 2: st.pop();
break;
case 3:st.display();
break;
case 4:System.exit(0);
default:System.out.println("Invalid input");
}
System.out.println("Do you want to continue (y/N):");
ch=s.next();
}
}
}

