Ignore:
Timestamp:
07/04/13 20:29:50 (11 years ago)
Author:
psniegowski
Message:

HIGHLIGHTS:

  • cleanup Instance management
    • extract Instance interface
    • extract Instance common algorithms to InstanceUtils?
  • fix closing issues: Ctrl+C or window close button

properly shutdown whole program

by Java Framsticks framework

  • fix parsing and printing of all request types
  • hide exception passing in special handle method of closures
    • substantially improve readability of closures
    • basically enable use of exception in asynchronous closures

(thrown exception is transported back to the caller)

  • implement call request on both sides

CHANGELOG:
Further improve calling.

Improve instance calling.

Calling is working on both sides.

Improve exception handling in testing.

Waiters do not supercede other apllication exception being thrown.

Finished parsing and printing of all request types (with tests).

Move implementation and tests of request parsing to Request.

Add tests for Requests.

Improve waits in asynchronours tests.

Extract more algorithms to InstanceUtils?.

Extract Instance.resolve to InstanceUtils?.

Improve naming.

Improve passing exception in InstanceClient?.

Hide calling of passed functor in StateCallback?.

Hide Exception passing in asynchronous closures.

Hide exception passing in Future.

Make ResponseCallback? an abstract class.

Make Future an abstract class.

Minor change.

Move getPath to Path.to()

Move bindAccess to InstanceUtils?.

Extract common things to InstanceUtils?.

Fix synchronization bug in Connection.

Move resolve to InstanceUtils?.

Allow names of Joinable to be dynamic.

Add support for set request server side.

More fixes in communication.

Fix issues with parsing in connection.

Cut new line characters when reading.

More improvements.

Migrate closures to FramsticksException?.

Several changes.

Extract resolveAndFetch to InstanceUtils? algorithms.

Test resolving and fetching.

More fixes with function signature deduction.

Do not print default values in SimpleAbstractAccess?.

Add test of FramsClass? printing.

Improve FramsticksException? messages.

Add explicit dispatcher synchronization feature.

Rework assertions in tests.

Previous solution was not generic enough.

Allow addition of joinables to collection after start.

Extract SimulatorInstance? from RemoteInstance?.

Remove PrivateJoinableCollection?.

Improve connections.

Move shutdown hook to inside the Monitor.

It should work in TestNG tests, but it seems that
hooks are not called.

In ServerTest? client connects to testing server.

Move socket initialization to receiver thread.

