Kontera

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, February 21, 2014

Simple Method Sending Email using JavaMail API

package javamail;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class JavaMail {   
  //From address
String d_email = "fromUsername@gmail.com",
            d_password = "password", //your email password
            d_host = "smtp.gmail.com",
            d_port = "465",
            m_to = "toUsername@gmail.com", // Target email address
            m_subject = "Testing",
            m_text = "Hey, this is a test email.";
   
    public JavaMailDemo() {
        Properties props = new Properties();
        props.put("mail.smtp.user", d_email);
        props.put("mail.smtp.host", d_host);
        props.put("mail.smtp.port", d_port);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        //props.put("mail.smtp.debug", "true");
        props.put("mail.smtp.socketFactory.port", d_port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);    
            MimeMessage msg = new MimeMessage(session);
            msg.setText(m_text);
            msg.setSubject(m_subject);
            msg.setFrom(new InternetAddress(d_email));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
            Transport.send(msg);
        } catch (Exception mex) {
            mex.printStackTrace();
        }
    }
  
    public static void main(String[] args) {
        JavaMail blah = new JavaMail();
    }
 
    private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(d_email, d_password);
        }
    }
}

Thursday, January 23, 2014

Java Code to Copy eMail from One Folder to Another in Gmail

The following java code copies the eMails from one folder to another folder in gmail.

Steps

  1. First create a new label in gmail by clicking the manage label link
  2. Create new label(Name of the source folder)
  3. Give the name of new label in source folder(eg:PHISH) place in the code
  4. Run the code  











Libraries Required :- JavaMail Download  

Source Code
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

/**
 *
 * @Sarju
 */
public class MoveMailToFolder {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            //eMail Authentication
            store.connect("imap.gmail.com", "username@gmail.com", "password");
            Folder inbox = store.getFolder("INBOX");//Source folder
            inbox.open(Folder.READ_WRITE);
            System.out.println("Opened source...");
            Folder spam = store.getFolder("PHISH"); // Destination folder
            spam.open(Folder.READ_WRITE);
            //Get the latest message
            Message[] msgs = inbox.getMessages(inbox.getMessageCount()-inbox.getUnreadMessageCount(),inbox.getMessageCount());
            inbox.copyMessages(msgs, spam);
            System.out.println("Copied messages...");
            inbox.close(false);
            store.close();
            } catch (Exception mex) {
        }
    }
}

Sunday, March 10, 2013

The Cigarette Smokers Problem

Multithreading - Multiprocessor operating systems
The Cigarette Smokers Problem
Consider a simulation with three smoker threads and one agent thread. Each
smoker continuously makes a cigarette and smokes it. But to make a cigarette, a
smoker needs three ingredients: tobacco, paper, and matches. One of the smoker
threads has only paper, another has only tobacco, and the third has only matches.
The agent thread has an infinite supply of all three materials. The three smoker
threads are initially blocked. The agent places two randomly chosen (different)
ingredients on the table and unblocks the one smoker who has the remaining
ingredient. The agent then blocks. The unblocked smoker removes the two
ingredients from the table, makes a cigarette, and smokes it for a random amount of
time, unblocking the agent on completion of smoking the cigarette. The agent then
puts out another random two of the three ingredients, and the cycle repeats.
Write a multi-class multithreaded Java program that uses a monitor to
synchronize the agent thread and the three smoker threads. Do not mechanically
translate semaphore code into monitor code! The agent thread executes in an
agent object created from an agent class. Each smoker thread executes in a smoker
object. All smoker objects are created from one smoker class whose constructor is
used to specify the ingredient possessed by the smoker object. A driver class with a
main method constructs the objects and starts the threads. Use a single monitor
object instantiated from a class Control for synchronization. Each of the four
threads invokes a synchronized monitor method for its synchronization. No
semaphores are allowed. No synchronized blocks are allowed, only synchronized
methods. No busy waiting is allowed. No calls to nap inside a synchronized method
are allowed (do not nap while holding the monitor object's lock, that is, while inside
a synchronized method or while inside a method called by a synchronized method).
Source Code:
/*
Cigarette Smoker's Problem Solution using java
Author : Sarju
Date: 10-03-2013
*/
import java.util.ArrayList;
import java.util.Random;
class CigaretteSmokersProblem {

