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

1 Dec 2013

Producer Consumer problem using wait and notify in java code

import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/*Java program to solve Producer Consumer problem using wait and notify
 */
public class ProducerConsumer {

    public static void main(String vals[]) {
        java.util.Vector sharedQueue = new 
java.util.Vector();

        int size = 4;
        
java.lang.Thread prodThread = new java.lang.Thread(new Producer(sharedQueue, size), "Producer");

        java.lang.Thread consThread = new java.lang.Thread(new Consumer(sharedQueue, size), "Consumer");
        prodThread.start();
        consThread.start();
    }
}

class Producer implements 
java.lang.Runnable {


    private final 
java.util.Vector sharedQueue;

    private final int SIZE;

    public Producer(
java.util.Vector sharedQueue, int size) {

        this.sharedQueue = sharedQueue;
        this.SIZE = size;
    }

    @Override
    public void run() {
        for (int i = 0; i < 7; i++) {
            System.out.println("Produced: " + i);
            try {
                produce(i);
            } catch (java.lang.InterruptedException e) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e);
            }

        }
    }

    private void produce(int i) throws InterruptedException {

        //wait if queue is full
        while (sharedQueue.size() == SIZE) {
            synchronized (sharedQueue) {
                System.out.println("Queue is full " + Thread.currentThread().getName()
                                    + " is waiting , size: " + sharedQueue.size());

                sharedQueue.wait();
            }
        }

        //producing element and notify consumers
        synchronized (sharedQueue) {
            sharedQueue.add(i);
            sharedQueue.notifyAll();
        }
    }
}

class Consumer implements 
java.lang.Runnable {


    private final 
java.util.Vector sharedQueue;

    private final int SIZE;

    public Consumer(
java.util.Vector sharedQueue, int size) {

        this.sharedQueue = sharedQueue;
        this.SIZE = size;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("Consumed: " + consume());
                
java.lang.Thread.sleep(50);

            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private int consume() throws InterruptedException {
        //wait if queue is empty
        while (sharedQueue.isEmpty()) {
            synchronized (sharedQueue) {
                System.out.println("Queue is empty " + Thread.currentThread().getName()
                                    + " is waiting , size: " + sharedQueue.size());

                sharedQueue.wait();
            }
        }

        //Otherwise consume element and notify waiting producer
        synchronized (sharedQueue) {
            sharedQueue.notifyAll();
            return (Integer) sharedQueue.remove(0);
        }
    }
}



output:

Producer Consumer problem using wait and notify in java code




30 Nov 2013

java swing buttons example

/* java swing buttons example, jbutton in java swing example, jbutton in java swing actionlistener, jbutton actionperformed java example */

import java.util.Map;
import java.util.TreeMap;
import javax.swing.JOptionPane;

public class ClientLogin extends javax.swing.JFrame {

   

    public ClientLogin() {
        initComponents();
    }

  

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setMinimumSize(new java.awt.Dimension(510, 400));
        getContentPane().setLayout(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Client Login", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14), new java.awt.Color(0, 0, 0))); // NOI18N

        jPanel1.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 3, 24));

        jLabel1.setText("Client Login");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(180, 20, 130, 30);

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 14));

        jLabel2.setText("User Id");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(50, 100, 100, 30);

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 14));

        jLabel3.setText("Password");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(50, 170, 110, 30);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(180, 100, 140, 30);

        jButton1.setFont(new java.awt.Font("Times New Roman", 1, 14));

        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(270, 233, 100, 30);

        jButton2.setFont(new java.awt.Font("Times New Roman", 1, 14));

        jButton2.setText("Reset");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(390, 233, 90, 30);
        jPanel1.add(jPasswordField1);
        jPasswordField1.setBounds(180, 170, 140, 30);

        getContentPane().add(jPanel1);

        jPanel1.setBounds(10, 10, 490, 310);

        pack();

    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        DBPack.DBConnection db=new DBPack.DBConnection();
        Map map=db.loginVal();
        String s=jTextField1.getText();
        String ss=jPasswordField1.getText();
        System.out.println("uname"+s);
        System.out.println("upass"+ss);
        boolean uname1=map.containsKey(s);
        boolean upass1=map.containsValue(ss);
        System.out.println("uname"+map);
        System.out.println(uname1+""+upass1);

        if(uname1 && upass1)

        {
           
            db.insertclient(s);
            System.out.println(uname1+""+upass1);
            JOptionPane.showMessageDialog(rootPane, "Login successfully");
            this.dispose();
            ClientHomeSW ch=new ClientHomeSW();
            ch.clientName(s);
            ch.setVisible(true);
           
        }
 else
        {
            JOptionPane.showMessageDialog(rootPane, "In-Valid Login");
 }

    }//GEN-LAST:event_jButton1ActionPerformed


    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientLogin().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}

