Changeset 85


Ignore:
Timestamp:
06/24/13 13:38:40 (11 years ago)
Author:
psniegowski
Message:

HIGHLIGHTS:

  • upgrade to Java 7
    • use try-multi-catch clauses
    • use try-with-resources were appropriate
  • configure FindBugs? (use mvn site and then navigate in browser to the report)
    • remove most bugs found
  • parametrize Dispatching environment (Dispatcher, RunAt?) to enforce more control on the place of closures actual call

CHANGELOG:
Rework FavouritesXMLFactory.

FindBugs?. Thread start.

FindBugs?. Minor change.

FindBugs?. Iterate over entrySet.

FindBugs?. Various.

FindBug?.

FindBug?. Encoding.

FindBug?. Final fields.

FindBug?.

Remove synchronization bug in ClientConnection?.

Experiments with findbugs.

Finish parametrization.

Make RunAt? an abstract class.

More changes in parametrization.

More changes in parametrizing dispatching.

Several changes to parametrize tasks.

Rename Runnable to RunAt?.

Add specific framsticks Runnable.

Add JSR305 (annotations).

Add findbugs reporting.

More improvements to ParamBuilder? wording.

Make FramsClass? accept also ParamBuilder?.

Change wording of ParamBuilder?.

Change wording of Request creation.

Use Java 7 exception catch syntax.

Add ScopeEnd? class.

Upgrade to Java 7.

Location:
java/main
Files:
4 added
63 edited

Legend:

