gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GNUnet-SVN] r18126 - in gnunet-java: . src/org/gnunet/construct src/org


From: gnunet
Subject: [GNUnet-SVN] r18126 - in gnunet-java: . src/org/gnunet/construct src/org/gnunet/util test/org/gnunet test/org/gnunet/construct
Date: Mon, 14 Nov 2011 02:49:59 +0100

Author: dold
Date: 2011-11-14 02:49:59 +0100 (Mon, 14 Nov 2011)
New Revision: 18126

Added:
   gnunet-java/src/org/gnunet/util/Program.java
   gnunet-java/test/org/gnunet/construct/
   gnunet-java/test/org/gnunet/construct/ConstructTest.java
Removed:
   gnunet-java/src/org/gnunet/construct/ConstructTest.java
   gnunet-java/src/org/gnunet/util/Connection.java
Modified:
   gnunet-java/ISSUES
   gnunet-java/src/org/gnunet/util/AbsoluteTime.java
   gnunet-java/src/org/gnunet/util/Configuration.java
   gnunet-java/src/org/gnunet/util/Scheduler.java
Log:
implemented parts of scheduler

Modified: gnunet-java/ISSUES
===================================================================
--- gnunet-java/ISSUES  2011-11-13 13:12:04 UTC (rev 18125)
+++ gnunet-java/ISSUES  2011-11-14 01:49:59 UTC (rev 18126)
@@ -40,8 +40,9 @@
 * signals:
   http://www.ibm.com/developerworks/java/library/i-signalhandling/
 
-Used Libraries:
- * https://github.com/magnuss/java-bloomfilter (LGPL) => freeway!
- * http://code.google.com/p/junixsocket/ (Apache License 2.0)
- 
+
+
+
+* exception handling in statically used classes (scheduler)
+ * solution: singleton?
  
\ No newline at end of file

Deleted: gnunet-java/src/org/gnunet/construct/ConstructTest.java
===================================================================
--- gnunet-java/src/org/gnunet/construct/ConstructTest.java     2011-11-13 
13:12:04 UTC (rev 18125)
+++ gnunet-java/src/org/gnunet/construct/ConstructTest.java     2011-11-14 
01:49:59 UTC (rev 18126)
@@ -1,16 +0,0 @@
-package org.gnunet.construct;
-
-import org.gnunet.messages.MessageHeader;
-import org.junit.Test;
-
-public class ConstructTest {
-
-       @Test
-       public void testParse_as() {
-               byte[] data = { 3, 4, 5, 6 };
-               MessageHeader mh = Construct.parse_as(data, 0, 
MessageHeader.class);
-               assert mh.size == 1536;
-               assert mh.type == 2560;
-       }
-
-}

Modified: gnunet-java/src/org/gnunet/util/AbsoluteTime.java
===================================================================
--- gnunet-java/src/org/gnunet/util/AbsoluteTime.java   2011-11-13 13:12:04 UTC 
(rev 18125)
+++ gnunet-java/src/org/gnunet/util/AbsoluteTime.java   2011-11-14 01:49:59 UTC 
(rev 18126)
@@ -29,7 +29,7 @@
  * 
  * @author Florian Dold
  */
-public class AbsoluteTime {
+public class AbsoluteTime implements Comparable {
     private static final Logger logger = LoggerFactory
             .getLogger(AbsoluteTime.class);
 
@@ -189,4 +189,10 @@
         }
         return new AbsoluteTime(abs_value - duration.getMilliseconds());
     }
+
+    @Override
+    public int compareTo(Object o) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
 }

Modified: gnunet-java/src/org/gnunet/util/Configuration.java
===================================================================
--- gnunet-java/src/org/gnunet/util/Configuration.java  2011-11-13 13:12:04 UTC 
(rev 18125)
+++ gnunet-java/src/org/gnunet/util/Configuration.java  2011-11-14 01:49:59 UTC 
(rev 18126)
@@ -59,24 +59,22 @@
     public Configuration() {
     }
 