Add proper closing on Ctrl+C (don't use signals).

Fix bugs with server accepting connections.

Merge Entity into Joinable.

Reworking ServerInstance?.

Extract more algorithm to InstanceUtils?.

Extract some common functionality from AbstractInstance?.

Functions were placed in InstanceUtils?.

Hide registry of Instance.

Use ValueParam? in Instance interface.

Minor change.

Extract Instance interface.

Old Instance is now AbstractInstance?.

Location:
java/main/src/main/java/com/framsticks/util
Files:
5 added
17 edited

Legend:

Unmodified
Added
Removed
  • java/main/src/main/java/com/framsticks/util/FramsticksException.java

    r88 r96  
    3535        }
    3636
    37         @Override
    38         public String getMessage() {
    39                 StringBuilder b = new StringBuilder();
     37        public void getShortMessage(StringBuilder b) {
    4038                if (message != null) {
    4139                        b.append(message);
     40                } else {
     41                        b.append("?");
    4242                }
    4343                if (arguments != null) {
     
    4545                                b.append(" ");
    4646                        }
    47                         Delimeted d = new Delimeted(", ", "");
     47                        Delimeted<Pair<String, Object>> d = new Delimeted<>(", ", "");
    4848                        d.append(arguments.iterator());
    4949
    5050                        b.append("(").append(d.build()).append(")");
    5151                }
    52                 if (this.getCause() != null) {
    53                         b.append(" caused by: [").append(this.getCause().getMessage()).append("]");
     52        }
     53
     54        public String getMsg() {
     55                return message;
     56        }
     57
     58        @Override
     59        public String getMessage() {
     60                StringBuilder b = new StringBuilder();
     61                getShortMessage(b);
     62                Throwable cause = this.getCause();
     63                while (cause != null) {
     64                        b.append(" caused by: [").append(cause.getClass().getCanonicalName()).append(": ");
     65                        if (cause instanceof FramsticksException) {
     66                                ((FramsticksException) cause).getShortMessage(b);
     67                        } else {
     68                                b.append(cause.getMessage());
     69                        }
     70                        b.append("]");
     71                        cause = cause.getCause();
    5472                }
    5573                return b.toString();
  • java/main/src/main/java/com/framsticks/util/Logging.java

    r90 r96  
    22
    33import org.apache.log4j.Logger;
     4
     5import com.framsticks.util.dispatching.ExceptionResultHandler;
    46
    57/**
     
    1719                return false;
    1820        }
     21
     22        public static ExceptionResultHandler logger(final Logger logger, final String action, final Object subject) {
     23                return new ExceptionResultHandler() {
     24                        @Override
     25                        public void handle(FramsticksException e) {
     26                                Logging.log(logger, action, subject, e);
     27                        }
     28                };
     29        }
    1930}
  • java/main/src/main/java/com/framsticks/util/PeriodicTask.java

    r90 r96  
    2121
    2222        public void again() {
    23                 dispatcher.dispatch(new Task<C>(System.currentTimeMillis() + period) {
     23                dispatcher.dispatch(new Task<C>(period) {
    2424                        @Override
    2525                        public void run() {
  • java/main/src/main/java/com/framsticks/util/StateFunctor.java

    r85 r96  
    11package com.framsticks.util;
     2
     3import com.framsticks.util.dispatching.ExceptionResultHandler;
    24
    35/**
    46 * @author Piotr Sniegowski
    57 */
    6 public interface StateFunctor {
     8public interface StateFunctor extends ExceptionResultHandler {
    79        //TODO RunAt
    8         public void call(Exception e);
     10        public void call();
    911}
  • java/main/src/main/java/com/framsticks/util/UnsupportedOperationException.java

    r84 r96  
    44 * @author Piotr Sniegowski
    55 */
    6 public class UnsupportedOperationException extends Exception {
     6public class UnsupportedOperationException extends FramsticksException {
    77
    88        /**
  • java/main/src/main/java/com/framsticks/util/dispatching/AbstractJoinable.java

    r90 r96  
    1414import com.framsticks.util.FramsticksException;
    1515
    16 
    17 
    1816public abstract class AbstractJoinable implements Joinable {
     17
    1918        private static final Logger log = Logger.getLogger(AbstractJoinable.class);
    20 
    2119
    2220        protected final Set<JoinableParent> owners = new HashSet<JoinableParent>();
     
    2523        protected static final Set<AbstractJoinable> joinablesRegistry = Collections.synchronizedSet(new HashSet<AbstractJoinable>());
    2624
    27         JoinableState state = JoinableState.INITILIAZED;
     25        protected JoinableState state = JoinableState.INITILIAZED;
     26        protected JoinableParent parent;
     27        protected Monitor monitor;
    2828
    2929        /**
     
    5353                this.state = state;
    5454
    55                 synchronized (this) {
    56                         log.debug(this + " is notifying " + joinableListeners.size() + " parents");
    57 
    58                         List<JoinableParent> parents = new LinkedList<>();
    59                         CollectionUtils.addAll(parents, joinableListeners.iterator());
    60 
    61                         for (JoinableParent p : parents) {
    62                                 if (p != null) {
    63                                         Dispatching.childChangedState(p, this, state);
    64                                 }
    65                         }
    66                         this.notifyAll();
    67                 }
     55                log.debug(this + " is notifying " + joinableListeners.size() + " parents");
     56
     57                List<JoinableParent> parents = new LinkedList<>();
     58                CollectionUtils.addAll(parents, joinableListeners.iterator());
     59
     60                for (JoinableParent p : parents) {
     61                        if (p != null) {
     62                                Dispatching.childChangedState(p, this, state);
     63                        }
     64                }
     65                this.notifyAll();
     66
    6867                report();
    6968
     
    145144                }
    146145                if (start) {
     146                        assert monitor == null;
     147                        monitor = owner.getMonitor();
    147148                        return this.start();
    148149                }
     
    185186        }
    186187
     188        protected boolean isRunning() {
     189                return state.equals(JoinableState.RUNNING);
     190        }
     191
     192        @Override
     193        public String toString() {
     194                return getName();
     195        }
     196
     197        // @Override
     198        public Monitor getMonitor() {
     199                return monitor;
     200        }
     201
    187202
    188203}
  • java/main/src/main/java/com/framsticks/util/dispatching/Dispatching.java

    r90 r96  
    33import org.apache.log4j.Logger;
    44
     5import com.framsticks.util.FramsticksException;
    56import com.framsticks.util.StateFunctor;
    67
     
    2829                        @Override
    2930                        public void run() {
    30                                 stateFunctor.call(null);
     31                                stateFunctor.call();
    3132                        }
    3233                });
     
    170171        }
    171172
    172 
     173        public static class Waiter {
     174                protected boolean done = false;
     175
     176                protected final double timeOut;
     177
     178                /**
     179                 * @param timeOut
     180                 */
     181                public Waiter(double timeOut) {
     182                        this.timeOut = timeOut;
     183                }
     184
     185                public synchronized void pass() {
     186                        done = true;
     187                        this.notify();
     188                }
     189
     190                public synchronized void waitFor() {
     191                        long end = System.currentTimeMillis() + (int)(timeOut * 1000);
     192                        while ((!done) && System.currentTimeMillis() < end) {
     193                                try {
     194                                        this.wait(end - System.currentTimeMillis());
     195                                } catch (InterruptedException e) {
     196                                        break;
     197                                }
     198                        }
     199                        if (!done) {
     200                                throw new FramsticksException().msg("waiter timed out");
     201                        }
     202                }
     203        }
     204
     205
     206        public static <C> void synchronize(Dispatcher<C> dispatcher, double seconds) {
     207                final Waiter waiter = new Waiter(seconds);
     208                dispatcher.dispatch(new RunAt<C>() {
     209                        @Override
     210                        public void run() {
     211                                waiter.pass();
     212                        }
     213                });
     214                waiter.waitFor();
     215        }
    173216
    174217}
  • java/main/src/main/java/com/framsticks/util/dispatching/Future.java

    r84 r96  
    11package com.framsticks.util.dispatching;
     2
     3import com.framsticks.util.FramsticksException;
    24
    35/**
    46 * @author Piotr Sniegowski
    57 */
    6 public interface Future <T> {
    7     void result(T result, Exception e);
     8public abstract class Future<T> implements ExceptionResultHandler {
     9
     10        protected final ExceptionResultHandler handler;
     11
     12        public Future(ExceptionResultHandler handler) {
     13                this.handler = handler;
     14        }
     15
     16        public Future() {
     17                this.handler = null;
     18        }
     19
     20        protected abstract void result(T result);
     21
     22        public final void pass(T result) {
     23                try {
     24                        result(result);
     25                } catch (FramsticksException e) {
     26                        handle(e);
     27                }
     28        }
     29
     30        public static <T> void passOrHandle(Future<T> future, T value, FramsticksException e) {
     31                if (e != null) {
     32                        future.handle(e);
     33                } else {
     34                        future.pass(value);
     35                }
     36        }
     37
     38        @Override
     39        public void handle(FramsticksException exception) {
     40                if (handler != null) {
     41                        handler.handle(exception);
     42                        return;
     43                }
     44                throw exception;
     45        }
    846}
  • java/main/src/main/java/com/framsticks/util/dispatching/Joinable.java

    r88 r96  
    55
    66public interface Joinable {
     7
     8        /** The name of the joinable.
     9         *
     10         * It should never be empty, but it is not required to remain
     11         * constant during lifetime of the object.
     12         */
     13        public String getName();
    714
    815        public boolean use(@Nonnull JoinableParent owner);
  • java/main/src/main/java/com/framsticks/util/dispatching/JoinableCollection.java

    r88 r96  
    22
    33import java.util.Collections;
    4 import java.util.HashMap;
    54import java.util.HashSet;
    65import java.util.Iterator;
    7 import java.util.Map;
    86import java.util.Set;
    97
    10 import com.framsticks.core.Entity;
    118import com.framsticks.params.annotations.AutoAppendAnnotation;
    129import com.framsticks.params.annotations.FramsClassAnnotation;
     
    1916
    2017        protected final Set<T> joinables = new HashSet<T>();
    21         protected final Map<String, T> namedJoinables = new HashMap<>();
    2218
    2319        protected boolean finishIfOne;
     
    3430
    3531        @AutoAppendAnnotation
    36         public void add(T joinable) {
    37                 assert isInState(JoinableState.INITILIAZED);
     32        public synchronized void add(T joinable) {
     33                if (this.state.ordinal() > JoinableState.RUNNING.ordinal()) {
     34                        throw new FramsticksException().msg("failed to add joinable - collection is passed running state").arg("joinable", joinable).arg("collection", this);
     35                }
    3836
    3937                if (joinables.contains(joinable)) {
    4038                        throw new FramsticksException().msg("joinable is already observed").arg("joinable", joinable).arg("in", this);
    4139                }
    42                 // if (observables.containsKey(observable.getName())) {
    43                 //      throw new FramsticksException().msg("observable with given name already exists").arg("name", observable.getName()).arg("in", this);
    44                 // }
     40                joinables.add(joinable);
    4541
    46                 if (joinable instanceof Entity) {
    47                         Entity e = (Entity) joinable;
    48                         if (!namedJoinables.containsKey(e.getName())) {
    49                                 namedJoinables.put(e.getName(), joinable);
    50                         }
     42                if (this.state.equals(JoinableState.RUNNING)) {
     43                        Dispatching.use(joinable, this);
    5144                }
    52 
    53                 joinables.add(joinable);
    5445        }
    5546
     
    10798        public void childChangedState(Joinable joinable, JoinableState state) {
    10899                proceedToState(getNextState());
    109 
    110100        }
    111101
     
    129119
    130120        public T get(String name) {
    131                 return namedJoinables.get(name);
     121                for (T j : joinables) {
     122                        if (j.getName().equals(name)) {
     123                                return j;
     124                        }
     125                }
     126                return null;
    132127        }
    133128
     129        public int size() {
     130                return joinables.size();
     131        }
    134132
    135         public Map<String, T> getObservables() {
    136                 return Collections.unmodifiableMap(namedJoinables);
     133        public boolean contains(T joinable) {
     134                return joinables.contains(joinable);
     135        }
     136
     137        @Override
     138        public String getName() {
     139                return observableName;
    137140        }
    138141
  • java/main/src/main/java/com/framsticks/util/dispatching/JoinableParent.java

    r88 r96  
    44
    55        public void childChangedState(Joinable joinable, JoinableState state);
     6        public Monitor getMonitor();
    67
    78}
  • java/main/src/main/java/com/framsticks/util/dispatching/Monitor.java

    r90 r96  
    22
    33import org.apache.log4j.Logger;
    4 // import edu.umd.cs.findbugs.annotations.SuppressWarnings;
    54import com.framsticks.util.dispatching.Dispatching;
     5import java.lang.Thread;
    66
    77public class Monitor implements JoinableParent {
     
    1010
    1111        protected final Joinable joinable;
     12        protected final Thread shutdownHook;
    1213
    1314        /**
     
    1617        public Monitor(Joinable joinable) {
    1718                this.joinable = joinable;
     19
     20                shutdownHook = new Thread(new Runnable() {
     21                        @Override
     22                        public void run() {
     23                                log.debug("running shutdown hook");
     24                                Monitor.this.drop().join();
     25                        }
     26                });
     27        }
     28
     29        public Monitor use() {
     30                Runtime.getRuntime().addShutdownHook(shutdownHook);
     31
     32                log.debug(this + " is using");
     33                Dispatching.use(joinable, this);
     34                return this;
    1835        }
    1936
     
    3451        }
    3552
    36         public Monitor use() {
    37                 log.debug(this + " is using");
    38                 Dispatching.use(joinable, this);
    39                 return this;
    40         }
    4153
    4254        public Monitor drop() {
     
    5062                Dispatching.joinAbsolutely(joinable);
    5163                log.debug(this + " is joined");
     64
     65                try {
     66                        Runtime.getRuntime().removeShutdownHook(shutdownHook);
     67                } catch (IllegalStateException e) {
     68                        /** In case IllegalStateException is caught, it means that JVM is in finalization stage */
     69                }
     70
    5271                return this;
    5372        }
     
    6786        }
    6887
     88        @Override
     89        public Monitor getMonitor() {
     90                return this;
     91        }
     92
     93        protected ExceptionHandler taskExceptionHandler;
     94
     95        /**
     96         * @return the taskExceptionHandler
     97         */
     98        public ExceptionHandler getTaskExceptionHandler() {
     99                return taskExceptionHandler;
     100        }
     101
     102        /**
     103         * @param taskExceptionHandler the taskExceptionHandler to set
     104         */
     105        public void setTaskExceptionHandler(ExceptionHandler taskExceptionHandler) {
     106                this.taskExceptionHandler = taskExceptionHandler;
     107        }
     108
    69109}
  • java/main/src/main/java/com/framsticks/util/dispatching/Task.java

    r85 r96  
    1313
    1414        public Task(long moment) {
    15                 this.moment = moment;
     15                this.moment = System.currentTimeMillis() + moment;
    1616        }
    1717
  • java/main/src/main/java/com/framsticks/util/dispatching/Thread.java

    r90 r96  
    4747        protected void routine() {
    4848                log.debug("starting thread " + this);
     49                assert getMonitor() != null;
     50                ExceptionHandler exceptionHandler = getMonitor().getTaskExceptionHandler();
    4951                while (!java.lang.Thread.interrupted()) {
    5052                        Task<? extends C> task;
     
    7375                                task.run();
    7476                        } catch (Exception e) {
     77                                if (exceptionHandler != null) {
     78                                        if (exceptionHandler.handle(this, e)) {
     79                                                continue;
     80                                        }
     81                                }
    7582                                log.error("error in thread: ", e);
    7683                        }
  • java/main/src/main/java/com/framsticks/util/lang/Delimeted.java

    r86 r96  
    33import java.util.Iterator;
    44
    5 import org.apache.commons.collections.Closure;
     5// import org.apache.commons.collections.Closure;
    66
    7 public class Delimeted implements Closure {
     7public class Delimeted<T> {
    88
    99        protected final String delimeter;
     
    1919        }
    2020
    21         public final Delimeted append(Object object) {
     21        public final Delimeted<T> append(T object) {
    2222                if (builder != null) {
    2323                        builder.append(delimeter);
     
    2929        }
    3030
    31         public final Delimeted append(Iterator<?> i) {
     31        public final Delimeted<T> append(Iterator<T> i) {
    3232                while (i.hasNext()) {
    3333                        append(i.next());
     
    4141
    4242        @Override
    43         public void execute(Object input) {
    44                 append(input);
     43        public String toString() {
     44                return build();
    4545        }
    4646
     47        // @Override
     48        // public void execute(Object input) {
     49        //      append(input);
     50        // }
     51
    4752}
  • java/main/src/main/java/com/framsticks/util/lang/Pair.java

    r87 r96  
    2424                }
    2525                Pair<?, ?> p = (Pair<?, ?>) obj;
    26                 // return first == p.first && second.equals(se)
    2726                return first.equals(p.first) && second.equals(p.second);
    2827        }
     
    3332        }
    3433
     34        public static <U1, U2> Pair<U1, U2> make(U1 first, U2 second) {
     35                return new Pair<U1, U2>(first, second);
     36        }
     37
    3538}
  • java/main/src/main/java/com/framsticks/util/lang/Strings.java

    r86 r96  
    11package com.framsticks.util.lang;
     2
     3import com.framsticks.util.FramsticksException;
    24
    35/**
     
    1517        public static boolean notEmpty(String str) {
    1618                return str != null && !str.equals("");
     19        }
     20
     21        public static void assureNotEmpty(String str) {
     22                if (!notEmpty(str)) {
     23                        throw new FramsticksException().msg("string is empty");
     24                }
    1725        }
    1826
     
    3543                int pos = string.indexOf(separator);
    3644                if (pos == -1) {
    37                         return new Pair<String, String>(string.substring(0,
    38                                         string.length() - 1), second);
     45                        return new Pair<String, String>(string, second);
    3946                } else {
    40                         return new Pair<String, String>(string.substring(0, pos),
    41                                         string.substring(pos + 1));
     47                        return new Pair<String, String>(string.substring(0, pos), string.substring(pos + 1));
    4248                }
    4349        }
Note: See TracChangeset for help on using the changeset viewer.