<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="./stylesheet/mathml.xsl"?>
<!--<?xml-stylesheet type="text/xsl" href="http://www.w3.org/Math/XSL/mathml.xsl"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd" [
	<!ENTITY mathml "http://www.w3.org/1998/Math/MathML">
	<!ATTLIST maction	id ID #IMPLIED>
]>-->
<!DOCTYPE html SYSTEM "myents.dtd">
<!--<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">-->
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<link href="./stylesheet/style.css" rel="stylesheet" type="text/css" />
		<title>Understanding the Server Side Architecture</title>
	</head>
	<body>
	<h1>Understanding the server side architecture.</h1>
	<p>The serverside architecture can be taught of as two use cases. The first is to find the factor of a mersenne number to check if it is a mersenne prime or not. The second it to take a mersenne prime number and calculated the corresponding perfect number.</p>
<h2>Use Case 1: Factorising a Mersenne Number.</h2>
<p>The first of these two use cases, find the factors of a mersenne number is by far the more complicated of the two and can be taught of in terms of a number on sub use cases. It involves taking in a mersenne number and finding it factors, since this is computationally a very intensive process, the client is informed of the result asynchronously by email when the calculation is finished. </p>
<p>Furthermore this now involves the notion of state. Since with multiple client invocations, each mersenne number, and it corresponding email address and factors (once it has finished factorising) , must be remembered. Since Web Service are largely stateless services (a consequence of using http as the stateless protocol) then this stateless service must facade some type of stateful service. The client must also be informed of the results, so there must be the ability to email the results to the calling client. Finally some sort of state lifecycle management is also desirable. On a server restart the mersenne number not finished factorising should at a minimum be restarted.
The sub use cases can therefore me details at follows:</p>
<ol>
	<li>The Basic Service</li>
	<li>Making a stateless service stateful</li>
	<li>Informing the Client</li>
	<li>Making the calculation</li>
	<li>Adding a persistence mechanism</li>
</ol> 
<p>These uses case are discussed in more detail below. However before discussion them individually it is worth looking at an over view of the <a href="./images/PerfectCalc.checkMersenneNumber(1).gif">sequence diagrams</a> and <a href="./images/class_dig.gif">class diagrams</a> for this use case.</p>
		<h3>The Basic Service</h3>
		<p>   The <a href="./images/Service.gif">basic service</a> is the <code>PerfectCalc</code> interface (here is the <a href="mersenne.wsdl">WSDL</a>).  It defines two method:</p>
		<ol>
			<li>
				<code> public boolean checkMersenneNumber(MersenneNumber k, String email)</code> takes a mersenne number (a number of the form (2^n -1) not necessarily a prime number) and an email address or the invoker, and factors the mersenne number and emails the result to the invokers. If the mersenne number has no other factor other than itself and one, then it is a <a href="mersenne.xhtml">mersenne prime</a>
			</li>
			<li>
				<code> public PerfectNumber calcPerfectNumber(MersennePrime mersennePrime)</code> takes a mersenne prime and calculates the corrosponding perfect number</li>
		</ol>
		<p> 
However, the second method belongs to the second use case and will be discussed below.</p>
		<h3>Making a stateless service stateful</h3>
		<p>
The <code>FactorFactory</code> object is <a href="./images/factory.gif">factory pattern</a> responsible for making the stateless <code>PerfectCalc</code> service stateful. The <code>FactorFactory</code> object is also a singleton with a protected constructor and a public static initialiser. Here is the code listing for the <code>FactorFactory</code> object.</p>
		<pre>
/**
 * A Factory class that is also a singleton object for creating multiple instances of the stateful Factor class
 * @testcase test.TestFactorFactory
 * @version 1.0
 * @author Eoin Lane
 */
public class FactorFactory implements IFactorFactory, Observer {
    /** This contructor is only called once and when it is it the Caretaker is created and initalised */
    protected FactorFactory() {
        // Initalise the Map
        this.map = new HashMap();
        //factors = new Vector();
        caretaker = new SimpleCaretaker();
        System.out.println("Caretaker created and initialised");
    }