    public static void main(String[] args) {
        table smokingtable = new table();

        agent controlAgent = new agent(smokingtable);

        controlAgent.start();

        for (int i = 0; i < 3; i++)
        {
            // each smoker-thread gets the controlAgent, so the thread can wake up the agent and we don't have to do notifyAll();
            smoker smokerThread = new smoker(smokingtable, i, "Smoker " + Integer.toString(i+1), controlAgent);
            smokerThread.start();
        }
    }
}

class smoker extends Thread {

    private table smokingtable = new table();
    private String ingredient;
    private int ingredientNumber;
    private agent controlAgent;

    public smoker(table pSmokingtable, int pIngredientNumber, String pName, agent pAgent)
    {
        // only save the number of the ingredient, we'll get the ingredient's name while the thread is running
        ingredientNumber = pIngredientNumber;
        this.smokingtable = pSmokingtable;
        setName(pName);
        controlAgent = pAgent;
    }

    @Override
    public void run()
    {
        while(true)
        {
            ingredient = smokingtable.getSmokerIngredient(ingredientNumber);

            if (!smokingtable.hasIngredient(ingredient) && !smokingtable.isEmpty())
            {
                System.out.println(getName() + " has " + ingredient + ".");
                try {
                    doSmoke();
                    System.out.println(getName() + " tells the agent to start the next round.");
                    // the thread tells the agent to continue
                    controlAgent.wake();
                } catch (Exception e) {}
            }
        }
    }

    public synchronized void doSmoke() throws Exception
    {
        System.out.println(getName() + " rolls the cigarette.");
        Thread.sleep(2500);
        System.out.println(getName() + " smokes.");
        Thread.sleep(2500);
        System.out.println(getName() + " has finished.");
    }

  }

class agent extends Thread {

    private table smokingtable;

    public agent(table pSmokingtable)
    {
        smokingtable = pSmokingtable;
    }

    @Override
    public void run()
    {
        while(true)
        {
            try {
                Thread.sleep(5000);
            } catch (Exception e) {}
            smokingtable.setAgentIngredients();
            // this triggers the smoker-threads to look at the table
            System.out.println("\n");
            System.out.println("The agents puts " + smokingtable.getAgentIngredients() + " on the table.");
            // pause the agent while one smoker thread is running
            pause();
        }
    }

    public synchronized void wake()
    {
        try
        {
            notify();
        } catch(Exception e){}
    }


    public synchronized void pause()
    {
        try
        {
            this.wait();
        } catch (Exception e) {}
    }

   
}

/*Class for creating table*/
class table {
    //Variables for storing ingredients(tabacco,paper,matches)
    private ArrayList allIngredients  = new ArrayList();
    private ArrayList agentIngredients = new ArrayList();

    public table()
    {
        allIngredients .add("tabacco");
        allIngredients .add("paper");
        allIngredients .add("matches");
    }
    /*Function for setting two ingredients randomly*/
    public void setAgentIngredients()
    {
        Random random = new Random();

        agentIngredients.clear();

        ArrayList copyAllElements = (ArrayList) allIngredients .clone();

        int ingredient1 = random.nextInt(copyAllElements.size());
        agentIngredients.add(copyAllElements.get(ingredient1));

        copyAllElements.remove(ingredient1);
        int ingredient2 = random.nextInt(copyAllElements.size());
        agentIngredients.add(copyAllElements.get(ingredient2));
    }
    /*Function for checking weather the table is empty*/
    public boolean isEmpty()
    {
        return (agentIngredients.size() == 0);
    }
    /*Function for getting two ingredients that
    are set previously by the function setAgentIngredients()*/
    public synchronized String getAgentIngredients()
    {
        notifyAll();
        return agentIngredients.toString();
    }
    /*Function for getting the ingredient
    with the corresponding smoker*/
    public synchronized String getSmokerIngredient(int pIngredient)
    {
        try {
            this.wait();
        } catch (Exception e) {}
        return allIngredients .get(pIngredient);
    }
    /*Function for Checking the smoker has the same ingredient
    as in the table if so smoking is is not possible*/
    public boolean hasIngredient(String ingredientName)
    {
        return (agentIngredients.contains(ingredientName));
    }

