Logo
Distributed Genetic Programming Framework
print print

File org.dgpf.search.control.Daemon.java

Here you can find all the information about the file org.dgpf.search.control.Daemon.java. You may explore it here or download it onto your local disk.
/*
 * Copyright (c) 2006 Universitaet Kassel
 *
 * E-Mail           : mirko.dietrich@hrz.uni-kassel.de
 * Original Filename: org.dgpf.search.control.Daemon.java
 *
 * License          : GNU LESSER GENERAL PUBLIC LICENSE
 *                    Version 2.1, February 1999
 *                    You should have received a copy of this license along
 *                    with this library; if not, write to the Free Software
 *                    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *                    MA 02111-1307, USA or download the license under
 *                    http://www.gnu.org/copyleft/lesser.html.
 *
 * Warranty         : This software is provided "as is" without any
 *                    warranty; without even the implied warranty of
 *                    merchantability or fitness for a particular purpose.
 *                    See the Gnu Lesser General Public License for more
 *                    details.
 */


package org.dgpf.search.control;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.BindException;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Vector;

import org.dgpf.search.algorithms.ga.local.LocalGeneticEngine;
import org.dgpf.search.api.SearchEngine;
import org.dgpf.search.api.SearchParameters;
import org.dgpf.search.api.utils.SearchFactory;
import org.dgpf.search.control.protocol.AbortSeEvent;
import org.dgpf.search.control.protocol.ICommunicationPeer;
import org.dgpf.search.control.protocol.JarFileEvent;
import org.dgpf.search.control.protocol.NetworkCommunicationPeer;
import org.dgpf.search.control.protocol.PropertyUpdateEvent;
import org.dgpf.search.control.protocol.RunningStatusEvent;
import org.sfc.events.ErrorEvent;
import org.sfc.events.EventPropagator;
import org.sfc.events.IEventListener;
import org.sfc.events.SfcEvent;
import org.sfc.meta.Property;
import org.sfc.meta.PropertyPort;
import org.sfc.net.cs.Server;
import org.sfc.parallel.events.ParallelStateEvent;
import org.sfc.utils.Typesafe;

/**
 * This daemon can be started on a working client machine. It will listen
 * to connections from a DGPF GUI. Once a connection is established jar
 * archives containing search jobs can be transfered to the client machine
 * via network and be processed mutually.
 * 
 * @author Mirko Dietrich
 */

