Java Server Faces form validators

Posted by marian on November 01, 2009

There are three clear trends towards building web-pages these days: PHP, ASP, and JSP / JSF / Struts.
This post addresses the problem of writing custom data validators for web forms.
Validators are introduced in JSF pages by the “validator” tag, a custom input field looking like:

The name of the validator is given by the validatorId.

The mapping between the validatorId and the class handling the validation is done through the faces-config.xml.
<?xml version=’1.0′ encoding=’UTF-8′?>
<faces-config version=”1.2″
xmlns=”http://java.sun.com/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd”>
<managed-bean>

</managed-bean>

<navigation-rule>
<from-view-id> … </from-view-id>
<navigation-case>
<from-outcome>…</from-outcome>
<to-view-id>…</to-view-id>
</navigation-case>
</navigation-rule>

<validator>
<validator-id>NameValidator</validator-id>
<validator-class>NameValidator</validator-class>
</validator>
</faces-config>
The name validator is backed up by some Java code, that handles the corresponding validation. Basically a custom field validator implements the marker interface javax.faces.validator.Validator, having a single method called validate. The data is passed to our validating class through the mediation of the “value” object, which has to be cast to the type we are expecting it to be. To offer greater flexibility I created an Abstract Class which handles all the JSF’s API calls, which is latter implemented by a concrete class.

  1. import javax.faces.application.FacesMessage;
  2. import javax.faces.component.UIComponent;
  3. import javax.faces.context.FacesContext;
  4. import javax.faces.validator.Validator;
  5. import javax.faces.validator.ValidatorException;
  6.  
  7. public abstract class AbstractValidator implements Validator{
  8.  
  9.     public abstract boolean validValue(String text);
  10.     public abstract String getErrorMessage();
  11.  
  12.     public void validate(FacesContext context, UIComponent component,
  13.             Object value) {
  14.  
  15.         if (value == null) return;
  16.  
  17.         String text = value.toString();
  18.  
  19.         if (!validValue(text)) {
  20.              FacesMessage message = new FacesMessage(
  21.                         FacesMessage.SEVERITY_ERROR,
  22.                         getErrorMessage(), null);
  23.                 throw new ValidatorException(message);
  24.         }
  25.     }
  26. }

The concrete class adapts our abstract validator to our needs :

  1. public class NameValidator extends AbstractValidator {
  2.  
  3.     private char prohibited[] = {'/', '.'};
  4.     private static String ERROR_MESSAGE = "Invalid name format.";
  5.  
  6.     @Override
  7.     public String getErrorMessage(){
  8.         return ERROR_MESSAGE;
  9.     }
  10.  
  11.      @Override
  12.     public boolean validValue(String text) {
  13.         if (text.length()==0) {
  14.              return false;
  15.         }
  16.         for (int i = 0; i &lt; prohibited.length; i++) {
  17.             if (text.indexOf(prohibited[i]) != -1) {
  18.                 return false;
  19.             }
  20.         }
  21.         return true;
  22.     }
  23. }

About Java and Distributed Systems

Posted by marian on October 24, 2009

It is rely weird when people refuse to learn anything new or reuse something old.

Late this day I have received an email about a workshop in Distributed Computing. Lets establish the context first. In my hometown the is a project undergoing which has as objective the creation of a local computer cluster. And, in this context it just happens that a company wants to promote a product in Distributed Computing .

The company is called Actieeon, and its website is http://proactive.inria.fr/. They say that they are Open Source, but of course they have an Enterprise Solution that you can license.

I am eager to see what will they say at the workshop, and if I could mange to stop laughing. I must admit that they have a beautiful source code, well documented, but to build a Distributed System in Java seems to be a rather stupid thing to do.

Let me explain miself. In my faculty, at the Distributed Systems course we of course study Java as a language for Distributed programming. This is not because it is very good, but because nobody wants to try something new or use something old. Probably our parents heard about C, Fortran or Ada, languages  that were used succesfully for parallel and distributed computing. But we do not know anything about them, we must know the all mighty Java, an universal panaceea for our computing problems. Ohh, and there is also Erlang which “is a language designed concurrency in mind”.

The basic question is: why would you need an Object Oriented Language when you need raw power ? Probably there is nobody to do distributed computing with something other that OOP concepts. I would prefer a functional languag like Haskel or Erlang:  they provide a clear demarcation between what should be executed sequentially and what should be executed in parallel. The Java solution is to provide some function calls, to some “objects”, to perform “something” in parallel. The resulting code cannot be something else than ugly. But, we use OOP principles, and “some” say that this is good practice.

Some say that Java is very portable, and it is,realy it is, but only when you print on the console “Hello world”.

But when you want to do input/output and run computationally intensive programs, well you would have to write a chron scripts for killing the Java Virtual machine. Of course, some may say that for example JRockit Java VM can be used for powering highly demanding websites; and it is true, it is well suited for the MVC pattern, but it isn’t a language to use in a distributed system.

First of all a Distributed System is a heterogeneous one. Clusters have a large variaty of Operating System, ranging from AIX, Solaris, RedHat, Ubuntu server. Cheap solutions also use NetBsd; try running Sun’s Java VM on that one; the whole system needs around 90 MB to run, but when you start Java, hmm arround 300 MB.

So we’ve covered Java’s ugly code, large memory consumption, portability; now lets see about how others deal with these issues. Which componany has as main bussines distributed computing ? Answer: Google, job searching. Some say that they use a combination of C, Python and Java. I would say that they generally use Python, and do all the dirty things at the C level. Python has low memory consumtion, it is a glue language and can work along with other languages relatively well. Of course, there is Jython the Java version of Python, but, realy, I don’t think they are using it.

Next we have Erricson and the telecommunication world. Do they use Java ? It seems that there are some niche companies that are testing the field, but Erricson uses Erlang. Their purpose is the creation of a fault tolerant environment for providing services such emargency call. How are exceptions treated by those at Erricson ?

Is there a fault on the system ? If yes, automatically kill the process or if it is something extremly serious kill the Virtual Machine on the corresponding node and then restart it, while relying on the existing redundancy. In Java you must catch tens of expetions and handle them. Wouldn’t it be simpler to just kill the process that makes the computation ? Well, you can’t since it is an OOP language:  it doesn’t have fault tollerance, there is no mechanism for killing and restaring the VM, it does not have lightweight processes you could kill if they do something nasty, but it has a hightly complex garbage collector that has the job of making some room in the excesivelly large memory that it is needed.

Installing the JRockit Java Virtual Machine under Ubuntu

Posted by marian on October 24, 2009

Does Eclipse run slow, or Netbeans consumes a lot of memory ?
Here is a solution, well a partial one since the memory consumption still remains: change the Eclipse’s Java VM or Netbeans Java VM with Oracle’s Java VM called JRockit and you’ll see a performance boost.
It is free, it is big and not so easy to tune, but it is fast.
First of all there are two flavors of the Oracle’s Java VM:

  • Oracle JRockit Mission Control
  • Oracle JRockit Real Time

I personally prefer Oracle JRockit Real Time. You can make up your mind by reading http://www.oracle.com/technology/software/products/jrockit/FAQ.htm
As a big plus you are not required to provide any information about yourself, such as e-mail (as others require) when downloading the installation kit.
After you have it, lets say it is jrrt-3.1.2-1.6.0-linux-x64.bin, you must make it executable:

  1. chmod +x

and then execute it (version of the kit used for testing is highlighted) :

  1. sudo ./jrrt-3.1.2-1.6.0-linux-x64.bin

You can install it in a number of locations, such as under /usr/lib/jvm , or /usr/lib64. Although this Java Virtual Machine is on 64 bits, I prefer the first location (although to the end, due to simlinks it doesn’t matter).
Then you perform a simlink to it :

  1. ln -s /usr/lib64/jvm/jrrt-3.1.2-1.6.0 /usr/lib/jvm/java-6-jrockit

The naming java-6-jrockit is needed by the update-alternatives in order to discover it.
Next you use the update-alternatives to notify the programming environment about its existence (a very very big minus, since Sun’s Java VM does it automatically):

update-alternatives -- install /usr/bin/java java /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/java 64
update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jar 64
update-alternatives --install /usr/bin/jarsigner jarsigner /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jarsigner 64
update-alternatives --install /usr/bin/javadoc javadoc /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/javadoc 64
update-alternatives --install /usr/bin/javah javah /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/javah 64
update-alternatives --install /usr/bin/javap javap /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/javap 64
update-alternatives --install /usr/bin/jconsole jconsole /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jconsole 64
update-alternatives --install /usr/bin/jdb jdb /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jdb 64
update-alternatives --install /usr/bin/jps jps /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jps 64
update-alternatives --install /usr/bin/rmiregistry rmiregistry /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/rmi 64
update-alternatives --install /usr/bin/appletviewer appletviewer /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/appletviewer 64
update-alternatives --install /usr/bin/apt apt /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/apt 64
update-alternatives --install /usr/bin/extcheck extcheck /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/extcheck 64
update-alternatives --install /usr/bin/idlj idlj /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/idlj 64
update-alternatives --install /usr/bin/jrunscript jrunscript /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jrunscript 64
update-alternatives --install /usr/bin/jstat jstat /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jstat 64
update-alternatives --install /usr/bin/jstatd jstatd /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jstatd 64
update-alternatives --install /usr/bin/native2ascii native2ascii /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/native2ascii 64
update-alternatives --install /usr/bin/rmic rmic /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/rmic 64
update-alternatives --install /usr/bin/schemagen schemagen /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/schemagen 64
update-alternatives --install /usr/bin/serialver serialver /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/serialver 64
update-alternatives --install /usr/bin/wsgen wsgen /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/wsgen 64
update-alternatives --install /usr/bin/wsimport wsimport /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/wsimport 64
update-alternatives --install /usr/bin/xjc xjc /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/xjc 64
update-alternatives --install /usr/bin/keytool keytool /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/keytool 64
update-alternatives --install /usr/bin/orbd orbd /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/orbd 64
update-alternatives --install /usr/bin/pack200 pack200 /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/pack200 64
update-alternatives --install /usr/bin/policytool policytool /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/policytool 64
update-alternatives --install /usr/bin/rmid rmid /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/rmid 64
update-alternatives --install /usr/bin/servertool servertool /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/servertool 64
update-alternatives --install /usr/bin/tnameserv tnameserv /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/tnameserv 64
update-alternatives --install /usr/bin/unpack200 unpack200 /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/unpack200 64

This being done you can now safely change the default Java VM :

sudo update-alternatives --config java

There are 5 alternatives which provide `java'.

  Selection    Alternative
-----------------------------------------------
          1    /usr/lib/jvm/java-6-sun/jre/bin/java
          2    /usr/bin/gij-4.2
          3    /usr/bin/gij-4.3
*+     4    /usr/lib/jvm/java-gcj/jre/bin/java
          5    /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/java
Press enter to keep the default[*], or type selection number: 5

If the change is successful, on a new call should look like:

sudo update-alternatives --config java
There are 5 alternatives which provide `java'.

  Selection    Alternative
-----------------------------------------------
          1    /usr/lib/jvm/java-6-sun/jre/bin/java
          2    /usr/bin/gij-4.2
          3    /usr/bin/gij-4.3
* +    4    /usr/lib/jvm/java-gcj/jre/bin/java
          5    /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/java
Press enter to keep the default[*], or type selection number: 5

Just press CTRL–C and go forward with:

sudo update-alternatives --config javac
There are 5 alternatives which provide `javac'.

  Selection    Alternative
-----------------------------------------------
          1    /usr/lib/jvm/java-6-sun/bin/javac
          2    /usr/bin/ecj
          3    /usr/bin/gcj-wrapper-4.3
*+     4    /usr/lib/jvm/java-gcj/bin/javac
          5    /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/javac

Press enter to keep the default[*], or type selection number: 5

sudo update-alternatives --config jar

There are 5 alternatives which provide `jar'.

  Selection    Alternative
-----------------------------------------------
          1    /usr/lib/jvm/java-6-sun/bin/jar
          2    /usr/bin/fastjar
 *+    3    /usr/lib/jvm/java-gcj/jre/bin/jar
          4    /usr/bin/gjar-4.3
          5    /usr/lib/jvm/jrrt-3.1.2-1.6.0/bin/jar

Press enter to keep the default[*], or type selection number: 5

JRockit proves a good way to boost the performance of you development environment, both on Eclipse and Netbeans. Its performance can be seen especially when you are developing web application, and you are using Apache Tomcat.

Changing the default Java Virtual Machine under Ubuntu

Posted by marian on October 24, 2009

It seems that there are things that the Open Source community can’t provide. One of those is the java virtual machine and the corresponding java sdk. Although under Ubuntu the default option is the gcj, one of the first thing I do is replacing it with a better one. There are two competitor (or is it just one, after all Oracle bought Sun Microsystems) : the Sun’s JAVA VM and Oracle’s JRockit JVM.

After installing one or both VM, one can simply switch between them using:

sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config jar

Last element in a list : 99 erlang problems

Posted by marian on July 18, 2009

Problem statement: Get the last element in a list.
Use case scenario:

  1. Compile the module
  2. 1> c(last).
    1. {ok,last}
  3. Use it:
  4. 2> last:last([1,2,3,4]).
    1. 4

Solution nr. 1:

-module(last).
  1. -export([last/1]).
  2.  
  3. last([LastOne])-&gt; LastOne;
  4. last([_|Tail])-&gt; last(Tail).

Solution nr. 2:

-module(last).
  1. -export([last/1]).
  2.  
  3. last(List)-&gt;hd(lists:reverse(List)).

Waiting Queues (Java homework)