    public synchronized void pause()
    {
        try {
            this.wait();
        } catch (Exception e) {}
    }
}

Sunday, March 3, 2013

Semaphores - Multiprocessor operating systems using Java

/*PROGRAM 1 – Semaphores - Multiprocessor operating systems
Assume there are three processes: Pa, Pb, and Pc. Only Pa can output
the letter A, Pb B, and Pc C.
Utilizing only semaphores (and no other variables) the processes are
synchronized so that the output satisfies the following conditions:
a) A B must be output before any C's can be output.
b) B's and C's must alternate in the output string, that is, after the
first B is output, another B cannot be output until a C is output.
Similarly, once a C is output, another C cannot be output until a B is output.
c) The total number of B's and C's which have been output at any given point in the output
string cannot exceed the number of A's which have been output up to that point.
Examples
AACB -- invalid, violates a)
ABACAC -- invalid, violates b)
AABCABC -- invalid, violates c)
AABCAAABC -- valid
AAAABCBC -- valid
AB -- valid*/

/*AUTHORS: Sarju S, Nidhin AS
Date: 3rd March 2013*/
class ABC {
    int aCount=0;//Variable used to ensure the third rule
    boolean  isPrintBC= false;//Used to ensure the second rule
    //Function used to print A
    synchronized void printA() {
        System.out.print("A");
        aCount++;
        try{
            Thread.sleep(1000);
            notify();
        }
        catch(Exception e){}
    }
    //Function used to print B
    synchronized void printB() {
        if(isPrintBC)//True
        try {
            wait();
        } catch(InterruptedException e) {
        System.out.println("InterruptedException caught");
        }
        //False
        if(aCount>0){
            System.out.print("B");
            try{
            Thread.sleep(1000);
            }
            catch(Exception e){}
            aCount--;
            isPrintBC=true;
            notify();
           
   
        }
        //Rule 3 voilated
        else{
            isPrintBC=true;
            notify();
            }
        }
    //Function used to print C
    synchronized void printC() {
    if(!isPrintBC)//False
        try {
            wait();
        } catch(InterruptedException e) {
        System.out.println("InterruptedException caught");
        }
        //True
        if(aCount>0){
            System.out.print("C");
            try{
            Thread.sleep(1000);
            }
            catch(Exception e){}
           
            aCount--;
            isPrintBC=false;
            notify();
   
        }
        //Rule 3 voilated
        else{
            isPrintBC=false;
            notify();
            }
    }
}
//Process Pa outputs A
class Pa implements Runnable {
    ABC abc;
    Pa(ABC abc) {
        this.abc = abc;
        new Thread(this, "Pa").start();
    }
    public void run() {
        for(int i=0;i<10 br="" i="">        abc.printA();
        }
    }
}
//Process Pb outputs B
class Pb implements Runnable {
    ABC abc;
    Pb(ABC abc) {
        this.abc = abc;
        new Thread(this, "Pb").start();
    }
    public void run() {
        for(int i=0;i<10 br="" i="">            abc.printB();
        }
    }
}
//Process Pc outputs C
class Pc implements Runnable {
    ABC abc;
    Pc(ABC abc) {
        this.abc = abc;
        new Thread(this, "Pc").start();
    }
    public void run() {
        for(int i=0;i<10 br="" i="">        abc.printC();
        }
    }
}
//Main Class
class Multi_Process_OS {
    public static void main(String args[]) {
    ABC abc = new ABC();
        new Pa(abc);
        new Pb(abc);
        new Pc(abc);
    }
}