    /**
     * Factory method to create instances of IFactor object
     * @param mersenneNumber number of the form (2^k-1)
     * @param email of the invoking client
     */
    public IFactor getFactor(MersenneNumber mersenneNumber, String email) {
        // Store the Mersenne number k value into the Map
        Double d = new Double(mersenneNumber.getK());
        this.map.put(d, email);
        Factor factor = new Factor(mersenneNumber);
        factor.attach(this);
        factor.factorize();
        // Create a Memento of the newly created factor object
        IMemento memento = new SimpleMemento(mersenneNumber.getK(), email);
        //Tell the caretaker about it
        this.caretaker.addElement(memento);
        return (IFactor)factor;
    }

    /** Returns a one and only one instance of this class */
    public static FactorFactory getInstance() {
        if (instance == null) {
            synchronized(FactorFactory.class) {
                if (instance == null) {
                    instance = new FactorFactory();
                }
            }
        }
        return instance;
    }

    /**
     * The callback method that the subject will call on this listener
     * @param factor the finished Factor class
     */
    public void update(Factor factor) {
        // Get the k value from the mersenne number in the factor class
        double k_value = factor.getMersenneNumber().getK();
        System.out.println("Observer informed of finished calculation of mersenne number: " + k_value);
        // Get the email corrosponding th the Factor's Mersenne k value
        String email = (String)(this.map.get(new Double(k_value)));
        Collection bag = factor.getFactors();
        mail(bag, email, k_value);
        // since this Factor class has now finished process remove it it's corrosponding memento object from the caretaker
        // Create a Memento of the newly created factor object
        IMemento memento = new SimpleMemento(k_value, email);
        this.caretaker.removeElement(factor);
    }

  
    private static FactorFactory instance = null;
    // Looks after and tracks all the created Factor objects
    private ICaretaker caretaker;
    // A map containing the Mersenne number, email value pair
    Map map;
}
</pre>
		<p>

The important things to note is the protected constructor where a <code>Vector</code> of <code>Factor</code> class is created and initialised. This <code>Vector</code> keeps a record of all the created <code>Factor</code> classes. The <code>Factor</code> classes are then created with the <code>getFactor(MersenneNumber mersenneNumber)</code> method.  This pattern of using a singleton factory object to create and keep track of the generated <code>Factor</code> object, allows a stateless facade to be exposed to the outside while internally stateful classes can be created and their life cycle managed.
</p>
		<h3>Informing the Client</h3>
		<p>The <a href="./images/callback.gif">observer pattern</a> is used here as a callback to the the <code>FactorFactory</code> object to tell it that the <code>Factor</code> obejct created to factorise a particular mersenne number is now finished. To achieve this FactorFactory implements the observer interface while tthe Factor object implements the </p>
		<pre>
/**
 * This object is used to factorise a mersenne number. There are potentially many of these created in memory at run time.
 * @testcase test.TestFactor
 * @author Eoin Lane
 * @version 1.0
 */
public class Factor implements IFactor, Subject {
    /**
     * Constructor
     * @param mersenneNumber a number of the form (2^k-1)
     */
    public Factor(MersenneNumber mersenneNumber) {
        strategy = new LLFactorer();
        this.mersenneNumber = mersenneNumber;
    }

    /** Factorise this object */
    public void factorize() {
        factors = this.strategy.factorize(this.mersenneNumber);
        this.inform();
    }

    public MersenneNumber getMersenneNumber() {
        return this.mersenneNumber;
    }

    /**
     * Register an observer with this object.
     * @param observer an observer
     */
    public void attach(Observer observer) {
        observersVector.addElement(observer);
    }

    /**
     * detach an observer from this object.
     * @param observer an observer
     */
    public void detach(Observer observer) {
        observersVector.removeElement(observer);
    }

    /** Inform all the observers of an event */
    public void inform() {
        java.util.Enumeration enumeration = observers();
        Collection bag = this.getFactors();
        while (enumeration.hasMoreElements()) {
            ((Observer)enumeration.nextElement()).update(this);
        }
    }

    public Enumeration observers() {
        return ((java.util.Vector) observersVector.clone()).elements();
    }

    public Collection getFactors() {
        return factors;
    }

    /*# private FactorFactory _factorFactory; */

    // The (2^k-1) object
    private MersenneNumber mersenneNumber;
    // The factors returned by the factorisation method
    private Collection factors;
    // The strategy to be used to factorise this object
    private IFactorer strategy = null;
   