Unmodified
Added
Removed
  • java/main/pom.xml

    r84 r85  
    1919        </properties>
    2020        <dependencies>
     21                <dependency>
     22                        <groupId>com.google.code.findbugs</groupId>
     23                        <artifactId>jsr305</artifactId>
     24                        <version>2.0.1</version>
     25                </dependency>
    2126                <dependency>
    2227                        <groupId>log4j</groupId>
     
    5257                        <version>1.5.2</version>
    5358                </dependency>
    54 
    5559                <dependency>
    5660                        <groupId>org.testng</groupId>
     
    8993                                <version>3.0</version>
    9094                                <configuration>
    91                                         <source>1.6</source>
    92                                         <target>1.6</target>
     95                                        <source>1.7</source>
     96                                        <target>1.7</target>
    9397                                </configuration>
    9498                        </plugin>
     
    122126                </plugins>
    123127        </build>
     128        <reporting>
     129                <plugins>
     130                        <plugin>
     131                                <groupId>org.codehaus.mojo</groupId>
     132                                <artifactId>findbugs-maven-plugin</artifactId>
     133                                <version>2.5.2</version>
     134                                <configuration>
     135                                        <!-- <plugins> -->
     136                                        <!--    <plugin> -->
     137                                        <!--            <groupId>com.google.code.findbugs</groupId> -->
     138                                        <!--            <artifactId>jsr305</artifactId> -->
     139                                        <!--            <version>2.0.1</version> -->
     140                                        <!--    </plugin> -->
     141                                        <!-- </plugins> -->
     142                                </configuration>
     143
     144                        </plugin>
     145                </plugins>
     146        </reporting>
    124147
    125148</project>
  • java/main/src/main/java/com/framsticks/communication/ClientConnection.java

    r84 r85  
    2121import java.util.regex.Matcher;
    2222import java.util.regex.Pattern;
     23import com.framsticks.util.dispatching.RunAt;
    2324
    2425/**
     
    2930        private final static Logger log = Logger.getLogger(ClientConnection.class);
    3031
    31         protected final Map<String, Subscription> subscriptions = new HashMap<String, Subscription>();
     32        protected final Map<String, Subscription<?>> subscriptions = new HashMap<>();
    3233
    3334        public String getAddress() {
     
    9394
    9495        private static class EventFire extends InboundMessage {
    95                 public final Subscription subscription;
    96 
    97                 private EventFire(Subscription subscription) {
     96                public final Subscription<?> subscription;
     97
     98                private EventFire(Subscription<?> subscription) {
    9899                        this.subscription = subscription;
    99100                }
     
    107108                public void eof() {
    108109                        finishCurrentFile();
    109                         Dispatching.invokeLaterOrNow(subscription.getDispatcher(), new Runnable() {
    110                                 @Override
    111                                 public void run() {
    112                                         subscription.getEventCallback().call(getFiles());
    113                                 }
    114                         });
    115                 }
    116         }
    117 
    118         private static class SentQuery extends InboundMessage {
     110
     111                        subscription.dispatchCall(getFiles());
     112                }
     113        }
     114
     115        private static class SentQuery<C> extends InboundMessage {
    119116                Request request;
    120                 ResponseCallback callback;
    121                 Dispatcher dispatcher;
     117                ResponseCallback<? extends C> callback;
     118                Dispatcher<C> dispatcher;
    122119
    123120                public void startFile(String path) {
     
    139136                        return request.toString();
    140137                }
    141         }
    142         private Map<Integer, SentQuery> queryMap = new HashMap<Integer, SentQuery>();
     138
     139                public void dispatchResponseProcess(final Response response) {
     140                        Dispatching.invokeLaterOrNow(dispatcher, new RunAt<C>() {
     141                                @Override
     142                                public void run() {
     143                                        callback.process(response);
     144                                }
     145                        });
     146                }
     147        }
     148        private Map<Integer, SentQuery<?>> queryMap = new HashMap<>();
    143149
    144150
     
    163169        }
    164170
    165         private SentQuery currentlySentQuery;
    166 
    167         public void send(Request request, ResponseCallback callback) {
    168                 send(request, AtOnceDispatcher.instance, callback);
    169         }
    170 
    171         public void send(Request request, Dispatcher dispatcher, ResponseCallback callback) {
     171        private SentQuery<?> currentlySentQuery;
     172
     173
     174        public <C extends Connection> void send(Request request, ResponseCallback<C> callback) {
     175                //TODO RunAt
     176                send(request, AtOnceDispatcher.getInstance(), callback);
     177        }
     178
     179        public <C> void send(Request request, Dispatcher<C> dispatcher, ResponseCallback<? extends C> callback) {
    172180
    173181                if (!isConnected()) {
     
    175183                        return;
    176184                }
    177                 final SentQuery sentQuery = new SentQuery();
     185                final SentQuery<C> sentQuery = new SentQuery<C>();
    178186                sentQuery.request = request;
    179187                sentQuery.callback = callback;
    180188                sentQuery.dispatcher = dispatcher;
    181189
    182                 senderThread.invokeLater(new Runnable(){
     190                senderThread.invokeLater(new RunAt<Connection>(){
    183191                        @Override
    184192                        public void run() {
     193                                Integer id;
    185194                                synchronized (ClientConnection.this) {
    186195
     
    192201                                                }
    193202                                        }
    194                                 }
    195                                 Integer id = stashQuery(sentQuery);
     203                                        if (requestIdEnabled) {
     204                                                queryMap.put(nextQueryId, sentQuery);
     205                                                id = nextQueryId++;
     206                                        } else {
     207                                                currentlySentQuery = sentQuery;
     208                                                id = null;
     209                                        }
     210                                }
    196211                                String command = sentQuery.request.getCommand();
    197212                                StringBuilder message = new StringBuilder();
     
    223238        }
    224239
    225         public void subscribe(final String path, final SubscriptionCallback callback) {
    226                 send(new RegistrationRequest().setPath(path), new ResponseCallback() {
     240        public <C> void subscribe(final String path, final Dispatcher<C> dispatcher, final SubscriptionCallback<? extends C> callback) {
     241                send(new RegistrationRequest().path(path), new ResponseCallback<Connection>() {
    227242                        @Override
    228243                        public void process(Response response) {
     
    233248                                }
    234249                                assert response.getFiles().isEmpty();
    235                                 Subscription subscription = new Subscription(ClientConnection.this, path, response.getComment());
     250                                Subscription<C> subscription = new Subscription<C>(ClientConnection.this, path, response.getComment(), dispatcher);
    236251                                log.debug("registered on event: " + subscription);
    237252                                synchronized (subscriptions) {
     
    241256                                if (subscription.getEventCallback() == null) {
    242257                                        log.info("subscription for " + path + " aborted");
    243                                         subscription.unsubscribe(new LoggingStateCallback(log, "abort subscription"));
     258                                        subscription.unsubscribe(new LoggingStateCallback<C>(log, "abort subscription"));
    244259                                }
    245260                        }
     
    253268
    254269        public void sendQueryVersion(final int version, final StateFunctor stateFunctor) {
    255                 send(new VersionRequest().version(version), new StateCallback() {
     270                send(new VersionRequest().version(version), new StateCallback<Connection>() {
    256271                        @Override
    257272                        public void call(Exception e) {
     
    266281                                        return;
    267282                                }
    268                                 send(new UseRequest().feature("request_id"), new StateCallback() {
     283                                send(new UseRequest().feature("request_id"), new StateCallback<Connection>() {
    269284                                        @Override
    270285                                        public void call(Exception e) {
     
    289304
    290305
    291         private synchronized SentQuery fetchQuery(Integer id, boolean remove) {
     306        private synchronized SentQuery<?> fetchQuery(Integer id, boolean remove) {
    292307                if (id == null) {
    293308                        if (requestIdEnabled) {
    294309                                return null;
    295310                        }
    296                         SentQuery result = currentlySentQuery;
     311                        SentQuery<?> result = currentlySentQuery;
    297312                        if (remove) {
    298313                                currentlySentQuery = null;
     
    302317                }
    303318                if (queryMap.containsKey(id)) {
    304                         SentQuery result = queryMap.get(id);
     319                        SentQuery<?> result = queryMap.get(id);
    305320                        if (remove) {
    306321                                queryMap.remove(id);
     
    312327
    313328        private int nextQueryId = 0;
    314 
    315         private Integer stashQuery(SentQuery sentQuery) {
    316                 if (!requestIdEnabled) {
    317                         currentlySentQuery = sentQuery;
    318                         return null;
    319                 }
    320                 queryMap.put(nextQueryId, sentQuery);
    321                 return nextQueryId++;
    322         }
    323329
    324330        protected void processMessage(InboundMessage inboundMessage) throws Exception {
     
    342348                        return;
    343349                }
    344                 Subscription subscription = subscriptions.get(matcher.group(1));
     350                Subscription<?> subscription = subscriptions.get(matcher.group(1));
    345351                if (subscription == null) {
    346352                        log.error("non subscribed event: " + matcher.group(1));
     
    362368
    363369                if (command.first.equals("file")) {
    364                         SentQuery sentQuery = fetchQuery(rest.first, false);
     370                        SentQuery<?> sentQuery = fetchQuery(rest.first, false);
    365371                        sentQuery.startFile(rest.second);
    366372                        processMessage(sentQuery);
     
    368374                }
    369375
    370                 SentQuery sentQuery = fetchQuery(rest.first, true);
     376                SentQuery<?> sentQuery = fetchQuery(rest.first, true);
    371377                if (sentQuery == null) {
    372378                        return;
     
    374380                log.debug("parsing response for request " + sentQuery);
    375381
    376                 final Response response = new Response(command.first.equals("ok"), rest.second, sentQuery.getFiles());
    377                 final ResponseCallback callback = sentQuery.callback;
    378 
    379                 Dispatching.invokeLaterOrNow(sentQuery.dispatcher, new Runnable() {
    380                         @Override
    381                         public void run() {
    382                                 callback.process(response);
    383                         }
    384                 });
     382                sentQuery.dispatchResponseProcess(new Response(command.first.equals("ok"), rest.second, sentQuery.getFiles()));
    385383        }
    386384
  • java/main/src/main/java/com/framsticks/communication/Connection.java

    r84 r85  
    11package com.framsticks.communication;
    22
     3import com.framsticks.util.io.Encoding;
    34import com.framsticks.util.lang.Pair;
    45import org.apache.log4j.Logger;
     
    67import java.io.IOException;
    78import java.io.InputStreamReader;
     9import java.io.OutputStreamWriter;
    810import java.io.PrintWriter;
    9 import java.lang.Thread;
    1011import java.net.Socket;
    1112import java.net.SocketTimeoutException;
    1213import java.util.regex.Matcher;
    1314import java.util.regex.Pattern;
     15
     16import com.framsticks.util.dispatching.RunAt;
     17import com.framsticks.util.dispatching.Thread;
    1418
    1519public abstract class Connection {
     
    2832        protected int protocolVersion = -1;
    2933
    30         protected final com.framsticks.util.dispatching.Thread senderThread = new com.framsticks.util.dispatching.Thread();
    31         protected Thread receiverThread;
     34        protected final Thread<Connection> senderThread = new Thread<>();
     35        protected final Thread<Connection> receiverThread = new Thread<>();
    3236
    3337        public boolean isConnected() {
     
    4246                        senderThread.interrupt();
    4347                        senderThread.join();
    44                         if (receiverThread != null) {
    45                                 receiverThread.interrupt();
    46                                 receiverThread.join();
    47                                 receiverThread = null;
    48                         }
     48
     49                        receiverThread.interrupt();
     50                        receiverThread.join();
    4951
    5052                        if (output != null) {
     
    7274
    7375        protected static final String ARGUMENT_PATTERN_FRAGMENT = "((?:\\S+)|(?:\"[^\"]*\"))";
    74         protected static Pattern requestIdEnabledPattern = Pattern.compile("^\\s*([0-9]+)(?:\\s+" + ARGUMENT_PATTERN_FRAGMENT + ")?\\n$");
    75         protected static Pattern requestIDisabledPattern = Pattern.compile("^\\s*" + ARGUMENT_PATTERN_FRAGMENT + "?\\n$");
    76         protected static Pattern eventPattern = Pattern.compile("^\\s*(\\S+)\\s*(\\S+)\\n");
     76        protected static final Pattern requestIdEnabledPattern = Pattern.compile("^\\s*([0-9]+)(?:\\s+" + ARGUMENT_PATTERN_FRAGMENT + ")?\\n$");
     77        protected static final Pattern requestIDisabledPattern = Pattern.compile("^\\s*" + ARGUMENT_PATTERN_FRAGMENT + "?\\n$");
     78        protected static final Pattern eventPattern = Pattern.compile("^\\s*(\\S+)\\s*(\\S+)\\n");
    7779
    7880
     
    126128        protected void runThreads() {
    127129                try {
    128                         output = new PrintWriter(socket.getOutputStream(), true);
    129                         input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     130                        output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Encoding.getFramsticksCharset()), true);
     131                        input = new BufferedReader(new InputStreamReader(socket.getInputStream(), Encoding.getFramsticksCharset()));
    130132                } catch (IOException e) {
    131133                        log.error("buffer creation failure");
     
    135137
    136138                senderThread.setName(this + "-sender");
    137                 receiverThread = new Thread(new Runnable() {
     139                receiverThread.setName(this + "-receiver");
     140
     141                senderThread.start();
     142                receiverThread.start();
     143
     144                receiverThread.invokeLater(new RunAt<Connection>() {
    138145                        @Override
    139146                        public void run() {
     
    148155                        }
    149156                });
    150                 receiverThread.setName(this + "-receiver");
    151157
    152                 senderThread.start();
    153                 receiverThread.start();
    154158        }
    155159
  • java/main/src/main/java/com/framsticks/communication/RequestHandler.java

    r77 r85  
    77 */
    88public interface RequestHandler {
    9     public void handle(ApplicationRequest request, ResponseCallback responseCallback);
     9        public void handle(ApplicationRequest request, ResponseCallback<?> responseCallback);
    1010}
  • java/main/src/main/java/com/framsticks/communication/ResponseCallback.java

    r84 r85  
    44 * @author Piotr Sniegowski
    55 */
    6 public interface ResponseCallback {
     6public interface ResponseCallback<C> {
    77        public void process(Response response);
    88}
  • java/main/src/main/java/com/framsticks/communication/ServerConnection.java

    r84 r85  
    88
    99import java.net.Socket;
     10import com.framsticks.util.dispatching.RunAt;
    1011
    1112/**
     
    2627
    2728        public void start() {
    28 
    29 
    3029                runThreads();
    3130        }
     
    4342        }
    4443
    45         protected void handleRequest(Request request, ResponseCallback responseCallback) {
     44        protected void handleRequest(Request request, ResponseCallback<?> responseCallback) {
    4645                if (request instanceof ApplicationRequest) {
    47                         requestHandler.handle((ApplicationRequest)request, responseCallback);
     46                        requestHandler.handle((ApplicationRequest) request, responseCallback);
    4847                        return;
    4948                }
     
    7069
    7170        protected final void respond(final Response response, final Integer id) {
    72                 senderThread.invokeLater(new Runnable() {
     71                senderThread.invokeLater(new RunAt<Connection>() {
    7372                        @Override
    7473                        public void run() {
     
    118117                }
    119118
    120                 handleRequest(request, new ResponseCallback() {
     119                handleRequest(request, new ResponseCallback<ServerConnection>() {
    121120                        @Override
    122121                        public void process(Response response) {
  • java/main/src/main/java/com/framsticks/communication/StateCallback.java

    r77 r85  
    66 * @author Piotr Sniegowski
    77 */
    8 public abstract class StateCallback implements ResponseCallback, StateFunctor {
     8public abstract class StateCallback<C> implements ResponseCallback<C>, StateFunctor {
    99        @Override
    1010        public void process(Response response) {
  • java/main/src/main/java/com/framsticks/communication/Subscription.java

    r84 r85  
    11package com.framsticks.communication;
    22
     3import java.util.List;
     4
    35import com.framsticks.communication.queries.RegistrationRequest;
    4 import com.framsticks.util.dispatching.AtOnceDispatcher;
    56import com.framsticks.util.dispatching.Dispatcher;
     7import com.framsticks.util.dispatching.Dispatching;
     8import com.framsticks.util.dispatching.RunAt;
    69import com.framsticks.util.StateFunctor;
    710import org.apache.log4j.Logger;
     
    1114 * @author Piotr Sniegowski
    1215 */
    13 public class Subscription {
     16public class Subscription<C> {
    1417
    15     private final static Logger log = Logger.getLogger(Subscription.class);
     18        private final static Logger log = Logger.getLogger(Subscription.class);
    1619
    17     private final ClientConnection connection;
    18     private final String path;
     20        private final ClientConnection connection;
     21        private final String path;
    1922        private final String registeredPath;
    20     private Dispatcher dispatcher = AtOnceDispatcher.instance;
     23        private final Dispatcher<C> dispatcher;
    2124
    2225        private EventCallback eventCallback;
    2326
    24         public Subscription(ClientConnection connection, String path, String registeredPath) {
     27        public Subscription(ClientConnection connection, String path, String registeredPath, Dispatcher<C> dispatcher) {
    2528                this.connection = connection;
    26         this.path = path;
     29                this.path = path;
    2730                this.registeredPath = registeredPath;
     31                this.dispatcher = dispatcher;
    2832        }
    2933
     
    4145        }
    4246
    43     public void setDispatcher(Dispatcher dispatcher) {
    44         this.dispatcher = dispatcher;
    45     }
     47        public void unsubscribe(final StateFunctor stateFunctor) {
     48                //@todo remove that /cli/ prefix, when registeredPath will be a fully qualified path
     49                connection.send(new RegistrationRequest().register(false).path(registeredPath), new ResponseCallback<Connection>() {
     50                        @Override
     51                        public void process(Response response) {
     52                                if (!response.getOk()) {
     53                                        log.error("failed to unsunscribe " + this + ": " + response.getComment());
     54                                        stateFunctor.call(new Exception(response.getComment()));
     55                                        return;
     56                                }
     57                                assert response.hasFiles();
     58                                log.debug("unsunscribed " + this);
     59                                stateFunctor.call(null);
     60                        }
     61                });
     62        }
    4663
    47     public void unsubscribe(final StateFunctor stateFunctor) {
    48         //@todo remove that /cli/ prefix, when registeredPath will be a fully qualified path
    49         connection.send(new RegistrationRequest().register(false).setPath(registeredPath), new ResponseCallback() {
    50             @Override
    51             public void process(Response response) {
    52                 if (!response.getOk()) {
    53                     log.error("failed to unsunscribe " + this + ": " + response.getComment());
    54                     stateFunctor.call(new Exception(response.getComment()));
    55                     return;
    56                 }
    57                 assert response.hasFiles();
    58                 log.debug("unsunscribed " + this);
    59                 stateFunctor.call(null);
    60             }
    61         });
    62     }
     64        public EventCallback getEventCallback() {
     65                return eventCallback;
     66        }
    6367
    64     public EventCallback getEventCallback() {
    65         return eventCallback;
    66     }
     68        public Dispatcher<C> getDispatcher() {
     69                return dispatcher;
     70        }
    6771
    68     public Dispatcher getDispatcher() {
    69         return dispatcher;
    70     }
     72        public void setEventCallback(EventCallback eventCallback) {
     73                this.eventCallback = eventCallback;
     74        }
    7175
    72     public void setEventCallback(EventCallback eventCallback) {
    73         this.eventCallback = eventCallback;
    74     }
     76        public void dispatchCall(final List<File> files) {
     77                Dispatching.invokeLaterOrNow(dispatcher, new RunAt<C>() {
     78                        @Override
     79                        public void run() {
     80                                eventCallback.call(files);
     81                        }
     82                });
     83        }
    7584}
  • java/main/src/main/java/com/framsticks/communication/SubscriptionCallback.java

    r77 r85  
    44 * @author Piotr Sniegowski
    55 */
    6 public interface SubscriptionCallback {
    7         EventCallback subscribed(Subscription subscription);
     6public interface SubscriptionCallback<C> {
     7        EventCallback subscribed(Subscription<? super C> subscription);
    88}
  • java/main/src/main/java/com/framsticks/communication/queries/ApplicationRequest.java

    r84 r85  
    1414        protected String fields;
    1515
    16         public ApplicationRequest setPath(String path) {
     16        public ApplicationRequest path(String path) {
    1717                assert path != null;
    1818                this.path = path;
     
    2020        }
    2121
    22         public ApplicationRequest setField(String field) {
     22        public ApplicationRequest field(String field) {
    2323                this.fields = field;
    2424                return this;
    2525        }
    2626
    27         public ApplicationRequest setFields(Collection<String> fields) {
     27        public ApplicationRequest fields(Collection<String> fields) {
    2828                Delimeted d = new Delimeted(",", "");
    2929                for (String f : fields) {
    3030                        d.append(f);
    3131                }
    32                 return setField(d.build());
     32                return field(d.build());
    3333        }
    3434
  • java/main/src/main/java/com/framsticks/communication/util/LoggingStateCallback.java

    r84 r85  
    77 * @author Piotr Sniegowski
    88 */
    9 public class LoggingStateCallback extends StateCallback {
     9public class LoggingStateCallback<C> extends StateCallback<C> {
    1010
    1111        protected final Logger logger;
     
    2323                        return;
    2424                }
    25         logger.debug(message);
     25                logger.debug(message);
    2626        }
    2727}
  • java/main/src/main/java/com/framsticks/communication/util/LoggingSubscriptionCallback.java

    r77 r85  
    99 * @author Piotr Sniegowski
    1010 */
    11 public class LoggingSubscriptionCallback implements SubscriptionCallback {
     11public class LoggingSubscriptionCallback<C> implements SubscriptionCallback<C> {
    1212
    13     protected final Logger logger;
    14     protected final String message;
    15     private final EventCallback eventCallback;
     13        protected final Logger logger;
     14        protected final String message;
     15        private final EventCallback eventCallback;
    1616
    17     public LoggingSubscriptionCallback(Logger logger, String message, EventCallback eventCallback) {
    18         this.logger = logger;
    19         this.message = message;
    20         this.eventCallback = eventCallback;
    21     }
     17        public LoggingSubscriptionCallback(Logger logger, String message, EventCallback eventCallback) {
     18                this.logger = logger;
     19                this.message = message;
     20                this.eventCallback = eventCallback;
     21        }
    2222
    23     @Override
    24     public EventCallback subscribed(Subscription subscription) {
    25         if (subscription == null) {
    26             logger.error("failed to subscribe for " + message);
    27             return null;
    28         }
    29         logger.info("successfuly subscribed for " + message);
    30         return eventCallback;
    31     }
     23        @Override
     24        public EventCallback subscribed(Subscription<? super C> subscription) {
     25                if (subscription == null) {
     26                        logger.error("failed to subscribe for " + message);
     27                        return null;
     28                }
     29                logger.info("successfuly subscribed for " + message);
     30                return eventCallback;
     31        }
    3232}
  • java/main/src/main/java/com/framsticks/core/Entity.java

    r84 r85  
    11package com.framsticks.core;
     2
     3import javax.annotation.OverridingMethodsMustInvokeSuper;
    24
    35import com.framsticks.params.FramsClass;
     
    79import org.apache.commons.configuration.Configuration;
    810import org.apache.log4j.Logger;
     11import com.framsticks.util.dispatching.RunAt;
    912
    1013/**
    1114 * @author Piotr Sniegowski
    1215 */
    13 public abstract class Entity implements Dispatcher {
     16public abstract class Entity implements Dispatcher<Entity> {
    1417
    1518        private final static Logger log = Logger.getLogger(Entity.class.getName());
     
    1720        protected String name = "entity";
    1821        protected EntityOwner owner;
    19         protected Dispatcher dispatcher;
     22        protected Dispatcher<Entity> dispatcher;
    2023
    2124        public Entity() {
     
    3235                this.name = name;
    3336                if (dispatcher instanceof Thread) {
    34                         ((Thread) dispatcher).setName(name);
     37                        ((Thread<Entity>) dispatcher).setName(name);
    3538                }
    3639        }
     
    5659
    5760        @Override
    58         public final void invokeLater(Runnable runnable) {
     61        public final void invokeLater(RunAt<? extends Entity> runnable) {
    5962                assert dispatcher != null;
    6063                dispatcher.invokeLater(runnable);
    6164        }
    6265
    63         public Dispatcher createDefaultDispatcher() {
    64                 return new Thread(name);
     66        public Dispatcher<Entity> createDefaultDispatcher() {
     67                return new Thread<Entity>(name).start();
    6568        }
    6669
     70        @OverridingMethodsMustInvokeSuper
    6771        protected void run() {
    6872                assert isActive();
     
    7478        }
    7579
    76         public Dispatcher getDispatcher() {
     80        public Dispatcher<Entity> getDispatcher() {
    7781                return dispatcher;
    7882        }
     
    8185         * @param dispatcher the dispatcher to set
    8286         */
    83         public void setDispatcher(Dispatcher dispatcher) {
     87        public void setDispatcher(Dispatcher<Entity> dispatcher) {
    8488                this.dispatcher = dispatcher;
    8589        }
     
    9094                        setDispatcher(createDefaultDispatcher());
    9195                }
    92                 invokeLater(new Runnable() {
     96                invokeLater(new RunAt<Entity>() {
    9397                        @Override
    9498                        public void run() {
  • java/main/src/main/java/com/framsticks/core/Instance.java

    r84 r85  
    1212import com.framsticks.util.lang.Casting;
    1313import org.apache.log4j.Logger;
     14import com.framsticks.util.dispatching.RunAt;
    1415
    1516import java.util.*;
     
    3334        protected void run() {
    3435                super.run();
    35                 root = new Node((CompositeParam)new ParamBuilder().setName("Instance").setId(name).setType("o").build(), null);
     36                root = new Node((CompositeParam)Param.build().name("Instance").id(name).type("o").finish(), null);
    3637                com.framsticks.model.Package.register(registry);
    3738        }
     
    7172        public void storeValue(Path path, Param param, Object value, final StateFunctor stateFunctor) {
    7273                assert isActive();
    73                 invokeLater(new Runnable() {
     74                invokeLater(new RunAt<Instance>() {
    7475                        @Override
    7576                        public void run() {
     
    9394        public void addListener(final InstanceListener listener) {
    9495                assert Dispatching.isThreadSafe();
    95                 Dispatching.invokeLaterOrNow(this, new Runnable() {
     96                Dispatching.invokeLaterOrNow(this, new RunAt<Instance>() {
    9697                        @Override
    9798                        public void run() {
     
    103104        public void removeListener(final InstanceListener listener) {
    104105                assert Dispatching.isThreadSafe();
    105                 Dispatching.invokeLaterOrNow(this, new Runnable() {
     106                Dispatching.invokeLaterOrNow(this, new RunAt<Instance>() {
    106107                        @Override
    107108                        public void run() {
     
    271272                if ("/".equals(file.getPath())) {
    272273                        if (root.getParam().getContainedTypeName() == null) {
    273                                 root = new Node((CompositeParam)new ParamBuilder().setName("Instance").setId(name).setType("o " + framsClass.getId()).build(), root.getObject());
     274                                root = new Node((CompositeParam)Param.build().name("Instance").id(name).type("o " + framsClass.getId()).finish(), root.getObject());
    274275                        }
    275276                }
     
    310311
    311312                                        String id = listAccess.computeIdentifierFor(accessInterface.getSelected());
    312                                         Param param = new ParamBuilder().setType("o " + accessInterface.getId()).setId(id).build();
     313                                        Param param = Param.build().type("o " + accessInterface.getId()).id(id).finish();
    313314                                        Object child = accessInterface.getSelected();
    314315                                        accessInterface.select(null);
  • java/main/src/main/java/com/framsticks/core/ListChange.java

    r84 r85  
    22
    33import com.framsticks.params.FramsClass;
    4 import com.framsticks.params.ParamBuilder;
     4import com.framsticks.params.Param;
    55import com.framsticks.params.types.DecimalParam;
    66import com.framsticks.params.types.EnumParam;
     
    5555        public static FramsClass getFramsClass() {
    5656                return new FramsClass("ListChange", "ListChange", null)
    57                                 .append(new ParamBuilder().setId("type").setName("type").setType(new EnumParam(Arrays.asList("Add", "Remove", "Modify"))).build())
    58                                 .append(new ParamBuilder().setId("id").setName("identifier").setType(StringParam.class).build())
    59                                 .append(new ParamBuilder().setId("pos").setName("position").setType(DecimalParam.class).build());
     57                                .append(Param.build().id("type").name("type").type(new EnumParam(Arrays.asList("Add", "Remove", "Modify"))))
     58                                .append(Param.build().id("id").name("identifier").type(StringParam.class))
     59                                .append(Param.build().id("pos").name("position").type(DecimalParam.class));
    6060        }
    6161
  • java/main/src/main/java/com/framsticks/core/LocalInstance.java

    r84 r85  
    1313import java.util.HashSet;
    1414import java.util.Set;
     15import com.framsticks.util.dispatching.RunAt;
    1516
    1617
     
    3334                                acceptSocket = new ServerSocket();
    3435                                acceptSocket.setReuseAddress(true);
    35                                 acceptThread = new Thread(name + "-accept");
     36                                acceptThread = new Thread<Accept>(name + "-accept").start();
    3637                                tryBind(accept);
    3738                        } catch (IOException e) {
     
    4344        protected final Set<InstanceClient> clients = new HashSet<InstanceClient>();
    4445        ServerSocket acceptSocket;
    45         Thread acceptThread;
     46
     47        public static class Accept {
     48        };
     49
     50        Thread<Accept> acceptThread;
    4651
    4752        protected void acceptNext() {
    48                 acceptThread.invokeLater(new Runnable() {
     53                acceptThread.invokeLater(new RunAt<Accept>() {
    4954                        @Override
    5055                        public void run() {
     
    5358                                        assert socket != null;
    5459                                        log.debug("accepted socket: " + socket.getInetAddress().getHostAddress());
    55                                         invokeLater(new Runnable() {
     60                                        invokeLater(new RunAt<LocalInstance>() {
    5661                                                @Override
    5762                                                public void run() {
     
    7075
    7176        public void tryBind(final Integer accept) {
    72                 acceptThread.invokeLater(new Runnable() {
     77                acceptThread.invokeLater(new RunAt<Accept>() {
    7378                        @Override
    7479                        public void run() {
  • java/main/src/main/java/com/framsticks/core/Path.java

    r84 r85  
    55import com.framsticks.params.Param;
    66import com.framsticks.util.dispatching.Dispatching;
     7
    78import java.util.Iterator;
    89import java.util.LinkedList;
    910import java.util.List;
    1011
     12import javax.annotation.concurrent.Immutable;
     13import javax.annotation.Nonnull;
     14
    1115import org.apache.commons.collections.ListUtils;
    1216
     
    1418 * @author Piotr Sniegowski
    1519 */
     20@Immutable
    1621public class Path {
    1722        // private final static Logger log = Logger.getLogger(Path.class.getName());
     
    6368        }
    6469
    65         public Path(Instance instance, List<Node> nodes, Node node) {
     70        public Path(@Nonnull Instance instance, List<Node> nodes, Node node) {
    6671                this.instance = instance;
    6772                StringBuilder b = new StringBuilder();
     
    196201        }
    197202
     203        public void setInstance(Instance instance) {
     204                this.instance = instance;
     205        }
     206
    198207        @SuppressWarnings("unchecked")
    199208        public
  • java/main/src/main/java/com/framsticks/core/Program.java

    r84 r85  
    1010import java.lang.reflect.Constructor;
    1111import java.util.*;
     12import com.framsticks.util.dispatching.RunAt;
    1213
    1314/**
    1415 * @author Piotr Sniegowski
    1516 */
    16 public class Program extends com.framsticks.util.dispatching.Thread {
     17public class Program extends com.framsticks.util.dispatching.Thread<Program> {
    1718
    1819        private final static Logger log = Logger.getLogger(Program.class.getName());
     
    101102
    102103                final Program program = new Program("program");
    103                 program.invokeLater(new Runnable() {
     104                program.invokeLater(new RunAt<Program>() {
    104105                        @Override
    105106                        public void run() {
  • java/main/src/main/java/com/framsticks/diagnostics/DiagnosticsEndpoint.java

    r84 r85  
    11package com.framsticks.diagnostics;
    22
     3import com.framsticks.core.Instance;
    34import com.framsticks.dumping.PrintWriterSink;
    45import com.framsticks.dumping.SaveStream;
     
    89import com.framsticks.util.PeriodicTask;
    910import com.framsticks.util.StateFunctor;
     11import com.framsticks.util.io.Encoding;
     12
    1013import org.apache.log4j.Logger;
    1114
    1215import java.io.File;
     16import java.io.FileOutputStream;
    1317import java.io.IOException;
     18import java.io.OutputStreamWriter;
    1419import java.io.PrintWriter;
    1520import java.text.SimpleDateFormat;
     
    2227
    2328        private final static Logger log = Logger.getLogger(DiagnosticsEndpoint.class.getName());
    24 
    2529
    2630        public DiagnosticsEndpoint() {
     
    3943
    4044                if (getObserver().dumpsInterval != null) {
    41                         new PeriodicTask(instance, getObserver().dumpsInterval * 1000) {
     45                        new PeriodicTask<Instance>(instance, getObserver().dumpsInterval * 1000) {
    4246                                @Override
    4347                                public void run() {
     
    5559                                                                final String fileName = getObserver().dumpsPath + "/" + instance + "_" + new SimpleDateFormat(getObserver().dumpsFormat).format(new Date()) + ".param";
    5660                                                                File file = new File(fileName);
    57                                                                 new SaveStream(new PrintWriterSink(new PrintWriter(file)), instance, instance.getRootPath(), new StateFunctor() {
     61                                                                new SaveStream(new PrintWriterSink(new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), Encoding.getFramsticksCharset()))), instance, instance.getRootPath(), new StateFunctor() {
    5862                                                                        @Override
    5963                                                                        public void call(Exception e) {
  • java/main/src/main/java/com/framsticks/dumping/FileInstance.java

    r84 r85  
    55import com.framsticks.core.Instance;
    66import com.framsticks.util.dispatching.Future;
     7import com.framsticks.util.io.Encoding;
    78
    89import org.apache.commons.configuration.Configuration;
     
    1112import java.io.BufferedReader;
    1213import java.io.File;
    13 import java.io.FileReader;
     14import java.io.FileInputStream;
    1415import java.io.IOException;
     16import java.io.InputStreamReader;
    1517
    1618/**
     
    3638                super.run();
    3739                try {
    38                         FileReader fileReader = new FileReader(file);
    39                         LoadStream stream = new LoadStream(this.getRootPath(), new BufferedReader(fileReader), this, new Future<Path>() {
     40                        LoadStream stream = new LoadStream(this.getRootPath(), new BufferedReader(new InputStreamReader(new FileInputStream(file), Encoding.getFramsticksCharset())), this, new Future<Path>() {
    4041                                @Override
    4142                                public void result(Path result, Exception e) {
  • java/main/src/main/java/com/framsticks/dumping/SaveStream.java

    r84 r85  
    1313import com.framsticks.util.dispatching.Dispatching;
    1414import org.apache.log4j.Logger;
     15import com.framsticks.util.dispatching.RunAt;
    1516
    1617import java.util.HashSet;
     
    4344        protected void dispatchWrite(final Path path) {
    4445                ++dispatched;
    45                 instance.invokeLater(new Runnable() {
     46                instance.invokeLater(new RunAt<Instance>() {
    4647                        @Override
    4748                        public void run() {
  • java/main/src/main/java/com/framsticks/examples/GenotypeBrowser.java

    r84 r85  
    4343
    4444                registry.putInfoIntoCache(new FramsClass("ModelBuilderRoot", "ModelBuilderRoot", null)
    45                                 .append(new ParamBuilder().setType("o Model").setId("model").setName("model").build())
    46                                 .append(new ParamBuilder().setType("s 1").setId("genotype").setName("genotype").build())
     45                                .append(Param.build().type("o Model").id("model").name("model"))
     46                                .append(Param.build().type("s 1").id("genotype").name("genotype"))
    4747                );
    48                 root = new Node((CompositeParam)new ParamBuilder().setType("o ModelBuilderRoot").setId(name).setName("Instance").build(), PropertiesAccess.createPropertiesMap());
     48                root = new Node((CompositeParam)Param.build().type("o ModelBuilderRoot").id(name).name("Instance").finish(), PropertiesAccess.createPropertiesMap());
    4949        }
    5050
  • java/main/src/main/java/com/framsticks/gui/Browser.java

    r84 r85  
    1919import java.util.List;
    2020import java.util.Set;
     21import com.framsticks.util.dispatching.RunAt;
    2122
    2223/**
    2324 * @author Piotr Sniegowski
    2425 */
    25 public class Browser extends Observer implements Dispatcher {
     26public class Browser extends Observer {
    2627
    2728        private static final Logger log = Logger.getLogger(Browser.class.getName());
     
    7879        public void autoResolvePath(final String path, final Future<Path> future) {
    7980                final Instance i = endpoints.get("localhost").getInstance();
    80                 i.invokeLater(new Runnable() {
     81                i.invokeLater(new RunAt<Instance>() {
    8182                        @Override
    8283                        public void run() {
     
    8990                                                }
    9091                                                if (e == null) {
    91                                                         mainFrame.invokeLater(new Runnable() {
     92                                                        mainFrame.invokeLater(new RunAt<Frame>() {
    9293                                                                @Override
    9394                                                                public void run() {
     
    142143
    143144                for (final Endpoint e : getEndpoints().values()) {
    144                         e.invokeLater(new Runnable() {
     145                        e.invokeLater(new RunAt<Instance>() {
    145146                                @Override
    146147                                public void run() {
    147148                                        final Path p = e.getInstance().getRootPath();
    148                                         invokeLater(new Runnable() {
     149                                        invokeLater(new RunAt<Browser>() {
    149150                                                @Override
    150151                                                public void run() {
     
    199200
    200201        @Override
    201         public Dispatcher createDefaultDispatcher() {
    202                 return SwingDispatcher.instance;
     202        public Dispatcher<Entity> createDefaultDispatcher() {
     203                return SwingDispatcher.getInstance();
    203204        }
    204205
  • java/main/src/main/java/com/framsticks/gui/EndpointAtFrame.java

    r84 r85  
    1414
    1515import javax.swing.tree.TreePath;
     16import com.framsticks.util.dispatching.RunAt;
    1617
    1718/**
     
    121122                                }
    122123                                Path p = new Path(path.getInstance(), nodes, n);
     124
     125                                //TODO breaks immutable
     126                                path.setInstance(path.getInstance());
     127
    123128                                log.debug("forced resolution: creating treenode for " + p);
    124129                                TreeNode childNode = new TreeNode(EndpointAtFrame.this, p);
     
    146151                log.trace("fetched " + path);
    147152
    148                 frame.invokeLater(new Runnable() {
     153                frame.invokeLater(new RunAt<Frame>() {
    149154                        @Override
    150155                        public void run() {
     
    155160                                final TreeNode result = (TreeNode) treePath.getLastPathComponent();
    156161                                // log.trace("found " + result + " == " + path);
    157                                 instance.invokeLater(new Runnable() {
     162                                instance.invokeLater(new RunAt<Instance>() {
    158163                                        @Override
    159164                                        public void run() {
  • java/main/src/main/java/com/framsticks/gui/Frame.java

    r84 r85  
    66import com.framsticks.gui.view.TreeCellRenderer;
    77import com.framsticks.util.dispatching.Dispatcher;
     8import com.framsticks.util.lang.ScopeEnd;
    89import com.framsticks.util.swing.KeyboardModifier;
    910import org.apache.log4j.Logger;
     
    2122import java.util.HashMap;
    2223import java.util.Map;
     24import com.framsticks.util.dispatching.RunAt;
    2325
    2426/**
     
    2628 */
    2729@SuppressWarnings("serial")
    28 public class Frame extends JFrame implements Dispatcher {
     30public class Frame extends JFrame implements Dispatcher<Frame> {
    2931
    3032        private static final Logger log = Logger.getLogger(Frame.class.getName());
     
    267269
    268270        @Override
    269         public void invokeLater(Runnable runnable) {
    270                 SwingDispatcher.instance.invokeLater(runnable);
     271        public void invokeLater(RunAt<? extends Frame> runnable) {
     272                SwingDispatcher.getInstance().invokeLater(runnable);
    271273        }
    272274
     
    325327        }
    326328
    327         public Runnable startChange(final DefaultMutableTreeNode node) {
     329        public ScopeEnd startChange(final DefaultMutableTreeNode node) {
    328330                assert isActive();
    329331                final TreePath selection = tree.getSelectionPath();
    330                 return new Runnable() {
    331                         @Override
    332                         public void run() {
     332                return new ScopeEnd() {
     333                        @Override
     334                        public void close() {
    333335                                assert isActive();
    334336                                treeModel.nodeChanged(node);
     
    373375                final TreePath treePath = endpointsByInstance.get(path.getInstance()).getTreePath(path, false);
    374376                log.info("go to path: " + path + "(" + treePath + ")");
    375                 invokeLater(new Runnable() {
     377
     378                new RunAt<Frame>(this) {
    376379                        @Override
    377380                        public void run() {
     381                                log.info("executed");
    378382                                tree.setSelectionPath(treePath);
    379383                                tree.makeVisible(treePath);
    380384                                assert tree.isVisible(treePath);
    381385                        }
    382 
    383                 });
     386                };
     387
    384388        }
    385389
     
    387391        public void addNode(TreeNode child, DefaultMutableTreeNode parent) {
    388392                assert isActive();
    389                 Runnable r = startChange(parent);
    390                 treeModel.insertNodeInto(child, parent, parent.getChildCount());
    391                 r.run();
     393
     394                try (ScopeEnd e = startChange(parent)) {
     395                        treeModel.insertNodeInto(child, parent, parent.getChildCount());
     396                }
    392397        }
    393398
  • java/main/src/main/java/com/framsticks/gui/ObjectPanel.java

    r84 r85  
    1515import java.util.Map;
    1616import static com.framsticks.util.lang.Containers.filterInstanceof;
     17import com.framsticks.util.dispatching.RunAt;
    1718
    1819@SuppressWarnings("serial")
     
    7374                }
    7475
    75                 frame.invokeLater(new Runnable() {
     76                frame.invokeLater(new RunAt<Frame>() {
    7677                        @Override
    7778                        public void run() {
  • java/main/src/main/java/com/framsticks/gui/SwingDispatcher.java

    r84 r85  
    55
    66import javax.swing.*;
     7import com.framsticks.util.dispatching.RunAt;
    78
    89/**
    910 * @author Piotr Sniegowski
    1011 */
    11 public class SwingDispatcher implements Dispatcher {
     12public class SwingDispatcher<C> implements Dispatcher<C> {
    1213
    13         public static final SwingDispatcher instance = new SwingDispatcher();
     14        @SuppressWarnings("rawtypes")
     15        protected static final SwingDispatcher instance = new SwingDispatcher();
     16
     17        @SuppressWarnings("unchecked")
     18        public static <C> Dispatcher<C> getInstance() {
     19                return (Dispatcher<C>) instance;
     20        }
    1421
    1522        public SwingDispatcher() {
    16                 invokeLater(new Runnable() {
     23                invokeLater(new RunAt<C>() {
    1724                        @Override
    1825                        public void run() {
     
    2835
    2936        @Override
    30         public final void invokeLater(Runnable runnable) {
     37        public final void invokeLater(RunAt<? extends C> runnable) {
    3138                assert !(runnable instanceof Task);
    3239                SwingUtilities.invokeLater(runnable);
  • java/main/src/main/java/com/framsticks/gui/TreeNode.java

    r84 r85  
    11package com.framsticks.gui;
    22
     3import com.framsticks.communication.Connection;
    34import com.framsticks.communication.Subscription;
    45import com.framsticks.communication.util.LoggingStateCallback;
     6import com.framsticks.core.Instance;
    57import com.framsticks.core.ListChange;
    68import com.framsticks.core.Path;
     
    1820import com.framsticks.util.StateFunctor;
    1921import org.apache.log4j.Logger;
     22import com.framsticks.util.dispatching.RunAt;
    2023
    2124import javax.swing.tree.DefaultMutableTreeNode;
     
    4043        final protected EndpointAtFrame endpoint;
    4144
    42         final protected Map<EventParam, Subscription> userSubscriptions = new HashMap<EventParam, Subscription>();
     45        final protected Map<EventParam, Subscription<?>> userSubscriptions = new HashMap<>();
    4346        protected Map<ValueControl, Object> localChanges = null;
    4447        protected String tooltip;
     
    5962                iconName = TreeCellRenderer.findIconName(name, path.getTextual());
    6063                tooltip = "?";
    61                 path.getInstance().invokeLater(new Runnable() {
     64                path.getInstance().invokeLater(new RunAt<Instance>() {
    6265                        @Override
    6366                        public void run() {
     
    8285                assert p.getInstance().isActive();
    8386                if (Logging.log(log, "fetch", TreeNode.this, e)) {
    84                         frame.invokeLater(new Runnable() {
     87                        frame.invokeLater(new RunAt<Frame>() {
    8588                                @Override
    8689                                public void run() {
     
    9295                }
    9396                updateChildren(p);
    94                 frame.invokeLater(new Runnable() {
     97                frame.invokeLater(new RunAt<Frame>() {
    9598                        @Override
    9699                        public void run() {
     
    104107                assert !frame.isActive();
    105108                /** TODO those two actions could be merged into single closure */
    106                 frame.invokeLater(new Runnable() {
     109                frame.invokeLater(new RunAt<Frame>() {
    107110                        @Override
    108111                        public void run() {
     
    149152                /**If some child were found, update in frame context.*/
    150153                if (childrenPaths.size() > 0) {
    151                         frame.invokeLater(new Runnable() {
     154                        frame.invokeLater(new RunAt<Frame>() {
    152155                                @Override
    153156                                public void run() {
     
    186189                final Path p = path;
    187190
    188                 p.getInstance().invokeLater(new Runnable() {
     191                p.getInstance().invokeLater(new RunAt<Instance>() {
    189192                        @Override
    190193                        public void run() {
     
    246249                final String name = (nameParam != null ? access.get(nameParam, String.class) : path.getTop().getParam().getId());
    247250
    248                 frame.invokeLater(new Runnable() {
     251                frame.invokeLater(new RunAt<Frame>() {
    249252                        @Override
    250253                        public void run() {
     
    303306                assert p.isResolved();
    304307                panel.setCurrentTreeNode(this);
    305                 p.getInstance().invokeLater(new Runnable() {
     308                p.getInstance().invokeLater(new RunAt<Instance>() {
    306309                        @Override
    307310                        public void run() {
     
    309312                                panel.pullValuesFromLocalToUser(access);
    310313
    311                                 frame.invokeLater(new Runnable() {
     314                                frame.invokeLater(new RunAt<Frame>() {
    312315                                        @Override
    313316                                        public void run() {
     
    341344                final Path p = path;
    342345                log.debug("preparing panel: " + p);
    343                 p.getInstance().invokeLater(new Runnable() {
     346                p.getInstance().invokeLater(new RunAt<Instance>() {
    344347                        @Override
    345348                        public void run() {
     
    347350                                final CompositeParam param = p.getTop().getParam();
    348351                                final FramsClass framsClass = p.getInstance().getInfoFromCache(param.getContainedTypeName());
    349                                 frame.invokeLater(new Runnable() {
     352                                frame.invokeLater(new RunAt<Frame>() {
    350353                                        @Override
    351354                                        public void run() {
     
    410413                        return;
    411414                }
    412                 userSubscriptions.get(eventParam).unsubscribe(new LoggingStateCallback(log, "unsubscribed " + eventParam));
     415                userSubscriptions.get(eventParam).unsubscribe(new LoggingStateCallback<Connection>(log, "unsubscribed " + eventParam));
    413416                userSubscriptions.remove(eventParam);
    414417        }
     
    500503                final Map<ValueControl, Object> changes = localChanges;
    501504                localChanges = null;
    502                 endpoint.getEndpoint().invokeLater(new Runnable() {
     505                endpoint.getEndpoint().invokeLater(new RunAt<Instance>() {
    503506                        @Override
    504507                        public void run() {
     
    514517                                                        }
    515518                                                        log.debug("applied changes for: " + p);
    516                                                         frame.invokeLater(new Runnable() {
     519                                                        frame.invokeLater(new RunAt<Frame>() {
    517520                                                                @Override
    518521                                                                public void run() {
     
    526529                });
    527530        }
    528 
    529531}
  • java/main/src/main/java/com/framsticks/gui/controls/EnumControl.java

    r84 r85  
    1414public class EnumControl extends ValueControl {
    1515
    16         protected final JComboBox list;
     16        protected final JComboBox<String> list;
    1717
    1818        private static final Logger log = Logger.getLogger(EnumControl.class.getName());
     
    2323                this.setMaximumSize(new Dimension(Integer.MAX_VALUE, LINE_HEIGHT));
    2424
    25                 list = new JComboBox();
     25                list = new JComboBox<String>();
    2626                for (String item : enumParam.getElements()) {
    2727                        list.addItem(item);
  • java/main/src/main/java/com/framsticks/gui/windows/ServerLogFrame.java

    r84 r85  
    4343                logText.setWrapStyleWord(true);
    4444                logText.setLineWrap(true);
    45                 JComboBox levelBox = new JComboBox();
     45                JComboBox<String> levelBox = new JComboBox<String>();
    4646                for (String i : STR_) {
    4747                        levelBox.addItem(i);
     
    4949                levelBox.addActionListener(new ActionListener() {
    5050                        public void actionPerformed(ActionEvent e) {
    51                                 levelReporting = ((JComboBox) e.getSource()).getSelectedIndex();
     51                                levelReporting = ((JComboBox<?>) e.getSource()).getSelectedIndex();
    5252                        }
    5353                });
  • java/main/src/main/java/com/framsticks/gui/windows/console/ConsoleFrame.java

    r84 r85  
    172172                addSentMessage(commandText);
    173173                commandLine.setText("");
    174                 connection.send(request, new ResponseCallback() {
     174                connection.send(request, new ResponseCallback<Connection>() {
    175175                        @Override
    176176                        public void process(Response response) {
  • java/main/src/main/java/com/framsticks/hosting/InstanceClient.java

    r84 r85  
    55import com.framsticks.communication.queries.GetRequest;
    66import com.framsticks.communication.queries.InfoRequest;
     7import com.framsticks.core.Instance;
    78import com.framsticks.core.Path;
    89import com.framsticks.params.*;
     
    1516import java.util.LinkedList;
    1617import java.util.List;
     18import com.framsticks.util.dispatching.RunAt;
    1719
    1820/**
     
    3739
    3840        @Override
    39         public void handle(final ApplicationRequest request, final ResponseCallback responseCallback) {
    40                 instance.invokeLater(new Runnable() {
     41        public void handle(final ApplicationRequest request, final ResponseCallback<?> responseCallback) {
     42                instance.invokeLater(new RunAt<Instance>() {
    4143                        @Override
    4244                        public void run() {
  • java/main/src/main/java/com/framsticks/hosting/ServerInstance.java

    r84 r85  
    44import com.framsticks.params.CompositeParam;
    55import com.framsticks.params.FramsClass;
    6 import com.framsticks.params.ParamBuilder;
     6import com.framsticks.params.Param;
    77import com.framsticks.core.LocalInstance;
    88import com.framsticks.util.dispatching.Future;
     
    4242                hosted.setName("hosted");
    4343                hosted.configure(hostedConfig);
    44                 root = new Node((CompositeParam)new ParamBuilder().setName("root").setId("root").setType("o" + hosted.getClass().getCanonicalName()).build(), hosted);
     44                root = new Node((CompositeParam)Param.build().name("root").id("root").type("o" + hosted.getClass().getCanonicalName()).finish(), hosted);
    4545        }
    4646
  • java/main/src/main/java/com/framsticks/leftovers/FavouritesXMLFactory.java

    r84 r85  
    33import java.io.BufferedWriter;
    44import java.io.File;
    5 import java.io.FileWriter;
     5import java.io.FileOutputStream;
     6import java.io.IOException;
     7import java.io.OutputStreamWriter;
     8import java.nio.file.Files;
    69import java.util.ArrayList;
    710import java.util.Collection;
    811import java.util.HashMap;
    9 import java.util.Iterator;
    1012import java.util.LinkedHashMap;
    1113import java.util.Map;
     
    1315import javax.xml.parsers.DocumentBuilder;
    1416import javax.xml.parsers.DocumentBuilderFactory;
     17import javax.xml.parsers.ParserConfigurationException;
    1518import javax.xml.stream.XMLOutputFactory;
     19import javax.xml.stream.XMLStreamException;
    1620import javax.xml.stream.XMLStreamWriter;
    1721
     22import org.apache.log4j.Logger;
    1823import org.w3c.dom.Document;
    1924import org.w3c.dom.Node;
    2025import org.w3c.dom.NodeList;
     26import org.xml.sax.SAXException;
     27
     28import com.framsticks.util.io.Encoding;
    2129
    2230public class FavouritesXMLFactory {
    23 
    24         private final String pathMark = "path";
    25         private final String nameMark = "name";
    26         private final String fieldMark = "field";
    27         private final String typeMark = "type";
     31        private static final Logger log = Logger
     32                        .getLogger(FavouritesXMLFactory.class);
     33
     34        private static final String PATH_MARK = "path";
     35        private static final String NAME_MARK = "name";
     36        private static final String FIELD_MARK = "field";
     37        private static final String TYPE_MARK = "type";
     38
     39        protected Node readDocument(String filename) {
     40                File file = new File(filename);
     41                if (!file.exists()) {
     42                        return null;
     43                }
     44                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
     45                                .newInstance();
     46                try {
     47                        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
     48                        Document doc = docBuilder.parse(file);
     49                        doc.getDocumentElement().normalize();
     50                        return doc.getFirstChild();
     51
     52                } catch (ParserConfigurationException | SAXException | IOException e) {
     53                        log.error(e);
     54                        return null;
     55                }
     56        }
     57
     58        public static class XmlWriter implements AutoCloseable {
     59
     60                BufferedWriter writer = null;
     61                XMLStreamWriter xml = null;
     62
     63                public XmlWriter(String filename) throws XMLStreamException,
     64                                IOException {
     65                        XMLOutputFactory factory = XMLOutputFactory.newInstance();
     66
     67                        File file = new File(filename);
     68                        Files.deleteIfExists(file.toPath());
     69
     70                        writer = new BufferedWriter(new OutputStreamWriter(
     71                                        new FileOutputStream(file),
     72                                        Encoding.getDefaultCharset()));
     73                        xml = factory.createXMLStreamWriter(writer);
     74
     75                        xml.writeStartDocument("1.0");
     76                }
     77
     78                public void close() {
     79                        try {
     80                                xml.writeEndDocument();
     81                                xml.flush();
     82                                xml.close();
     83                                writer.close();
     84                        } catch (XMLStreamException | IOException e) {
     85                                log.error(e);
     86                        }
     87                }
     88
     89                public void start(String name) throws XMLStreamException {
     90                        xml.writeStartElement(name);
     91                }
     92
     93                public void element(String name, Object value) throws XMLStreamException {
     94                        start(name);
     95                        xml.writeCharacters(value.toString());
     96                        end();
     97                }
     98
     99                public void end() throws XMLStreamException {
     100                        xml.writeEndElement();
     101                }
     102
     103                public void attribute(String name, Object value) throws XMLStreamException {
     104                        xml.writeAttribute(name, value.toString());
     105                }
     106        }
    28107
    29108        /**
     
    39118                        return;
    40119                }
    41                 XMLOutputFactory factory = XMLOutputFactory.newInstance();
    42                 BufferedWriter writer = null;
    43                 XMLStreamWriter xmlWriter = null;
    44                 try {
    45                         File file = new File(path);
    46                         if (file.exists()) {
    47                                 file.delete();
    48                         }
    49                         writer = new BufferedWriter(new FileWriter(file));
    50                         xmlWriter = factory.createXMLStreamWriter(writer);
    51                         xmlWriter.writeStartDocument("1.0");
    52                         xmlWriter.writeStartElement("root");
     120
     121                try (XmlWriter xml = new XmlWriter(path)) {
     122                        xml.start("framsticks");
    53123                        for (UserFavourite node : nodes) {
    54                                 xmlWriter.writeStartElement("item");
    55 
    56                                 xmlWriter.writeStartElement(pathMark);
    57                                 xmlWriter.writeCharacters(node.getPath());
    58                                 xmlWriter.writeEndElement();
    59 
    60                                 xmlWriter.writeStartElement(nameMark);
    61                                 xmlWriter.writeCharacters(node.getName());
    62                                 xmlWriter.writeEndElement();
     124                                xml.start("item");
     125
     126                                xml.element(PATH_MARK, node.getPath());
     127                                xml.element(NAME_MARK, node.getName());
    63128
    64129                                /*if(node.isFavouriteNode()){
     
    67132                                        xmlWriter.writeEndElement();
    68133                                }else{ //isFavouriteField() */
    69                                         xmlWriter.writeStartElement(fieldMark);
    70                                         xmlWriter.writeCharacters(node.getField());
    71                                         xmlWriter.writeEndElement();
    72                                 //}
    73 
    74                                 xmlWriter.writeEndElement();
    75                         }
    76 
    77                         xmlWriter.writeEndDocument();
    78                         xmlWriter.flush();
    79                 } catch (Exception e) {
    80                 } finally {
    81                         try {
    82                                 xmlWriter.close();
    83                                 writer.close();
    84                         } catch (Exception e) {
    85                         }
     134                                xml.element(FIELD_MARK, node.getField());
     135                                xml.end();
     136                        }
     137                        xml.end();
     138                } catch (XMLStreamException | IOException e) {
     139                        log.error(e);
    86140                }
    87141        }
     
    95149         *         concatenation of path and field getName.
    96150         */
    97         public LinkedHashMap<String, UserFavourite> readFavouritesXML(String filePath) {
     151        public LinkedHashMap<String, UserFavourite> readFavouritesXML(
     152                        String filePath) {
     153
     154                Node root = readDocument(filePath);
     155                if (root == null) {
     156                        return null;
     157                }
    98158                LinkedHashMap<String, UserFavourite> result = new LinkedHashMap<String, UserFavourite>();
    99159
    100                 File file = new File(filePath);
    101                 if (file.exists()) {
    102                         DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    103                                         .newInstance();
    104                         try {
    105                                 DocumentBuilder docBuilder = docBuilderFactory
    106                                                 .newDocumentBuilder();
    107                                 Document doc = docBuilder.parse(file);
    108                                 doc.getDocumentElement().normalize();
    109                                 Node root = doc.getFirstChild();
    110                                 NodeList items = root.getChildNodes();
    111                                 UserFavourite userNode;
    112                                 String path, name, field;
    113                                 for (int i = 0; i < items.getLength(); i++) {
    114                                         Node item = items.item(i);
    115                                         NodeList itemDetails = item.getChildNodes();
    116                                         if (itemDetails.getLength() == 3) {
    117                                                 if (itemDetails.item(0).getNodeName().equals(pathMark)
    118                                                                 && itemDetails.item(1).getNodeName().equals(nameMark)
    119                                                                 && (itemDetails.item(2).getNodeName().equals(fieldMark)
    120                                                                                 || itemDetails.item(2).getNodeName().equals(typeMark))) {
    121                                                         path = itemDetails.item(0).getTextContent();
    122                                                         name = itemDetails.item(1).getTextContent();
    123                                                         if (itemDetails.item(2).getNodeName().equals(
    124                                                                         fieldMark)) {
    125                                                                 field = itemDetails.item(2).getTextContent();
    126                                                                 userNode = new UserFavourite(path, name, field);
    127                                                                 result.put(path+field, userNode);
    128                                                         }else{
    129                                                                 try {
    130                                                                         // int nodeTypeId = Integer.parseInt(itemDetails.item(2).getTextContent());
    131                                                                         userNode = new UserFavourite(path, name, null);
    132                                                                         result.put(path, userNode);
    133                                                                 } catch (Exception e) {
    134                                                                 }
    135                                                         }
     160                NodeList items = root.getChildNodes();
     161                UserFavourite userNode;
     162                String path, name, field;
     163                for (int i = 0; i < items.getLength(); i++) {
     164                        Node item = items.item(i);
     165                        NodeList itemDetails = item.getChildNodes();
     166                        if (itemDetails.getLength() == 3) {
     167                                if (itemDetails.item(0).getNodeName().equals(PATH_MARK)
     168                                                && itemDetails.item(1).getNodeName().equals(NAME_MARK)
     169                                                && (itemDetails.item(2).getNodeName().equals(FIELD_MARK)
     170                                                                || itemDetails.item(2).getNodeName().equals(TYPE_MARK))) {
     171                                        path = itemDetails.item(0).getTextContent();
     172                                        name = itemDetails.item(1).getTextContent();
     173                                        if (itemDetails.item(2).getNodeName().equals(
     174                                                        FIELD_MARK)) {
     175                                                field = itemDetails.item(2).getTextContent();
     176                                                userNode = new UserFavourite(path, name, field);
     177                                                result.put(path+field, userNode);
     178                                        }else{
     179                                                try {
     180                                                        // int nodeTypeId = Integer.parseInt(itemDetails.item(2).getTextContent());
     181                                                        userNode = new UserFavourite(path, name, null);
     182                                                        result.put(path, userNode);
     183                                                } catch (Exception e) {
    136184                                                }
    137185                                        }
    138186                                }
    139                         } catch (Exception e) {
    140                         }
    141 
     187                        }
    142188                }
    143189
     
    159205                        return;
    160206                }
    161                 XMLOutputFactory factory = XMLOutputFactory.newInstance();
    162                 BufferedWriter writer = null;
    163                 XMLStreamWriter xmlWriter = null;
    164                 try {
    165                         File file = new File(path);
    166                         if (file.exists()) {
    167                                 file.delete();
    168                         }
    169                         writer = new BufferedWriter(new FileWriter(file));
    170                         xmlWriter = factory.createXMLStreamWriter(writer);
    171                         xmlWriter.writeStartDocument("1.0");
    172                         xmlWriter.writeStartElement("root");
    173 
    174                         Iterator<String> iterator = groupColumns.keySet().iterator();
    175                         while (iterator.hasNext()) {
    176                                 /*
    177           Definition of read/write mark.
    178          */
    179                                 String itemMark = "item";
    180                                 xmlWriter.writeStartElement(itemMark);
    181                                 String itemPath = iterator.next();
    182                                 xmlWriter.writeAttribute(pathMark, itemPath);
    183 
    184                                 for (String column : groupColumns.get(itemPath)) {
    185                                         String columnMark = "column";
    186                                         xmlWriter.writeStartElement(columnMark);
    187                                         xmlWriter.writeCharacters(column);
    188                                         xmlWriter.writeEndElement();
     207                try (XmlWriter xml = new XmlWriter(path)) {
     208                        xml.start("framsticks");
     209                        for (Map.Entry<String, ArrayList<String>> i : groupColumns.entrySet()) {
     210                                xml.start("item");
     211                                xml.attribute(PATH_MARK, i.getKey());
     212                                for (String column : i.getValue()) {
     213                                        xml.element("column", column);
    189214                                }
    190 
    191                                 xmlWriter.writeEndElement();
    192                         }
    193 
    194                         xmlWriter.writeEndDocument();
    195                         xmlWriter.flush();
    196                 } catch (Exception e) {
    197                 } finally {
    198                         try {
    199                                 xmlWriter.close();
    200                                 writer.close();
    201                         } catch (Exception e) {
    202                         }
     215                                xml.end();
     216                        }
     217                        xml.end();
     218                } catch (XMLStreamException | IOException e) {
     219                        log.error(e);
    203220                }
    204221        }
     
    214231        public HashMap<String, ArrayList<String>> readColumnConfigurationXML(
    215232                        String path) {
     233                Node root = readDocument(path);
     234                if (root == null) {
     235                        return null;
     236                }
     237
    216238                HashMap<String, ArrayList<String>> result = new LinkedHashMap<String, ArrayList<String>>();
    217239
    218                 File file = new File(path);
    219                 if (file.exists()) {
    220                         DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    221                                         .newInstance();
    222                         try {
    223                                 DocumentBuilder docBuilder = docBuilderFactory
    224                                                 .newDocumentBuilder();
    225                                 Document doc = docBuilder.parse(file);
    226                                 doc.getDocumentElement().normalize();
    227                                 Node root = doc.getFirstChild();
    228                                 NodeList items = root.getChildNodes();
    229                                 String itemPath;
    230                                 ArrayList<String> columns;
    231                                 for (int i = 0; i < items.getLength(); i++) {
    232                                         Node item = items.item(i);
    233                                         itemPath = item.getAttributes().getNamedItem(pathMark)
    234                                                         .getNodeValue();
    235                                         columns = new ArrayList<String>();
    236                                         NodeList itemDetails = item.getChildNodes();
    237                                         for (int j = 0; j < itemDetails.getLength(); j++) {
    238                                                 columns.add(itemDetails.item(j).getTextContent());
    239                                         }
    240                                         result.put(itemPath, columns);
    241                                 }
    242                         } catch (Exception e) {
    243                         }
    244 
    245                 }
    246 
     240                NodeList items = root.getChildNodes();
     241                String itemPath;
     242                ArrayList<String> columns;
     243                for (int i = 0; i < items.getLength(); i++) {
     244                        Node item = items.item(i);
     245                        itemPath = item.getAttributes().getNamedItem(PATH_MARK)
     246                                        .getNodeValue();
     247                        columns = new ArrayList<String>();
     248                        NodeList itemDetails = item.getChildNodes();
     249                        for (int j = 0; j < itemDetails.getLength(); j++) {
     250                                columns.add(itemDetails.item(j).getTextContent());
     251                        }
     252                        result.put(itemPath, columns);
     253                }
    247254                return result;
    248255        }
  • java/main/src/main/java/com/framsticks/leftovers/f0/NeuroClass.java

    r84 r85  
    1616
    1717        /**
    18          * The symbol glymph.
    19          */
    20         private int[] symbolGlymph;
     18         * The symbol glyph.
     19         */
     20        private int[] symbolGlyph;
    2121
    2222        /**
     
    7171         * @param prefLocation the pref location
    7272         * @param visualHints  the visual hints
    73          * @param symbolGlymph the symbol glymph
     73         * @param symbolGlyph the symbol glymph
    7474         */
    7575        public NeuroClass(FramsClass framsClass, int prefInputs,
    7676                                          int prefOutput, int prefLocation, int visualHints,
    77                                           int[] symbolGlymph) {
    78                 super();
     77                                          int[] symbolGlyph) {
    7978                this.framsClass = framsClass;
    8079                this.prefInputs = prefInputs;
     
    8281                this.prefLocation = prefLocation;
    8382                this.visualHints = visualHints;
    84                 this.symbolGlymph = symbolGlymph;
     83                this.symbolGlyph = (symbolGlyph == null ? null : Arrays.copyOf(symbolGlyph, symbolGlyph.length));
    8584        }
    8685
     
    153152         */
    154153        int[] getSymbolGlyph() {
    155                 return symbolGlymph;
     154                return symbolGlyph;
    156155        }
    157156
     
    165164         */
    166165        void setSymbolGlyph(int[] data) {
    167                 symbolGlymph = data;
     166                symbolGlyph = data;
    168167        }
    169168
     
    191190                                .append(", prefLocation=").append(prefLocation)
    192191                                .append(", visualHints=").append(visualHints)
    193                                 .append(", symbolGlymph=").append(Arrays.toString(symbolGlymph));
     192                                .append(", symbolGlymph=").append(Arrays.toString(symbolGlyph));
    194193
    195194                sb.append(", paramList={");
  • java/main/src/main/java/com/framsticks/observers/Endpoint.java

    r84 r85  
    88import com.framsticks.util.dispatching.Dispatcher;
    99import org.apache.log4j.Logger;
     10import com.framsticks.util.dispatching.RunAt;
    1011
    1112/**
    1213 * @author Piotr Sniegowski
    1314 */
    14 public class Endpoint implements Dispatcher, InstanceListener {
     15public class Endpoint implements Dispatcher<Instance>, InstanceListener {
    1516        private final static Logger log = Logger.getLogger(Endpoint.class.getName());
    1617
     
    6768
    6869        @Override
    69         public final void invokeLater(Runnable runnable) {
     70        public final void invokeLater(RunAt<? extends Instance> runnable) {
    7071                instance.invokeLater(runnable);
    7172        }
  • java/main/src/main/java/com/framsticks/params/ArrayListAccess.java

    r84 r85  
    3131        @Override
    3232        public Param getParam(int i) {
    33                 return new ParamBuilder().setId(Integer.toString(i)).setName(elementAccess.getId()).setType("o " + elementAccess.getId()).build();
     33                return Param.build().id(Integer.toString(i)).name(elementAccess.getId()).type("o " + elementAccess.getId()).finish();
    3434        }
    3535
  • java/main/src/main/java/com/framsticks/params/Flags.java

    r84 r85  
    6060                                }
    6161                        }
    62                 } catch (IllegalArgumentException e) {
    63                         e.printStackTrace();
    64                 } catch (IllegalAccessException e) {
     62                } catch (IllegalArgumentException | IllegalAccessException e) {
    6563                        e.printStackTrace();
    6664                }
     
    8078                                } catch (SecurityException e) {
    8179                                        log.warn("security exception was thrown while trying to read flag (" + flag + ")");
    82                                 } catch (NoSuchFieldException e) {
    83                                         log.warn("selected flag is not known (" + flag + ")");
    84                                 } catch (IllegalArgumentException e) {
    85                                         log.warn("selected flag is not known (" + flag + ")");
    86                                 } catch (IllegalAccessException e) {
     80                                } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
    8781                                        log.warn("selected flag is not known (" + flag + ")");
    8882                                }
  • java/main/src/main/java/com/framsticks/params/FramsClass.java

    r84 r85  
    2626public final class FramsClass {
    2727
    28         private final static Logger log = Logger.getLogger(FramsClass.class.getName());
    29 
    30         /**
    31           * The Class which represents group.
    32           */
     28        private final static Logger log = Logger.getLogger(FramsClass.class
     29                        .getName());
     30
     31        /**
     32         * The Class which represents group.
     33         */
    3334
    3435        /** The offset of the parameter (applied for newly added parameter). */
     
    9192        }
    9293
     94        public FramsClass append(ParamBuilder builder) {
     95                return append(builder.finish());
     96        }
     97
    9398        /**
    9499         * Adds new group.
     
    185190        public static FramsClass getFramsClass() {
    186191                return new FramsClass("class", "class", null)
    187                         .append(new ParamBuilder().setId("name").setName("Name").setType(StringParam.class).build())
    188                         .append(new ParamBuilder().setId("id").setName("id").setType(StringParam.class).build())
    189                         .append(new ParamBuilder().setId("desc").setName("Description").setType(StringParam.class).build());
     192                        .append(Param.build().id("name").name("Name").type(StringParam.class))
     193                        .append(Param.build().id("id").name("id").type(StringParam.class))
     194                        .append(Param.build().id("desc").name("Description").type(StringParam.class));
    190195        }
    191196
     
    210215                                //TODO uid should be passed along during construction
    211216                                if (containedType instanceof Class) {
    212                                         return "l " + ((Class<?>) containedType).getCanonicalName() + " name";
     217                                        return "l " + ((Class<?>) containedType).getCanonicalName()
     218                                                        + " name";
    213219                                }
    214220                        }
     
    248254
    249255                public Constructor(Class<?> src, String name) {
    250                         result = new FramsClass(name, name, GENERATE_HELP_PREFIX + src.toString());
     256                        result = new FramsClass(name, name, GENERATE_HELP_PREFIX
     257                                        + src.toString());
    251258                        currentClass = src;
    252259                        while (currentClass != null) {
    253260                                try {
    254261                                        currentClass.getMethod("constructFramsClass", Constructor.class).invoke(null, this);
    255                                 } catch (Exception ignored) {
     262                                } catch (IllegalAccessException | IllegalArgumentException
     263                                                | InvocationTargetException | NoSuchMethodException
     264                                                | SecurityException e) {
     265                                        log.debug("failed to use constructFramsClass static method (skipping): ", e);
    256266                                }
    257267                                currentClass = currentClass.getSuperclass();
     
    285295                                        if (method.getName().startsWith("get")) {
    286296                                                String fieldName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
    287                                                 Param param = new ParamBuilder().setType(returnParamClass).setName(fieldName).setId(fieldName).setHelp(GENERATE_HELP_PREFIX + method.toString()).build();
     297                                                Param param = Param.build().type(returnParamClass).name(fieldName).id(fieldName).help(GENERATE_HELP_PREFIX + method.toString()).finish();
    288298                                                assert param != null;
    289299                                                result.append(param);
     
    308318                                        return this;
    309319                                }
    310                                 Param param = new ParamBuilder().setType(paramClass).setName(field.getName()).setId(field.getName()).setHelp(GENERATE_HELP_PREFIX + field.toString()).build();
     320                                Param param = Param.build().type(paramClass).name(field.getName()).id(field.getName()).help(GENERATE_HELP_PREFIX + field.toString()).finish();
    311321                                assert param != null;
    312322                                result.append(param);
  • java/main/src/main/java/com/framsticks/params/Param.java

    r84 r85  
    105105        public static FramsClass getFramsClass() {
    106106                return new FramsClass("prop", "prop", null)
    107                                 .append(new ParamBuilder().setId("name").setName("Name").setType(StringParam.class).build())
    108                                 .append(new ParamBuilder().setId("id").setName("Id").setType(StringParam.class).build())
    109                                 .append(new ParamBuilder().setId("type").setName("Type").setType(StringParam.class).build())
    110                                 .append(new ParamBuilder().setId("help").setName("Help").setType(StringParam.class).build())
    111                                 .append(new ParamBuilder().setId("flags").setName("Flags").setType(DecimalParam.class).build());
     107                        .append(Param.build().id("name").name("Name").type(StringParam.class).finish())
     108                        .append(Param.build().id("id").name("Id").type(StringParam.class).finish())
     109                        .append(Param.build().id("type").name("Type").type(StringParam.class).finish())
     110                        .append(Param.build().id("help").name("Help").type(StringParam.class).finish())
     111                        .append(Param.build().id("flags").name("Flags").type(DecimalParam.class).finish());
     112        }
     113
     114        public static ParamBuilder build() {
     115                return new ParamBuilder();
    112116        }
    113117
  • java/main/src/main/java/com/framsticks/params/ParamBuilder.java

    r84 r85  
    5555        private PrimitiveParam primitiveParam;
    5656
     57        ParamBuilder() {
     58        }
     59
    5760        /**
    5861         * Build Param based on provided data.
     
    6265         *             when Param getType is not defined
    6366         */
    64         public Param build()  {
     67        public Param finish()  {
    6568                assert param != null;
    6669                param.id = id;
     
    7376        }
    7477
    75         public ParamBuilder setId(String id) {
     78        public ParamBuilder id(String id) {
    7679                this.id = id;
    7780                return this;
     
    8790        }
    8891
    89         public <T extends Param> ParamBuilder setType(Class<T> type) {
     92        public <T extends Param> ParamBuilder type(Class<T> type) {
    9093                try {
    9194                        return internalSetType(type, type.newInstance());
    92                 } catch (InstantiationException e) {
     95                } catch (InstantiationException | IllegalAccessException e) {
    9396                        e.printStackTrace();
    94                 } catch (IllegalAccessException e) {
    95                         e.printStackTrace();
    96                 }
    97                 return this;
    98         }
    99 
    100         public <T extends Param> ParamBuilder setType(T param) {
     97                }
     98                return this;
     99        }
     100
     101        public <T extends Param> ParamBuilder type(T param) {
    101102                return internalSetType(param.getClass(), param);
    102103        }
     
    108109        }
    109110
    110         public ParamBuilder setGroup(Integer group) {
     111        public ParamBuilder group(Integer group) {
    111112                this.group = group;
    112113                return this;
    113114        }
    114115
    115         public ParamBuilder setFlags(Integer flags) {
     116        public ParamBuilder flags(Integer flags) {
    116117                this.flags = flags;
    117118                return this;
    118119        }
    119120
    120         public ParamBuilder setName(String name) {
     121        public ParamBuilder name(String name) {
    121122                this.name = name;
    122123                return this;
     
    142143        }
    143144
    144         public ParamBuilder setType(String type) {
     145        public ParamBuilder type(String type) {
    145146
    146147                log.trace("parsing type: " + type);
     
    153154                switch (first.charAt(0)) {
    154155                        case 'o': {
    155                                 setType(new ObjectParam(second != null ? second : first.substring(1)));
     156                                type(new ObjectParam(second != null ? second : first.substring(1)));
    156157                                break;
    157158                        }
     
    164165                                        log.error("invalid procedure signature '" + signature + "': " + e);
    165166                                }
    166                                 setType(procedureParam);
     167                                type(procedureParam);
    167168                                break;
    168169                        }
     
    171172                                int tildeIndex = type.indexOf("~");
    172173                                if (tildeIndex != -1) {
    173                                         setType(new EnumParam(new ArrayList<String>(Arrays.asList(type.substring(tildeIndex + 1).split("~")))));
     174                                        type(new EnumParam(new ArrayList<String>(Arrays.asList(type.substring(tildeIndex + 1).split("~")))));
    174175                                } else {
    175176                                        if (first.length() >= 2) {
    176                                 switch (first.charAt(1)) {
     177                                                switch (first.charAt(1)) {
    177178                                                        case 'b': {
    178                                                                 setType(BinaryParam.class);
     179                                                                type(BinaryParam.class);
    179180                                                                break;
    180181                                                        }
    181182                                                        case 'c': {
    182                                                                 setType(ColorParam.class);
     183                                                                type(ColorParam.class);
    183184                                                                break;
     185                                                        }
     186                                                        default: {
     187                                                                log.error("unknown type: " + first);
     188                                                                return this;
    184189                                                        }
    185190                                                }
    186191                                        }
    187192                                        if ("0".equals(second) && "1".equals(third)) {
    188                                                 setType(BooleanParam.class);
     193                                                type(BooleanParam.class);
    189194                                        }
    190195                                        if (param == null) {
    191                                                 setType(DecimalParam.class);
     196                                                type(DecimalParam.class);
    192197                                        }
    193198                                }
     
    198203                        }
    199204                        case 'f': {
    200                                 setType(FloatParam.class);
     205                                type(FloatParam.class);
    201206                                parseMinMaxDefNumber(Double.class, second, third);
    202207                                break;
    203208                        }
    204209                        case 'x': {
    205                                 setType(UniversalParam.class);
     210                                type(UniversalParam.class);
    206211                                break;
    207212                        }
    208213                        case 's': {
    209                                 setType(StringParam.class);
    210                                 setMin(second);
    211                                 setMax(third);
     214                                type(StringParam.class);
     215                                min(second);
     216                                max(third);
    212217                                break;
    213218                        }
    214219                        case 'e': {
    215                                 setType(EventParam.class);
     220                                type(EventParam.class);
    216221                                break;
    217222                        }
    218223                        case 'l': {
    219                                 setType(third != null ? new UniqueListParam(second, third) : new ArrayListParam(second));
    220                                 break;
    221                         }
    222 
    223                 }
    224                 return this;
    225         }
    226 
    227         public ParamBuilder setHelp(String help) {
     224                                type(third != null ? new UniqueListParam(second, third) : new ArrayListParam(second));
     225                                break;
     226                        }
     227                        default:{
     228                                log.error("unknown type: " + first);
     229                                return this;
     230                        }
     231                }
     232                return this;
     233        }
     234
     235        public ParamBuilder help(String help) {
    228236                this.help = help;
    229237                return this;
     
    237245        }
    238246
    239         public <T> ParamBuilder setMin(T min) {
     247        public <T> ParamBuilder min(T min) {
    240248                if (primitiveParam != null) {
    241249                        this.primitiveParam.min = min;
     
    244252        }
    245253
    246         public <T> ParamBuilder setMax(T max) {
     254        public <T> ParamBuilder max(T max) {
    247255                if (primitiveParam != null) {
    248256                        this.primitiveParam.max = max;
     
    251259        }
    252260
    253         public <T> ParamBuilder setDef(T def) {
     261        public <T> ParamBuilder def(T def) {
    254262                if (def != null && primitiveParam != null) {
    255263                        this.primitiveParam.def = def;
     
    277285
    278286                try {
    279                         setId(paramEntryValues[0]);
    280                         setGroup(Integer.valueOf(paramEntryValues[1]));
    281                         setFlags(Flags.read(paramEntryValues[2]));
    282                         setName(paramEntryValues[3]);
    283                         setType(paramEntryValues[4]);
    284                         setHelp(paramEntryValues[6]);
     287                        id(paramEntryValues[0]);
     288                        group(Integer.valueOf(paramEntryValues[1]));
     289                        flags(Flags.read(paramEntryValues[2]));
     290                        name(paramEntryValues[3]);
     291                        type(paramEntryValues[4]);
     292                        help(paramEntryValues[6]);
    285293                } catch (IndexOutOfBoundsException e) {
    286294                        /** everything is ok, parameters have just finished*/
     
    290298                        return null;
    291299                }
    292                 return build();
     300                return finish();
    293301        }
    294302
    295303        public void setField(String key, String value) {
    296                 if (key.equals(ID_FIELD)) {
    297                         setId(value);
    298                 } else if (key.equals(NAME_FIELD)) {
    299                         setName(value);
    300                 } else if (key.equals(TYPE_FIELD)) {
    301                         setType(value);
    302                 } else if (key.equals(FLAGS_FIELD)) {
    303                         setFlags(Flags.read(value));
    304                 } else if (key.equals(HELP_FIELD)) {
    305                         setHelp(value);
    306                 } else if (key.equals(GROUP_FIELD)) {
    307                         setGroup(Integer.valueOf(value));
     304                switch (key) {
     305                        case ID_FIELD:
     306                                id(value);
     307                                break;
     308                        case NAME_FIELD:
     309                                name(value);
     310                                break;
     311                        case TYPE_FIELD:
     312                                type(value);
     313                                break;
     314                        case FLAGS_FIELD:
     315                                flags(Flags.read(value));
     316                                break;
     317                        case HELP_FIELD:
     318                                help(value);
     319                                break;
     320                        case GROUP_FIELD:
     321                                group(Integer.valueOf(value));
     322                                break;
     323                        default:
     324                                log.error("unknown field for Param: " + key);
     325                                break;
    308326                }
    309327        }
     
    312330        public static FramsClass getFramsClass() {
    313331                return new FramsClass("prop", "prop", null)
    314                                 .append(new ParamBuilder().setId("name").setName("Name").setType(StringParam.class).build())
    315                                 .append(new ParamBuilder().setId("id").setName("Id").setType(StringParam.class).build())
    316                                 .append(new ParamBuilder().setId("type").setName("Type").setType(StringParam.class).build())
    317                                 .append(new ParamBuilder().setId("help").setName("Help").setType(StringParam.class).build())
    318                                 .append(new ParamBuilder().setId("flags").setName("Flags").setType(DecimalParam.class).build());
     332                        .append(Param.build().id("name").name("Name").type(StringParam.class))
     333                        .append(Param.build().id("id").name("Id").type(StringParam.class))
     334                        .append(Param.build().id("type").name("Type").type(StringParam.class))
     335                        .append(Param.build().id("help").name("Help").type(StringParam.class))
     336                        .append(Param.build().id("group").name("Group").type(DecimalParam.class))
     337                        .append(Param.build().id("flags").name("Flags").type(DecimalParam.class));
    319338        }
    320339
  • java/main/src/main/java/com/framsticks/params/PropertiesAccess.java

    r84 r85  
    4040                assert properties != null;
    4141                assert param != null;
    42                 Object object = null;
     42                Object object = properties.get(param.getId());
     43                if (object != null) {
     44                        try {
     45                                return type.cast(object);
     46                        } catch (ClassCastException e) {
     47                                throw (ClassCastException) new ClassCastException("property " + param + " type is " + object.getClass().getName() + ", not " + type.getName()).initCause(e);
     48                        }
     49                }
    4350                try {
    44                         object = properties.get(param.getId());
    45                         if (object == null) {
    46                                 return param.getDef(type);
    47                         }
    48                         return type.cast(object);
     51                        return param.getDef(type);
    4952                } catch (ClassCastException e) {
    50                         throw new ClassCastException("property " + param.getId() + " type is " + object.getClass().getName() + ", not " + type.getName());
     53                        throw (ClassCastException) new ClassCastException("default value of property " + param + " is not of type " + type.getName()).initCause(e);
    5154                }
    5255
  • java/main/src/main/java/com/framsticks/params/ReflectionAccess.java

    r84 r85  
    4747                        try {
    4848                                return type.cast(reflectedClass.getMethod(accessorName(true, id)).invoke(object));
    49                         } catch (NoSuchMethodException ex) {
    50                                 //ex.printStackTrace();
    51                         } catch (InvocationTargetException e) {
     49                        } catch (NoSuchMethodException | InvocationTargetException ex) {
     50                                //e.printStackTrace();
     51                        }
     52                        try {
     53                                return type.cast(reflectedClass.getMethod(id).invoke(object));
     54                        } catch (NoSuchMethodException | InvocationTargetException ex) {
    5255                                //e.printStackTrace();
    5356                        }
    5457
    55                 } catch (IllegalAccessException ex) {
     58                } catch (IllegalAccessException e) {
    5659                        log.warn("illegal access error occurred while trying to access returnedObject");
    57                         ex.printStackTrace();
     60                        e.printStackTrace();
    5861                } catch (ClassCastException ignored) {
    5962
     
    8790                        try {
    8891                                reflectedClass.getMethod(accessorName(false, id), new Class[]{param.getStorageType()}).invoke(object, value);
    89                         } catch (InvocationTargetException ignored) {
    90                         } catch (NoSuchMethodException ignored) {
     92                        } catch (InvocationTargetException | NoSuchMethodException ignored) {
     93                        }
     94                        try {
     95                                reflectedClass.getMethod(id, new Class[]{param.getStorageType()}).invoke(object, value);
     96                        } catch (InvocationTargetException | NoSuchMethodException ignored) {
    9197                        }
    9298                } catch (Exception ex) {
     
    161167                try {
    162168                        return reflectedClass.newInstance();
    163                 } catch (InstantiationException e) {
    164                         e.printStackTrace();
    165                 } catch (IllegalAccessException e) {
     169                } catch (InstantiationException | IllegalAccessException e) {
    166170                        e.printStackTrace();
    167171                }
  • java/main/src/main/java/com/framsticks/params/UniqueListAccess.java

    r84 r85  
    3535                //log.error("accesing unique list through index");
    3636                //return null;
    37                 //return new ParamBuilder().setId(Integer.toString(i)).setName(elementAccess.getId()).setType("o " + elementAccess.getId()).build();
     37                //return Param.build().setId(Integer.toString(i)).setName(elementAccess.getId()).type("o " + elementAccess.getId()).build();
    3838        }
    3939
     
    4444                        return getParam(i);
    4545                }
    46                 return new ParamBuilder().setId(id).setName(elementAccess.getId()).setType("o " + elementAccess.getId()).build();
     46                return Param.build().id(id).name(elementAccess.getId()).type("o " + elementAccess.getId()).finish();
    4747        }
    4848
  • java/main/src/main/java/com/framsticks/params/types/ProcedureParam.java

    r84 r85  
    22
    33import com.framsticks.params.Param;
    4 import com.framsticks.params.ParamBuilder;
    54import com.framsticks.util.lang.Strings;
    65
     
    2019
    2120        protected static Param parseType(String type, String name) {
    22                 return new ParamBuilder().setType(type).setName(name).build();
     21                return Param.build().type(type).name(name).finish();
    2322        }
    2423
  • java/main/src/main/java/com/framsticks/parsers/F0Parser.java

    r84 r85  
    8484                        ParseException {
    8585
    86                 InputStreamReader reader = null;
    87                 try {
    88                         reader = new InputStreamReader(is, "UTF-8");
     86                try (InputStreamReader reader = new InputStreamReader(is, "UTF-8")) {
    8987                        BufferedReader br = new BufferedReader(reader);
    9088                        while (br.ready()) {
     
    114112                        if (result.isEmpty() || !(result.get(0) instanceof Model)) {
    115113                                result.add(0, processLine("m:"));
    116                         }
    117                 } finally {
    118                         if (reader != null) {
    119                                 reader.close();
    120114                        }
    121115                }
  • java/main/src/main/java/com/framsticks/parsers/F0Writer.java

    r84 r85  
    1515        protected final SinkInterface sink;
    1616        protected final Model model;
    17         protected boolean omit = true;
     17        protected boolean omitDefaults = true;
    1818
    1919        public F0Writer(Schema schema, Model model, SinkInterface sink) {
     
    2323        }
    2424
    25         F0Writer omitDefaultValues(boolean omit) {
    26                 this.omit = omit;
     25        public F0Writer setOmitDefaults(boolean omitDefaults) {
     26                this.omitDefaults = omitDefaults;
    2727                return this;
    2828        }
     
    4949                        }
    5050                        Object value = access.get(param, Object.class);
    51                         if ((param instanceof PrimitiveParam) && Misc.equals(value, ((PrimitiveParam) param).getDef(Object.class))) {
     51                        if (omitDefaults && (param instanceof PrimitiveParam) && Misc.equals(value, ((PrimitiveParam) param).getDef(Object.class))) {
    5252                                contiguous = false;
    5353                                continue;
  • java/main/src/main/java/com/framsticks/parsers/FileSource.java

    r78 r85  
    22
    33import com.framsticks.params.SourceInterface;
     4import com.framsticks.util.io.Encoding;
    45
    56import java.io.*;
     
    89public class FileSource implements SourceInterface {
    910
    10         private BufferedReader reader;
    11         private String filename;
    12        
    13         public FileSource(String filename) throws IOException
    14         {
     11        private final BufferedReader reader;
     12        private final String filename;
     13
     14        protected FileSource(InputStream stream, String filename) {
    1515                this.filename = filename;
    16         reader = new BufferedReader(new FileReader(filename));
     16                this.reader = new BufferedReader(new InputStreamReader(stream, Encoding.getFramsticksCharset()));
     17        }
     18
     19        public FileSource(String filename) throws IOException {
     20                this(new FileInputStream(filename), filename);
    1721        }
    1822
    1923        public FileSource(InputStream stream) {
    20                 filename = "<stream>";
    21                 reader = new BufferedReader(new InputStreamReader(stream));
     24                this(stream, "<stream>");
    2225        }
    2326
    24 
    25     @Override
    26     public String readLine()
     27        @Override
     28        public String readLine()
    2729        {
    2830                try
     
    3537        }
    3638
    37     @Override
    38     public String getFilename()
     39        @Override
     40        public String getFilename()
    3941        {
    4042                return filename;
    4143        }
    4244
    43     @Override
    44     public String demangleInclude(String include)
     45        @Override
     46        public String demangleInclude(String include)
    4547        {
    4648                if (!include.contains(java.io.File.separator)) {
     
    5254                        }
    5355                        include = currentFilePath + include;
    54                 }       
     56                }
    5557                return include;
    5658        }
    5759
    58     @Override
    59     public SourceInterface openInclude(String include)
     60        @Override
     61        public SourceInterface openInclude(String include)
    6062        {
    6163                try
     
    6567                catch(IOException e)
    6668                {
    67                        
     69
    6870                }
    6971                return null;
    7072        }
    7173
    72     @Override
    73     public void close()
     74        @Override
     75        public void close()
    7476        {
    7577                try {
    7678                        reader.close();
    7779                } catch (IOException e) {
    78                        
     80
    7981                }
    8082        }
    81        
     83
    8284}
  • java/main/src/main/java/com/framsticks/parsers/GenotypeLoader.java

    r77 r85  
    2222                //getId, group-number, getFlags, getName, getType(getType min max), getHelp
    2323                entries
    24                         .append(new ParamBuilder().setId("name").setGroup(0).setName("Name").setType(new StringParam()).setMin(0).setMax(40).build())
    25                         .append(new ParamBuilder().setId("genotype").setGroup(0).setName("Genotype").setType(new StringParam()).setMin(1).build())
    26                         .append(new ParamBuilder().setId("info").setGroup(0).setName("Info").setType(new StringParam()).setMin(1).setHelp("Additional information or comments").build())
    27                         .append(new ParamBuilder().setId("simi").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Similarity").setType(new FloatParam()).build())
    28                         .append(new ParamBuilder().setId("energ0").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Starting energy").setType(new FloatParam()).build())
    29                         .append(new ParamBuilder().setId("strsiz").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).setName("Body parts (deprecated; use numparts)").setType(new FloatParam()).build())
    30                         .append(new ParamBuilder().setId("strjoints").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).setName("Body joints (deprecated; use numjoints)").setType(new FloatParam()).build())
    31                         .append(new ParamBuilder().setId("nnsiz").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).setName("Brain size (deprecated; use numneurons)").setType(new FloatParam()).build())
    32                         .append(new ParamBuilder().setId("nncon").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).setName("Brain connections (deprecated; use numconnections)").setType(new FloatParam()).build())
    33                         .append(new ParamBuilder().setId("numparts").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Body parts").setType(new FloatParam()).build())
    34                         .append(new ParamBuilder().setId("numjoints").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Body joints").setType(new FloatParam()).build())
    35                         .append(new ParamBuilder().setId("numneurons").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Brain size").setType(new FloatParam()).build())
    36                         .append(new ParamBuilder().setId("numconnections").setGroup(1).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Brain connections").setType(new FloatParam()).build())
    37                         .append(new ParamBuilder().setId("num").setGroup(2).setName("Ordinal number").setType(new DecimalParam()).build())
    38                         .append(new ParamBuilder().setId("gnum").setGroup(2).setName("Generation").setType(new DecimalParam()).build())
    39                         .append(new ParamBuilder().setId("popsiz").setGroup(2).setFlags(Flags.USERHIDDEN).setName("Deprecated; use entities").setType(new DecimalParam()).build())
    40                         .append(new ParamBuilder().setId("entities").setGroup(2).setFlags(Flags.DONTSAVE).setName("Instances").setType(new DecimalParam()).setHelp("Copies of this genotype").build())
    41                         .append(new ParamBuilder().setId("lifespan").setGroup(2).setName("Life span").setType(new FloatParam()).setHelp("Average life span").build())
    42                         .append(new ParamBuilder().setId("velocity").setGroup(2).setName("Velocity").setType(new FloatParam()).setHelp("Average velocity").build())
    43                         .append(new ParamBuilder().setId("distance").setGroup(2).setName("Distance").setType(new FloatParam()).build())
    44                         .append(new ParamBuilder().setId("vertvel").setGroup(2).setName("Vertical velocity").setType(new FloatParam()).build())
    45                         .append(new ParamBuilder().setId("vertpos").setGroup(2).setName("Vertical position").setType(new FloatParam()).build())
    46                         .append(new ParamBuilder().setId("fit").setGroup(3).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Fitness").setType(new FloatParam()).build())
    47                         .append(new ParamBuilder().setId("fit2").setGroup(3).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("Final fitness").setType(new FloatParam()).setHelp("Fitness shifted by (avg-n*stddev)").build())
    48                         .append(new ParamBuilder().setId("f0genotype").setGroup(4).setFlags(Flags.READONLY | Flags.DONTSAVE).setName("f0 genotype").setType(new StringParam()).setMin(1).setHelp("converted to f0 genotype").build())
    49                         .append(new ParamBuilder().setId("user1").setGroup(2).setName("User field 1").setType(new UniversalParam()).build())
    50                         .append(new ParamBuilder().setId("user2").setGroup(2).setName("User field 2").setType(new UniversalParam()).build())
    51                         .append(new ParamBuilder().setId("user3").setGroup(2).setName("User field 3").setType(new UniversalParam()).build())
    52                         .append(new ParamBuilder().setId("isValid").setGroup(0).setFlags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).setName("Valid").setType(new DecimalParam()).setMin(0).setMax(1).build())
    53                         .append(new ParamBuilder().setId("uid").setGroup(0).setFlags(Flags.READONLY | Flags.USERHIDDEN).setName("#").setType("s").setHelp("Unique identifier").build());
     24                        .append(Param.build().id("name").group(0).name("Name").type(StringParam.class).min(0).max(40))
     25                        .append(Param.build().id("genotype").group(0).name("Genotype").type(StringParam.class).min(1))
     26                        .append(Param.build().id("info").group(0).name("Info").type(StringParam.class).min(1).help("Additional information or comments"))
     27                        .append(Param.build().id("simi").group(1).flags(Flags.READONLY | Flags.DONTSAVE).name("Similarity").type(FloatParam.class))
     28                        .append(Param.build().id("energ0").group(1).flags(Flags.READONLY | Flags.DONTSAVE).name("Starting energy").type(FloatParam.class))
     29                        .append(Param.build().id("strsiz").group(1).flags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).name("Body parts (deprecated; use numparts)").type(FloatParam.class))
     30                        .append(Param.build().id("strjoints").group(1).flags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).name("Body joints (deprecated; use numjoints)").type(FloatParam.class))
     31                        .append(Param.build().id("nnsiz").group(1).flags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).name("Brain size (deprecated; use numneurons)").type(FloatParam.class))
     32                        .append(Param.build().id("nncon").group(1).flags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).name("Brain connections (deprecated; use numconnections)").type(FloatParam.class))
     33                        .append(Param.build().id("numparts").group(1).flags(Flags.READONLY | Flags.DONTSAVE).name("Body parts").type(FloatParam.class))
     34                        .append(Param.build().id("numjoints").group(1).flags(Flags.READONLY | Flags.DONTSAVE).name("Body joints").type(FloatParam.class))
     35                        .append(Param.build().id("numneurons").group(1).flags(Flags.READONLY | Flags.DONTSAVE).name("Brain size").type(FloatParam.class))
     36                        .append(Param.build().id("numconnections").group(1).flags(Flags.READONLY | Flags.DONTSAVE).name("Brain connections").type(FloatParam.class))
     37                        .append(Param.build().id("num").group(2).name("Ordinal number").type(DecimalParam.class))
     38                        .append(Param.build().id("gnum").group(2).name("Generation").type(DecimalParam.class))
     39                        .append(Param.build().id("popsiz").group(2).flags(Flags.USERHIDDEN).name("Deprecated; use entities").type(DecimalParam.class))
     40                        .append(Param.build().id("entities").group(2).flags(Flags.DONTSAVE).name("Instances").type(DecimalParam.class).help("Copies of this genotype"))
     41                        .append(Param.build().id("lifespan").group(2).name("Life span").type(FloatParam.class).help("Average life span"))
     42                        .append(Param.build().id("velocity").group(2).name("Velocity").type(FloatParam.class).help("Average velocity"))
     43                        .append(Param.build().id("distance").group(2).name("Distance").type(FloatParam.class))
     44                        .append(Param.build().id("vertvel").group(2).name("Vertical velocity").type(FloatParam.class))
     45                        .append(Param.build().id("vertpos").group(2).name("Vertical position").type(FloatParam.class))
     46                        .append(Param.build().id("fit").group(3).flags(Flags.READONLY | Flags.DONTSAVE).name("Fitness").type(FloatParam.class))
     47                        .append(Param.build().id("fit2").group(3).flags(Flags.READONLY | Flags.DONTSAVE).name("Final fitness").type(FloatParam.class).help("Fitness shifted by (avg-n*stddev)"))
     48                        .append(Param.build().id("f0genotype").group(4).flags(Flags.READONLY | Flags.DONTSAVE).name("f0 genotype").type(StringParam.class).min(1).help("converted to f0 genotype"))
     49                        .append(Param.build().id("user1").group(2).name("User field 1").type(UniversalParam.class))
     50                        .append(Param.build().id("user2").group(2).name("User field 2").type(UniversalParam.class))
     51                        .append(Param.build().id("user3").group(2).name("User field 3").type(UniversalParam.class))
     52                        .append(Param.build().id("isValid").group(0).flags(Flags.READONLY | Flags.DONTSAVE | Flags.USERHIDDEN).name("Valid").type(DecimalParam.class).min(0).max(1))
     53                        .append(Param.build().id("uid").group(0).flags(Flags.READONLY | Flags.USERHIDDEN).name("#").type("s").help("Unique identifier"));
    5454
    5555                ReflectionAccess reflectionParam = new ReflectionAccess(Genotype.class, entries);
  • java/main/src/main/java/com/framsticks/parsers/Loaders.java

    r84 r85  
    3535                                        }
    3636                                        if (object instanceof ParamBuilder) {
    37                                                 result.append(((ParamBuilder) object).build());
     37                                                result.append(((ParamBuilder) object).finish());
    3838                                        }
    3939                                }
  • java/main/src/main/java/com/framsticks/parsers/Schema.java

    r84 r85  
    2626 * classes definitions that can be used in f0 representation). Definitions are
    2727 * loaded from XML stream.
    28  * 
     28 *
    2929 * @author Jarek Szymczak <name.surname@gmail.com>
    3030 * (please replace name and surname with my personal data)
     
    4646        /**
    4747         * Instantiates a new schema.
    48          * 
     48         *
    4949         * @param inputStream
    5050         *            the xml stream with schema
     
    104104                        }
    105105
    106                 } catch (IOException e) {
    107                         logger.fatal("unexpected exception occurred: ", e);
    108                         throw e;
    109                 } catch (ParserConfigurationException e) {
    110                         logger.fatal("unexpected exception occurred: ", e);
    111                         throw e;
    112                 } catch (SAXException e) {
     106                } catch (IOException | ParserConfigurationException | SAXException e) {
    113107                        logger.fatal("unexpected exception occurred: ", e);
    114108                        throw e;
     
    121115         * node under certain attribute getName. If value is not present or is other
    122116         * getType than integer 0 is returned.
    123          * 
     117         *
    124118         * @return attribute value if value exists and it's integer (0 otherwise)
    125          * 
     119         *
    126120         */
    127121        private static int getIntAttribute(NamedNodeMap attributes, String name) {
     
    152146         * Method used for convenience, it retrieves the value stored in node under
    153147         * certain attribute getName. If value is not present method returns null.
    154          * 
     148         *
    155149         * @param attributeName
    156150         *            the attribute getName
     
    158152         *            the node
    159153         * @return attribute value if value exists (null otherwise)
    160          * 
     154         *
    161155         */
    162156        private static String getAttributeFromNode(String attributeName, Node node) {
     
    169163        /**
    170164         * In this method analysis of single class is performed.
    171          * 
     165         *
    172166         * @param classNode
    173167         *            the class node
     
    228222        /**
    229223         * It analyses the single property within the class
    230          * 
     224         *
    231225         * @param attributes
    232226         *            the attributes of property
     
    267261                }
    268262
    269                 ParamBuilder builder = new ParamBuilder();
    270                 builder.setId(id).setName(name).setHelp(description).setGroup(group).setFlags(flags);
    271 
    272                 builder.setType(type);
     263                ParamBuilder builder = Param.build();
     264                builder.id(id).name(name).help(description).group(group).flags(flags);
     265
     266                builder.type(type);
    273267
    274268                if ("d".equals(type)) {
    275                         builder.setMin(extractAttribute(attributes, "MIN", Integer.class));
    276                         builder.setMax(extractAttribute(attributes, "MAX", Integer.class));
    277                         builder.setDef(extractAttribute(attributes, "DEF", Integer.class));
     269                        builder.min(extractAttribute(attributes, "MIN", Integer.class));
     270                        builder.max(extractAttribute(attributes, "MAX", Integer.class));
     271                        builder.def(extractAttribute(attributes, "DEF", Integer.class));
    278272                } else if ("f".equals(type)) {
    279                         builder.setMin(extractAttribute(attributes, "MIN", Double.class));
    280                         builder.setMax(extractAttribute(attributes, "MAX", Double.class));
    281                         builder.setDef(extractAttribute(attributes, "DEF", Double.class));
     273                        builder.min(extractAttribute(attributes, "MIN", Double.class));
     274                        builder.max(extractAttribute(attributes, "MAX", Double.class));
     275                        builder.def(extractAttribute(attributes, "DEF", Double.class));
    282276                } else if ("s".equals(type)) {
    283                         builder.setMin(extractAttribute(attributes, "MIN", Integer.class));
    284                         builder.setMax(extractAttribute(attributes, "MAX", Integer.class));
    285                         builder.setDef(extractAttribute(attributes, "DEF", Integer.class));
    286                         builder.setDef(getAttribute(attributes, "DEF"));
     277                        builder.min(extractAttribute(attributes, "MIN", Integer.class));
     278                        builder.max(extractAttribute(attributes, "MAX", Integer.class));
     279                        builder.def(extractAttribute(attributes, "DEF", Integer.class));
     280                        builder.def(getAttribute(attributes, "DEF"));
    287281                } else {
    288                         builder.setType(type);
    289                 }
    290                 return builder.build();
     282                        builder.type(type);
     283                }
     284                return builder.finish();
    291285        }
    292286
  • java/main/src/main/java/com/framsticks/portals/Portal.java

    r84 r85  
    2222        public void run() {
    2323                super.run();
    24                 new PeriodicTask(this, 1000) {
     24                new PeriodicTask<Portal>(this, 1000) {
    2525
    2626                        @Override
  • java/main/src/main/java/com/framsticks/portals/PortalEndpoint.java

    r84 r85  
    11package com.framsticks.portals;
    22
     3import com.framsticks.core.Instance;
    34import com.framsticks.core.Path;
    45import com.framsticks.observers.Endpoint;
     
    78import com.framsticks.util.Logging;
    89import org.apache.log4j.Logger;
     10import com.framsticks.util.dispatching.RunAt;
    911
    1012/**
     
    1820        }
    1921
    20     @Override
    21     public Portal getObserver() {
    22         return (Portal) observer;
    23     }
     22        @Override
     23        public Portal getObserver() {
     24                return (Portal) observer;
     25        }
    2426
    25     @Override
    26     public void onRun(Exception e) {
    27         assert Dispatching.isThreadSafe();
     27        @Override
     28        public void onRun(Exception e) {
     29                assert Dispatching.isThreadSafe();
    2830
    29         super.onRun(e);
     31                super.onRun(e);
    3032
    31         if (e != null) {
    32             return;
    33         }
    34         final String path = "/simulator/genepools/groups/0/genotypes";
    35         instance.invokeLater(new Runnable() {
    36             @Override
    37             public void run() {
    38                 PortalEndpoint.this.instance.resolve(path, new Future<Path>() {
    39                     @Override
    40                     public void result(Path result, Exception e) {
    41                         Logging.log(log, "resolve", path, e);
    42                     }
    43                 });
    44             }
    45         });
    46     }
     33                if (e != null) {
     34                        return;
     35                }
     36                final String path = "/simulator/genepools/groups/0/genotypes";
     37                instance.invokeLater(new RunAt<Instance>() {
     38                        @Override
     39                        public void run() {
     40                                PortalEndpoint.this.instance.resolve(path, new Future<Path>() {
     41                                        @Override
     42                                        public void result(Path result, Exception e) {
     43                                                Logging.log(log, "resolve", path, e);
     44                                        }
     45                                });
     46                        }
     47                });
     48        }
    4749
    48     @Override
    49     public void onStop(Exception e) {
    50     }
     50        @Override
     51        public void onStop(Exception e) {
     52        }
    5153
    5254
    53     /*@Override
    54     public void onChange(final Path path) {
    55         //if path.getTop().getParam().
    56         observer.invokeLater(new Runnable() {
    57             @Override
    58             public void run() {
    59                 log.debug("change at " + path);
    60             }
    61         });
    62     }
    63     */
     55        /*@Override
     56        public void onChange(final Path path) {
     57                //if path.getTop().getParam().
     58                observer.invokeLater(new Runnable() {
     59                        @Override
     60                        public void run() {
     61                                log.debug("change at " + path);
     62                        }
     63                });
     64        }
     65        */
    6466
    6567
  • java/main/src/main/java/com/framsticks/remote/RecursiveFetcher.java

    r84 r85  
    1212import org.apache.log4j.Logger;
    1313import static com.framsticks.util.lang.Containers.filterInstanceof;
     14import com.framsticks.util.dispatching.RunAt;
    1415
    1516/**
     
    5152                                if (childPath.isResolved() && instance.getInfoFromCache(childPath) != null) {
    5253                                        ++dispatched;
    53                                         instance.invokeLater(new Runnable() {
     54                                        instance.invokeLater(new RunAt<Instance>() {
    5455                                                @Override
    5556                                                public void run() {
  • java/main/src/main/java/com/framsticks/remote/RemoteInstance.java

    r84 r85  
    1717import com.framsticks.util.lang.Casting;
    1818import com.framsticks.util.lang.Pair;
     19import com.framsticks.util.dispatching.RunAt;
    1920
    2021import org.apache.commons.configuration.Configuration;
     
    3334        protected ClientConnection connection;
    3435
    35         protected final Set<Pair<Path, Subscription>> subscriptions = new HashSet<Pair<Path, Subscription>>();
    36 
    37         public Pair<Path, Subscription> getSubscription(Path path) {
    38                 for (Pair<Path, Subscription> s : subscriptions) {
     36        protected final Set<Pair<Path, Subscription<?>>> subscriptions = new HashSet<>();
     37
     38        public Pair<Path, Subscription<?>> getSubscription(Path path) {
     39                for (Pair<Path, Subscription<?>> s : subscriptions) {
    3940                        if (s.first.matches(path)) {
    4041                                return s;
     
    6768                                                }
    6869
    69                                                 invokeLater(new Runnable() {
     70                                                invokeLater(new RunAt<Instance>() {
    7071                                                        @Override
    7172                                                        public void run() {
     
    8586                                                                                EventParam param = getParam(simulator, "running_changed", EventParam.class);
    8687                                                                                assert param != null;
    87                                                                                 connection.subscribe(simulator.getTextual() + "/" + param.getId(), new LoggingSubscriptionCallback(log, "server running state change", new EventCallback() {
     88                                                                                connection.subscribe(simulator.getTextual() + "/" + param.getId(), RemoteInstance.this, new LoggingSubscriptionCallback<Instance>(log, "server running state change", new EventCallback() {
    8889                                                                                        @Override
    8990                                                                                        public void call(List<File> files) {
    90                                                                                                 invokeLater(new Runnable() {
     91                                                                                                invokeLater(new RunAt<Instance>() {
    9192                                                                                                        @Override
    9293                                                                                                        public void run() {
     
    9697                                                                                        }
    9798                                                                                }));
    98                                                                                 new PeriodicTask(RemoteInstance.this, 1000) {
     99                                                                                new PeriodicTask<Instance>(RemoteInstance.this, 1000) {
    99100                                                                                        @Override
    100101                                                                                        public void run() {
     
    187188                assert param != null;
    188189                assert path.isResolved();
    189                 connection.send(new GetRequest().setField(param.getId()).setPath(path.getTextual()), this, new ResponseCallback() {
     190                connection.send(new GetRequest().field(param.getId()).path(path.getTextual()), this, new ResponseCallback<Instance>() {
    190191                        @Override
    191192                        public void process(Response response) {
     
    232233
    233234                //TODO: if the info is in the cache, then don't communicate
    234                 connection.send(new InfoRequest().setPath(path.getTextual()), this, new ResponseCallback() {
     235                connection.send(new InfoRequest().path(path.getTextual()), this, new ResponseCallback<Instance>() {
    235236                        @Override
    236237                        public void process(Response response) {
     
    268269
    269270                log.trace("fetching values for " + path);
    270                 connection.send(new GetRequest().setPath(path.getTextual()), this, new ResponseCallback() {
     271                connection.send(new GetRequest().path(path.getTextual()), this, new ResponseCallback<Instance>() {
    271272                        @Override
    272273                        public void process(Response response) {
     
    344345                }
    345346
    346                 final Pair<Path, Subscription> temporary = new Pair<Path, Subscription>(path, null);
     347                final Pair<Path, Subscription<?>> temporary = new Pair<>(path, null);
    347348                subscriptions.add(temporary);
    348349
    349                 connection.subscribe(path.getTextual() + "_changed", new SubscriptionCallback() {
    350                         @Override
    351                         public EventCallback subscribed(final Subscription subscription) {
     350                connection.subscribe(path.getTextual() + "_changed", this, new SubscriptionCallback<Instance>() {
     351                        @Override
     352                        public EventCallback subscribed(final Subscription<? super Instance> subscription) {
    352353                                if (subscription == null) {
    353354                                        log.error("failed to subscribe for change event for " + path);
     
    355356                                }
    356357                                log.debug("subscribed for change event for " + path);
    357                                 subscription.setDispatcher(RemoteInstance.this);
    358                                 RemoteInstance.this.invokeLater(new Runnable() {
     358                                // subscription.setDispatcher(RemoteInstance.this);
     359                                RemoteInstance.this.invokeLater(new RunAt<Instance>() {
    359360                                        @Override
    360361                                        public void run() {
    361362                                                subscriptions.remove(temporary);
    362                                                 subscriptions.add(new Pair<Path, Subscription>(path, subscription));
     363                                                subscriptions.add(new Pair<Path, Subscription<?>>(path, subscription));
    363364                                        }
    364365                                });
     
    459460
    460461                log.trace("storing value " + param + " for " + path);
    461                 connection.send(new SetRequest().value(value.toString()).setField(param.getId()).setPath(path.getTextual()), this, new StateCallback() {
     462                connection.send(new SetRequest().value(value.toString()).field(param.getId()).path(path.getTextual()), this, new StateCallback<Instance>() {
    462463                        @Override
    463464                        public void call(Exception e) {
  • java/main/src/main/java/com/framsticks/util/PeriodicTask.java

    r84 r85  
    33import com.framsticks.util.dispatching.Dispatcher;
    44import com.framsticks.util.dispatching.Task;
     5import com.framsticks.util.dispatching.RunAt;
    56
    67/**
    78 * @author Piotr Sniegowski
    89 */
    9 public abstract class PeriodicTask implements Runnable {
     10public abstract class PeriodicTask<C> extends RunAt<C> {
    1011
    11     protected final long period;
    12     protected Dispatcher dispatcher;
     12        protected final long period;
     13        protected Dispatcher<? super C> dispatcher;
    1314
    14     public PeriodicTask(Dispatcher dispatcher, long period) {
    15         this.period = period;
    16         this.dispatcher = dispatcher;
    17         dispatcher.invokeLater(this);
    18     }
     15        public PeriodicTask(Dispatcher<? super C> dispatcher, long period) {
     16                this.period = period;
     17                this.dispatcher = dispatcher;
     18                dispatcher.invokeLater(this);
     19        }
    1920
    2021
    21     public void again() {
    22         dispatcher.invokeLater(new Task(System.currentTimeMillis() + period) {
    23             @Override
    24             public void run() {
    25                 PeriodicTask.this.run();
    26             }
    27         });
    28     }
     22        public void again() {
     23                dispatcher.invokeLater(new Task<C>(System.currentTimeMillis() + period) {
     24                        @Override
     25                        public void run() {
     26                                PeriodicTask.this.run();
     27                        }
     28                });
     29        }
    2930
    3031}
  • java/main/src/main/java/com/framsticks/util/StateFunctor.java

    r77 r85  
    55 */
    66public interface StateFunctor {
     7        //TODO RunAt
    78        public void call(Exception e);
    89}
  • java/main/src/main/java/com/framsticks/util/dispatching/AtOnceDispatcher.java

    r84 r85  
    44 * @author Piotr Sniegowski
    55 */
    6 public class AtOnceDispatcher implements Dispatcher {
     6public class AtOnceDispatcher<C> implements Dispatcher<C> {
    77
    8     public static final AtOnceDispatcher instance = new AtOnceDispatcher();
     8        @SuppressWarnings("rawtypes")
     9        protected static final AtOnceDispatcher instance = new AtOnceDispatcher();
    910
    10     @Override
    11     public final boolean isActive() {
    12         return true;
    13     }
     11        @SuppressWarnings("unchecked")
     12        public static <C> Dispatcher<C> getInstance() {
     13                return (Dispatcher<C>) instance;
     14        }
    1415
    15     @Override
    16     public final void invokeLater(Runnable runnable) {
    17         runnable.run();
    18     }
     16        @Override
     17        public final boolean isActive() {
     18                return true;
     19        }
     20
     21        @Override
     22        public final void invokeLater(RunAt<? extends C> runnable) {
     23                runnable.run();
     24        }
    1925}
  • java/main/src/main/java/com/framsticks/util/dispatching/Dispatcher.java

    r84 r85  
    44 * @author Piotr Sniegowski
    55 */
    6 public interface Dispatcher {
    7     public boolean isActive();
    8     public void invokeLater(Runnable runnable);
     6public interface Dispatcher<C> {
     7        public boolean isActive();
     8        public void invokeLater(RunAt<? extends C> runnable);
    99}
  • java/main/src/main/java/com/framsticks/util/dispatching/Dispatching.java

    r84 r85  
    88public abstract class Dispatching {
    99
    10     public static boolean isThreadSafe() {
    11         return true;
    12     }
     10        public static boolean isThreadSafe() {
     11                return true;
     12        }
    1313
    14     public static void invokeLaterOrNow(Dispatcher dispatcher, Runnable runnable) {
    15         if (dispatcher.isActive()) {
    16             runnable.run();
    17             return;
    18         }
    19         dispatcher.invokeLater(runnable);
    20     }
     14        public static <C> void invokeLaterOrNow(Dispatcher<C> dispatcher, RunAt<? extends C> runnable) {
     15                if (dispatcher.isActive()) {
     16                        runnable.run();
     17                        return;
     18                }
     19                dispatcher.invokeLater(runnable);
     20        }
    2121
    22     public static void dispatchOk(Dispatcher dispatcher, final StateFunctor stateFunctor) {
    23         dispatcher.invokeLater(new Runnable() {
    24             @Override
    25             public void run() {
    26                 stateFunctor.call(null);
    27             }
    28         });
    29     }
     22        //TODO RunAt StateFunctor
     23        public static <C> void dispatchOk(Dispatcher<C> dispatcher, final StateFunctor stateFunctor) {
     24                dispatcher.invokeLater(new RunAt<C>() {
     25                        @Override
     26                        public void run() {
     27                                stateFunctor.call(null);
     28                        }
     29                });
     30        }
    3031
    31     public static boolean assertInvokeLater(Dispatcher dispatcher, Runnable runnable) {
    32         dispatcher.invokeLater(runnable);
    33         return true;
    34     }
     32        // public static boolean assertInvokeLater(Dispatcher dispatcher, RunAt runnable) {
     33        //      dispatcher.invokeLater(runnable);
     34        //      return true;
     35        // }
    3536
    36     public static void invokeDispatch(Dispatcher dispatcher, final Dispatcher finalDispatcher, final Runnable runnable) {
    37         dispatcher.invokeLater(new Runnable() {
    38             @Override
    39             public void run() {
    40                 finalDispatcher.invokeLater(runnable);
    41             }
    42         });
    43     }
     37        public static <P, C> void invokeDispatch(Dispatcher<P> dispatcher, final Dispatcher<C> finalDispatcher, final RunAt<C> runnable) {
     38                dispatcher.invokeLater(new RunAt<P>() {
     39                        @Override
     40                        public void run() {
     41                                finalDispatcher.invokeLater(runnable);
     42                        }
     43                });
     44        }
    4445
    4546}
  • java/main/src/main/java/com/framsticks/util/dispatching/Task.java

    r84 r85  
    44 * @author Piotr Sniegowski
    55 */
    6 public abstract class Task implements Runnable {
     6public abstract class Task<C> extends RunAt<C> {
    77
    8     protected final long moment;
     8        protected final long moment;
    99
    10     public Task() {
    11         moment = System.currentTimeMillis();
    12     }
     10        public Task() {
     11                moment = System.currentTimeMillis();
     12        }
    1313
    14     public Task(long moment) {
    15         this.moment = moment;
    16     }
     14        public Task(long moment) {
     15                this.moment = moment;
     16        }
    1717
    18     public final long getMoment() {
    19         return moment;
    20     }
     18        public final long getMoment() {
     19                return moment;
     20        }
    2121
    2222}
  • java/main/src/main/java/com/framsticks/util/dispatching/Thread.java

    r84 r85  
    55import java.util.LinkedList;
    66import java.util.ListIterator;
     7import com.framsticks.util.dispatching.RunAt;
    78
    89/**
    910 * @author Piotr Sniegowski
    1011 */
    11 public class Thread implements Dispatcher {
     12public class Thread<C> implements Dispatcher<C> {
    1213
    1314        private static final Logger log = Logger.getLogger(Thread.class.getName());
     
    1516        protected final java.lang.Thread thread;
    1617
    17         private final LinkedList<Task> queue = new LinkedList<Task>();
     18        private final LinkedList<Task<? extends C>> queue = new LinkedList<>();
    1819
    1920        public Thread() {
    20                 thread = new java.lang.Thread(new Runnable() {
     21                thread = new java.lang.Thread(new java.lang.Runnable() {
    2122                        @Override
    2223                        public void run() {
     
    2526                });
    2627        }
     28
    2729        public Thread(String s) {
    2830                this();
    2931                thread.setName(s);
    30                 thread.start();
     32                // thread.start();
    3133        }
    3234
     
    3436                this.thread = thread;
    3537                thread.setName(s);
     38        }
     39
     40        public Thread<C> start() {
     41                thread.start();
     42                return this;
    3643        }
    3744
     
    4350        protected void routine() {
    4451                while (!java.lang.Thread.interrupted()) {
    45                         Task task;
     52                        Task<? extends C> task;
    4653                        synchronized (queue) {
    4754                                if (queue.isEmpty()) {
     
    7481        }
    7582
    76         protected void enqueueTask(Task task) {
     83        protected void enqueueTask(Task<? extends C> task) {
    7784                synchronized (queue) {
    78                         ListIterator<Task> i = queue.listIterator();
     85                        ListIterator<Task<? extends C>> i = queue.listIterator();
    7986                        while (i.hasNext()) {
    80                                 Task t = i.next();
     87                                Task<? extends C> t = i.next();
    8188                                if (t.getMoment() > task.getMoment()) {
    8289                                        i.previous();
     
    104111
    105112        @Override
    106         public void invokeLater(final Runnable runnable) {
     113        public void invokeLater(final RunAt<? extends C> runnable) {
    107114                if (!(runnable instanceof Task)) {
    108                         enqueueTask(new Task() {
     115                        enqueueTask(new Task<C>() {
    109116                                @Override
    110117                                public void run() {
     
    114121                        return;
    115122                }
    116                 enqueueTask((Task)runnable);
     123                enqueueTask((Task<? extends C>) runnable);
    117124        }
    118125
     
    125132        }
    126133
    127         public void start() {
    128                 thread.start();
    129         }
    130 
    131134        public void setName(String name) {
    132135                thread.setName(name);
    133136
    134137        }
     138
     139        public static boolean interrupted() {
     140                return java.lang.Thread.interrupted();
     141        }
    135142}
  • java/main/src/main/java/com/framsticks/visualization/Viewer.java

    r84 r85  
    11package com.framsticks.visualization;
    22
     3import com.framsticks.util.io.Encoding;
    34import com.sun.j3d.loaders.IncorrectFormatException;
    45import com.sun.j3d.loaders.ParsingErrorException;
     
    1819import java.io.*;
    1920
    20 // import org.apache.log4j.Logger;
     21import org.apache.log4j.Logger;
    2122
    2223public class Viewer {
    2324
    24     // private static Logger log = Logger.getLogger(Viewer.class);
     25        private static Logger log = Logger.getLogger(Viewer.class);
    2526
    26     Canvas3D canvas3d;
    27     SimpleUniverse universe;
     27        Canvas3D canvas3d;
     28        SimpleUniverse universe;
    2829
    29     public Viewer() {
    30         super();
     30        public Viewer() {
     31                super();
    3132
    32         init();
    33     }
     33                init();
     34        }
    3435
    3536        public BranchGroup createSceneGraph() {
    36         // Create the root of the branch graph
    37         BranchGroup objRoot = new BranchGroup();
     37                // Create the root of the branch graph
     38                BranchGroup objRoot = new BranchGroup();
    3839
    39         // Create a Transform group to scale all objects so they
    40         // appear in the scene.
    41         TransformGroup objScale = new TransformGroup();
    42         Transform3D t3d = new Transform3D();
    43         t3d.setScale(0.7);
    44         objScale.setTransform(t3d);
    45         objRoot.addChild(objScale);
     40                // Create a Transform group to scale all objects so they
     41                // appear in the scene.
     42                TransformGroup objScale = new TransformGroup();
     43                Transform3D t3d = new Transform3D();
     44                t3d.setScale(0.7);
     45                objScale.setTransform(t3d);
     46                objRoot.addChild(objScale);
    4647
    47         TransformGroup objTrans = new TransformGroup();
    48         objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
    49         objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
    50         objScale.addChild(objTrans);
     48                TransformGroup objTrans = new TransformGroup();
     49                objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
     50                objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
     51                objScale.addChild(objTrans);
    5152
    52         String filename = "/visualization/models/cylinder.obj";
    53         int flags = ObjectFile.RESIZE;
    54         flags |= ObjectFile.TRIANGULATE;
    55         flags |= ObjectFile.STRIPIFY;
     53                String filename = "/visualization/models/cylinder.obj";
     54                int flags = ObjectFile.RESIZE;
     55                flags |= ObjectFile.TRIANGULATE;
     56                flags |= ObjectFile.STRIPIFY;
    5657                double creaseAngle = 60.0;
    5758                ObjectFile f = new ObjectFile(flags,
    58                 (float) (creaseAngle * Math.PI / 180.0));
    59         Scene s = null;
    60         try {
     59                                (float) (creaseAngle * Math.PI / 180.0));
     60                Scene s = null;
     61                try {
    6162                        InputStream is = this.getClass().getResourceAsStream(filename);
    62             s = f.load(new InputStreamReader(is));
    63         } catch (FileNotFoundException e) {
    64             System.err.println(e);
    65             System.exit(1);
    66         } catch (ParsingErrorException e) {
    67             System.err.println(e);
    68             System.exit(1);
    69         } catch (IncorrectFormatException e) {
    70             System.err.println(e);
    71             System.exit(1);
    72         }
     63                        s = f.load(new InputStreamReader(is, Encoding.getDefaultCharset()));
     64                } catch (FileNotFoundException | ParsingErrorException | IncorrectFormatException e) {
     65                        log.fatal("fatal error", e);
     66                        return null;
     67                }
    7368
    74         objTrans.addChild(s.getSceneGroup());
     69                objTrans.addChild(s.getSceneGroup());
    7570
    76         BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
     71                BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    7772
    78         Color3f bgColor = new Color3f(0.05f, 0.05f, 0.5f);
    79         Background bgNode = new Background(bgColor);
    80         bgNode.setApplicationBounds(bounds);
    81         objRoot.addChild(bgNode);
     73                Color3f bgColor = new Color3f(0.05f, 0.05f, 0.5f);
     74                Background bgNode = new Background(bgColor);
     75                bgNode.setApplicationBounds(bounds);
     76                objRoot.addChild(bgNode);
    8277
    83         return objRoot;
    84     }
     78                return objRoot;
     79        }
    8580
    86     private void init() {
     81        private void init() {
    8782
    88             JTextPane textPane = new JTextPane();
    89         textPane.setEditable(false);
     83                JTextPane textPane = new JTextPane();
     84                textPane.setEditable(false);
    9085
    91         GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
     86                GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
    9287
    93         // Create a Canvas3D using the preferred configuration
    94         canvas3d = new Canvas3D(config);
     88                // Create a Canvas3D using the preferred configuration
     89                canvas3d = new Canvas3D(config);
    9590
    96         // Create simple universe with view branch
    97         universe = new SimpleUniverse(canvas3d);
    98         BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
     91                // Create simple universe with view branch
     92                universe = new SimpleUniverse(canvas3d);
     93                BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    9994
    100         // add mouse behaviours to the ViewingPlatform
    101         ViewingPlatform viewingPlatform = universe.getViewingPlatform();
     95                // add mouse behaviours to the ViewingPlatform
     96                ViewingPlatform viewingPlatform = universe.getViewingPlatform();
    10297
    103         PlatformGeometry platformGeometry = new PlatformGeometry();
     98                PlatformGeometry platformGeometry = new PlatformGeometry();
    10499
    105         // Set up the ambient light
    106         Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f);
    107         AmbientLight ambientLightNode = new AmbientLight(ambientColor);
    108         ambientLightNode.setInfluencingBounds(bounds);
    109         platformGeometry.addChild(ambientLightNode);
     100                // Set up the ambient light
     101                Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f);
     102                AmbientLight ambientLightNode = new AmbientLight(ambientColor);
     103                ambientLightNode.setInfluencingBounds(bounds);
     104                platformGeometry.addChild(ambientLightNode);
    110105
    111         // Set up the directional lights
    112         Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f);
    113         Vector3f light1Direction = new Vector3f(1.0f, 1.0f, 1.0f);
    114         Color3f light2Color = new Color3f(1.0f, 1.0f, 1.0f);
    115         Vector3f light2Direction = new Vector3f(-1.0f, -1.0f, -1.0f);
     106                // Set up the directional lights
     107                Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f);
     108                Vector3f light1Direction = new Vector3f(1.0f, 1.0f, 1.0f);
     109                Color3f light2Color = new Color3f(1.0f, 1.0f, 1.0f);
     110                Vector3f light2Direction = new Vector3f(-1.0f, -1.0f, -1.0f);
    116111
    117         DirectionalLight light1 = new DirectionalLight(light1Color,
    118                 light1Direction);
    119         light1.setInfluencingBounds(bounds);
    120         platformGeometry.addChild(light1);
     112                DirectionalLight light1 = new DirectionalLight(light1Color,
     113                                light1Direction);
     114                light1.setInfluencingBounds(bounds);
     115                platformGeometry.addChild(light1);
    121116
    122         DirectionalLight light2 = new DirectionalLight(light2Color,
    123                 light2Direction);
    124         light2.setInfluencingBounds(bounds);
    125         platformGeometry.addChild(light2);
     117                DirectionalLight light2 = new DirectionalLight(light2Color,
     118                                light2Direction);
     119                light2.setInfluencingBounds(bounds);
     120                platformGeometry.addChild(light2);
    126121
    127         viewingPlatform.setPlatformGeometry(platformGeometry);
     122                viewingPlatform.setPlatformGeometry(platformGeometry);
    128123
    129         viewingPlatform.setNominalViewingTransform();
     124                viewingPlatform.setNominalViewingTransform();
    130125
    131         // Ensure at least 5 msec per frame (i.e., < 200Hz)
    132         universe.getViewer().getView().setMinimumFrameCycleTime(5);
     126                // Ensure at least 5 msec per frame (i.e., < 200Hz)
     127                universe.getViewer().getView().setMinimumFrameCycleTime(5);
    133128
    134         BranchGroup scene = new BranchGroup();
    135         BranchGroup content = createSceneGraph();
     129                BranchGroup scene = new BranchGroup();
     130                BranchGroup content = createSceneGraph();
    136131
    137         // canvas3d.addMouseListener(behaviour);
    138         TransformGroup transformGroup = new TransformGroup(new Transform3D());
    139         transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
    140         transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
    141         MouseRotate behaviour = new MouseRotate();
    142         behaviour.setTransformGroup(transformGroup);
    143         transformGroup.addChild(behaviour);
    144         // behaviour.addListener(canvas3d);
    145         // behaviour.initialize();
    146         behaviour.setSchedulingBounds(new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0));
    147         transformGroup.addChild(content);
    148         // transformGroup.addChild(behaviour);
    149         scene.addChild(transformGroup);
     132                // canvas3d.addMouseListener(behaviour);
     133                TransformGroup transformGroup = new TransformGroup(new Transform3D());
     134                transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
     135                transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
     136                MouseRotate behaviour = new MouseRotate();
     137                behaviour.setTransformGroup(transformGroup);
     138                transformGroup.addChild(behaviour);
     139                // behaviour.addListener(canvas3d);
     140                // behaviour.initialize();
     141                behaviour.setSchedulingBounds(new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0));
     142                transformGroup.addChild(content);
     143                // transformGroup.addChild(behaviour);
     144                scene.addChild(transformGroup);
    150145
    151         universe.addBranchGraph(scene);
     146                universe.addBranchGraph(scene);
    152147                canvas3d.startRenderer();
    153148                Dimension d = new Dimension(500, 500);
    154149                canvas3d.setMinimumSize(d);
    155150                canvas3d.setSize(d);
    156     }
     151        }
    157152
    158     public Component getViewComponent() {
    159         return canvas3d;
    160     }
     153        public Component getViewComponent() {
     154                return canvas3d;
     155        }
    161156
    162157
Note: See TracChangeset for help on using the changeset viewer.