sorting map in java example code

//map in java example code (using enumeration and iterator):

public class mapexample
{
public static void main(String vals[])
{
try
{
//creating vector object
java.util.Vector v=new java.util.Vector();

//adding elements to vector
int primitive=10;
Integer wrapper=new Integer(20);
String str="Satya";
v.add(primitive);
v.add(wrapper);
v.add(str);
v.add(2,new Integer(30));

System.out.println("the items in vector are: +v");
System.out.println("the number of items in vector are (size): "+v.size());
System.out.println("the item at position 2 is: "+v.elementAt(2));
System.out.println("the first item of vector is: "+v.firstElement());
System.out.println("the last item of vector is: "+v.lastElement());
System.out.println("now removing item at position 2");
v.removeElementAt(2);

//by using enumeration
java.util.Enumeration e=v.elements();
System.out.println("\nthe items in vector are (througth enumeration): "+v);
while(e.hasMoreElements())
{
System.out.println("the item is: "+e.nextElement());
}

//by using iterator
java.util.Iterator itr=v.iterator();
System.out.println("\nthe items in vector are (througth iterator): ");
while(itr.hasNext())
{
System.out.println(itr.next()+" ");
}
}
catch(Exception e)
{
 e.printStackTrace();
}
}
}

output:

sorting map in java example code

10 Oct 2012

finding synonyms and hyponyms for words in java

/* finding synonyms and hyponyms for words in java */

import edu.smu.tspell.wordnet.NounSynset;
import edu.smu.tspell.wordnet.Synset;
import edu.smu.tspell.wordnet.SynsetType;
import edu.smu.tspell.wordnet.WordNetDatabase;

public class wordnet 
{
    String a[]=new String[2];
    public static void wordnet(String a[])
    {
        int j=0;
        while(j<2)
        {
        
            System.setProperty("wordnet.database.dir", "C:\\Program Files\\WordNet\\2.1\\dict");
            NounSynset nounSynset;
            NounSynset[] hyponyms;
            WordNetDatabase database = WordNetDatabase.getFileInstance();
            Synset[] synsets = database.getSynsets(a[j], SynsetType.NOUN);
             System.out.println("*********************************************");
            for (int i = 0; i < synsets.length; i++)
                {
            nounSynset = (NounSynset)(synsets[i]);
            hyponyms = nounSynset.getHyponyms();
           
            System.err.println(nounSynset.getWordForms()[0] +": " + nounSynset.getDefinition() + ") has " + hyponyms.length + " hyponyms");
           
                }
            j++;
        }
         System.out.println("*********************************************");
    }

}

DFS in java with example

//DFS in java with example, Depth first search(DFS) in java example code, dfs program in java

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import weiss.nonstandard.PriorityQueue;
import weiss.nonstandard.PairingHeap;
import weiss.nonstandard.BinaryHeap;

// Used to signal violations of preconditions for
// various shortest path algorithms.
class GraphException extends java.lang.RuntimeException
{
    public GraphException(java.lang.String name)
    {
        super(name);
    }
}

// Represents an edge in the graph.
class Edge
{
    public Vertex     dest;   // Second vertex in Edge
    public double     cost;   // Edge cost
    
    public Edge( Vertex d, double c )
    {
        dest = d;
        cost = c;
    }
}

// Represents an entry in the priority queue for Dijkstra's algorithm.
class Path implements Comparable
{
    public Vertex     dest;   // w
    public double     cost;   // d(w)
    
    public Path( Vertex d, double c )
    {
        dest = d;
        cost = c;
    }
    
    public int compareTo( Object rhs )
    {
        double otherCost = ((Path)rhs).cost;
        
        return cost < otherCost ? -1 : cost > otherCost ? 1 : 0;
    }
}

// Represents a vertex in the graph.
class Vertex
{
    public String     name;   // Vertex name
    public List       adj;    // Adjacent vertices
    public double     dist;   // Cost
    public Vertex     prev;   // Previous vertex on shortest path
    public int        scratch;// Extra variable used in algorithm

    public Vertex( String nm )

      { name = nm; adj = new LinkedList( ); reset( ); }

    public void reset( )

      { dist = Graph.INFINITY; prev = null; pos = null; scratch = 0; }    
      