-    private Configuration(Configuration c) {
-        sections.putAll(c.sections);
-    }
-
-    public Configuration clone() {
-        return new Configuration(this);
-    }
-
     /**
      * Parse a configuration file, add all of the options in the file to the
      * configuration environment.
      * 
      * @param filename
      *            name of the configuration file
-     * @throws FileNotFoundException
+     * @throws ParsingError
      */
-    public void parse(String filename) throws FileNotFoundException {
-        Scanner sc = new Scanner(new File(filename)).useDelimiter(delim);
+    public void parse(String filename) {
+        Scanner sc;
+        try {
+            sc = new Scanner(new File(filename)).useDelimiter(delim);
+        } catch (FileNotFoundException e) {
+            throw new ParsingError("Configuration file \"" + filename
+                    + "\" not found");
+        }
 
         String current_section = "";
 
@@ -203,26 +201,29 @@
     public long getValueNumer(String section, String option) {
         String num_str = getValueString(section, option);
         if (num_str == null) {
-            throw new ParsingError ("Failure in configuration section " + 
section + " option " + option + ": value empty");
+            throw new ParsingError("Failure in configuration section "
+                    + section + " option " + option + ": value empty");
         }
         try {
             return Long.parseLong(num_str);
         } catch (NumberFormatException e) {
-            throw new ParsingError ("Failure in configuration section " + 
section + " option " + option + ": " + e.getMessage(), e);
+            throw new ParsingError("Failure in configuration section "
+                    + section + " option " + option + ": " + e.getMessage(), 
e);
         }
     }
-    
+
     /**
      * Set an option to a string value in a section.
      * 
      * @param section
      * @param option
-     * @param value
-     *            null if value not found
+     * @throws ParsingError
      */
     public String getValueString(String section, String option) {
         if (!sections.containsKey(section)) {
-            return null;
+            throw new ParsingError(String.format(
+                    "Failure in configuration section %s: option %s not found",
+                    section, option));
         }
         return sections.get(section).get(option);
     }
@@ -247,20 +248,25 @@
      *            option of interest
      * @param choices
      *            list of legal values
-     * @return matching value from choices, null if nothing matches
+     * @return matching value from choices
+     * @throws ParsingError
      */
     public String getValueChoice(String section, String option,
             Iterable<String> choices) {
         String value = getValueString(section, option);
         if (value == null) {
-            return null;
+            throw new ParsingError(String.format(
+                    "Failure in configuration section %s: value not found",
+                    section));
         }
         for (String c : choices) {
             if (c.equals(value)) {
                 return value;
             }
         }
-        return null;
+        throw new ParsingError(String.format(
+                "Failure in configuration section %s: invalid value",
+                section));
     }
 
     /**
@@ -273,9 +279,8 @@
      * @return true if so, false of not
      * 
      */
-    // XXX: should this be named "hasValue"?
     public boolean haveValue(String section, String option) {
-        return sections.containsValue(section)
+        return sections.containsKey(section)
                 && sections.get(section).containsKey(option);
     }
 
@@ -288,10 +293,12 @@
      *            option of interest
      * @return true, false, null
      */
-    public Boolean getValueYesNo(String section, String option) {
+    public boolean getValueYesNo(String section, String option) {
         String v = getValueChoice(section, option, Arrays.asList("YES", "NO"));
         if (v == null) {
-            return null;
+            throw new ParsingError(String.format(
+                    "Failure in configuration section %s: option %s not found",
+                    section, option));
         }
         if (v.equals("YES")) {
             return true;
@@ -299,7 +306,7 @@
         if (v.equals("NO")) {
             return false;
         }
-        return null;
+        throw new ParsingError("Configuration error: value not recognized as 
YES or NO");
     }
 
     /**
@@ -326,7 +333,6 @@
         return sections.keySet();
     }
 
-   
     /**
      * Expand an expression of the form "$FOO/BAR" to "DIRECTORY/BAR" where
      * either in the "PATHS" section or the environment "FOO" is set to
@@ -336,7 +342,6 @@
      *            string to $-expand
      * @return $-expanded string
      */
-    // XXX: this is not really platform independent?
     public String expandDollar(String orig) {
         Map<String, String> env = System.getenv();
         for (Map.Entry<String, String> e : env.entrySet()) {
@@ -369,19 +374,15 @@
         throw new UnsupportedOperationException();
     }
 
-
-    public static class ParsingError extends Error
-    {
-        ParsingError (String msg, Throwable t)
-        {
+    @SuppressWarnings("serial")
+    public static class ParsingError extends Error {
+        ParsingError(String msg, Throwable t) {
             super(msg, t);
         }
-        ParsingError (String msg)
-        {
+
+        ParsingError(String msg) {
             super(msg);
         }
     }
 
-    
 }
-

Deleted: gnunet-java/src/org/gnunet/util/Connection.java
===================================================================
--- gnunet-java/src/org/gnunet/util/Connection.java     2011-11-13 13:12:04 UTC 
(rev 18125)
+++ gnunet-java/src/org/gnunet/util/Connection.java     2011-11-14 01:49:59 UTC 
(rev 18126)
@@ -1,182 +0,0 @@
-/*
-     This file is part of GNUnet.
-     (C) 2009 Christian Grothoff (and other contributing authors)
-
-     GNUnet is free software; you can redistribute it and/or modify
-     it under the terms of the GNU General Public License as published
-     by the Free Software Foundation; either version 2, or (at your
-     option) any later version.
-
-     GNUnet is distributed in the hope that it will be useful, but
-     WITHOUT ANY WARRANTY; without even the implied warranty of
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-     General Public License for more details.
-
-     You should have received a copy of the GNU General Public License
-     along with GNUnet; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
-*/
-
-
-
-package org.gnunet.util;
-
-import java.io.IOException;
-import java.net.Inet4Address;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.nio.channels.Channel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-
-/**
- * A connection sends data over a channel asynchronously using the scheduler.
- * 
- * @author Florian Dold
- *
- */
-public class Connection {
-       public class TransmitHandle {
-               void cancel() {
-                       throw new UnsupportedOperationException();
-               }
-       }
-
-       private boolean persist;
-       
-       private Channel chan;
-
-       private Connection(Channel c) {
-           chan = c;
-       }
-
-       public static Connection fromAccept(ServerSocket ss) {
-               throw new UnsupportedOperationException();
-       }
-
-       public static Connection fromExisting(Socket ss) throws IOException {
-           SocketChannel sc = ss.getChannel();
-           sc.configureBlocking(false);
-               return new Connection(sc);
-       }
-
-       public static Connection fromConnect(String hostname, int port) throws 
IOException {
-           throw new UnsupportedOperationException();
-       }
-
-       public static Connection fromUnixPath(String path) {
-               // problematic as java has no nativ support for unix domain 
sockets
-               throw new UnsupportedOperationException();
-       }
-
-       public static Connection fromSocketAddress(SocketAddress addr) {
-               throw new UnsupportedOperationException();
-       }
-
-       /**
-        * Receive data from the given socket. Note that this function will call
-        * "receiver" asynchronously using the scheduler. It will "immediately"
-        * return. Note that there MUST only be one active receive call per 
socket
-        * at any given point in time (so do not call receive again until the
-        * receiver callback has been invoked).
-        * 
-        * @param max
-        *            maximum number of bytes to read
-        * @param timeout
-        *            maximum amount of time to wait
-        * @param receiver
-        *            function to call with received data
-        */
-
-       public void receive(int max, RelativeTime timeout, Receiver r) {
-               throw new UnsupportedOperationException();
-       }
-
-       /**
-        * Cancel receive job on the given socket. Note that the receiver 
callback
-        * must not have been called yet in order for the cancellation to be 
valid.
-        * 
-        * @return closure of the original receiver callback closure
-        */
-       public void cancelReceive() {
-               throw new UnsupportedOperationException();
-       }
-
-       /**
-        * Ask the socket to call us once the specified number of bytes are 
free in
-        * the transmission buffer. May call the notify method immediately if 
enough
-        * space is available. Note that this function will abort if "size" is
-        * greater than GNUNET_SERVER_MAX_MESSAGE_SIZE.
-        * 
-        * Note that "notify" will be called either when enough buffer space is
-        * available OR when the socket is destroyed. The size parameter given 
to
-        * notify is guaranteed to be larger or equal to size if the buffer is
-        * ready, or zero if the socket was destroyed (or at least closed for
-        * writing). Finally, any time before 'notify' is called, a client may 
call
-        * "notify_transmit_ready_cancel" to cancel the transmission request.
-        * 
-        * Only one transmission request can be scheduled at the same time. 
Notify
-        * will be run with the same scheduler priority as that of the caller.
-        * 
-        * @param size
-        *            number of bytes to send
-        * @param timeout
-        *            after how long should we give up (and call notify with buf
-        *            NULL and size 0)?
-        * @param notify
-        *            function to call when buffer space is available
-        * @return non-NULL if the notify callback was queued, NULL if we are
-        *         already going to notify someone else (busy)
-        */
-       public TransmitHandle notifyTransmitReady(int size, RelativeTime 
timeout,
-                       boolean auto_retry, TransmitReadyNotify cb) {
-               throw new UnsupportedOperationException();
-       }
-
-       /**
-        * Set the persist option on this connection handle. Indicates that the
-        * underlying socket or fd should never really be closed. Used for
-        * indicating process death.
-        */
-       public void persist() {
-               this.persist = true;
-       }
-
-       /**
-        * Disable the "CORK" feature for communication with the given socket,
-        * forcing the OS to immediately flush the buffer on transmission 
instead of
-        * potentially buffering multiple messages. Essentially reduces the OS 
send
-        * buffers to zero. Used to make sure that the last messages sent 
through
-        * the connection reach the other side before the process is terminated.
-        */
-       // XXX: error code / exception
-       public void disableCorking() {
-               throw new UnsupportedOperationException();
-       }
-
-       /**
-        * Check if socket is valid (no fatal errors have happened so far). Note
-        * that a socket that is still trying to connect is considered valid.
-        */
-       public boolean check() {
-               throw new UnsupportedOperationException();
-       }
-
-       /**
-        * Configure this connection to ignore shutdown signals.
-        * 
-        * @param do_ignore
-        *            GNUNET_YES to ignore, GNUNET_NO to restore default
-        */
-       public void ignoreShutdown(boolean doIgnore) {
-       }
-       
-       public Channel getChannel() {
-           throw new UnsupportedOperationException();
-       }
-
-
-}

Added: gnunet-java/src/org/gnunet/util/Program.java
===================================================================
--- gnunet-java/src/org/gnunet/util/Program.java                                
(rev 0)
+++ gnunet-java/src/org/gnunet/util/Program.java        2011-11-14 01:49:59 UTC 
(rev 18126)
@@ -0,0 +1,5 @@
+package org.gnunet.util;
+
+public class Program {
+
+}

Modified: gnunet-java/src/org/gnunet/util/Scheduler.java
===================================================================
--- gnunet-java/src/org/gnunet/util/Scheduler.java      2011-11-13 13:12:04 UTC 
(rev 18125)
+++ gnunet-java/src/org/gnunet/util/Scheduler.java      2011-11-14 01:49:59 UTC 
(rev 18126)
@@ -16,191 +16,219 @@
      along with GNUnet; see the file COPYING.  If not, write to the
      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
      Boston, MA 02111-1307, USA.
-*/
+ */
 
-
 package org.gnunet.util;
 
 import java.io.IOException;
 import java.nio.channels.Channel;
+import java.nio.channels.ClosedChannelException;
 import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.nio.channels.spi.SelectorProvider;
+import java.util.Comparator;
+import java.util.EnumMap;
 import java.util.EnumSet;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
+import java.util.PriorityQueue;
+import java.util.Queue;
 import java.util.Set;
 import java.util.TreeSet;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-
 /**
  * Schedule computations using CPS
  * 
  * @author Florian Dold
  */
 public class Scheduler {
+    private static final Logger logger = LoggerFactory
+            .getLogger(Scheduler.class);
+
     public enum Priority {
-        KEEP, IDLE, BACKGROUND, DEFAULT, HIGH, UI, URGENT, SHUTDOWN
+        IDLE, BACKGROUND, DEFAULT, HIGH, UI, URGENT, SHUTDOWN;
+        static public final Priority KEEP = null;
     }
 
     public enum Reason {
         STARTUP, SHUTDOWN, TIMEOUT, READ_READY, WRITE_READY, PREREQ_DONE
     }
 
-    static List<TaskIdentifier> pending = new LinkedList<TaskIdentifier>();
+    private static List<TaskIdentifier> pending = new 
LinkedList<TaskIdentifier>();
 
-    static List<TimeoutTask> pending_timeout = new LinkedList<TimeoutTask>();
+    private static Queue<TimeoutTask> pending_timeout = new 
PriorityQueue<TimeoutTask>();
 
-    static TaskIdentifier active_task;
+    private static TaskIdentifier active_task;
 
-    static Priority current_priority;
-    static boolean current_liveness;
+    private static Priority current_priority;
+    private static boolean current_liveness;
 
-    static int ready_count;
-    
-    static TaskIdentifier[] ready = new 
TaskIdentifier[Priority.values().length];
-    
-    static Set<Channel> rs = new TreeSet<Channel>();
-    static Set<Channel> ws = new TreeSet<Channel>();
-    
-    static RelativeTime timeout;
+    private static int ready_count = 0;
 
+    // fast / implemented with arrays, according to java docs
+    private static Map<Priority, LinkedList<TaskIdentifier>> ready = new 
EnumMap<Priority, LinkedList<TaskIdentifier>>(
+            Priority.class);
+
+    static {
+        for (Priority e : Priority.values()) {
+            ready.put(e, new LinkedList<TaskIdentifier>());
+        }
+    }
+
+    private static Selector selector;
+    {
+        try {
+            selector = SelectorProvider.provider().openSelector();
+        } catch (IOException e) {
+            // what to do here?
+            logger.error("fatal: cannot create selector");
+            System.exit(-1);
+        }
+    }
+
+    private static RelativeTime timeout;
+
     public static interface Task {
         public void run(Context ctx);
 
         public static class Context {
-            EnumSet<Reason> reasons;
-            Set<Channel> readableSet;
-            Set<Channel> writeableSet;
+            EnumSet<Reason> reasons = EnumSet.noneOf(Reason.class);
+            Set<Channel> readableSet = null;
+            Set<Channel> writeableSet = null;
         }
     }
-    
+
     final public static Task NO_TASK = new Task() {
         @Override
         public void run(Context ctx) {
         }
     };
 
-    public static abstract class TaskIdentifier {
+    public static class TaskIdentifier {
         private final Task task;
+        private final TaskIdentifier prereq;
         private Task.Context ctx = new Task.Context();
         boolean liveness;
+        Priority priority;
 
-        TaskIdentifier(Task t) {
+        TaskIdentifier(Task t, Priority priority, boolean liveness,
+                TaskIdentifier prereq) {
             this.task = t;
+            this.priority = (priority == null) ? current_priority : priority;
+            this.liveness = liveness;
+            this.prereq = prereq;
         }
 
-        /*
-         * The actual code a task is supposed to execute
-         */
         void run(Task.Context ctx) {
             task.run(ctx);
         }
 
-        public abstract void cancel();
-    }
-
-    public static class Continuation extends TaskIdentifier {
-        Continuation(Task t) {
-            super(t);
-        }
-
-        @Override
         public void cancel() {
-
+            pending.remove(this);
         }
     }
 
-    static class TimeoutTask extends TaskIdentifier {
+    static class TimeoutTask extends TaskIdentifier implements
+            Comparable<TimeoutTask> {
         final AbsoluteTime timeout;
+        boolean selected = false;
 
-        TimeoutTask(RelativeTime delay, Task t) {
-            super(t);
+        TimeoutTask(Task t, Priority p, boolean liveness,
+                TaskIdentifier prereq, RelativeTime delay) {
+            super(t, p, liveness, prereq);
             timeout = delay.toAbsolute();
-            // timeout_heap.add (dti.timeout, this);
         }
 
-        // private final AbsoluteTime timeout;
-
+        @Override
         public void cancel() {
-            // timeout_heap.remove (this);
+            super.cancel(); // in case the delay is already over
+            pending_timeout.remove(this);
         }
+
+        @Override
+        public int compareTo(TimeoutTask o) {
+            return (new Long(this.timeout.getMilliseconds())
+                    .compareTo(o.timeout.getMilliseconds()));
+        }
     }
-    
-    
-    /*
-    static class SelectTask extends TaskIdentifier {
-        
-    }
-    
-    static class PrereqTask extends TaskIdentifier {
-        
-    }
-    */
-    
-    
-    
-    
-    
-    
-    
+
     /**
-     * Schedule a new task to be run as soon as possible. The task
-     * will be run with the priority of the calling task.
-     *
-     * @param task main function of the task
-     * @param task_cls closure of task
-     * @return unique task identifier for the job
-     *         only valid until "task" is started!
+     * Schedule a new task to be run as soon as possible. The task will be run
+     * with the priority of the calling task.
+     * 
+     * @param task
+     *            main function of the task
+     * @param task_cls
+     *            closure of task
+     * @return unique task identifier for the job only valid until "task" is
+     *         started!
      */
-    public static void addNow(Task task) {
-        throw new UnsupportedOperationException();
+    public static TaskIdentifier addNow(Task task) {
+        return addSelect(Priority.KEEP, null, RelativeTime.ZERO, null, null,
+                task);
     }
 
-    /**
-     * Run the task as soon as its prerequisites are satisfied.
-     */
     public static TaskIdentifier addDelayed(RelativeTime delay, Task task) {
-        return new TimeoutTask(delay, task);
+        return addSelect(Priority.KEEP, null, delay, null, null, task);
     }
 
     /**
-     * Run the task regardless of any prerequisites.
+     * Run the task regardless of any prerequisites, before any other task of
+     * the same priority.
      */
     public static void addContinuation(Task task, EnumSet<Reason> reason) {
+        assert current_priority != null;
+        TaskIdentifier tid = new TaskIdentifier(task, Priority.KEEP,
+                current_liveness, null);
+        queueReady(tid);
+    }
 
-    }
-    
-    
-    
     public static TaskIdentifier addAfter(TaskIdentifier prereq, Task t) {
-        return addSelect(Priority.KEEP, prereq, RelativeTime.ZERO, null, null, 
t);
+        return addSelect(Priority.KEEP, prereq, RelativeTime.ZERO, null, null,
+                t);
     }
-    
+
     public static TaskIdentifier addWithPriority(Priority prio, Task t) {
-        //return addSelect(prio, NO_TASK, RelativeTime.ZERO, null, null, t);
-        throw new UnsupportedOperationException();
+        return addSelect(prio, null, RelativeTime.ZERO, null, null, t);
     }
-    
-    
-    
-    
+
     // should register the channels with the selector
     public static TaskIdentifier addSelect(Priority p, TaskIdentifier prereq,
-            RelativeTime delay, Set<SelectableChannel> rs, 
Set<SelectableChannel> ws, Task t) {
-                return null;
+            RelativeTime delay, Set<SelectableChannel> rs,
+            Set<SelectableChannel> ws, Task t) {
+        if (rs != null) {
+            for (SelectableChannel s : rs) {
+                try {
+                    s.register(selector, SelectionKey.OP_READ, null);
+                } catch (ClosedChannelException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+
+        }
+        if (ws != null) {
+            for (SelectableChannel s : ws) {
+                try {
+                    s.register(selector, SelectionKey.OP_WRITE, null);
+                } catch (ClosedChannelException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+
+        }
+
+        TimeoutTask tid = new TimeoutTask(t, p, current_liveness, prereq, 
delay);
+
+        return tid;
+
     }
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
 
     /**
      * Request the shutdown of a scheduler. Marks all currently pending tasks 
as
@@ -238,13 +266,6 @@
     }
 
     /**
-     * Cancel execution of the specified task. The task must not yet have run.
-     */
-    public void cancel(TaskIdentifier task) {
-        throw new UnsupportedOperationException();
-    }
-
-    /**
      * Initialize and run scheduler. This function will return when all tasks
      * have completed. On systems with signals, receiving a SIGTERM (and other
      * similar signals) will cause "GNUNET_SCHEDULER_shutdown" to be run after
@@ -256,73 +277,75 @@
      * 
      * @param task
      *            task to run immediately
-     * @throws IOException 
+     * @throws IOException
      */
     public static void run(Task task) throws IOException {
-        // XXX: which kind of set to use?
-        // XXX: what about the shutdown pipe / signal handlers?
-        Selector sel;
-        try {
-            sel = SelectorProvider.provider().openSelector();
-        } catch (IOException e) {
-            // XXX: what to do?
-            e.printStackTrace();
-            return;
-        }
-        
         current_priority = Priority.DEFAULT;
         current_liveness = true;
-        addContinuation(task, EnumSet.of(Reason.STARTUP));
         
+        timeout = RelativeTime.FOREVER;
         
-        
+        addContinuation(task, EnumSet.of(Reason.STARTUP));
+
         while (checkLiveness()) {
-            rs.clear();
-            ws.clear();
-            timeout = RelativeTime.FOREVER;
+
             
-            updateSets();
-            
             if (ready_count > 0) {
                 timeout = RelativeTime.ZERO;
+            } else {
+                timeout = RelativeTime.FOREVER;
             }
+
+            AbsoluteTime now = AbsoluteTime.now();
             
-            sel.select(timeout.getMilliseconds());
-            
-            if (timeout.getMilliseconds() == 0) {
-                try {
-                    Thread.sleep(1);
-                } catch (InterruptedException e) {
-                    ;
+            while (true) {
+                TimeoutTask t = pending_timeout.peek();
+
+                if (t == null || t.timeout.compareTo(now) < 0) {
+                    break;
+                } else {
+                    pending_timeout.remove(t);
+                    pending.add(t);
+                    register(t);
                 }
             }
-            
-            checkReady();
+
+            selector.select(timeout.getMilliseconds());
+
+            for (SelectionKey sk : selector.selectedKeys()) {
+                sk.cancel();
+                TimeoutTask tid = (TimeoutTask) sk.attachment();
+                if (!tid.selected) {
+                    queueReady(tid);
+                } else {
+                    tid.selected = true;
+                }
+            }
+
             runReady();
         }
     }
 
+    private static void register(TimeoutTask t) {
+        // register with selector
+        
+    }
+
+    private static void queueReady(TaskIdentifier tid) {
+        assert tid.priority != null;
+        ready.get(tid.priority).add(tid);
+        ready_count++;
+    }
+
     private static void runReady() {
         do {
             if (ready_count == 0) {
                 return;
             }
-        } while (false /*....todo*/);
-        
-        
-    }
+        } while (false /* ....todo */);
 
-    private static void checkReady() {
-        AbsoluteTime now = AbsoluteTime.now();
-        // ...
-        
     }
 
-    private static void updateSets() {
-        // update sets does not do the same thing as the C code.
-        
-    }
-
     /**
      * Check if the system is still life. Trigger shutdown if we have tasks, 
but
      * none of them give us lifeness.

Copied: gnunet-java/test/org/gnunet/construct/ConstructTest.java (from rev 
18097, gnunet-java/src/org/gnunet/construct/ConstructTest.java)
===================================================================
--- gnunet-java/test/org/gnunet/construct/ConstructTest.java                    
        (rev 0)
+++ gnunet-java/test/org/gnunet/construct/ConstructTest.java    2011-11-14 
01:49:59 UTC (rev 18126)
@@ -0,0 +1,16 @@
+package org.gnunet.construct;
+
+import org.gnunet.messages.MessageHeader;
+import org.junit.Test;
+
+public class ConstructTest {
+
+       @Test
+       public void testParse_as() {
+               byte[] data = { 3, 4, 5, 6 };
+               MessageHeader mh = Construct.parse_as(data, 0, 
MessageHeader.class);
+               assert mh.size == 1536;
+               assert mh.type == 2560;
+       }
+
+}




reply via email to

[Prev in Thread] Current Thread [Next in Thread]