Flylib.com

Books Software

 
 
 

Unit Testing


Unit Testing

To test the Voice Help application:

  1. Download the free implementation of the Speech Converter API from the following URL:

    http://freetts. sourceforge .net/docs/index.php

  2. Set the path of the bin directory of J2SDK by executing the following command at the command prompt:

    set path=%path%;D:\j2sdk1.4.0_02\bin;
    
  3. Set the classpath of the lib directory of J2SDK and Speech Converter API by executing the following command at the command prompt:

    set classpath = %classpath%;d:\j2sdk1.4.0_02\lib;C:\j2sdk1.4.0_02\lib;c:\freetts-bin-  
    1_2_beta\lib\freetts.jar;c:\freetts-bin-1_2_beta\lib\cmulex.jar;c:\freetts-bin-1_2_beta\lib\
    jsapi.jar;
    

  4. Copy the SpeakHelp.java, SpeakHelpText.java, and SelectHelpVoice.java files to a folder on your computer. Use the cd command at the command prompt to move to the folder in which you have copied the Java files. Compile the files by using the following javac command:

    javac *.java
    
  5. To run the Voice Help application, specify the following command at the command prompt:

    java SpeakHelp
    
  6. The user interface of the Voice Help application appears. Click the Help button. A question mark icon appears.

  7. Select any menu option or button to listen to the help information for that option or button, as shown in Figure 4-7:

    click to expand: this figure shows the selected menu to listen to the help information for that menu option.
    Figure 4-7: The Voice Menu with Help



Chapter 5: Creating a Counting Application

 Download CD Content

The Java API provides the javax.speech and javax.speech.synthesis packages to develop an application to count the number of vowels , consonants, words, and sentences in the text provided by an end user . This helps in calculating the word count of a document.

This chapter describes how to develop a Counting application, which provides a user interface containing four buttons to count the number of vowels, consonants, words, and sentences in the specified text. This application converts the count values to speech in the voice selected by an end user.

Architecture of the Counting Application

The Counting application uses the following files:

  • SpeechCounting.java: Allows an end user to specify the text in the text area provided by the interface. This file also counts the number of vowels, consonants, words, and sentences in the specified text.

  • SpeakCounting.java: Converts the count values to speech.

  • SelectVoiceType.java: Allows an end user to select the voice in which the application converts the count values to speech.

Figure 5-1 shows the architecture of the Counting application:

click to expand: this figure shows the files that the counting application uses and the sequence in which the application uses them.
Figure 5-1: Architecture of the Counting Application

The SpeechCounting.java file creates the user interface of the Counting application that contains the File menu and four buttons: Vowel, Consonant, Word, and Sentence .

The File menu allows end users to open an existing file in the text area provided by the interface. An end user can select File->Select Voice to select the required voice. The application uses the selected voice to read out the count values of vowels, consonants, words, and sentences.

The SpeechCounting.java file calls the SelectVoiceType.java file, which provides an interface that contains two radio buttons, Voice 1 and Voice 2, for selecting a voice.

The SpeechCounting.java file calls the SpeakCounting.java file to convert the count values of vowels, consonants, words, and sentences to speech.



Creating the User Interface for the Counting Application

The SpeechCounting.java file creates the user interface for the Counting application. Listing 5-1 shows the contents of the SpeechCounting.java file:

Listing 5-1: The SpeechCounting.java File