    public PriorityQueue.Position pos;  // Used for dijkstra2 (Chapter 23)
}

public class Graph
{
    public static final double INFINITY = Double.MAX_VALUE;
    private Map vertexMap = new HashMap( ); // Maps String to Vertex

    /**

     * Add a new edge to the graph.
     */
    public void addEdge( String sourceName, String destName, double cost )
    {
        Vertex v = getVertex( sourceName );
        Vertex w = getVertex( destName );
        v.adj.add( new Edge( w, cost ) );
    }

    /**

     * Driver routine to handle unreachables and print total cost.
     * It calls recursive routine to print shortest path to
     * destNode after a shortest path algorithm has run.
     */
    public void printPath( String destName )
    {
        Vertex w = (Vertex) vertexMap.get( destName );
        if( w == null )
            throw new NoSuchElementException( "Destination vertex not found" );
        else if( w.dist == INFINITY )
            System.out.println( destName + " is unreachable" );
        else
        {
            System.out.print( "(Cost is: " + w.dist + ") " );
            printPath( w );
            System.out.println( );
        }
    }

    /**

     * If vertexName is not present, add it to vertexMap.
     * In either case, return the Vertex.
     */
    private Vertex getVertex( String vertexName )
    {
        Vertex v = (Vertex) vertexMap.get( vertexName );
        if( v == null )
        {
            v = new Vertex( vertexName );
            vertexMap.put( vertexName, v );
        }
        return v;
    }

    /**

     * Recursive routine to print shortest path to dest
     * after running shortest path algorithm. The path
     * is known to exist.
     */
    private void printPath( Vertex dest )
    {
        if( dest.prev != null )
        {
            printPath( dest.prev );
            System.out.print( " to " );
        }
        System.out.print( dest.name );
    }
    
    /**
     * Initializes the vertex output info prior to running
     * any shortest path algorithm.
     */
    private void clearAll( )
    {
        for( Iterator itr = vertexMap.values( ).iterator( ); itr.hasNext( ); )
            ( (Vertex)itr.next( ) ).reset( );
    }

