Changeset 85
- Timestamp:
- 06/24/13 13:38:40 (12 years ago)
- Location:
- java/main
- Files:
-
- 4 added
- 63 edited
Legend:
- Unmodified
- Added
- Removed
-
java/main/pom.xml
r84 r85 19 19 </properties> 20 20 <dependencies> 21 <dependency> 22 <groupId>com.google.code.findbugs</groupId> 23 <artifactId>jsr305</artifactId> 24 <version>2.0.1</version> 25 </dependency> 21 26 <dependency> 22 27 <groupId>log4j</groupId> … … 52 57 <version>1.5.2</version> 53 58 </dependency> 54 55 59 <dependency> 56 60 <groupId>org.testng</groupId> … … 89 93 <version>3.0</version> 90 94 <configuration> 91 <source>1. 6</source>92 <target>1. 6</target>95 <source>1.7</source> 96 <target>1.7</target> 93 97 </configuration> 94 98 </plugin> … … 122 126 </plugins> 123 127 </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> 124 147 125 148 </project> -
java/main/src/main/java/com/framsticks/communication/ClientConnection.java
r84 r85 21 21 import java.util.regex.Matcher; 22 22 import java.util.regex.Pattern; 23 import com.framsticks.util.dispatching.RunAt; 23 24 24 25 /** … … 29 30 private final static Logger log = Logger.getLogger(ClientConnection.class); 30 31 31 protected final Map<String, Subscription > subscriptions = new HashMap<String, Subscription>();32 protected final Map<String, Subscription<?>> subscriptions = new HashMap<>(); 32 33 33 34 public String getAddress() { … … 93 94 94 95 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) { 98 99 this.subscription = subscription; 99 100 } … … 107 108 public void eof() { 108 109 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 { 119 116 Request request; 120 ResponseCallback callback;121 Dispatcher dispatcher;117 ResponseCallback<? extends C> callback; 118 Dispatcher<C> dispatcher; 122 119 123 120 public void startFile(String path) { … … 139 136 return request.toString(); 140 137 } 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<>(); 143 149 144 150 … … 163 169 } 164 170 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) { 172 180 173 181 if (!isConnected()) { … … 175 183 return; 176 184 } 177 final SentQuery sentQuery = new SentQuery();185 final SentQuery<C> sentQuery = new SentQuery<C>(); 178 186 sentQuery.request = request; 179 187 sentQuery.callback = callback; 180 188 sentQuery.dispatcher = dispatcher; 181 189 182 senderThread.invokeLater(new Run nable(){190 senderThread.invokeLater(new RunAt<Connection>(){ 183 191 @Override 184 192 public void run() { 193 Integer id; 185 194 synchronized (ClientConnection.this) { 186 195 … … 192 201 } 193 202 } 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 } 196 211 String command = sentQuery.request.getCommand(); 197 212 StringBuilder message = new StringBuilder(); … … 223 238 } 224 239 225 public void subscribe(final String path, final SubscriptionCallbackcallback) {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>() { 227 242 @Override 228 243 public void process(Response response) { … … 233 248 } 234 249 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); 236 251 log.debug("registered on event: " + subscription); 237 252 synchronized (subscriptions) { … … 241 256 if (subscription.getEventCallback() == null) { 242 257 log.info("subscription for " + path + " aborted"); 243 subscription.unsubscribe(new LoggingStateCallback (log, "abort subscription"));258 subscription.unsubscribe(new LoggingStateCallback<C>(log, "abort subscription")); 244 259 } 245 260 } … … 253 268 254 269 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>() { 256 271 @Override 257 272 public void call(Exception e) { … … 266 281 return; 267 282 } 268 send(new UseRequest().feature("request_id"), new StateCallback () {283 send(new UseRequest().feature("request_id"), new StateCallback<Connection>() { 269 284 @Override 270 285 public void call(Exception e) { … … 289 304 290 305 291 private synchronized SentQuery fetchQuery(Integer id, boolean remove) {306 private synchronized SentQuery<?> fetchQuery(Integer id, boolean remove) { 292 307 if (id == null) { 293 308 if (requestIdEnabled) { 294 309 return null; 295 310 } 296 SentQuery result = currentlySentQuery;311 SentQuery<?> result = currentlySentQuery; 297 312 if (remove) { 298 313 currentlySentQuery = null; … … 302 317 } 303 318 if (queryMap.containsKey(id)) { 304 SentQuery result = queryMap.get(id);319 SentQuery<?> result = queryMap.get(id); 305 320 if (remove) { 306 321 queryMap.remove(id); … … 312 327 313 328 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 }323 329 324 330 protected void processMessage(InboundMessage inboundMessage) throws Exception { … … 342 348 return; 343 349 } 344 Subscription subscription = subscriptions.get(matcher.group(1));350 Subscription<?> subscription = subscriptions.get(matcher.group(1)); 345 351 if (subscription == null) { 346 352 log.error("non subscribed event: " + matcher.group(1)); … … 362 368 363 369 if (command.first.equals("file")) { 364 SentQuery sentQuery = fetchQuery(rest.first, false);370 SentQuery<?> sentQuery = fetchQuery(rest.first, false); 365 371 sentQuery.startFile(rest.second); 366 372 processMessage(sentQuery); … … 368 374 } 369 375 370 SentQuery sentQuery = fetchQuery(rest.first, true);376 SentQuery<?> sentQuery = fetchQuery(rest.first, true); 371 377 if (sentQuery == null) { 372 378 return; … … 374 380 log.debug("parsing response for request " + sentQuery); 375 381 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())); 385 383 } 386 384 -
java/main/src/main/java/com/framsticks/communication/Connection.java
r84 r85 1 1 package com.framsticks.communication; 2 2 3 import com.framsticks.util.io.Encoding; 3 4 import com.framsticks.util.lang.Pair; 4 5 import org.apache.log4j.Logger; … … 6 7 import java.io.IOException; 7 8 import java.io.InputStreamReader; 9 import java.io.OutputStreamWriter; 8 10 import java.io.PrintWriter; 9 import java.lang.Thread;10 11 import java.net.Socket; 11 12 import java.net.SocketTimeoutException; 12 13 import java.util.regex.Matcher; 13 14 import java.util.regex.Pattern; 15 16 import com.framsticks.util.dispatching.RunAt; 17 import com.framsticks.util.dispatching.Thread; 14 18 15 19 public abstract class Connection { … … 28 32 protected int protocolVersion = -1; 29 33 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<>(); 32 36 33 37 public boolean isConnected() { … … 42 46 senderThread.interrupt(); 43 47 senderThread.join(); 44 if (receiverThread != null) { 45 receiverThread.interrupt(); 46 receiverThread.join(); 47 receiverThread = null; 48 } 48 49 receiverThread.interrupt(); 50 receiverThread.join(); 49 51 50 52 if (output != null) { … … 72 74 73 75 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"); 77 79 78 80 … … 126 128 protected void runThreads() { 127 129 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())); 130 132 } catch (IOException e) { 131 133 log.error("buffer creation failure"); … … 135 137 136 138 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>() { 138 145 @Override 139 146 public void run() { … … 148 155 } 149 156 }); 150 receiverThread.setName(this + "-receiver");151 157 152 senderThread.start();153 receiverThread.start();154 158 } 155 159 -
java/main/src/main/java/com/framsticks/communication/RequestHandler.java
r77 r85 7 7 */ 8 8 public interface RequestHandler { 9 public void handle(ApplicationRequest request, ResponseCallbackresponseCallback);9 public void handle(ApplicationRequest request, ResponseCallback<?> responseCallback); 10 10 } -
java/main/src/main/java/com/framsticks/communication/ResponseCallback.java
r84 r85 4 4 * @author Piotr Sniegowski 5 5 */ 6 public interface ResponseCallback {6 public interface ResponseCallback<C> { 7 7 public void process(Response response); 8 8 } -
java/main/src/main/java/com/framsticks/communication/ServerConnection.java
r84 r85 8 8 9 9 import java.net.Socket; 10 import com.framsticks.util.dispatching.RunAt; 10 11 11 12 /** … … 26 27 27 28 public void start() { 28 29 30 29 runThreads(); 31 30 } … … 43 42 } 44 43 45 protected void handleRequest(Request request, ResponseCallback responseCallback) {44 protected void handleRequest(Request request, ResponseCallback<?> responseCallback) { 46 45 if (request instanceof ApplicationRequest) { 47 requestHandler.handle((ApplicationRequest) request, responseCallback);46 requestHandler.handle((ApplicationRequest) request, responseCallback); 48 47 return; 49 48 } … … 70 69 71 70 protected final void respond(final Response response, final Integer id) { 72 senderThread.invokeLater(new Run nable() {71 senderThread.invokeLater(new RunAt<Connection>() { 73 72 @Override 74 73 public void run() { … … 118 117 } 119 118 120 handleRequest(request, new ResponseCallback () {119 handleRequest(request, new ResponseCallback<ServerConnection>() { 121 120 @Override 122 121 public void process(Response response) { -
java/main/src/main/java/com/framsticks/communication/StateCallback.java
r77 r85 6 6 * @author Piotr Sniegowski 7 7 */ 8 public abstract class StateCallback implements ResponseCallback, StateFunctor {8 public abstract class StateCallback<C> implements ResponseCallback<C>, StateFunctor { 9 9 @Override 10 10 public void process(Response response) { -
java/main/src/main/java/com/framsticks/communication/Subscription.java
r84 r85 1 1 package com.framsticks.communication; 2 2 3 import java.util.List; 4 3 5 import com.framsticks.communication.queries.RegistrationRequest; 4 import com.framsticks.util.dispatching.AtOnceDispatcher;5 6 import com.framsticks.util.dispatching.Dispatcher; 7 import com.framsticks.util.dispatching.Dispatching; 8 import com.framsticks.util.dispatching.RunAt; 6 9 import com.framsticks.util.StateFunctor; 7 10 import org.apache.log4j.Logger; … … 11 14 * @author Piotr Sniegowski 12 15 */ 13 public class Subscription {16 public class Subscription<C> { 14 17 15 18 private final static Logger log = Logger.getLogger(Subscription.class); 16 19 17 18 20 private final ClientConnection connection; 21 private final String path; 19 22 private final String registeredPath; 20 private Dispatcher dispatcher = AtOnceDispatcher.instance;23 private final Dispatcher<C> dispatcher; 21 24 22 25 private EventCallback eventCallback; 23 26 24 public Subscription(ClientConnection connection, String path, String registeredPath ) {27 public Subscription(ClientConnection connection, String path, String registeredPath, Dispatcher<C> dispatcher) { 25 28 this.connection = connection; 26 29 this.path = path; 27 30 this.registeredPath = registeredPath; 31 this.dispatcher = dispatcher; 28 32 } 29 33 … … 41 45 } 42 46 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 } 46 63 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 } 63 67 64 public EventCallback getEventCallback() {65 return eventCallback;66 68 public Dispatcher<C> getDispatcher() { 69 return dispatcher; 70 } 67 71 68 public Dispatcher getDispatcher() {69 return dispatcher;70 72 public void setEventCallback(EventCallback eventCallback) { 73 this.eventCallback = eventCallback; 74 } 71 75 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 } 75 84 } -
java/main/src/main/java/com/framsticks/communication/SubscriptionCallback.java
r77 r85 4 4 * @author Piotr Sniegowski 5 5 */ 6 public interface SubscriptionCallback {7 EventCallback subscribed(Subscription subscription);6 public interface SubscriptionCallback<C> { 7 EventCallback subscribed(Subscription<? super C> subscription); 8 8 } -
java/main/src/main/java/com/framsticks/communication/queries/ApplicationRequest.java
r84 r85 14 14 protected String fields; 15 15 16 public ApplicationRequest setPath(String path) {16 public ApplicationRequest path(String path) { 17 17 assert path != null; 18 18 this.path = path; … … 20 20 } 21 21 22 public ApplicationRequest setField(String field) {22 public ApplicationRequest field(String field) { 23 23 this.fields = field; 24 24 return this; 25 25 } 26 26 27 public ApplicationRequest setFields(Collection<String> fields) {27 public ApplicationRequest fields(Collection<String> fields) { 28 28 Delimeted d = new Delimeted(",", ""); 29 29 for (String f : fields) { 30 30 d.append(f); 31 31 } 32 return setField(d.build());32 return field(d.build()); 33 33 } 34 34 -
java/main/src/main/java/com/framsticks/communication/util/LoggingStateCallback.java
r84 r85 7 7 * @author Piotr Sniegowski 8 8 */ 9 public class LoggingStateCallback extends StateCallback{9 public class LoggingStateCallback<C> extends StateCallback<C> { 10 10 11 11 protected final Logger logger; … … 23 23 return; 24 24 } 25 25 logger.debug(message); 26 26 } 27 27 } -
java/main/src/main/java/com/framsticks/communication/util/LoggingSubscriptionCallback.java
r77 r85 9 9 * @author Piotr Sniegowski 10 10 */ 11 public class LoggingSubscriptionCallback implements SubscriptionCallback{11 public class LoggingSubscriptionCallback<C> implements SubscriptionCallback<C> { 12 12 13 14 15 13 protected final Logger logger; 14 protected final String message; 15 private final EventCallback eventCallback; 16 16 17 18 19 20 21 17 public LoggingSubscriptionCallback(Logger logger, String message, EventCallback eventCallback) { 18 this.logger = logger; 19 this.message = message; 20 this.eventCallback = eventCallback; 21 } 22 22 23 24 public EventCallback subscribed(Subscriptionsubscription) {25 26 27 28 29 30 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 } 32 32 } -
java/main/src/main/java/com/framsticks/core/Entity.java
r84 r85 1 1 package com.framsticks.core; 2 3 import javax.annotation.OverridingMethodsMustInvokeSuper; 2 4 3 5 import com.framsticks.params.FramsClass; … … 7 9 import org.apache.commons.configuration.Configuration; 8 10 import org.apache.log4j.Logger; 11 import com.framsticks.util.dispatching.RunAt; 9 12 10 13 /** 11 14 * @author Piotr Sniegowski 12 15 */ 13 public abstract class Entity implements Dispatcher {16 public abstract class Entity implements Dispatcher<Entity> { 14 17 15 18 private final static Logger log = Logger.getLogger(Entity.class.getName()); … … 17 20 protected String name = "entity"; 18 21 protected EntityOwner owner; 19 protected Dispatcher dispatcher;22 protected Dispatcher<Entity> dispatcher; 20 23 21 24 public Entity() { … … 32 35 this.name = name; 33 36 if (dispatcher instanceof Thread) { 34 ((Thread ) dispatcher).setName(name);37 ((Thread<Entity>) dispatcher).setName(name); 35 38 } 36 39 } … … 56 59 57 60 @Override 58 public final void invokeLater(Run nablerunnable) {61 public final void invokeLater(RunAt<? extends Entity> runnable) { 59 62 assert dispatcher != null; 60 63 dispatcher.invokeLater(runnable); 61 64 } 62 65 63 public Dispatcher createDefaultDispatcher() {64 return new Thread (name);66 public Dispatcher<Entity> createDefaultDispatcher() { 67 return new Thread<Entity>(name).start(); 65 68 } 66 69 70 @OverridingMethodsMustInvokeSuper 67 71 protected void run() { 68 72 assert isActive(); … … 74 78 } 75 79 76 public Dispatcher getDispatcher() {80 public Dispatcher<Entity> getDispatcher() { 77 81 return dispatcher; 78 82 } … … 81 85 * @param dispatcher the dispatcher to set 82 86 */ 83 public void setDispatcher(Dispatcher dispatcher) {87 public void setDispatcher(Dispatcher<Entity> dispatcher) { 84 88 this.dispatcher = dispatcher; 85 89 } … … 90 94 setDispatcher(createDefaultDispatcher()); 91 95 } 92 invokeLater(new Run nable() {96 invokeLater(new RunAt<Entity>() { 93 97 @Override 94 98 public void run() { -
java/main/src/main/java/com/framsticks/core/Instance.java
r84 r85 12 12 import com.framsticks.util.lang.Casting; 13 13 import org.apache.log4j.Logger; 14 import com.framsticks.util.dispatching.RunAt; 14 15 15 16 import java.util.*; … … 33 34 protected void run() { 34 35 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); 36 37 com.framsticks.model.Package.register(registry); 37 38 } … … 71 72 public void storeValue(Path path, Param param, Object value, final StateFunctor stateFunctor) { 72 73 assert isActive(); 73 invokeLater(new Run nable() {74 invokeLater(new RunAt<Instance>() { 74 75 @Override 75 76 public void run() { … … 93 94 public void addListener(final InstanceListener listener) { 94 95 assert Dispatching.isThreadSafe(); 95 Dispatching.invokeLaterOrNow(this, new Run nable() {96 Dispatching.invokeLaterOrNow(this, new RunAt<Instance>() { 96 97 @Override 97 98 public void run() { … … 103 104 public void removeListener(final InstanceListener listener) { 104 105 assert Dispatching.isThreadSafe(); 105 Dispatching.invokeLaterOrNow(this, new Run nable() {106 Dispatching.invokeLaterOrNow(this, new RunAt<Instance>() { 106 107 @Override 107 108 public void run() { … … 271 272 if ("/".equals(file.getPath())) { 272 273 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()); 274 275 } 275 276 } … … 310 311 311 312 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(); 313 314 Object child = accessInterface.getSelected(); 314 315 accessInterface.select(null); -
java/main/src/main/java/com/framsticks/core/ListChange.java
r84 r85 2 2 3 3 import com.framsticks.params.FramsClass; 4 import com.framsticks.params.Param Builder;4 import com.framsticks.params.Param; 5 5 import com.framsticks.params.types.DecimalParam; 6 6 import com.framsticks.params.types.EnumParam; … … 55 55 public static FramsClass getFramsClass() { 56 56 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)); 60 60 } 61 61 -
java/main/src/main/java/com/framsticks/core/LocalInstance.java
r84 r85 13 13 import java.util.HashSet; 14 14 import java.util.Set; 15 import com.framsticks.util.dispatching.RunAt; 15 16 16 17 … … 33 34 acceptSocket = new ServerSocket(); 34 35 acceptSocket.setReuseAddress(true); 35 acceptThread = new Thread (name + "-accept");36 acceptThread = new Thread<Accept>(name + "-accept").start(); 36 37 tryBind(accept); 37 38 } catch (IOException e) { … … 43 44 protected final Set<InstanceClient> clients = new HashSet<InstanceClient>(); 44 45 ServerSocket acceptSocket; 45 Thread acceptThread; 46 47 public static class Accept { 48 }; 49 50 Thread<Accept> acceptThread; 46 51 47 52 protected void acceptNext() { 48 acceptThread.invokeLater(new Run nable() {53 acceptThread.invokeLater(new RunAt<Accept>() { 49 54 @Override 50 55 public void run() { … … 53 58 assert socket != null; 54 59 log.debug("accepted socket: " + socket.getInetAddress().getHostAddress()); 55 invokeLater(new Run nable() {60 invokeLater(new RunAt<LocalInstance>() { 56 61 @Override 57 62 public void run() { … … 70 75 71 76 public void tryBind(final Integer accept) { 72 acceptThread.invokeLater(new Run nable() {77 acceptThread.invokeLater(new RunAt<Accept>() { 73 78 @Override 74 79 public void run() { -
java/main/src/main/java/com/framsticks/core/Path.java
r84 r85 5 5 import com.framsticks.params.Param; 6 6 import com.framsticks.util.dispatching.Dispatching; 7 7 8 import java.util.Iterator; 8 9 import java.util.LinkedList; 9 10 import java.util.List; 10 11 12 import javax.annotation.concurrent.Immutable; 13 import javax.annotation.Nonnull; 14 11 15 import org.apache.commons.collections.ListUtils; 12 16 … … 14 18 * @author Piotr Sniegowski 15 19 */ 20 @Immutable 16 21 public class Path { 17 22 // private final static Logger log = Logger.getLogger(Path.class.getName()); … … 63 68 } 64 69 65 public Path( Instance instance, List<Node> nodes, Node node) {70 public Path(@Nonnull Instance instance, List<Node> nodes, Node node) { 66 71 this.instance = instance; 67 72 StringBuilder b = new StringBuilder(); … … 196 201 } 197 202 203 public void setInstance(Instance instance) { 204 this.instance = instance; 205 } 206 198 207 @SuppressWarnings("unchecked") 199 208 public -
java/main/src/main/java/com/framsticks/core/Program.java
r84 r85 10 10 import java.lang.reflect.Constructor; 11 11 import java.util.*; 12 import com.framsticks.util.dispatching.RunAt; 12 13 13 14 /** 14 15 * @author Piotr Sniegowski 15 16 */ 16 public class Program extends com.framsticks.util.dispatching.Thread {17 public class Program extends com.framsticks.util.dispatching.Thread<Program> { 17 18 18 19 private final static Logger log = Logger.getLogger(Program.class.getName()); … … 101 102 102 103 final Program program = new Program("program"); 103 program.invokeLater(new Run nable() {104 program.invokeLater(new RunAt<Program>() { 104 105 @Override 105 106 public void run() { -
java/main/src/main/java/com/framsticks/diagnostics/DiagnosticsEndpoint.java
r84 r85 1 1 package com.framsticks.diagnostics; 2 2 3 import com.framsticks.core.Instance; 3 4 import com.framsticks.dumping.PrintWriterSink; 4 5 import com.framsticks.dumping.SaveStream; … … 8 9 import com.framsticks.util.PeriodicTask; 9 10 import com.framsticks.util.StateFunctor; 11 import com.framsticks.util.io.Encoding; 12 10 13 import org.apache.log4j.Logger; 11 14 12 15 import java.io.File; 16 import java.io.FileOutputStream; 13 17 import java.io.IOException; 18 import java.io.OutputStreamWriter; 14 19 import java.io.PrintWriter; 15 20 import java.text.SimpleDateFormat; … … 22 27 23 28 private final static Logger log = Logger.getLogger(DiagnosticsEndpoint.class.getName()); 24 25 29 26 30 public DiagnosticsEndpoint() { … … 39 43 40 44 if (getObserver().dumpsInterval != null) { 41 new PeriodicTask (instance, getObserver().dumpsInterval * 1000) {45 new PeriodicTask<Instance>(instance, getObserver().dumpsInterval * 1000) { 42 46 @Override 43 47 public void run() { … … 55 59 final String fileName = getObserver().dumpsPath + "/" + instance + "_" + new SimpleDateFormat(getObserver().dumpsFormat).format(new Date()) + ".param"; 56 60 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() { 58 62 @Override 59 63 public void call(Exception e) { -
java/main/src/main/java/com/framsticks/dumping/FileInstance.java
r84 r85 5 5 import com.framsticks.core.Instance; 6 6 import com.framsticks.util.dispatching.Future; 7 import com.framsticks.util.io.Encoding; 7 8 8 9 import org.apache.commons.configuration.Configuration; … … 11 12 import java.io.BufferedReader; 12 13 import java.io.File; 13 import java.io.File Reader;14 import java.io.FileInputStream; 14 15 import java.io.IOException; 16 import java.io.InputStreamReader; 15 17 16 18 /** … … 36 38 super.run(); 37 39 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>() { 40 41 @Override 41 42 public void result(Path result, Exception e) { -
java/main/src/main/java/com/framsticks/dumping/SaveStream.java
r84 r85 13 13 import com.framsticks.util.dispatching.Dispatching; 14 14 import org.apache.log4j.Logger; 15 import com.framsticks.util.dispatching.RunAt; 15 16 16 17 import java.util.HashSet; … … 43 44 protected void dispatchWrite(final Path path) { 44 45 ++dispatched; 45 instance.invokeLater(new Run nable() {46 instance.invokeLater(new RunAt<Instance>() { 46 47 @Override 47 48 public void run() { -
java/main/src/main/java/com/framsticks/examples/GenotypeBrowser.java
r84 r85 43 43 44 44 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")) 47 47 ); 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()); 49 49 } 50 50 -
java/main/src/main/java/com/framsticks/gui/Browser.java
r84 r85 19 19 import java.util.List; 20 20 import java.util.Set; 21 import com.framsticks.util.dispatching.RunAt; 21 22 22 23 /** 23 24 * @author Piotr Sniegowski 24 25 */ 25 public class Browser extends Observer implements Dispatcher{26 public class Browser extends Observer { 26 27 27 28 private static final Logger log = Logger.getLogger(Browser.class.getName()); … … 78 79 public void autoResolvePath(final String path, final Future<Path> future) { 79 80 final Instance i = endpoints.get("localhost").getInstance(); 80 i.invokeLater(new Run nable() {81 i.invokeLater(new RunAt<Instance>() { 81 82 @Override 82 83 public void run() { … … 89 90 } 90 91 if (e == null) { 91 mainFrame.invokeLater(new Run nable() {92 mainFrame.invokeLater(new RunAt<Frame>() { 92 93 @Override 93 94 public void run() { … … 142 143 143 144 for (final Endpoint e : getEndpoints().values()) { 144 e.invokeLater(new Run nable() {145 e.invokeLater(new RunAt<Instance>() { 145 146 @Override 146 147 public void run() { 147 148 final Path p = e.getInstance().getRootPath(); 148 invokeLater(new Run nable() {149 invokeLater(new RunAt<Browser>() { 149 150 @Override 150 151 public void run() { … … 199 200 200 201 @Override 201 public Dispatcher createDefaultDispatcher() {202 return SwingDispatcher. instance;202 public Dispatcher<Entity> createDefaultDispatcher() { 203 return SwingDispatcher.getInstance(); 203 204 } 204 205 -
java/main/src/main/java/com/framsticks/gui/EndpointAtFrame.java
r84 r85 14 14 15 15 import javax.swing.tree.TreePath; 16 import com.framsticks.util.dispatching.RunAt; 16 17 17 18 /** … … 121 122 } 122 123 Path p = new Path(path.getInstance(), nodes, n); 124 125 //TODO breaks immutable 126 path.setInstance(path.getInstance()); 127 123 128 log.debug("forced resolution: creating treenode for " + p); 124 129 TreeNode childNode = new TreeNode(EndpointAtFrame.this, p); … … 146 151 log.trace("fetched " + path); 147 152 148 frame.invokeLater(new Run nable() {153 frame.invokeLater(new RunAt<Frame>() { 149 154 @Override 150 155 public void run() { … … 155 160 final TreeNode result = (TreeNode) treePath.getLastPathComponent(); 156 161 // log.trace("found " + result + " == " + path); 157 instance.invokeLater(new Run nable() {162 instance.invokeLater(new RunAt<Instance>() { 158 163 @Override 159 164 public void run() { -
java/main/src/main/java/com/framsticks/gui/Frame.java
r84 r85 6 6 import com.framsticks.gui.view.TreeCellRenderer; 7 7 import com.framsticks.util.dispatching.Dispatcher; 8 import com.framsticks.util.lang.ScopeEnd; 8 9 import com.framsticks.util.swing.KeyboardModifier; 9 10 import org.apache.log4j.Logger; … … 21 22 import java.util.HashMap; 22 23 import java.util.Map; 24 import com.framsticks.util.dispatching.RunAt; 23 25 24 26 /** … … 26 28 */ 27 29 @SuppressWarnings("serial") 28 public class Frame extends JFrame implements Dispatcher {30 public class Frame extends JFrame implements Dispatcher<Frame> { 29 31 30 32 private static final Logger log = Logger.getLogger(Frame.class.getName()); … … 267 269 268 270 @Override 269 public void invokeLater(Run nablerunnable) {270 SwingDispatcher. instance.invokeLater(runnable);271 public void invokeLater(RunAt<? extends Frame> runnable) { 272 SwingDispatcher.getInstance().invokeLater(runnable); 271 273 } 272 274 … … 325 327 } 326 328 327 public RunnablestartChange(final DefaultMutableTreeNode node) {329 public ScopeEnd startChange(final DefaultMutableTreeNode node) { 328 330 assert isActive(); 329 331 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() { 333 335 assert isActive(); 334 336 treeModel.nodeChanged(node); … … 373 375 final TreePath treePath = endpointsByInstance.get(path.getInstance()).getTreePath(path, false); 374 376 log.info("go to path: " + path + "(" + treePath + ")"); 375 invokeLater(new Runnable() { 377 378 new RunAt<Frame>(this) { 376 379 @Override 377 380 public void run() { 381 log.info("executed"); 378 382 tree.setSelectionPath(treePath); 379 383 tree.makeVisible(treePath); 380 384 assert tree.isVisible(treePath); 381 385 } 382 383 }); 386 }; 387 384 388 } 385 389 … … 387 391 public void addNode(TreeNode child, DefaultMutableTreeNode parent) { 388 392 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 } 392 397 } 393 398 -
java/main/src/main/java/com/framsticks/gui/ObjectPanel.java
r84 r85 15 15 import java.util.Map; 16 16 import static com.framsticks.util.lang.Containers.filterInstanceof; 17 import com.framsticks.util.dispatching.RunAt; 17 18 18 19 @SuppressWarnings("serial") … … 73 74 } 74 75 75 frame.invokeLater(new Run nable() {76 frame.invokeLater(new RunAt<Frame>() { 76 77 @Override 77 78 public void run() { -
java/main/src/main/java/com/framsticks/gui/SwingDispatcher.java
r84 r85 5 5 6 6 import javax.swing.*; 7 import com.framsticks.util.dispatching.RunAt; 7 8 8 9 /** 9 10 * @author Piotr Sniegowski 10 11 */ 11 public class SwingDispatcher implements Dispatcher{12 public class SwingDispatcher<C> implements Dispatcher<C> { 12 13 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 } 14 21 15 22 public SwingDispatcher() { 16 invokeLater(new Run nable() {23 invokeLater(new RunAt<C>() { 17 24 @Override 18 25 public void run() { … … 28 35 29 36 @Override 30 public final void invokeLater(Run nablerunnable) {37 public final void invokeLater(RunAt<? extends C> runnable) { 31 38 assert !(runnable instanceof Task); 32 39 SwingUtilities.invokeLater(runnable); -
java/main/src/main/java/com/framsticks/gui/TreeNode.java
r84 r85 1 1 package com.framsticks.gui; 2 2 3 import com.framsticks.communication.Connection; 3 4 import com.framsticks.communication.Subscription; 4 5 import com.framsticks.communication.util.LoggingStateCallback; 6 import com.framsticks.core.Instance; 5 7 import com.framsticks.core.ListChange; 6 8 import com.framsticks.core.Path; … … 18 20 import com.framsticks.util.StateFunctor; 19 21 import org.apache.log4j.Logger; 22 import com.framsticks.util.dispatching.RunAt; 20 23 21 24 import javax.swing.tree.DefaultMutableTreeNode; … … 40 43 final protected EndpointAtFrame endpoint; 41 44 42 final protected Map<EventParam, Subscription > userSubscriptions = new HashMap<EventParam, Subscription>();45 final protected Map<EventParam, Subscription<?>> userSubscriptions = new HashMap<>(); 43 46 protected Map<ValueControl, Object> localChanges = null; 44 47 protected String tooltip; … … 59 62 iconName = TreeCellRenderer.findIconName(name, path.getTextual()); 60 63 tooltip = "?"; 61 path.getInstance().invokeLater(new Run nable() {64 path.getInstance().invokeLater(new RunAt<Instance>() { 62 65 @Override 63 66 public void run() { … … 82 85 assert p.getInstance().isActive(); 83 86 if (Logging.log(log, "fetch", TreeNode.this, e)) { 84 frame.invokeLater(new Run nable() {87 frame.invokeLater(new RunAt<Frame>() { 85 88 @Override 86 89 public void run() { … … 92 95 } 93 96 updateChildren(p); 94 frame.invokeLater(new Run nable() {97 frame.invokeLater(new RunAt<Frame>() { 95 98 @Override 96 99 public void run() { … … 104 107 assert !frame.isActive(); 105 108 /** TODO those two actions could be merged into single closure */ 106 frame.invokeLater(new Run nable() {109 frame.invokeLater(new RunAt<Frame>() { 107 110 @Override 108 111 public void run() { … … 149 152 /**If some child were found, update in frame context.*/ 150 153 if (childrenPaths.size() > 0) { 151 frame.invokeLater(new Run nable() {154 frame.invokeLater(new RunAt<Frame>() { 152 155 @Override 153 156 public void run() { … … 186 189 final Path p = path; 187 190 188 p.getInstance().invokeLater(new Run nable() {191 p.getInstance().invokeLater(new RunAt<Instance>() { 189 192 @Override 190 193 public void run() { … … 246 249 final String name = (nameParam != null ? access.get(nameParam, String.class) : path.getTop().getParam().getId()); 247 250 248 frame.invokeLater(new Run nable() {251 frame.invokeLater(new RunAt<Frame>() { 249 252 @Override 250 253 public void run() { … … 303 306 assert p.isResolved(); 304 307 panel.setCurrentTreeNode(this); 305 p.getInstance().invokeLater(new Run nable() {308 p.getInstance().invokeLater(new RunAt<Instance>() { 306 309 @Override 307 310 public void run() { … … 309 312 panel.pullValuesFromLocalToUser(access); 310 313 311 frame.invokeLater(new Run nable() {314 frame.invokeLater(new RunAt<Frame>() { 312 315 @Override 313 316 public void run() { … … 341 344 final Path p = path; 342 345 log.debug("preparing panel: " + p); 343 p.getInstance().invokeLater(new Run nable() {346 p.getInstance().invokeLater(new RunAt<Instance>() { 344 347 @Override 345 348 public void run() { … … 347 350 final CompositeParam param = p.getTop().getParam(); 348 351 final FramsClass framsClass = p.getInstance().getInfoFromCache(param.getContainedTypeName()); 349 frame.invokeLater(new Run nable() {352 frame.invokeLater(new RunAt<Frame>() { 350 353 @Override 351 354 public void run() { … … 410 413 return; 411 414 } 412 userSubscriptions.get(eventParam).unsubscribe(new LoggingStateCallback (log, "unsubscribed " + eventParam));415 userSubscriptions.get(eventParam).unsubscribe(new LoggingStateCallback<Connection>(log, "unsubscribed " + eventParam)); 413 416 userSubscriptions.remove(eventParam); 414 417 } … … 500 503 final Map<ValueControl, Object> changes = localChanges; 501 504 localChanges = null; 502 endpoint.getEndpoint().invokeLater(new Run nable() {505 endpoint.getEndpoint().invokeLater(new RunAt<Instance>() { 503 506 @Override 504 507 public void run() { … … 514 517 } 515 518 log.debug("applied changes for: " + p); 516 frame.invokeLater(new Run nable() {519 frame.invokeLater(new RunAt<Frame>() { 517 520 @Override 518 521 public void run() { … … 526 529 }); 527 530 } 528 529 531 } -
java/main/src/main/java/com/framsticks/gui/controls/EnumControl.java
r84 r85 14 14 public class EnumControl extends ValueControl { 15 15 16 protected final JComboBox list;16 protected final JComboBox<String> list; 17 17 18 18 private static final Logger log = Logger.getLogger(EnumControl.class.getName()); … … 23 23 this.setMaximumSize(new Dimension(Integer.MAX_VALUE, LINE_HEIGHT)); 24 24 25 list = new JComboBox ();25 list = new JComboBox<String>(); 26 26 for (String item : enumParam.getElements()) { 27 27 list.addItem(item); -
java/main/src/main/java/com/framsticks/gui/windows/ServerLogFrame.java
r84 r85 43 43 logText.setWrapStyleWord(true); 44 44 logText.setLineWrap(true); 45 JComboBox levelBox = new JComboBox();45 JComboBox<String> levelBox = new JComboBox<String>(); 46 46 for (String i : STR_) { 47 47 levelBox.addItem(i); … … 49 49 levelBox.addActionListener(new ActionListener() { 50 50 public void actionPerformed(ActionEvent e) { 51 levelReporting = ((JComboBox ) e.getSource()).getSelectedIndex();51 levelReporting = ((JComboBox<?>) e.getSource()).getSelectedIndex(); 52 52 } 53 53 }); -
java/main/src/main/java/com/framsticks/gui/windows/console/ConsoleFrame.java
r84 r85 172 172 addSentMessage(commandText); 173 173 commandLine.setText(""); 174 connection.send(request, new ResponseCallback () {174 connection.send(request, new ResponseCallback<Connection>() { 175 175 @Override 176 176 public void process(Response response) { -
java/main/src/main/java/com/framsticks/hosting/InstanceClient.java
r84 r85 5 5 import com.framsticks.communication.queries.GetRequest; 6 6 import com.framsticks.communication.queries.InfoRequest; 7 import com.framsticks.core.Instance; 7 8 import com.framsticks.core.Path; 8 9 import com.framsticks.params.*; … … 15 16 import java.util.LinkedList; 16 17 import java.util.List; 18 import com.framsticks.util.dispatching.RunAt; 17 19 18 20 /** … … 37 39 38 40 @Override 39 public void handle(final ApplicationRequest request, final ResponseCallback responseCallback) {40 instance.invokeLater(new Run nable() {41 public void handle(final ApplicationRequest request, final ResponseCallback<?> responseCallback) { 42 instance.invokeLater(new RunAt<Instance>() { 41 43 @Override 42 44 public void run() { -
java/main/src/main/java/com/framsticks/hosting/ServerInstance.java
r84 r85 4 4 import com.framsticks.params.CompositeParam; 5 5 import com.framsticks.params.FramsClass; 6 import com.framsticks.params.Param Builder;6 import com.framsticks.params.Param; 7 7 import com.framsticks.core.LocalInstance; 8 8 import com.framsticks.util.dispatching.Future; … … 42 42 hosted.setName("hosted"); 43 43 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); 45 45 } 46 46 -
java/main/src/main/java/com/framsticks/leftovers/FavouritesXMLFactory.java
r84 r85 3 3 import java.io.BufferedWriter; 4 4 import java.io.File; 5 import java.io.FileWriter; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.OutputStreamWriter; 8 import java.nio.file.Files; 6 9 import java.util.ArrayList; 7 10 import java.util.Collection; 8 11 import java.util.HashMap; 9 import java.util.Iterator;10 12 import java.util.LinkedHashMap; 11 13 import java.util.Map; … … 13 15 import javax.xml.parsers.DocumentBuilder; 14 16 import javax.xml.parsers.DocumentBuilderFactory; 17 import javax.xml.parsers.ParserConfigurationException; 15 18 import javax.xml.stream.XMLOutputFactory; 19 import javax.xml.stream.XMLStreamException; 16 20 import javax.xml.stream.XMLStreamWriter; 17 21 22 import org.apache.log4j.Logger; 18 23 import org.w3c.dom.Document; 19 24 import org.w3c.dom.Node; 20 25 import org.w3c.dom.NodeList; 26 import org.xml.sax.SAXException; 27 28 import com.framsticks.util.io.Encoding; 21 29 22 30 public 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 } 28 107 29 108 /** … … 39 118 return; 40 119 } 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"); 53 123 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()); 63 128 64 129 /*if(node.isFavouriteNode()){ … … 67 132 xmlWriter.writeEndElement(); 68 133 }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); 86 140 } 87 141 } … … 95 149 * concatenation of path and field getName. 96 150 */ 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 } 98 158 LinkedHashMap<String, UserFavourite> result = new LinkedHashMap<String, UserFavourite>(); 99 159 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) { 136 184 } 137 185 } 138 186 } 139 } catch (Exception e) { 140 } 141 187 } 142 188 } 143 189 … … 159 205 return; 160 206 } 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); 189 214 } 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); 203 220 } 204 221 } … … 214 231 public HashMap<String, ArrayList<String>> readColumnConfigurationXML( 215 232 String path) { 233 Node root = readDocument(path); 234 if (root == null) { 235 return null; 236 } 237 216 238 HashMap<String, ArrayList<String>> result = new LinkedHashMap<String, ArrayList<String>>(); 217 239 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 } 247 254 return result; 248 255 } -
java/main/src/main/java/com/framsticks/leftovers/f0/NeuroClass.java
r84 r85 16 16 17 17 /** 18 * The symbol gly mph.19 */ 20 private int[] symbolGly mph;18 * The symbol glyph. 19 */ 20 private int[] symbolGlyph; 21 21 22 22 /** … … 71 71 * @param prefLocation the pref location 72 72 * @param visualHints the visual hints 73 * @param symbolGly mph the symbol glymph73 * @param symbolGlyph the symbol glymph 74 74 */ 75 75 public NeuroClass(FramsClass framsClass, int prefInputs, 76 76 int prefOutput, int prefLocation, int visualHints, 77 int[] symbolGlymph) { 78 super(); 77 int[] symbolGlyph) { 79 78 this.framsClass = framsClass; 80 79 this.prefInputs = prefInputs; … … 82 81 this.prefLocation = prefLocation; 83 82 this.visualHints = visualHints; 84 this.symbolGly mph = symbolGlymph;83 this.symbolGlyph = (symbolGlyph == null ? null : Arrays.copyOf(symbolGlyph, symbolGlyph.length)); 85 84 } 86 85 … … 153 152 */ 154 153 int[] getSymbolGlyph() { 155 return symbolGly mph;154 return symbolGlyph; 156 155 } 157 156 … … 165 164 */ 166 165 void setSymbolGlyph(int[] data) { 167 symbolGly mph = data;166 symbolGlyph = data; 168 167 } 169 168 … … 191 190 .append(", prefLocation=").append(prefLocation) 192 191 .append(", visualHints=").append(visualHints) 193 .append(", symbolGlymph=").append(Arrays.toString(symbolGly mph));192 .append(", symbolGlymph=").append(Arrays.toString(symbolGlyph)); 194 193 195 194 sb.append(", paramList={"); -
java/main/src/main/java/com/framsticks/observers/Endpoint.java
r84 r85 8 8 import com.framsticks.util.dispatching.Dispatcher; 9 9 import org.apache.log4j.Logger; 10 import com.framsticks.util.dispatching.RunAt; 10 11 11 12 /** 12 13 * @author Piotr Sniegowski 13 14 */ 14 public class Endpoint implements Dispatcher , InstanceListener {15 public class Endpoint implements Dispatcher<Instance>, InstanceListener { 15 16 private final static Logger log = Logger.getLogger(Endpoint.class.getName()); 16 17 … … 67 68 68 69 @Override 69 public final void invokeLater(Run nablerunnable) {70 public final void invokeLater(RunAt<? extends Instance> runnable) { 70 71 instance.invokeLater(runnable); 71 72 } -
java/main/src/main/java/com/framsticks/params/ArrayListAccess.java
r84 r85 31 31 @Override 32 32 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(); 34 34 } 35 35 -
java/main/src/main/java/com/framsticks/params/Flags.java
r84 r85 60 60 } 61 61 } 62 } catch (IllegalArgumentException e) { 63 e.printStackTrace(); 64 } catch (IllegalAccessException e) { 62 } catch (IllegalArgumentException | IllegalAccessException e) { 65 63 e.printStackTrace(); 66 64 } … … 80 78 } catch (SecurityException e) { 81 79 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) { 87 81 log.warn("selected flag is not known (" + flag + ")"); 88 82 } -
java/main/src/main/java/com/framsticks/params/FramsClass.java
r84 r85 26 26 public final class FramsClass { 27 27 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 */ 33 34 34 35 /** The offset of the parameter (applied for newly added parameter). */ … … 91 92 } 92 93 94 public FramsClass append(ParamBuilder builder) { 95 return append(builder.finish()); 96 } 97 93 98 /** 94 99 * Adds new group. … … 185 190 public static FramsClass getFramsClass() { 186 191 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)); 190 195 } 191 196 … … 210 215 //TODO uid should be passed along during construction 211 216 if (containedType instanceof Class) { 212 return "l " + ((Class<?>) containedType).getCanonicalName() + " name"; 217 return "l " + ((Class<?>) containedType).getCanonicalName() 218 + " name"; 213 219 } 214 220 } … … 248 254 249 255 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()); 251 258 currentClass = src; 252 259 while (currentClass != null) { 253 260 try { 254 261 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); 256 266 } 257 267 currentClass = currentClass.getSuperclass(); … … 285 295 if (method.getName().startsWith("get")) { 286 296 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(); 288 298 assert param != null; 289 299 result.append(param); … … 308 318 return this; 309 319 } 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(); 311 321 assert param != null; 312 322 result.append(param); -
java/main/src/main/java/com/framsticks/params/Param.java
r84 r85 105 105 public static FramsClass getFramsClass() { 106 106 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(); 112 116 } 113 117 -
java/main/src/main/java/com/framsticks/params/ParamBuilder.java
r84 r85 55 55 private PrimitiveParam primitiveParam; 56 56 57 ParamBuilder() { 58 } 59 57 60 /** 58 61 * Build Param based on provided data. … … 62 65 * when Param getType is not defined 63 66 */ 64 public Param build() {67 public Param finish() { 65 68 assert param != null; 66 69 param.id = id; … … 73 76 } 74 77 75 public ParamBuilder setId(String id) {78 public ParamBuilder id(String id) { 76 79 this.id = id; 77 80 return this; … … 87 90 } 88 91 89 public <T extends Param> ParamBuilder setType(Class<T> type) {92 public <T extends Param> ParamBuilder type(Class<T> type) { 90 93 try { 91 94 return internalSetType(type, type.newInstance()); 92 } catch (InstantiationException e) {95 } catch (InstantiationException | IllegalAccessException e) { 93 96 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) { 101 102 return internalSetType(param.getClass(), param); 102 103 } … … 108 109 } 109 110 110 public ParamBuilder setGroup(Integer group) {111 public ParamBuilder group(Integer group) { 111 112 this.group = group; 112 113 return this; 113 114 } 114 115 115 public ParamBuilder setFlags(Integer flags) {116 public ParamBuilder flags(Integer flags) { 116 117 this.flags = flags; 117 118 return this; 118 119 } 119 120 120 public ParamBuilder setName(String name) {121 public ParamBuilder name(String name) { 121 122 this.name = name; 122 123 return this; … … 142 143 } 143 144 144 public ParamBuilder setType(String type) {145 public ParamBuilder type(String type) { 145 146 146 147 log.trace("parsing type: " + type); … … 153 154 switch (first.charAt(0)) { 154 155 case 'o': { 155 setType(new ObjectParam(second != null ? second : first.substring(1)));156 type(new ObjectParam(second != null ? second : first.substring(1))); 156 157 break; 157 158 } … … 164 165 log.error("invalid procedure signature '" + signature + "': " + e); 165 166 } 166 setType(procedureParam);167 type(procedureParam); 167 168 break; 168 169 } … … 171 172 int tildeIndex = type.indexOf("~"); 172 173 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("~"))))); 174 175 } else { 175 176 if (first.length() >= 2) { 176 switch (first.charAt(1)) {177 switch (first.charAt(1)) { 177 178 case 'b': { 178 setType(BinaryParam.class);179 type(BinaryParam.class); 179 180 break; 180 181 } 181 182 case 'c': { 182 setType(ColorParam.class);183 type(ColorParam.class); 183 184 break; 185 } 186 default: { 187 log.error("unknown type: " + first); 188 return this; 184 189 } 185 190 } 186 191 } 187 192 if ("0".equals(second) && "1".equals(third)) { 188 setType(BooleanParam.class);193 type(BooleanParam.class); 189 194 } 190 195 if (param == null) { 191 setType(DecimalParam.class);196 type(DecimalParam.class); 192 197 } 193 198 } … … 198 203 } 199 204 case 'f': { 200 setType(FloatParam.class);205 type(FloatParam.class); 201 206 parseMinMaxDefNumber(Double.class, second, third); 202 207 break; 203 208 } 204 209 case 'x': { 205 setType(UniversalParam.class);210 type(UniversalParam.class); 206 211 break; 207 212 } 208 213 case 's': { 209 setType(StringParam.class);210 setMin(second);211 setMax(third);214 type(StringParam.class); 215 min(second); 216 max(third); 212 217 break; 213 218 } 214 219 case 'e': { 215 setType(EventParam.class);220 type(EventParam.class); 216 221 break; 217 222 } 218 223 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) { 228 236 this.help = help; 229 237 return this; … … 237 245 } 238 246 239 public <T> ParamBuilder setMin(T min) {247 public <T> ParamBuilder min(T min) { 240 248 if (primitiveParam != null) { 241 249 this.primitiveParam.min = min; … … 244 252 } 245 253 246 public <T> ParamBuilder setMax(T max) {254 public <T> ParamBuilder max(T max) { 247 255 if (primitiveParam != null) { 248 256 this.primitiveParam.max = max; … … 251 259 } 252 260 253 public <T> ParamBuilder setDef(T def) {261 public <T> ParamBuilder def(T def) { 254 262 if (def != null && primitiveParam != null) { 255 263 this.primitiveParam.def = def; … … 277 285 278 286 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]); 285 293 } catch (IndexOutOfBoundsException e) { 286 294 /** everything is ok, parameters have just finished*/ … … 290 298 return null; 291 299 } 292 return build();300 return finish(); 293 301 } 294 302 295 303 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; 308 326 } 309 327 } … … 312 330 public static FramsClass getFramsClass() { 313 331 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)); 319 338 } 320 339 -
java/main/src/main/java/com/framsticks/params/PropertiesAccess.java
r84 r85 40 40 assert properties != null; 41 41 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 } 43 50 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); 49 52 } 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); 51 54 } 52 55 -
java/main/src/main/java/com/framsticks/params/ReflectionAccess.java
r84 r85 47 47 try { 48 48 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) { 52 55 //e.printStackTrace(); 53 56 } 54 57 55 } catch (IllegalAccessException e x) {58 } catch (IllegalAccessException e) { 56 59 log.warn("illegal access error occurred while trying to access returnedObject"); 57 e x.printStackTrace();60 e.printStackTrace(); 58 61 } catch (ClassCastException ignored) { 59 62 … … 87 90 try { 88 91 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) { 91 97 } 92 98 } catch (Exception ex) { … … 161 167 try { 162 168 return reflectedClass.newInstance(); 163 } catch (InstantiationException e) { 164 e.printStackTrace(); 165 } catch (IllegalAccessException e) { 169 } catch (InstantiationException | IllegalAccessException e) { 166 170 e.printStackTrace(); 167 171 } -
java/main/src/main/java/com/framsticks/params/UniqueListAccess.java
r84 r85 35 35 //log.error("accesing unique list through index"); 36 36 //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(); 38 38 } 39 39 … … 44 44 return getParam(i); 45 45 } 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(); 47 47 } 48 48 -
java/main/src/main/java/com/framsticks/params/types/ProcedureParam.java
r84 r85 2 2 3 3 import com.framsticks.params.Param; 4 import com.framsticks.params.ParamBuilder;5 4 import com.framsticks.util.lang.Strings; 6 5 … … 20 19 21 20 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(); 23 22 } 24 23 -
java/main/src/main/java/com/framsticks/parsers/F0Parser.java
r84 r85 84 84 ParseException { 85 85 86 InputStreamReader reader = null; 87 try { 88 reader = new InputStreamReader(is, "UTF-8"); 86 try (InputStreamReader reader = new InputStreamReader(is, "UTF-8")) { 89 87 BufferedReader br = new BufferedReader(reader); 90 88 while (br.ready()) { … … 114 112 if (result.isEmpty() || !(result.get(0) instanceof Model)) { 115 113 result.add(0, processLine("m:")); 116 }117 } finally {118 if (reader != null) {119 reader.close();120 114 } 121 115 } -
java/main/src/main/java/com/framsticks/parsers/F0Writer.java
r84 r85 15 15 protected final SinkInterface sink; 16 16 protected final Model model; 17 protected boolean omit = true;17 protected boolean omitDefaults = true; 18 18 19 19 public F0Writer(Schema schema, Model model, SinkInterface sink) { … … 23 23 } 24 24 25 F0Writer omitDefaultValues(boolean omit) {26 this.omit = omit;25 public F0Writer setOmitDefaults(boolean omitDefaults) { 26 this.omitDefaults = omitDefaults; 27 27 return this; 28 28 } … … 49 49 } 50 50 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))) { 52 52 contiguous = false; 53 53 continue; -
java/main/src/main/java/com/framsticks/parsers/FileSource.java
r78 r85 2 2 3 3 import com.framsticks.params.SourceInterface; 4 import com.framsticks.util.io.Encoding; 4 5 5 6 import java.io.*; … … 8 9 public class FileSource implements SourceInterface { 9 10 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) { 15 15 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); 17 21 } 18 22 19 23 public FileSource(InputStream stream) { 20 filename = "<stream>"; 21 reader = new BufferedReader(new InputStreamReader(stream)); 24 this(stream, "<stream>"); 22 25 } 23 26 24 25 @Override 26 public String readLine() 27 @Override 28 public String readLine() 27 29 { 28 30 try … … 35 37 } 36 38 37 38 39 @Override 40 public String getFilename() 39 41 { 40 42 return filename; 41 43 } 42 44 43 44 45 @Override 46 public String demangleInclude(String include) 45 47 { 46 48 if (!include.contains(java.io.File.separator)) { … … 52 54 } 53 55 include = currentFilePath + include; 54 } 56 } 55 57 return include; 56 58 } 57 59 58 59 60 @Override 61 public SourceInterface openInclude(String include) 60 62 { 61 63 try … … 65 67 catch(IOException e) 66 68 { 67 69 68 70 } 69 71 return null; 70 72 } 71 73 72 73 74 @Override 75 public void close() 74 76 { 75 77 try { 76 78 reader.close(); 77 79 } catch (IOException e) { 78 80 79 81 } 80 82 } 81 83 82 84 } -
java/main/src/main/java/com/framsticks/parsers/GenotypeLoader.java
r77 r85 22 22 //getId, group-number, getFlags, getName, getType(getType min max), getHelp 23 23 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")); 54 54 55 55 ReflectionAccess reflectionParam = new ReflectionAccess(Genotype.class, entries); -
java/main/src/main/java/com/framsticks/parsers/Loaders.java
r84 r85 35 35 } 36 36 if (object instanceof ParamBuilder) { 37 result.append(((ParamBuilder) object). build());37 result.append(((ParamBuilder) object).finish()); 38 38 } 39 39 } -
java/main/src/main/java/com/framsticks/parsers/Schema.java
r84 r85 26 26 * classes definitions that can be used in f0 representation). Definitions are 27 27 * loaded from XML stream. 28 * 28 * 29 29 * @author Jarek Szymczak <name.surname@gmail.com> 30 30 * (please replace name and surname with my personal data) … … 46 46 /** 47 47 * Instantiates a new schema. 48 * 48 * 49 49 * @param inputStream 50 50 * the xml stream with schema … … 104 104 } 105 105 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) { 113 107 logger.fatal("unexpected exception occurred: ", e); 114 108 throw e; … … 121 115 * node under certain attribute getName. If value is not present or is other 122 116 * getType than integer 0 is returned. 123 * 117 * 124 118 * @return attribute value if value exists and it's integer (0 otherwise) 125 * 119 * 126 120 */ 127 121 private static int getIntAttribute(NamedNodeMap attributes, String name) { … … 152 146 * Method used for convenience, it retrieves the value stored in node under 153 147 * certain attribute getName. If value is not present method returns null. 154 * 148 * 155 149 * @param attributeName 156 150 * the attribute getName … … 158 152 * the node 159 153 * @return attribute value if value exists (null otherwise) 160 * 154 * 161 155 */ 162 156 private static String getAttributeFromNode(String attributeName, Node node) { … … 169 163 /** 170 164 * In this method analysis of single class is performed. 171 * 165 * 172 166 * @param classNode 173 167 * the class node … … 228 222 /** 229 223 * It analyses the single property within the class 230 * 224 * 231 225 * @param attributes 232 226 * the attributes of property … … 267 261 } 268 262 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); 273 267 274 268 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)); 278 272 } 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)); 282 276 } 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")); 287 281 } else { 288 builder. setType(type);289 } 290 return builder. build();282 builder.type(type); 283 } 284 return builder.finish(); 291 285 } 292 286 -
java/main/src/main/java/com/framsticks/portals/Portal.java
r84 r85 22 22 public void run() { 23 23 super.run(); 24 new PeriodicTask (this, 1000) {24 new PeriodicTask<Portal>(this, 1000) { 25 25 26 26 @Override -
java/main/src/main/java/com/framsticks/portals/PortalEndpoint.java
r84 r85 1 1 package com.framsticks.portals; 2 2 3 import com.framsticks.core.Instance; 3 4 import com.framsticks.core.Path; 4 5 import com.framsticks.observers.Endpoint; … … 7 8 import com.framsticks.util.Logging; 8 9 import org.apache.log4j.Logger; 10 import com.framsticks.util.dispatching.RunAt; 9 11 10 12 /** … … 18 20 } 19 21 20 21 22 23 22 @Override 23 public Portal getObserver() { 24 return (Portal) observer; 25 } 24 26 25 26 27 27 @Override 28 public void onRun(Exception e) { 29 assert Dispatching.isThreadSafe(); 28 30 29 31 super.onRun(e); 30 32 31 32 33 34 35 instance.invokeLater(new Runnable() {36 37 38 39 40 41 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 } 47 49 48 49 50 50 @Override 51 public void onStop(Exception e) { 52 } 51 53 52 54 53 54 55 56 57 58 59 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 */ 64 66 65 67 -
java/main/src/main/java/com/framsticks/remote/RecursiveFetcher.java
r84 r85 12 12 import org.apache.log4j.Logger; 13 13 import static com.framsticks.util.lang.Containers.filterInstanceof; 14 import com.framsticks.util.dispatching.RunAt; 14 15 15 16 /** … … 51 52 if (childPath.isResolved() && instance.getInfoFromCache(childPath) != null) { 52 53 ++dispatched; 53 instance.invokeLater(new Run nable() {54 instance.invokeLater(new RunAt<Instance>() { 54 55 @Override 55 56 public void run() { -
java/main/src/main/java/com/framsticks/remote/RemoteInstance.java
r84 r85 17 17 import com.framsticks.util.lang.Casting; 18 18 import com.framsticks.util.lang.Pair; 19 import com.framsticks.util.dispatching.RunAt; 19 20 20 21 import org.apache.commons.configuration.Configuration; … … 33 34 protected ClientConnection connection; 34 35 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) { 39 40 if (s.first.matches(path)) { 40 41 return s; … … 67 68 } 68 69 69 invokeLater(new Run nable() {70 invokeLater(new RunAt<Instance>() { 70 71 @Override 71 72 public void run() { … … 85 86 EventParam param = getParam(simulator, "running_changed", EventParam.class); 86 87 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() { 88 89 @Override 89 90 public void call(List<File> files) { 90 invokeLater(new Run nable() {91 invokeLater(new RunAt<Instance>() { 91 92 @Override 92 93 public void run() { … … 96 97 } 97 98 })); 98 new PeriodicTask (RemoteInstance.this, 1000) {99 new PeriodicTask<Instance>(RemoteInstance.this, 1000) { 99 100 @Override 100 101 public void run() { … … 187 188 assert param != null; 188 189 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>() { 190 191 @Override 191 192 public void process(Response response) { … … 232 233 233 234 //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>() { 235 236 @Override 236 237 public void process(Response response) { … … 268 269 269 270 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>() { 271 272 @Override 272 273 public void process(Response response) { … … 344 345 } 345 346 346 final Pair<Path, Subscription > temporary = new Pair<Path, Subscription>(path, null);347 final Pair<Path, Subscription<?>> temporary = new Pair<>(path, null); 347 348 subscriptions.add(temporary); 348 349 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) { 352 353 if (subscription == null) { 353 354 log.error("failed to subscribe for change event for " + path); … … 355 356 } 356 357 log.debug("subscribed for change event for " + path); 357 subscription.setDispatcher(RemoteInstance.this);358 RemoteInstance.this.invokeLater(new Run nable() {358 // subscription.setDispatcher(RemoteInstance.this); 359 RemoteInstance.this.invokeLater(new RunAt<Instance>() { 359 360 @Override 360 361 public void run() { 361 362 subscriptions.remove(temporary); 362 subscriptions.add(new Pair<Path, Subscription >(path, subscription));363 subscriptions.add(new Pair<Path, Subscription<?>>(path, subscription)); 363 364 } 364 365 }); … … 459 460 460 461 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>() { 462 463 @Override 463 464 public void call(Exception e) { -
java/main/src/main/java/com/framsticks/util/PeriodicTask.java
r84 r85 3 3 import com.framsticks.util.dispatching.Dispatcher; 4 4 import com.framsticks.util.dispatching.Task; 5 import com.framsticks.util.dispatching.RunAt; 5 6 6 7 /** 7 8 * @author Piotr Sniegowski 8 9 */ 9 public abstract class PeriodicTask implements Runnable{10 public abstract class PeriodicTask<C> extends RunAt<C> { 10 11 11 12 protected Dispatcherdispatcher;12 protected final long period; 13 protected Dispatcher<? super C> dispatcher; 13 14 14 public PeriodicTask(Dispatcherdispatcher, long period) {15 16 17 18 15 public PeriodicTask(Dispatcher<? super C> dispatcher, long period) { 16 this.period = period; 17 this.dispatcher = dispatcher; 18 dispatcher.invokeLater(this); 19 } 19 20 20 21 21 22 dispatcher.invokeLater(new Task(System.currentTimeMillis() + period) {23 24 25 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 } 29 30 30 31 } -
java/main/src/main/java/com/framsticks/util/StateFunctor.java
r77 r85 5 5 */ 6 6 public interface StateFunctor { 7 //TODO RunAt 7 8 public void call(Exception e); 8 9 } -
java/main/src/main/java/com/framsticks/util/dispatching/AtOnceDispatcher.java
r84 r85 4 4 * @author Piotr Sniegowski 5 5 */ 6 public class AtOnceDispatcher implements Dispatcher{6 public class AtOnceDispatcher<C> implements Dispatcher<C> { 7 7 8 public static final AtOnceDispatcher instance = new AtOnceDispatcher(); 8 @SuppressWarnings("rawtypes") 9 protected static final AtOnceDispatcher instance = new AtOnceDispatcher(); 9 10 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 } 14 15 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 } 19 25 } -
java/main/src/main/java/com/framsticks/util/dispatching/Dispatcher.java
r84 r85 4 4 * @author Piotr Sniegowski 5 5 */ 6 public interface Dispatcher {7 8 public void invokeLater(Runnablerunnable);6 public interface Dispatcher<C> { 7 public boolean isActive(); 8 public void invokeLater(RunAt<? extends C> runnable); 9 9 } -
java/main/src/main/java/com/framsticks/util/dispatching/Dispatching.java
r84 r85 8 8 public abstract class Dispatching { 9 9 10 11 12 10 public static boolean isThreadSafe() { 11 return true; 12 } 13 13 14 public static void invokeLaterOrNow(Dispatcher dispatcher, Runnablerunnable) {15 16 17 18 19 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 } 21 21 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 } 30 31 31 public static boolean assertInvokeLater(Dispatcher dispatcher, Runnablerunnable) {32 33 34 32 // public static boolean assertInvokeLater(Dispatcher dispatcher, RunAt runnable) { 33 // dispatcher.invokeLater(runnable); 34 // return true; 35 // } 35 36 36 public static void invokeDispatch(Dispatcher dispatcher, final Dispatcher finalDispatcher, final Runnablerunnable) {37 dispatcher.invokeLater(new Runnable() {38 39 40 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 } 44 45 45 46 } -
java/main/src/main/java/com/framsticks/util/dispatching/Task.java
r84 r85 4 4 * @author Piotr Sniegowski 5 5 */ 6 public abstract class Task implements Runnable{6 public abstract class Task<C> extends RunAt<C> { 7 7 8 8 protected final long moment; 9 9 10 11 12 10 public Task() { 11 moment = System.currentTimeMillis(); 12 } 13 13 14 15 16 14 public Task(long moment) { 15 this.moment = moment; 16 } 17 17 18 19 20 18 public final long getMoment() { 19 return moment; 20 } 21 21 22 22 } -
java/main/src/main/java/com/framsticks/util/dispatching/Thread.java
r84 r85 5 5 import java.util.LinkedList; 6 6 import java.util.ListIterator; 7 import com.framsticks.util.dispatching.RunAt; 7 8 8 9 /** 9 10 * @author Piotr Sniegowski 10 11 */ 11 public class Thread implements Dispatcher{12 public class Thread<C> implements Dispatcher<C> { 12 13 13 14 private static final Logger log = Logger.getLogger(Thread.class.getName()); … … 15 16 protected final java.lang.Thread thread; 16 17 17 private final LinkedList<Task > queue = new LinkedList<Task>();18 private final LinkedList<Task<? extends C>> queue = new LinkedList<>(); 18 19 19 20 public Thread() { 20 thread = new java.lang.Thread(new Runnable() {21 thread = new java.lang.Thread(new java.lang.Runnable() { 21 22 @Override 22 23 public void run() { … … 25 26 }); 26 27 } 28 27 29 public Thread(String s) { 28 30 this(); 29 31 thread.setName(s); 30 thread.start();32 // thread.start(); 31 33 } 32 34 … … 34 36 this.thread = thread; 35 37 thread.setName(s); 38 } 39 40 public Thread<C> start() { 41 thread.start(); 42 return this; 36 43 } 37 44 … … 43 50 protected void routine() { 44 51 while (!java.lang.Thread.interrupted()) { 45 Task task;52 Task<? extends C> task; 46 53 synchronized (queue) { 47 54 if (queue.isEmpty()) { … … 74 81 } 75 82 76 protected void enqueueTask(Task task) {83 protected void enqueueTask(Task<? extends C> task) { 77 84 synchronized (queue) { 78 ListIterator<Task > i = queue.listIterator();85 ListIterator<Task<? extends C>> i = queue.listIterator(); 79 86 while (i.hasNext()) { 80 Task t = i.next();87 Task<? extends C> t = i.next(); 81 88 if (t.getMoment() > task.getMoment()) { 82 89 i.previous(); … … 104 111 105 112 @Override 106 public void invokeLater(final Run nablerunnable) {113 public void invokeLater(final RunAt<? extends C> runnable) { 107 114 if (!(runnable instanceof Task)) { 108 enqueueTask(new Task () {115 enqueueTask(new Task<C>() { 109 116 @Override 110 117 public void run() { … … 114 121 return; 115 122 } 116 enqueueTask((Task )runnable);123 enqueueTask((Task<? extends C>) runnable); 117 124 } 118 125 … … 125 132 } 126 133 127 public void start() {128 thread.start();129 }130 131 134 public void setName(String name) { 132 135 thread.setName(name); 133 136 134 137 } 138 139 public static boolean interrupted() { 140 return java.lang.Thread.interrupted(); 141 } 135 142 } -
java/main/src/main/java/com/framsticks/visualization/Viewer.java
r84 r85 1 1 package com.framsticks.visualization; 2 2 3 import com.framsticks.util.io.Encoding; 3 4 import com.sun.j3d.loaders.IncorrectFormatException; 4 5 import com.sun.j3d.loaders.ParsingErrorException; … … 18 19 import java.io.*; 19 20 20 //import org.apache.log4j.Logger;21 import org.apache.log4j.Logger; 21 22 22 23 public class Viewer { 23 24 24 //private static Logger log = Logger.getLogger(Viewer.class);25 private static Logger log = Logger.getLogger(Viewer.class); 25 26 26 27 27 Canvas3D canvas3d; 28 SimpleUniverse universe; 28 29 29 30 30 public Viewer() { 31 super(); 31 32 32 33 33 init(); 34 } 34 35 35 36 public BranchGroup createSceneGraph() { 36 37 37 // Create the root of the branch graph 38 BranchGroup objRoot = new BranchGroup(); 38 39 39 40 41 42 43 44 45 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); 46 47 47 48 49 50 48 TransformGroup objTrans = new TransformGroup(); 49 objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); 50 objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); 51 objScale.addChild(objTrans); 51 52 52 53 54 55 53 String filename = "/visualization/models/cylinder.obj"; 54 int flags = ObjectFile.RESIZE; 55 flags |= ObjectFile.TRIANGULATE; 56 flags |= ObjectFile.STRIPIFY; 56 57 double creaseAngle = 60.0; 57 58 ObjectFile f = new ObjectFile(flags, 58 59 60 59 (float) (creaseAngle * Math.PI / 180.0)); 60 Scene s = null; 61 try { 61 62 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 } 73 68 74 69 objTrans.addChild(s.getSceneGroup()); 75 70 76 71 BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); 77 72 78 79 80 81 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); 82 77 83 84 78 return objRoot; 79 } 85 80 86 81 private void init() { 87 82 88 89 83 JTextPane textPane = new JTextPane(); 84 textPane.setEditable(false); 90 85 91 86 GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); 92 87 93 94 88 // Create a Canvas3D using the preferred configuration 89 canvas3d = new Canvas3D(config); 95 90 96 97 98 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); 99 94 100 101 95 // add mouse behaviours to the ViewingPlatform 96 ViewingPlatform viewingPlatform = universe.getViewingPlatform(); 102 97 103 98 PlatformGeometry platformGeometry = new PlatformGeometry(); 104 99 105 106 107 108 109 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); 110 105 111 112 113 114 115 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); 116 111 117 118 119 120 112 DirectionalLight light1 = new DirectionalLight(light1Color, 113 light1Direction); 114 light1.setInfluencingBounds(bounds); 115 platformGeometry.addChild(light1); 121 116 122 123 124 125 117 DirectionalLight light2 = new DirectionalLight(light2Color, 118 light2Direction); 119 light2.setInfluencingBounds(bounds); 120 platformGeometry.addChild(light2); 126 121 127 122 viewingPlatform.setPlatformGeometry(platformGeometry); 128 123 129 124 viewingPlatform.setNominalViewingTransform(); 130 125 131 132 126 // Ensure at least 5 msec per frame (i.e., < 200Hz) 127 universe.getViewer().getView().setMinimumFrameCycleTime(5); 133 128 134 135 129 BranchGroup scene = new BranchGroup(); 130 BranchGroup content = createSceneGraph(); 136 131 137 138 139 140 141 142 143 144 145 146 147 148 149 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); 150 145 151 146 universe.addBranchGraph(scene); 152 147 canvas3d.startRenderer(); 153 148 Dimension d = new Dimension(500, 500); 154 149 canvas3d.setMinimumSize(d); 155 150 canvas3d.setSize(d); 156 151 } 157 152 158 159 160 153 public Component getViewComponent() { 154 return canvas3d; 155 } 161 156 162 157
Note: See TracChangeset
for help on using the changeset viewer.