    /** @associates &lt;{Observer}&gt; */
    private Vector observersVector = new java.util.Vector();
}
</pre>
		<h3>Making the calculation</h3>
		<p>A <a href="./images/strategy.gif">strategy pattern </a>is used to implement the factorisation. The strategy pattern allows an algorithmic change of the implemention at run time, depending on the best choice of strageties (<em>i.e.</em>a different algorithm maybe used depending on the size of the number to be factored). Here is the code for <code>LLFactoer</code> a simple algormetic implementation of a the <code>IFactor</code> inferface. 
</p>
		<pre>
import java.util.Collection;
import primes.PrimeNumber;
import java.lang.Math;
import perfectNumbers.MersenneNumber;

/**
 * A simple concrete implementation of the strategy IFactorer interface
 * @testcase test.TestLLFactorer
 * @author Eoin Lane
 * @version 1.0
 */
public class LLFactorer implements IFactorer {
    public Collection factorize(Number number) {
        return new java.util.ArrayList(null);
    }

    // We can check a potential factor n of Mp by seeing if 2^p (mod n) =1
    public Collection factorize(MersenneNumber mersenneNumber) {
        System.out.println("Got Mersenne number for processsing");
        // A Collection bag to collect the factors
        Collection bag = new java.util.ArrayList();
        double maxNumberOfIteration = Math.pow((double)2, (double)(mersenneNumber.getK()));
        double siveNumberOfIteration = sive(maxNumberOfIteration);
        for (long i = 1; i &lt; siveNumberOfIteration; i++) {
            if ((factorize(mersenneNumber.getK(), (long)i) == 0)) {
                bag.add(new Long(i));
                System.out.println(i + "\t" + factorize(mersenneNumber.getK(), i));
            }
        }
        return bag;
    }

    //a simple algorithm for checking for find a^b (mod c)
    public static double factorize(double b, double c) {
        double a = 2;
        double res = 1;
        double d;
        while (b > 0) {
            d = b % 2;
            if (d == 1) {
                res = a * res;
                if (res > c) res = res % c;
            }
            a = a * a;
            if (a > c)
                a = a % c;
            b = (b - d) / 2;
        }
        return res;
    }

    // A simple sive to cut down the number of potential factors
    public static double sive(double a) {
        return (a + 1) / 2;
    }
}
</pre>
		<p>
			The <code>Factor</code> object calls the  <code>public Collection factorize(MersenneNumber mersenneNumber)</code> method defined in the <code>Factorer</code> interface to do the factorisation. The <code>LLFactorer</code> object (shown above) implements this method by first calling the <code>public static long sive(long a)</code> method to cut down on the potential factor. This is a very simple method that just cuts the number of factors in half (<em>i.e.</em> if (2^4-1)=15 is to be checked, then only factors up to half that number need to be checked). These potential factors are then iterated through and individually checked using the factorized algorithm found in the <code>public static double factorize(double b, double c)</code> method. Most of the material for the above strategy code can be found the following <a href="http://www.tasam.com/~lrwiman/FAQ-mers">Mersenne FAQ
</a>
		</p>
		<h3>Adding a persistence mechanism</h3>
		<p>In case of a server restart the current mersenne numbers being factored need to be persisted. To achieve this a <em>
				<a href="./images/persistence.gif">memento pattern</a>
			</em> is used. This is conjenction with a <code>Caretaker</code> object which manages and persists the <code>Memeto</code> objects. The <code>Memento</code> objects represent the state of the <code>Factor</code> objects currently being computed and the <code>Caretaker</code> object manages and persists these object. On startup the <code>Caretaker</code> checks if all the previous <code>Factor</code> objects had finished. Unfinished <code>Factor</code> object are reinitialised and their calculations restated. In a later iteration, the stage of factorization will also be persisted.</p>
		<pre>
/**
 * A simple interface of the Caretaker interface. This Caretaker implementation is used to persist Factor object by keeping a
 * list of Memento representing the state of the current Factor instance. It writes that list to disk using a a JDO DAO object
 * @author Eoin Lane
 * @version 1.0
 */
public class SimpleCaretaker implements ICaretaker {
    /** The current list of Memento objects */
    private Vector currentList;

    /** The initalisign list of factor objects */
    private Vector factors;

    /**
     * @link dependency
     * @label mementos
     */

    /*# IMemento lnkIMemento; */

    /**
     * Initialise the caretaker load Memento object using JDO from disk if necessary
     * @param a vector of factory objects
     */
    public SimpleCaretaker(Vector factors) {
        this.currentList = new Vector();
        this.factors = factors;
        System.out.println("Loading Memento objects using JDO from if necessary disk");
    }