    /**

     * Single-source unweighted shortest-path algorithm.
     */
    public void unweighted( String startName )
    {
        clearAll( ); 

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        LinkedList q = new LinkedList( );

        q.addLast( start ); start.dist = 0;

        while( !q.isEmpty( ) )

        {
            Vertex v = (Vertex) q.removeFirst( );

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                if( w.dist == INFINITY )
                {
                    w.dist = v.dist + 1;
                    w.prev = v;
                    q.addLast( w );
                }
            }
        }
    }

    /**

     * Single-source weighted shortest-path algorithm.
     */
    public void dijkstra( String startName )
    {
        PriorityQueue pq = new BinaryHeap( );

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( );

        pq.insert( new Path( start, 0 ) ); start.dist = 0;
        
        int nodesSeen = 0;
        while( !pq.isEmpty( ) && nodesSeen < vertexMap.size( ) )
        {
            Path vrec = (Path) pq.deleteMin( );
            Vertex v = vrec.dest;
            if( v.scratch != 0 )  // already processed v
                continue;
                
            v.scratch = 1;
            nodesSeen++;

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( cvw < 0 )
                    throw new GraphException( "Graph has negative edges" );
                    
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist +cvw;
                    w.prev = v;
                    pq.insert( new Path( w, w.dist ) );
                }
            }
        }
    }

    /**

     * Single-source weighted shortest-path algorithm using pairing heaps.
     */
    public void dijkstra2( String startName )
    {
        PriorityQueue pq = new PairingHeap( );

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( );

        start.pos = pq.insert( new Path( start, 0 ) ); start.dist = 0;

        while ( !pq.isEmpty( ) )

        {
            Path vrec = (Path) pq.deleteMin( );
            Vertex v = vrec.dest;
                
            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )
            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( cvw < 0 )
                    throw new GraphException( "Graph has negative edges" );
                    
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                    
                    Path newVal = new Path( w, w.dist );                    
                    if( w.pos == null )
                        w.pos = pq.insert( newVal );
                    else
                        pq.decreaseKey( w.pos, newVal ); 
                }
            }
        }
    }

    /**

     * Single-source negative-weighted shortest-path algorithm.
     */
    public void negative( String startName )
    {
        clearAll( ); 

        Vertex start = (Vertex) vertexMap.get( startName );

        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        LinkedList q = new LinkedList( );

        q.addLast( start ); start.dist = 0; start.scratch++;

        while( !q.isEmpty( ) )

        {
            Vertex v = (Vertex) q.removeFirst( );
            if( v.scratch++ > 2 * vertexMap.size( ) )
                throw new GraphException( "Negative cycle detected" );

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                      // Enqueue only if not already on the queue
                    if( w.scratch++ % 2 == 0 )
                        q.addLast( w );
                    else
                        w.scratch--;  // undo the enqueue increment    
                }
            }
        }
    }

    /**

     * Single-source negative-weighted acyclic-graph shortest-path algorithm.
     */
    public void acyclic( String startName )
    {
        Vertex start = (Vertex) vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( ); 

        LinkedList q = new LinkedList( );
        start.dist = 0;
        
          // Compute the indegrees
        Collection vertexSet = vertexMap.values( );
        for( Iterator vsitr = vertexSet.iterator( ); vsitr.hasNext( ); )
        {
            Vertex v = (Vertex) vsitr.next( );
            for( Iterator witr = v.adj.iterator( ); witr.hasNext( ); )
                ( (Edge) witr.next( ) ).dest.scratch++;
        }    
            
          // Enqueue vertices of indegree zero
        for( Iterator vsitr = vertexSet.iterator( ); vsitr.hasNext( ); )
        {
            Vertex v = (Vertex) vsitr.next( );
            if( v.scratch == 0 )
                q.addLast( v );
        }    
       
        int iterations;
        for( iterations = 0; !q.isEmpty( ); iterations++ )
        {
            Vertex v = (Vertex) q.removeFirst( );

            for( Iterator itr = v.adj.iterator( ); itr.hasNext( ); )

            {
                Edge e = (Edge) itr.next( );
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( --w.scratch == 0 )
                    q.addLast( w );
                
                if( v.dist == INFINITY )
                    continue;    
                
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                }
            }
        }
        
        if(iterations!=vertexMap.size())
            throw new GraphException("Graph has a cycle!");
    }

    public static boolean processRequest(java.io.BufferedReader in,Graph g)

    {
        String startName=null;
        String destName=null;
        String alg=null;

        try

        {
System.out.print("Enter start node:");
            if((startName=in.readLine())==null)
                return false;
            System.out.print("Enter destination node:");
            if((destName=in.readLine())==null)
                return false;
            System.out.print("Enter algorithm (u, d, n, a ):");   
            if((alg=in.readLine())==null)
                return false;
            
            if(alg.equals("u"))
                g.unweighted(startName);
            else if(alg.equals("d"))    
            {
                g.dijkstra(startName);
                g.printPath(destName);
                g.dijkstra2(startName);
            }
            else if(alg.equals("n"))
                g.negative(startName);
            else if(alg.equals("a"))
                g.acyclic(startName);
                    
            g.printPath(destName);
        }
        catch(java.io.IOException e)
          { 
           System.err.println(e); 
          }
        catch(NoSuchElementException e)
          { 
           System.err.println(e); 
          }          
        catch(GraphException e)
          { 
          System.err.println(e); 
          }
        return true;
    }

    /**

     * A main routine that:
     * 1. Reads a file containing edges (supplied as a command-line parameter);
     * 2. Forms the graph;
     * 3. Repeatedly prompts for two vertices and
     *    runs the shortest path algorithm.
     * The data file is a sequence of lines of the format source destination.
     */
    public static void main(String []args)
    {
        Graph g=new Graph();
        try
        {
            java.io.FileReader fin=new java.io.FileReader(args[0]);
            java.io.BufferedReader graphFile=new java.io.BufferedReader(fin);
            java.lang.String line;
            while((line=graphFile.readLine())!=null)
            {
                java.util.StringTokenizer st=new java.util.StringTokenizer(line);

                try

                {
                    if(st.countTokens()!=3)
                    {
                        System.err.println("Skipping ill-formatted line"+line);
                        continue;
                    }
                    String source=st.nextToken();
                    String dest=st.nextToken();
                    int cost=java.lang.Integer.parseInt(st.nextToken());
                    g.addEdge(source,dest,cost);
                }
                catch(java.lang.NumberFormatException e )
                  { 
                  System.err.println("Skipping ill-formatted line"+line); 
                  }
             }
         }
         catch(java.io.IOException e)
           { 
            System.err.println(e); 
           }

         System.out.println("File read");

         System.out.println(g.vertexMap.size()+"vertices");

         java.io.BufferedReader in=new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

         while(processRequest(in,g));
    }
}


graph.txt

D C 10
A B 12
D B 23
A D 87
E D 43
B E 11
C A 19


Running Procedure:
c:\>java classname graph.txt

For ieee projects visit our site here