Saturday, November 17, 2012

Qick Sort Using Java

/* Implementation of QUICK SORT ALGORITHM using JAVA
Date:         18/11/2012
Author :     Sarju S */

import java.util.*;
import java.io.*;

public class QuickSort{
    public static void main(String[] args) {
        try{
        System.out.println("\nEnter the total number of element to sort:");
        DataInputStream din  = new DataInputStream(System.in);
        din = new DataInputStream(System.in);
        int totalNumbers = Integer.parseInt(din.readLine());
        int array[] = new int[totalNumbers];
        System.out.println("Enter the elements: ");
        for(int i=0;i            array[i] = Integer.parseInt(din.readLine());
        }
        recursiveQuickSort(array, 0, array.length-1);
        System.out.println("The following array should be sorted: ");
        printList(array);
        System.exit(0);
        }
        catch(Exception e){
        }
    }

    public static void recursiveQuickSort(int[] list, int first, int last) {
        if(first < last)
        {
            int p = partition(list, first, last);
            printList(list);
            recursiveQuickSort(list, first, p-1);
            recursiveQuickSort(list, p+1, last);
        }
    }

    public static int partition(int[] list, int first, int last) {
        int p = first;
        for(int n = p+1; n <= last; n++)
            if(list[n] < list[p])
            {
                swap(list, n, p+1);
                swap(list, p, p+1);
                p++;
            }
        return p;
    }

    private static void swap(int[] list, int index1, int index2) {
        int temp = list[index1];
        list[index1] = list[index2];
        list[index2] = temp;
    }

    protected static void printList(int[] list) {
        for(int n = 0; n < list.length; n++)
            System.out.print(list[n]+" ");
        System.out.println();
    }
}

Tries


  •  The standard Trie for a set of strings S is an ordered tree such that:
    •   Each node but the root is labeled with a character 
    • The children of a node are alphabetically ordered 
    • The paths from the external nodes to the root yield the strings of S
  •   Example: standard Trie for the set of strings


Java Code:

/* Implementation of Trie using JAVA
Date:         18/11/2012
Author :     Sarju S
*/
import java.io.*;
class TrieNode
{
    char letter;
    TrieNode[] links;
    boolean fullWord;
  
    TrieNode(char letter, boolean fullWord)
    {
        this.letter = letter;
        links = new TrieNode[26];//For storing 26 English Alphabets
        this.fullWord = fullWord;
    }
}
public class Trie
{   
    /*Function for creating Empty Trie*/
    static TrieNode createTree()
    {
        return(new TrieNode('\0', false));
    }
   /*Function for insertion into Trie*/
    static void insertWord(TrieNode root, String word)
    {
        int offset = 97;//ASCII Value of 'a'
        int l = word.length();
        char[] letters = word.toCharArray();
        TrieNode curNode = root;
      
        for (int i = 0; i < l; i++)
        {
            if (curNode.links[letters[i]-offset] == null)
                curNode.links[letters[i]-offset] = new TrieNode(letters[i], i == l-1 ? true : false);
            curNode = curNode.links[letters[i]-offset];
        }
    }
     /*Function for search a particular word from Trie*/
    static boolean find(TrieNode root, String word)
    {
        char[] letters = word.toCharArray();
        int l = letters.length;
        int offset = 97;//ASCII Value of 'a'
        TrieNode curNode = root;
      
        int i;
        for (i = 0; i < l; i++)
        {
            if (curNode == null)
                return false;
            curNode = curNode.links[letters[i]-offset];
        }
      
        if (i == l && curNode == null)
            return false;
      
        if (curNode != null && !curNode.fullWord)
            return false;
      
        return true;
    }
    /*Function for Printing Trie*/
    static void printTree(TrieNode root, int level, char[] branch)
    {
        if (root == null)
            return;
      
        for (int i = 0; i < root.links.length; i++)
        {
            branch[level] = root.letter;
            printTree(root.links[i], level+1, branch);  
        }
      
        if (root.fullWord)
        {
            for (int j = 1; j <= level; j++)
                System.out.print(branch[j]);
            System.out.println();
        }
    }
  