    /** Clears the current Vector list */
    public void clear(Vector factor) {
        currentList = new Vector();
        this.factors = factors;
    }

    /** Adds an element */
    public void addElement(Object obj) {
        currentList.addElement(obj);
    }

    /** Removes an element */
    public void removeElement(Object obj) {
        currentList.removeElement(obj);
    }

    //------------------------------------
    private void remove(IMemento obj) {
        IMemento m = (IMemento)obj;
        m.restore(); //and restore the old position
    }
}
</pre>
		<p>The persistence mechanism used here is  the new java data object mechanism and since this is a relatively new topic, here is a simple resource to get stated <a href="http://www.jdocentral.com/index.html">http://www.jdocentral.com/index.html</a>. A JDO data access object (DAO) is used to encapsulate the persistence mechanism and the <code>Caretaker</code> obejct uses the <code>JDODOA</code> object to persist the object graph of <code>Menento</code> objects (these <code>Memento</code> objects contain the state of the <code>Factor</code> objects currently in memory)</p>
<h2>Use Case 2: Calculate a Prefect Number from a Mersenne Prime.</h2>
<p>This use is also defined in the <code>IPerfectCalc</code> interface and implemented in <code>PerfectCalc</code>. As a reminder, here are the method delcared in the <code>IPerfectCalc</code> interface again:   It defines two method:</p>
		<ol>
			<li>
				<code> public boolean checkMersenneNumber(MersenneNumber k, String email)</code> takes a mersenne number (a number of the form (2^n -1) not necessarily a prime number) and an email address or the invoker, and factors the mersenne number and emails the result to the invokers. If the mersenee number has no other factor other than itself and one, then it is a <a href="mersenne.xhtml">mersenne prime</a>
			</li>
			<li>
				<code> public PerfectNumber calcPerfectNumber(MersennePrime mersennePrime)</code> takes a mersenne prime and calculates the corresponding perfect number</li>
</ol>
<p>As is evident from the service description this, service takes a mersenne prime and returns the corresponding perfect number. Here is the <a href="./images/PerfectCalc.calcPerfectNumber(1).gif">sequence diagrams</a> and <a href="./images/perfectNumbers.gif">class diagram</a> for this use case.</p>

		<h2>The Patterns</h2>
		<p>This server side architecture used a number of GOF patterns and is detailed below. </p>

<p>A stateless facde service class expose to the client via a Web Service. This facde calls the <code>FactorFactory</code> (which is a factory class, a mediator and a singleton) to create a <code>Factor</code> stateful objects. There will be potentially many of these objects, depending on the number of client requests from factorization. The <code>Factor</code> stateful object uses a strategy pattern to find the factors of the mersenne number and informs the <code>FactorFactory</code> of the state change using an observer pattern. The <code>FactorFactory</code> will then email the result. Finally the <code>FactorFactory</code>also uses a memento pattern to persist the sate of the mersenne number factorisation calculation, so the it may be reinstated in the case of a server restart. </p>

		<p>Here is a list of and references to the GOF patterns used: </p>
		<ol>
			<li>The <a href="./images/service.gif">facde pattern</a> (the stateless service exposes a simple interface of <em>checkMersenne</em> number to the client)
</li>
			<li>The <a href="./images/factory.gif">Factory method</a> (an <code>FactorFactory</code> object for creating Factor (or any other type of object implementing the IFactor interface) at runtime.
</li>
			<li>The <a href="./images/factory.gif">Singleton pattern</a> is used for the <code>FactorFactory</code> object to ensure there is only one object creating  and managing <code>Factor</code> objects</li>
			<li>The <a href="./images/strategy.gif">Strategy pattern</a> (for factorising the MersenneNumber, decoupling the Factor object from how it factors)</li>
			<li>The <a href="./images/factory.gif">Mediator pattern</a> is used in the <code>FactorFactory</code> again to control and manage the life cycle of the <code>Factor</code> objects that it is responsible for creating.</li>
			<li>The <a href="./images/callback.gif">Observer pattern</a> (a call back to the FactorFactoy object that the statefull Factor object has finished factoring and the results should be emailed to the calling client)  
</li>
<li>The <a href="/images/memento.gif">Memento pattern</a> to persist the state of the Factor object in case of a server restart</li>
		</ol>
				
	</body>
</html>