Posted by marian on June 29, 2009

  1. package waitingQueues;
  2.  
  3. import javax.swing.JApplet;
  4. import waitingQueues.controller.Controller;
  5. import waitingQueues.controller.ControllerInterface;
  6. import waitingQueues.model.Model;
  7. import waitingQueues.model.ModelInterface;
  8. import waitingQueues.view.View;
  9. import waitingQueues.view.ViewInterface;
  10.  
  11. /**
  12.  * This the main class. It instantiates the Model, View and Controller from the MVC model
  13.  * @author Marian Dan
  14.  *
  15.  */
  16. public class Main extends JApplet{
  17.  /*
  18.   * The default constructor on the Main class.
  19.   */
  20.  public Main(){
  21.    
  22.   //create an instance of the user interface/ the view
  23.    ui = new View();
  24.   //create an instance of the model we are working on
  25.   model=new Model();
  26.   //create an instance of the controller that manages the
  27.   //interactions between the model and the  
  28.   controller=new Controller(ui,model);  
  29.  }
  30.  //the application is designed to run both as an applet or as an
  31.  //application
  32.  /**
  33.   * Overrides the default init method of the JApplet
  34.   */
  35.  public void init(){
  36.  
  37.  }
  38.  /**
  39.   * Overrides the default start method of the JApplet
  40.   */
  41.  public void start(){
  42.  
  43.  }
  44.  /**
  45.   * Overrides the default stoo method of the JApplet
  46.   */
  47.  public void stop(){
  48.  
  49.  }
  50.  /**
  51.   * Overrides the default destroy method of the JApplet
  52.   */
  53.  public void destroy(){
  54.  
  55.  }
  56.  
  57.  /**
  58.   * The standard public String toString() is overridden
  59.   */
  60.  public String toString(){
  61.   return "This is the main application";
  62.  }
  63.  /**
  64.   * Check to see if this is the instance of the main application
  65.   */
  66.  public boolean equals(Object other) {
  67.   if(this==other) return true;
  68.   else return false;
  69.  }
  70.  
  71.  /**
  72.   * For running the application as an application
  73.   */
  74.  public static void main(String args[]) {
  75.   final Main  application = new Main();  
  76.  }
  77.  private static final long serialVersionUID = 2028805364097710940L;
  78.  private final ViewInterface ui;
  79.  private final ModelInterface model;
  80.  private final ControllerInterface controller;
  81.  
  82. }
  1. package waitingQueues;
  2.  
  3. /**
  4.  * The purpose of this class is to provide means of treating exceptions,
  5.  * that arise when the program is running. The class WaitingQueuesException
  6.  * inherits the methods of the default Java class Exception.
  7.  */
  8. public class WaitingQueuesException extends Exception{
  9.  /**
  10.   * Default constructor
  11.   * @param String
  12.   */
  13.  public WaitingQueuesException(String mess){
  14.   //this.printStackTrace();
  15.   message=mess;
  16.   System.out.println("Exception: # "+message);
  17.  }
  18.  /**
  19.   * This method overrides the default toString() method
  20.   *
  21.   */
  22.  public String toString()
  23.  {
  24.   return message;
  25.  }
  26.  /**
  27.   * The method returns the message associated with the exception
  28.   */
  29.  public String getMessage(){
  30.   return message;
  31.  }
  32.  /**
  33.   * Check to see if this is the instance of the View
  34.   */
  35.  public boolean equals(Object other) {
  36.   if(other instanceof WaitingQueuesException){
  37.    WaitingQueuesException m=(WaitingQueuesException)other;
  38.    if(m.toString().equals(message)) return true;
  39.    else return false;
  40.    
  41.   }else return false;
  42.  }
  43.  private static final long serialVersionUID = 4593665563049627269L;
  44.  //stores the error message
  45.  private String message="";
  46.  
  47. }
  1. package waitingQueues;
  2. /**
  3.  * Stores constants regarding the application limitations such as the maximum number of
  4.  * clients or queues
  5.  * @author Marian Dan
  6.  *
  7.  */
  8. public class Constants {
  9.  /**
  10.   * Stores the minimum limit for the number of queues
  11.   */
  12.  public static final int MINIMUM_NUMBER_OF_QUEUES =1;
  13.  /**
  14.   * Stores the minimum limit for the waiting time
  15.   */
  16.  public static final int MINIMUM_WAITING_TIME =1;
  17.  /**
  18.   * Stores the minimum limit for the service time
  19.   */
  20.  public static final int MINIMUM_SERVICE_TIME =1;
  21.  /**
  22.   * Stores the minimum limit for the arrival time
  23.   */
  24.  public static final int MINIMUM_ARRIVAL_TIME =1;
  25.  /**
  26.   * Stores the minimum limit for the number of clients
  27.   */
  28.  public static final int MINIMUM_NUMBER_OF_CLIENTS =1;
  29.  
  30.  /**
  31.   * Stores the maximum limit for the number of queues
  32.   */
  33.  public static final int MAXIMUM_NUMBER_OF_QUEUES =1000;
  34.  /**
  35.   * Stores the maximum limit for the waiting time
  36.   */
  37.  public static final int MAXIMUM_WAITING_TIME =1000;
  38.  /**
  39.   * Stores the maximum limit for the service time
  40.   */
  41.  public static final int MAXIMUM_SERVICE_TIME =1000;
  42.  /**
  43.   * Stores the maximum limit for the arrival time
  44.   */
  45.  public static final int MAXIMUM_ARRIVAL_TIME =1000;
  46.  /**
  47.   * Stores the maximum limit for the number of clients
  48.   */
  49.  public static final int MAXIMUM_NUMBER_OF_CLIENTS =1000;
  50. }
  1. package waitingQueues.view;
  2.  
  3. import java.awt.Dimension;
  4. import java.awt.event.ActionListener;
  5.  
  6. import javax.swing.JButton;
  7. import javax.swing.JEditorPane;
  8. import javax.swing.JFrame;
  9. import javax.swing.JLabel;
  10. import javax.swing.JOptionPane;
  11. import javax.swing.JPanel;
  12. import javax.swing.JScrollPane;
  13. import javax.swing.JTextField;
  14.  
  15. import waitingQueues.WaitingQueuesException;
  16.  
  17. public class InputForm extends JFrame {
  18.  public InputForm() {
  19.   // let decorations be available
  20.   JFrame.setDefaultLookAndFeelDecorated(true);
  21.   // Create and set up the window.
  22.   panel.setLayout(null);
  23.   // set the bounds of the panel
  24.   panel.setBounds(0, 0, 300, 530);
  25.  
  26.   clientsLabel.setBounds(10, 10, 120, 20);
  27.   clientsTxt.setBounds(140, 10, 120, 20);
  28.  
  29.   queuesLabel.setBounds(10, 40, 120, 20);
  30.   queuesTxt.setBounds(140, 40, 120, 20);
  31.  
  32.   arrivalTimeLabel.setBounds(10, 70, 100, 20);
  33.   arrivalTimeMinTxt.setBounds(140, 70, 50, 20);
  34.   arrivalTimeMaxTxt.setBounds(210, 70, 50, 20);
  35.  
  36.   serviceTimeLabel.setBounds(10, 100, 100, 20);
  37.   serviceTimeMinTxt.setBounds(140, 100, 50, 20);
  38.   serviceTimeMaxTxt.setBounds(210, 100, 50, 20);
  39.  
  40.   simulationForTimeLabel.setBounds(100, 130, 50, 20);
  41.   simulateForTxt.setBounds(210, 130, 50, 20);
  42.  
  43.   simulationTimeLabel.setBounds(100, 160, 70, 20);
  44.   simulateTxt.setBounds(210, 160, 50, 20);
  45.   simulateTxt.setEditable(false);
  46.  
  47.   simulateBtn.setBounds(10, 130, 85, 20);
  48.   descriptionLabel.setBounds(10, 190, 100, 20);
  49.  
  50.   // create a scrolling area for processing area
  51.   scrolledContent = new JScrollPane(content);
  52.   // set just the horizontal scroll bar
  53.   scrolledContent
  54.     .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  55.   // set the prefferred size
  56.   scrolledContent.setPreferredSize(new Dimension(300, 220));
  57.   // set the minim size of scrooll pane
  58.   content.setEditable(false);
  59.   content.setText("");
  60.   scrolledContent.setMinimumSize(new Dimension(10, 10));
  61.   scrolledContent.setBounds(10, 210, 270, 250);
  62.   averageTimeLabel.setBounds(10, 470, 80, 20);
  63.   averageTimeTxt.setBounds(100, 470, 180, 20);
  64.   averageTimeTxt.setEditable(false);
  65.  
  66.   // add the scrolled panel to the frame
  67.  
  68.   panel.add(clientsLabel);
  69.   panel.add(queuesLabel);
  70.   panel.add(arrivalTimeLabel);
  71.   panel.add(serviceTimeLabel);
  72.   panel.add(simulationForTimeLabel);
  73.   panel.add(simulationTimeLabel);
  74.   panel.add(clientsTxt);
  75.   panel.add(queuesTxt);
  76.   panel.add(arrivalTimeMinTxt);
  77.   panel.add(arrivalTimeMaxTxt);
  78.   panel.add(serviceTimeMinTxt);
  79.   panel.add(serviceTimeMaxTxt);
  80.   panel.add(simulationTimeLabel);
  81.   panel.add(simulateForTxt);
  82.   panel.add(simulateTxt);
  83.   panel.add(simulateBtn);
  84.   panel.add(descriptionLabel);
  85.   panel.add(scrolledContent);
  86.   panel.add(averageTimeTxt);
  87.   panel.add(averageTimeLabel);
  88.  
  89.   // add the panel to the frame
  90.   this.add(panel);
  91.   // set the size of the frame
  92.   this.setSize(300, 530);
  93.   // Display the window.
  94.   this.setVisible(true);
  95.   // set the default close operation, i.e. what happens when you click on
  96.   // X
  97.   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  98.   // it should not be resizable
  99.   this.setResizable(false);
  100.   // set the title of the application
  101.   this.setTitle("Queue simulation <<Input form>>  Marian Dan Alexandru");
  102.  }
  103.  
  104.  protected int getNumberOfQueues() throws WaitingQueuesException {
  105.   int n = 0;
  106.  
  107.   try {
  108.    n = Integer.parseInt(queuesTxt.getText());
  109.   } catch (NumberFormatException ex) {
  110.    throw new WaitingQueuesException(
  111.      "The input is not valid.\nPlease enter a postive integer for the number of queues.");
  112.   }
  113.  
  114.   return n;
  115.  }
  116.  
  117.  protected int getNumberOfClients() throws WaitingQueuesException {
  118.   int n = 0;
  119.   try {
  120.    n = Integer.parseInt(clientsTxt.getText());
  121.   } catch (NumberFormatException ex) {
  122.    throw new WaitingQueuesException(
  123.      "The input is not valid.\nPlease enter a postive integer for the number of clients.");
  124.   }
  125.   return n;
  126.  }
  127.  
  128.  protected int getMinimumArrivalTime() throws WaitingQueuesException {
  129.   int n = 0;
  130.  
  131.   try {
  132.    n = Integer.parseInt(arrivalTimeMinTxt.getText());
  133.   } catch (NumberFormatException ex) {
  134.    throw new WaitingQueuesException(
  135.      "The input is not valid.\nPlease enter a postive integer for the minimum arrival time.");
  136.   }
  137.  
  138.   return n;
  139.  }
  140.  
  141.  protected int getMaximumArrivalTime() throws WaitingQueuesException {
  142.   int n = 0;
  143.  
  144.   try {
  145.    n = Integer.parseInt(arrivalTimeMaxTxt.getText());
  146.   } catch (NumberFormatException ex) {
  147.    throw new WaitingQueuesException(
  148.      "The input is not valid.\nPlease enter a postive integer for the maximum arrival time.");
  149.   }
  150.  
  151.   return n;
  152.  }
  153.  
  154.  protected int getMinimumServiceTime() throws WaitingQueuesException {
  155.   int n = 0;
  156.  
  157.   try {
  158.    n = Integer.parseInt(serviceTimeMinTxt.getText());
  159.   } catch (NumberFormatException ex) {
  160.    throw new WaitingQueuesException(
  161.      "The input is not valid.\nPlease enter a postive integer for the  minimum service time.");
  162.   }
  163.  
  164.   return n;
  165.  }
  166.  
  167.  protected int getMaximumServiceTime() throws WaitingQueuesException {
  168.   int n = 0;
  169.  
  170.   try {
  171.    n = Integer.parseInt(serviceTimeMaxTxt.getText());
  172.   } catch (NumberFormatException ex) {
  173.    throw new WaitingQueuesException(
  174.      "The input is not valid.\nPlease enter a postive integer for the maximum service time.");
  175.   }
  176.   return n;
  177.  }
  178.  
  179.  protected int getTimeForSimulation() throws WaitingQueuesException {
  180.   int n = 0;
  181.  
  182.   try {
  183.    n = Integer.parseInt(simulateForTxt.getText());
  184.   } catch (NumberFormatException ex) {
  185.    throw new WaitingQueuesException(
  186.      "The input is not valid.\nPlease enter a postive integer for the simulation time period.");
  187.   }
  188.  
  189.   return n;
  190.  }
  191.  
  192.  protected void setSimulationTime(String time) {
  193.   simulateTxt.setText("" + time);
  194.  }
  195.  
  196.  protected void setAverageTime(String time) {
  197.   averageTimeTxt.setText("" + time);
  198.  }
  199.  
  200.  protected void addToMessageQueue(String message) {
  201.   String s = content.getText();
  202.   s = message + s;
  203.   content.setText(s);
  204.  }
  205.  
  206.  protected final void showMessage(String message, String title) {
  207.   JOptionPane.showMessageDialog(null, message, title,
  208.     JOptionPane.WARNING_MESSAGE);
  209.  }
  210.  
  211.  protected final void showErrorMessage(String message) {
  212.   JOptionPane.showMessageDialog(this, message, "Error",
  213.     JOptionPane.ERROR_MESSAGE);
  214.  }
  215.  
  216.  /**
  217.   * Add an action listener to the Simulate button
  218.   *
  219.   * @param e
  220.   */
  221.  protected final void addSimulateBtnListener(ActionListener e) {
  222.   simulateBtn.addActionListener(e);
  223.  }
  224.  
  225.  public String toString() {
  226.   String s = "";
  227.   try {
  228.    s += "Clients: " + getNumberOfClients() + "\n" + "Queues: "
  229.      + getNumberOfQueues() + "\n" + "Min Arrival Time: "
  230.      + getMinimumArrivalTime() + "\n" + "Max Arrival Time: "
  231.      + getMaximumArrivalTime() + "\n" + "Min Service Time: "
  232.      + getMinimumServiceTime() + "\n" + "Max Service Time: "
  233.      + getMaximumServiceTime() + "\n" + "Simulate for: "
  234.      + getTimeForSimulation() + "\n" + "Simulation time: "
  235.      + simulateTxt.getText() + "\n";
  236.   } catch (Exception e) {
  237.    // do nothing
  238.   }
  239.   return s;
  240.  }
  241.  
  242.  protected void enableNewSimulation(boolean value){
  243.   simulateBtn.setEnabled(value);  
  244.  }
  245.  
  246.  private final JPanel panel = new JPanel();
  247.  private final JLabel clientsLabel = new JLabel("Number of clients:");
  248.  private final JLabel queuesLabel = new JLabel("Number of queues:");
  249.  private final JLabel arrivalTimeLabel = new JLabel("Arrival time:");
  250.  private final JLabel serviceTimeLabel = new JLabel("Service time:");
  251.  private final JLabel simulationForTimeLabel = new JLabel("For time:");
  252.  private final JLabel simulationTimeLabel = new JLabel("Time:");
  253.  private final JLabel descriptionLabel = new JLabel("Description:");
  254.  private final JLabel averageTimeLabel = new JLabel("Average time:");
  255.  
  256.  private final JButton simulateBtn = new JButton("Simulate");
  257.  
  258.  private final JTextField clientsTxt = new JTextField();
  259.  private final JTextField queuesTxt = new JTextField();
  260.  private final JTextField arrivalTimeMinTxt = new JTextField();
  261.  private final JTextField arrivalTimeMaxTxt = new JTextField();
  262.  private final JTextField serviceTimeMinTxt = new JTextField();
  263.  private final JTextField serviceTimeMaxTxt = new JTextField();
  264.  private final JTextField simulateForTxt = new JTextField();
  265.  private final JTextField simulateTxt = new JTextField();
  266.  private final JTextField averageTimeTxt = new JTextField();
  267.  private final JEditorPane content = new JEditorPane();
  268.  private final JScrollPane scrolledContent;
  269.  private static final long serialVersionUID = -1994987175182483198L;
  270.  
  271. }
  1. package waitingQueues.view;
  2.  
  3. import java.awt.Dimension;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;
  6.  
  7. import javax.swing.JFrame;
  8. import javax.swing.JPanel;
  9. import javax.swing.JScrollPane;
  10.  
  11. import waitingQueues.WaitingQueuesException;
  12.  
  13. public class OutputForm extends JFrame {
  14.  public OutputForm() {
  15.   // let decorations be available
  16.   JFrame.setDefaultLookAndFeelDecorated(true);
  17.   // Create and set up the window.
  18.  
  19.   array = new ArrayList();
  20.  
  21.   panel.setLayout(null);
  22.   // set the bounds of the panel
  23.   panel.setBounds(0, 0, OUTPUT_FORM_WIDTH, OUTPUT_FORM_HEIGHT);
  24.  
  25.   // create a scrolling area for processing area
  26.   scrolledContent = new JScrollPane(panel);
  27.   // scrolledContent = new JScrollPane();
  28.   // set just the horizontal scroll bar
  29.   scrolledContent
  30.     .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  31.   // set the prefferred size
  32.   scrolledContent.setPreferredSize(new Dimension(
  33.     OutputForm.OUTPUT_FORM_WIDTH, OUTPUT_FORM_HEIGHT));
  34.   // set the minim size of scrooll pane
  35.   scrolledContent.setMinimumSize(new Dimension(10, 10));
  36.   scrolledContent.setBounds(0, 0, OutputForm.OUTPUT_FORM_WIDTH,
  37.     OUTPUT_FORM_HEIGHT);
  38.  
  39.   // add the scrolled panel to the frame
  40.   this.add(scrolledContent);
  41.  
  42.   panel.setPreferredSize(new Dimension(OUTPUT_FORM_WIDTH,
  43.     OUTPUT_FORM_HEIGHT));
  44.  
  45.   this.setPreferredSize(new Dimension(OUTPUT_FORM_WIDTH + 40,
  46.     OUTPUT_FORM_HEIGHT));
  47.   pack();
  48.  
  49.   // set the size of the frame
  50.   this.setLocation(320, 0);
  51.   this.setSize(OUTPUT_FORM_WIDTH + 40, OUTPUT_FORM_HEIGHT);
  52.   // Display the window.
  53.   this.setVisible(true);
  54.   // set the default close operation, i.e. what happens when you click on
  55.   // X
  56.   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  57.   // it should not be resizeble
  58.   // this.setResizable(false);
  59.   // set the title of the application
  60.   this.setTitle("Queue display");
  61.  }
  62.  
  63.  protected void addQueue(int iId) throws WaitingQueuesException {
  64.   Iterator it;
  65.   boolean found = false;
  66.  
  67.   it = array.iterator();
  68.   while (it.hasNext()) {
  69.    Object obj = it.next();
  70.    // find the type of the object in order to draw it
  71.    if (obj != null && (obj instanceof QueueView)) {
  72.     QueueView q = (QueueView) obj;
  73.     if (q.equals(iId)) {
  74.      found = true;
  75.      break;
  76.     }
  77.    }
  78.   }
  79.   if (!found) {
  80.    QueueView queue = new QueueView(iId);
  81.    queue.setBounds(0, getNumberOfExistingQueues()
  82.      * QueueView.QUEUE_VIEW_HEIGHT, OUTPUT_FORM_WIDTH,
  83.      QueueView.QUEUE_VIEW_HEIGHT);
  84.    panel.setPreferredSize(new Dimension(OUTPUT_FORM_WIDTH,
  85.      (getNumberOfExistingQueues() + 1)
  86.        * QueueView.QUEUE_VIEW_HEIGHT));
  87.    
  88.    array.add(queue);
  89.    panel.add(queue);
  90.    pack();
  91.   } else {
  92.    throw new WaitingQueuesException("Queue already present");
  93.   }
  94.   //TODO
  95.   //System.out.println("ouput form "+iId);
  96.  }
  97.  
  98.  private int getNumberOfExistingQueues() {
  99.   return array.size();
  100.  }
  101.  
  102.  protected void setQueueContent(int iId, String s[]) {
  103.   Iterator it;
  104.   it = array.iterator();
  105.   while (it.hasNext()) {
  106.    Object obj = it.next();
  107.    // find the type of the object in order to draw it
  108.    if (obj != null && (obj instanceof QueueView)) {
  109.     QueueView q = (QueueView) obj;
  110.     if (q.equals(iId)) {
  111.      q.setQueueInformation(s);
  112.     }
  113.    }
  114.   }
  115.  }
  116.  
  117.  protected void reset() {
  118.   for (int i = 0; i < array.size(); i++) {
  119.    Object obj=array.get(i);
  120.    if (obj instanceof QueueView) {
  121.     QueueView q = (QueueView) obj;
  122.     q.setVisible(false);
  123.     panel.remove(q);
  124.     q = null;
  125.     //TODO
  126.     //System.out.println("ouput form xx");
  127.    }
  128.   }
  129.   array.clear();
  130.   //pack();
  131.  }
  132.  
  133.  private final JPanel panel = new JPanel();
  134.  private final JScrollPane scrolledContent;
  135.  protected static final int OUTPUT_FORM_WIDTH = 400;
  136.  protected static final int OUTPUT_FORM_HEIGHT = 400;
  137.  private ArrayList array;
  138. }
  1. package waitingQueues.view;
  2.  
  3. import java.awt.Dimension;
  4.  
  5. import javax.swing.JEditorPane;
  6. import javax.swing.JLabel;
  7. import javax.swing.JPanel;
  8. import javax.swing.JScrollPane;
  9. import javax.swing.JTextField;
  10.  
  11. public class QueueView extends JPanel{
  12.  public QueueView(int iId){
  13.   super();
  14.  
  15.   this.iId=iId;
  16.   this.setLayout(null);
  17.  
  18.   nameLabel = new JLabel("Queue #"+(iId+1)+":");
  19.   nameLabel.setBounds(0,0,100,20);  
  20.   //create a scrolling area for processing area
  21.   scrolledContent = new JScrollPane(content);
  22.   //set just the horizontal scroll bar
  23.   scrolledContent.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
  24.   //set the prefferred size
  25.   scrolledContent.setPreferredSize(new Dimension(OutputForm.OUTPUT_FORM_WIDTH-110, QUEUE_VIEW_HEIGHT));
  26.   //set the minim size of scrooll pane
  27.   scrolledContent.setMinimumSize(new Dimension(10, 10));
  28.   //just text
  29.   //content.setContentType("text");
  30.   //it shouldn't be editable
  31.   content.setEditable(false);
  32.   scrolledContent.setBounds(100, 0, OutputForm.OUTPUT_FORM_WIDTH-100, QUEUE_VIEW_HEIGHT);
  33.   //scrolledContent.setVisible(true);
  34.  
  35.   this.add(scrolledContent);
  36.   this.add(nameLabel);
  37.  }
  38.  
  39.  public int getId(){
  40.   return iId;
  41.  }
  42.  
  43.  public void setQueueInformation(String s[]){
  44.   String x="";
  45.   for(int i=0; i<s.length; i++){
  46.    x+=" "+s[i];  
  47.   }
  48.   content.setText(x);  
  49.  }
  50.  
  51.  public boolean equals(int iId){
  52.   return this.iId==iId;
  53.  
  54.  }
  55.  private int iId;
  56.  private final JScrollPane scrolledContent;
  57.  private final JLabel nameLabel;
  58.  private final JTextField content = new JTextField();
  59.  protected static final int QUEUE_VIEW_HEIGHT = 40;
  60.  private static final long serialVersionUID = -912479900798989604L;
  61. }
  1. package waitingQueues.view;
  2.  
  3. import java.awt.event.ActionListener;
  4.  
  5. import waitingQueues.WaitingQueuesException;
  6.  
  7. public class View implements ViewInterface {
  8.  public View() {
  9.   inputForm = new InputForm();
  10.   outputForm = new OutputForm();
  11.   // outputForm.setVisible(false);
  12.  }
  13.  
  14.  public int getNumberOfQueues() throws WaitingQueuesException {
  15.   int n = 0;
  16.   if (inputForm != null) {
  17.    n = inputForm.getNumberOfQueues();
  18.   }
  19.   return n;
  20.  }
  21.  
  22.  public int getNumberOfClients() throws WaitingQueuesException {
  23.   int n = 0;
  24.   if (inputForm != null) {
  25.    n = inputForm.getNumberOfClients();
  26.   }
  27.   return n;
  28.  }
  29.  
  30.  public int getMinimumArrivalTime() throws WaitingQueuesException {
  31.   int n = 0;
  32.   if (inputForm != null) {
  33.    n = inputForm.getMinimumArrivalTime();
  34.   }
  35.   return n;
  36.  }
  37.  
  38.  public int getMaximumArrivalTime() throws WaitingQueuesException {
  39.   int n = 0;
  40.   if (inputForm != null) {
  41.    n = inputForm.getMaximumArrivalTime();
  42.   }
  43.   return n;
  44.  }
  45.  
  46.  public int getMinimumServiceTime() throws WaitingQueuesException {
  47.   int n = 0;
  48.   if (inputForm != null) {
  49.    n = inputForm.getMinimumServiceTime();
  50.   }
  51.   return n;
  52.  }
  53.  
  54.  public int getMaximumServiceTime() throws WaitingQueuesException {
  55.   int n = 0;
  56.   if (inputForm != null) {
  57.    n = inputForm.getMaximumServiceTime();
  58.   }
  59.   return n;
  60.  }
  61.  
  62.  public int getTimeForSimulation() throws WaitingQueuesException {
  63.   int n = 0;
  64.   if (inputForm != null) {
  65.    n = inputForm.getTimeForSimulation();
  66.   }
  67.   return n;
  68.  }
  69.  
  70.  public void setSimulationTime(String time) {
  71.   if (inputForm != null) {
  72.    inputForm.setSimulationTime(time);
  73.   }
  74.  }
  75.  
  76.  public void showMessage(String message, String title) {
  77.   if (inputForm != null) {
  78.    inputForm.showMessage(message, title);
  79.   }
  80.  }
  81.  
  82.  public void showErrorMessage(String message) {
  83.   if (inputForm != null) {
  84.    inputForm.showErrorMessage(message);
  85.   }
  86.  }
  87.  
  88.  public void enableNewSimulation(boolean value){
  89.   if (inputForm != null) {
  90.    inputForm.enableNewSimulation(value);
  91.   }
  92.  }
  93.  
  94.  public void addQueue(int iId) throws WaitingQueuesException {
  95.   outputForm.addQueue(iId);
  96.  }
  97.  
  98.  public void setQueueContent(int iId, String s[]) {
  99.   outputForm.setQueueContent(iId, s);
  100.  }
  101.  
  102.  public void setVisibilityOfOutput(boolean isVisible) {
  103.   outputForm.setVisible(isVisible);
  104.  }
  105.  
  106.  /**
  107.   * Add an action listener to the Simulate button
  108.   *
  109.   * @param e
  110.   */
  111.  public void addSimulateBtnListener(ActionListener e) {
  112.   if (inputForm != null) {
  113.    inputForm.addSimulateBtnListener(e);
  114.   }
  115.  }
  116.  
  117.  public void appendMessageToMessageQueue(String message) {
  118.   inputForm.addToMessageQueue(message);
  119.  }
  120.  
  121.  public String toString() {
  122.   return inputForm.toString();
  123.  }
  124.  
  125.  public void reset() {
  126.   outputForm.reset();
  127.  }
  128.  
  129.  public void setAverageTime(String time) {
  130.   inputForm.setAverageTime(time);
  131.  }
  132.  
  133.  private static InputForm inputForm;
  134.  private static OutputForm outputForm;
  135. }
  1. package waitingQueues.view;
  2.  
  3. import java.awt.event.ActionListener;
  4.  
  5. import waitingQueues.WaitingQueuesException;
  6.  
  7. public interface ViewInterface {
  8.  public int getNumberOfQueues() throws WaitingQueuesException;
  9.  
  10.  public int getNumberOfClients() throws WaitingQueuesException;
  11.  
  12.  public int getMinimumArrivalTime() throws WaitingQueuesException;
  13.  
  14.  public int getMaximumArrivalTime() throws WaitingQueuesException;
  15.  
  16.  public int getMinimumServiceTime() throws WaitingQueuesException;
  17.  
  18.  public int getMaximumServiceTime() throws WaitingQueuesException;
  19.  
  20.  public void showMessage(String message, String title);
  21.  
  22.  public void showErrorMessage(String message);
  23.  
  24.  public int getTimeForSimulation() throws WaitingQueuesException;
  25.  
  26.  public void setSimulationTime(String time);
  27.  
  28.  public void addQueue(int iId) throws WaitingQueuesException;
  29.  
  30.  public void setQueueContent(int iId, String s[]);
  31.  
  32.  public void appendMessageToMessageQueue(String message);
  33.  
  34.  public void setVisibilityOfOutput(boolean isVisible);
  35.  
  36.  public void reset();
  37.  
  38.  public void setAverageTime(String time);
  39.  
  40.  public void enableNewSimulation(boolean value);
  41.  
  42.  /**
  43.   * Add an action listener to the Simulate button
  44.   *
  45.   * @param e
  46.   */
  47.  public void addSimulateBtnListener(ActionListener e);
  48.  
  49. }
  1. package waitingQueues.model;
  2.  
  3. //import waitingQueues.Constants;
  4. /**
  5.  * Stores information about the person, such waiting time, arrival time and
  6.  * service time
  7.  */
  8. public class Person implements PersonInterface {
  9.  /**
  10.   * Default constructor
  11.   *
  12.   * @param iPersonId
  13.   *            -id of person
  14.   */
  15.  public Person(int iPersonId) {
  16.   personId = iPersonId;
  17.  }
  18.  
  19.  /**
  20.   * Cosntructor
  21.   *
  22.   * @param iPersonId -
  23.   *            person id
  24.   * @param iServiceTime -
  25.   *            service time
  26.   * @param iArrivalTime -
  27.   *            arrival time
  28.   */
  29.  public Person(int iPersonId, int iServiceTime, int iArrivalTime) {
  30.   personId = iPersonId;
  31.   serviceTime = iServiceTime;
  32.   arrivalTime = iArrivalTime;
  33.  }
  34.  
  35.  /**
  36.   * Returns the id of the person.
  37.   */
  38.  public int getPersonId() {
  39.   return personId;
  40.  }
  41.  
  42.  /*
  43.   * private void setServiceTime(int value) { // precondition if (value <
  44.   * Constants.MINIMUM_SERVICE_TIME || value > Constants.MAXIMUM_WAITING_TIME)
  45.   * throw new IllegalArgumentException("Value " + value + " violates the
  46.   * precondition"); serviceTime = value; // postcondition if (serviceTime !=
  47.   * value) new AssertionError("In Person, value " + value + " violates the
  48.   * postcondition"); }
  49.   */
  50.  /**
  51.   * Increments the waiting time with the amount given by the parameter.
  52.   */
  53.  public void incrementWaitingTime(int amount) {
  54.   waitingTime += amount;
  55.  }
  56.  
  57.  /**
  58.   * Decrements the service time with the amount given by the parameter.
  59.   */
  60.  public void decrementServiceTime(int amount) {
  61.   serviceTime -= amount;
  62.  }
  63.  
  64.  /*
  65.   * private void setArrivalTime(int value) { // precondition if (value <
  66.   * Constants.MINIMUM_SERVICE_TIME || value > Constants.MAXIMUM_WAITING_TIME)
  67.   * throw new IllegalArgumentException("In Person, value " + value + "
  68.   * violates the precondition"); serviceTime = value; // postcondition if
  69.   * (serviceTime != value) new AssertionError("In Person, value " + value + "
  70.   * violates the postcondition"); }
  71.   */
  72.  
  73.  /**
  74.   * Returns the arrival time
  75.   */
  76.  public int getArrivalTime() {
  77.   return arrivalTime;
  78.  }
  79.  
  80.  /**
  81.   * Destroys the object.
  82.   */
  83.  public void destroy() {
  84.   serviceTime = 0;
  85.   waitingTime = 0;
  86.   arrivalTime = 0;
  87.  }
  88.  
  89.  /**
  90.   * It returns a string containing the parameters of the client.
  91.   */
  92.  public String toString() {
  93.   String s = "";
  94.   s += "(" + personId + ")" + "[" + serviceTime + "]" + "{" + waitingTime
  95.     + "}" + "#" + arrivalTime;
  96.   return s;
  97.  }
  98.  
  99.  /**
  100.   * Returns true if the person has been served.
  101.   */
  102.  public boolean personWasServed() {
  103.   return serviceTime == 0;
  104.  }
  105.  
  106.  /**
  107.   * Compare two persons according to their arrival time.
  108.   */
  109.  public int compareTo(Object obj) {
  110.   if (!(obj instanceof Person))
  111.    throw new AssertionError(
  112.      "Invalid object violates the precondition. Cannot compare objects of this type");
  113.  
  114.   Person p = (Person) obj;
  115.   if (arrivalTime < p.arrivalTime)
  116.    return -1;
  117.   else if (arrivalTime > p.arrivalTime)
  118.    return 1;
  119.   else
  120.    return 0;
  121.  }
  122.  /**
  123.   * Returns a copy of the object.
  124.   */
  125.  public Object clone() {
  126.   Object object = new Person(personId, serviceTime, arrivalTime);
  127.   ((Person) object).waitingTime = waitingTime;
  128.   return object;
  129.  }
  130.  /**
  131.   * Returns the waiting time
  132.   * @return the waiting time
  133.   */
  134.  public int getWaitingTime() {
  135.   return waitingTime;
  136.  }
  137.  /**
  138.   * Returns the service time
  139.   * @return the service time
  140.   */
  141.  public int getServiceTime() {
  142.   return serviceTime;
  143.  }
  144.  
  145.  private int serviceTime;
  146.  private int waitingTime;
  147.  private int arrivalTime;
  148.  private final int personId;
  149. }
  1. package waitingQueues.model;
  2.  
  3. public interface PersonInterface extends Comparable, Cloneable{
  4.  /**
  5.   * Destroys the object.
  6.   */
  7.  public void destroy();
  8.  /**
  9.   * Returns the id of the person.
  10.   */
  11.  public int getPersonId();
  12.  /**
  13.   * Increments the waiting time with the amount given by the parameter.
  14.   */
  15.  public void incrementWaitingTime(int amount);
  16.  /**
  17.   * Decrements the service time with the amount given by the parameter.
  18.   */
  19.  public void decrementServiceTime(int amount);
  20.  /**
  21.   * It returns a string containing the parameters of the client.
  22.   */
  23.  public String toString();
  24.  /**
  25.   * Returns true if the person has been served.
  26.   */
  27.  public boolean personWasServed();
  28.  /**
  29.   * Returns the waiting time
  30.   * @return the waiting time
  31.   */
  32.  public int getWaitingTime();
  33.  /**
  34.   * Returns the service time
  35.   * @return the service time
  36.   */
  37.  public int getServiceTime();
  38.  /**
  39.   * Returns the arrival time
  40.   */
  41.  public int getArrivalTime();
  42.  /**
  43.   * Compare two persons according to their arrival time.
  44.   */
  45.  public Object clone();
  46. }
  1. package waitingQueues.model;
  2.  
  3. import waitingQueues.Constants;
  4. import waitingQueues.WaitingQueuesException;
  5.  
  6. /**
  7.  * The purpose of the class is to implement the QueueuADT and manage the
  8.  * operations on queues
  9.  *
  10.  * @author Marian Dan
  11.  *
  12.  */
  13. public class Queue implements QueueADT {
  14.  /**
  15.   * Default constructor
  16.   */
  17.  public Queue() {
  18.   this.size = 0;
  19.   front = null;
  20.   rear = null;
  21.  }
  22.  
  23.  /**
  24.   * Checks if the queue is full
  25.   *
  26.   * @return true ( if the queue is full)
  27.   * @invariant isProperFormed()==true
  28.   */
  29.  public boolean isFull() {
  30.   return size == Constants.MAXIMUM_NUMBER_OF_QUEUES;
  31.  }
  32.  
  33.  /**
  34.   * Checks if the queue is empty
  35.   *
  36.   * @return true ( if the queue is empty)
  37.   * @invariant isProperFormed()==true
  38.   */
  39.  public boolean isEmpty() {
  40.   return size == 0;
  41.  }
  42.  
  43.  /**
  44.   * Enqueues an object.
  45.   *
  46.   * @precondition o!=null
  47.   * @postcondition rear==o
  48.   * @invariant isProperFormed()==true
  49.   */
  50.  public void enqueue(Object o) throws WaitingQueuesException {
  51.   assert (o != null) : "You whant to enter a null object in the Queue ?";
  52.   // precondition
  53.   if (isFull())
  54.    throw new WaitingQueuesException("The queue is full.");
  55.  
  56.   size++;
  57.  
  58.   Element element = new Element(o);
  59.   // TODO
  60.   // System.out.println("queue "+((Person)o).toString());
  61.   if (front == null) {
  62.    rear = element;
  63.    front = element;
  64.   } else {
  65.    rear.setNext(element);
  66.    rear = element;
  67.   }
  68.   // postcondition
  69.   if (rear != element)
  70.    throw new AssertionError(
  71.      "The value for the next element was not assigned");
  72.  
  73.  }
  74.  
  75.  /**
  76.   * Dequeues the front of returns it.
  77.   *
  78.   * @return the object that has been removed from the queue
  79.   * @precondition this.isEmpty()==false
  80.   * @postcondition size decreases with one
  81.   * @invariant isProperFormed()==true
  82.   */
  83.  public Object dequeue() throws WaitingQueuesException {
  84.   // precondition
  85.   if (isEmpty())
  86.    throw new WaitingQueuesException("The queue is empty.");
  87.   if (front == null)
  88.    throw new AssertionError(
  89.      "For some reason the queue does not have a front element.");
  90.   Object o = front.getData();
  91.   size–;
  92.   front = front.getNext();
  93.   assert (o != null) : "Returning null object from dequeue";
  94.   return o;
  95.  
  96.  }
  97.  
  98.  /**
  99.   * Destroys the object.
  100.   *
  101.   * @invariant isProperFormed()==true
  102.   */
  103.  public void destroy() {
  104.   try {
  105.    while (!isEmpty()) {
  106.     Object obj = dequeue();
  107.     if (obj instanceof Element) {
  108.      Element element = (Element) obj;
  109.      element.destroy();
  110.      element = null;
  111.     }
  112.     obj = null;
  113.    }
  114.   } catch (WaitingQueuesException e) {
  115.    System.out.println("queue " + e.getMessage());
  116.   }
  117.   size = 0;
  118.   front = null;
  119.   rear = null;
  120.  
  121.  }
  122.  
  123.  /**
  124.   * Returns a copy of the object.
  125.   *
  126.   * @postcondition object!=null
  127.   * @invariant isProperFormed()==true
  128.   */
  129.  public Object clone() {
  130.   Object object = new Queue();
  131.   Queue queue = (Queue) object;
  132.   if (front != null) {
  133.    Element i = front;
  134.    while (i != null) {
  135.     Person person = (Person) i.getData();
  136.     try {
  137.      queue.enqueue(person.clone());
  138.     } catch (Exception e) {
  139.      e.printStackTrace();
  140.     }
  141.     i = i.getNext();
  142.    }
  143.   }
  144.   assert (object == null) : "Cloning null object";
  145.   return object;
  146.  }
  147.  
  148.  /**
  149.   * Returns true if the element is proper formed
  150.   *
  151.   * @return true if the element is proper formed
  152.   */
  153.  public boolean isProperFormed() {
  154.   /**
  155.    * if the queue has size 1 then it stores exactly one object that object
  156.    * is stored both in rear and front
  157.    */
  158.   if (size == 1 && rear == front && rear != null)
  159.    return true;
  160.   /**
  161.    * if the queue has maximum size then it must be full
  162.    */
  163.   if (size == Constants.MAXIMUM_NUMBER_OF_QUEUES && this.isFull())
  164.    return true;
  165.   /**
  166.    * if the queue has size 0 then it does not store anything and therefore
  167.    * it must be empty
  168.    */
  169.   if (size == 0 && rear == null && front == null && this.isEmpty())
  170.    return true;
  171.   /**
  172.    * if the queue has its size between the boudaries then rear and front
  173.    * must be different than null
  174.    */
  175.   if (size > 1 && size < Constants.MAXIMUM_NUMBER_OF_QUEUES
  176.     && size > Constants.MINIMUM_NUMBER_OF_QUEUES && rear != null
  177.     && front != null)
  178.    return true;
  179.  
  180.   // in any other case return false
  181.   return false;
  182.  }
  183.  
  184.  /*
  185.   * public String[] printQueueContent() { if (isEmpty()) { return null; }
  186.   * String array[] = new String[size]; int k = 0; if (front != null) {
  187.   * Element i = front; while (i != null) { array[k] = i.getData().toString() + " ";
  188.   * i = i.getNext(); // TODO System.out.println("queueu " + array[k]); k++; } }
  189.   * return array; }
  190.   */
  191.  
  192.  /**
  193.   *
  194.   * @invariant isProperFormed()==true
  195.   */
  196.  private static int getSize(QueueADT queue) {
  197.   QueueADT q = (QueueADT) queue.clone();
  198.  
  199.   if (q.isEmpty()) {
  200.    return 0;
  201.   }
  202.  
  203.   int k = 0;
  204.  
  205.   while (!q.isEmpty()) {
  206.    try {
  207.     q.dequeue();
  208.     k++;
  209.    } catch (WaitingQueuesException e) {
  210.     e.printStackTrace();
  211.    }
  212.   }
  213.   return k;
  214.  }
  215.  
  216.  /**
  217.   * Returns the string representation of the elements of the queue
  218.   * @precondition queue!=null
  219.   * @postcondition return is not null
  220.   * @invariant isProperFormed()==true
  221.   */
  222.  public static String[] printQueueContent(QueueADT queue) {
  223.   QueueADT q = (QueueADT) queue.clone();
  224.  
  225.   if (q.isEmpty()) {
  226.    return null;
  227.   }
  228.   String array[] = new String[Queue.getSize(q)];
  229.   int k = 0;
  230.  
  231.   while (!q.isEmpty()) {
  232.    try {
  233.     Object object = q.dequeue();
  234.     if (!(object instanceof Person))
  235.      throw new AssertionError(
  236.        "For some reason the queue returned an invalid object.");
  237.  
  238.     Person i = (Person) object;
  239.     array[k] = i.toString() + " ";
  240.     //System.out.println("queueu " + array[k]);
  241.     k++;
  242.    } catch (WaitingQueuesException e) {
  243.     e.printStackTrace();
  244.    }
  245.   }
  246.   return array;
  247.  }
  248.  
  249.  /**
  250.   * Manages the stored elements
  251.   *
  252.   */
  253.  public class Element {
  254.   private Element() {
  255.    next = null;
  256.    data = null;
  257.   }
  258.  
  259.   /**
  260.    * @precondition obj!=null
  261.    * @postcondition data!=null && next==null
  262.    * @param obj
  263.    */
  264.   private Element(Object obj) {
  265.    assert (obj == null) : "Object to be stored is null";
  266.    next = null;
  267.    data = obj;
  268.   }
  269.  
  270.   /**
  271.    * @precondition eElement!=null
  272.    * @postcondition next==null
  273.    * @invariant isProperFormed()==true
  274.    * @param eElement
  275.    */
  276.   private void setNext(Element eElement) {
  277.    assert (eElement == null) : "Next element is null";
  278.    next = eElement;
  279.    assert (eElement != next) : "Assignment error";
  280.   }
  281.  
  282.   /**
  283.    *
  284.    * @return
  285.    * @invariant isProperFormed()==true
  286.    */
  287.   private Element getNext() {
  288.    return next;
  289.   }
  290.  
  291.   /**
  292.    *
  293.    * @return
  294.    * @invariant isProperFormed()==true
  295.    */
  296.   private Object getData() {
  297.    return data;
  298.   }
  299.  
  300.   private void destroy() {
  301.    next = null;
  302.    data = null;
  303.   }
  304.  
  305.   private boolean isProperFormed() {
  306.    if (data == null && next == null)
  307.     return true;
  308.    if (next != null && data != null)
  309.     return true;
  310.    return false;
  311.   }
  312.  
  313.   private Element next = null;
  314.   private Object data;
  315.  }
  316.  
  317.  /*
  318.   * public int getSize() { return size; }
  319.   */
  320.  
  321.  private int size;
  322.  private Element front;
  323.  private Element rear;
  324. }
  1. package waitingQueues.model;
  2.  
  3. import waitingQueues.WaitingQueuesException;
  4.  
  5. public interface QueueADT extends Cloneable{
  6.  /**
  7.   * Checks if the queue is full
  8.   *
  9.   * @return true ( if the queue is full)
  10.   */
  11.  public boolean isFull();
  12.  /**
  13.   * Checks if the queue is empty
  14.   *
  15.   * @return true ( if the queue is empty)
  16.   */
  17.  public boolean isEmpty();
  18.  /**
  19.   * Enqueues an object.
  20.   */
  21.  public void enqueue(Object o) throws WaitingQueuesException;
  22.  /**
  23.   * Dequeues the front of returns it.
  24.   * @return the stored object
  25.   */
  26.  public Object dequeue() throws WaitingQueuesException;
  27.  /**
  28.   * Destroys the object.
  29.   */
  30.  public void destroy();
  31.  /**
  32.   * Returns a copy of the object.
  33.   */
  34.  public Object clone();
  35. }
  1. package waitingQueues.model;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import waitingQueues.Constants;
  6. import waitingQueues.WaitingQueuesException;
  7.  
  8. /**
  9.  * The purpose of the Model is to set the input parameters on which the
  10.  * simulation will run, to generate the persons and them queues, manages those
  11.  * and retrieve the queue content.
  12.  *
  13.  * @author Marian Dan
  14.  *
  15.  */
  16. public class Model implements ModelInterface {
  17.  /**
  18.   * Default constructor
  19.   */
  20.  public Model() {
  21.   availableQueues = -1;
  22.   personArray = new ArrayList();
  23.   officeOpened = false;
  24.   message = "";
  25.   simulationTime = 0;
  26.   averageTime = 0.0;
  27.  }
  28.  
  29.  /**
  30.   * It passes a message to the controller that will redirect it to the view.
  31.   * The message will be displayed in the description field in the InputForm.
  32.   */
  33.  public String passMessage() {
  34.   String mess = message;
  35.   message = "";
  36.   return mess;
  37.  }
  38.  
  39.  /**
  40.   * Returns a String representation of the simulation time.
  41.   */
  42.  public String getSimulationTime() {
  43.   return "" + simulationTime;
  44.  
  45.  }
  46.  
  47.  /**
  48.   * It returns true if the office has been opened.
  49.   *
  50.   * @return true if the office has been opened, false otherwise
  51.   */
  52.  public boolean hasTheOfficeOpened() {
  53.   // return availableQueues >= 0;
  54.   return officeOpened;
  55.  }
  56.  
  57.  /**
  58.   * Returns an array of strings containing a representation of person’s
  59.   * characteristics.
  60.   *
  61.   * @return
  62.   */
  63.  public String[] getQueueContent(int index) {
  64.   // precondition
  65.   if (array == null)
  66.    throw new AssertionError("For some reason the queue is invalid");
  67.   if (index < 0 || index >= array.length)
  68.    throw new IllegalArgumentException("Values " + index
  69.      + " violate the precondition");
  70.  
  71.   if (array[index] == null) {
  72.    String s[] = new String[1];
  73.    s[0] = "EMPTY";
  74.    return s;
  75.   } else {
  76.    // TODO
  77.    // System.out.println("model —–" + index);
  78.    return Queue.printQueueContent(array[index]);
  79.   }
  80.  }
  81.  
  82.  /**
  83.   * It returns a string containing the parameters of the model such as the
  84.   * number of queues or clients.
  85.   */
  86.  public String toString() {
  87.   String s = "";
  88.   s += "Clients: " + iNumberOfClients + "\n" + "Queues: "
  89.     + iMaximumNumberOfQueues + "\n" + "Min Arrival Time: "
  90.     + iMinimumArrivalTime + "\n" + "Max Arrival Time: "
  91.     + iMaximumArrivalTime + "\n" + "Min Service Time: "
  92.     + iMinimumServiceTime + "\n" + "Max Service Time: "
  93.     + iMaximumServiceTime + "\n" + "Simulate for: "
  94.     + "Simulation time: " + simulationTime + "\n";
  95.   return s;
  96.  
  97.  }
  98.  
  99.  /**
  100.   * Sets the parameters of the simulations.
  101.   *
  102.   * @param numberOfClients -
  103.   *            clients
  104.   * @param maximumNumberOfQueues -
  105.   *            queues
  106.   * @param minimumArrivalTime -
  107.   *            minimum arrival time
  108.   * @param maximumArrivalTime -
  109.   *            maximum arrival time
  110.   * @param minimumServiceTime -
  111.   *            minimum service time
  112.   * @param maximumServiceTime -
  113.   *            maximum service time
  114.   */
  115.  public void setSimulationParameters(int numberOfClients,
  116.    int maximumNumberOfQueues, int minimumArrivalTime,
  117.    int maximumArrivalTime, int minimumServiceTime,
  118.    int maximumServiceTime) {
  119.  
  120.   setNumberOfClients(numberOfClients);
  121.   setMaximumNumberOfQueues(maximumNumberOfQueues);
  122.   setServiceTimeLimits(minimumServiceTime, maximumServiceTime);
  123.   setArrivalTimeLimits(minimumArrivalTime, maximumArrivalTime);
  124.   array = new QueueADT[maximumNumberOfQueues];
  125.   queueFinishTime = new int[maximumNumberOfQueues];
  126.  
  127.   for (int i = 0; i < maximumNumberOfQueues; i++) {
  128.    queueFinishTime[i] = 0;
  129.   }
  130.   for (int i = 0; i < numberOfClients; i++) {
  131.    PersonInterface p = createPerson(i);
  132.    personArray.add(p);
  133.   }
  134.  
  135.   /*
  136.    * if (personArray != null) java.util.Collections.sort(personArray);
  137.    */
  138.  }
  139.  
  140.  /**
  141.   * It simulates the queue operations
  142.   */
  143.  public void simulate() throws WaitingQueuesException {
  144.  
  145.   ++simulationTime;
  146.  
  147.   if (simulationTime > 0) {
  148.    // compute waiting times
  149.    updateWaitingAndServingTime();
  150.    for (int i = 0; i < array.length; i++)
  151.     movingFromThisQueue(i);
  152.   }
  153.  
  154.   // add arrived persons into the queue
  155.  
  156.   if (personArray != null) {
  157.    boolean found;
  158.    do {
  159.     found = false;
  160.     for (int i = 0; i < personArray.size(); i++) {
  161.      Object obj = personArray.get(i);
  162.      if (!(obj instanceof PersonInterface))
  163.       throw new AssertionError(
  164.         "The array contains an invalid object, that is not a person");
  165.  
  166.      PersonInterface p = (PersonInterface) obj;
  167.      if (p.getArrivalTime() == (simulationTime)) {
  168.       addPersonToQueue(p);
  169.       p.incrementWaitingTime(1);
  170.       totalTime++;
  171.       // TODO
  172.       // System.out.println("model *"+p.toString());
  173.       personArray.remove(i);
  174.       found = true;
  175.       break;
  176.      }
  177.      // System.out.println("model +"+" "+p.getArrivalTime()+"
  178.      // "+simulationTime+(p.getArrivalTime() == simulationTime));
  179.     }
  180.    } while (found);
  181.   }
  182.  
  183.  }
  184.  
  185.  /**
  186.   * Resets the model.
  187.   */
  188.  public void reset() {
  189.   // addMessage("The model has been reset.");
  190.   if (array != null) {
  191.    for (int i = 0; i < array.length; i++) {
  192.     Object obj = array[i];
  193.     if (obj instanceof QueueADT) {
  194.      QueueADT q = (QueueADT) obj;
  195.      q.destroy();
  196.      q = null;
  197.     }
  198.     array[i] = null;
  199.    }
  200.   }
  201.   array = null;
  202.   if (personArray != null) {
  203.    for (int i = 0; i < personArray.size(); i++) {
  204.     Object obj = personArray.get(i);
  205.     if (obj instanceof QueueADT) {
  206.      PersonInterface q = (PersonInterface) obj;
  207.      q.destroy();
  208.      q = null;
  209.     }
  210.     // personArray.remove(i);
  211.    }
  212.    personArray.clear();
  213.    // personArray = new ArrayList();
  214.   }
  215.   availableQueues = -1;
  216.   officeOpened = false;
  217.   simulationTime = 0;
  218.   totalTime = 0;
  219.   nrPersons = 0;
  220.  }
  221.  
  222.  /**
  223.   * Returns a string representation of the average time.
  224.   */
  225.  public String getAverageTime() {
  226.   double displayTime = averageTime;
  227.   return "" + displayTime;
  228.  }
  229.  
  230.  /**
  231.   * Returns true if all the persons were served.
  232.   */
  233.  public boolean allPersonsServed() {
  234.   if (simulationTime <= iMaximumArrivalTime)
  235.    return false;
  236.   boolean ok = true;
  237.   for (int i = 0; i < array.length; i++)
  238.    if (!array[i].isEmpty())
  239.     ok = false;
  240.   return ok;
  241.  }
  242.  
  243.  private void setServiceTimeLimits(int minimumServiceTime,
  244.    int maximumServiceTime) {
  245.   // precondition
  246.   if (minimumServiceTime < Constants.MINIMUM_SERVICE_TIME
  247.     || minimumServiceTime > Constants.MAXIMUM_SERVICE_TIME
  248.     || maximumServiceTime < Constants.MINIMUM_SERVICE_TIME
  249.     || maximumServiceTime > Constants.MAXIMUM_SERVICE_TIME
  250.     || minimumServiceTime > maximumServiceTime)
  251.    throw new IllegalArgumentException("Values " + minimumServiceTime
  252.      + "," + maximumServiceTime + " violate the precondition");
  253.   iMinimumServiceTime = minimumServiceTime;
  254.   iMaximumServiceTime = maximumServiceTime;
  255.   // postcondition
  256.   if (minimumServiceTime != iMinimumServiceTime
  257.     || maximumServiceTime != iMaximumServiceTime)
  258.    throw new AssertionError("Values " + minimumServiceTime + ","
  259.      + maximumServiceTime + " violate the postcondition");
  260.  }
  261.  
  262.  private void setArrivalTimeLimits(int minimumArrivalTime,
  263.    int maximumArrivalTime) {
  264.   // precondition
  265.   if (minimumArrivalTime < Constants.MINIMUM_ARRIVAL_TIME
  266.     || minimumArrivalTime > Constants.MAXIMUM_ARRIVAL_TIME
  267.     || maximumArrivalTime < Constants.MINIMUM_ARRIVAL_TIME
  268.     || maximumArrivalTime > Constants.MAXIMUM_ARRIVAL_TIME
  269.     || minimumArrivalTime > maximumArrivalTime)
  270.    throw new IllegalArgumentException("Values " + minimumArrivalTime
  271.      + "," + maximumArrivalTime + " violate the precondition");
  272.   iMinimumArrivalTime = minimumArrivalTime;
  273.   iMaximumArrivalTime = maximumArrivalTime;
  274.   // postcondition
  275.   if (minimumArrivalTime != iMinimumArrivalTime
  276.     || maximumArrivalTime != iMaximumArrivalTime)
  277.    throw new AssertionError("Values " + minimumArrivalTime + ","
  278.      + maximumArrivalTime + " violate the postcondition");
  279.  }
  280.  
  281.  private void setNumberOfClients(int numberOfClients) {
  282.   // precondition
  283.   if (numberOfClients < Constants.MINIMUM_NUMBER_OF_CLIENTS
  284.     || numberOfClients > Constants.MAXIMUM_NUMBER_OF_CLIENTS)
  285.    throw new IllegalArgumentException("Values " + numberOfClients
  286.      + " violate the precondition");
  287.  
  288.   iNumberOfClients = numberOfClients;
  289.   // postcondition
  290.   if (numberOfClients != iNumberOfClients)
  291.    throw new AssertionError("Values " + iNumberOfClients + ","
  292.      + numberOfClients + " violate the postcondition");
  293.  }
  294.  
  295.  private void setMaximumNumberOfQueues(int maximumNumberOfQueues) {
  296.   // precondition
  297.   if (maximumNumberOfQueues < Constants.MINIMUM_NUMBER_OF_QUEUES
  298.     || maximumNumberOfQueues > Constants.MAXIMUM_NUMBER_OF_QUEUES)
  299.    throw new IllegalArgumentException("Values "
  300.      + maximumNumberOfQueues + " violate the precondition");
  301.  
  302.   iMaximumNumberOfQueues = maximumNumberOfQueues;
  303.  
  304.   // postcondition
  305.   if (maximumNumberOfQueues != iMaximumNumberOfQueues)
  306.    throw new AssertionError("Values " + iNumberOfClients + ","
  307.      + maximumNumberOfQueues + " violate the postcondition");
  308.  }
  309.  
  310.  /*
  311.   * private void openNewQueue() { if (availableQueues + 1 >
  312.   * iMaximumNumberOfQueues) throw new AssertionError( "Maximum number of
  313.   * queues was reached. No other queues can be openned."); QueueADT queue =
  314.   * new Queue(); int openedQueue = -1; for (int i = 0; i < availableQueues;
  315.   * i++) if (array[i] == null) openedQueue = i; if (openedQueue == -1)
  316.   * openedQueue = ++availableQueues; array[openedQueue] = queue;
  317.   * addMessage("Opened a new customer queue, the queue number # " +
  318.   * openedQueue); }
  319.   */
  320.  
  321.  private void openTheOffice() {
  322.   if (hasTheOfficeOpened())
  323.    throw new AssertionError("The office has been already openned.");
  324.   if (!hasTheOfficeOpened()) {
  325.    // openNewQueue();
  326.    officeOpened = true;
  327.    // addMessage("The office has been open");
  328.   }
  329.  }
  330.  
  331.  private void addPersonToQueue(PersonInterface person)
  332.    throws WaitingQueuesException {
  333.   // check person
  334.   if (!hasTheOfficeOpened()) {
  335.    openTheOffice();
  336.   }
  337.   int n;
  338.   n = optimization(person);
  339.   if (n == -1)
  340.    throw new AssertionError("Invalid queue functionning");
  341.  
  342.   addMessage("Person " + person.getPersonId() + " entered queue #" + n);
  343.   array[n].enqueue(person);
  344.   nrPersons++;
  345.  }
  346.  
  347.  private void movingFromThisQueue(int queueId) throws WaitingQueuesException {
  348.  
  349.   if (array[queueId] != null) {
  350.    Object temp = ((QueueADT) array[queueId]).clone();
  351.    Object old = ((QueueADT) array[queueId]).clone();
  352.  
  353.    QueueADT q = (QueueADT) temp;
  354.    QueueADT temp2 = new Queue();
  355.  
  356.    PersonInterface person;
  357.    Object obj = null;
  358.    if (q.isEmpty()) {
  359.     return;
  360.    } else {
  361.     while (!q.isEmpty()) {
  362.      try {
  363.       obj = q.dequeue();
  364.       if (!q.isEmpty())
  365.        temp2.enqueue(obj);
  366.      } catch (WaitingQueuesException e) {
  367.       e.printStackTrace();
  368.      }
  369.     }
  370.    }
  371.    if (obj != null) {
  372.     assert (obj instanceof PersonInterface) : "cast error in model";
  373.     person = (PersonInterface) obj;
  374.     array[queueId] = temp2;
  375.     int n = optimization(person);
  376.     if (n != queueId) {
  377.      addMessage("Person " + person.getPersonId()
  378.        + "abandonned queue " + queueId + " and entered "
  379.        + n);
  380.      array[n].enqueue(person);
  381.     } else
  382.      array[queueId] = (QueueADT) old;
  383.  
  384.    }
  385.   }
  386.   return;
  387.  
  388.  }
  389.  
  390.  private int optimization(PersonInterface person) {
  391.   for (int i = 0; i < array.length; i++)
  392.    if (array[i] == null)
  393.     array[i] = new Queue();
  394.   int min = computeQueueFinishTime(array[0]);
  395.   int index_min = 0;
  396.   if (min != 0)
  397.    for (int i = 1; i < array.length; i++) {
  398.     int size = computeQueueFinishTime(array[i]);
  399.     if (size == 0) {
  400.      min = 0;
  401.      index_min = i;
  402.      break;
  403.     } else if (min > size) {
  404.      min = size;
  405.      index_min = i;
  406.     }
  407.    }
  408.   return index_min;
  409.  }
  410.  
  411.  private static int computeQueueFinishTime(QueueADT queue) {
  412.   if (queue == null)
  413.    return 0;
  414.  
  415.   QueueADT q = (QueueADT) queue.clone();
  416.  
  417.   if (q.isEmpty()) {
  418.    return 0;
  419.   }
  420.  
  421.   int n = 0;
  422.   while (!q.isEmpty()) {
  423.    try {
  424.     Object object = q.dequeue();
  425.     if (!(object instanceof Person))
  426.      throw new AssertionError(
  427.        "For some reason the queue returned an invalid object.");
  428.     Person i = (Person) object;
  429.     n += i.getServiceTime();
  430.     n++;
  431.    } catch (WaitingQueuesException e) {
  432.     e.printStackTrace();
  433.    }
  434.   }
  435.   if (n == 0) {
  436.    throw new AssertionError("The queue should not be void");
  437.   }
  438.   return n;
  439.  }
  440.  
  441.  private static void updateQueueWaitingTime(QueueADT queue) {
  442.   if (queue == null)
  443.    return;
  444.   QueueADT q = queue;
  445.   QueueADT temp = new Queue();
  446.   if (q.isEmpty()) {
  447.    return;
  448.   }
  449.  
  450.   while (!q.isEmpty()) {
  451.    try {
  452.     Object object = q.dequeue();
  453.     if (!(object instanceof Person))
  454.      throw new AssertionError(
  455.        "For some reason the queue returned an invalid object.");
  456.     PersonInterface i = (PersonInterface) object;
  457.     i.incrementWaitingTime(1);
  458.     totalTime++;
  459.     temp.enqueue(i);
  460.    } catch (WaitingQueuesException e) {
  461.     e.printStackTrace();
  462.    }
  463.   }
  464.  
  465.   while (!temp.isEmpty()) {
  466.    try {
  467.     Object object = temp.dequeue();
  468.     q.enqueue(object);
  469.    } catch (WaitingQueuesException e) {
  470.     e.printStackTrace();
  471.    }
  472.   }
  473.  
  474.   temp.destroy();
  475.   temp = null;
  476.  
  477.  }
  478.  
  479.  private static void updateQueueServiceTime(QueueADT queue, int queueId) {
  480.   if (queue == null)
  481.    return;
  482.   QueueADT q = queue;
  483.   QueueADT temp = new Queue();
  484.   if (q.isEmpty()) {
  485.    return;
  486.   }
  487.  
  488.   if (!q.isEmpty()) {
  489.    try {
  490.     // get the first entry
  491.     Object object = q.dequeue();
  492.     if (!(object instanceof Person))
  493.      throw new AssertionError(
  494.        "For some reason the queue returned an invalid object.");
  495.     Person i = (Person) object;
  496.     i.decrementServiceTime(1);
  497.     if (i.personWasServed()) {
  498.      addMessage("Person " + i.getPersonId()
  499.        + " was served and exited queue #" + queueId);
  500.      i.destroy();
  501.      i = null;
  502.     } else
  503.      temp.enqueue(i);
  504.    } catch (WaitingQueuesException e) {
  505.     e.printStackTrace();
  506.    }
  507.   }
  508.  
  509.   while (!q.isEmpty()) {
  510.    try {
  511.     Object object = q.dequeue();
  512.     temp.enqueue(object);
  513.    } catch (WaitingQueuesException e) {
  514.     e.printStackTrace();
  515.    }
  516.   }
  517.  
  518.   while (!temp.isEmpty()) {
  519.    try {
  520.     Object object = temp.dequeue();
  521.     q.enqueue(object);
  522.    } catch (WaitingQueuesException e) {
  523.     e.printStackTrace();
  524.    }
  525.   }
  526.   temp.destroy();
  527.   temp = null;
  528.  }
  529.  
  530.  private void updateWaitingAndServingTime() {
  531.   for (int i = 0; i < array.length; i++)
  532.    if (array[i] != null) {
  533.     updateQueueServiceTime(array[i], i);
  534.     updateQueueWaitingTime(array[i]);
  535.     queueFinishTime[i] = computeQueueFinishTime(array[i]);
  536.    }
  537.   // System.out.println(" model …. " + totalTime + " " + nrPersons);
  538.   this.averageTime = totalTime / (1.0 * nrPersons);
  539.  }
  540.  
  541.  /*
  542.   * public int availableOffices() { return availableQueues; }
  543.   */
  544.  
  545.  private static void addMessage(String sMessage) {
  546.   message += "\n" + sMessage;
  547.  }
  548.  
  549.  private PersonInterface createPerson(int id) {
  550.   int service = randomNumber(iMinimumServiceTime, iMaximumServiceTime);
  551.   int arrival = randomNumber(iMinimumArrivalTime, iMaximumArrivalTime);
  552.   PersonInterface p = new Person(id, service, arrival);
  553.   // TODO
  554.   //System.out.println(p.toString());
  555.   return p;
  556.  }
  557.  
  558.  private static int randomNumber(int minimumValue, int maximumValue) {
  559.   if (minimumValue < 0 || maximumValue < 0)
  560.    throw new IllegalArgumentException("Values " + minimumValue + ","
  561.      + maximumValue + " violates the precondition");
  562.  
  563.   int n;
  564.   do {
  565.    n = minimumValue + (int) (Math.random() * maximumValue);
  566.   } while (n < minimumValue || n > maximumValue);
  567.  
  568.   if (!(n >= minimumValue || n <= maximumValue))
  569.    throw new AssertionError("Invalid random number " + n
  570.      + " was generated.");
  571.   return n;
  572.  
  573.  }
  574.  
  575.  // private static ArrayList array = null;
  576.  private static QueueADT[] array;
  577.  private int queueFinishTime[];
  578.  private int availableQueues;
  579.  private int iNumberOfClients;
  580.  private int iMaximumNumberOfQueues;
  581.  private int iMinimumArrivalTime;
  582.  private int iMaximumArrivalTime;
  583.  private int iMinimumServiceTime;
  584.  private int iMaximumServiceTime;
  585.  private static String message;
  586.  private boolean officeOpened;
  587.  private int simulationTime;
  588.  private ArrayList personArray;
  589.  
  590.  private double averageTime;
  591.  private static int nrPersons = 0;
  592.  private static int totalTime = 0;
  593.  
  594. }
  1. package waitingQueues.model;
  2.  
  3. import waitingQueues.WaitingQueuesException;
  4. /**
  5.  * Interface for the Model
  6.  * @author Marian Dan
  7.  *
  8.  */
  9. public interface ModelInterface {
  10.  //public int availableOffices();
  11.  
  12.  /**
  13.   * It passes a message to the controller that will redirect it to the view.
  14.   * The message will be displayed in the description field in the InputForm.
  15.   */
  16.  public String passMessage();
  17.  /**
  18.   * Sets the parameters of the simulations.
  19.   *
  20.   * @param numberOfClients -
  21.   *            clients
  22.   * @param maximumNumberOfQueues -
  23.   *            queues
  24.   * @param minimumArrivalTime -
  25.   *            minimum arrival time
  26.   * @param maximumArrivalTime -
  27.   *            maximum arrival time
  28.   * @param minimumServiceTime -
  29.   *            minimum service time
  30.   * @param maximumServiceTime -
  31.   *            maximum service time
  32.   */
  33.  public void setSimulationParameters(int numberOfClients,
  34.    int maximumNumberOfQueues, int minimumArrivalTime,
  35.    int maximumArrivalTime, int minimumServiceTime,
  36.    int maximumServiceTime);
  37.  /**
  38.   * It simulates the queue operations
  39.   */
  40.  public void simulate() throws WaitingQueuesException;
  41.  /**
  42.   * Resets the model.
  43.   */
  44.  public void reset();
  45.  /**
  46.   * Returns a String representation of the simulation time.
  47.   */
  48.  public String getSimulationTime();
  49.  /**
  50.   * Returns an array of strings containing a representation of person’s
  51.   * characteristics.
  52.   *
  53.   * @return
  54.   */
  55.  public String[] getQueueContent(int index);
  56.  /**
  57.   * Returns a string representation of the average time.
  58.   */
  59.  public String getAverageTime();
  60.  /**
  61.   * Returns true if all the persons were served.
  62.   */
  63.  public boolean allPersonsServed();
  64. }
  1. package waitingQueues.controller;
  2.  
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import waitingQueues.Constants;
  6. import waitingQueues.WaitingQueuesException;
  7. import waitingQueues.model.ModelInterface;
  8. import waitingQueues.view.ViewInterface;
  9.  
  10. import java.util.Timer;
  11. import java.util.TimerTask;
  12.  
  13. /**
  14.  *
  15.  * The purpose of the Controller class is to address / handle de interactions
  16.  * between the Model and the View. The Controller handles all the events that
  17.  * may arise during the program execution, such as the user clicking on a
  18.  * button, and triggers changes in the Model. In this way all the three
  19.  * components the Controller, Model and View are interconnected.
  20.  *
  21.  * @author Marian Dan
  22.  *
  23.  */
  24. public class Controller implements ControllerInterface {
  25.  /**
  26.   * Default constructor (no arguments) – should be avoided
  27.   *
  28.   */
  29.  public Controller() {
  30.   this(null, null);
  31.  }
  32.  
  33.  /**
  34.   * Constructor for the controller class It manages the interaction between
  35.   * the user, View and Model
  36.   *
  37.   * @param view
  38.   * @param model
  39.   * @pre view !=null && model!=null
  40.   * @post this.view!=null && this.model!=null
  41.   */
  42.  public Controller(ViewInterface view, ModelInterface model) {
  43.   assert (view != null) : "view is null";
  44.   assert (model != null) : "model is null";
  45.  
  46.   this.view = view;
  47.   this.model = model;
  48.   // assign the button listener
  49.   view.addSimulateBtnListener(new SimulateListener());
  50.  }
  51.  
  52.  /**
  53.   * The class manages the events that happen when the user presses on the
  54.   * button
  55.   *
  56.   */
  57.  private final class SimulateListener implements ActionListener {
  58.   private String oldParameters = "";
  59.  
  60.   /**
  61.    * @pre e!=null
  62.    */
  63.   public final void actionPerformed(ActionEvent e) {
  64.    try {
  65.     assert (e != null) : "Null reference in SimulateListener";
  66.     // /System.out.println("controller simulate \n" +
  67.     // view.toString());
  68.     int clients = view.getNumberOfClients();
  69.     int queues = view.getNumberOfQueues();
  70.     int minArrivalTime = view.getMinimumArrivalTime();
  71.     int maxArrivalTime = view.getMaximumArrivalTime();
  72.     int minServiceTime = view.getMinimumServiceTime();
  73.     int maxServiceTime = view.getMaximumServiceTime();
  74.     int simulateForTime = view.getTimeForSimulation();
  75.     // check if the parameters have changed
  76.     String currentParameters = "" + clients + queues
  77.       + minArrivalTime + maxArrivalTime + minServiceTime
  78.       + maxServiceTime;
  79.     if (clients < 1 || queues < 1 || minArrivalTime < 1
  80.       || maxArrivalTime < 1 || minServiceTime < 1
  81.       || maxServiceTime < 1 || simulateForTime < 1)
  82.      throw new WaitingQueuesException(
  83.        "Parameters are integer numbers greather or equal to one");
  84.     if (minArrivalTime > maxArrivalTime
  85.       || minServiceTime > maxServiceTime)
  86.      throw new WaitingQueuesException(
  87.        "The maximum time must be at least equal to the \nminimum time, and not less as you've entered.");
  88.  
  89.     if (maxArrivalTime > Constants.MAXIMUM_ARRIVAL_TIME)
  90.      throw new WaitingQueuesException(
  91.        "The maximum arrival time must be at most "
  92.          + Constants.MAXIMUM_ARRIVAL_TIME);
  93.     if (maxServiceTime > Constants.MAXIMUM_SERVICE_TIME)
  94.      throw new WaitingQueuesException(
  95.        "The maximum service time must be at most "
  96.          + Constants.MAXIMUM_SERVICE_TIME);
  97.  
  98.     if (minArrivalTime < Constants.MINIMUM_ARRIVAL_TIME)
  99.      throw new WaitingQueuesException(
  100.        "The minimum arrival time must be at least "
  101.          + Constants.MINIMUM_ARRIVAL_TIME);
  102.     if (minServiceTime < Constants.MINIMUM_SERVICE_TIME)
  103.      throw new WaitingQueuesException(
  104.        "The minimum service time must be at least "
  105.          + Constants.MINIMUM_SERVICE_TIME);
  106.  
  107.     if (currentParameters.compareTo(oldParameters) != 0
  108.       || model.allPersonsServed()) {
  109.      oldParameters = currentParameters;
  110.  
  111.      view.reset();
  112.      model.reset();
  113.  
  114.      model.setSimulationParameters(clients, queues,
  115.        minArrivalTime, maxArrivalTime, minServiceTime,
  116.        maxServiceTime);
  117.  
  118.      for (int i = 0; i < view.getNumberOfQueues(); i++) {
  119.       view.addQueue(i);
  120.       String s[] = { "EMPTY" };
  121.       view.setQueueContent(i, s);
  122.      }
  123.      view.setVisibilityOfOutput(true);
  124.      view.setSimulationTime(model.getSimulationTime());
  125.      view.enableNewSimulation(false);
  126.      startSimulation(simulateForTime);
  127.      // view.enableNewSimulation(true);
  128.     } else {
  129.      // simulateModel();
  130.      view.enableNewSimulation(false);
  131.      startSimulation(simulateForTime);
  132.      // view.enableNewSimulation(true);
  133.     }
  134.  
  135.    } catch (WaitingQueuesException er) {
  136.     view.showErrorMessage(er.getMessage());
  137.    }
  138.    return;
  139.   }
  140.  }
  141.  
  142.  /**
  143.   * The method initializes the model and runs the simulation on it
  144.   *
  145.   * @throws WaitingQueuesException
  146.   */
  147.  private void simulateModel() throws WaitingQueuesException {
  148.   model.simulate();
  149.   String empty[] = { "EMPTY" };
  150.   for (int i = 0; i < view.getNumberOfQueues(); i++) {
  151.    String s[] = model.getQueueContent(i);
  152.    if (s != null) {
  153.     view.setQueueContent(i, s);
  154.    } else
  155.     view.setQueueContent(i, empty);
  156.    view.setAverageTime(model.getAverageTime());
  157.   }
  158.   view.setSimulationTime(model.getSimulationTime());
  159.   view.appendMessageToMessageQueue(model.passMessage());
  160.  }
  161.  
  162.  /**
  163.   * It starts the simulation
  164.   *
  165.   * @param simulationTimeAmount -
  166.   *            the amount of time for which which the simulation is run
  167.   */
  168.  private void startSimulation(int simulationTimeAmount) {
  169.   timer = new Timer();
  170.   remainingSimulationTime = simulationTimeAmount;
  171.   timer.schedule(new Task(), 1000);
  172.  
  173.  }
  174.  
  175.  /**
  176.   * The class is used to creat a timer task (that uses a thread that executes
  177.   * the simulation at specific time intervals)
  178.   */
  179.  private class Task extends TimerTask {
  180.   public void run() {
  181.    try {
  182.     if (remainingSimulationTime > 0 && !model.allPersonsServed()) {
  183.      // do smth
  184.      remainingSimulationTime–;
  185.      simulateModel();
  186.      timer.schedule(new Task(), 1000);
  187.     } else {
  188.      timer.cancel(); // Terminate the thread
  189.      view.enableNewSimulation(true);
  190.      if (model.allPersonsServed())
  191.       view.showMessage(model.getAverageTime(),
  192.         "Final average time is:");
  193.     }
  194.    } catch (WaitingQueuesException er) {
  195.     view.showErrorMessage(er.getMessage());
  196.     timer.cancel();
  197.     timer = null;
  198.     view.enableNewSimulation(true);
  199.    }
  200.   }
  201.  }
  202.  
  203.  /*
  204.   * private class ToDo { Timer timer; int seconds;
  205.   *
  206.   * public ToDo(int seconds) { timer = new Timer(); this.seconds = seconds;
  207.   * timer.schedule(new ToDoTask(), seconds * 1000); }
  208.   *
  209.   * class ToDoTask extends TimerTask { public void run() {
  210.   * System.out.println("controller OK, It's time to do something!"); if
  211.   * (remainingSimulationTime > 0) { // do smth remainingSimulationTime–;
  212.   * System.out.println("controller " + remainingSimulationTime);
  213.   * timer.schedule(new ToDoTask(), seconds * 1000); } else timer.cancel(); //
  214.   * Terminate the thread } } }
  215.   */
  216.  
  217.  private int remainingSimulationTime = 0;
  218.  private ViewInterface view;
  219.  private ModelInterface model;
  220.  private Timer timer;
  221. }
  1. package waitingQueues.controller;
  2.  
  3. /**
  4.  * The Controller interface is a dump file
  5.  * @author Marian Dan
  6.  *
  7.  */
  8. public interface ControllerInterface {
  9.  
  10. }