start example
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
/*Import required awt event classes.*/
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*Import required io classes.*/
import java.io.File;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.FileWriter;
import javax.swing.text.BadLocationException;
import java.util.StringTokenizer;
/*
Class: SpeechCounting-Creates the user interface for the SpeechCounting
Methods:
actionPerformed(): Defines the actions to be performed, when user clicks any button or menu item.
open(): Opens the file selected by the end user in the textarea of the textpad.
main(): Creates the main window of the application.
*/
public class SpeechCounting extends JFrame implements ActionListener
{
   /*Declare objects of JMenuBar class.*/
   JMenuBar menubar;
   /* Declare objects of JMenu class.*/
   JMenu filemenu;
   /*Declare objects of JMenuItem class.*/
   JMenuItem openfilemenuitem,selectvoicemenuitem,exitmenuitem;
   /* Declare objects of JTextArea class.*/
   JTextArea textarea;
   /*Declare objects of JScrollPane class.*/
   JScrollPane scrollpane;
   /*Declare objects of JPanel class.*/
   JPanel buttonpanel;
   /*Declare objects of JButton class.*/
   JButton vowelcounterbutton, Consonantcounterbutton, wordcounterbutton, sentencecounterbutton;
   /*Declare objects of String class.*/
   String textareastring;
   String selectedvoicename;
   String speakstring;
   String str;
   /*Declare objects of JFileChooser class.*/
   JFileChooser filechooser;
   /*Declare objects of File class.*/
   File file;
   /*Declare objects of FileInputStream class.*/
   FileInputStream fin;
   /*Declare objects of SpeakCounting class.*/
   SpeakCounting st;
   /*Declare objects of SelectVoiceType class.*/
   SelectVoiceType selectvoice;
   public SpeechCounting()
   {
      /*Sets the window title.*/
      super("Vowel, Consonant, Word, and Sentence Counting Application");
      /* 
      Sets the look and feel for the speechcounting.
      */
      try
      {        
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      }
      catch(Exception e)
      {
         System.out.println("Unknown Look and Feel."+e);   
      }
      /* 
      Declare and initialize object of Container class. 
      */
      Container contentpane=getContentPane();
      /*Initialize object of String class.*/
      textareastring=new String();
      /* 
      Initialize object of JMenuItems class.
      */
      openfilemenuitem = new JMenuItem("Open (Alt+F+O)");
      selectvoicemenuitem=new JMenuItem("Select Voice (Alt+F+V)");
      exitmenuitem=new JMenuItem("Exit (Alt+F+E)");
      /* 
      Declare and initialize object of Dimension class.
      */
      Dimension screendimension=Toolkit.getDefaultToolkit().getScreenSize();
      /*Sets window location.*/
      setLocation(screendimension.width/2-250,screendimension.height/2-250);
      /*Sets action command for menu items.*/
      openfilemenuitem.setActionCommand("open");
      selectvoicemenuitem.setActionCommand("voice");
      exitmenuitem.setActionCommand("exit");
      /*Sets mnemonic for items.*/
      openfilemenuitem.setMnemonic('O');
      selectvoicemenuitem.setMnemonic('V');
      exitmenuitem.setMnemonic('E');
      /*Adds action listener for items.*/
      openfilemenuitem.addActionListener(this);
      selectvoicemenuitem.addActionListener(this);
      exitmenuitem.addActionListener(this);
      /*Initialize object of JMenu class.*/
      filemenu=new JMenu("File");
      /*Sets mnemonic for menu.*/
      filemenu.setMnemonic('F');
      /*Sets window closing operation.*/
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      /*Adds menu items to menu.*/
      filemenu.add(openfilemenuitem);
      filemenu.add(selectvoicemenuitem);
      filemenu.add(exitmenuitem);
      /*
      Initialize object of JMenuBar class. 
      */
      menubar=new JMenuBar();
      /*Adds menus to menu bar.*/
      menubar.add(filemenu);
      setJMenuBar(menubar);
      vowelcounterbutton=new JButton("Vowel");
      Consonantcounterbutton=new JButton("Consonant");
      wordcounterbutton=new JButton("Word");
      sentencecounterbutton=new JButton("Sentence");
      /* 
      Sets action command for menu buttons. 
      */
      vowelcounterbutton.setActionCommand("vowel");
      Consonantcounterbutton.setActionCommand("consonant");
      wordcounterbutton.setActionCommand("word");
      sentencecounterbutton.setActionCommand("sentence");
      /*Sets mnemonic for buttons.*/
      vowelcounterbutton.setMnemonic('V');
      Consonantcounterbutton.setMnemonic('C');
      wordcounterbutton.setMnemonic('W');
      sentencecounterbutton.setMnemonic('S');
      /*Adds action listener for buttons.*/
      vowelcounterbutton.addActionListener(this);
      Consonantcounterbutton.addActionListener(this);
      wordcounterbutton.addActionListener(this);
      sentencecounterbutton.addActionListener(this);
      /* 
      Initialize object of JPanel and sets layout as gridlayout.
      */
      buttonpanel=new JPanel(new GridLayout(1, 4, 5, 5));
      /*Adds buttons to panel.*/
      buttonpanel.add(vowelcounterbutton);
      buttonpanel.add(Consonantcounterbutton);
      buttonpanel.add(wordcounterbutton);
      buttonpanel.add(sentencecounterbutton);
      /*Adds panel to contentpane.*/
      contentpane.add(buttonpanel, BorderLayout.NORTH);
      /*
      Initialize object of JTextArea class. 
      */
      textarea=new JTextArea();
      /* 
      Initialize object of JScrollPane class.
      */
      scrollpane=new JScrollPane(textarea);
      /*Adds panel to contentpane.*/
      contentpane.add(scrollpane);
      /*
      Initialize object of SelectVoiceType class.
      */
      selectvoice=new SelectVoiceType(this);
      /*
      Initialize object of String class.
      */
      selectedvoicename=new String("kevin16");
      selectvoice.getOkButton().addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent ae)
         {
            selectedvoicename=selectvoice.getVoiceName();
            selectvoice.setVisible(false);
         }
      });
      /*Set the size of user interface.*/
      setSize(400,400);
      /*Set the visibility true.*/
      setVisible(true);
   }
   /*
   actionPerformed - This method is called when the user clicks the Vowel, Consonant, 
   Word or Sentence
   button, selects file menu items.
   Parameters: ae - an ActionEvent object containing details of the event.
   Return Value: NA
   */
   public void actionPerformed(ActionEvent ae)
   {
      String actioncommand=ae.getActionCommand();
      /*
      This is executed when user clicks the Open menu item.
      */
      if (actioncommand=="open")
      {
         try
         {   
            /*Initialize a new JFileChooser.*/
            filechooser=new JFileChooser();
            /*
            Create and set a new FileFilter for the JFileChooser.
            */
            filechooser.setFileFilter(new javax.swing.filechooser.FileFilter()
            {
            public boolean accept(File f)
            {
               if(f.isDirectory())
               {
                  return true;
               }
               String name=f.getName();
               /*
               Allows only text and java files to be opened in the user interface of text pad.
               */
               if ((name.endsWith(".txt"))(name.endsWith(".java")))
               {
                  return true;
               }
               return false;
            }
            public String getDescription()
            {
               return "Text Files";
            }
         });
         /*Open the JFileChooser.*/
         filechooser.showOpenDialog(this);
         file = filechooser.getSelectedFile();
         if(file==null)
         {
            System.out.println("No file Selected");
         }
         else
         {
            /* 
            Check if the selected file is a valid file.
            */
            if(file.isFile())
            {
               str = file.getAbsolutePath();
               open();
            }
            else
            {
               /* 
               Print the error message if the selected file is not a valid file.
               */
               JOptionPane.showMessageDialog(null,"The selected file is not a valid File","Select 
               another File",JOptionPane.WARNING_MESSAGE);
            }
         }
      }
      catch(Exception e) 
      {
         System.out.println("Error" + e);   
      }
   }
   /*
   This is executed when user clicks the Voice menu item.
   */
   if(actioncommand=="voice")
   selectvoice.setVisible(true);
   /*
   This is executed when user clicks the Exit menu item.
   */
   if(actioncommand=="exit")
   System.exit(0);
   /*
   This is executed when user clicks the Vowel button.
   */
   if(actioncommand=="vowel")
   {
      /*Declare objects of String class.*/
      String textareachar;
      textareastring = textarea.getText();
      int textarealength=textareastring.length();
      int vowelcount=0;
      for(int i=0;i<textarealength;i++)
      {
         textareachar=textareastring.substring(i,i+1);
         if("aeiou".indexOf(textareachar)!=-1)
         {
            vowelcount=vowelcount+1;
         }
      }
      if(vowelcount==1)
      {
         speakstring="There is "+vowelcount +"Vowel.";
      }
      else
      {
         speakstring="There are "+vowelcount +"Vowels.";
      }
      st=new SpeakCounting(speakstring,selectedvoicename);
      /*
      Invoke the speakSelText() method of SpeakCounting class
      */
      st.speakSelText();
   }
   /*
   This is executed when user clicks the Consonant button.
   */
   if (actioncommand=="consonant")
   {
      String textareachar;
      textareastring = textarea.getText();
      int textarealength=textareastring.length();
      int consonantcount=0;
      for(int i=0;i<textarealength;i++)
      {
         textareachar=textareastring.substring(i,i+1);
         if ("bcdfghjklmnopqrstuwxyz".indexOf(textareachar)!=-1)
         {
            consonantcount=consonantcount+1;
         }
      }
      if(consonantcount==1)
      {
         speakstring="There is "+consonantcount +"Consonant.";
      }
      else
      {
         speakstring="There are "+consonantcount +"Consonants.";
      }
      st=new SpeakCounting(speakstring,selectedvoicename);
      /*
      Invoke the speakSelText() method of SpeakCounting class
      */
      st.speakSelText();
   }
   /*
   This is executed when user clicks the Word button.
   */
   if(actioncommand=="word")
   {
      textareastring = textarea.getText();
      int totalLines = textarea.getLineCount();
      int wordlength=0;
      for (int i=0;i< totalLines;i++ )
      {
         try
         {
            int start = textarea.getLineStartOffset(i);
            int end = textarea.getLineEndOffset(i);
            String line = textareastring.substring(start, end);
            String[] words=line.split(" ");
            for(int j=0;j<words.length;j++ )
            {
               if(words[j].trim().length()>0)
               {
                  wordlength=wordlength+1;
               }
            }
         }
         catch(BadLocationException ble)
         {
         }
      }
      if(wordlength==1)
      {
         speakstring="There is "+wordlength +"Word.";
      }
      else
      {
         speakstring="There are "+wordlength +"Words.";
      }
      st=new SpeakCounting(speakstring,selectedvoicename);
      /*
      Invoke the speakSelText() method of SpeakCounting class.
      */
      st.speakSelText();
   }
   /*
   This is executed when user clicks the Sentence button.
   */
   if(actioncommand=="sentence")
   {
      textareastring = textarea.getText();
      StringTokenizer sttoken = new StringTokenizer(textareastring,".");
      int lengthofarray=sttoken.countTokens();
      if(lengthofarray==1)
      {
         speakstring="There is"+lengthofarray+"Sentence.";
      }
      else
      {
         speakstring="There are "+lengthofarray +"Sentences.";
      }
      st=new SpeakCounting(speakstring,selectedvoicename);
      /*
      Invoke the speakSelText() method of SpeakCounting class.
      */
      st.speakSelText();
      }
   }
   /*
   open: This method opens a file dialog box.
   Parameter: NA
   Return Value: NA
   */
   public void open() 
   {
      try
      {
         /*
         Initialize a new FileInputStream.
         */
         fin = new FileInputStream(filechooser.getSelectedFile().getAbsolutePath());
         /*
         Initialize a new object of BufferedReader class.
         */
         BufferedReader br = new BufferedReader(new InputStreamReader(fin));
         String readLine = "";
         textarea.setText("");
         while ((readLine = br.readLine())!=null)
         {
            textarea.setText(textarea.getText()+ "\n"+readLine);
         }
         if(textarea.getText()==null)
         {
            JOptionPane.showMessageDialog(null, "The file has no content", "Select another
            File", JOptionPane.WARNING_MESSAGE);
         }
         fin.close();
      }
      catch(IOException ioe)
      {
         System.err.println("I/O Error on Open");
      }
   }
   /*
   setvoice(): retrieves the voice selected by the end user.
   Parameters:
   str:String representing the voice selected by the end user
   Return Type: NA
   */
   public void setvoice(String str)
   {
      selectedvoicename=str;
   }
   public static void main(String[] args) 
   {
      SpeechCounting speechcounting=new SpeechCounting();
   }
}
end example
 

Download this listing .

In the above code, the main() method creates an instance of the SpeechCounting.java class.

The methods defined in Listing 5-1 are:

  • actionPerformed(): Acts as an event listener and activates an appropriate method based on the action the end user performs .

  • open(): Opens the file selected by the end user in the text area provided by the interface.

  • main(): Creates the main window of the application.

The SpeechCounting.java file creates the main window of the Counting application, as shown in Figure 5-2:

click to expand: this figure shows the user interface of the counting application, which contains the file menu and four buttons.
Figure 5-2: User Interface of the Counting Application

Figure 5-3 shows the File menu options of the Counting application:

click to expand: this figure shows the options available in the file menu of the counting application.
Figure 5-3: The File Menu of the Counting Application

To open an existing text file, select File->Open. The Open dialog box appears, as shown in Figure 5-4:

click to expand: this figure shows the dialog box to open a text file in the text area provided by the user interface.
Figure 5-4: The Open Dialog Box

Select the required file and click Open to open a file.

Select File-> Select Voice to select the voice in which the Counting application reads out the count values of vowels, consonants, words, and sentences in the text specified by an end user.

Click File-> Exit to close the Counting application.