public class Daemon extends Server implements IEventListener
  {

  /**
   * The buffer for the network communication.
   */

  private static final int         BUFFER_SIZE     = 16;

  /**
   * The running <code>SearchEngine</code>.
   */

  private SearchEngine<?>          m_se            = null;

  /**
   * Hols parameters for the <code>SearchEngine</code> being executed.
   */

  private SearchParameters<?>      m_sp            = null;

  /**
   * The port the server listens on.
   */

  private int                      m_port;

  /**
   * Every single <code>ICommunicationPeer</code> maps to one DGPF GUI
   * instance.
   */

  Vector<NetworkCommunicationPeer> m_conns         = new Vector<NetworkCommunicationPeer>();

  /**
   * Holds the current running jar name.
   */

  private String                   m_jar_file_name = null;

  /**
   * Print usage message.
   */

  private static void printUsage()
    {
    System.out.println("DGPF client machine daemon");
    System.out.println("Usage:  Daemon <port>");
    }

  /**
   * Creates a daemon that listens on a tcp port.
   * 
   * @param p_port
   *          Is the port the server will listen on.
   */

  public Daemon(int p_port)
    {
    super(null, new EventPropagator(), p_port);
    this.m_port = p_port;
    }

  /**
   * Process incoming events.
   * 
   * @param p_event
   *          is an incoming event.
   */

  public void receive(final SfcEvent p_event)
    {
    if(p_event instanceof ParallelStateEvent)
      {
      ParallelStateEvent l_event = (ParallelStateEvent) p_event;
      if(l_event.getSource() instanceof LocalGeneticEngine)
        {
        RunningStatusEvent l_running = new RunningStatusEvent(this.m_se);
        l_running.setRunning(l_event.get_state());
        l_running.setCurrent_running_jar(this.m_jar_file_name);
        for(ICommunicationPeer ip : this.m_conns)
          {
          try
            {
            ip.receive(l_running);
            }
          catch(Exception e)
            {
            e.printStackTrace();
            }
          }
        }

      }

    /*
     * If the port is already in use or if there's a lack of privileges we
     * notify the user.
     */

    else
      if(p_event instanceof ErrorEvent
          && ((ErrorEvent) p_event).get_error() instanceof BindException)
        {
        System.err.println("Error: Can't bind to port " + this.m_port
            + "! " + "Retrying...");
        return;
        }

      /*
       * A new job just arrived. Now temporarily save the jar file, load it
       * into the classloader and fire it up.
       */

      else
        if(p_event instanceof JarFileEvent)
          {
          byte[] l_jar = ((JarFileEvent) p_event).getJar();
          String l_jar_file_name = ((JarFileEvent) p_event).getFilename();
          FileOutputStream l_out = null;
          File l_tmpfile = new File(System.getProperty("java.io.tmpdir")
              + System.getProperty("file.separator") + l_jar_file_name);
          try
            {
            l_out = new FileOutputStream(l_tmpfile);
            }
          catch(FileNotFoundException e)
            {
            e.printStackTrace();
            return;
            }
          try
            {
            l_out.write(l_jar);
            l_out.close();
            }
          catch(IOException e)
            {
            System.err.println("Error: Could not write temporarily file: "
                + l_tmpfile);
            e.printStackTrace();
            return;
            }

          /* Start search job */
          try
            {
            this.m_jar_file_name = l_jar_file_name;
            startJar(l_tmpfile);
            }
          catch(Exception e)
            {
            System.err.println("Error: Unable to run received jar file!");
            e.printStackTrace();
            }
          l_tmpfile.delete();
          return;
          }

        /*
         * The <code>SearchParameters</code> are about to be changed.
         */

        else
          if(p_event instanceof PropertyUpdateEvent)
            {
            Property<Object> l_property = Typesafe
                .cast(((PropertyUpdateEvent) p_event).getProperty());
            Object l_value = ((PropertyUpdateEvent) p_event).getValue();
            PropertyPort<Object> l_pp = l_property.get_port(this.m_sp
                .getClass());
            int l_size = ((PropertyUpdateEvent) p_event).getSize();
            if(l_size == -1) // -1 denotes not an array
              l_pp.set(this.m_sp, l_value);
            else
              l_pp.set(this.m_sp, l_size, l_value);
            return;
            }

          else
            if(p_event instanceof AbortSeEvent)
              {
              abortSeIfRunning();
              }
    /*
     * else { System.err.println("unhandled event: " + p_event); }
     */

    }

  /**
   * Loads a jar file at runtime and instantiates the
   * <code>startup.Factory</code> class thus starting a search job.
   * 
   * @param p_tmpfile
   *          The jar file to execute.
   * @throws ClassNotFoundException
   * @throws MalformedURLException
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   * @throws InstantiationException
   * @throws SecurityException
   * @throws IllegalArgumentException
   */

  private void startJar(File p_tmpfile) throws ClassNotFoundException,
      MalformedURLException, IllegalArgumentException, SecurityException,
      InstantiationException, IllegalAccessException,
      InvocationTargetException
    {
    // kill a running search engine
    abortSeIfRunning();

    URLClassLoader l_cl = new URLClassLoader(
        new URL[] { p_tmpfile.toURL() });
    Class l_startup_factory = l_cl.loadClass("startup.Factory");
    SearchFactory l_factory = (SearchFactory) l_startup_factory
        .getConstructors()[0].newInstance(new Object[] {});
    this.m_se = l_factory.create();
    this.m_se.set_events_serializable(true);
    // send update events to all connected gui instances.
    this.m_se.add_listener(this.get_event_propagator());
    this.m_sp = this.m_se.get_parameters();
    this.m_se.start();
    sendRunningStatus();
    System.out.println("SearchEngine started: " + this.m_se);
    }

  /**
   * Process incoming connection.
   * 
   * @param p_socket
   *          Socket of the new connection.
   * @return True if connection established successfully, false otherwise.
   */

  @Override
  public boolean process_socket(final Socket p_socket)
    {
    NetworkCommunicationPeer ncp = new NetworkCommunicationPeer(this
        .get_event_propagator(), this, p_socket, Daemon.BUFFER_SIZE);
    if(ncp.isConnectionEstablished())
      {
      System.out.println("Client connected: "
          + p_socket.getRemoteSocketAddress());
      boolean added = this.m_conns.add(ncp);
      sendRunningStatus();
      return added;
      }
    System.err.println("Protocol init failed with client "
        + p_socket.getRemoteSocketAddress() + ", disconnecting!");
    return false;
    }

  /**
   * Main method.
   * 
   * @param p_args
   *          command line arguments. Used to specify a port other than the
   *          default port number
   *          <code>NetworkCommunicationPeer.DEFAULT_PORT</code>.
   */

  public static void main(String[] p_args)
    {
    int l_port = NetworkCommunicationPeer.DEFAULT_PORT;
    if(p_args.length == 1)
      {
      try
        {
        l_port = Integer.parseInt(p_args[0]);
        }
      catch(NumberFormatException nfe)
        {
        System.err.println("Please specify a valid port number.");
        printUsage();
        System.exit(1);
        }
      }
    Daemon l_d = new Daemon(l_port);
    l_d.do_start();
    l_d.get_event_propagator().add_listener(l_d);
    System.out.println("listening on port " + l_port + "...");
    }

  /**
   * Getter for se.
   * 
   * @return se.
   */

  public SearchEngine<?> getSe()
    {
    return this.m_se;
    }

  /**
   * Setter for se.
   * 
   * @param p_se
   *          SE to set.
   */

  public void setSe(SearchEngine<?> p_se)
    {
    this.m_se = p_se;
    }

  /**
   * Terminates the current se if running.
   * 
   * @return true if abort called.
   */

  public boolean abortSeIfRunning()
    {
    boolean l_status = false;
    if(this.m_se != null && this.m_se.is_running())
      {
      this.m_se.abort();
      l_status = true;
      this.m_jar_file_name = null;
      }
    return l_status;
    }

  /**
   * Getter for m_jar_file_name.
   * 
   * @return m_jar_file_name Jar file name.
   */

  public String getJar_file_name()
    {
    return this.m_jar_file_name;
    }

  /**
   * Setter for m_jar_file_name.
   * 
   * @param p_jar_file_name
   *          File name to set.
   */

  public void setJar_file_name(String p_jar_file_name)
    {
    this.m_jar_file_name = p_jar_file_name;
    }

  /**
   * Sends runing status to event propagator.
   */

  private void sendRunningStatus()
    {
    RunningStatusEvent l_status = new RunningStatusEvent(this);
    if(this.m_se != null)
      {
      l_status.setRunning(this.m_se.is_running());
      l_status.setCurrent_running_jar(this.m_jar_file_name);
      }
    get_event_propagator().receive(l_status);
    }

  }

File Information:

file name:Daemon.java
package:org.dgpf.search.control
qualified name:org.dgpf.search.control.Daemon.java
file type:Java Source File
download location:download http://dgpf.sourceforge.net/source/org/dgpf/search/control/Daemon.java
size:11.482 KB (11758 B)
uploaded: 2015-07-22 04:11:00 GMT+0000
last update: 2006-09-24 23:47:04 GMT+0000
last access: 2017-11-23 07:35:20 GMT+0000

statistics online since 2006-01-02.   RSS Feed
Contact us by sending an email to tweise@gmx.de to receive further information, to report errors, or to join our project.
All content on this site (http://dgpf.sourceforge.net/) is LGPL-licensed.
http://dgpf.sourceforge.net/scripts/source/source.php last modified at 2015-07-22 04:10:53 GMT+0000 served at 2017-11-23 07:35:20 GMT+0000.
Valid CSS Valid XHTML 1.1
Valid RSS SourceForge.net Logo