Memory architecture simulation (Java homework)

Posted by marian on June 29, 2009

The homework was structured as follows:

memory

|-controller

|    |-Controller.java

|    |-ControllerInterface.java

|-model

|-view

|-Main.java

|-MemoryException

Main.java

  1. package memory;
  2.  
  3. import javax.swing.JFrame;
  4.  
  5. import memory.Main;
  6. import memory.controller.Controller;
  7. import memory.controller.ControllerInterface;
  8. import memory.model.Model;
  9. import memory.model.ModelInterface;
  10. import memory.view.View;
  11. import memory.view.ViewInterface;
  12.  
  13. public class Main {
  14. /*
  15. * The default constructor on the Main class.
  16. */
  17. public Main(){
  18. // let decorations be available
  19. JFrame.setDefaultLookAndFeelDecorated(true);
  20. // Create and set up the window.
  21.  
  22. //create an instance of the user interface/ the view
  23. final ViewInterface ui = new View();
  24. //create an instance of the model we are working on
  25. final ModelInterface model=new Model();
  26. //create an instance of the controller that manages the
  27. //interactions between the model and the
  28. final ControllerInterface controller=new Controller(ui,model);
  29. }
  30. //the application is designed to run both as an applet or as an
  31. //application
  32. public void init(){
  33.  
  34. }
  35. public void start(){
  36.  
  37. }
  38. public void stop(){
  39.  
  40. }
  41. public void destroy(){
  42.  
  43. }
  44. //for running as an application
  45. public static void main(String args[]) {
  46. final Main  application = new Main();
  47. }
  48.  
  49. /**
  50. * The standard public String toString() is overridden
  51. */
  52. public String toString(){
  53. return "This is the main application";
  54. }
  55. /**
  56. * Check to see if this is the instance of the main application
  57. */
  58. public boolean equals(Object other) {
  59. if(this==other) return true;
  60. else return false;
  61. }
  62.  
  63. private static final long serialVersionUID = 2028805364097710940L;
  64.  
  65. }
  1. package memory;
  2.  
  3. /**
  4.  * The purpose of this class is to provide means of treating exceptions,
  5.  * that arise when the program is running. The class FlipFlopException
  6.  * inherits the methods of the default Java class Exception.
  7.  */
  8. public class MemoryException extends Exception{
  9.  /**
  10.   * Default constructor
  11.   * @param String
  12.   */
  13.  public MemoryException(String mess){
  14.   message=mess;
  15.   //System.out.println("Exception: "+message);
  16.  }
  17.  /**
  18.   * This method overrides the default toString() method
  19.   *
  20.   */
  21.  public String toString()
  22.  {
  23.   return message;
  24.  }
  25.  /**
  26.   * Check to see if this is the instance of the View
  27.   */
  28.  public boolean equals(Object other) {
  29.   if(other instanceof MemoryException){
  30.    MemoryException m=(MemoryException)other;
  31.    if(m.toString().equals(message)) return true;
  32.    else return false;
  33.    
  34.   }else return false;
  35.  }
  36.  private static final long serialVersionUID = 4593665563049627269L;
  37.  //stores the error message
  38.  private String message="";
  39. }
  1. package memory.controller;
  2.  
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.MouseEvent;
  6. import java.util.StringTokenizer;
  7. import javax.swing.JComboBox;
  8.  
  9. import memory.MemoryException;
  10. import memory.model.ModelInterface;
  11. import memory.view.MemoryShape;
  12. import memory.view.Shape;
  13. import memory.view.ShapeMouseInterface;
  14. import memory.view.SignalShape;
  15. import memory.view.ViewInterface;
  16. import memory.view.WorkingPanel;
  17.  
  18. public final class Controller implements ControllerInterface {
  19.  /**
  20.   * Default constructor (no arguments) – should be avoided
  21.   *
  22.   */
  23.  public Controller() {
  24.   this(null, null);
  25.  }
  26.  
  27.  public Controller(ViewInterface view, ModelInterface model) {
  28.   this.view = view;
  29.   this.model = model;
  30.   view.addWriteBtnListener(new WriteListener());
  31.   view.addMemoryBtnListener(new MemoryListener());
  32.   view.addReturnBtnListener(new ReturnListener());
  33.   view.addComboBoxListener(new ChoiceComboBoxListener());
  34.   view.addWorkingPanelMouseListener(new WorkingPanelMouseListener());
  35.  
  36.  }
  37.  
  38.  private static final class WriteListener implements ActionListener {
  39.   public final void actionPerformed(ActionEvent e) {
  40.    //System.out.println("write");
  41.    reprogramming = true;
  42.    return;
  43.   }
  44.  }
  45.  
  46.  private static final class MemoryListener implements ActionListener {
  47.   public final void actionPerformed(ActionEvent e) {
  48.    //System.out.println("memory");
  49.    view.setInputPanel();
  50.    return;
  51.   }
  52.  }
  53.  
  54.  private static final class ReturnListener implements ActionListener {
  55.   public final void actionPerformed(ActionEvent e) {
  56.    int type = 0;
  57.    int depth = 0;
  58.    int length = 0;
  59.    //System.out.println("return");
  60.    String name = "";
  61.    if(shapeToBeProgrammed==null) reprogramming=false;
  62.    try {
  63.     if (!reprogramming) {
  64.      System.out.println("not programming");
  65.      name = view.getMemoryName();
  66.      if (name == null)
  67.       throw new MemoryException("Please enter memory name");
  68.      if (name.length() == 0)
  69.       throw new MemoryException("Please enter memory name");
  70.      if (temporaryChoice == null) {
  71.       throw new MemoryException(
  72.         "Please chose a value for the memory type.");
  73.      }
  74.      if (temporaryChoice.length() == 0) {
  75.       throw new MemoryException(
  76.         "Please chose a value for the memory type.");
  77.      }
  78.      type = 0;
  79.      if (temporaryChoice == "PROM")
  80.       type = 1;
  81.      else if (temporaryChoice == "EEPROM")
  82.       type = 2;
  83.      else if (temporaryChoice == "UVPROM")
  84.       type = 3;
  85.      else if (temporaryChoice == "RAM")
  86.       type = 4;
  87.      if (type == 0)
  88.       throw new MemoryException("Invalid choice");
  89.      try {
  90.       length = Integer.parseInt(view.getWordSize());
  91.      } catch (NumberFormatException ex) {
  92.       throw new MemoryException("The size is not valid");
  93.      }
  94.      try {
  95.       depth = Integer.parseInt(view.getMemoryDepth());
  96.      } catch (NumberFormatException ex) {
  97.       throw new MemoryException(
  98.         "The depth of memory is not valid");
  99.      }
  100.     };
  101.     if(reprogramming){
  102.      int mid = shapeToBeProgrammed.getId();
  103.      
  104.      depth=model.getMemoryDepth(mid);
  105.      length=model.getMemoryWdth(mid);
  106.      
  107.     }
  108.     String s = view.getInitialData();
  109.     int[][] a = new int[1 << depth][length];
  110.     StringTokenizer pass1 = new StringTokenizer(s);
  111.     String s2 = "";
  112.     while (pass1.hasMoreElements())
  113.      s2 += pass1.nextElement();
  114.     StringTokenizer terms = new StringTokenizer(s2, "10", true);
  115.  
  116.     for (int i = 0; i < 1 << depth; i++)
  117.      for (int j = 0; j < length; j++)
  118.       if (!terms.hasMoreTokens())
  119.        throw new MemoryException(
  120.          "Not all portions of the memory are initialized.\nPlease try again");
  121.       else {
  122.        try {
  123.         String x = terms.nextToken();
  124.  
  125.         a[i][j] = Integer.parseInt(x);
  126.         if (a[i][j] != 0 && a[i][j] != 1)
  127.          throw new MemoryException(
  128.            "Please enter a sequence of 1's and 0's.");
  129.  
  130.        } catch (NumberFormatException ex) {
  131.         throw new MemoryException(
  132.           "The initial data contains invalid characters.");
  133.        }
  134.       }
  135.     view.unsetInputPanel();
  136.     view.resetInput();
  137.     if (!reprogramming) {
  138.      int id = model.addMemory(name, depth, length, type, a);
  139.      view.addMemoryBox(model.getName(id), id, depth, length);
  140.      temporaryChoice = "";
  141.     } else {
  142.      //System.out.println("reprogramming");
  143.      int mid = shapeToBeProgrammed.getId();
  144.      //System.out.println("reprogramming memory with");
  145.      /*for(int i=0; i<a.length; i++)
  146.      {
  147.       for(int j=0; j<a[i].length; j++)
  148.        System.out.println(a[i][j]);
  149.      }*/
  150.        
  151.      model.reprogram(mid, a);
  152.      reprogramming = false;
  153.     }
  154.    } catch (MemoryException exception) {
  155.     view.showErrorMessage(exception.toString());
  156.    }finally{
  157.     shapeToBeProgrammed=null;
  158.     reprogramming = false;
  159.    }
  160.    return;
  161.   }
  162.  }
  163.  
  164.  private static final class ChoiceComboBoxListener implements ActionListener {
  165.   public final void actionPerformed(ActionEvent e) {
  166.    JComboBox cb = (JComboBox) e.getSource();
  167.    String choice = (String) cb.getSelectedItem();
  168.    temporaryChoice = choice;
  169.    //System.out.println(choice);
  170.    return;
  171.   }
  172.  }
  173.  
  174.  private final static class WorkingPanelMouseListener implements
  175.    ShapeMouseInterface {
  176.   public WorkingPanelMouseListener() {
  177.    panel = view.getWorkingPanel();
  178.   }
  179.  
  180.   public final void mousePressed(MouseEvent evt) {
  181.    // User has pressed the mouse. Find the shape that the user has
  182.    // clicked on. If there is a shape at the position when the mouse
  183.    // was clicked, then start dragging it.
  184.    // panel=view.getWorkingPanel();
  185.    int x = evt.getX();
  186.    int y = evt.getY();
  187.    for (int i = 0; i < panel.getVectorSize(); i++) {
  188.     // check shapes from back to front (from the first to the last)
  189.     Object obj = panel.getVectorElement(i);
  190.     // if this a memory shape
  191.     if (obj instanceof MemoryShape) {
  192.      MemoryShape s = (MemoryShape) obj;
  193.      if (s.containsPoint(x, y)) {
  194.       shapeBeingDragged = s;
  195.       shapeToBeProgrammed=s;
  196.       // get the coordinates
  197.       //System.out.println("Default is : "
  198.       //  + shapeBeingDragged.getId());
  199.  
  200.       oldX = x;
  201.       oldY = y;
  202.  
  203.       if (reprogramming) {
  204.        view.writeToMemory();
  205.       }
  206.  
  207.      } else {
  208.       // it is not a memory, see if it is in the signals
  209.       int n = s.getInputSignalVectorSize();
  210.       //System.out.println("n= " + n);
  211.       // detrmine the input
  212.       for (int j = 0; j < n; j++) {
  213.        Object o = s.getInputSignalVectorElement(j);
  214.        // if this is a signal shape
  215.  
  216.        if (o instanceof SignalShape) {
  217.         // cast
  218.         SignalShape sig = (SignalShape) o;
  219.         // is the pointer inside the shape
  220.         if (sig.containsPoint(x, y)) {
  221.          String inputText = view
  222.            .inputDialog("Please enter the signal value");
  223.  
  224.          int signal = 0;
  225.          // do {
  226.          try {
  227.           try {
  228.            signal = Integer
  229.              .parseInt(inputText);
  230.  
  231.           } catch (NumberFormatException ex) {
  232.            throw new MemoryException(
  233.              "The initial data contains invalid characters.\nPlease enter only 0 or 1 for signal value");
  234.           }
  235.           if (signal == 0 || signal == 1) {
  236.            // get id of the memory
  237.            int mid = s.getId();
  238.            sig.setLabel("\n" + signal);
  239.            // get id of signal
  240.            int sid = sig.getId();
  241.  
  242.            model.setInputSignal(mid, sid,
  243.              signal);
  244.            String soutput[] = model
  245.              .getOutputSignal(mid);
  246.            //System.out.println("output");
  247.            for (int k = 0; k < soutput.length; k++) {
  248.             Object o2 = s
  249.               .getOutputSignalVectorElement(k);
  250.             if (o2 instanceof SignalShape) {
  251.              SignalShape sigout = (SignalShape) o2;
  252.              sigout.setLabel("\n"
  253.                + soutput[k]);
  254.             }
  255.             //System.out.print(soutput[k]);
  256.            }
  257.            //System.out.println("<<>> " + mid
  258.            //  + " " + sid + " " + signal);
  259.            panel.repaint();
  260.            break;
  261.           } else
  262.            throw new MemoryException(
  263.              "Please enter only 0 or 1.");
  264.          } catch (MemoryException exception) {
  265.           view.showErrorMessage(exception
  266.             .toString());
  267.          }
  268.          // } while (signal != 1 && signal != 0);
  269.         }
  270.        }
  271.       }
  272.      }
  273.     }
  274.    }
  275.    //System.out.println("salut");
  276.    panel.repaint();
  277.   }
  278.  
  279.   public final void mouseDragged(MouseEvent evt) {
  280.    // the mouse is moving =>move the dragged shape
  281.    // get the mouse coordinates
  282.    int x = evt.getX();
  283.    int y = evt.getY();
  284.  
  285.    if (shapeBeingDragged != null) {
  286.     shapeBeingDragged.moveBy(x – oldX, y – oldY);
  287.     // set the old coordinates
  288.     oldX = x;
  289.     oldY = y;
  290.    }
  291.    // System.out.println("mouse moved "+x+" "+y+"\n");
  292.    panel.repaint();
  293.   }
  294.  
  295.   public final void mouseReleased(MouseEvent evt) {
  296.    shapeBeingDragged = null;
  297.    panel.repaint();
  298.   }
  299.  
  300.   public final void mouseMoved(MouseEvent evt) {
  301.  
  302.   }
  303.  
  304.   public final void mouseClicked(MouseEvent evt) {
  305.  
  306.   }
  307.  
  308.   public final void mouseEntered(MouseEvent evt) {
  309.  
  310.   }
  311.  
  312.   public final void mouseExited(MouseEvent evt) {
  313.  
  314.   }
  315.   /**
  316.    * The shape that is currently being dragged non-null value : dragging is in
  317.    * progress
  318.    */
  319.   private Shape shapeBeingDragged = null;
  320.  
  321.   /**
  322.    * The old X coordinate of the mouse
  323.    */
  324.   private int oldX;
  325.  
  326.   /**
  327.    * The old Y coordinate of the mouse
  328.    */
  329.   private int oldY;
  330.   private WorkingPanel panel;
  331.  }
  332.  /**
  333.   * The standard public String toString() is overridden
  334.   */
  335.  public String toString(){
  336.   return "The controller";
  337.  }
  338.  /**
  339.   * Check to see if this is the instance of the controller
  340.   */
  341.  public boolean equals(Object other) {
  342.   if(this==other) return true;
  343.   else return false;
  344.  }
  345.  
  346.  private static ViewInterface view;
  347.  private static ModelInterface model;
  348.  private static String temporaryChoice;
  349.  private static boolean reprogramming = false;
  350.  private static Shape shapeToBeProgrammed= null;
  351.  /**
  352.   * The mouse listener for the graphicPanel (controls the motion of states,
  353.   * transitions, guides)
  354.   */
  355. // private ShapeMouseInterface graphicPanelMouseHandler;
  356.  
  357. }
  1. package memory.controller;
  2.  
  3. public interface ControllerInterface {
  4.  
  5. }
  1. package memory.view;
  2.  
  3.  
  4.  
  5. public class Point {
  6.  /**
  7.   * Default constructor
  8.   */
  9.  public Point() {
  10.   this(null,0,0);
  11.  }
  12.  /**
  13.   * Cosntructor
  14.   * @param referencePoint
  15.   */
  16.  public Point(Point referencePoint) {
  17.   this(referencePoint,0,0);
  18.  
  19.  }
  20.  /**
  21.   * Constructor
  22.   * @param referencePoint
  23.   * @param dx
  24.   * @param dy
  25.   */
  26.  public Point(Point referencePoint, int dx, int dy){
  27.   this.dx=dx;
  28.   this.dy=dy;
  29.   //this.referencePoint = null;
  30.   this.referencePoint = referencePoint;
  31.  }
  32.  /**
  33.   * Returns the X coordinate
  34.   * @return
  35.   */
  36.  public int getX() {
  37.   if (referencePoint != null) {
  38.    return referencePoint.getX() + dx;
  39.   } else
  40.    return dx;
  41.  }
  42.  /**
  43.   * Returns the Y coordinate
  44.   * @return
  45.   */
  46.  public int getY() {
  47.   if (referencePoint != null) {
  48.    return referencePoint.getY() + dy;
  49.   } else
  50.    return dy;
  51.  }
  52.  /**
  53.   * Sets the X coordinate
  54.   * @param x
  55.   */
  56.  public void setX(int x) {
  57.   dx = x;
  58.  }
  59.  /**
  60.   * Sets the Y coordinate
  61.   * @param y
  62.   */
  63.  public void setY(int y) {
  64.   dy = y;
  65.  }
  66.  
  67.  public void setReferencePoint(Point p) {
  68.   referencePoint = p;
  69.  }
  70.  /**
  71.   * The standard public String toString() is overridden in order to give
  72.   * formatted printable version of the stored memory data
  73.   */
  74.  public String toString(){
  75.   return getX()+" "+getY();
  76.  }
  77.  /**
  78.   * We make the following assumptions: Two points are equivalent if
  79.   * they have both the same coordinates
  80.   */
  81.  public boolean equals(Object other) {
  82.   boolean b = false;
  83.   try {
  84.    Point objectRom = null;
  85.    // optimistic approach
  86.    objectRom = (Point) other;  
  87.    if (objectRom.getX()==getX() && objectRom.getY()==getY())
  88.     return true;
  89.    else return false;
  90.   } catch (ClassCastException e) {
  91.    e.printStackTrace();
  92.   }
  93.   return b;
  94.  }
  95.  
  96.  private int dx;
  97.  private int dy;
  98.  private Point referencePoint;
  99. }
  1. package memory.view;
  2.  
  3. import java.awt.BasicStroke;
  4. import java.awt.Color;
  5. import java.awt.Dimension;
  6. import java.awt.Font;
  7. import java.awt.FontMetrics;
  8. import java.awt.Graphics;
  9. import java.awt.Graphics2D;
  10. import java.awt.RenderingHints;
  11. import java.awt.geom.Rectangle2D;
  12. import java.util.StringTokenizer;
  13.  
  14. public class Shape {
  15.  public Shape() {
  16.   from = new Point();
  17.   to = new Point(from);
  18.  }
  19.  
  20.  public Shape(String label, int id) {
  21.   this();
  22.   this.label = label;
  23.   this.id = id;
  24.  }
  25.  
  26.  /**
  27.   * Function that determines whether the coordinates (x,y) are inside the
  28.   * shape
  29.   *
  30.   * @param int
  31.   * @param int
  32.   * @return boolean
  33.   */
  34.  public boolean containsPoint(int x, int y) {
  35.   /*
  36.    * if (x >= this.from.x && x <= this.from.x + width && y >= this.from.y &&
  37.    * y <= this.from.y + height) return true; else return false;
  38.    */
  39.   if (x >= from.getX() && x <= to.getX() && y >= from.getY()
  40.     && y <= to.getY()) {
  41.    //System.out.println("OK " + x + " " + y + " >> " + from.getX()
  42.    //  + " " + from.getY() + " " + to.getX() + " " + to.getY());
  43.    return true;
  44.   } else {
  45.    //System.out.println("ERR " + x + " " + y + " >> " + from.getX()
  46.    //  + " " + from.getY() + " " + to.getX() + " " + to.getY());
  47.    return false;
  48.   }
  49.  
  50.  }
  51.  
  52.  protected void draw(Graphics g) {
  53.   Graphics2D g2 = (Graphics2D) g;
  54.   BasicStroke bs; // Reference to to BasicStroke
  55.   Rectangle2D rectangle; // Reference to rectangle
  56.   float[] solid = { 12.0f, 0.0f }; // Solid line style
  57.  
  58.   // Set rendering hints to improve display quality
  59.   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  60.     RenderingHints.VALUE_ANTIALIAS_ON);
  61.  
  62.   // Set the basic stroke
  63.   bs = new BasicStroke(3.0f, BasicStroke.CAP_SQUARE,
  64.     BasicStroke.JOIN_MITER, 1.0f, solid, 0.0f);
  65.   g2.setStroke(bs);
  66.  
  67.   // Define ellipse
  68.   // rectangle = new Rectangle2D.Double(from.x + dx + 0.0, from.y + +dy +
  69.   // 0.0, to.x-from.x+0.0, to.y-from.y + 0.0);
  70.   // rectangle = new
  71.   // Rectangle2D.Double(to.getX()-from.getX(),to.getY()-from.getY() ,
  72.   // to.getX(), from.getY());
  73.   rectangle = new Rectangle2D.Double(from.getX(), from.getY(), to.getX()
  74.     – from.getX(), to.getY() – from.getY());
  75.   g2.setColor(color);
  76.   g2.fill(rectangle);
  77.   g2.setFont(myFont);
  78.   g2.setBackground(Color.CYAN);
  79.   g2.setColor(Color.black);
  80.   g2.draw(rectangle);
  81.   StringTokenizer token = new StringTokenizer(label, "\n");
  82.   int i = 20;
  83.   while (token.hasMoreTokens()) {
  84.    g2.drawString(token.nextToken(), from.getX() + textX, from.getY()
  85.      + i);
  86.    i += 20;
  87.   }
  88.  }
  89.  
  90.  /**
  91.   * Get the preferred dimensions of the figure
  92.   *
  93.   * @param Graphics
  94.   *            g
  95.   * @return Dimension
  96.   */
  97.  protected final Dimension getPreferredSize(Graphics g) {
  98.   Font font = g.getFont();
  99.   StringTokenizer token = new StringTokenizer(label, "\n");
  100.   if (font != null) {
  101.    g.setFont(myFont);
  102.    // get font metrics (it looks nice if we take care of this)
  103.    FontMetrics fm = g.getFontMetrics(font);
  104.  
  105.    int width = 0;
  106.    int height = 0;
  107.    while (token.hasMoreTokens()) {
  108.     width = Math.max((fm.stringWidth(token.nextToken()) * 5) / 2,
  109.       width);
  110.     height += 20;
  111.    }
  112.    // width+=40; height+=20;
  113.    // to.setX(from.getX()+width);
  114.    // to.setY(from.getY()+height);
  115.    to.setX(width);
  116.    to.setY(height);
  117.  
  118.    return new Dimension(width, height);
  119.   } else {
  120.    return new Dimension(100, 100);
  121.   }
  122.  }
  123.  
  124.  /**
  125.   * Modifies the coordinates with dx, dy
  126.   *
  127.   * @param newX
  128.   * @param newY
  129.   */
  130.  public void moveBy(int dx, int dy) {
  131.   from.setX(from.getX() + dx);
  132.   from.setY(from.getY() + dy);
  133.   // from.setX(dx);
  134.   // from.setY(dy);
  135.   // System.out.println(dx+" "+dy);
  136.  }
  137.  
  138.  /**
  139.   * Modifies the coordinates
  140.   *
  141.   * @param newX
  142.   * @param newY
  143.   */
  144.  /*
  145.   * public void moveXY(int newX, int newY) { int dx=to.getX()-from.getX();
  146.   * int dy=to.getY()-from.getY(); from.setX(newX); from.setY(newY); to=new
  147.   * Point(from); to.setX(newX+dx); to.setY(newY+dy);
  148.   * //System.out.println("newX "+x+" newY "+y); }
  149.   */
  150.  
  151.  /*
  152.   * public void resize(int width, int height) { Point p=new
  153.   * Point(to,width-to.getX(),height-to.getY()); to=p; }
  154.   */
  155.  protected void setColor(Color color) {
  156.   this.color = color;
  157.  }
  158.  
  159.  public int getId() {
  160.   return id;
  161.  }
  162.  
  163.  protected Point getFromPoint() {
  164.   return from;
  165.  }
  166.  
  167.  protected Point getToPoint() {
  168.   return to;
  169.  }
  170.  
  171.  protected void setTextPosition(int x) {
  172.   textX = x;
  173.  }
  174.  
  175.  protected void setFromPoint(Point p) {
  176.   from = p;
  177.   to.setReferencePoint(p);
  178.  }
  179.  
  180.  protected void setLabel(String s) {
  181.   label = s;
  182.  }
  183.  
  184.  protected String getLabel() {
  185.   return label;
  186.  }
  187.  /**
  188.   * The standard public String toString() is overridden
  189.   */
  190.  public String toString(){
  191.   return label+" with id "+id;
  192.  }
  193.  /**
  194.   * Check to see if this is the instance of a shape
  195.   */
  196.  public boolean equals(Object other) {
  197.   if(other instanceof Shape)
  198.    return true;
  199.   else
  200.    return false;
  201.  }
  202.  
  203.  private Font myFont = new Font("SansSerif", Font.ITALIC, 18);
  204.  private Color color = Color.yellow;
  205.  private int textX = 0;
  206.  /*
  207.   * private int width = 40; private int height= 40;
  208.   */
  209.  private Point from = new Point();
  210.  private Point to = new Point();
  211.  private int id;
  212.  private String label;
  213. }
  1. package memory.view;
  2.  
  3. import java.awt.event.MouseListener;
  4. import java.awt.event.MouseMotionListener;
  5.  
  6. public interface ShapeMouseInterface extends MouseListener, MouseMotionListener{
  7. }
  1. package memory.view;
  2. import java.awt.Color;
  3.  
  4. public class SignalShape extends Shape{
  5.  public SignalShape(int id,String label){
  6.   super(label,id);
  7.   this.label=label;
  8.   setColor(Color.WHITE);
  9.  }
  10.  public void setLabel(String s){
  11.   value=s;
  12.   super.setLabel(label+value);
  13.  }
  14.  /**
  15.   * The standard public String toString() is overridden
  16.   */
  17.  public String toString(){
  18.   return "Signal "+ label+ " from "+super.toString();
  19.  }
  20.  /**
  21.   * Check to see if this is the instance of a Signalshape
  22.   */
  23.  public boolean equals(Object other) {
  24.   if(other instanceof SignalShape)
  25.    return true;
  26.   else
  27.    return false;
  28.  }
  29.  private String value="";
  30.  private String label;
  31. }
  1. package memory.view;
  2.  
  3. import javax.swing.JButton;
  4. import javax.swing.JComboBox;
  5. import javax.swing.JEditorPane;
  6. import javax.swing.JFrame;
  7. import javax.swing.JLabel;
  8. import javax.swing.JOptionPane;
  9. import javax.swing.JPanel;
  10. import javax.swing.JScrollPane;
  11. import javax.swing.JTextField;
  12.  
  13. import java.awt.Color;
  14. import java.awt.Dimension;
  15. import java.awt.event.ActionListener;
  16.  
  17. public final class View extends JFrame implements ViewInterface{
  18.  public View(){
  19.   //we shall manage layout, so put it to null
  20.   panel.setLayout(null);
  21.   workingPanel.setLayout(null);
  22.   commandPanel.setLayout(null);
  23.   inputPanel.setLayout(null);
  24.   inputPanel.setVisible(false);
  25.  
  26.   //set the bounds of the panel
  27.   panel.setBounds(0, 0, 600, 600);
  28.   inputPanel.setBounds(0, 0, 600, 600);
  29.  
  30.   workingPanel.setBounds(0, 0, 600, 500);
  31.  
  32.   commandPanel.setBounds(0,510,600,600);
  33.   commandRegionLabel.setBounds(0,0, 100, 20);
  34.   writeBtn.setBounds(50,20,100,20);
  35.   memoryBtn.setBounds(400,20,100,20);
  36.  
  37.    
  38.   commandPanel.add(commandRegionLabel);
  39.   commandPanel.add(writeBtn);
  40.   commandPanel.add(memoryBtn);
  41.   //commandPanel.add(promBtn);
  42.   //commandPanel.add(eepromBtn);
  43.   //commandPanel.add(uvpromBtn);
  44.  
  45.   memoryNameLabel.setBounds(10,10,100,20);
  46.   memoryTypeLabel.setBounds(10,40,100,20);
  47.   depthLabel.setBounds(10,70,100,20);
  48.   sizeLabel.setBounds(10,100,100,20);
  49.   initializationLabel.setBounds(10,120,100,20);
  50.  
  51.  
  52.   //create a scrolling area for processing area
  53.   initializedContent = new JScrollPane(editorPane);
  54.   //set just vertical scrollbar and not horizontal
  55.   initializedContent
  56.     .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  57.   //set the prefferred size
  58.   initializedContent.setPreferredSize(new Dimension(400, 400));
  59.   //set the minim size of scrooll pane
  60.   initializedContent.setMinimumSize(new Dimension(10, 10));
  61.   //just text
  62.   editorPane.setContentType("text");
  63.   //it shouldn't be editable
  64.   editorPane.setEditable(true);
  65.   initializedContent.setBounds(10, 140, 580, 400);
  66.   returnBtn.setBounds(250,540,100,20);
  67.   nameTxt.setBounds(120,10, 100, 20);
  68.   choice.setBounds(120,40, 100, 20);
  69.   choice.setEditable(true);
  70.   depthTxt.setBounds(120,70,100,20);
  71.   lengthTxt.setBounds(120,100,100,20);
  72.  
  73.   inputPanel.add(memoryNameLabel);
  74.   inputPanel.add(nameTxt);
  75.   inputPanel.add(memoryTypeLabel);
  76.   inputPanel.add(depthLabel);
  77.   inputPanel.add(sizeLabel);
  78.   inputPanel.add(initializationLabel);
  79.   inputPanel.add(initializedContent);
  80.   inputPanel.add(returnBtn);  
  81.   inputPanel.add(choice);
  82.   inputPanel.add(lengthTxt);
  83.   inputPanel.add(depthTxt);
  84.  
  85.  
  86.   panel.add(inputPanel);
  87.   panel.add(workingPanel);
  88.   panel.add(commandPanel);
  89.  
  90.   //add the panel to the frame
  91.   this.add(panel);
  92.   //set the size of the frame
  93.   this.setSize(600, 600);
  94.   // Display the window.
  95.   this.setVisible(true);
  96.   //set the default close operation, i.e. what happens when you click on X
  97.   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  98.   //it should not be resizeble
  99.   this.setResizable(false);
  100.   //set the title of the application
  101.   this.setTitle("Memory simulation application – Marian Dan Alexandru");
  102.  
  103.  
  104.  }
  105.  
  106.  /**
  107.   * Add an action listener to the Signal button
  108.   * @param e
  109.   */
  110.  public final void addWriteBtnListener(ActionListener e) {
  111.   writeBtn.addActionListener(e);
  112.  }
  113.  
  114.  /**
  115.   * Add an action listener to the PROM button
  116.   * @param e
  117.   */
  118.  /*public final void addPromBtnListener(ActionListener e) {
  119.   promBtn.addActionListener(e);
  120.  }*/
  121.  
  122.  /**
  123.   * Add an action listener to the EEPROM button
  124.   * @param e
  125.   */
  126.  /*public final void addEepromlBtnListener(ActionListener e) {
  127.   eepromBtn.addActionListener(e);
  128.  }*/
  129.  
  130.  /**
  131.   * Add an action listener to the UVPROM button
  132.   * @param e
  133.   */
  134.  /*public final void addUvpromBtnListener(ActionListener e) {<