    public static void main(String[] args)
    {
        TrieNode tree = createTree();
           String words,searchWord;
        int choice;
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        try{
            do{
                System.out.print("\nMENU\n1:Insert\n2.Search\n3.Print\n4.Exit\n");
                System.out.println("Enter Your Choice:");
                choice = Integer.parseInt(in.readLine());
                switch(choice){
                    case 1:    System.out.println("Enter the word to insert :");
                            words = in.readLine();
                            insertWord(tree, words);
                            break;
                    case 2:    System.out.println("Enter the word to search :");
                            searchWord = in.readLine();
                             if (find(tree, searchWord))
                                System.out.println("The word was found");
                             else
                                System.out.println("The word was NOT found");
                            break;
                    case 3:    char[] branch = new char[50];
                            System.out.println("The Trie");
                            printTree(tree, 0, branch);
                    }
                }while(choice<4 br="br">            }
        catch(Exception e){
        }
       
    }
}

 OUPUT

C:\Users\Sarju>javac trie.java

C:\Users\Sarju>java Trie

MENU
1:Insert
2.Search
3.Print
4.Exit
Enter Your Choice:
1
Enter the word to insert :
sss

MENU
1:Insert
2.Search
3.Print
4.Exit
Enter Your Choice:
1
Enter the word to insert :
www

MENU
1:Insert
2.Search
3.Print
4.Exit
Enter Your Choice:
3
The Trie
sss
www

MENU
1:Insert
2.Search
3.Print
4.Exit
Enter Your Choice:
2
Enter the word to search :
kkk
The word was NOT found

MENU
1:Insert
2.Search
3.Print
4.Exit
Enter Your Choice:4

C:\Users\Sarju>

                For More Details : Click Here    

Thursday, October 25, 2012

Deap -Implementation in Java


Deap

A deap is a double-ended heap that supports the double-ended priority operations of insert, delet-min, and delete-max. Similar to min-max heap but deap is faster on these operations by a constant factor, and the algorithms are simpler.

Definition: A deap is a complete binary tree that is either empty or satisfies the following properties:

   (1) The root contains no element
   (2) The left subtree is a min heap.
   (3) The right subtree is a max heap.
   (4) If the right subtree is not empty, then let i be     any node in the left subtree. Let j be the corresponding node in the right subtree. If such a j does not exist, then let j be the node  in the right subtree that corresponds to the  parent of i. The key in node i is less than or equal to that of j.

Example




Insertion into Deap



After the insertion of 4



After the insertion of 30


 

Deletion of  min Element



Implementation

/*
Program Name: Deap.java
 * Author: Sarju
 * Date: 1-10-12
 * Reference: Shiuh-Sheng Yu, Department of Information Management, National Chi Nan University
 * 
 */
 import java.io.*;
public class Deap {
    int[] deap;
    int n = 1;
    public Deap(int maxSize) {
        deap = new int[maxSize];
    }
    private boolean inMaxHeap(int i) {
        while (i > 3) {
            i /= 2;
           
         }
        if (i == 2) return false;
        return true;
    }
    private int maxPartner(int pos) {
        int offset = 1;
        int i = pos;
        while (i > 3) {
            i /= 2;
            offset *= 2;
        }
        if ((pos + offset) > n) return (pos+offset)/2;
        return pos + offset;
    }
    private int minPartner(int pos) {
        int offset = 1;
        int i = pos;
        while (i > 3) {
            i /= 2;
            offset *= 2;
        }
        return pos - offset;
    }
    private void minInsert(int at, int key) {
        for (int parent; (parent = at / 2) != 1 && key < deap[parent]; deap[at] = deap[parent], at = parent) ;
        deap[at] = key;
    }
    private void maxInsert(int at, int key) {
        for (int parent; (parent = at / 2) != 1 && key > deap[parent]; deap[at] = deap[parent], at = parent) ;
        deap[at] = key;
    }
    public int deleteMax() {
        int i, j;
        int key;
        if (n >= 3) { // if more than 2 elements
            key = deap[3];
        } else {
            n--;
            return deap[2];
        }
        int x = deap[n--];
        // while i has child, move larger to i
        for (i = 3; 2*i <= n; deap[i] = deap[j], i = j) {
            j = i * 2;
            if (j+1 <= n) {
                if (deap[j] < deap[j+1]) {
                    j++;
                }
            }
        }
        // try to put x at leaf i
        // find biggest at min partner
        j = minPartner(i);
        int biggest = j;
        if (2*j <= n) {
            biggest = 2*j;
            if (((2*j + 1) <= n) && (deap[2*j] < deap[2*j+1])) {
                biggest++;
            }
        }
        if (x < deap[biggest]) {
            // x can't put at i, must change with deap[biggest]
            deap[i] = deap[biggest];
            minInsert(biggest, x);
        } else {
            maxInsert(i, x);
        }
        return key;
    }
    public int deleteMin() {
        int i, j, key = deap[2], x = deap[n--];
        // while i has child, move smaller to i
        for (i = 2; 2*i <= n; deap[i] = deap[j], i = j) {
            j = i * 2;
            if (j+1 <= n && deap[j] > deap[j+1]) {
                j++;
            }
        }
        // try to put x at leaf i
        j = maxPartner(i);
        if (x > deap[j]) {
            deap[i] = deap[j];
            maxInsert(j, x);
        } else {
            minInsert(i, x);
        }
        return key;
    }
    public void insert(int x) {
        n++;
        if (n == deap.length) {
            System.out.println("The heap is full");
            System.exit(1);
        }
        if (n == 2) {
            deap[2] = x;
            return;
        }
        if (inMaxHeap(n)) {
            int i = minPartner(n);
            if (x < deap[i]) {
                deap[n] = deap[i];
                minInsert(i, x);
            } else {
                maxInsert(n, x);
            }
        } else {
            int i = maxPartner(n);
            if (x > deap[i]) {
                deap[n] = deap[i];
                maxInsert(i, x);
            } else {
                minInsert(n, x);
            }
        }
    }
    public void print() {
        int levelNum = 2;
        int thisLevel = 0;
        int gap = 8;
        for (int i = 2; i <= n; i++) {
            for (int j = 0; j < gap-1; j++) {
                System.out.print(" ");
            }
            if (thisLevel != 0) {
                for (int j = 0; j < gap-1; j++) {
                    System.out.print(" ");
                }
            }
            if (Integer.toString(deap[i]).length() == 1) {
                System.out.print(" ");
            }
            System.out.print(deap[i]);
            thisLevel++;
            if (thisLevel == levelNum) {
                System.out.println();
                thisLevel = 0;
                levelNum *= 2;
                gap/=2;
            }
        }
        System.out.println();
        if (thisLevel != 0) {
            System.out.println();
        }
    }
    public static void main(String[] argv) {
        Deap a = new Deap(1024);
        int choice,element;
        
        try{
        do{   
        System.out.print("\n1:Insert\n2.DeleteMin\n3.DeleteMax\n4.Exit");
        System.out.print("\nEnter Your Choice:");
        DataInputStream din  = new DataInputStream(System.in);
        choice = Integer.parseInt(din.readLine());
        switch(choice){
            case 1: /*For Adding new Element*/
                    System.out.println("\nEnter the element to insert:");
                    din = new DataInputStream(System.in);
                    element = Integer.parseInt(din.readLine());
                    a.insert(element);
                    a.print();
                    break;
            case 2:
                    a.deleteMin();
                    a.print();
                    break;
            case 3:
                    a.deleteMax();
                    a.print();
           
        }
        }while(choice<4 br="br">        }
        catch(Exception e){
        }
       
    }
}