id
int64
0
10.2k
text_id
stringlengths
17
67
repo_owner
stringclasses
232 values
repo_name
stringclasses
295 values
issue_url
stringlengths
39
89
pull_url
stringlengths
37
87
comment_url
stringlengths
37
94
links_count
int64
1
2
link_keyword
stringclasses
12 values
issue_title
stringlengths
7
197
issue_body
stringlengths
45
21.3k
base_sha
stringlengths
40
40
head_sha
stringlengths
40
40
diff_url
stringlengths
120
170
diff
stringlengths
478
132k
changed_files
stringlengths
47
2.6k
changed_files_exts
stringclasses
22 values
changed_files_count
int64
1
22
java_changed_files_count
int64
1
22
kt_changed_files_count
int64
0
0
py_changed_files_count
int64
0
0
code_changed_files_count
int64
1
22
repo_symbols_count
int64
32.6k
242M
repo_tokens_count
int64
6.59k
49.2M
repo_lines_count
int64
992
6.2M
repo_files_without_tests_count
int64
12
28.1k
changed_symbols_count
int64
0
36.1k
changed_tokens_count
int64
0
6.5k
changed_lines_count
int64
0
561
changed_files_without_tests_count
int64
1
17
issue_symbols_count
int64
45
21.3k
issue_words_count
int64
2
1.39k
issue_tokens_count
int64
13
4.47k
issue_lines_count
int64
1
325
issue_links_count
int64
0
19
issue_code_blocks_count
int64
0
31
pull_create_at
timestamp[s]
stars
int64
10
44.3k
language
stringclasses
8 values
languages
stringclasses
296 values
license
stringclasses
2 values
2,041
telstra/open-kilda/5043/4991
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/4991
https://github.com/telstra/open-kilda/pull/5043
https://github.com/telstra/open-kilda/pull/5043
1
closes
GRPC API returns incorrect JSON error response
**Steps to reproduce:** *****ON HARDWARE ENV***** 1. go to GRPC swagger 2. send some incorrect request. For example try to get logical port for unknown IP 1.1.1.1 ```GET /noviflow/1.1.1.1/logicalports``` **Expected result:** Correct JSON response **Actual result:** Concatenation of 2 JSONs which can't be parsed ``` can't parse JSON. Raw result: {"timestamp":1667985669923,"error-code":-1,"error-message":"Communication failure - UNAVAILABLE: io exception"}{"timestamp":"2022-11-09T09:21:09.937+0000","status":500,"error":"Internal Server Error","message":"UNAVAILABLE: io exception","path":"/api/v1/noviflow/1.1.1.1/logicalports"} ```
d149be4aacd25954eef9bee08f4a579219511f25
894ff16bb3a5f19b6e3bd854424743a08169c815
https://github.com/telstra/open-kilda/compare/d149be4aacd25954eef9bee08f4a579219511f25...894ff16bb3a5f19b6e3bd854424743a08169c815
diff --git a/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java b/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java index 976105b18..eb164b24e 100644 --- a/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java +++ b/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java @@ -30,13 +30,16 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import java.io.IOException; +import javax.servlet.http.HttpServletResponse; + @ControllerAdvice public class GrpcExceptionHandler extends ResponseEntityExceptionHandler { /** * Exception handler. */ - @ExceptionHandler + @ExceptionHandler(GrpcRequestFailureException.class) public ResponseEntity<Object> handleException(GrpcRequestFailureException ex, WebRequest request) { HttpStatus status; @@ -57,11 +60,10 @@ public class GrpcExceptionHandler extends ResponseEntityExceptionHandler { return makeExceptionalResponse(ex, makeErrorPayload(ex.getCode(), ex.getMessage()), status, request); } - - @ExceptionHandler - public ResponseEntity<Object> handleException(StatusRuntimeException ex, WebRequest request) { - GrpcMessageError body = makeErrorPayload(-1, format("Communication failure - %s", ex.getMessage())); - return makeExceptionalResponse(ex, body, HttpStatus.INTERNAL_SERVER_ERROR, request); + + @ExceptionHandler(StatusRuntimeException.class) + public void handleException(StatusRuntimeException ex, HttpServletResponse response) throws IOException { + response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value()); } @Override @@ -72,6 +74,7 @@ public class GrpcExceptionHandler extends ResponseEntityExceptionHandler { return makeExceptionalResponse(exception, error, status, request); } + private ResponseEntity<Object> makeExceptionalResponse( Exception ex, GrpcMessageError body, HttpStatus status, WebRequest request) { logger.error(format("Produce error response: %s", body));
['src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java']
{'.java': 1}
1
1
0
0
1
11,506,971
2,402,919
294,445
3,136
733
122
15
1
655
61
192
16
0
2
2023-01-18T22:24:30
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,043
telstra/open-kilda/5023/5022
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/5022
https://github.com/telstra/open-kilda/pull/5023
https://github.com/telstra/open-kilda/pull/5023
1
closes
Incorrect error message if flow max_latency is higher than max_latency_tier2
**Steps to reproduce:** 1. Try to create flow by API `POST /v2/flows` where flow max_latency is higher than max_latency_tier2 ``` { "flow_id": "nik", "source": { "inner_vlan_id": 0, "port_number": 10, "switch_id": "00:00:00:22:3d:6b:00:7a", "vlan_id": 0 }, "destination": { "inner_vlan_id": 0, "port_number": 10, "switch_id": "00:00:00:22:3d:6c:00:40", "vlan_id": 0 }, "maximum_bandwidth": 1000, "max_latency": 200, "max_latency_tier2": 100 } ``` **Expected result:** correct error message with latency in milliseconds `The maxLatency 200 is higher than maxLatencyTier2 100` **Actual result:** `"The maxLatency 200000000 is higher than maxLatencyTier2 100000000"`
6fd226f9f3641e58803283dc6f3914024a2f04c7
793c41caf94b57b25be54d93b14fcfbc86a6dc76
https://github.com/telstra/open-kilda/compare/6fd226f9f3641e58803283dc6f3914024a2f04c7...793c41caf94b57b25be54d93b14fcfbc86a6dc76
diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtils.java b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtils.java index 02775742e..27b1fb07e 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtils.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtils.java @@ -19,6 +19,8 @@ import static java.lang.String.format; import org.openkilda.messaging.error.ErrorType; +import java.util.concurrent.TimeUnit; + public final class ValidatorUtils { private ValidatorUtils() {} @@ -40,9 +42,9 @@ public final class ValidatorUtils { } if (maxLatency > maxLatencyTier2) { throw new InvalidFlowException( - format("The maxLatency %d is higher than maxLatencyTier2 %d", - maxLatency, - maxLatencyTier2), + format("The maxLatency %dms is higher than maxLatencyTier2 %dms", + TimeUnit.NANOSECONDS.toMillis(maxLatency), + TimeUnit.NANOSECONDS.toMillis(maxLatencyTier2)), ErrorType.DATA_INVALID); } } diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/test/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtilsTest.java b/src-java/flowhs-topology/flowhs-storm-topology/src/test/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtilsTest.java index 6f59cf997..29a07399a 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/test/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtilsTest.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/test/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtilsTest.java @@ -15,12 +15,40 @@ package org.openkilda.wfm.topology.flowhs.validation; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.junit.Test; public class ValidatorUtilsTest { + @Test public void maxLatencyValidatorMustAcceptEqualMaxLatencyAndMaxLatencyTier2() throws InvalidFlowException { // should not raise exception ValidatorUtils.maxLatencyValidator(500L, 500L); } + + @Test + public void maxLatencyValidatorThrowsExceptionIfMaxLatencyTier2HigherThanMaxLatency() throws InvalidFlowException { + Exception exception = assertThrows(InvalidFlowException.class, () -> { + ValidatorUtils.maxLatencyValidator(60000000L, 50000000L); + }); + assertThat(exception.getMessage(), equalTo("The maxLatency 60ms is higher than maxLatencyTier2 50ms")); + } + + @Test + public void maxLatencyValidatorThrowsExceptionIfMaxLatencyNullAndMaxLatencyTier2Not() throws InvalidFlowException { + Exception exception = assertThrows(InvalidFlowException.class, () -> { + ValidatorUtils.maxLatencyValidator(null, 50000000L); + }); + assertThat(exception.getMessage(), equalTo("maxLatencyTier2 property cannot be used without maxLatency")); + } + + @Test + public void maxLatencyValidatorMustAcceptMaxLatencyExistAndMaxLatencyTier2IsNull() throws InvalidFlowException { + // should not raise exception + ValidatorUtils.maxLatencyValidator(500L, null); + } + }
['src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtils.java', 'src-java/flowhs-topology/flowhs-storm-topology/src/test/java/org/openkilda/wfm/topology/flowhs/validation/ValidatorUtilsTest.java']
{'.java': 2}
2
2
0
0
2
11,506,866
2,402,897
294,443
3,136
448
86
8
1
745
80
252
30
0
1
2022-12-21T12:51:37
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,076
telstra/open-kilda/3678/3577
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3577
https://github.com/telstra/open-kilda/pull/3678
https://github.com/telstra/open-kilda/pull/3678
1
close
flowHistory: stateBefore is showing new value instead of old one
**Steps to reproduce:** 1. create a flow 2. update the flow (i.e. sourceVlan 30 -> 40) **Actual result:** flow is updated and valid but the `stateBefore` action in flowHistory is showing new value of vlan ``` { "type": "stateBefore", ... "sourceVlan": 40, ``` **Expected result:** The `stateBefore` section should show the old value of vlan ``` { "type": "stateBefore", ... "sourceVlan": 30, ```
6ddebb44595cfc994c5a7e7c57c81fdd7d8b13eb
67a3d643145c7ee01c8a77eea64df4e839c9b9f0
https://github.com/telstra/open-kilda/compare/6ddebb44595cfc994c5a7e7c57c81fdd7d8b13eb...67a3d643145c7ee01c8a77eea64df4e839c9b9f0
diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/update/actions/CompleteFlowPathRemovalAction.java b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/update/actions/CompleteFlowPathRemovalAction.java index 01250983f..cfc819fc2 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/update/actions/CompleteFlowPathRemovalAction.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/update/actions/CompleteFlowPathRemovalAction.java @@ -25,6 +25,7 @@ import org.openkilda.wfm.topology.flowhs.fsm.update.FlowUpdateContext; import org.openkilda.wfm.topology.flowhs.fsm.update.FlowUpdateFsm; import org.openkilda.wfm.topology.flowhs.fsm.update.FlowUpdateFsm.Event; import org.openkilda.wfm.topology.flowhs.fsm.update.FlowUpdateFsm.State; +import org.openkilda.wfm.topology.flowhs.mapper.RequestedFlowMapper; import lombok.extern.slf4j.Slf4j; import net.jodah.failsafe.RetryPolicy; @@ -55,6 +56,7 @@ public class CompleteFlowPathRemovalAction extends private void removeFlowPaths(FlowUpdateFsm stateMachine) { Flow flow = getFlow(stateMachine.getFlowId()); + Flow originalFlow = RequestedFlowMapper.INSTANCE.toFlow(stateMachine.getOriginalFlow()); FlowPath oldPrimaryForward = flow.getPath(stateMachine.getOldPrimaryForwardPath()).orElse(null); FlowPath oldPrimaryReverse = flow.getPath(stateMachine.getOldPrimaryReversePath()).orElse(null); @@ -70,16 +72,16 @@ public class CompleteFlowPathRemovalAction extends FlowPathPair pathsToDelete = FlowPathPair.builder().forward(oldPrimaryForward).reverse(oldPrimaryReverse).build(); deleteFlowPaths(pathsToDelete); - saveRemovalActionWithDumpToHistory(stateMachine, flow, pathsToDelete); + saveRemovalActionWithDumpToHistory(stateMachine, originalFlow, pathsToDelete); } else { log.debug("Completing removal of the flow path {} (no reverse pair)", oldPrimaryForward); deleteFlowPath(oldPrimaryForward); - saveRemovalActionWithDumpToHistory(stateMachine, flow, oldPrimaryForward); + saveRemovalActionWithDumpToHistory(stateMachine, originalFlow, oldPrimaryForward); } } else if (oldPrimaryReverse != null) { log.debug("Completing removal of the flow path {} (no forward pair)", oldPrimaryReverse); deleteFlowPath(oldPrimaryReverse); - saveRemovalActionWithDumpToHistory(stateMachine, flow, oldPrimaryReverse); + saveRemovalActionWithDumpToHistory(stateMachine, originalFlow, oldPrimaryReverse); } if (oldProtectedForward != null) { @@ -88,16 +90,16 @@ public class CompleteFlowPathRemovalAction extends FlowPathPair pathsToDelete = FlowPathPair.builder().forward(oldProtectedForward).reverse(oldProtectedReverse).build(); deleteFlowPaths(pathsToDelete); - saveRemovalActionWithDumpToHistory(stateMachine, flow, pathsToDelete); + saveRemovalActionWithDumpToHistory(stateMachine, originalFlow, pathsToDelete); } else { log.debug("Completing removal of the flow path {} (no reverse pair)", oldProtectedForward); deleteFlowPath(oldProtectedForward); - saveRemovalActionWithDumpToHistory(stateMachine, flow, oldProtectedForward); + saveRemovalActionWithDumpToHistory(stateMachine, originalFlow, oldProtectedForward); } } else if (oldProtectedReverse != null) { log.debug("Completing removal of the flow path {} (no forward pair)", oldProtectedReverse); deleteFlowPath(oldProtectedReverse); - saveRemovalActionWithDumpToHistory(stateMachine, flow, oldProtectedReverse); + saveRemovalActionWithDumpToHistory(stateMachine, originalFlow, oldProtectedReverse); } } }
['src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/update/actions/CompleteFlowPathRemovalAction.java']
{'.java': 1}
1
1
0
0
1
7,454,200
1,560,352
195,547
2,171
1,295
253
14
1
518
63
124
23
0
2
2020-08-10T15:04:49
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,083
telstra/open-kilda/3279/3278
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3278
https://github.com/telstra/open-kilda/pull/3279
https://github.com/telstra/open-kilda/pull/3279
1
close
Needs investigation: unhandled nullpointer exception in Floodlight
<details> <summary> error </summary> ``` { "_index": "kilda-2020.03.10", "_type": "kilda-FL", "_id": "AXDEivoQzzwg1EoeFaPK", "_version": 1, "_score": null, "_source": { "role": "FL_ROLE_IS_UNDEFINED", "level": "ERROR", "thread": "pool-5-thread-19", "message": "Unhandled exception into org.openkilda.floodlight.service.session.SessionService$1: null", "type": "kilda-FL", "tags": [ "kilda-floodlight" ], "@timestamp": "2020-03-10T13:03:27.116Z", "port": 59306, "@version": 1, "host": "172.22.0.15", "stack_trace": "java.lang.NullPointerException: null\\n\\tat org.openkilda.floodlight.service.session.Session.handleResponse(Session.java:167)\\n\\tat org.openkilda.floodlight.service.session.SwitchSessions.handleResponse(SwitchSessions.java:39)\\n\\tat org.openkilda.floodlight.service.session.SessionService.handleResponse(SessionService.java:91)\\n\\tat org.openkilda.floodlight.service.session.SessionService$1.call(SessionService.java:75)\\n\\tat org.openkilda.floodlight.service.session.SessionService$1.call(SessionService.java:72)\\n\\tat org.openkilda.floodlight.command.CommandWrapper.call(CommandWrapper.java:38)\\n\\tat org.openkilda.floodlight.command.CommandWrapper.call(CommandWrapper.java:26)\\n\\tat org.openkilda.floodlight.service.CommandProcessorService.lambda$executeOneShot$0(CommandProcessorService.java:130)\\n\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\\n\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\\n\\tat java.lang.Thread.run(Thread.java:748)\\n", "loggerName": "org.openkilda.floodlight.command.Command", "contextMap": { "correlation_id": "4d9811a1-6574-4fba-a3f3-ce8489ae51e9" }, "region": "FL_REGION_IS_UNDEFINED" }, "fields": { "@timestamp": [ 1583845407116 ] }, "highlight": { "level": [ "@kibana-highlighted-field@ERROR@/kibana-highlighted-field@" ] }, "sort": [ 1583845407116 ] } ``` </details> Correlation id search shows one related debug message: `org.openkilda.floodlight.service.of.InputService - receive message (dpId: 00:00:36:1c:7a:77:97:7e, xId: 0, version: OF_13, type: PACKET_IN)` No related negative consequences observed
dcc74e5b18a8ca9fb0dc0e39cd0669d9f7a6d8e1
0dd10ef41d0dee141749ecce7fed5ced46395e1d
https://github.com/telstra/open-kilda/compare/dcc74e5b18a8ca9fb0dc0e39cd0669d9f7a6d8e1...0dd10ef41d0dee141749ecce7fed5ced46395e1d
diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/service/session/Session.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/service/session/Session.java index f3fca253f..41029d81d 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/service/session/Session.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/service/session/Session.java @@ -164,7 +164,7 @@ public class Session implements AutoCloseable { } // check session completion (we have received all responses, if we got response for closing barrier request) - if (closingBarrier.isDone()) { + if (closingBarrier != null && closingBarrier.isDone()) { incompleteRequestsStream() .forEach(entry -> entry.complete(Optional.empty())); return true; @@ -181,7 +181,14 @@ public class Session implements AutoCloseable { CompletableFuture<Optional<OFMessage>> future = new CompletableFuture<>(); long xid = message.getXid(); - requestsByXid.put(xid, future); + if (xid == 0) { + log.error("Send OF request with xid:0 to {} - {}", sw.getId(), message); + } + CompletableFuture<Optional<OFMessage>> existing = requestsByXid.put(xid, future); + if (existing != null) { + log.error("Detect xid collision on {} xid:{} - can lead to unprocessed/missing response", sw.getId(), xid); + existing.complete(Optional.empty()); // to avoid infinite wait on replaced future object + } group.bindRequest(this, xid); return future; diff --git a/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/service/session/SessionServiceTest.java b/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/service/session/SessionServiceTest.java index ff43b1166..9e445c8af 100644 --- a/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/service/session/SessionServiceTest.java +++ b/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/service/session/SessionServiceTest.java @@ -39,6 +39,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.projectfloodlight.openflow.protocol.OFBadActionCode; +import org.projectfloodlight.openflow.protocol.OFBadRequestCode; import org.projectfloodlight.openflow.protocol.OFBarrierRequest; import org.projectfloodlight.openflow.protocol.OFFactory; import org.projectfloodlight.openflow.protocol.OFMessage; @@ -205,6 +206,38 @@ public class SessionServiceTest extends EasyMockSupport { } } + @Test + public void responseBeforeClose() throws Exception { + IOFSwitch sw = createMock(IOFSwitch.class); + setupSwitchMock(sw, dpId); + swWriteAlwaysSuccess(sw); + doneWithSetUp(sw); + + OFFactory ofFactory = sw.getOFFactory(); + CompletableFuture<Optional<OFMessage>> first; + CompletableFuture<Optional<OFMessage>> second; + try (Session session = subject.open(context, sw)) { + OFPacketOut egress = makePacketOut(ofFactory, 100); + first = session.write(egress); + + second = session.write(makePacketOut(ofFactory, 1)); + + // response before close + OFMessage ingress = ofFactory.errorMsgs().buildBadRequestErrorMsg() + .setXid(egress.getXid()) + .setCode(OFBadRequestCode.BAD_PORT) + .build(); + subject.handleResponse(dpId, ingress); + } + + completeSessions(sw); + + // received error response must be reported via future + expectExceptionResponse(first, SessionErrorResponseException.class); + // second request must be marker as completed + expectNoResponse(second); + } + @Test public void sessionBarrierWriteError() throws Exception { IOFSwitch sw = createMock(IOFSwitch.class); @@ -244,6 +277,12 @@ public class SessionServiceTest extends EasyMockSupport { } } + private void expectNoResponse(CompletableFuture<Optional<OFMessage>> future) + throws ExecutionException, InterruptedException { + Assert.assertTrue(future.isDone()); + Assert.assertFalse(future.get().isPresent()); + } + private void setupSwitchMock(IOFSwitch mock, DatapathId dpId) { expect(mock.getId()).andStubReturn(dpId); expect(mock.getOFFactory()).andStubReturn(OFFactoryVer13.INSTANCE);
['src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/service/session/Session.java', 'src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/service/session/SessionServiceTest.java']
{'.java': 2}
2
2
0
0
2
6,882,400
1,436,563
181,072
2,009
635
143
11
1
2,312
114
661
50
0
1
2020-03-10T15:17:41
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
10,024
serg-delft/andy/112/111
serg-delft
andy
https://github.com/SERG-Delft/andy/issues/111
https://github.com/SERG-Delft/andy/pull/112
https://github.com/SERG-Delft/andy/pull/112
1
closes
Assessing time message phrasing is incorrect
https://github.com/cse1110/andy/blob/4e53516cc38247149e281646700dd116d8167323/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java#L194 The word `question` should be replaced with `solution`.
e3095a639b2fff45a2df509a5fa1293fd005ed39
5b839c6ad771c0355b651748778840fd9edb9262
https://github.com/serg-delft/andy/compare/e3095a639b2fff45a2df509a5fa1293fd005ed39...5b839c6ad771c0355b651748778840fd9edb9262
diff --git a/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java b/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java index cad447d..52c9b6d 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java +++ b/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java @@ -191,7 +191,7 @@ public class StandardResultWriter implements ResultWriter { if(modeActionSelector(ctx)!=null) l(String.format("\\nAndy is running in %s mode and took %.1f seconds to assess your solution.", modeActionSelector(ctx).getMode().toString(), timeInSeconds)); else - l(String.format("\\nAndy took %.1f seconds to assess your question.", timeInSeconds)); + l(String.format("\\nAndy took %.1f seconds to assess your solution.", timeInSeconds)); } private void printMetaTestResults(Context ctx, MetaTestsResult metaTests) {
['src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java']
{'.java': 1}
1
1
0
0
1
195,939
40,216
5,916
89
197
40
2
1
221
9
70
3
1
0
2022-05-17T21:40:15
71
Java
{'Java': 1238634, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Makefile': 12592, 'Dockerfile': 1722, 'NASL': 1620, 'Shell': 63}
MIT License
10,025
serg-delft/andy/110/109
serg-delft
andy
https://github.com/SERG-Delft/andy/issues/109
https://github.com/SERG-Delft/andy/pull/110
https://github.com/SERG-Delft/andy/pull/110
1
closes
`assertNull` is not considered an assertion by code check
`assertNull` is not considered an assertion by the TestMethodsHaveAssertions code check: https://github.com/cse1110/andy/blob/main/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java This assertion method as well as other JUnit methods that have been missed should be added to this code check.
8932a6199da9c6e5760e646fe4ebbdd4b96baa55
594ae60cd6d906ca3f8c8373cf29c7630cb192ed
https://github.com/serg-delft/andy/compare/8932a6199da9c6e5760e646fe4ebbdd4b96baa55...594ae60cd6d906ca3f8c8373cf29c7630cb192ed
diff --git a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java index 76fa129..06db6b4 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java +++ b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java @@ -35,6 +35,14 @@ public class TestMethodsHaveAssertions extends WithinTestMethod { add("assertTrue"); add("assertFalse"); add("assertThrows"); + add("assertNull"); + add("assertArrayEquals"); + add("assertDoesNotThrow"); + add("assertIterableEquals"); + add("assertLinesMatch"); + add("assertNotNull"); + add("assertNotSame"); + add("assertSame"); // assertj add("assertThat");
['src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java']
{'.java': 1}
1
1
0
0
1
195,686
40,163
5,908
89
260
53
8
1
332
32
77
3
1
0
2022-05-16T20:53:45
71
Java
{'Java': 1238634, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Makefile': 12592, 'Dockerfile': 1722, 'NASL': 1620, 'Shell': 63}
MIT License
10,027
serg-delft/andy/101/99
serg-delft
andy
https://github.com/SERG-Delft/andy/issues/99
https://github.com/SERG-Delft/andy/pull/101
https://github.com/SERG-Delft/andy/pull/101
1
closes
Score of 100/100 is possible even if not everything is completed
Grades >= 99.5 get rounded up to 100. This is an edge case: any grade between 99 and 100 should be rounded down to 99, otherwise students may get confused and think that they have completed an exercise even if they haven't actually passed everything. For example: ``` Status: Done Andy v0.27.1-85578d2 (2022-04-25T09:29:42+0000) [...] --- Assessment Branch coverage: 20/21 (overall weight=0.10) Mutation coverage: 27/27 (overall weight=0.30) Code checks: 0/0 (overall weight=0.00) Meta tests: 17/17 (overall weight=0.60) Final grade: 100/100 Super congrats! [...] ``` Note the number of covered branches - only 20 out of 21 branches are covered, but due to the low weight of the branch coverage score, this branch is worth less than 0.5/100, so the final score becomes 99.5/100, which Andy incorrectly rounds up to 100/100.
b1d07f8e5a7703f30f1719afbe5b9166c68e0f23
1a2e3182b0b8552063485a3a0ccf1ea1d0b931b9
https://github.com/serg-delft/andy/compare/b1d07f8e5a7703f30f1719afbe5b9166c68e0f23...1a2e3182b0b8552063485a3a0ccf1ea1d0b931b9
diff --git a/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java b/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java index d6ccdc3..6e71536 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java +++ b/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java @@ -24,6 +24,11 @@ public class GradeCalculator { if(finalGrade < 0 || finalGrade > 100) throw new RuntimeException("Invalid grade calculation"); + // Grades between 99.5 and 100 should be rounded down to 99 instead of up + if (finalGrade == 100 && hasIncompleteComponents(gradeValues, weights)) { + finalGrade = 99; + } + return finalGrade; } @@ -79,4 +84,16 @@ public class GradeCalculator { return (float)checksPassed / totalChecks; } + /** + * @param gradeValues the grade values + * @param weights the weights + * @return whether any of the components with positive weight are incomplete + */ + private boolean hasIncompleteComponents(GradeValues gradeValues, GradeWeight weights) { + return weights.getBranchCoverageWeight() > 0.0f && gradeValues.getCoveredBranches() < gradeValues.getTotalBranches() || + weights.getMutationCoverageWeight() > 0.0f && gradeValues.getDetectedMutations() < gradeValues.getTotalMutations() || + weights.getMetaTestsWeight() > 0.0f && gradeValues.getMetaTestsPassed() < gradeValues.getTotalMetaTests() || + weights.getCodeChecksWeight() > 0.0f && gradeValues.getChecksPassed() < gradeValues.getTotalChecks(); + } + } diff --git a/src/test/java/unit/grade/GradeCalculatorTest.java b/src/test/java/unit/grade/GradeCalculatorTest.java index d834ba6..2d340ec 100644 --- a/src/test/java/unit/grade/GradeCalculatorTest.java +++ b/src/test/java/unit/grade/GradeCalculatorTest.java @@ -3,6 +3,7 @@ package unit.grade; import nl.tudelft.cse1110.andy.grade.GradeCalculator; import nl.tudelft.cse1110.andy.grade.GradeValues; import nl.tudelft.cse1110.andy.grade.GradeWeight; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -81,4 +82,52 @@ public class GradeCalculatorTest { of(25, 25, 55, 55, 100, 100, 2, 5, 94) // 0.4*1 + 0.3*1 + 0.2*1 + 0.1*(2/5) = 0.94 --> 94 ); } + + /* + * Test where the grade is between 99.5 and 100, should be rounded down to 99 and not + * rounded up to 100, as 100 should only be achievable if everything + * with a positive weight is fully completed. + */ + @Test + void withGradeBetween99And100() { + GradeWeight weights = new GradeWeight(0.1f, 0.3f, 0.6f, 0.0f); + + GradeValues grades = new GradeValues(); + grades.setBranchGrade(20, 21); + grades.setMutationGrade(27, 27); + grades.setMetaGrade(17, 17); + grades.setCheckGrade(0, 0); + + int finalGrade = new GradeCalculator().calculateFinalGrade(grades, weights); + + assertThat(finalGrade).isEqualTo(99); + } + + @ParameterizedTest + @MethodSource("zeroWeights") + void withZeroWeights(int coveredBranches, int totalBranches, + int detectedMutations, int totalMutations, + int metaTestsPassed, int totalMetaTests, + int checksPassed, int totalChecks, int expectedGrade) { + + GradeWeight weights = new GradeWeight(0.4f, 0.0f, 0.5f, 0.1f); + + GradeValues grades = new GradeValues(); + grades.setBranchGrade(coveredBranches, totalBranches); + grades.setMutationGrade(detectedMutations, totalMutations); + grades.setMetaGrade(metaTestsPassed, totalMetaTests); + grades.setCheckGrade(checksPassed, totalChecks); + + int finalGrade = new GradeCalculator().calculateFinalGrade(grades, weights); + + assertThat(finalGrade).isEqualTo(expectedGrade); + } + + private static Stream<Arguments> zeroWeights() { + return Stream.of( + of(25, 25, 2, 55, 100, 100, 5, 5, 100), // 0.4*1 + 0*(2/55) + 0.5*1 + 0.1*1 = 1.0 --> 100 + of(25, 25, 2, 55, 100, 100, 4, 5, 98), // 0.4*1 + 0*(2/55) + 0.5*1 + 0.1*(4/5) = 0.98 --> 98 + of(25, 25, 55, 55, 100, 100, 4, 5, 98) // 0.4*1 + 0*1 + 0.5*1 + 0.1*(4/5) = 0.98 --> 98 + ); + } }
['src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java', 'src/test/java/unit/grade/GradeCalculatorTest.java']
{'.java': 2}
2
2
0
0
2
194,190
39,847
5,881
89
999
226
17
1
860
129
248
25
0
1
2022-04-29T23:05:50
71
Java
{'Java': 1238634, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Makefile': 12592, 'Dockerfile': 1722, 'NASL': 1620, 'Shell': 63}
MIT License
2,069
telstra/open-kilda/3853/3871
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3871
https://github.com/telstra/open-kilda/pull/3853
https://github.com/telstra/open-kilda/pull/3853
1
closes
[Server42] disabling 'server42_flow_rtt' in feature toggle leads to excess rules on a switch with enabled 'server42_flow_rtt'
**Steps to reproduce:** 1. enable `server42_flow_rtt` in feature toggle and on a switch; 2. make sure the switch is valid; 3. disable the `server42_flow_rtt` feature toggle; **Actual result:** The switch has the excess server42 rules ``` "excess": [ -9223372036854775783, -9223372036854775782, -9223372036854775781 ], "excess-hex": [ "8000000000000019", "800000000000001a", "800000000000001b" ], ``` **Expected result:** The switch should be valid after disabling the 'server42_flow_rtt' feature toggle
1b6441b8d478b2360e947dbf138c23004692121f
95965992ce961d1a1159b15683baf51ad46709a3
https://github.com/telstra/open-kilda/compare/1b6441b8d478b2360e947dbf138c23004692121f...95965992ce961d1a1159b15683baf51ad46709a3
diff --git a/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/GetExpectedDefaultRulesRequest.java b/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/GetExpectedDefaultRulesRequest.java index cb00cd99b..2cb382c6d 100644 --- a/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/GetExpectedDefaultRulesRequest.java +++ b/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/GetExpectedDefaultRulesRequest.java @@ -44,8 +44,11 @@ public class GetExpectedDefaultRulesRequest extends CommandData { @JsonProperty("switch_arp") private boolean switchArp; - @JsonProperty("server42_flow_rtt") - private boolean server42FlowRtt; + @JsonProperty("server42_flow_rtt_feature_toggle") + private boolean server42FlowRttFeatureToggle; + + @JsonProperty("server42_flow_rtt_switch_property") + private boolean server42FlowRttSwitchProperty; @JsonProperty("server42_port") private Integer server42Port; @@ -76,7 +79,10 @@ public class GetExpectedDefaultRulesRequest extends CommandData { @JsonProperty("multi_table") boolean multiTable, @JsonProperty("switch_lldp") boolean switchLldp, @JsonProperty("switch_arp") boolean switchArp, - @JsonProperty("server42_flow_rtt") boolean server42FlowRtt, + @JsonProperty("server42_flow_rtt_feature_toggle") + boolean server42FlowRttFeatureToggle, + @JsonProperty("server42_flow_rtt_switch_property") + boolean server42FlowRttSwitchProperty, @JsonProperty("server42_port") Integer server42Port, @JsonProperty("server42_vlan") Integer server42Vlan, @JsonProperty("server42_mac_address") MacAddress server42MacAddress, @@ -90,7 +96,8 @@ public class GetExpectedDefaultRulesRequest extends CommandData { this.multiTable = multiTable; this.switchLldp = switchLldp; this.switchArp = switchArp; - this.server42FlowRtt = server42FlowRtt; + this.server42FlowRttFeatureToggle = server42FlowRttFeatureToggle; + this.server42FlowRttSwitchProperty = server42FlowRttSwitchProperty; this.server42Port = server42Port; this.server42Vlan = server42Vlan; this.server42MacAddress = server42MacAddress; diff --git a/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesDeleteRequest.java b/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesDeleteRequest.java index a4e544e2b..8dae46093 100644 --- a/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesDeleteRequest.java +++ b/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesDeleteRequest.java @@ -58,8 +58,11 @@ public class SwitchRulesDeleteRequest extends CommandData { @JsonProperty("switch_arp") private boolean switchArp = false; - @JsonProperty("server42_flow_rtt") - private boolean server42FlowRtt = false; + @JsonProperty("server42_flow_rtt_feature_toggle") + private boolean server42FlowRttFeatureToggle = false; + + @JsonProperty("server42_flow_rtt_switch_property") + private boolean server42FlowRttSwitchProperty = false; @JsonProperty("server42_port") private Integer server42Port; diff --git a/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesInstallRequest.java b/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesInstallRequest.java index e89d8beab..7d23982d3 100644 --- a/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesInstallRequest.java +++ b/src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesInstallRequest.java @@ -52,8 +52,11 @@ public class SwitchRulesInstallRequest extends CommandData { @JsonProperty("switch_arp") private boolean switchArp = false; - @JsonProperty("server42_flow_rtt") - private boolean server42FlowRtt = false; + @JsonProperty("server42_flow_rtt_feature_toggle") + private boolean server42FlowRttFeatureToggle = false; + + @JsonProperty("server42_flow_rtt_switch_property") + private boolean server42FlowRttSwitchProperty = false; @JsonProperty("server42_port") private Integer server42Port; diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java index 95d04de40..02876d96b 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java @@ -756,18 +756,22 @@ class RecordHandler implements Runnable { Integer server42Port = request.getServer42Port(); Integer server42Vlan = request.getServer42Vlan(); MacAddress server42MacAddress = request.getServer42MacAddress(); - if (request.isServer42FlowRtt() && server42Port != null && server42Vlan != null - && server42MacAddress != null) { + + if (request.isServer42FlowRttFeatureToggle()) { installedRules.add( processInstallDefaultFlowByCookie(request.getSwitchId(), SERVER_42_TURNING_COOKIE)); - installedRules.add(switchManager.installServer42OutputVlanFlow( - dpid, server42Port, server42Vlan, server42MacAddress)); - installedRules.add(switchManager.installServer42OutputVxlanFlow( - dpid, server42Port, server42Vlan, server42MacAddress)); - - for (Integer port : request.getServer42FlowRttPorts()) { - installedRules.add(switchManager.installServer42InputFlow( - dpid, server42Port, port, server42MacAddress)); + + if (request.isServer42FlowRttSwitchProperty() && server42Port != null && server42Vlan != null + && server42MacAddress != null) { + installedRules.add(switchManager.installServer42OutputVlanFlow( + dpid, server42Port, server42Vlan, server42MacAddress)); + installedRules.add(switchManager.installServer42OutputVxlanFlow( + dpid, server42Port, server42Vlan, server42MacAddress)); + + for (Integer port : request.getServer42FlowRttPorts()) { + installedRules.add(switchManager.installServer42InputFlow( + dpid, server42Port, port, server42MacAddress)); + } } } } @@ -951,7 +955,8 @@ class RecordHandler implements Runnable { removedRules.addAll(switchManager.deleteDefaultRules(dpid, request.getIslPorts(), request.getFlowPorts(), request.getFlowLldpPorts(), request.getFlowArpPorts(), request.getServer42FlowRttPorts(), request.isMultiTable(), request.isSwitchLldp(), - request.isSwitchArp(), request.isServer42FlowRtt())); + request.isSwitchArp(), + request.isServer42FlowRttFeatureToggle() && request.isServer42FlowRttSwitchProperty())); } } @@ -1008,16 +1013,19 @@ class RecordHandler implements Runnable { Integer server42Port = request.getServer42Port(); Integer server42Vlan = request.getServer42Vlan(); MacAddress server42MacAddress = request.getServer42MacAddress(); - if (request.isServer42FlowRtt() && server42Port != null && server42Vlan != null - && server42MacAddress != null) { + if (request.isServer42FlowRttFeatureToggle()) { switchManager.installServer42TurningFlow(dpid); - switchManager.installServer42OutputVlanFlow( - dpid, server42Port, server42Vlan, server42MacAddress); - switchManager.installServer42OutputVxlanFlow( - dpid, server42Port, server42Vlan, server42MacAddress); - for (Integer port : request.getServer42FlowRttPorts()) { - switchManager.installServer42InputFlow(dpid, server42Port, port, server42MacAddress); + if (request.isServer42FlowRttSwitchProperty() && server42Port != null && server42Vlan != null + && server42MacAddress != null) { + switchManager.installServer42OutputVlanFlow( + dpid, server42Port, server42Vlan, server42MacAddress); + switchManager.installServer42OutputVxlanFlow( + dpid, server42Port, server42Vlan, server42MacAddress); + + for (Integer port : request.getServer42FlowRttPorts()) { + switchManager.installServer42InputFlow(dpid, server42Port, port, server42MacAddress); + } } } } @@ -1073,7 +1081,8 @@ class RecordHandler implements Runnable { boolean multiTable = request.isMultiTable(); boolean switchLldp = request.isSwitchLldp(); boolean switchArp = request.isSwitchArp(); - boolean server42FlowRtt = request.isServer42FlowRtt(); + boolean server42FlowRttFeatureToggle = request.isServer42FlowRttFeatureToggle(); + boolean server42FlowRttSwitchProperty = request.isServer42FlowRttSwitchProperty(); Integer server42Port = request.getServer42Port(); Integer server42Vlan = request.getServer42Vlan(); MacAddress server42MacAddress = request.getServer42MacAddress(); @@ -1103,11 +1112,9 @@ class RecordHandler implements Runnable { defaultRules.add(context.getSwitchManager().buildArpInputCustomerFlow(dpid, port)); } } - if (server42FlowRtt) { - defaultRules.addAll(context.getSwitchManager() - .buildExpectedServer42Flows(dpid, server42Port, server42Vlan, server42MacAddress, - server42FlowRttPorts)); - } + defaultRules.addAll(context.getSwitchManager() + .buildExpectedServer42Flows(dpid, server42FlowRttFeatureToggle, server42FlowRttSwitchProperty, + server42Port, server42Vlan, server42MacAddress, server42FlowRttPorts)); List<FlowEntry> flows = defaultRules.stream() .map(OfFlowStatsMapper.INSTANCE::toFlowEntry) diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/ISwitchManager.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/ISwitchManager.java index f2b9e05ef..5e9b2283c 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/ISwitchManager.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/ISwitchManager.java @@ -424,15 +424,18 @@ public interface ISwitchManager extends IFloodlightService { * Build all expected Server 42 rules. * * @param dpid switch id - * @param server42Port server 42 port - * @param server42Vlan vlan of packer received from server 42 - * @param server42MacAddress mac address of server 42 + * @param server42FlowRttFeatureToggle server 42 feature toggle + * @param server42FlowRttSwitchProperty server 42 switch property + * @param server42Port server 42 port. Could be null if server42FlowRttSwitchProperty is false + * @param server42Vlan vlan of packer received from server 42. + * Could be null if server42FlowRttSwitchProperty is false + * @param server42MacAddress mac address of server 42. Could be null if server42FlowRttSwitchProperty is false * @param customerPorts switch ports with enabled server 42 ping * @return modification command */ List<OFFlowMod> buildExpectedServer42Flows( - DatapathId dpid, int server42Port, int server42Vlan, MacAddress server42MacAddress, - Set<Integer> customerPorts) + DatapathId dpid, boolean server42FlowRttFeatureToggle, boolean server42FlowRttSwitchProperty, + Integer server42Port, Integer server42Vlan, MacAddress server42MacAddress, Set<Integer> customerPorts) throws SwitchNotFoundException; /** diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchManager.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchManager.java index 52dc453a6..83f9251f3 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchManager.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchManager.java @@ -1773,18 +1773,25 @@ public class SwitchManager implements IFloodlightModule, IFloodlightService, ISw @Override public List<OFFlowMod> buildExpectedServer42Flows( - DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, + DatapathId dpid, boolean server42FlowRttFeatureToggle, boolean server42FlowRttSwitchProperty, + Integer server42Port, Integer server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts) throws SwitchNotFoundException { List<SwitchFlowGenerator> generators = new ArrayList<>(); - for (Integer port : customerPorts) { - generators.add(switchFlowFactory.getServer42InputFlowGenerator(server42Port, port, server42MacAddress)); - } - generators.add(switchFlowFactory.getServer42TurningFlowGenerator()); - generators.add(switchFlowFactory.getServer42OutputVlanFlowGenerator( - server42Port, server42Vlan, server42MacAddress)); - generators.add(switchFlowFactory.getServer42OutputVxlanFlowGenerator( - server42Port, server42Vlan, server42MacAddress)); + if (server42FlowRttFeatureToggle) { + generators.add(switchFlowFactory.getServer42TurningFlowGenerator()); + + if (server42FlowRttSwitchProperty) { + for (Integer port : customerPorts) { + generators.add(switchFlowFactory.getServer42InputFlowGenerator( + server42Port, port, server42MacAddress)); + } + generators.add(switchFlowFactory.getServer42OutputVlanFlowGenerator( + server42Port, server42Vlan, server42MacAddress)); + generators.add(switchFlowFactory.getServer42OutputVxlanFlowGenerator( + server42Port, server42Vlan, server42MacAddress)); + } + } IOFSwitch sw = lookupSwitch(dpid); return generators.stream() diff --git a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopology.java b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopology.java index 5424742ad..0ef489304 100644 --- a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopology.java +++ b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopology.java @@ -229,6 +229,7 @@ public class NbWorkerTopology extends AbstractTopology<NbWorkerTopologyConfig> { .shuffleGrouping(SWITCHES_BOLT_NAME, StreamType.TO_SWITCH_MANAGER.toString()) .shuffleGrouping(ROUTER_BOLT_NAME, StreamType.ERROR.toString()) .shuffleGrouping(FEATURE_TOGGLES_BOLT_NAME, StreamType.ERROR.toString()) + .shuffleGrouping(FEATURE_TOGGLES_BOLT_NAME, StreamType.TO_SWITCH_MANAGER.toString()) .shuffleGrouping(KILDA_CONFIG_BOLT_NAME, StreamType.ERROR.toString()) .shuffleGrouping(PATHS_BOLT_NAME, StreamType.ERROR.toString()) .shuffleGrouping(HISTORY_BOLT_NAME, StreamType.ERROR.toString()) diff --git a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/bolts/FeatureTogglesBolt.java b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/bolts/FeatureTogglesBolt.java index b52692701..7ef7152b8 100644 --- a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/bolts/FeatureTogglesBolt.java +++ b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/bolts/FeatureTogglesBolt.java @@ -15,6 +15,7 @@ package org.openkilda.wfm.topology.nbworker.bolts; +import org.openkilda.messaging.command.switches.SwitchValidateRequest; import org.openkilda.messaging.error.ErrorType; import org.openkilda.messaging.error.MessageException; import org.openkilda.messaging.info.InfoData; @@ -25,9 +26,11 @@ import org.openkilda.messaging.nbtopology.request.CreateOrUpdateFeatureTogglesRe import org.openkilda.messaging.nbtopology.request.GetFeatureTogglesRequest; import org.openkilda.messaging.nbtopology.response.FeatureTogglesResponse; import org.openkilda.model.FeatureToggles; +import org.openkilda.model.SwitchId; import org.openkilda.persistence.PersistenceManager; import org.openkilda.wfm.error.FeatureTogglesNotFoundException; import org.openkilda.wfm.share.mappers.FeatureTogglesMapper; +import org.openkilda.wfm.share.utils.KeyProvider; import org.openkilda.wfm.topology.nbworker.StreamType; import org.openkilda.wfm.topology.nbworker.services.FeatureTogglesService; import org.openkilda.wfm.topology.nbworker.services.IFeatureTogglesCarrier; @@ -94,6 +97,18 @@ public class FeatureTogglesBolt extends PersistenceOperationsBolt implements IFe emit(STREAM_NOTIFICATION_ID, getCurrentTuple(), makeNotificationTuple(payload)); } + @Override + public void requestSwitchSync(SwitchId switchId) { + SwitchValidateRequest data = SwitchValidateRequest.builder() + .switchId(switchId) + .performSync(true) + .processMeters(true) + .removeExcess(true) + .build(); + getOutput().emit(StreamType.TO_SWITCH_MANAGER.toString(), getCurrentTuple(), + new Values(data, KeyProvider.generateChainedKey(getCorrelationId()))); + } + // -- private -- private Values makeNotificationTuple(InfoData payload) { @@ -106,5 +121,7 @@ public class FeatureTogglesBolt extends PersistenceOperationsBolt implements IFe public void declareOutputFields(OutputFieldsDeclarer declarer) { super.declareOutputFields(declarer); declarer.declareStream(STREAM_NOTIFICATION_ID, STREAM_NOTIFICATION_FIELDS); + declarer.declareStream(StreamType.TO_SWITCH_MANAGER.toString(), + new Fields(MessageEncoder.FIELD_ID_PAYLOAD, MessageEncoder.FIELD_ID_CONTEXT)); } } diff --git a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FeatureTogglesService.java b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FeatureTogglesService.java index 764f9fc90..d2d856ca2 100644 --- a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FeatureTogglesService.java +++ b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FeatureTogglesService.java @@ -17,13 +17,16 @@ package org.openkilda.wfm.topology.nbworker.services; import org.openkilda.model.FeatureToggles; import org.openkilda.model.FeatureToggles.FeatureTogglesCloner; +import org.openkilda.model.Switch; import org.openkilda.persistence.repositories.FeatureTogglesRepository; import org.openkilda.persistence.repositories.RepositoryFactory; +import org.openkilda.persistence.repositories.SwitchRepository; import org.openkilda.persistence.tx.TransactionManager; import org.openkilda.wfm.error.FeatureTogglesNotFoundException; import lombok.extern.slf4j.Slf4j; +import java.util.Collection; import java.util.Optional; @Slf4j @@ -31,12 +34,14 @@ public class FeatureTogglesService { private final IFeatureTogglesCarrier carrier; private FeatureTogglesRepository featureTogglesRepository; + private SwitchRepository switchRepository; private TransactionManager transactionManager; public FeatureTogglesService(IFeatureTogglesCarrier carrier, RepositoryFactory repositoryFactory, TransactionManager transactionManager) { this.carrier = carrier; this.featureTogglesRepository = repositoryFactory.createFeatureTogglesRepository(); + this.switchRepository = repositoryFactory.createSwitchRepository(); this.transactionManager = transactionManager; } @@ -71,6 +76,15 @@ public class FeatureTogglesService { if (!before.equals(after)) { log.info("Emit feature-toggles update notification - toggles:{}", after); carrier.featureTogglesUpdateNotification(after); + + if (before.getServer42FlowRtt() != after.getServer42FlowRtt()) { + Collection<Switch> switches = switchRepository.findActive(); + + for (Switch sw : switches) { + log.info("Emit switch {} sync command", sw.getSwitchId()); + carrier.requestSwitchSync(sw.getSwitchId()); + } + } } return after; } diff --git a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/IFeatureTogglesCarrier.java b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/IFeatureTogglesCarrier.java index ffdb3bb2e..9fef92a89 100644 --- a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/IFeatureTogglesCarrier.java +++ b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/IFeatureTogglesCarrier.java @@ -16,7 +16,10 @@ package org.openkilda.wfm.topology.nbworker.services; import org.openkilda.model.FeatureToggles; +import org.openkilda.model.SwitchId; public interface IFeatureTogglesCarrier { void featureTogglesUpdateNotification(FeatureToggles toggles); + + void requestSwitchSync(SwitchId switchId); } diff --git a/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/fsm/SwitchValidateFsm.java b/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/fsm/SwitchValidateFsm.java index 64e8cdadf..6b62e6ab9 100644 --- a/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/fsm/SwitchValidateFsm.java +++ b/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/fsm/SwitchValidateFsm.java @@ -79,7 +79,6 @@ import org.squirrelframework.foundation.fsm.impl.AbstractStateMachine; import java.util.HashSet; import java.util.List; -import java.util.Optional; import java.util.Set; @Slf4j @@ -334,9 +333,7 @@ public class SwitchValidateFsm extends AbstractStateMachine< final SwitchId switchId = getSwitchId(); log.info("Sending requests to get expected switch service rules (switch={}, key={})", switchId, key); - - Optional<FeatureToggles> featureToggles = featureTogglesRepository.find(); - boolean isServer42FlowRtt = switchProperties.isServer42FlowRtt() && featureToggles + boolean isServer42FlowRttFeatureToggle = featureTogglesRepository.find() .map(FeatureToggles::getServer42FlowRtt) .orElse(FeatureToggles.DEFAULTS.getServer42FlowRtt()); @@ -346,7 +343,8 @@ public class SwitchValidateFsm extends AbstractStateMachine< .multiTable(isMultiTable) .switchLldp(isSwitchLldp) .switchArp(isSwitchArp) - .server42FlowRtt(isServer42FlowRtt) + .server42FlowRttFeatureToggle(isServer42FlowRttFeatureToggle) + .server42FlowRttSwitchProperty(switchProperties.isServer42FlowRtt()) .server42Port(switchProperties.getServer42Port()) .server42Vlan(switchProperties.getServer42Vlan()) .server42MacAddress(switchProperties.getServer42MacAddress()); @@ -366,7 +364,7 @@ public class SwitchValidateFsm extends AbstractStateMachine< if (flowSide.isMultiTableSegment()) { payload.flowPort(endpoint.getPortNumber()); - if (isServer42FlowRtt && !flow.isOneSwitchFlow()) { + if (isServer42FlowRttFeatureToggle && switchProperties.isServer42FlowRtt() && !flow.isOneSwitchFlow()) { payload.server42FlowRttPort(endpoint.getPortNumber()); } } diff --git a/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/service/impl/SwitchRuleServiceImpl.java b/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/service/impl/SwitchRuleServiceImpl.java index 80c8d544b..8385093e0 100644 --- a/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/service/impl/SwitchRuleServiceImpl.java +++ b/src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/service/impl/SwitchRuleServiceImpl.java @@ -75,14 +75,15 @@ public class SwitchRuleServiceImpl implements SwitchRuleService { return; } Optional<SwitchProperties> switchProperties = switchPropertiesRepository.findBySwitchId(switchId); - if (switchProperties.isPresent()) { - boolean server42Rtt = featureTogglesRepository.find().map(FeatureToggles::getServer42FlowRtt).orElse(false) - && switchProperties.get().isServer42FlowRtt(); + boolean server42FeatureToggle = featureTogglesRepository.find() + .map(FeatureToggles::getServer42FlowRtt).orElse(false); + data.setServer42FlowRttFeatureToggle(server42FeatureToggle); + if (switchProperties.isPresent()) { data.setMultiTable(switchProperties.get().isMultiTable()); data.setSwitchLldp(switchProperties.get().isSwitchLldp()); data.setSwitchArp(switchProperties.get().isSwitchArp()); - data.setServer42FlowRtt(server42Rtt); + data.setServer42FlowRttSwitchProperty(switchProperties.get().isServer42FlowRtt()); data.setServer42Port(switchProperties.get().getServer42Port()); data.setServer42Vlan(switchProperties.get().getServer42Vlan()); data.setServer42MacAddress(switchProperties.get().getServer42MacAddress()); @@ -92,7 +93,7 @@ public class SwitchRuleServiceImpl implements SwitchRuleService { Set<Integer> flowArpPorts = new HashSet<>(); Set<Integer> server42FlowPorts = new HashSet<>(); fillFlowPorts(switchProperties.get(), flowPaths, flowPorts, flowLldpPorts, flowArpPorts, server42FlowPorts, - server42Rtt); + server42FeatureToggle && switchProperties.get().isServer42FlowRtt()); data.setFlowPorts(flowPorts); data.setFlowLldpPorts(flowLldpPorts); @@ -118,14 +119,16 @@ public class SwitchRuleServiceImpl implements SwitchRuleService { return; } Optional<SwitchProperties> switchProperties = switchPropertiesRepository.findBySwitchId(switchId); - if (switchProperties.isPresent()) { - boolean server42Rtt = featureTogglesRepository.find().map(FeatureToggles::getServer42FlowRtt).orElse(false) - && switchProperties.get().isServer42FlowRtt(); + boolean server42FeatureToggle = featureTogglesRepository.find() + .map(FeatureToggles::getServer42FlowRtt).orElse(false); + data.setServer42FlowRttFeatureToggle(server42FeatureToggle); + + if (switchProperties.isPresent()) { data.setMultiTable(switchProperties.get().isMultiTable()); data.setSwitchLldp(switchProperties.get().isSwitchLldp()); data.setSwitchArp(switchProperties.get().isSwitchArp()); - data.setServer42FlowRtt(server42Rtt); + data.setServer42FlowRttSwitchProperty(switchProperties.get().isServer42FlowRtt()); data.setServer42Port(switchProperties.get().getServer42Port()); data.setServer42Vlan(switchProperties.get().getServer42Vlan()); data.setServer42MacAddress(switchProperties.get().getServer42MacAddress()); @@ -135,7 +138,7 @@ public class SwitchRuleServiceImpl implements SwitchRuleService { Set<Integer> flowArpPorts = new HashSet<>(); Set<Integer> server42FlowPorts = new HashSet<>(); fillFlowPorts(switchProperties.get(), flowPaths, flowPorts, flowLldpPorts, flowArpPorts, server42FlowPorts, - server42Rtt); + server42FeatureToggle && switchProperties.get().isServer42FlowRtt()); data.setFlowPorts(flowPorts); data.setFlowLldpPorts(flowLldpPorts); data.setFlowArpPorts(flowArpPorts);
['src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesInstallRequest.java', 'src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/GetExpectedDefaultRulesRequest.java', 'src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/IFeatureTogglesCarrier.java', 'src-java/floodlight-service/floodlight-api/src/main/java/org/openkilda/messaging/command/switches/SwitchRulesDeleteRequest.java', 'src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/service/impl/SwitchRuleServiceImpl.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/ISwitchManager.java', 'src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/fsm/SwitchValidateFsm.java', 'src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/bolts/FeatureTogglesBolt.java', 'src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FeatureTogglesService.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchManager.java', 'src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopology.java']
{'.java': 12}
12
12
0
0
12
8,208,315
1,712,711
215,048
2,324
12,276
2,504
192
12
625
62
161
24
0
1
2020-11-15T23:54:42
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
10,029
serg-delft/andy/86/83
serg-delft
andy
https://github.com/SERG-Delft/andy/issues/83
https://github.com/SERG-Delft/andy/pull/86
https://github.com/SERG-Delft/andy/pull/86
1
fixes
Overload Andy constructor
Overload the Andy constructor in order to preserve backward compatibility after the changes introduced in #70 as those changes break the Maven plugin
28faca02fe2c80e58ca06a01390cf6007fb96f32
86803722431cb76859ee539f530eeeb82c7047ee
https://github.com/serg-delft/andy/compare/28faca02fe2c80e58ca06a01390cf6007fb96f32...86803722431cb76859ee539f530eeeb82c7047ee
diff --git a/src/main/java/nl/tudelft/cse1110/andy/Andy.java b/src/main/java/nl/tudelft/cse1110/andy/Andy.java index 1aaef12..342db50 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/Andy.java +++ b/src/main/java/nl/tudelft/cse1110/andy/Andy.java @@ -33,10 +33,18 @@ public class Andy { this.metaData = metaData; } + public Andy(Action action, String workDir, String outputDir, List<String> librariesToBeIncluded, ResultWriter writer) { + this(action, workDir, outputDir, librariesToBeIncluded, writer, SubmissionMetaData.empty()); + } + public Andy(Action action, String workDir, String outputDir, ResultWriter writer, SubmissionMetaData metaData) { this(action, workDir, outputDir, null, writer, metaData); } + public Andy(Action action, String workDir, String outputDir, ResultWriter writer) { + this(action, workDir, outputDir, null, writer); + } + public void run() { Context ctx = buildContext(); diff --git a/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java b/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java index f25a358..5eb64de 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java +++ b/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java @@ -10,4 +10,8 @@ public class SubmissionMetaData { this.studentId = studentId; this.exercise = exercise; } + + public static SubmissionMetaData empty() { + return new SubmissionMetaData(null, null, null); + } } \\ No newline at end of file
['src/main/java/nl/tudelft/cse1110/andy/Andy.java', 'src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java']
{'.java': 2}
2
2
0
0
2
194,498
39,940
5,901
88
504
107
12
2
149
23
25
1
0
0
2021-12-21T22:39:27
71
Java
{'Java': 1238634, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Makefile': 12592, 'Dockerfile': 1722, 'NASL': 1620, 'Shell': 63}
MIT License
2,077
telstra/open-kilda/3664/3603
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3603
https://github.com/telstra/open-kilda/pull/3664
https://github.com/telstra/open-kilda/pull/3664
1
close
Unhandled exception in org.openkilda.wfm.topology.nbworker.bolts.FlowOperationsBolt
Sometimes we receive the below exception. [error11153.txt](https://github.com/telstra/open-kilda/files/4884154/error11153.txt) search reference: ``` Duplicate key Flow(entityId=22849, flowId=03Jul135507_722_capsicum2093, srcSwitch=Switch(entityId=83, switchId=00:00:00:00:00:00:00:01, status=INACTIVE, socketAddress=/172.18.0.24:40782, hostname=lab_service-1.kilda-controller_default, controller=null, description=Nicira, Inc. OF_13 2.12.0, ofVersion=OF_13, ofDescriptionManufacturer=Nicira, Inc., ofDescriptionHardware=Open vSwitch, ofDescriptionSoftware=2.12.0, ofDescriptionSerialNumber=None, ofDescriptionDatapath=None, features=[RESET_COUNTS_FLAG, GROUP_PACKET_OUT_CONTROLLER, PKTPS_FLAG, METERS, MULTI_TABLE, MATCH_UDP_PORT], underMaintenance=false, timeCreate=null, timeModify=null, pop=null, latitude=0.0, longitude=0.0, street=null, city=null, country=null), destSwitch=Switch(entityId=83, switchId=00:00:00:00:00:00:00:01, status=INACTIVE, socketAddress=/172.18.0.24:40782, hostname... ```
f7f09f0666353009488a47612361ab2f3cbdded1
4494aca7b97b961c7e6a8ed81850e56bb68a509d
https://github.com/telstra/open-kilda/compare/f7f09f0666353009488a47612361ab2f3cbdded1...4494aca7b97b961c7e6a8ed81850e56bb68a509d
diff --git a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FlowOperationsService.java b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FlowOperationsService.java index a34dd59e6..3621c6c3d 100644 --- a/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FlowOperationsService.java +++ b/src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FlowOperationsService.java @@ -72,6 +72,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; @Slf4j public class FlowOperationsService { @@ -182,26 +183,27 @@ public class FlowOperationsService { if (!switchRepository.findById(switchId).isPresent()) { throw new SwitchNotFoundException(switchId); } - Set<Flow> flows = new HashSet<>(); if (port != null) { - flowPathRepository.findBySegmentEndpoint(switchId, port).stream() - // NOTE(tdurakov): filter out paths here that are orphaned for the flow - .filter(flowPath -> flowPath.getFlow().isActualPathId(flowPath.getPathId())) - .map(FlowPath::getFlow) - .forEach(flows::add); - flows.addAll(flowRepository.findByEndpoint(switchId, port)); + return getFlowsForEndpoint(flowPathRepository.findBySegmentEndpoint(switchId, port), + flowRepository.findByEndpoint(switchId, port)); } else { - flowPathRepository.findBySegmentSwitch(switchId).stream() - // NOTE(tdurakov): filter out paths here that are orphaned for the flow - .filter(flowPath -> flowPath.getFlow().isActualPathId(flowPath.getPathId())) - .map(FlowPath::getFlow) - .forEach(flows::add); - flows.addAll(flowRepository.findByEndpointSwitch(switchId)); + return getFlowsForEndpoint(flowPathRepository.findBySegmentSwitch(switchId), + flowRepository.findByEndpointSwitch(switchId)); } + } + + private Collection<Flow> getFlowsForEndpoint(Collection<FlowPath> flowPaths, + Collection<Flow> flows) { + Stream<Flow> flowBySegment = flowPaths.stream() + // NOTE(tdurakov): filter out paths here that are orphaned for the flow + .filter(flowPath -> flowPath.getFlow().isActualPathId(flowPath.getPathId())) + .map(FlowPath::getFlow); // need to return Flows unique by id - return flows.stream() - .collect(Collectors.toMap(Flow::getFlowId, Function.identity())) + // Due to possible race condition we can have one flow with different flow paths + // In this case we should get the last one + return Stream.concat(flowBySegment, flows.stream()) + .collect(Collectors.toMap(Flow::getFlowId, Function.identity(), (flow1, flow2) -> flow2)) .values(); }
['src-java/nbworker-topology/nbworker-storm-topology/src/main/java/org/openkilda/wfm/topology/nbworker/services/FlowOperationsService.java']
{'.java': 1}
1
1
0
0
1
7,451,736
1,559,841
195,491
2,170
2,130
419
32
1
1,004
53
299
6
1
1
2020-07-28T13:00:41
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,081
telstra/open-kilda/3376/3369
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3369
https://github.com/telstra/open-kilda/pull/3376
https://github.com/telstra/open-kilda/pull/3376
1
close
Periodic fl router sync in rare cases may disrupt ISL discovery process on port
**Scenario:** given: port is in DOWN state 1. Floodlight router periodic sync happens 2. simultaneously with sync a port UP event happens At this point race appears. Because sync uses correlationId as key when writing to kafka and portUp event uses switchId, the order of events may disrupt, so that portUp event gets immediately followed buy portDown state (comming from sync), causing the related port to be considered by the system as 'Down'. This in turn will prevent a related ISL on that port to be discovered until next periodic sync happens. **Expected:** Disruption of port events order should not happen
67e32cb4a6e8a648789c02434db9331bab413378
bbd6e82d1bad685effd010edc8cd7c68650789da
https://github.com/telstra/open-kilda/compare/67e32cb4a6e8a648789c02434db9331bab413378...bbd6e82d1bad685effd010edc8cd7c68650789da
diff --git a/src-java/base-topology/base-messaging/src/main/java/org/openkilda/messaging/info/ChunkedInfoMessage.java b/src-java/base-topology/base-messaging/src/main/java/org/openkilda/messaging/info/ChunkedInfoMessage.java index d3f8db22b..f3b9567a7 100644 --- a/src-java/base-topology/base-messaging/src/main/java/org/openkilda/messaging/info/ChunkedInfoMessage.java +++ b/src-java/base-topology/base-messaging/src/main/java/org/openkilda/messaging/info/ChunkedInfoMessage.java @@ -51,11 +51,4 @@ public class ChunkedInfoMessage extends InfoMessage { this.messageId = String.join(" : ", String.valueOf(messageIndex), correlationId); this.totalMessages = totalMessages; } - - public ChunkedInfoMessage(InfoData data, long timestamp, String correlationId, - int messageIndex, int totalMessages, String region) { - super(data, timestamp, correlationId, region); - this.messageId = String.join(" : ", String.valueOf(messageIndex), correlationId); - this.totalMessages = totalMessages; - } } diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java index ba4760553..7a56ceac4 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java @@ -191,8 +191,6 @@ class RecordHandler implements Runnable { try { handleCommand(message, replyToTopic, replyDestination); - } catch (SwitchOperationException e) { - logger.error("Unable to handle request {}: {}", message.getData().getClass().getName(), e.getMessage()); } catch (FlowCommandException e) { String errorMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); logger.error("Failed to handle message {}: {}", message, errorMessage); @@ -205,7 +203,7 @@ class RecordHandler implements Runnable { } private void handleCommand(CommandMessage message, String replyToTopic, Destination replyDestination) - throws FlowCommandException, SwitchOperationException { + throws FlowCommandException { logger.debug("Handling message: '{}'. Reply topic: '{}'. Reply destination: '{}'.", message, replyToTopic, replyDestination); CommandData data = message.getData(); @@ -775,11 +773,11 @@ class RecordHandler implements Runnable { * * @param message NetworkCommandData */ - private void doNetworkDump(final CommandMessage message) throws SwitchOperationException { + private void doNetworkDump(final CommandMessage message) { logger.info("Processing request from WFM to dump switches. {}", message.getCorrelationId()); SwitchTrackingService switchTracking = context.getModuleContext().getServiceImpl(SwitchTrackingService.class); - switchTracking.dumpAllSwitches(message.getCorrelationId()); + switchTracking.dumpAllSwitches(); } private void doInstallSwitchRules(final CommandMessage message) { diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchTrackingService.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchTrackingService.java index 17cb27d95..00dcdbb1d 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchTrackingService.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchTrackingService.java @@ -28,7 +28,6 @@ import org.openkilda.floodlight.utils.CorrelationContext; import org.openkilda.floodlight.utils.FloodlightDashboardLogger; import org.openkilda.floodlight.utils.NewCorrelationContextRequired; import org.openkilda.messaging.Message; -import org.openkilda.messaging.info.ChunkedInfoMessage; import org.openkilda.messaging.info.InfoData; import org.openkilda.messaging.info.InfoMessage; import org.openkilda.messaging.info.discovery.NetworkDumpSwitchData; @@ -77,10 +76,10 @@ public class SwitchTrackingService implements IOFSwitchListener, IService { /** * Send dump contain all connected at this moment switches. */ - public void dumpAllSwitches(String correlationId) { + public void dumpAllSwitches() { discoveryLock.writeLock().lock(); try { - dumpAllSwitchesAction(correlationId); + dumpAllSwitchesAction(); } finally { discoveryLock.writeLock().unlock(); } @@ -167,20 +166,11 @@ public class SwitchTrackingService implements IOFSwitchListener, IService { } } - private void dumpAllSwitchesAction(String correlationId) { + private void dumpAllSwitchesAction() { Collection<IOFSwitch> iofSwitches = switchManager.getAllSwitchMap(true).values(); - int switchCounter = 0; for (IOFSwitch sw : iofSwitches) { - try { - NetworkDumpSwitchData swData = new NetworkDumpSwitchData(buildSwitch(sw)); - producerService.sendMessageAndTrack(discoveryTopic, - correlationId, - new ChunkedInfoMessage(swData, System.currentTimeMillis(), - correlationId, switchCounter, iofSwitches.size(), region)); - } catch (Exception e) { - logger.error("Failed to send network dump for {}", sw.getId()); - } - switchCounter++; + NetworkDumpSwitchData payload = new NetworkDumpSwitchData(buildSwitch(sw)); + emitDiscoveryEvent(sw.getId(), payload); } } @@ -204,28 +194,33 @@ public class SwitchTrackingService implements IOFSwitchListener, IService { private void switchDiscoveryAction(DatapathId dpId, SwitchChangeType event) { logger.info("Send switch discovery ({} - {})", dpId, event); - Message message = null; + SwitchInfoData payload = null; if (SwitchChangeType.DEACTIVATED != event && SwitchChangeType.REMOVED != event) { try { IOFSwitch sw = switchManager.lookupSwitch(dpId); SpeakerSwitchView switchView = buildSwitch(sw); - message = buildSwitchMessage(sw, switchView, event); + payload = buildSwitchMessage(sw, switchView, event); } catch (SwitchNotFoundException e) { logger.error( "Switch {} is not in management state now({}), switch ISL discovery details will be degraded.", dpId, e.getMessage()); } } - if (message == null) { - message = buildSwitchMessage(dpId, event); + if (payload == null) { + payload = buildSwitchMessage(dpId, event); } - producerService.sendMessageAndTrack(discoveryTopic, dpId.toString(), message); + emitDiscoveryEvent(dpId, payload); } private void portDiscoveryAction(DatapathId dpId, OFPortDesc portDesc, PortChangeType changeType) { logger.info("Send port discovery ({}-{} - {})", dpId, portDesc.getPortNo(), changeType); - Message message = buildPortMessage(dpId, portDesc, changeType); + InfoData payload = OfPortDescConverter.INSTANCE.toPortInfoData(dpId, portDesc, changeType); + emitDiscoveryEvent(dpId, payload); + } + + private void emitDiscoveryEvent(DatapathId dpId, InfoData payload) { + Message message = buildMessage(payload); producerService.sendMessageAndTrack(discoveryTopic, dpId.toString(), message); } @@ -236,8 +231,8 @@ public class SwitchTrackingService implements IOFSwitchListener, IService { * @param eventType type of event * @return Message */ - private Message buildSwitchMessage(IOFSwitch sw, SpeakerSwitchView switchView, SwitchChangeType eventType) { - return buildMessage(IofSwitchConverter.buildSwitchInfoData(sw, switchView, eventType)); + private SwitchInfoData buildSwitchMessage(IOFSwitch sw, SpeakerSwitchView switchView, SwitchChangeType eventType) { + return IofSwitchConverter.buildSwitchInfoData(sw, switchView, eventType); } /** @@ -247,21 +242,8 @@ public class SwitchTrackingService implements IOFSwitchListener, IService { * @param eventType type of event * @return Message */ - private Message buildSwitchMessage(DatapathId dpId, SwitchChangeType eventType) { - return buildMessage(new SwitchInfoData(new SwitchId(dpId.getLong()), eventType)); - } - - /** - * Builds a port state change message with port number. - * - * @param switchId datapathId of switch - * @param portDesc port that triggered the event - * @param type type of port event - * @return Message - */ - private Message buildPortMessage(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type) { - InfoData data = OfPortDescConverter.INSTANCE.toPortInfoData(switchId, portDesc, type); - return buildMessage(data); + private SwitchInfoData buildSwitchMessage(DatapathId dpId, SwitchChangeType eventType) { + return new SwitchInfoData(new SwitchId(dpId.getLong()), eventType); } /** diff --git a/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/switchmanager/SwitchTrackingServiceTest.java b/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/switchmanager/SwitchTrackingServiceTest.java index 385d06c40..74e7b41b5 100644 --- a/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/switchmanager/SwitchTrackingServiceTest.java +++ b/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/switchmanager/SwitchTrackingServiceTest.java @@ -33,8 +33,9 @@ import org.openkilda.floodlight.error.SwitchNotFoundException; import org.openkilda.floodlight.service.FeatureDetectorService; import org.openkilda.floodlight.service.kafka.IKafkaProducerService; import org.openkilda.floodlight.service.kafka.KafkaUtilityService; +import org.openkilda.floodlight.utils.CorrelationContext; +import org.openkilda.floodlight.utils.CorrelationContext.CorrelationContextClosable; import org.openkilda.messaging.Message; -import org.openkilda.messaging.info.ChunkedInfoMessage; import org.openkilda.messaging.info.InfoData; import org.openkilda.messaging.info.InfoMessage; import org.openkilda.messaging.info.discovery.NetworkDumpSwitchData; @@ -364,12 +365,14 @@ public class SwitchTrackingServiceTest extends EasyMockSupport { replayAll(); String correlationId = "unit-test-correlation-id"; - service.dumpAllSwitches(correlationId); + try (CorrelationContextClosable dummy = CorrelationContext.create(correlationId)) { + service.dumpAllSwitches(); + } verify(producerService); ArrayList<Message> expectedMessages = new ArrayList<>(); - expectedMessages.add(new ChunkedInfoMessage( + expectedMessages.add(new InfoMessage( new NetworkDumpSwitchData(new SpeakerSwitchView( new SwitchId(swAid.getLong()), new InetSocketAddress(Inet4Address.getByName("127.0.1.1"), 32768), @@ -380,8 +383,8 @@ public class SwitchTrackingServiceTest extends EasyMockSupport { ImmutableList.of( new SpeakerSwitchPortView(1, SpeakerSwitchPortView.State.UP), new SpeakerSwitchPortView(2, SpeakerSwitchPortView.State.UP)))), - 0, correlationId, 0, 2, "1")); - expectedMessages.add(new ChunkedInfoMessage( + 0, correlationId)); + expectedMessages.add(new InfoMessage( new NetworkDumpSwitchData(new SpeakerSwitchView( new SwitchId(swBid.getLong()), new InetSocketAddress(Inet4Address.getByName("127.0.1.2"), 32768), @@ -393,7 +396,7 @@ public class SwitchTrackingServiceTest extends EasyMockSupport { new SpeakerSwitchPortView(3, SpeakerSwitchPortView.State.UP), new SpeakerSwitchPortView(4, SpeakerSwitchPortView.State.UP), new SpeakerSwitchPortView(5, SpeakerSwitchPortView.State.DOWN)))), - 0, correlationId, 1, 2, "1")); + 0, correlationId)); assertEquals(expectedMessages, producedMessages); }
['src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchTrackingService.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/kafka/RecordHandler.java', 'src-java/base-topology/base-messaging/src/main/java/org/openkilda/messaging/info/ChunkedInfoMessage.java', 'src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/switchmanager/SwitchTrackingServiceTest.java']
{'.java': 4}
4
4
0
0
4
6,975,382
1,456,195
183,400
2,030
4,219
815
73
3
618
101
129
6
0
0
2020-04-08T13:09:11
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,070
telstra/open-kilda/3852/3821
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3821
https://github.com/telstra/open-kilda/pull/3852
https://github.com/telstra/open-kilda/pull/3852
1
close
System is unable to create a protected flow with max_latency strategy
1. Given a topology, that has at least 2 non-overlapping paths 2. Try creating a protected flow with max_latency strategy and non-zero max_latency ``` { "flow_id" : "protected_flow_max_lat", "source" : { "switch_id" : "00:00:00:00:00:00:00:01", "port_number" : 13, "vlan_id" : 2043 }, "destination" : { "switch_id" : "00:00:00:00:00:00:00:02", "port_number" : 13, "vlan_id" : 4014 }, "maximum_bandwidth" : 123, "max_latency": 11, "path_computation_strategy": "max_latency", "allocate_protected_path": true } ``` **Expected:** System is able to create such flow if there are at least 2 paths that match the max_latency SLA **Actual:** System not able to create such flow, no matter how big max_latency is specified note: special case with `max_latency: 0` works fine autotest that reveals the issue is available
511f17febcd951b12758c9e5d88432a705d50c53
ce5d744a3bd50085d4d81817857415af17c70212
https://github.com/telstra/open-kilda/compare/511f17febcd951b12758c9e5d88432a705d50c53...ce5d744a3bd50085d4d81817857415af17c70212
diff --git a/src-java/kilda-pce/src/main/java/org/openkilda/pce/AvailableNetworkFactory.java b/src-java/kilda-pce/src/main/java/org/openkilda/pce/AvailableNetworkFactory.java index 29a4b0225..def399f25 100644 --- a/src-java/kilda-pce/src/main/java/org/openkilda/pce/AvailableNetworkFactory.java +++ b/src-java/kilda-pce/src/main/java/org/openkilda/pce/AvailableNetworkFactory.java @@ -16,6 +16,7 @@ package org.openkilda.pce; import org.openkilda.model.Flow; +import org.openkilda.model.FlowPath; import org.openkilda.model.Isl; import org.openkilda.model.PathId; import org.openkilda.pce.exception.RecoverableException; @@ -88,7 +89,7 @@ public class AvailableNetworkFactory { flowPaths.forEach(pathId -> flowPathRepository.findById(pathId) .ifPresent(flowPath -> { - network.processDiversitySegments(flowPath.getSegments()); + network.processDiversitySegments(flowPath.getSegments(), flow); network.processDiversitySegmentsWithPop(flowPath.getSegments()); })); } @@ -96,6 +97,11 @@ public class AvailableNetworkFactory { return network; } + private boolean isPrimaryPath(Flow flow, FlowPath flowPath) { + return flowPath.getPathId().equals(flow.getForwardPathId()) + || flowPath.getPathId().equals(flow.getReversePathId()); + } + private Collection<Isl> getAvailableIsls(BuildStrategy buildStrategy, Flow flow) { if (buildStrategy == BuildStrategy.COST) { Collection<Isl> isls = flow.isIgnoreBandwidth() diff --git a/src-java/kilda-pce/src/main/java/org/openkilda/pce/impl/AvailableNetwork.java b/src-java/kilda-pce/src/main/java/org/openkilda/pce/impl/AvailableNetwork.java index b33692c2f..c7c4936ef 100644 --- a/src-java/kilda-pce/src/main/java/org/openkilda/pce/impl/AvailableNetwork.java +++ b/src-java/kilda-pce/src/main/java/org/openkilda/pce/impl/AvailableNetwork.java @@ -15,6 +15,9 @@ package org.openkilda.pce.impl; +import static com.google.common.collect.Sets.newHashSet; + +import org.openkilda.model.Flow; import org.openkilda.model.Isl; import org.openkilda.model.PathSegment; import org.openkilda.model.Switch; @@ -88,15 +91,17 @@ public class AvailableNetwork { /** * Adds diversity weights into {@link AvailableNetwork} based on passed path segments and configuration. */ - public void processDiversitySegments(List<PathSegment> segments) { + public void processDiversitySegments(List<PathSegment> segments, Flow flow) { + Set<SwitchId> terminatingSwitches = newHashSet(flow.getSrcSwitchId(), flow.getDestSwitchId()); for (PathSegment segment : segments) { Node srcNode = getSwitch(segment.getSrcSwitchId()); Node dstNode = getSwitch(segment.getDestSwitchId()); - if (dstNode != null) { + if (dstNode != null && !terminatingSwitches.contains(dstNode.getSwitchId())) { dstNode.increaseDiversityGroupUseCounter(); } - if (srcNode != null && segment.getSeqId() == 0) { + + if (srcNode != null && segment.getSeqId() == 0 && !terminatingSwitches.contains(srcNode.getSwitchId())) { srcNode.increaseDiversityGroupUseCounter(); } diff --git a/src-java/kilda-pce/src/test/java/org/openkilda/pce/AvailableNetworkFactoryTest.java b/src-java/kilda-pce/src/test/java/org/openkilda/pce/AvailableNetworkFactoryTest.java index 2405ccb4d..dd98393a3 100644 --- a/src-java/kilda-pce/src/test/java/org/openkilda/pce/AvailableNetworkFactoryTest.java +++ b/src-java/kilda-pce/src/test/java/org/openkilda/pce/AvailableNetworkFactoryTest.java @@ -142,6 +142,8 @@ public class AvailableNetworkFactoryTest { flow.setSrcSwitch(switchA); flow.setDestSwitch(switchC); flow.setGroupId(GROUP_ID); + flow.setForwardPathId(new PathId("forward_path_id")); + flow.setReversePathId(new PathId("reverse_path_id")); when(config.getNetworkStrategy()).thenReturn(BuildStrategy.COST.name()); when(islRepository.findActiveWithAvailableBandwidth(flow.getBandwidth(), flow.getEncapsulationType())) @@ -150,8 +152,6 @@ public class AvailableNetworkFactoryTest { when(flowPathRepository.findPathIdsByFlowGroupId(GROUP_ID)) .thenReturn(Lists.newArrayList(FORWARD_PATH_ID, REVERSE_PATH_ID)); - - AvailableNetwork availableNetwork = availableNetworkFactory.getAvailableNetwork(flow, Collections.emptyList()); assertEquals(2, availableNetwork.getSwitch(switchB.getSwitchId()).getDiversityGroupUseCounter()); } diff --git a/src-java/kilda-pce/src/test/java/org/openkilda/pce/impl/AvailableNetworkTest.java b/src-java/kilda-pce/src/test/java/org/openkilda/pce/impl/AvailableNetworkTest.java index 1a0938a94..aaf1b703b 100644 --- a/src-java/kilda-pce/src/test/java/org/openkilda/pce/impl/AvailableNetworkTest.java +++ b/src-java/kilda-pce/src/test/java/org/openkilda/pce/impl/AvailableNetworkTest.java @@ -21,6 +21,7 @@ import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import org.openkilda.model.Flow; import org.openkilda.model.FlowPath; import org.openkilda.model.Isl; import org.openkilda.model.IslConfig; @@ -58,6 +59,12 @@ public class AvailableNetworkTest { private static final SwitchId SRC_SWITCH = new SwitchId("00:00:00:22:3d:6c:00:b8"); private static final SwitchId DST_SWITCH = new SwitchId("00:00:00:22:3d:5a:04:87"); + private static final Flow DUMMY_FLOW = Flow.builder() + .flowId("flow-id") + .srcSwitch(Switch.builder().switchId(new SwitchId("1")).build()) + .destSwitch(Switch.builder().switchId(new SwitchId("2")).build()) + .build(); + @Test public void shouldNotAllowDuplicates() { AvailableNetwork network = new AvailableNetwork(); @@ -149,9 +156,8 @@ public class AvailableNetworkTest { addLink(network, DST_SWITCH, SRC_SWITCH, 2, 1, cost, 5); addLink(network, DST_SWITCH, SRC_SWITCH, 1, 3, cost, 5); - network.processDiversitySegments( - asList(buildPathWithSegment(SRC_SWITCH, DST_SWITCH, 3, 1, 0), - buildPathWithSegment(DST_SWITCH, SRC_SWITCH, 1, 3, 0))); + network.processDiversitySegments(singletonList(buildPathSegment(SRC_SWITCH, DST_SWITCH, 3, 1, 0)), DUMMY_FLOW); + network.processDiversitySegments(singletonList(buildPathSegment(DST_SWITCH, SRC_SWITCH, 1, 3, 0)), DUMMY_FLOW); network.reduceByWeight(weightFunction); assertThat(network.getSwitch(SRC_SWITCH).getOutgoingLinks(), Matchers.hasSize(1)); @@ -271,8 +277,8 @@ public class AvailableNetworkTest { network.processDiversitySegmentsWithPop( - asList(buildPathWithSegment(SWITCH_1, SWITCH_3, 2, 1, 0), - buildPathWithSegment(SWITCH_3, SWITCH_5, 2, 2, 1))); + asList(buildPathSegment(SWITCH_1, SWITCH_3, 2, 1, 0), + buildPathSegment(SWITCH_3, SWITCH_5, 2, 2, 1))); for (Edge edge : network.edges) { long currentWeight = weightFunction.apply(edge).toLong(); assertEquals(cost, currentWeight); @@ -329,7 +335,7 @@ public class AvailableNetworkTest { addLink(network, SRC_SWITCH, DST_SWITCH, 7, 60, 10, 3); network.processDiversitySegments( - singletonList(buildPathWithSegment(SRC_SWITCH, DST_SWITCH, 7, 60, 0))); + singletonList(buildPathSegment(SRC_SWITCH, DST_SWITCH, 7, 60, 0)), DUMMY_FLOW); Node srcSwitch = network.getSwitch(SRC_SWITCH); @@ -338,13 +344,35 @@ public class AvailableNetworkTest { assertEquals(1, edge.getDestSwitch().getDiversityGroupUseCounter()); } + @Test + public void shouldFillEmptyDiversityWeightsForTerminatingSwitch() { + AvailableNetwork network = new AvailableNetwork(); + addLink(network, SRC_SWITCH, DST_SWITCH, 7, 60, 10, 3); + + Flow flow = Flow.builder() + .flowId("flow-id") + .srcSwitch(Switch.builder().switchId(SRC_SWITCH).build()) + .destSwitch(Switch.builder().switchId(DST_SWITCH).build()) + .build(); + + network.processDiversitySegments( + singletonList(buildPathSegment(SRC_SWITCH, DST_SWITCH, 7, 60, 0)), flow); + + Node srcSwitch = network.getSwitch(SRC_SWITCH); + + Edge edge = srcSwitch.getOutgoingLinks().iterator().next(); + assertEquals(1, edge.getDiversityGroupUseCounter()); + assertEquals(0, edge.getDestSwitch().getDiversityGroupUseCounter()); + assertEquals(0, edge.getSrcSwitch().getDiversityGroupUseCounter()); + } + @Test public void shouldFillDiversityWeightsTransit() { AvailableNetwork network = new AvailableNetwork(); addLink(network, SRC_SWITCH, DST_SWITCH, 7, 60, 10, 3); network.processDiversitySegments( - singletonList(buildPathWithSegment(SRC_SWITCH, DST_SWITCH, 7, 60, 1))); + singletonList(buildPathSegment(SRC_SWITCH, DST_SWITCH, 7, 60, 1)), DUMMY_FLOW); Node srcSwitch = network.getSwitch(SRC_SWITCH); @@ -368,8 +396,8 @@ public class AvailableNetworkTest { addLink(network, switchB, switchC, 2, 2, 10, 3); addLink(network, switchC, switchD, 3, 3, 10, 3); network.processDiversitySegments(asList( - buildPathWithSegment(switchA, switchB, 1, 1, 0), - buildPathWithSegment(switchC, switchD, 3, 3, 0))); + buildPathSegment(switchA, switchB, 1, 1, 0), + buildPathSegment(switchC, switchD, 3, 3, 0)), DUMMY_FLOW); Node nodeB = network.getSwitch(switchB); @@ -386,7 +414,7 @@ public class AvailableNetworkTest { addLink(network, SRC_SWITCH, DST_SWITCH, 7, 60, 10, 3); network.processDiversitySegments( - singletonList(buildPathWithSegment(SRC_SWITCH, DST_SWITCH, 1, 2, 0))); + singletonList(buildPathSegment(SRC_SWITCH, DST_SWITCH, 1, 2, 0)), DUMMY_FLOW); Node srcSwitch = network.getSwitch(SRC_SWITCH); @@ -420,7 +448,7 @@ public class AvailableNetworkTest { network.addLink(isl); } - private PathSegment buildPathWithSegment(SwitchId srcDpid, SwitchId dstDpid, int srcPort, int dstPort, int seqId) { + private PathSegment buildPathSegment(SwitchId srcDpid, SwitchId dstDpid, int srcPort, int dstPort, int seqId) { return buildPathWithSegment(srcDpid, dstDpid, srcPort, dstPort, null, null, seqId); }
['src-java/kilda-pce/src/main/java/org/openkilda/pce/impl/AvailableNetwork.java', 'src-java/kilda-pce/src/test/java/org/openkilda/pce/impl/AvailableNetworkTest.java', 'src-java/kilda-pce/src/main/java/org/openkilda/pce/AvailableNetworkFactory.java', 'src-java/kilda-pce/src/test/java/org/openkilda/pce/AvailableNetworkFactoryTest.java']
{'.java': 4}
4
4
0
0
4
8,208,315
1,712,711
215,048
2,324
1,108
231
19
2
878
115
260
26
0
1
2020-11-13T17:04:26
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,071
telstra/open-kilda/3834/3754
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3754
https://github.com/telstra/open-kilda/pull/3834
https://github.com/telstra/open-kilda/pull/3834
1
close
GRPC: any error leads to InternalServerError instead of showing actual error
**Step to reproduce:** send a request with an invalid body to a grpc endpoint for examle: ``` curl --location --request PUT '<address_grpc_speaker>/api/v1/noviflow/<ip_address_of_switch>/remotelogserver' \\ --header 'Accept: application/json;charset=UTF-8' \\ --header 'Content-Type: application/json' \\ --header 'Authorization: <credentials>' \\ --data-raw '{ "ip_address": "1.1.1.1111", "port": 10514 }' ``` **Actual result:** 500 InternalServerError ``` {... "error-code": -1, "error-message": "Internal service error" }{... "status": 500, "error": "Internal Server Error", "exception": "java.util.concurrent.CompletionException", "message": "org.openkilda.grpc.speaker.exception.GrpcRequestFailureException: Invalid hostname,please provide valid hostname.", "path": "/api/v1/noviflow/<ip_address_of_switch>/remotelogserver" } ``` **Expected result:** The system should return `400 Bad Request`.
2da2d480b4a66301ca2e834944eb03fed36b2adf
3b7cddd66c7a7d1e3cb42fd928c19b45efbdf9a4
https://github.com/telstra/open-kilda/compare/2da2d480b4a66301ca2e834944eb03fed36b2adf...3b7cddd66c7a7d1e3cb42fd928c19b45efbdf9a4
diff --git a/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/client/GrpcResponseObserver.java b/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/client/GrpcResponseObserver.java index 142980f87..baa3c9caa 100644 --- a/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/client/GrpcResponseObserver.java +++ b/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/client/GrpcResponseObserver.java @@ -66,8 +66,6 @@ public class GrpcResponseObserver<V> implements StreamObserver<V> { @Override public void onError(Throwable throwable) { - log.warn(String.format("Error occurred during sending of GRPC request %s on switch %s", - operation, switchAddress), throwable); future.completeExceptionally(throwable); } diff --git a/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java b/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java index fbc287ece..976105b18 100644 --- a/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java +++ b/src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java @@ -21,6 +21,7 @@ import org.openkilda.grpc.speaker.exception.GrpcRequestFailureException; import org.openkilda.messaging.error.ErrorType; import org.openkilda.messaging.error.GrpcMessageError; +import io.grpc.StatusRuntimeException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -29,15 +30,14 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; -import java.net.SocketException; -import java.util.concurrent.CompletionException; - @ControllerAdvice public class GrpcExceptionHandler extends ResponseEntityExceptionHandler { - @ExceptionHandler(GrpcRequestFailureException.class) - protected ResponseEntity<Object> handleGrpcRequestExeption(GrpcRequestFailureException ex, - WebRequest request) { + /** + * Exception handler. + */ + @ExceptionHandler + public ResponseEntity<Object> handleException(GrpcRequestFailureException ex, WebRequest request) { HttpStatus status; switch (ex.getErrorType()) { @@ -58,28 +58,12 @@ public class GrpcExceptionHandler extends ResponseEntityExceptionHandler { return makeExceptionalResponse(ex, makeErrorPayload(ex.getCode(), ex.getMessage()), status, request); } - @ExceptionHandler(CompletionException.class) - protected ResponseEntity<Object> handleCompletionExceptions(CompletionException wrapper, WebRequest request) { - ResponseEntity<Object> response; - try { - throw wrapper.getCause(); - } catch (SocketException e) { - GrpcMessageError body = makeErrorPayload(-1, format("Communication failure - %s", e.getMessage())); - response = makeExceptionalResponse(e, body, HttpStatus.INTERNAL_SERVER_ERROR, request); - } catch (Exception e) { - GrpcMessageError body = makeErrorPayload(-1, ErrorType.INTERNAL_ERROR.toString()); - response = makeExceptionalResponse( - e, body, HttpStatus.INTERNAL_SERVER_ERROR, request); - } catch (Throwable e) { - GrpcMessageError body = makeErrorPayload(-1, ErrorType.INTERNAL_ERROR.toString()); - response = new ResponseEntity<>(body, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); - } - return response; + @ExceptionHandler + public ResponseEntity<Object> handleException(StatusRuntimeException ex, WebRequest request) { + GrpcMessageError body = makeErrorPayload(-1, format("Communication failure - %s", ex.getMessage())); + return makeExceptionalResponse(ex, body, HttpStatus.INTERNAL_SERVER_ERROR, request); } - /** - * {@inheritDoc} - */ @Override protected ResponseEntity<Object> handleExceptionInternal(Exception exception, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { @@ -90,7 +74,7 @@ public class GrpcExceptionHandler extends ResponseEntityExceptionHandler { private ResponseEntity<Object> makeExceptionalResponse( Exception ex, GrpcMessageError body, HttpStatus status, WebRequest request) { - logger.error(format("Produce error response: %s", body), ex); + logger.error(format("Produce error response: %s", body)); return super.handleExceptionInternal(ex, body, new HttpHeaders(), status, request); }
['src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/client/GrpcResponseObserver.java', 'src-java/grpc-speaker/grpc-service/src/main/java/org/openkilda/grpc/speaker/utils/GrpcExceptionHandler.java']
{'.java': 2}
2
2
0
0
2
8,084,339
1,687,650
212,206
2,295
2,233
411
40
2
963
84
249
31
0
2
2020-11-06T12:17:06
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,072
telstra/open-kilda/3812/3797
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3797
https://github.com/telstra/open-kilda/pull/3812
https://github.com/telstra/open-kilda/pull/3812
1
closes
Server42: stats app leaks memory if no server42 flows were created
After ~1h, if no server42 flows are created, the `server42-stats` container runs out of memory. Steps: 1. Start kilda and just leave it for hour+. Do not create any flows 2. call `docker logs server42-stats` [server42_stats_oom.zip](https://github.com/telstra/open-kilda/files/5416162/server42_stats_oom.zip) **Expected:** stats app works just fine **Actual:** java.lang.OutOfMemoryError: Java heap space
a31b5d5a851c6e69c0dccf11ab5325f2743841f3
f772902e4eb13632bd3ca8fdfa50539e22281725
https://github.com/telstra/open-kilda/compare/a31b5d5a851c6e69c0dccf11ab5325f2743841f3...f772902e4eb13632bd3ca8fdfa50539e22281725
diff --git a/src-java/server42/server42-control-server-stub/src/main/java/org/openkilda/server42/control/serverstub/StatsServer.java b/src-java/server42/server42-control-server-stub/src/main/java/org/openkilda/server42/control/serverstub/StatsServer.java index 7a5200d52..873ee1998 100644 --- a/src-java/server42/server42-control-server-stub/src/main/java/org/openkilda/server42/control/serverstub/StatsServer.java +++ b/src-java/server42/server42-control-server-stub/src/main/java/org/openkilda/server42/control/serverstub/StatsServer.java @@ -87,8 +87,10 @@ public class StatsServer extends Thread { } } - if (!flows.isEmpty()) { - server.send(flowBucketBuilder.build().toByteArray()); + server.send(flowBucketBuilder.build().toByteArray()); + if (flows.isEmpty()) { + log.info("send ping"); + } else { log.info("send stats"); } diff --git a/src-java/server42/server42-stats/src/main/java/org/openkilda/server42/stats/zeromq/StatsCollector.java b/src-java/server42/server42-stats/src/main/java/org/openkilda/server42/stats/zeromq/StatsCollector.java index 133e55d5f..5337f7216 100644 --- a/src-java/server42/server42-stats/src/main/java/org/openkilda/server42/stats/zeromq/StatsCollector.java +++ b/src-java/server42/server42-stats/src/main/java/org/openkilda/server42/stats/zeromq/StatsCollector.java @@ -73,7 +73,10 @@ public class StatsCollector extends Thread { sessionId = RandomStringUtils.randomAlphanumeric(8); log.info("started with session id {}", sessionId); while (!isInterrupted()) { - try (Socket server = context.createSocket(ZMQ.PULL)) { + + Socket server = null; + try { + server = context.createSocket(ZMQ.PULL); server.setReceiveTimeOut(1000); server.connect(connectEndpoint); log.info("connect to {}", connectEndpoint); @@ -90,11 +93,13 @@ public class StatsCollector extends Thread { log.debug("stats received"); handleInput(recv); } - } catch (org.zeromq.ZMQException ex) { log.error(ex.toString()); } finally { log.info("disconnected"); + if (server != null) { + context.destroySocket(server); + } } } }
['src-java/server42/server42-control-server-stub/src/main/java/org/openkilda/server42/control/serverstub/StatsServer.java', 'src-java/server42/server42-stats/src/main/java/org/openkilda/server42/stats/zeromq/StatsCollector.java']
{'.java': 2}
2
2
0
0
2
7,961,455
1,663,076
209,057
2,255
589
98
15
2
410
47
107
7
1
0
2020-10-28T13:08:49
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,073
telstra/open-kilda/3743/3744
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3744
https://github.com/telstra/open-kilda/pull/3743
https://github.com/telstra/open-kilda/pull/3743
1
close
BFD session status is not updated on db
`bfd_session_status` field hasn't been updated in db for isl on any commands.
4734f2f67cc5d5047a3d94dcf3b5a9e45f1db765
d780c52ba403e80463aaa286874693f163279e14
https://github.com/telstra/open-kilda/compare/4734f2f67cc5d5047a3d94dcf3b5a9e45f1db765...d780c52ba403e80463aaa286874693f163279e14
diff --git a/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/DiscoveryBfdMonitor.java b/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/DiscoveryBfdMonitor.java index d0d9cee25..d6093c143 100644 --- a/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/DiscoveryBfdMonitor.java +++ b/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/DiscoveryBfdMonitor.java @@ -72,7 +72,7 @@ public class DiscoveryBfdMonitor extends DiscoveryMonitor<IslEndpointBfdStatus> update = new IslEndpointBfdStatus(true, BfdSessionStatus.DOWN); break; case BFD_KILL: - update = new IslEndpointBfdStatus(false, null, true); + update = new IslEndpointBfdStatus(false, null); break; case BFD_FAIL: update = new IslEndpointBfdStatus(false, BfdSessionStatus.FAIL); @@ -89,10 +89,7 @@ public class DiscoveryBfdMonitor extends DiscoveryMonitor<IslEndpointBfdStatus> @Override public void actualFlush(Endpoint endpoint, Isl persistentView) { - IslEndpointBfdStatus bfdStatus = discoveryData.get(endpoint); - if (bfdStatus.isForceReset() || bfdStatus.getStatus() != null) { - persistentView.setBfdSessionStatus(bfdStatus.getStatus()); - } + persistentView.setBfdSessionStatus(discoveryData.get(endpoint).getStatus()); } /** diff --git a/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/IslFsm.java b/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/IslFsm.java index 00843d0de..007d0d5e6 100644 --- a/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/IslFsm.java +++ b/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/IslFsm.java @@ -316,11 +316,17 @@ public final class IslFsm extends AbstractBaseFsm<IslFsm, IslFsmState, IslFsmEve for (DiscoveryMonitor<?> entry : monitorsByPriority) { entry.load(start, isl); } + + fixUpPersistentData(isl); } else { log.debug("There is no persistent ISL data {} ==> {} (do not load monitors state)", start, end); } } + private void fixUpPersistentData(Isl link) { + link.setBfdSessionStatus(null); + } + private void sendInstallMultiTable(IIslCarrier carrier) { final Endpoint source = reference.getSource(); final Endpoint dest = reference.getDest(); diff --git a/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/model/IslEndpointBfdStatus.java b/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/model/IslEndpointBfdStatus.java index 3d7a12001..50a25460c 100644 --- a/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/model/IslEndpointBfdStatus.java +++ b/src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/model/IslEndpointBfdStatus.java @@ -18,22 +18,18 @@ package org.openkilda.wfm.topology.network.model; import org.openkilda.model.BfdSessionStatus; import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; import lombok.Value; @Value +@EqualsAndHashCode(exclude = {"enabled"}) @AllArgsConstructor public class IslEndpointBfdStatus { boolean enabled; BfdSessionStatus status; - boolean forceReset; - public IslEndpointBfdStatus() { this(false, null); } - - public IslEndpointBfdStatus(boolean enabled, BfdSessionStatus status) { - this(enabled, status, false); - } } diff --git a/src-java/network-topology/network-storm-topology/src/test/java/org/openkilda/wfm/topology/network/service/NetworkIslServiceTest.java b/src-java/network-topology/network-storm-topology/src/test/java/org/openkilda/wfm/topology/network/service/NetworkIslServiceTest.java index 48182facb..3ba8f3db7 100644 --- a/src-java/network-topology/network-storm-topology/src/test/java/org/openkilda/wfm/topology/network/service/NetworkIslServiceTest.java +++ b/src-java/network-topology/network-storm-topology/src/test/java/org/openkilda/wfm/topology/network/service/NetworkIslServiceTest.java @@ -34,6 +34,7 @@ import org.openkilda.config.provider.PropertiesBasedConfigurationProvider; import org.openkilda.messaging.command.reroute.RerouteAffectedFlows; import org.openkilda.messaging.info.discovery.RemoveIslDefaultRulesResult; import org.openkilda.messaging.info.event.IslStatusUpdateNotification; +import org.openkilda.model.BfdSessionStatus; import org.openkilda.model.FeatureToggles; import org.openkilda.model.Isl; import org.openkilda.model.IslDownReason; @@ -691,6 +692,52 @@ public class NetworkIslServiceTest { verify(dashboardLogger).onIslDown(reference); } + @Test + public void resetBfdFailOnStart() { + testBfdStatusReset(BfdSessionStatus.FAIL); + } + + @Test + public void resetBfdUpOnStart() { + testBfdStatusReset(BfdSessionStatus.UP); + } + + private void testBfdStatusReset(BfdSessionStatus initialStatus) { + setupIslStorageStub(); + + final Instant start = clock.adjust(Duration.ofSeconds(1)); + Isl alphaToBeta = makeIsl(endpointAlpha1, endpointBeta2, false) + .bfdSessionStatus(initialStatus) + .build(); + islStorage.save(alphaToBeta); + islStorage.save( + makeIsl(endpointBeta2, endpointAlpha1, false) + .bfdSessionStatus(initialStatus) + .build()); + + clock.adjust(Duration.ofSeconds(1)); + + IslReference reference = new IslReference(endpointAlpha1, endpointBeta2); + service.islSetupFromHistory(reference.getSource(), reference, alphaToBeta); + + Optional<Isl> potential = islStorage.lookup(reference.getSource(), reference.getDest()); + + Assert.assertTrue(potential.isPresent()); + Isl link = potential.get(); + Assert.assertNull(link.getBfdSessionStatus()); + + potential = islStorage.lookup(reference.getDest(), reference.getSource()); + Assert.assertTrue(potential.isPresent()); + link = potential.get(); + Assert.assertNull(link.getBfdSessionStatus()); + + service.bfdStatusUpdate(reference.getSource(), reference, BfdStatusUpdate.UP); + verifyBfdStatus(reference, BfdSessionStatus.UP, null); + + service.bfdStatusUpdate(reference.getDest(), reference, BfdStatusUpdate.UP); + verifyBfdStatus(reference, BfdSessionStatus.UP, BfdSessionStatus.UP); + } + private IslReference prepareBfdEnabledIsl() { IslReference reference = prepareActiveIsl(); @@ -748,6 +795,24 @@ public class NetworkIslServiceTest { return reference; } + private void verifyBfdStatus(IslReference reference, BfdSessionStatus leftToRight, BfdSessionStatus rightToLeft) { + Optional<Isl> potential = islStorage.lookup(reference.getSource(), reference.getDest()); + Assert.assertTrue(potential.isPresent()); + verifyBfdStatus(potential.get(), leftToRight); + + potential = islStorage.lookup(reference.getDest(), reference.getSource()); + Assert.assertTrue(potential.isPresent()); + verifyBfdStatus(potential.get(), rightToLeft); + } + + private void verifyBfdStatus(Isl link, BfdSessionStatus status) { + if (status != null) { + Assert.assertEquals(status, link.getBfdSessionStatus()); + } else { + Assert.assertNull(link.getBfdSessionStatus()); + } + } + private void verifyIslBandwidthUpdate(long expectedForward, long expectedReverse) { Isl forward = lookupIsl(endpointAlpha1, endpointBeta2); Assert.assertEquals(expectedForward, forward.getMaxBandwidth());
['src-java/network-topology/network-storm-topology/src/test/java/org/openkilda/wfm/topology/network/service/NetworkIslServiceTest.java', 'src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/DiscoveryBfdMonitor.java', 'src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/model/IslEndpointBfdStatus.java', 'src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/isl/IslFsm.java']
{'.java': 4}
4
4
0
0
4
7,789,529
1,628,073
204,565
2,234
817
171
21
3
77
12
18
1
0
0
2020-09-25T16:48:52
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,074
telstra/open-kilda/3711/3673
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3673
https://github.com/telstra/open-kilda/pull/3711
https://github.com/telstra/open-kilda/pull/3711
1
close
Flow endpoint with server42-enabled switch has rule discrepancies
Create a flow with at least one endpoint being a server42-enabled switch. Validate the switch **Expected:** no rule discrepancies, all rules appear in 'proper' section **Actual:** `EXCLUSION_FLOW` type rule appears in 'missing' section, `SERVER_42_INGRESS` type rule appears in 'excess' section - rules are not getting synchronized via sync switch api - also reproduces during switch update or partial update
91cb45cdded45ac97c503f619581bd4c52711617
1ec84f602ce1d3c0cbd37381af3cb486f8a3cab1
https://github.com/telstra/open-kilda/compare/91cb45cdded45ac97c503f619581bd4c52711617...1ec84f602ce1d3c0cbd37381af3cb486f8a3cab1
diff --git a/src-java/kilda-model/src/main/java/org/openkilda/model/cookie/Cookie.java b/src-java/kilda-model/src/main/java/org/openkilda/model/cookie/Cookie.java index ddcd2ba7b..3a434feba 100644 --- a/src-java/kilda-model/src/main/java/org/openkilda/model/cookie/Cookie.java +++ b/src-java/kilda-model/src/main/java/org/openkilda/model/cookie/Cookie.java @@ -91,7 +91,7 @@ public class Cookie extends CookieBase implements Comparable<Cookie> { } /** - * Conver existing {@link Cookie} instance into {@link CookieBuilder}. + * Convert existing {@link Cookie} instance into {@link CookieBuilder}. */ public CookieBuilder toBuilder() { return new CookieBuilder() diff --git a/src-java/kilda-persistence-neo4j/src/main/java/org/openkilda/persistence/SimpleConversionCallback.java b/src-java/kilda-persistence-neo4j/src/main/java/org/openkilda/persistence/SimpleConversionCallback.java index 95d8c2cf3..f5ae80be3 100644 --- a/src-java/kilda-persistence-neo4j/src/main/java/org/openkilda/persistence/SimpleConversionCallback.java +++ b/src-java/kilda-persistence-neo4j/src/main/java/org/openkilda/persistence/SimpleConversionCallback.java @@ -88,7 +88,31 @@ class SimpleConversionCallback implements ConversionCallback { throw new PersistenceException("Unable to locate appropriate converter for null-valued target type and " + value); } - // Look up for a converter with corresponding entity and graph classes. + // Look up for a converter with exact entity and graph classes. + for (Map.Entry<ParameterizedType, Class<? extends AttributeConverter>> converter : converters.entrySet()) { + Type[] genericTypes = converter.getKey().getActualTypeArguments(); + Class entityClass = (Class) genericTypes[0]; + Class graphClass = (Class) genericTypes[1]; + + if (targetType.equals(entityClass) && graphClass.equals(value.getClass())) { + try { + return (T) converter.getValue().newInstance().toEntityAttribute(value); + } catch (InstantiationException | IllegalAccessException ex) { + throw new PersistenceException("Unable to instantiate the converter " + + converter.getValue().getSimpleName(), ex); + } + } + + if (targetType.equals(graphClass) && entityClass.equals(value.getClass())) { + try { + return (T) converter.getValue().newInstance().toGraphProperty(value); + } catch (InstantiationException | IllegalAccessException ex) { + throw new PersistenceException("Unable to instantiate the converter " + + converter.getValue().getSimpleName(), ex); + } + } + } + // Look up for a converter with assignable entity and graph classes. for (Map.Entry<ParameterizedType, Class<? extends AttributeConverter>> converter : converters.entrySet()) { Type[] genericTypes = converter.getKey().getActualTypeArguments(); Class entityClass = (Class) genericTypes[0]; @@ -98,7 +122,7 @@ class SimpleConversionCallback implements ConversionCallback { try { return (T) converter.getValue().newInstance().toEntityAttribute(value); } catch (InstantiationException | IllegalAccessException ex) { - throw new PersistenceException("Unable to instaniate the converter " + throw new PersistenceException("Unable to instantiate the converter " + converter.getValue().getSimpleName(), ex); } } @@ -107,7 +131,7 @@ class SimpleConversionCallback implements ConversionCallback { try { return (T) converter.getValue().newInstance().toGraphProperty(value); } catch (InstantiationException | IllegalAccessException ex) { - throw new PersistenceException("Unable to instaniate the converter " + throw new PersistenceException("Unable to instantiate the converter " + converter.getValue().getSimpleName(), ex); } } diff --git a/src-java/kilda-persistence-neo4j/src/test/java/org/openkilda/persistence/SimpleConversionCallbackTest.java b/src-java/kilda-persistence-neo4j/src/test/java/org/openkilda/persistence/SimpleConversionCallbackTest.java index 80ced2aa2..8be2fda21 100644 --- a/src-java/kilda-persistence-neo4j/src/test/java/org/openkilda/persistence/SimpleConversionCallbackTest.java +++ b/src-java/kilda-persistence-neo4j/src/test/java/org/openkilda/persistence/SimpleConversionCallbackTest.java @@ -18,6 +18,9 @@ package org.openkilda.persistence; import static org.junit.Assert.assertEquals; import org.openkilda.model.SwitchId; +import org.openkilda.model.cookie.FlowSegmentCookie; +import org.openkilda.persistence.converters.CookieConverter; +import org.openkilda.persistence.converters.ExclusionCookieConverter; import org.openkilda.persistence.converters.SwitchIdConverter; import org.junit.Test; @@ -55,5 +58,20 @@ public class SimpleConversionCallbackTest { // then assertEquals(entity, actualEntity); } + + @Test + public void shouldUseExactTypeConverterWhenMultipleAvailable() { + // given + SimpleConversionCallback conversionCallback = + new SimpleConversionCallback(Arrays.asList(CookieConverter.class, + ExclusionCookieConverter.class)); + long graphObject = 1L; + + //when + FlowSegmentCookie cookie = conversionCallback.convert(FlowSegmentCookie.class, graphObject); + + // then + assertEquals(cookie.getClass(), FlowSegmentCookie.class); + } }
['src-java/kilda-persistence-neo4j/src/main/java/org/openkilda/persistence/SimpleConversionCallback.java', 'src-java/kilda-persistence-neo4j/src/test/java/org/openkilda/persistence/SimpleConversionCallbackTest.java', 'src-java/kilda-model/src/main/java/org/openkilda/model/cookie/Cookie.java']
{'.java': 3}
3
3
0
0
3
7,508,886
1,571,537
196,809
2,182
2,040
331
32
2
415
59
90
7
0
0
2020-09-04T15:39:45
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,079
telstra/open-kilda/3578/3255
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3255
https://github.com/telstra/open-kilda/pull/3578
https://github.com/telstra/open-kilda/pull/3578
1
closes
Flow path cannot be removed when it goes through a non-existing ISL
**Steps:** given: A busy environment with reroutes happening. An ISL with flows going though it 1. Call port down on one end of ISL 2. As soon as isl is marked as FAILED delete the ISL using NB API 3. Check existing flow paths. Repeat above steps until you get a flow path that still use the removed ISL **Problem:** Flow leaves excess flow paths during reroutes due to following errors ``` Flow perfload_28Feb133820_640_onion6002 error - CompleteFlowPathRemovalAction failed: ISL 00:00:b2:81:f7:c9:1f:55_4 - 00:00:cc:2e:48:4f:a9:6c_2 not found to be updated ``` ``` Flow perfload_28Feb133820_640_onion6002 error - Failed to remove paths : Failed to remove paths: "perfload_28Feb133820_640_onion6002_31b20347-2fab-4fe8-8b06-43ab00cf9b27", "perfload_28Feb133820_640_onion6002_103977e2-f365-430b-b622-a313a859bcde" ```
c941444489a6381a1ab00d6bbb216871c4ecebfe
9f723a2d6550567660a0effd9a456c4bf2bb601a
https://github.com/telstra/open-kilda/compare/c941444489a6381a1ab00d6bbb216871c4ecebfe...9f723a2d6550567660a0effd9a456c4bf2bb601a
diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/common/actions/BaseFlowPathRemovalAction.java b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/common/actions/BaseFlowPathRemovalAction.java index db6f7ba2f..25215eb92 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/common/actions/BaseFlowPathRemovalAction.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/common/actions/BaseFlowPathRemovalAction.java @@ -20,6 +20,7 @@ import static java.lang.String.format; import org.openkilda.model.Flow; import org.openkilda.model.FlowPath; import org.openkilda.model.SwitchId; +import org.openkilda.persistence.PersistenceException; import org.openkilda.persistence.PersistenceManager; import org.openkilda.persistence.repositories.IslRepository; import org.openkilda.wfm.share.history.model.FlowDumpData; @@ -73,7 +74,12 @@ public abstract class BaseFlowPathRemovalAction<T extends FlowProcessingFsm<T, S dstSwitch, dstPort); log.debug("Updating ISL {}_{} - {}_{} with used bandwidth {}", srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth); - islRepository.updateAvailableBandwidth(srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth); + try { + islRepository.updateAvailableBandwidth(srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth); + } catch (PersistenceException e) { + log.warn(format("Couldn't update ISL %s_%d - %s_%d with used bandwidth %d. %s", + srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth, e.getMessage()), e); + } } protected void saveRemovalActionWithDumpToHistory(T stateMachine, Flow flow, FlowPath flowPath) {
['src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/common/actions/BaseFlowPathRemovalAction.java']
{'.java': 1}
1
1
0
0
1
7,307,799
1,530,552
191,746
2,119
527
119
8
1
827
105
271
12
0
2
2020-06-30T14:05:20
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
2,080
telstra/open-kilda/3448/3446
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3446
https://github.com/telstra/open-kilda/pull/3448
https://github.com/telstra/open-kilda/pull/3448
1
close
flowDeleteV2 is leaving excess meter on Centec switch
**Steps to reproduce:** 1. create a flow on a Centec switch; 2. delete the flow; **Actual result:** excess meter on a Centec switch after deleting the flow **Expected result:** system shouldn't leave excess meter
17f2f05087d4abeaecfed9ba417602399343eddd
d375ebb43d325c6f3d6c365efd4ac83e29082afa
https://github.com/telstra/open-kilda/compare/17f2f05087d4abeaecfed9ba417602399343eddd...d375ebb43d325c6f3d6c365efd4ac83e29082afa
diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentInstallCommand.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentInstallCommand.java index 01c2f9873..d9ec2d829 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentInstallCommand.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentInstallCommand.java @@ -64,6 +64,10 @@ public class IngressFlowSegmentInstallCommand extends IngressFlowSegmentCommand if (encapsulation.getType() == FlowEncapsulationType.VXLAN) { required.add(SwitchFeature.NOVIFLOW_COPY_FIELD); } + if (metadata.isMultiTable()) { + required.add(SwitchFeature.MULTI_TABLE); + } + return required; } diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentRemoveCommand.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentRemoveCommand.java index 6b08beffd..8c9c5e5d2 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentRemoveCommand.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentRemoveCommand.java @@ -26,6 +26,7 @@ import org.openkilda.model.FlowEndpoint; import org.openkilda.model.FlowTransitEncapsulation; import org.openkilda.model.MeterConfig; import org.openkilda.model.MeterId; +import org.openkilda.model.SwitchFeature; import org.openkilda.model.SwitchId; import com.fasterxml.jackson.annotation.JsonProperty; @@ -70,7 +71,7 @@ public class IngressFlowSegmentRemoveCommand extends IngressFlowSegmentCommand { @Override protected List<OFFlowMod> makeIngressModMessages(MeterId effectiveMeterId) { List<OFFlowMod> ofMessages = super.makeIngressModMessages(effectiveMeterId); - if (rulesContext != null) { + if (getSwitchFeatures().contains(SwitchFeature.MULTI_TABLE) && rulesContext != null) { if (rulesContext.isRemoveCustomerCatchRule()) { ofMessages.add(getFlowModFactory().makeCustomerPortSharedCatchMessage()); } diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowInstallCommand.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowInstallCommand.java index b75325dec..22b8f9322 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowInstallCommand.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowInstallCommand.java @@ -25,12 +25,14 @@ import org.openkilda.messaging.MessageContext; import org.openkilda.model.FlowEndpoint; import org.openkilda.model.MeterConfig; import org.openkilda.model.MeterId; +import org.openkilda.model.SwitchFeature; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.projectfloodlight.openflow.protocol.OFFlowMod; import java.util.List; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -79,6 +81,16 @@ public class OneSwitchFlowInstallCommand extends OneSwitchFlowCommand { return ofMessages; } + @Override + protected Set<SwitchFeature> getRequiredFeatures() { + Set<SwitchFeature> required = super.getRequiredFeatures(); + if (metadata.isMultiTable()) { + required.add(SwitchFeature.MULTI_TABLE); + } + + return required; + } + @Override protected SegmentAction getSegmentAction() { return SegmentAction.INSTALL; diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowRemoveCommand.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowRemoveCommand.java index 63509bbc5..796d6204f 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowRemoveCommand.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowRemoveCommand.java @@ -25,6 +25,7 @@ import org.openkilda.messaging.MessageContext; import org.openkilda.model.FlowEndpoint; import org.openkilda.model.MeterConfig; import org.openkilda.model.MeterId; +import org.openkilda.model.SwitchFeature; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -65,7 +66,7 @@ public class OneSwitchFlowRemoveCommand extends OneSwitchFlowCommand { @Override protected List<OFFlowMod> makeIngressModMessages(MeterId effectiveMeterId) { List<OFFlowMod> ofMessages = super.makeIngressModMessages(effectiveMeterId); - if (rulesContext != null) { + if (getSwitchFeatures().contains(SwitchFeature.MULTI_TABLE) && rulesContext != null) { if (rulesContext.isRemoveCustomerCatchRule()) { ofMessages.add(getFlowModFactory().makeCustomerPortSharedCatchMessage()); } diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressFlowModFactory.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressFlowModFactory.java index 1746cf321..622f21e01 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressFlowModFactory.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressFlowModFactory.java @@ -26,7 +26,6 @@ import org.openkilda.model.SwitchFeature; import org.openkilda.model.cookie.Cookie; import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import lombok.AccessLevel; import lombok.Getter; @@ -35,7 +34,6 @@ import org.projectfloodlight.openflow.protocol.OFFactory; import org.projectfloodlight.openflow.protocol.OFFlowMod; import org.projectfloodlight.openflow.protocol.OFFlowModFlags; import org.projectfloodlight.openflow.protocol.instruction.OFInstruction; -import org.projectfloodlight.openflow.protocol.instruction.OFInstructionWriteMetadata; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.OFPort; @@ -109,8 +107,7 @@ public abstract class IngressFlowModFactory { .setMatch(of.buildMatch() .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .build()) - .setInstructions(ImmutableList.of( - of.instructions().gotoTable(TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)))) + .setInstructions(makeCustomerPortSharedCatchInstructions()) .build(); } @@ -121,12 +118,6 @@ public abstract class IngressFlowModFactory { */ public OFFlowMod makeLldpInputCustomerFlowMessage() { FlowEndpoint endpoint = command.getEndpoint(); - RoutingMetadata metadata = RoutingMetadata.builder().lldpFlag(true).build(switchFeatures); - OFInstructionWriteMetadata writeMetadata = of.instructions().buildWriteMetadata() - .setMetadata(metadata.getValue()) - .setMetadataMask(metadata.getMask()) - .build(); - return flowModBuilderFactory.makeBuilder(of, SwitchManager.INPUT_TABLE_ID) .setPriority(SwitchManager.LLDP_INPUT_CUSTOMER_PRIORITY) .setCookie(U64.of(Cookie.encodeLldpInputCustomer(endpoint.getPortNumber()))) @@ -135,9 +126,8 @@ public abstract class IngressFlowModFactory { .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .setExact(MatchField.ETH_TYPE, EthType.LLDP) .build()) - .setInstructions(ImmutableList.of( - of.instructions().gotoTable(TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)), - writeMetadata)) + .setInstructions(makeConnectedDevicesMatchInstructions( + RoutingMetadata.builder().lldpFlag(true).build(switchFeatures))) .build(); } @@ -148,12 +138,6 @@ public abstract class IngressFlowModFactory { */ public OFFlowMod makeArpInputCustomerFlowMessage() { FlowEndpoint endpoint = command.getEndpoint(); - RoutingMetadata metadata = RoutingMetadata.builder().arpFlag(true).build(switchFeatures); - OFInstructionWriteMetadata writeMetadata = of.instructions().buildWriteMetadata() - .setMetadata(metadata.getValue()) - .setMetadataMask(metadata.getMask()) - .build(); - return flowModBuilderFactory.makeBuilder(of, SwitchManager.INPUT_TABLE_ID) .setPriority(SwitchManager.ARP_INPUT_CUSTOMER_PRIORITY) .setCookie(U64.of(Cookie.encodeArpInputCustomer(endpoint.getPortNumber()))) @@ -162,9 +146,8 @@ public abstract class IngressFlowModFactory { .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .setExact(MatchField.ETH_TYPE, EthType.ARP) .build()) - .setInstructions(ImmutableList.of( - of.instructions().gotoTable(TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)), - writeMetadata)) + .setInstructions(makeConnectedDevicesMatchInstructions( + RoutingMetadata.builder().arpFlag(true).build(switchFeatures))) .build(); } @@ -177,4 +160,8 @@ public abstract class IngressFlowModFactory { } protected abstract List<OFInstruction> makeForwardMessageInstructions(OFFactory of, MeterId effectiveMeterId); + + protected abstract List<OFInstruction> makeCustomerPortSharedCatchInstructions(); + + protected abstract List<OFInstruction> makeConnectedDevicesMatchInstructions(RoutingMetadata metadata); } diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressInstallFlowModFactory.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressInstallFlowModFactory.java index 14469d0bc..364ad82ed 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressInstallFlowModFactory.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressInstallFlowModFactory.java @@ -19,9 +19,11 @@ import org.openkilda.floodlight.command.flow.ingress.IngressFlowSegmentBase; import org.openkilda.floodlight.switchmanager.SwitchManager; import org.openkilda.floodlight.utils.OfAdapter; import org.openkilda.floodlight.utils.OfFlowModBuilderFactory; +import org.openkilda.floodlight.utils.metadata.RoutingMetadata; import org.openkilda.model.MeterId; import org.openkilda.model.SwitchFeature; +import com.google.common.collect.ImmutableList; import net.floodlightcontroller.core.IOFSwitch; import org.projectfloodlight.openflow.protocol.OFFactory; import org.projectfloodlight.openflow.protocol.action.OFAction; @@ -60,6 +62,22 @@ public abstract class IngressInstallFlowModFactory extends IngressFlowModFactory return instructions; } + @Override + protected List<OFInstruction> makeCustomerPortSharedCatchInstructions() { + return ImmutableList.of( + of.instructions().gotoTable(TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID))); + } + + @Override + protected List<OFInstruction> makeConnectedDevicesMatchInstructions(RoutingMetadata metadata) { + return ImmutableList.of( + of.instructions().gotoTable(TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)), + of.instructions().buildWriteMetadata() + .setMetadata(metadata.getValue()) + .setMetadataMask(metadata.getMask()) + .build()); + } + protected abstract List<OFAction> makeTransformActions(); protected abstract List<OFInstruction> makeMetadataInstructions(); diff --git a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressRemoveFlowModFactory.java b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressRemoveFlowModFactory.java index aca3f6cbf..201b59309 100644 --- a/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressRemoveFlowModFactory.java +++ b/src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressRemoveFlowModFactory.java @@ -17,6 +17,7 @@ package org.openkilda.floodlight.command.flow.ingress.of; import org.openkilda.floodlight.command.flow.ingress.IngressFlowSegmentBase; import org.openkilda.floodlight.utils.OfFlowModBuilderFactory; +import org.openkilda.floodlight.utils.metadata.RoutingMetadata; import org.openkilda.model.MeterId; import org.openkilda.model.SwitchFeature; @@ -39,4 +40,14 @@ public abstract class IngressRemoveFlowModFactory extends IngressFlowModFactory protected List<OFInstruction> makeForwardMessageInstructions(OFFactory of, MeterId effectiveMeterId) { return Collections.emptyList(); } + + @Override + protected List<OFInstruction> makeCustomerPortSharedCatchInstructions() { + return Collections.emptyList(); + } + + @Override + protected List<OFInstruction> makeConnectedDevicesMatchInstructions(RoutingMetadata metadata) { + return Collections.emptyList(); + } } diff --git a/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/command/flow/ingress/IngressCommandInstallTest.java b/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/command/flow/ingress/IngressCommandInstallTest.java index 79af6f74e..d5351a824 100644 --- a/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/command/flow/ingress/IngressCommandInstallTest.java +++ b/src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/command/flow/ingress/IngressCommandInstallTest.java @@ -21,7 +21,9 @@ import org.openkilda.floodlight.command.flow.FlowSegmentReport; import org.openkilda.floodlight.error.SwitchErrorResponseException; import org.openkilda.floodlight.error.SwitchOperationException; import org.openkilda.floodlight.error.UnsupportedSwitchOperationException; +import org.openkilda.model.SwitchFeature; +import net.floodlightcontroller.core.IOFSwitch; import org.junit.Assert; import org.junit.Test; import org.projectfloodlight.openflow.protocol.OFBadRequestCode; @@ -34,9 +36,16 @@ import org.projectfloodlight.openflow.protocol.instruction.OFInstructionMeter; import org.projectfloodlight.openflow.protocol.instruction.OFInstructionWriteActions; import java.util.List; +import java.util.Set; import java.util.concurrent.CompletableFuture; abstract class IngressCommandInstallTest extends IngressCommandTest { + @Override + protected void switchFeaturesSetup(IOFSwitch target, Set<SwitchFeature> features) { + features.add(SwitchFeature.MULTI_TABLE); + super.switchFeaturesSetup(target, features); + } + @Test public void noMeterRequested() throws Exception { IngressFlowSegmentBase command = makeCommand(endpointIngressOneVlan, null, makeMetadata());
['src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowInstallCommand.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressRemoveFlowModFactory.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/OneSwitchFlowRemoveCommand.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressFlowModFactory.java', 'src-java/floodlight-service/floodlight-modules/src/test/java/org/openkilda/floodlight/command/flow/ingress/IngressCommandInstallTest.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentRemoveCommand.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/IngressFlowSegmentInstallCommand.java', 'src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/command/flow/ingress/of/IngressInstallFlowModFactory.java']
{'.java': 8}
8
8
0
0
8
7,161,859
1,495,433
187,811
2,078
3,921
707
82
7
224
34
52
10
0
0
2020-05-06T16:52:46
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
10,026
serg-delft/andy/107/106
serg-delft
andy
https://github.com/SERG-Delft/andy/issues/106
https://github.com/SERG-Delft/andy/pull/107
https://github.com/SERG-Delft/andy/pull/107
1
closes
assertThatExceptionOfType is not counted as an assertion by code check
`assertThatExceptionOfType` is not considered an assertion by the TestMethodsHaveAssertions code check: https://github.com/cse1110/andy/blob/main/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java This assertion method as well as all other AssertJ methods that have been missed should be added to this code check.
fb70989e22d025c48335b1ed9683f5cc1397a247
b2d05bbbcb506cc0bafc56f5766a6d8cc1572b16
https://github.com/serg-delft/andy/compare/fb70989e22d025c48335b1ed9683f5cc1397a247...b2d05bbbcb506cc0bafc56f5766a6d8cc1572b16
diff --git a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java index 523423e..76fa129 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java +++ b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java @@ -39,6 +39,13 @@ public class TestMethodsHaveAssertions extends WithinTestMethod { // assertj add("assertThat"); add("assertThatThrownBy"); + add("assertThatExceptionOfType"); + add("assertThatCode"); + add("assertThatIllegalArgumentException"); + add("assertThatIllegalStateException"); + add("assertThatIOException"); + add("assertThatNullPointerException"); + add("assertThatObject"); }};
['src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java']
{'.java': 1}
1
1
0
0
1
195,396
40,112
5,901
89
296
51
7
1
353
33
80
3
1
0
2022-05-14T20:53:31
71
Java
{'Java': 1238634, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Makefile': 12592, 'Dockerfile': 1722, 'NASL': 1620, 'Shell': 63}
MIT License
2,082
telstra/open-kilda/3284/3277
telstra
open-kilda
https://github.com/telstra/open-kilda/issues/3277
https://github.com/telstra/open-kilda/pull/3284
https://github.com/telstra/open-kilda/pull/3284
1
closes
multiTable: intentional rerouteFlow via APIv2 is leavling excess rule
**Steps to reproduce:** * enable singleTable mode on all switches; * create a flow via APIv2; * enable multiTable mode on all switches; * make other path more preferable; * init flow reroute via APIv2 (`"/api/v2/flows/{flow_id}/reroute"`); **Actual result:** Flow is rerouted, but excess rule appeared on involved switches **Expected result:** no excess rule when reroute is completed
06c990975456ed0382915e5f97cea4cf4bee3381
fbfbd5432017cd6b33321bb78a57a2dc05f57ce1
https://github.com/telstra/open-kilda/compare/06c990975456ed0382915e5f97cea4cf4bee3381...fbfbd5432017cd6b33321bb78a57a2dc05f57ce1
diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/FlowRerouteFsm.java b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/FlowRerouteFsm.java index 2b1efece2..928b34ad7 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/FlowRerouteFsm.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/FlowRerouteFsm.java @@ -60,6 +60,7 @@ import org.openkilda.wfm.topology.flowhs.fsm.reroute.actions.UpdateFlowStatusAct import org.openkilda.wfm.topology.flowhs.fsm.reroute.actions.ValidateFlowAction; import org.openkilda.wfm.topology.flowhs.fsm.reroute.actions.ValidateIngressRulesAction; import org.openkilda.wfm.topology.flowhs.fsm.reroute.actions.ValidateNonIngressRulesAction; +import org.openkilda.wfm.topology.flowhs.model.RequestedFlow; import org.openkilda.wfm.topology.flowhs.service.FlowRerouteHubCarrier; import lombok.Getter; @@ -84,6 +85,7 @@ public final class FlowRerouteFsm extends FlowPathSwappingFsm<FlowRerouteFsm, St private boolean rerouteProtected; private boolean effectivelyDown; + private RequestedFlow originalFlow; private FlowStatus originalFlowStatus; private FlowEncapsulationType originalEncapsulationType; diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/RemoveOldRulesAction.java b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/RemoveOldRulesAction.java index 2d0f31b54..7412adbc3 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/RemoveOldRulesAction.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/RemoveOldRulesAction.java @@ -27,6 +27,7 @@ import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteContext; import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteFsm; import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteFsm.Event; import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteFsm.State; +import org.openkilda.wfm.topology.flowhs.mapper.RequestedFlowMapper; import org.openkilda.wfm.topology.flowhs.service.FlowCommandBuilder; import org.openkilda.wfm.topology.flowhs.service.FlowCommandBuilderFactory; @@ -54,18 +55,22 @@ public class RemoveOldRulesAction extends FlowProcessingAction<FlowRerouteFsm, S Collection<FlowSegmentRequestFactory> factories = new ArrayList<>(); + Flow flow = RequestedFlowMapper.INSTANCE.toFlow(stateMachine.getOriginalFlow()); + if (stateMachine.getOldPrimaryForwardPath() != null && stateMachine.getOldPrimaryReversePath() != null) { FlowPath oldForward = getFlowPath(stateMachine.getOldPrimaryForwardPath()); + oldForward.setFlow(flow); FlowPath oldReverse = getFlowPath(stateMachine.getOldPrimaryReversePath()); - Flow flow = oldForward.getFlow(); + oldReverse.setFlow(flow); factories.addAll(commandBuilder.buildAll( stateMachine.getCommandContext(), flow, oldForward, oldReverse)); } if (stateMachine.getOldProtectedForwardPath() != null && stateMachine.getOldProtectedReversePath() != null) { FlowPath oldForward = getFlowPath(stateMachine.getOldProtectedForwardPath()); + oldForward.setFlow(flow); FlowPath oldReverse = getFlowPath(stateMachine.getOldProtectedReversePath()); - Flow flow = oldForward.getFlow(); + oldReverse.setFlow(flow); factories.addAll(commandBuilder.buildAllExceptIngress( stateMachine.getCommandContext(), flow, oldForward, oldReverse)); } diff --git a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/ValidateFlowAction.java b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/ValidateFlowAction.java index 017b3cf12..e3291ce8f 100644 --- a/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/ValidateFlowAction.java +++ b/src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/ValidateFlowAction.java @@ -39,6 +39,7 @@ import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteContext; import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteFsm; import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteFsm.Event; import org.openkilda.wfm.topology.flowhs.fsm.reroute.FlowRerouteFsm.State; +import org.openkilda.wfm.topology.flowhs.mapper.RequestedFlowMapper; import lombok.extern.slf4j.Slf4j; @@ -70,7 +71,7 @@ public class ValidateFlowAction extends NbTrackableAction<FlowRerouteFsm, State, dashboardLogger.onFlowPathReroute(flowId, affectedIsl, context.isForceReroute()); Flow flow = persistenceManager.getTransactionManager().doInTransaction(() -> { - Flow foundFlow = getFlow(flowId, FetchStrategy.NO_RELATIONS); + Flow foundFlow = getFlow(flowId, FetchStrategy.DIRECT_RELATIONS); if (foundFlow.getStatus() == FlowStatus.IN_PROGRESS) { throw new FlowProcessingException(ErrorType.REQUEST_INVALID, format("Flow %s is in progress now", flowId)); @@ -79,6 +80,7 @@ public class ValidateFlowAction extends NbTrackableAction<FlowRerouteFsm, State, stateMachine.setOriginalFlowStatus(foundFlow.getStatus()); stateMachine.setOriginalEncapsulationType(foundFlow.getEncapsulationType()); stateMachine.setRecreateIfSamePath(!foundFlow.isActive() || context.isForceReroute()); + stateMachine.setOriginalFlow(RequestedFlowMapper.INSTANCE.toRequestedFlow(foundFlow)); flowRepository.updateStatus(foundFlow.getFlowId(), FlowStatus.IN_PROGRESS); return foundFlow;
['src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/ValidateFlowAction.java', 'src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/FlowRerouteFsm.java', 'src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/reroute/actions/RemoveOldRulesAction.java']
{'.java': 3}
3
3
0
0
3
6,894,219
1,439,158
181,325
2,010
837
172
15
3
399
57
96
13
0
0
2020-03-12T10:12:21
71
Java
{'Java': 16533357, 'Groovy': 2440542, 'TypeScript': 876184, 'Python': 375764, 'JavaScript': 369015, 'HTML': 366643, 'CSS': 234005, 'C++': 89798, 'Shell': 61998, 'Dockerfile': 30647, 'Makefile': 20530, 'Gherkin': 5609, 'CMake': 4314, 'Jinja': 1187}
Apache License 2.0
10,014
wiiiiam278/huskhomes/392/391
wiiiiam278
huskhomes
https://github.com/WiIIiam278/HuskHomes/issues/391
https://github.com/WiIIiam278/HuskHomes/pull/392
https://github.com/WiIIiam278/HuskHomes/pull/392
1
fixes
Local online user resolution on teleport from username targets by closest match prevents a global exact match
Attempting username resolution against a user that has the partial username of another (i.e requesting a teleport to `APP`, while another user of the name `APPLE` is present on the network) will cause unintended outcomes. Referencing the example, this can result in the use `APPLE` being teleported to INSTEAD of the user `APP`.
b1bd44ac642352ac3c982767a18d0c74a4219146
a11cf17bb1b163b502b2e03d308bb566995d5fc1
https://github.com/wiiiiam278/huskhomes/compare/b1bd44ac642352ac3c982767a18d0c74a4219146...a11cf17bb1b163b502b2e03d308bb566995d5fc1
diff --git a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java index b849e815..d255ecd3 100644 --- a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java +++ b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java @@ -202,7 +202,6 @@ public class BukkitPluginTests { Assertions.assertFalse(plugin.getValidator().isValidName(name)); } - // test descriptions @DisplayName("Test Validator Accepts Valid Descriptions") @ParameterizedTest(name = "Valid Description: \\"{0}\\"") @ValueSource(strings = { @@ -366,7 +365,6 @@ public class BukkitPluginTests { } - // home tests, like warps but with a user parameter (owner) as well as name and position and a test for changing home privacy @Nested @DisplayName("Home Tests") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 3ad6f382..b8c6fb40 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -78,6 +78,31 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver { @NotNull List<OnlineUser> getOnlineUsers(); + /** + * Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match + * + * @param playerName the name of the player to find + * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found + */ + default Optional<OnlineUser> getOnlineUser(@NotNull String playerName) { + return getOnlineUserExact(playerName) + .or(() -> getOnlineUsers().stream() + .filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase())) + .findFirst()); + } + + /** + * Finds a local {@link OnlineUser} by their name. + * + * @param playerName the name of the player to find + * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found + */ + default Optional<OnlineUser> getOnlineUserExact(@NotNull String playerName) { + return getOnlineUsers().stream() + .filter(user -> user.getUsername().equalsIgnoreCase(playerName)) + .findFirst(); + } + @NotNull Set<SavedUser> getSavedUsers(); @@ -111,22 +136,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver { log(Level.INFO, "Successfully initialized " + name); } - /** - * Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match - * - * @param playerName the name of the player to find - * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found - */ - @NotNull - default Optional<OnlineUser> findOnlinePlayer(@NotNull String playerName) { - return getOnlineUsers().stream() - .filter(user -> user.getUsername().equalsIgnoreCase(playerName)) - .findFirst() - .or(() -> getOnlineUsers().stream() - .filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase())) - .findFirst()); - } - /** * The plugin {@link Settings} loaded from file * diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index cc3b17b1..0fd59cc6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -50,7 +50,7 @@ public class RtpCommand extends Command implements UserListTabProvider { @Override public void execute(@NotNull CommandUser executor, @NotNull String[] args) { - final Optional<OnlineUser> optionalTeleporter = args.length >= 1 ? plugin.findOnlinePlayer(args[0]) + final Optional<OnlineUser> optionalTeleporter = args.length >= 1 ? plugin.getOnlineUser(args[0]) : executor instanceof OnlineUser ? Optional.of((OnlineUser) executor) : Optional.empty(); if (optionalTeleporter.isEmpty()) { if (args.length == 0) { diff --git a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index 427efb84..5bb3d77c 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -145,7 +145,7 @@ public class RequestsManager { @NotNull TeleportRequest.Type type) throws IllegalArgumentException { final long expiry = Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime(); final TeleportRequest request = new TeleportRequest(requester, type, expiry); - final Optional<OnlineUser> localTarget = plugin.findOnlinePlayer(targetUser); + final Optional<OnlineUser> localTarget = plugin.getOnlineUser(targetUser); if (localTarget.isPresent()) { if (localTarget.get().equals(requester)) { throw new IllegalArgumentException("Cannot send a teleport request to yourself"); @@ -282,7 +282,7 @@ public class RequestsManager { .ifPresent(recipient::sendMessage); // Find the requester and inform them of the response - final Optional<OnlineUser> localRequester = plugin.findOnlinePlayer(request.getRequesterName()); + final Optional<OnlineUser> localRequester = plugin.getOnlineUser(request.getRequesterName()); if (localRequester.isPresent()) { handleLocalRequestResponse(localRequester.get(), request); } else if (plugin.getSettings().doCrossServer()) { diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Target.java b/common/src/main/java/net/william278/huskhomes/teleport/Target.java index a5eda39b..9cd7a031 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Target.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Target.java @@ -21,8 +21,17 @@ package net.william278.huskhomes.teleport; import org.jetbrains.annotations.NotNull; +/** + * Represents a target; a player name or a location that will be teleported <i>to</i>. + */ public interface Target { + /** + * Create a {@link Target} from a player name + * + * @param target the player name + * @return the target + */ @NotNull static Target username(@NotNull String target) { return new Username(target); diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java index 527cd104..351fb54d 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -35,6 +35,11 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +/** + * Represents the process of a {@link Teleportable} being teleported to a {@link Target}. + * + * @see Teleport#builder(HuskHomes) + */ public class Teleport { protected final HuskHomes plugin; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java index fe1a9b6f..c6291fe8 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java @@ -26,6 +26,9 @@ import org.jetbrains.annotations.NotNull; import java.util.List; +/** + * A builder for {@link Teleport} and {@link TimedTeleport} objects. + */ public class TeleportBuilder { private final HuskHomes plugin; private OnlineUser executor; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java index b379cad5..547d53da 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java @@ -90,6 +90,7 @@ public class TeleportRequest { /** * The user making the request */ + @NotNull public String getRequesterName() { return requesterName; } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java index 759b38bb..e71f87f0 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java @@ -20,9 +20,22 @@ package net.william278.huskhomes.teleport; import org.jetbrains.annotations.NotNull; +import net.william278.huskhomes.user.OnlineUser; +/** + * Represents a teleporter; the person performing the teleport. + * <p> + * Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference + * that needs to be resolved first. + */ public interface Teleportable { + /** + * Create a {@link Teleportable} from a player name + * + * @param teleporter the player name + * @return the teleportable + */ @NotNull static Teleportable username(@NotNull String teleporter) { return new Username(teleporter); diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index cedf12b9..287501cd 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -30,6 +30,11 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +/** + * Represents a {@link Teleport} that has an associated warmup time; the teleport will not be performed until the + * warmup time has elapsed, during which the user must not move or take damage. + * @see Teleport#builder(HuskHomes) + */ public class TimedTeleport extends Teleport { public static final String BYPASS_PERMISSION = "huskhomes.bypass_teleport_warmup"; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Username.java b/common/src/main/java/net/william278/huskhomes/teleport/Username.java index 646e61e5..af9ce00b 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Username.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Username.java @@ -25,11 +25,30 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; +/** + * Represents the username of a player who may or may not be online, either locally as an {@link OnlineUser}, + * or on a different server. + * + * @param name The name of the player + */ public record Username(@NotNull String name) implements Teleportable, Target { + /** + * Search for a local {@link OnlineUser} by their name. + * + * @param plugin The instance of {@link HuskHomes} + * @return An {@link Optional} containing the {@link OnlineUser} if found + * @throws TeleportationException If the user is not found + * @implNote If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this + * method will search for the user by exact name. + * <p> + * Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for + * the closest name match. + */ @NotNull - public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) throws TeleportationException { - return plugin.findOnlinePlayer(name); + public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) { + return plugin.getPlayerList(true).stream().anyMatch(listedName -> listedName.equalsIgnoreCase(name)) + ? plugin.getOnlineUserExact(name) : plugin.getOnlineUser(name); } }
['common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java', 'common/src/main/java/net/william278/huskhomes/teleport/Username.java', 'common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java', 'common/src/main/java/net/william278/huskhomes/command/RtpCommand.java', 'common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java', 'common/src/main/java/net/william278/huskhomes/HuskHomes.java', 'common/src/main/java/net/william278/huskhomes/teleport/Target.java', 'common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java', 'common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java', 'bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java', 'common/src/main/java/net/william278/huskhomes/teleport/Teleport.java']
{'.java': 11}
11
11
0
0
11
854,930
178,974
23,410
191
4,920
1,083
106
10
329
53
71
1
0
0
2023-05-05T00:27:29
68
Java
{'Java': 1018468, 'Shell': 392}
Apache License 2.0
1,056
korpling/annis/337/336
korpling
annis
https://github.com/korpling/ANNIS/issues/336
https://github.com/korpling/ANNIS/pull/337
https://github.com/korpling/ANNIS/pull/337#issuecomment-46556611
1
closes
Existence of directory is not checked when saving corpus properties
By default ANNIS (service) saves corpus properties in the directory `.annis/data` under the user's home directory. It does not ensure that the directory exists, nor do the installation instructions for public servers give any suggestion to create it. So the first time a user attempts to import a corpus, a `FileNotFoundException` is raised and the corpus.properties file is not saved. The fix is trivial.
fa8c590fa111f81868e19edc5d824b6ded036afa
757e6f1ce8960926ddee2aec19c1d524766b0ab9
https://github.com/korpling/annis/compare/fa8c590fa111f81868e19edc5d824b6ded036afa...757e6f1ce8960926ddee2aec19c1d524766b0ab9
diff --git a/annis-service/src/main/java/annis/dao/SpringAnnisDao.java b/annis-service/src/main/java/annis/dao/SpringAnnisDao.java index 7841746c1..99005e534 100644 --- a/annis-service/src/main/java/annis/dao/SpringAnnisDao.java +++ b/annis-service/src/main/java/annis/dao/SpringAnnisDao.java @@ -336,6 +336,17 @@ public class SpringAnnisDao extends SimpleJdbcDaoSupport implements AnnisDao, File dir = getRealDataDir(); + if (!dir.exists()) + { + if (dir.mkdirs()) + { + log.info("Created directory " + dir); + } + else + { + log.error("Directory " + dir + " doesn't exist and cannot be created"); + } + } if (fileName == null) {
['annis-service/src/main/java/annis/dao/SpringAnnisDao.java']
{'.java': 1}
1
1
0
0
1
2,174,345
494,626
76,939
416
238
55
11
1
406
64
80
2
0
0
2014-06-18T23:00:37
66
Java
{'Java': 1687873, 'CSS': 1227164, 'JavaScript': 799395, 'HTML': 359647, 'Python': 342188, 'SCSS': 13834, 'Shell': 4730, 'ANTLR': 1996, 'Makefile': 1509}
Apache License 2.0
265
metafacture/metafacture-core/441/440
metafacture
metafacture-core
https://github.com/metafacture/metafacture-core/issues/440
https://github.com/metafacture/metafacture-core/pull/441
https://github.com/metafacture/metafacture-core/pull/441
1
resolves
Do not trim control field values in MARCXML handler.
Originally introduced in 5bdcd5d, this breaks positional access (`<substring>`) to control field data elements. > For fixed-length fields with various kinds of coded information, specific data elements are positionally defined. _— [MARC 21 Bibliographic - Control Fields](https://www.loc.gov/marc/bibliographic/bd00x.html)_ Related to #233.
89793c7c68999118dc625a18082e8c1f1ed5c1ca
df6a86256da3fc47b4ac1e4c8fbe9a5b953dbbc8
https://github.com/metafacture/metafacture-core/compare/89793c7c68999118dc625a18082e8c1f1ed5c1ca...df6a86256da3fc47b4ac1e4c8fbe9a5b953dbbc8
diff --git a/metafacture-biblio/src/main/java/org/metafacture/biblio/marc21/MarcXmlHandler.java b/metafacture-biblio/src/main/java/org/metafacture/biblio/marc21/MarcXmlHandler.java index a79ecce6..76340b66 100644 --- a/metafacture-biblio/src/main/java/org/metafacture/biblio/marc21/MarcXmlHandler.java +++ b/metafacture-biblio/src/main/java/org/metafacture/biblio/marc21/MarcXmlHandler.java @@ -126,7 +126,7 @@ else if (DATAFIELD.equals(localName)) { getReceiver().endEntity(); } else if (CONTROLFIELD.equals(localName)) { - getReceiver().literal(currentTag, builder.toString().trim()); + getReceiver().literal(currentTag, builder.toString()); } else if (RECORD.equals(localName) && checkNamespace(uri)) { getReceiver().endRecord(); diff --git a/metafacture-biblio/src/test/java/org/metafacture/biblio/marc21/MarcXmlHandlerTest.java b/metafacture-biblio/src/test/java/org/metafacture/biblio/marc21/MarcXmlHandlerTest.java index 3902a604..8a9f8c86 100644 --- a/metafacture-biblio/src/test/java/org/metafacture/biblio/marc21/MarcXmlHandlerTest.java +++ b/metafacture-biblio/src/test/java/org/metafacture/biblio/marc21/MarcXmlHandlerTest.java @@ -77,6 +77,20 @@ public void shouldFindTagAttributeAtSecondPositionInControlFieldElement() verify(receiver).literal("001", fieldValue); } + @Test + public void issue440_shouldNotRemoveWhitespaceFromControlFields() throws SAXException { + final AttributesImpl attributes = new AttributesImpl(); + attributes.addAttribute(NAMESPACE, "tag", "tag", "CDATA", "008"); + + final String fieldValue = " t20202020au |||||||||||| ||||ger d"; + + marcXmlHandler.startElement(NAMESPACE, CONTROLFIELD, "", attributes); + marcXmlHandler.characters(fieldValue.toCharArray(), 0, fieldValue.length()); + marcXmlHandler.endElement(NAMESPACE, CONTROLFIELD, ""); + + verify(receiver).literal("008", fieldValue); + } + @Test public void issue233ShouldNotRemoveWhitespaceFromLeader() throws SAXException {
['metafacture-biblio/src/main/java/org/metafacture/biblio/marc21/MarcXmlHandler.java', 'metafacture-biblio/src/test/java/org/metafacture/biblio/marc21/MarcXmlHandlerTest.java']
{'.java': 2}
2
2
0
0
2
1,164,082
246,757
38,384
340
142
24
2
1
349
40
80
7
1
0
2022-02-15T14:42:14
65
Java
{'Java': 2061460, 'GAP': 9719, 'Shell': 5031, 'Batchfile': 2118, 'JavaScript': 97}
Apache License 2.0
9,313
cse1110/andy/101/99
cse1110
andy
https://github.com/SERG-Delft/andy/issues/99
https://github.com/SERG-Delft/andy/pull/101
https://github.com/SERG-Delft/andy/pull/101
1
closes
Score of 100/100 is possible even if not everything is completed
Grades >= 99.5 get rounded up to 100. This is an edge case: any grade between 99 and 100 should be rounded down to 99, otherwise students may get confused and think that they have completed an exercise even if they haven't actually passed everything. For example: ``` Status: Done Andy v0.27.1-85578d2 (2022-04-25T09:29:42+0000) [...] --- Assessment Branch coverage: 20/21 (overall weight=0.10) Mutation coverage: 27/27 (overall weight=0.30) Code checks: 0/0 (overall weight=0.00) Meta tests: 17/17 (overall weight=0.60) Final grade: 100/100 Super congrats! [...] ``` Note the number of covered branches - only 20 out of 21 branches are covered, but due to the low weight of the branch coverage score, this branch is worth less than 0.5/100, so the final score becomes 99.5/100, which Andy incorrectly rounds up to 100/100.
b1d07f8e5a7703f30f1719afbe5b9166c68e0f23
1a2e3182b0b8552063485a3a0ccf1ea1d0b931b9
https://github.com/cse1110/andy/compare/b1d07f8e5a7703f30f1719afbe5b9166c68e0f23...1a2e3182b0b8552063485a3a0ccf1ea1d0b931b9
diff --git a/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java b/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java index d6ccdc3..6e71536 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java +++ b/src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java @@ -24,6 +24,11 @@ public class GradeCalculator { if(finalGrade < 0 || finalGrade > 100) throw new RuntimeException("Invalid grade calculation"); + // Grades between 99.5 and 100 should be rounded down to 99 instead of up + if (finalGrade == 100 && hasIncompleteComponents(gradeValues, weights)) { + finalGrade = 99; + } + return finalGrade; } @@ -79,4 +84,16 @@ public class GradeCalculator { return (float)checksPassed / totalChecks; } + /** + * @param gradeValues the grade values + * @param weights the weights + * @return whether any of the components with positive weight are incomplete + */ + private boolean hasIncompleteComponents(GradeValues gradeValues, GradeWeight weights) { + return weights.getBranchCoverageWeight() > 0.0f && gradeValues.getCoveredBranches() < gradeValues.getTotalBranches() || + weights.getMutationCoverageWeight() > 0.0f && gradeValues.getDetectedMutations() < gradeValues.getTotalMutations() || + weights.getMetaTestsWeight() > 0.0f && gradeValues.getMetaTestsPassed() < gradeValues.getTotalMetaTests() || + weights.getCodeChecksWeight() > 0.0f && gradeValues.getChecksPassed() < gradeValues.getTotalChecks(); + } + } diff --git a/src/test/java/unit/grade/GradeCalculatorTest.java b/src/test/java/unit/grade/GradeCalculatorTest.java index d834ba6..2d340ec 100644 --- a/src/test/java/unit/grade/GradeCalculatorTest.java +++ b/src/test/java/unit/grade/GradeCalculatorTest.java @@ -3,6 +3,7 @@ package unit.grade; import nl.tudelft.cse1110.andy.grade.GradeCalculator; import nl.tudelft.cse1110.andy.grade.GradeValues; import nl.tudelft.cse1110.andy.grade.GradeWeight; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -81,4 +82,52 @@ public class GradeCalculatorTest { of(25, 25, 55, 55, 100, 100, 2, 5, 94) // 0.4*1 + 0.3*1 + 0.2*1 + 0.1*(2/5) = 0.94 --> 94 ); } + + /* + * Test where the grade is between 99.5 and 100, should be rounded down to 99 and not + * rounded up to 100, as 100 should only be achievable if everything + * with a positive weight is fully completed. + */ + @Test + void withGradeBetween99And100() { + GradeWeight weights = new GradeWeight(0.1f, 0.3f, 0.6f, 0.0f); + + GradeValues grades = new GradeValues(); + grades.setBranchGrade(20, 21); + grades.setMutationGrade(27, 27); + grades.setMetaGrade(17, 17); + grades.setCheckGrade(0, 0); + + int finalGrade = new GradeCalculator().calculateFinalGrade(grades, weights); + + assertThat(finalGrade).isEqualTo(99); + } + + @ParameterizedTest + @MethodSource("zeroWeights") + void withZeroWeights(int coveredBranches, int totalBranches, + int detectedMutations, int totalMutations, + int metaTestsPassed, int totalMetaTests, + int checksPassed, int totalChecks, int expectedGrade) { + + GradeWeight weights = new GradeWeight(0.4f, 0.0f, 0.5f, 0.1f); + + GradeValues grades = new GradeValues(); + grades.setBranchGrade(coveredBranches, totalBranches); + grades.setMutationGrade(detectedMutations, totalMutations); + grades.setMetaGrade(metaTestsPassed, totalMetaTests); + grades.setCheckGrade(checksPassed, totalChecks); + + int finalGrade = new GradeCalculator().calculateFinalGrade(grades, weights); + + assertThat(finalGrade).isEqualTo(expectedGrade); + } + + private static Stream<Arguments> zeroWeights() { + return Stream.of( + of(25, 25, 2, 55, 100, 100, 5, 5, 100), // 0.4*1 + 0*(2/55) + 0.5*1 + 0.1*1 = 1.0 --> 100 + of(25, 25, 2, 55, 100, 100, 4, 5, 98), // 0.4*1 + 0*(2/55) + 0.5*1 + 0.1*(4/5) = 0.98 --> 98 + of(25, 25, 55, 55, 100, 100, 4, 5, 98) // 0.4*1 + 0*1 + 0.5*1 + 0.1*(4/5) = 0.98 --> 98 + ); + } }
['src/main/java/nl/tudelft/cse1110/andy/grade/GradeCalculator.java', 'src/test/java/unit/grade/GradeCalculatorTest.java']
{'.java': 2}
2
2
0
0
2
194,190
39,847
5,881
89
999
226
17
1
860
129
248
25
0
1
2022-04-29T23:05:50
65
Java
{'Java': 1190111, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Python': 2949}
MIT License
9,315
cse1110/andy/86/83
cse1110
andy
https://github.com/SERG-Delft/andy/issues/83
https://github.com/SERG-Delft/andy/pull/86
https://github.com/SERG-Delft/andy/pull/86
1
fixes
Overload Andy constructor
Overload the Andy constructor in order to preserve backward compatibility after the changes introduced in #70 as those changes break the Maven plugin
28faca02fe2c80e58ca06a01390cf6007fb96f32
86803722431cb76859ee539f530eeeb82c7047ee
https://github.com/cse1110/andy/compare/28faca02fe2c80e58ca06a01390cf6007fb96f32...86803722431cb76859ee539f530eeeb82c7047ee
diff --git a/src/main/java/nl/tudelft/cse1110/andy/Andy.java b/src/main/java/nl/tudelft/cse1110/andy/Andy.java index 1aaef12..342db50 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/Andy.java +++ b/src/main/java/nl/tudelft/cse1110/andy/Andy.java @@ -33,10 +33,18 @@ public class Andy { this.metaData = metaData; } + public Andy(Action action, String workDir, String outputDir, List<String> librariesToBeIncluded, ResultWriter writer) { + this(action, workDir, outputDir, librariesToBeIncluded, writer, SubmissionMetaData.empty()); + } + public Andy(Action action, String workDir, String outputDir, ResultWriter writer, SubmissionMetaData metaData) { this(action, workDir, outputDir, null, writer, metaData); } + public Andy(Action action, String workDir, String outputDir, ResultWriter writer) { + this(action, workDir, outputDir, null, writer); + } + public void run() { Context ctx = buildContext(); diff --git a/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java b/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java index f25a358..5eb64de 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java +++ b/src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java @@ -10,4 +10,8 @@ public class SubmissionMetaData { this.studentId = studentId; this.exercise = exercise; } + + public static SubmissionMetaData empty() { + return new SubmissionMetaData(null, null, null); + } } \\ No newline at end of file
['src/main/java/nl/tudelft/cse1110/andy/Andy.java', 'src/main/java/nl/tudelft/cse1110/andy/writer/weblab/SubmissionMetaData.java']
{'.java': 2}
2
2
0
0
2
194,498
39,940
5,901
88
504
107
12
2
149
23
25
1
0
0
2021-12-21T22:39:27
65
Java
{'Java': 1190111, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Python': 2949}
MIT License
9,310
cse1110/andy/112/111
cse1110
andy
https://github.com/SERG-Delft/andy/issues/111
https://github.com/SERG-Delft/andy/pull/112
https://github.com/SERG-Delft/andy/pull/112
1
closes
Assessing time message phrasing is incorrect
https://github.com/cse1110/andy/blob/4e53516cc38247149e281646700dd116d8167323/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java#L194 The word `question` should be replaced with `solution`.
e3095a639b2fff45a2df509a5fa1293fd005ed39
5b839c6ad771c0355b651748778840fd9edb9262
https://github.com/cse1110/andy/compare/e3095a639b2fff45a2df509a5fa1293fd005ed39...5b839c6ad771c0355b651748778840fd9edb9262
diff --git a/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java b/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java index cad447d..52c9b6d 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java +++ b/src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java @@ -191,7 +191,7 @@ public class StandardResultWriter implements ResultWriter { if(modeActionSelector(ctx)!=null) l(String.format("\\nAndy is running in %s mode and took %.1f seconds to assess your solution.", modeActionSelector(ctx).getMode().toString(), timeInSeconds)); else - l(String.format("\\nAndy took %.1f seconds to assess your question.", timeInSeconds)); + l(String.format("\\nAndy took %.1f seconds to assess your solution.", timeInSeconds)); } private void printMetaTestResults(Context ctx, MetaTestsResult metaTests) {
['src/main/java/nl/tudelft/cse1110/andy/writer/standard/StandardResultWriter.java']
{'.java': 1}
1
1
0
0
1
195,939
40,216
5,916
89
197
40
2
1
221
9
70
3
1
0
2022-05-17T21:40:15
65
Java
{'Java': 1190111, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Python': 2949}
MIT License
9,311
cse1110/andy/110/109
cse1110
andy
https://github.com/SERG-Delft/andy/issues/109
https://github.com/SERG-Delft/andy/pull/110
https://github.com/SERG-Delft/andy/pull/110
1
closes
`assertNull` is not considered an assertion by code check
`assertNull` is not considered an assertion by the TestMethodsHaveAssertions code check: https://github.com/cse1110/andy/blob/main/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java This assertion method as well as other JUnit methods that have been missed should be added to this code check.
8932a6199da9c6e5760e646fe4ebbdd4b96baa55
594ae60cd6d906ca3f8c8373cf29c7630cb192ed
https://github.com/cse1110/andy/compare/8932a6199da9c6e5760e646fe4ebbdd4b96baa55...594ae60cd6d906ca3f8c8373cf29c7630cb192ed
diff --git a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java index 76fa129..06db6b4 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java +++ b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java @@ -35,6 +35,14 @@ public class TestMethodsHaveAssertions extends WithinTestMethod { add("assertTrue"); add("assertFalse"); add("assertThrows"); + add("assertNull"); + add("assertArrayEquals"); + add("assertDoesNotThrow"); + add("assertIterableEquals"); + add("assertLinesMatch"); + add("assertNotNull"); + add("assertNotSame"); + add("assertSame"); // assertj add("assertThat");
['src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java']
{'.java': 1}
1
1
0
0
1
195,686
40,163
5,908
89
260
53
8
1
332
32
77
3
1
0
2022-05-16T20:53:45
65
Java
{'Java': 1190111, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Python': 2949}
MIT License
266
metafacture/metafacture-core/344/343
metafacture
metafacture-core
https://github.com/metafacture/metafacture-core/issues/343
https://github.com/metafacture/metafacture-core/pull/344
https://github.com/metafacture/metafacture-core/pull/344
1
fixes
JSON-LD keywords in input data break _else pass-through in morph
Somehow data input field names like `@id`, `@graph` end up in morph feedback/recursion and are missing in the output. This came up in https://gitlab.com/oersi/oersi-etl/-/issues/29#note_453341447 and I've implemented a fix for metafacture-fix in https://github.com/metafacture/metafacture-fix/commit/f4dc31dbb3a1aae86cfef9811f4f074f1ab87a61. I'll branch off from https://github.com/metafacture/metafacture-core/pull/342 to add a test case for metamorph.
89a3b261f6cd34e9d65c8e28b35e45c6d5165df1
15c29d9f5ebd25bcae78eaa84fc6f9e351d4fab2
https://github.com/metafacture/metafacture-core/compare/89a3b261f6cd34e9d65c8e28b35e45c6d5165df1...15c29d9f5ebd25bcae78eaa84fc6f9e351d4fab2
diff --git a/metamorph/src/main/java/org/metafacture/metamorph/Metamorph.java b/metamorph/src/main/java/org/metafacture/metamorph/Metamorph.java index 43dd9a17..e38b9d05 100644 --- a/metamorph/src/main/java/org/metafacture/metamorph/Metamorph.java +++ b/metamorph/src/main/java/org/metafacture/metamorph/Metamorph.java @@ -338,11 +338,11 @@ else if (fallbackReceiver != null) { elseNestedEntityStarted = true; } - send(currentLiteralName, value, fallbackReceiver); + send(escapeFeedbackChar(currentLiteralName), value, fallbackReceiver); } } else { - send(path, value, fallbackReceiver); + send(escapeFeedbackChar(path), value, fallbackReceiver); } } } @@ -363,6 +363,14 @@ private void send(final String path, final String value, final List<NamedValueRe } } + private boolean startsWithFeedbackChar(final String name) { + return name.length() != 0 && name.charAt(0) == FEEDBACK_CHAR; + } + + private String escapeFeedbackChar(final String name) { + return name == null ? null : (startsWithFeedbackChar(name) ? ESCAPE_CHAR : "") + name; + } + /** * @param streamReceiver * the outputHandler to set @@ -388,7 +396,7 @@ public void receive(final String name, final String value, final NamedValueSourc "encountered literal with name='null'. This indicates a bug in a function or a collector."); } - if (name.length() != 0 && name.charAt(0) == FEEDBACK_CHAR) { + if (startsWithFeedbackChar(name)) { dispatch(name, value, null, false); return; } diff --git a/metamorph/src/test/java/org/metafacture/metamorph/TestMetamorphBasics.java b/metamorph/src/test/java/org/metafacture/metamorph/TestMetamorphBasics.java index 6345b8ea..7f551ba1 100644 --- a/metamorph/src/test/java/org/metafacture/metamorph/TestMetamorphBasics.java +++ b/metamorph/src/test/java/org/metafacture/metamorph/TestMetamorphBasics.java @@ -106,6 +106,7 @@ private void testElseData(final String elseKeyword) { "</rules>", i -> { i.startRecord("1"); + i.literal("@id", "123"); i.literal("Shikotan", "Aekap"); i.startEntity("Germany"); i.literal("Langeoog", "Moin"); @@ -113,18 +114,21 @@ private void testElseData(final String elseKeyword) { i.literal("Borkum", "Tach"); i.endEntity(); i.startEntity("Germany"); + i.literal("@foo", "bar"); i.literal("Baltrum", "Moin Moin"); i.endEntity(); i.endRecord(); }, o -> { o.get().startRecord("1"); + o.get().literal("@id", "123"); o.get().literal("Shikotan", "Aekap"); o.get().literal("Germany.Langeoog", "Moin"); o.get().startEntity("Germany"); o.get().literal("Hawaii", "Aloha"); o.get().literal("Germany.Borkum", "Tach"); o.get().endEntity(); + o.get().literal("Germany.@foo", "bar"); o.get().literal("Germany.Baltrum", "Moin Moin"); o.get().endRecord(); } @@ -223,8 +227,10 @@ public void shouldHandleUnmatchedLiteralsAndEntitiesInElseNestedSource() { "</rules>", i -> { i.startRecord("1"); + i.literal("@id", "123"); i.literal("Shikotan", "Aekap"); i.startEntity("Germany"); + i.literal("@foo", "bar"); i.literal("Langeoog", "Moin"); i.literal("Baltrum", "Moin Moin"); i.endEntity(); @@ -235,8 +241,10 @@ public void shouldHandleUnmatchedLiteralsAndEntitiesInElseNestedSource() { }, o -> { o.get().startRecord("1"); + o.get().literal("@id", "123"); o.get().literal("Shikotan", "Aekap"); o.get().startEntity("Germany"); + o.get().literal("@foo", "bar"); o.get().literal("Langeoog", "Moin"); o.get().literal("Baltrum", "Moin Moin"); o.get().endEntity();
['metamorph/src/main/java/org/metafacture/metamorph/Metamorph.java', 'metamorph/src/test/java/org/metafacture/metamorph/TestMetamorphBasics.java']
{'.java': 2}
2
2
0
0
2
1,021,295
215,098
32,702
337
732
149
14
1
457
45
138
3
3
0
2020-11-26T10:04:59
65
Java
{'Java': 2061460, 'GAP': 9719, 'Shell': 5031, 'Batchfile': 2118, 'JavaScript': 97}
Apache License 2.0
9,312
cse1110/andy/107/106
cse1110
andy
https://github.com/SERG-Delft/andy/issues/106
https://github.com/SERG-Delft/andy/pull/107
https://github.com/SERG-Delft/andy/pull/107
1
closes
assertThatExceptionOfType is not counted as an assertion by code check
`assertThatExceptionOfType` is not considered an assertion by the TestMethodsHaveAssertions code check: https://github.com/cse1110/andy/blob/main/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java This assertion method as well as all other AssertJ methods that have been missed should be added to this code check.
fb70989e22d025c48335b1ed9683f5cc1397a247
b2d05bbbcb506cc0bafc56f5766a6d8cc1572b16
https://github.com/cse1110/andy/compare/fb70989e22d025c48335b1ed9683f5cc1397a247...b2d05bbbcb506cc0bafc56f5766a6d8cc1572b16
diff --git a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java index 523423e..76fa129 100644 --- a/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java +++ b/src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java @@ -39,6 +39,13 @@ public class TestMethodsHaveAssertions extends WithinTestMethod { // assertj add("assertThat"); add("assertThatThrownBy"); + add("assertThatExceptionOfType"); + add("assertThatCode"); + add("assertThatIllegalArgumentException"); + add("assertThatIllegalStateException"); + add("assertThatIOException"); + add("assertThatNullPointerException"); + add("assertThatObject"); }};
['src/main/java/nl/tudelft/cse1110/andy/codechecker/checks/TestMethodsHaveAssertions.java']
{'.java': 1}
1
1
0
0
1
195,396
40,112
5,901
89
296
51
7
1
353
33
80
3
1
0
2022-05-14T20:53:31
65
Java
{'Java': 1190111, 'JavaScript': 110694, 'HTML': 97754, 'CSS': 91695, 'TypeScript': 22968, 'Python': 2949}
MIT License
9,392
kaotoio/kaoto-backend/730/728
kaotoio
kaoto-backend
https://github.com/KaotoIO/kaoto-backend/issues/728
https://github.com/KaotoIO/kaoto-backend/pull/730
https://github.com/KaotoIO/kaoto-backend/pull/730
1
fixes
[BUG] Documentation GitHub workflow is broken: Invalid miniclass definition: DSLSpecification
**Describe the bug** ``` > @ docs-api /home/runner/work/kaoto-backend/kaoto-backend > leafdoc -t leafdoc-templates/plain -o docs/index.html -c "🐱" leafdoc-templates/index.leafdoc */src/main/java/ -e true -x .java Invalid miniclass definition: DSLSpecification Error: No class/namespace set when parsing through: null 🐱method identifier: String Returns the identifier of the supported language. This must be unique on the whole Kaoto instance and relates the deployments and parsers services with the DSL specification. file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:371 if (!currentNamespace.supersections.hasOwnProperty(dt)) { ^ TypeError: Cannot read property 'supersections' of undefined at Leafdoc.addStr (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:371:28) at Leafdoc.addBuffer (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:193:15) at Leafdoc.addFile (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:185:15) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:174:10) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:169:10) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:169:10) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:169:10) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:169:10) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:169:10) at Leafdoc.addDir (file:///home/runner/work/kaoto-backend/kaoto-backend/node_modules/leafdoc/src/leafdoc.mjs:169:10) ``` **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** Documentation GitHub action working **Logs** If applicable, add logs to help explain your problem. **Environment (please complete the following information):** **Additional context** failure was relatively hidden because another job is failign for a long time and so there was a red cross on all commit of main branch for a very long time https://github.com/KaotoIO/kaoto-backend/issues/530
411a91e0d79e895c5ded32c5a6fe0340cc059d43
bf66b8331811247fb1204a36f2531062125b3b69
https://github.com/kaotoio/kaoto-backend/compare/411a91e0d79e895c5ded32c5a6fe0340cc059d43...bf66b8331811247fb1204a36f2531062125b3b69
diff --git a/services-interfaces/src/main/java/io/kaoto/backend/api/service/dsl/DSLSpecification.java b/services-interfaces/src/main/java/io/kaoto/backend/api/service/dsl/DSLSpecification.java index c55d9cbc..45ce3198 100644 --- a/services-interfaces/src/main/java/io/kaoto/backend/api/service/dsl/DSLSpecification.java +++ b/services-interfaces/src/main/java/io/kaoto/backend/api/service/dsl/DSLSpecification.java @@ -12,7 +12,7 @@ import java.util.Objects; import java.util.function.Predicate; /** - * 🐱miniclass DSLSpecification + * 🐱class DSLSpecification * <p> * <p> * 🐱section
['services-interfaces/src/main/java/io/kaoto/backend/api/service/dsl/DSLSpecification.java']
{'.java': 1}
1
1
0
0
1
888,104
174,126
25,423
204
59
21
2
1
2,585
186
686
53
1
1
2023-06-28T10:03:32
63
Java
{'Java': 1180804, 'Handlebars': 15423, 'Shell': 10824, 'HTML': 5156}
Apache License 2.0
9,030
ballerina-platform/ballerina-distribution/358/350
ballerina-platform
ballerina-distribution
https://github.com/ballerina-platform/ballerina-distribution/issues/350
https://github.com/ballerina-platform/ballerina-distribution/pull/358
https://github.com/ballerina-platform/ballerina-distribution/pull/358
1
fixes
Language server launcher scripts does not have executable permission when pulling the distribution using the updater tool
**Description:** Please note $title for jballerina-1.1.0-beta distribution, which affects the IntelliJ plugin and ends up as a language server initialization failure. **Suggested Labels:** <!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels--> **Suggested Assignees:** <!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees--> **Affected Product Version:** - OS - Ubuntu 18.04.3 LTS - Ballerina version - jBallerina 1.1.0-beta - Language specification 2019R3 - Command 1.1.0-alpha **OS, DB, other environment details and versions:** **Steps to reproduce:** **Related Issues:** <!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. -->
854a3b36c452dbf22c1bd42eaf1a26cff124326c
db982268b7b50e85fdcb62b1b85994d857c9884a
https://github.com/ballerina-platform/ballerina-distribution/compare/854a3b36c452dbf22c1bd42eaf1a26cff124326c...db982268b7b50e85fdcb62b1b85994d857c9884a
diff --git a/ballerina-command/src/main/java/org/ballerinalang/command/util/OSUtils.java b/ballerina-command/src/main/java/org/ballerinalang/command/util/OSUtils.java index cb69e524f..11042ee6b 100644 --- a/ballerina-command/src/main/java/org/ballerinalang/command/util/OSUtils.java +++ b/ballerina-command/src/main/java/org/ballerinalang/command/util/OSUtils.java @@ -57,14 +57,7 @@ public class OSUtils { * @return name of the file */ public static String getExecutableFileName() { - if (OSUtils.isWindows()) { - return "ballerina.bat"; - } else if (OSUtils.isUnix() || OSUtils.isSolaris()) { - return "ballerina"; - } else if (OSUtils.isMac()) { - return "ballerina"; - } - return null; + return OSUtils.isWindows() ? "ballerina.bat" : "ballerina"; } /** @@ -72,14 +65,23 @@ public class OSUtils { * @return name of the file */ public static String getInstallScriptFileName() { - if (OSUtils.isWindows()) { - return "install.bat"; - } else if (OSUtils.isUnix() || OSUtils.isSolaris()) { - return "install"; - } else if (OSUtils.isMac()) { - return "install"; - } - return null; + return OSUtils.isWindows() ? "install.bat" : "install"; + } + + /** + * Provide file name of debug adapter script for current operating system. + * @return name of the file + */ + public static String getDebugAdapterName() { + return OSUtils.isWindows() ? "debug-adapter-launcher.bat" : "debug-adapter-launcher.sh"; + } + + /** + * Provide file name of language server launcher script for current operating system. + * @return name of the file + */ + public static String getLangServerLauncherName() { + return OSUtils.isWindows() ? "language-server-launcher.bat" : "language-server-launcher.sh"; } public static String getBallerinaVersionFilePath() throws IOException { diff --git a/ballerina-command/src/main/java/org/ballerinalang/command/util/ToolUtil.java b/ballerina-command/src/main/java/org/ballerinalang/command/util/ToolUtil.java index 3dedd5521..b84143acd 100644 --- a/ballerina-command/src/main/java/org/ballerinalang/command/util/ToolUtil.java +++ b/ballerina-command/src/main/java/org/ballerinalang/command/util/ToolUtil.java @@ -385,6 +385,23 @@ public class ToolUtil { addExecutablePermissionToFile(new File(distPath + File.separator + distribution + File.separator + "bin" + File.separator + OSUtils.getExecutableFileName())); + + + String langServerPath = distPath + File.separator + distribution + File.separator + "lib" + + File.separator + "tools"; + File launcherServer = new File(langServerPath + File.separator + "lang-server" + + File.separator + "launcher" + File.separator + OSUtils.getLangServerLauncherName()); + File debugAdpater = new File(langServerPath + File.separator + "debug-adapter" + + File.separator + "launcher" + File.separator + OSUtils.getDebugAdapterName()); + + if (debugAdpater.exists()) { + addExecutablePermissionToFile(debugAdpater); + } + + if (launcherServer.exists()) { + addExecutablePermissionToFile(launcherServer); + } + new File(zipFileLocation).delete(); } finally { conn.disconnect();
['ballerina-command/src/main/java/org/ballerinalang/command/util/ToolUtil.java', 'ballerina-command/src/main/java/org/ballerinalang/command/util/OSUtils.java']
{'.java': 2}
2
2
0
0
2
84,205
16,806
2,344
20
2,085
442
51
2
1,062
144
241
25
0
0
2019-12-17T13:11:23
63
Java
{'Java': 300258, 'Ballerina': 216591, 'Shell': 16993, 'Batchfile': 5737}
Apache License 2.0
9,164
wiiiiam278/huskhomes2/392/391
wiiiiam278
huskhomes2
https://github.com/WiIIiam278/HuskHomes/issues/391
https://github.com/WiIIiam278/HuskHomes/pull/392
https://github.com/WiIIiam278/HuskHomes/pull/392
1
fixes
Local online user resolution on teleport from username targets by closest match prevents a global exact match
Attempting username resolution against a user that has the partial username of another (i.e requesting a teleport to `APP`, while another user of the name `APPLE` is present on the network) will cause unintended outcomes. Referencing the example, this can result in the use `APPLE` being teleported to INSTEAD of the user `APP`.
b1bd44ac642352ac3c982767a18d0c74a4219146
a11cf17bb1b163b502b2e03d308bb566995d5fc1
https://github.com/wiiiiam278/huskhomes2/compare/b1bd44ac642352ac3c982767a18d0c74a4219146...a11cf17bb1b163b502b2e03d308bb566995d5fc1
diff --git a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java index b849e815..d255ecd3 100644 --- a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java +++ b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java @@ -202,7 +202,6 @@ public class BukkitPluginTests { Assertions.assertFalse(plugin.getValidator().isValidName(name)); } - // test descriptions @DisplayName("Test Validator Accepts Valid Descriptions") @ParameterizedTest(name = "Valid Description: \\"{0}\\"") @ValueSource(strings = { @@ -366,7 +365,6 @@ public class BukkitPluginTests { } - // home tests, like warps but with a user parameter (owner) as well as name and position and a test for changing home privacy @Nested @DisplayName("Home Tests") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 3ad6f382..b8c6fb40 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -78,6 +78,31 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver { @NotNull List<OnlineUser> getOnlineUsers(); + /** + * Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match + * + * @param playerName the name of the player to find + * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found + */ + default Optional<OnlineUser> getOnlineUser(@NotNull String playerName) { + return getOnlineUserExact(playerName) + .or(() -> getOnlineUsers().stream() + .filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase())) + .findFirst()); + } + + /** + * Finds a local {@link OnlineUser} by their name. + * + * @param playerName the name of the player to find + * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found + */ + default Optional<OnlineUser> getOnlineUserExact(@NotNull String playerName) { + return getOnlineUsers().stream() + .filter(user -> user.getUsername().equalsIgnoreCase(playerName)) + .findFirst(); + } + @NotNull Set<SavedUser> getSavedUsers(); @@ -111,22 +136,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver { log(Level.INFO, "Successfully initialized " + name); } - /** - * Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match - * - * @param playerName the name of the player to find - * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found - */ - @NotNull - default Optional<OnlineUser> findOnlinePlayer(@NotNull String playerName) { - return getOnlineUsers().stream() - .filter(user -> user.getUsername().equalsIgnoreCase(playerName)) - .findFirst() - .or(() -> getOnlineUsers().stream() - .filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase())) - .findFirst()); - } - /** * The plugin {@link Settings} loaded from file * diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index cc3b17b1..0fd59cc6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -50,7 +50,7 @@ public class RtpCommand extends Command implements UserListTabProvider { @Override public void execute(@NotNull CommandUser executor, @NotNull String[] args) { - final Optional<OnlineUser> optionalTeleporter = args.length >= 1 ? plugin.findOnlinePlayer(args[0]) + final Optional<OnlineUser> optionalTeleporter = args.length >= 1 ? plugin.getOnlineUser(args[0]) : executor instanceof OnlineUser ? Optional.of((OnlineUser) executor) : Optional.empty(); if (optionalTeleporter.isEmpty()) { if (args.length == 0) { diff --git a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index 427efb84..5bb3d77c 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -145,7 +145,7 @@ public class RequestsManager { @NotNull TeleportRequest.Type type) throws IllegalArgumentException { final long expiry = Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime(); final TeleportRequest request = new TeleportRequest(requester, type, expiry); - final Optional<OnlineUser> localTarget = plugin.findOnlinePlayer(targetUser); + final Optional<OnlineUser> localTarget = plugin.getOnlineUser(targetUser); if (localTarget.isPresent()) { if (localTarget.get().equals(requester)) { throw new IllegalArgumentException("Cannot send a teleport request to yourself"); @@ -282,7 +282,7 @@ public class RequestsManager { .ifPresent(recipient::sendMessage); // Find the requester and inform them of the response - final Optional<OnlineUser> localRequester = plugin.findOnlinePlayer(request.getRequesterName()); + final Optional<OnlineUser> localRequester = plugin.getOnlineUser(request.getRequesterName()); if (localRequester.isPresent()) { handleLocalRequestResponse(localRequester.get(), request); } else if (plugin.getSettings().doCrossServer()) { diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Target.java b/common/src/main/java/net/william278/huskhomes/teleport/Target.java index a5eda39b..9cd7a031 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Target.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Target.java @@ -21,8 +21,17 @@ package net.william278.huskhomes.teleport; import org.jetbrains.annotations.NotNull; +/** + * Represents a target; a player name or a location that will be teleported <i>to</i>. + */ public interface Target { + /** + * Create a {@link Target} from a player name + * + * @param target the player name + * @return the target + */ @NotNull static Target username(@NotNull String target) { return new Username(target); diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java index 527cd104..351fb54d 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -35,6 +35,11 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +/** + * Represents the process of a {@link Teleportable} being teleported to a {@link Target}. + * + * @see Teleport#builder(HuskHomes) + */ public class Teleport { protected final HuskHomes plugin; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java index fe1a9b6f..c6291fe8 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java @@ -26,6 +26,9 @@ import org.jetbrains.annotations.NotNull; import java.util.List; +/** + * A builder for {@link Teleport} and {@link TimedTeleport} objects. + */ public class TeleportBuilder { private final HuskHomes plugin; private OnlineUser executor; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java index b379cad5..547d53da 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java @@ -90,6 +90,7 @@ public class TeleportRequest { /** * The user making the request */ + @NotNull public String getRequesterName() { return requesterName; } diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java index 759b38bb..e71f87f0 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java @@ -20,9 +20,22 @@ package net.william278.huskhomes.teleport; import org.jetbrains.annotations.NotNull; +import net.william278.huskhomes.user.OnlineUser; +/** + * Represents a teleporter; the person performing the teleport. + * <p> + * Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference + * that needs to be resolved first. + */ public interface Teleportable { + /** + * Create a {@link Teleportable} from a player name + * + * @param teleporter the player name + * @return the teleportable + */ @NotNull static Teleportable username(@NotNull String teleporter) { return new Username(teleporter); diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index cedf12b9..287501cd 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -30,6 +30,11 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +/** + * Represents a {@link Teleport} that has an associated warmup time; the teleport will not be performed until the + * warmup time has elapsed, during which the user must not move or take damage. + * @see Teleport#builder(HuskHomes) + */ public class TimedTeleport extends Teleport { public static final String BYPASS_PERMISSION = "huskhomes.bypass_teleport_warmup"; diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Username.java b/common/src/main/java/net/william278/huskhomes/teleport/Username.java index 646e61e5..af9ce00b 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Username.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Username.java @@ -25,11 +25,30 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; +/** + * Represents the username of a player who may or may not be online, either locally as an {@link OnlineUser}, + * or on a different server. + * + * @param name The name of the player + */ public record Username(@NotNull String name) implements Teleportable, Target { + /** + * Search for a local {@link OnlineUser} by their name. + * + * @param plugin The instance of {@link HuskHomes} + * @return An {@link Optional} containing the {@link OnlineUser} if found + * @throws TeleportationException If the user is not found + * @implNote If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this + * method will search for the user by exact name. + * <p> + * Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for + * the closest name match. + */ @NotNull - public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) throws TeleportationException { - return plugin.findOnlinePlayer(name); + public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) { + return plugin.getPlayerList(true).stream().anyMatch(listedName -> listedName.equalsIgnoreCase(name)) + ? plugin.getOnlineUserExact(name) : plugin.getOnlineUser(name); } }
['common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java', 'common/src/main/java/net/william278/huskhomes/teleport/Username.java', 'common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java', 'common/src/main/java/net/william278/huskhomes/command/RtpCommand.java', 'common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java', 'common/src/main/java/net/william278/huskhomes/HuskHomes.java', 'common/src/main/java/net/william278/huskhomes/teleport/Target.java', 'common/src/main/java/net/william278/huskhomes/teleport/Teleportable.java', 'common/src/main/java/net/william278/huskhomes/teleport/TeleportBuilder.java', 'bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java', 'common/src/main/java/net/william278/huskhomes/teleport/Teleport.java']
{'.java': 11}
11
11
0
0
11
854,930
178,974
23,410
191
4,920
1,083
106
10
329
53
71
1
0
0
2023-05-05T00:27:29
62
Java
{'Java': 919259, 'Shell': 392}
Apache License 2.0
1,061
ita-social-projects/greencity/5164/4465
ita-social-projects
greencity
https://github.com/ita-social-projects/GreenCity/issues/4465
https://github.com/ita-social-projects/GreenCity/pull/5164
https://github.com/ita-social-projects/GreenCity/pull/5164
1
fixed
[Event] User is able to edit ended event.
**Environment:** macOS Monterey 12.4 Safari 15.5 **Reproducible:** always **Build found:** 22.07.22 **Steps to reproduce** 1. Sign in Green City project. 2. Create event. 3. Open the event page when it ends. **Actual result** The "Edit" link is present and the user is able to edit the event. **Expected result** There is no "Edit" link. **User story and test case links** E.g.: "User story #3195 [Test case](https://jira.softserve.academy/browse/GC-3161)" **Labels to be added** "Bug", Priority ("priority: medium "), Severity ("severity: major").
206f90b844331a97c5255f1e813d46bf243c26f1
268b72df6808ee78a785fdc95da2093331a1cf9b
https://github.com/ita-social-projects/greencity/compare/206f90b844331a97c5255f1e813d46bf243c26f1...268b72df6808ee78a785fdc95da2093331a1cf9b
diff --git a/service/src/main/java/greencity/service/EventServiceImpl.java b/service/src/main/java/greencity/service/EventServiceImpl.java index a4e4641ac..23a4afbd0 100644 --- a/service/src/main/java/greencity/service/EventServiceImpl.java +++ b/service/src/main/java/greencity/service/EventServiceImpl.java @@ -223,7 +223,7 @@ public class EventServiceImpl implements EventService { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } - if (!toUpdate.isOpen()) { + if (findLastEventDateTime(toUpdate).isBefore(ZonedDateTime.now())) { throw new BadRequestException(ErrorMessage.EVENT_IS_FINISHED); } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index ad92087d0..feff3b22b 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1740,12 +1740,29 @@ public class ModelUtils { event.setTitle("Title"); List<EventDateLocation> dates = new ArrayList<>(); dates.add(new EventDateLocation(1L, event, - ZonedDateTime.of(2000, 1, 1, 1, 1, 1, 1, ZoneId.systemDefault()), - ZonedDateTime.of(2000, 2, 1, 1, 1, 1, 1, ZoneId.systemDefault()), + ZonedDateTime.of(2098, 1, 1, 1, 1, 1, 1, ZoneId.systemDefault()), + ZonedDateTime.of(2099, 2, 1, 1, 1, 1, 1, ZoneId.systemDefault()), new Coordinates(45.45, 45.45, "Ua Address", "En Address"), null)); dates.add(new EventDateLocation(2L, event, - ZonedDateTime.of(2002, 1, 1, 1, 1, 1, 1, ZoneId.systemDefault()), - ZonedDateTime.of(2002, 2, 1, 1, 1, 1, 1, ZoneId.systemDefault()), + ZonedDateTime.of(2099, 1, 1, 1, 1, 1, 1, ZoneId.systemDefault()), + ZonedDateTime.of(2100, 2, 1, 1, 1, 1, 1, ZoneId.systemDefault()), + new Coordinates(45.45, 45.45, "Ua Address", "En Address"), null)); + event.setDates(dates); + event.setTags(List.of(getEventTag())); + event.setTitleImage(AppConstant.DEFAULT_HABIT_IMAGE); + return event; + } + + public static Event getEventWithFinishedDate() { + Event event = new Event(); + event.setDescription("Description"); + event.setId(1L); + event.setOrganizer(getUser()); + event.setTitle("Title"); + List<EventDateLocation> dates = new ArrayList<>(); + dates.add(new EventDateLocation(1L, event, + ZonedDateTime.of(2000, 1, 1, 1, 1, 1, 1, ZoneId.systemDefault()), + ZonedDateTime.of(2001, 2, 1, 1, 1, 1, 1, ZoneId.systemDefault()), new Coordinates(45.45, 45.45, "Ua Address", "En Address"), null)); event.setDates(dates); event.setTags(List.of(getEventTag())); diff --git a/service/src/test/java/greencity/service/EventServiceImplTest.java b/service/src/test/java/greencity/service/EventServiceImplTest.java index 896917989..b811299ac 100644 --- a/service/src/test/java/greencity/service/EventServiceImplTest.java +++ b/service/src/test/java/greencity/service/EventServiceImplTest.java @@ -21,7 +21,6 @@ import greencity.repository.EventRepo; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.provider.EnumSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.modelmapper.ModelMapper; @@ -115,8 +114,7 @@ class EventServiceImplTest { @Test void updateFinishedEvent() { - Event actualEvent = ModelUtils.getEvent(); - actualEvent.setOpen(false); + Event actualEvent = ModelUtils.getEventWithFinishedDate(); UpdateEventDto eventToUpdateDto = ModelUtils.getUpdateEventDto(); String userEmail = ModelUtils.getUser().getEmail(); @@ -589,7 +587,7 @@ class EventServiceImplTest { @Test void rateEvent() { - Event event = ModelUtils.getEvent(); + Event event = ModelUtils.getEventWithFinishedDate(); User user = ModelUtils.getAttenderUser(); event.setAttenders(Set.of(user)); when(eventRepo.findById(any())).thenReturn(Optional.of(event));
['service/src/test/java/greencity/ModelUtils.java', 'service/src/main/java/greencity/service/EventServiceImpl.java', 'service/src/test/java/greencity/service/EventServiceImplTest.java']
{'.java': 3}
3
3
0
0
3
1,306,758
273,366
38,204
693
112
25
2
1
579
78
157
24
1
0
2023-02-02T09:48:48
56
Java
{'Java': 2701205, 'HTML': 429257, 'JavaScript': 135338, 'CSS': 59705, 'PLpgSQL': 5721, 'Go': 2336, 'Dockerfile': 111, 'Procfile': 110}
MIT License
1,064
apache/camel-k-runtime/302/301
apache
camel-k-runtime
https://github.com/apache/camel-k-runtime/issues/301
https://github.com/apache/camel-k-runtime/pull/302
https://github.com/apache/camel-k-runtime/pull/302
1
fix
Can't get response from platform HTTP
Getting error whenever I try to read some binary content from a rest endpoint: ``` Error executing reactive work due to You must set the Content-Length header to be the total size of the message body BEFORE sending any data if you are not using HTTP chunked encoding. ``` I'm working on a fix
a0db7e1926e6b046072ed63efe917d29f27ef526
80665b0cdb5249938566ec117145a8c11556b1e5
https://github.com/apache/camel-k-runtime/compare/a0db7e1926e6b046072ed63efe917d29f27ef526...80665b0cdb5249938566ec117145a8c11556b1e5
diff --git a/camel-k-runtime-http/src/main/java/org/apache/camel/k/http/engine/RuntimePlatformHttpConsumer.java b/camel-k-runtime-http/src/main/java/org/apache/camel/k/http/engine/RuntimePlatformHttpConsumer.java index 300fe915..bb448643 100644 --- a/camel-k-runtime-http/src/main/java/org/apache/camel/k/http/engine/RuntimePlatformHttpConsumer.java +++ b/camel-k-runtime-http/src/main/java/org/apache/camel/k/http/engine/RuntimePlatformHttpConsumer.java @@ -200,6 +200,14 @@ public class RuntimePlatformHttpConsumer extends DefaultConsumer { ExchangeHelper.setFailureHandled(exchange); } + // set the content-length if it can be determined, or chunked encoding + final Integer length = determineContentLength(exchange, body); + if (length != null) { + response.putHeader("Content-Length", String.valueOf(length)); + } else { + response.setChunked(true); + } + // set the content type in the response. final String contentType = MessageHelper.getContentType(message); if (contentType != null) { @@ -209,6 +217,15 @@ public class RuntimePlatformHttpConsumer extends DefaultConsumer { return body; } + static Integer determineContentLength(Exchange camelExchange, Object body) { + if (body instanceof byte[]) { + return ((byte[]) body).length; + } else if (body instanceof ByteBuffer) { + return ((ByteBuffer) body).remaining(); + } + return null; + } + /* * Copied from org.apache.camel.http.common.DefaultHttpBinding.determineResponseCode(Exchange, Object) * If DefaultHttpBinding.determineResponseCode(Exchange, Object) is moved to a module without the servlet-api
['camel-k-runtime-http/src/main/java/org/apache/camel/k/http/engine/RuntimePlatformHttpConsumer.java']
{'.java': 1}
1
1
0
0
1
522,794
101,131
13,953
175
638
122
17
1
300
54
61
7
0
1
2020-04-15T13:48:26
56
Java
{'Java': 379701, 'Groovy': 14549, 'Shell': 9051, 'Kotlin': 870, 'JavaScript': 857}
Apache License 2.0
1,063
ita-social-projects/greencity/2920/2908
ita-social-projects
greencity
https://github.com/ita-social-projects/GreenCity/issues/2908
https://github.com/ita-social-projects/GreenCity/pull/2920
https://github.com/ita-social-projects/GreenCity/pull/2920
1
fix
[GreenCity] Fix bug in CustomShoppingListItemController
**Fix bug in CustomShoppingListItemController:** `/custom/shopping-list-items/{userId}/custom-shopping-list-items` Bug occurs when user tries to update items' status.
2c72e67aa4c134b5bc076362f262e24c740f9ceb
23d958cadb924448e6d0f79633f2a3fec4739de4
https://github.com/ita-social-projects/greencity/compare/2c72e67aa4c134b5bc076362f262e24c740f9ceb...23d958cadb924448e6d0f79633f2a3fec4739de4
diff --git a/core/src/main/java/greencity/controller/CustomShoppingListItemController.java b/core/src/main/java/greencity/controller/CustomShoppingListItemController.java index fade95927..549d72cdf 100644 --- a/core/src/main/java/greencity/controller/CustomShoppingListItemController.java +++ b/core/src/main/java/greencity/controller/CustomShoppingListItemController.java @@ -105,7 +105,8 @@ public class CustomShoppingListItemController { @ApiResponse(code = 200, message = HttpStatuses.OK), @ApiResponse(code = 303, message = HttpStatuses.SEE_OTHER), @ApiResponse(code = 400, message = HttpStatuses.BAD_REQUEST), - @ApiResponse(code = 401, message = HttpStatuses.UNAUTHORIZED) + @ApiResponse(code = 401, message = HttpStatuses.UNAUTHORIZED), + @ApiResponse(code = 404, message = HttpStatuses.BAD_REQUEST) }) @PatchMapping("/{userId}/custom-shopping-list-items") public ResponseEntity<CustomShoppingListItemResponseDto> updateItemStatus(@PathVariable @CurrentUserId Long userId, diff --git a/service-api/src/main/java/greencity/constant/ErrorMessage.java b/service-api/src/main/java/greencity/constant/ErrorMessage.java index 6ddfcfb5b..d3a948d14 100644 --- a/service-api/src/main/java/greencity/constant/ErrorMessage.java +++ b/service-api/src/main/java/greencity/constant/ErrorMessage.java @@ -145,6 +145,7 @@ public final class ErrorMessage { public static final String ACHIEVEMENT_NOT_FOUND_BY_ID = "The name does not exist by this id: "; public static final String PAGE_INDEX_IS_MORE_THAN_TOTAL_PAGES = "Page index is more than total pages: "; public static final String MULTIPART_FILE_BAD_REQUEST = "Bad inputed image string : "; + public static final String INCORRECT_INPUT_ITEM_STATUS = "Incorrect input status to update item."; private ErrorMessage() { } diff --git a/service/src/main/java/greencity/service/CustomShoppingListItemServiceImpl.java b/service/src/main/java/greencity/service/CustomShoppingListItemServiceImpl.java index 7a9bb02ee..0dc1e1e00 100644 --- a/service/src/main/java/greencity/service/CustomShoppingListItemServiceImpl.java +++ b/service/src/main/java/greencity/service/CustomShoppingListItemServiceImpl.java @@ -12,6 +12,7 @@ import greencity.entity.Habit; import greencity.entity.User; import greencity.entity.UserShoppingListItem; import greencity.enums.ShoppingListItemStatus; +import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.CustomShoppingListItemNotSavedException; import greencity.exception.exceptions.NotFoundException; import greencity.repository.CustomShoppingListItemRepo; @@ -139,22 +140,22 @@ public class CustomShoppingListItemServiceImpl implements CustomShoppingListItem @Transactional @Override public CustomShoppingListItemResponseDto updateItemStatus(Long userId, Long itemId, String itemStatus) { - CustomShoppingListItemResponseDto customShoppingListItemResponseDto = null; CustomShoppingListItem customShoppingListItem = customShoppingListItemRepo.findByUserIdAndItemId(userId, itemId); - if (itemStatus.equals(ShoppingListItemStatus.DONE.toString())) { + if (customShoppingListItem == null) { + throw new NotFoundException(CUSTOM_SHOPPING_LIST_ITEM_NOT_FOUND_BY_ID); + } + if (itemStatus.equalsIgnoreCase(ShoppingListItemStatus.DONE.name())) { customShoppingListItem.setStatus(ShoppingListItemStatus.DONE); - customShoppingListItemRepo.save(customShoppingListItem); - customShoppingListItemResponseDto = - modelMapper.map(customShoppingListItem, CustomShoppingListItemResponseDto.class); + return modelMapper.map(customShoppingListItemRepo.save(customShoppingListItem), + CustomShoppingListItemResponseDto.class); } - if (itemStatus.equals(ShoppingListItemStatus.ACTIVE.toString())) { + if (itemStatus.equalsIgnoreCase(ShoppingListItemStatus.ACTIVE.name())) { customShoppingListItem.setStatus(ShoppingListItemStatus.ACTIVE); - customShoppingListItemRepo.save(customShoppingListItem); - customShoppingListItemResponseDto = - modelMapper.map(customShoppingListItem, CustomShoppingListItemResponseDto.class); + return modelMapper.map(customShoppingListItemRepo.save(customShoppingListItem), + CustomShoppingListItemResponseDto.class); } - return customShoppingListItemResponseDto; + throw new BadRequestException(ErrorMessage.INCORRECT_INPUT_ITEM_STATUS); } /** diff --git a/service/src/test/java/greencity/service/CustomShoppingListItemServiceImplTest.java b/service/src/test/java/greencity/service/CustomShoppingListItemServiceImplTest.java index 3b151fb93..a0e9e12cb 100644 --- a/service/src/test/java/greencity/service/CustomShoppingListItemServiceImplTest.java +++ b/service/src/test/java/greencity/service/CustomShoppingListItemServiceImplTest.java @@ -2,6 +2,7 @@ package greencity.service; import greencity.ModelUtils; import greencity.client.RestClient; +import greencity.constant.ErrorMessage; import greencity.dto.shoppinglistitem.BulkSaveCustomShoppingListItemDto; import greencity.dto.shoppinglistitem.CustomShoppingListItemResponseDto; import greencity.dto.shoppinglistitem.CustomShoppingListItemSaveRequestDto; @@ -13,6 +14,7 @@ import greencity.enums.EmailNotification; import greencity.enums.Role; import greencity.enums.ShoppingListItemStatus; import greencity.enums.UserStatus; +import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.CustomShoppingListItemNotSavedException; import greencity.exception.exceptions.NotFoundException; import greencity.repository.CustomShoppingListItemRepo; @@ -243,7 +245,14 @@ class CustomShoppingListItemServiceImplTest { when(customShoppingListItemRepo.save(customShoppingListItem1)).thenReturn(customShoppingListItem1); when(modelMapper.map(customShoppingListItem1, CustomShoppingListItemResponseDto.class)).thenReturn(test1); assertEquals(test1, customShoppingListItemService.updateItemStatus(12L, 2L, "ACTIVE")); - + when(customShoppingListItemRepo.findByUserIdAndItemId(any(), anyLong())).thenReturn(null); + Exception thrown1 = assertThrows(NotFoundException.class, + () -> customShoppingListItemService.updateItemStatus(64L, 1L, "DONE")); + assertEquals(thrown1.getMessage(), ErrorMessage.CUSTOM_SHOPPING_LIST_ITEM_NOT_FOUND_BY_ID); + when(customShoppingListItemRepo.findByUserIdAndItemId(12L, 2L)).thenReturn(customShoppingListItem1); + Exception thrown2 = assertThrows(BadRequestException.class, + () -> customShoppingListItemService.updateItemStatus(12L, 2L, "NOTDONE")); + assertEquals(thrown2.getMessage(), ErrorMessage.INCORRECT_INPUT_ITEM_STATUS); } @Test
['service/src/test/java/greencity/service/CustomShoppingListItemServiceImplTest.java', 'service/src/main/java/greencity/service/CustomShoppingListItemServiceImpl.java', 'service-api/src/main/java/greencity/constant/ErrorMessage.java', 'core/src/main/java/greencity/controller/CustomShoppingListItemController.java']
{'.java': 4}
4
4
0
0
4
1,192,538
250,216
34,920
660
1,787
305
25
3
174
14
37
6
0
0
2021-06-24T12:59:33
56
Java
{'Java': 2701205, 'HTML': 429257, 'JavaScript': 135338, 'CSS': 59705, 'PLpgSQL': 5721, 'Go': 2336, 'Dockerfile': 111, 'Procfile': 110}
MIT License
1,062
ita-social-projects/greencity/4717/4667
ita-social-projects
greencity
https://github.com/ita-social-projects/GreenCity/issues/4667
https://github.com/ita-social-projects/GreenCity/pull/4717
https://github.com/ita-social-projects/GreenCity/pull/4717
1
fixed
[API][Add a comment]Adding a comment to an existing event
**Environment:** All. **Reproducible:** always. **Build found:** 23.10.2022 **Preconditions** 1.Open Postman. 2.The user is authorised. 3.Event added **Steps to reproduce** 1. Apply the POST method by using request URL https://greencity.testgreencity.ga/events/comments/{eventId} 2.Fill the request "body"e.g. { "text": "string" } 3. Perform the request. **Actual result** Status Code : 500 Internal Server Error **Expected result** Status Code : 201 Created "body" is : { "text": "string" } **User story and test case links** "User story #3208" **Labels to be added** "Bug", Priority ("Medium"), Severity ("Medium"), Type ("Functional"), "API" (for back-end bugs).
189891be7af9b3055f84c1ad6bcdb30f7144b1da
f01fc0d0d6c6fc2ca8de4797b2a3b83dcb8b2526
https://github.com/ita-social-projects/greencity/compare/189891be7af9b3055f84c1ad6bcdb30f7144b1da...f01fc0d0d6c6fc2ca8de4797b2a3b83dcb8b2526
diff --git a/core/src/main/java/greencity/controller/EventCommentController.java b/core/src/main/java/greencity/controller/EventCommentController.java index 966639acd..f35963543 100644 --- a/core/src/main/java/greencity/controller/EventCommentController.java +++ b/core/src/main/java/greencity/controller/EventCommentController.java @@ -47,7 +47,7 @@ public class EventCommentController { @ApiResponse(code = 401, message = HttpStatuses.UNAUTHORIZED), @ApiResponse(code = 404, message = HttpStatuses.NOT_FOUND), }) - @PostMapping("{eventId}") + @PostMapping("/{eventId}") public ResponseEntity<AddEventCommentDtoResponse> save(@PathVariable Long eventId, @Valid @RequestBody AddEventCommentDtoRequest request, @ApiIgnore @CurrentUser UserVO user) { diff --git a/service-api/src/main/java/greencity/client/RestClient.java b/service-api/src/main/java/greencity/client/RestClient.java index ff0236948..a8f0850b4 100644 --- a/service-api/src/main/java/greencity/client/RestClient.java +++ b/service-api/src/main/java/greencity/client/RestClient.java @@ -379,7 +379,7 @@ public class RestClient { * @author Inna Yashna */ public void sendNewEventComment(EventCommentForSendEmailDto message) { - HttpHeaders headers = new HttpHeaders(); + HttpHeaders headers = setHeader(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<EventCommentForSendEmailDto> entity = new HttpEntity<>(message, headers); restTemplate.exchange(greenCityUserServerAddress diff --git a/service-api/src/test/java/greencity/client/RestClientTest.java b/service-api/src/test/java/greencity/client/RestClientTest.java index 4f2ced9b2..1b553944a 100644 --- a/service-api/src/test/java/greencity/client/RestClientTest.java +++ b/service-api/src/test/java/greencity/client/RestClientTest.java @@ -337,8 +337,11 @@ class RestClientTest { void sendNewEventComment() { EventCommentForSendEmailDto message = ModelUtils.getEventCommentForSendEmailDto(); HttpHeaders httpHeaders = new HttpHeaders(); + String accessToken = "accessToken"; httpHeaders.setContentType(MediaType.APPLICATION_JSON); + httpHeaders.set(AUTHORIZATION, accessToken); HttpEntity<EventCommentForSendEmailDto> entity = new HttpEntity<>(message, httpHeaders); + when(httpServletRequest.getHeader(AUTHORIZATION)).thenReturn(accessToken); when(restTemplate.exchange(greenCityUserServerAddress + RestTemplateLinks.ADD_EVENT_COMMENT, HttpMethod.POST, entity, Object.class)) .thenReturn(ResponseEntity.ok(Object)); diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index 8bb8a050c..207fdb17e 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -5,10 +5,7 @@ import greencity.constant.ErrorMessage; import greencity.dto.PageableDto; import greencity.dto.event.EventAuthorDto; import greencity.dto.event.EventVO; -import greencity.dto.eventcomment.AddEventCommentDtoRequest; -import greencity.dto.eventcomment.AddEventCommentDtoResponse; -import greencity.dto.eventcomment.EventCommentDto; -import greencity.dto.eventcomment.EventCommentForSendEmailDto; +import greencity.dto.eventcomment.*; import greencity.dto.user.UserVO; import greencity.entity.User; import greencity.entity.event.Event; @@ -58,6 +55,7 @@ public class EventCommentServiceImpl implements EventCommentService { eventComment.setEvent(modelMapper.map(eventVO, Event.class)); AddEventCommentDtoResponse addEventCommentDtoResponse = modelMapper.map( eventCommentRepo.save(eventComment), AddEventCommentDtoResponse.class); + addEventCommentDtoResponse.setAuthor(modelMapper.map(userVO, EventCommentAuthorDto.class)); sendEmailDto(addEventCommentDtoResponse); return addEventCommentDtoResponse; } diff --git a/service/src/test/java/greencity/service/EventCommentServiceImplTest.java b/service/src/test/java/greencity/service/EventCommentServiceImplTest.java index 673a69259..b81d83988 100644 --- a/service/src/test/java/greencity/service/EventCommentServiceImplTest.java +++ b/service/src/test/java/greencity/service/EventCommentServiceImplTest.java @@ -8,6 +8,7 @@ import greencity.dto.event.EventAuthorDto; import greencity.dto.event.EventVO; import greencity.dto.eventcomment.AddEventCommentDtoRequest; import greencity.dto.eventcomment.AddEventCommentDtoResponse; +import greencity.dto.eventcomment.EventCommentAuthorDto; import greencity.dto.eventcomment.EventCommentDto; import greencity.dto.user.UserVO; import greencity.entity.User; @@ -68,10 +69,12 @@ class EventCommentServiceImplTest { AddEventCommentDtoRequest addEventCommentDtoRequest = ModelUtils.getAddEventCommentDtoRequest(); EventComment eventComment = ModelUtils.getEventComment(); EventAuthorDto eventAuthorDto = ModelUtils.getEventAuthorDto(); + EventCommentAuthorDto eventCommentAuthorDto = ModelUtils.getEventCommentAuthorDto(); when(eventService.findById(anyLong())).thenReturn(eventVO); when(eventCommentRepo.save(any(EventComment.class))).then(AdditionalAnswers.returnsFirstArg()); when(eventCommentRepo.findById(anyLong())).thenReturn(Optional.of(eventComment)); + when(modelMapper.map(userVO, EventCommentAuthorDto.class)).thenReturn(eventCommentAuthorDto); when(modelMapper.map(user, EventAuthorDto.class)).thenReturn(eventAuthorDto); when(modelMapper.map(userVO, User.class)).thenReturn(user); when(modelMapper.map(eventVO, Event.class)).thenReturn(event);
['service-api/src/main/java/greencity/client/RestClient.java', 'service/src/test/java/greencity/service/EventCommentServiceImplTest.java', 'service-api/src/test/java/greencity/client/RestClientTest.java', 'core/src/main/java/greencity/controller/EventCommentController.java', 'service/src/main/java/greencity/service/EventCommentServiceImpl.java']
{'.java': 5}
5
5
0
0
5
1,288,202
269,372
37,722
690
534
105
10
3
710
88
180
35
1
0
2022-11-04T09:17:47
56
Java
{'Java': 2701205, 'HTML': 429257, 'JavaScript': 135338, 'CSS': 59705, 'PLpgSQL': 5721, 'Go': 2336, 'Dockerfile': 111, 'Procfile': 110}
MIT License
803
ably/ably-java/914/913
ably
ably-java
https://github.com/ably/ably-java/issues/913
https://github.com/ably/ably-java/pull/914
https://github.com/ably/ably-java/pull/914
1
fixes
Released channel re-added to the channel map after DETACHED message
If you call channels.release(), that removes the channel from the channel map and detaches it. However, the protocol messaged for DETACHED returning to us re-adds the channel to the channel map (via a call to channels.get()), therefore undoing the release action. One way to fix this would be to not re-add the channel when processing DETACHED if its not there.
94ecb6fada26982aaa698f3291f150f344eb2cd4
42d89759da3fd4b91d9069df3c49609b890afa2c
https://github.com/ably/ably-java/compare/94ecb6fada26982aaa698f3291f150f344eb2cd4...42d89759da3fd4b91d9069df3c49609b890afa2c
diff --git a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java index 666521af..ffb33d42 100644 --- a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java +++ b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java @@ -217,8 +217,12 @@ public class AblyRealtime extends AblyRest { @Override public void onMessage(ProtocolMessage msg) { String channelName = msg.channel; - Channel channel; - synchronized(this) { channel = channels.get(channelName); } + Channel channel = null; + synchronized(this) { + if (channels.containsKey(channelName)) { + channel = channels.get(channelName); + } + } if(channel == null) { Log.e(TAG, "Received channel message for non-existent channel"); return; diff --git a/lib/src/test/java/io/ably/lib/test/common/Helpers.java b/lib/src/test/java/io/ably/lib/test/common/Helpers.java index bc6cc8fe..2dce9b10 100644 --- a/lib/src/test/java/io/ably/lib/test/common/Helpers.java +++ b/lib/src/test/java/io/ably/lib/test/common/Helpers.java @@ -632,24 +632,56 @@ public class Helpers { * Wait for a given number of messages */ public void waitForRecv() { - waitForRecv(1); + waitForRecv(1, 6000000); } public void waitForSend() { - waitForSend(1); + waitForSend(1, 6000000); + } + public void waitForRecv(int count) { + waitForRecv(count, 6000000); + } + public void waitForSend(int count) { + waitForSend(count, 6000000); } /** * Wait for a given number of messages * @param count */ - public synchronized void waitForRecv(int count) { + public synchronized void waitForRecv(int count, long timeoutInMillis) { + long timeoutAt = System.currentTimeMillis() + timeoutInMillis; while(receivedMessages.size() < count) { - try { wait(); } catch(InterruptedException e) {} + synchronized (this) { + try { + if (System.currentTimeMillis() > timeoutAt || receivedMessages.size() >= count) { + break; + } + + wait(); + } catch(InterruptedException e) {} + } + } + + if (receivedMessages.size() < count) { + throw new AssertionError("Did not receive expected number of messages"); } } - public synchronized void waitForSend(int count) { + public synchronized void waitForSend(int count, long timeoutInMillis) { + long timeoutAt = System.currentTimeMillis() + timeoutInMillis; while(sentMessages.size() < count) { - try { wait(); } catch(InterruptedException e) {} + synchronized (this) { + try { + if (System.currentTimeMillis() > timeoutAt || sentMessages.size() >= count) { + break; + } + + wait(); + } catch(InterruptedException e) {} + } + } + + if (sentMessages.size() < count) { + throw new AssertionError("Did not send expected number of messages"); } } diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java index b7391033..46ddaaac 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java @@ -2007,6 +2007,41 @@ public class RealtimeChannelTest extends ParameterizedTest { } } + /* + * Checks that the DETACHED message sent by the server when a channel is released is dropped. + */ + @Test + public void detach_message_to_released_channel_is_dropped() throws AblyException { + AblyRealtime ably = null; + long oldRealtimeTimeout = Defaults.realtimeRequestTimeout; + final String channelName = "detach_message_to_released_channel_is_dropped"; + + try { + DebugOptions opts = createOptions(testVars.keys[0].keyStr); + Helpers.RawProtocolMonitor monitor = Helpers.RawProtocolMonitor.createReceiver(ProtocolMessage.Action.detached); + opts.protocolListener = monitor; + + /* Make test faster */ + Defaults.realtimeRequestTimeout = 1000; + opts.channelRetryTimeout = 1000; + + ably = new AblyRealtime(opts); + Channel channel = ably.channels.get(channelName); + channel.attach(); + (new ChannelWaiter(channel)).waitFor(ChannelState.attached); + + // Listen for detach messages and release the channel + ably.channels.release(channelName); + monitor.waitForRecv(1, 10000); + + assertFalse(ably.channels.containsKey("messages_to_non_existent_channels_are_dropped")); + } finally { + if (ably != null) + ably.close(); + Defaults.realtimeRequestTimeout = oldRealtimeTimeout; + } + } + class DetachingProtocolListener implements DebugOptions.RawProtocolListener { public Channel theChannel;
['lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java', 'lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java', 'lib/src/test/java/io/ably/lib/test/common/Helpers.java']
{'.java': 3}
3
3
0
0
3
760,441
152,227
19,909
109
323
49
8
1
364
60
77
5
0
0
2023-02-06T11:14:36
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
801
ably/ably-java/927/926
ably
ably-java
https://github.com/ably/ably-java/issues/926
https://github.com/ably/ably-java/pull/927
https://github.com/ably/ably-java/pull/927
1
fixes
equals() for TokenDetails is broken
Following is how `equals` has been implemented for `TokenDetails` ``` @Override public boolean equals(Object obj) { TokenDetails details = (TokenDetails)obj; return equalNullableStrings(this.token, details.token) & equalNullableStrings(this.capability, details.capability) & equalNullableStrings(this.clientId, details.clientId) & (this.issued == details.issued) & (this.expires == details.expires); } ``` This implementation doesn't take into account when obj is null or not the type of token details. **Expected** Return false when obj is null or a different type Spotted: Flutter plugin Stream writer does this check when writing types to streams ``` protected void writeValue(@NonNull ByteArrayOutputStream stream, @Nullable Object value) { if (value == null || value.equals(null)) { stream.write(NULL); ```
99a4ca601093e5a25fe017cccd152aa9bbe405e7
565aed9d39b94e7f7f789b30ec471e10cfbba77f
https://github.com/ably/ably-java/compare/99a4ca601093e5a25fe017cccd152aa9bbe405e7...565aed9d39b94e7f7f789b30ec471e10cfbba77f
diff --git a/lib/src/main/java/io/ably/lib/rest/Auth.java b/lib/src/main/java/io/ably/lib/rest/Auth.java index e1c068b6..dc3fa9fc 100644 --- a/lib/src/main/java/io/ably/lib/rest/Auth.java +++ b/lib/src/main/java/io/ably/lib/rest/Auth.java @@ -6,6 +6,7 @@ import java.security.GeneralSecurityException; import java.util.HashMap; import java.util.Locale; import java.util.Map; +import java.util.Objects; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @@ -358,6 +359,8 @@ public class Auth { */ @Override public boolean equals(Object obj) { + if (!(obj instanceof TokenDetails)) return false; + TokenDetails details = (TokenDetails)obj; return equalNullableStrings(this.token, details.token) & equalNullableStrings(this.capability, details.capability) & @@ -366,7 +369,12 @@ public class Auth { (this.expires == details.expires); } -} + @Override + public int hashCode() { + return Objects.hash(token, capability, clientId, issued, expires); + } + + } /** * Defines the properties of an Ably Token.
['lib/src/main/java/io/ably/lib/rest/Auth.java']
{'.java': 1}
1
1
0
0
1
760,456
152,227
19,912
109
246
45
10
1
968
99
188
25
0
2
2023-03-17T10:24:09
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
477
marklogic/java-client-api/869/867
marklogic
java-client-api
https://github.com/marklogic/java-client-api/issues/867
https://github.com/marklogic/java-client-api/pull/869
https://github.com/marklogic/java-client-api/pull/869
1
fix
rowRecord.getString("firstName") returns ...OkHttpServices$OkHttpServiceResult@4dd663d5
Where I expected to get the value of the firstName column extracted by xpath, I'm getting an OkHttpServiceResult object, which has an undesirable toString. Notice the "firstName: com.marklogic.client.impl.OkHttpServices$OkHttpServiceResult@1b2283a" in the output below. Can you help me see what I'm doing wrong? With the following Java: ``` import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.ObjectMapper; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.DatabaseClientFactory.DigestAuthContext; import com.marklogic.client.document.DocumentManager; import com.marklogic.client.expression.PlanBuilder; import com.marklogic.client.expression.PlanBuilder.Plan; import com.marklogic.client.io.DocumentMetadataHandle; import com.marklogic.client.row.RowManager; import com.marklogic.client.row.RowRecord; import com.marklogic.client.type.CtsReferenceExpr; import com.marklogic.client.type.PlanExprCol; import java.util.HashMap; public class Optic2 { public static void main(String[] args) throws Exception { DatabaseClient client = DatabaseClientFactory.newClient("engrlab-129-192.engrlab.marklogic.com", 8000, new DigestAuthContext("admin", "admin")); DocumentManager docMgr = client.newDocumentManager(); ObjectMapper mapper = new ObjectMapper() .configure(Feature.ALLOW_SINGLE_QUOTES, true); docMgr.writeAs("/optic/test/musician1.json", mapper.readTree( "{'musician':{" + " 'lastName':'Armstrong', 'firstName':'Louis', 'dob':'1901-08-04', 'instrument':['trumpet', 'vocal']" + "}}")); docMgr.writeAs("/optic/test/musician2.json", mapper.readTree( "{'musician':{" + " 'lastName':'Byron', 'firstName':'Don', 'dob':'1958-11-08', 'instrument':['clarinet', 'saxophone']" + "}}")); docMgr.writeAs("/optic/test/musician3.json", mapper.readTree( "{'musician':{" + " 'lastName':'Coltrane', 'firstName':'John', 'dob':'1926-09-23', 'instrument':['saxophone']" + "}}")); docMgr.writeAs("/optic/test/musician4.json", mapper.readTree( "{'musician':{" + " 'lastName':'Davis', 'firstName':'Miles', 'dob':'1926-05-26', 'instrument':['trumpet']" + "}}")); RowManager rowMgr = client.newRowManager(); PlanBuilder p = rowMgr.newPlanBuilder(); HashMap<String,CtsReferenceExpr> uriLexicon = new HashMap<String,CtsReferenceExpr>(); uriLexicon.put("uri", p.cts.uriReference()); String[] uris = new String[] {"/optic/test/musician1.json", "/optic/test/musician2.json", "/optic/test/musician3.json" }; PlanExprCol[] columns = new PlanExprCol[] {p.as("firstName", p.xpath("doc", "/musician/firstName"))}; Plan plan = p.fromLexicons(uriLexicon) .where(p.cts.documentQuery(p.xs.stringSeq(uris))) .joinDoc(p.col("doc"), p.col("uri")) .select(columns); for (RowRecord row: rowMgr.resultRows(plan)) { System.out.println("firstName: " + row.getString("firstName") + ", uri: " + row.getString("uri")); } } } ``` I get the following output: ``` 09:34:41.599 [main] DEBUG c.m.client.impl.OkHttpServices - Connecting to engrlab-129-192.engrlab.marklogic.com at 8000 as admin 09:34:45.563 [main] INFO c.m.client.impl.DocumentManagerImpl - Writing content for /optic/test/musician1.json 09:34:45.575 [main] DEBUG c.m.client.impl.OkHttpServices - Sending /optic/test/musician1.json document in transaction null 09:34:46.059 [main] INFO c.m.client.impl.DocumentManagerImpl - Writing content for /optic/test/musician2.json 09:34:46.059 [main] DEBUG c.m.client.impl.OkHttpServices - Sending /optic/test/musician2.json document in transaction null 09:34:46.207 [main] INFO c.m.client.impl.DocumentManagerImpl - Writing content for /optic/test/musician3.json 09:34:46.207 [main] DEBUG c.m.client.impl.OkHttpServices - Sending /optic/test/musician3.json document in transaction null 09:34:46.350 [main] INFO c.m.client.impl.DocumentManagerImpl - Writing content for /optic/test/musician4.json 09:34:46.351 [main] DEBUG c.m.client.impl.OkHttpServices - Sending /optic/test/musician4.json document in transaction null 09:34:47.150 [main] DEBUG c.m.client.impl.OkHttpServices - Posting rows firstName: com.marklogic.client.impl.OkHttpServices$OkHttpServiceResult@1b2283a, uri: /optic/test/musician1.json firstName: com.marklogic.client.impl.OkHttpServices$OkHttpServiceResult@a637e7, uri: /optic/test/musician2.json firstName: com.marklogic.client.impl.OkHttpServices$OkHttpServiceResult@1e7aac8, uri: /optic/test/musician3.json ``` And the following HTTP wire trace for the optic query: ``` POST /v1/rows?output=object&column-types=rows&node-columns=reference&row-format=json HTTP/1.1 ML-Agent-ID: java Accept: multipart/mixed; boundary=60571458-ff42-4838-8518-8daf9382c4e5 Authorization: Digest username="admin", realm="public", nonce="35c963f0f9cc36:giWRHfuTfU3ag/QKF6Z3eA==", uri="/v1/rows?output=object&column-types=rows&node-columns=reference&row-format=json", response="649bf6fd6f0155494696de6d47b2b32a", qop=auth, nc=00000005, cnonce="5456ce49757347d8", algorithm=MD5, opaque="760201d04a9987db" Content-Type: application/json Transfer-Encoding: chunked Host: engrlab-129-192.engrlab.marklogic.com:8000 Connection: Keep-Alive Accept-Encoding: gzip User-Agent: okhttp/3.9.0 40c {"$optic":{"ns":"op", "fn":"operators", "args":[{"ns":"op", "fn":"from-lexicons", "args":[{"uri":{"ns":"cts", "fn":"uri-reference", "args":[]}}]}, {"ns":"op", "fn":"where", "args":[{"ns":"cts", "fn":"document-query", "args":[[{"ns":"xs", "fn":"string", "args":["/optic/test/musician1.json"]}, {"ns":"xs", "fn":"string", "args":["/optic/test/musician2.json"]}, {"ns":"xs", "fn":"string", "args":["/optic/test/musician3.json"]}]]}]}, {"ns":"op", "fn":"join-doc", "args":[{"ns":"op", "fn":"col", "args":[{"ns":"xs", "fn":"string", "args":["doc"]}]}, {"ns":"op", "fn":"col", "args":[{"ns":"xs", "fn":"string", "args":["uri"]}]}]}, {"ns":"op", "fn":"select", "args":[[{"ns":"op", "fn":"col", "args":[{"ns":"xs", "fn":"string", "args":["uri"]}]}, {"ns":"op", "fn":"as", "args":[{"ns":"op", "fn":"col", "args":[{"ns":"xs", "fn":"string", "args":["firstName"]}]}, {"ns":"op", "fn":"xpath", "args":[{"ns":"op", "fn":"col", "args":[{"ns":"xs", "fn":"string", "args":["doc"]}]}, {"ns":"xs", "fn":"string", "args":["/musician/firstName"]}]}]}]]}]}} 0 HTTP/1.1 200 OK ML-Effective-Timestamp: 15139604854019900 Content-type: multipart/mixed; boundary=60571458-ff42-4838-8518-8daf9382c4e5 Server: MarkLogic Content-Length: 1473 Connection: Keep-Alive Keep-Alive: timeout=5 --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: application/json; charset=utf-8 Content-Disposition: inline; kind=columns {"columns":[{"name":"uri"},{"name":"firstName"}]} --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: application/json; charset=utf-8 Content-Disposition: inline; kind=row {"uri":{"type":"xs:string","value":"/optic/test/musician1.json"},"firstName":{"type":"cid","value":"cid:firstName[0]"}} --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: text/plain; charset=utf-8 Content-ID: <firstName[0]> Content-Disposition: inline; kind=row-attachment Louis --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: application/json; charset=utf-8 Content-Disposition: inline; kind=row {"uri":{"type":"xs:string","value":"/optic/test/musician2.json"},"firstName":{"type":"cid","value":"cid:firstName[1]"}} --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: text/plain; charset=utf-8 Content-ID: <firstName[1]> Content-Disposition: inline; kind=row-attachment Don --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: application/json; charset=utf-8 Content-Disposition: inline; kind=row {"uri":{"type":"xs:string","value":"/optic/test/musician3.json"},"firstName":{"type":"cid","value":"cid:firstName[2]"}} --60571458-ff42-4838-8518-8daf9382c4e5 Content-Type: text/plain; charset=utf-8 Content-ID: <firstName[2]> Content-Disposition: inline; kind=row-attachment John --60571458-ff42-4838-8518-8daf9382c4e5-- ```
1a1bec5be196f44ca587eaaac81ca47ac37592db
73f9710113ea8a55899a11f8a1ac50d9f3de84d8
https://github.com/marklogic/java-client-api/compare/1a1bec5be196f44ca587eaaac81ca47ac37592db...73f9710113ea8a55899a11f8a1ac50d9f3de84d8
diff --git a/src/main/java/com/marklogic/client/impl/RowManagerImpl.java b/src/main/java/com/marklogic/client/impl/RowManagerImpl.java index 4b81e3ee8..f2fd3f4b2 100644 --- a/src/main/java/com/marklogic/client/impl/RowManagerImpl.java +++ b/src/main/java/com/marklogic/client/impl/RowManagerImpl.java @@ -50,6 +50,7 @@ import com.marklogic.client.impl.RESTServices.RESTServiceResultIterator; import com.marklogic.client.io.BaseHandle; import com.marklogic.client.io.Format; import com.marklogic.client.io.InputStreamHandle; +import com.marklogic.client.io.StringHandle; import com.marklogic.client.io.XMLStreamReaderHandle; import com.marklogic.client.io.marker.AbstractReadHandle; import com.marklogic.client.io.marker.AbstractWriteHandle; @@ -1094,7 +1095,11 @@ public class RowManagerImpl } @Override public String getString(String columnName) { - return asString(get(columnName)); + try { + return asString(get(columnName)); + } catch(NodeNotAStringException e) { + throw new IllegalArgumentException("value for column \\""+columnName+"\\" not a string"); + } } private boolean asBoolean(String columnName, Object value) { @@ -1139,10 +1144,22 @@ public class RowManagerImpl } throw new IllegalStateException("column "+columnName+" does not have a short value"); } - private String asString(Object value) { + /** + * @throws NodeNotAStringException when the value is a node but not a single text node + * (with content-type "text/plain") + */ + private String asString(Object value) throws NodeNotAStringException { if (value == null || value instanceof String) { return (String) value; } + if (value instanceof RESTServiceResult) { + RESTServiceResult result = (RESTServiceResult) value; + if ( result.getMimetype() != null && result.getMimetype().startsWith("text/plain") ) { + return result.getContent(new StringHandle()).get(); + } else { + throw new NodeNotAStringException(); + } + } return value.toString(); } @@ -1176,27 +1193,27 @@ public class RowManagerImpl } */ - String valueStr = asString(value); + try { + String valueStr = asString(value); - Function<String,? extends XsAnyAtomicTypeVal> factory = getFactory(as); - if (factory != null) { - return as.cast(factory.apply(valueStr)); - } + Function<String,? extends XsAnyAtomicTypeVal> factory = getFactory(as); + if (factory != null) { + return as.cast(factory.apply(valueStr)); + } - // fallback - @SuppressWarnings("unchecked") - Constructor<T> constructor = (Constructor<T>) constructors.get(as); - if (constructor == null) { - try { + // fallback + @SuppressWarnings("unchecked") + Constructor<T> constructor = (Constructor<T>) constructors.get(as); + if (constructor == null) { constructor = as.getConstructor(String.class); - } catch(NoSuchMethodException e) { - throw new IllegalArgumentException("cannot construct "+columnName+" value as class: "+as.getName()); + constructors.put(as, constructor); } - constructors.put(as, constructor); - } - try { return constructor.newInstance(valueStr); + } catch(NodeNotAStringException e) { + throw new IllegalArgumentException("column \\""+columnName+"\\" is a node, not an atomic"); + } catch(NoSuchMethodException e) { + throw new IllegalArgumentException("cannot construct "+columnName+" value as class: "+as.getName()); } catch (InstantiationException e) { throw new MarkLogicBindingException("could not construct value as class: "+as.getName(), e); } catch (IllegalAccessException e) { @@ -1532,4 +1549,7 @@ public class RowManagerImpl return this; } } + + private static class NodeNotAStringException extends Exception { + } } diff --git a/src/test/java/com/marklogic/client/test/RowManagerTest.java b/src/test/java/com/marklogic/client/test/RowManagerTest.java index f23f362ea..bc3ba2f02 100644 --- a/src/test/java/com/marklogic/client/test/RowManagerTest.java +++ b/src/test/java/com/marklogic/client/test/RowManagerTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.IOException; import java.io.LineNumberReader; @@ -451,15 +452,25 @@ public class RowManagerTest { String[] firstName = {"Louis", "Miles"}; int rowNum = 0; + boolean didARowFail = false; for (RowRecord row: rowMgr.resultRows(builtPlan)) { assertEquals("unexpected lastName value in row record "+rowNum, lastName[rowNum], row.getString("lastName")); assertEquals("unexpected firstName value in row record "+rowNum, firstName[rowNum], row.getString("firstName")); - String instruments = row.getContent("instruments", new StringHandle()).get(); + String instruments; + try { + instruments = row.getString("instruments"); + } catch (IllegalArgumentException e ) { + didARowFail = true; + instruments = row.getContentAs("instruments", String.class); + } assertNotNull("null instrucments value in row record "+rowNum, instruments); assertTrue("unexpected instrucments value in row record "+rowNum, instruments.contains("trumpet")); rowNum++; } + if ( didARowFail == false ) { + fail("getString(\\"instruments\\") should throw an exception since some rows return an array"); + } assertEquals("unexpected count of result records", 2, rowNum); } @Test
['src/main/java/com/marklogic/client/impl/RowManagerImpl.java', 'src/test/java/com/marklogic/client/test/RowManagerTest.java']
{'.java': 2}
2
2
0
0
2
4,378,052
975,960
99,799
692
2,359
475
54
1
8,230
509
2,372
149
0
3
2017-12-28T17:04:09
55
Java
{'Java': 10343403, 'Kotlin': 164515, 'JavaScript': 67526, 'XQuery': 59700, 'XSLT': 13897, 'Shell': 1820, 'HTML': 374}
Apache License 2.0
478
marklogic/java-client-api/289/249
marklogic
java-client-api
https://github.com/marklogic/java-client-api/issues/249
https://github.com/marklogic/java-client-api/pull/289
https://github.com/marklogic/java-client-api/pull/289
1
fixes
DocumentPatchBuilder.replaceValue cannot replace boolean values
This is probably actually a bug in the REST API but I found it in Java. ``` patchBuilder.replaceValue("/accepted", true); patchBuilder.replaceValue("/accepted", new Boolean(true)); ``` Both of these insert a string value into the JSON property rather than a boolean. A workaround is to use replaceFragment patchBuilder.replaceFragment("/accepted", true) but this is a hackish workaround -- it works because the string "true", unquoted, evaluates to a boolean in constructing the patch.
5304c8dfa86ef8053377c0dcd74fbb932dee04c8
2faead09a11cb2b8c35bd6e22797e1f33354d559
https://github.com/marklogic/java-client-api/compare/5304c8dfa86ef8053377c0dcd74fbb932dee04c8...2faead09a11cb2b8c35bd6e22797e1f33354d559
diff --git a/src/main/java/com/marklogic/client/impl/DocumentPatchBuilderImpl.java b/src/main/java/com/marklogic/client/impl/DocumentPatchBuilderImpl.java index 37748044c..3c25a176a 100644 --- a/src/main/java/com/marklogic/client/impl/DocumentPatchBuilderImpl.java +++ b/src/main/java/com/marklogic/client/impl/DocumentPatchBuilderImpl.java @@ -86,7 +86,8 @@ implements DocumentPatchBuilder String selectPath; Cardinality cardinality; boolean isFragment = true; - String input; + Object input; + String inputAsString; ContentReplaceOperation(String selectPath, Cardinality cardinality, boolean isFragment, Object input ) { @@ -94,15 +95,23 @@ implements DocumentPatchBuilder this.selectPath = selectPath; this.cardinality = cardinality; this.isFragment = isFragment; - this.input = (input instanceof String) ? - (String) input : input.toString(); + this.input = input; + this.inputAsString = null; + if (input != null) { + inputAsString = (input instanceof String) ? (String) input : input.toString(); + } } @Override public void write(JSONStringWriter serializer) { writeStartReplace(serializer, selectPath, cardinality); serializer.writeStartEntry("content"); if (isFragment) { - serializer.writeFragment(input); + serializer.writeFragment(inputAsString); + } else if (input instanceof Boolean) { + serializer.writeBooleanValue(input); + } + else if (input instanceof Number) { + serializer.writeNumberValue(input); } else { serializer.writeStringValue(input); } @@ -115,9 +124,9 @@ implements DocumentPatchBuilder writeStartReplace(out, selectPath, cardinality); if (isFragment) { serializer.writeCharacters(""); // force the tag close - out.getWriter().write(input); + out.getWriter().write(inputAsString); } else { - serializer.writeCharacters(input); + serializer.writeCharacters(inputAsString); } serializer.writeEndElement(); } diff --git a/src/main/java/com/marklogic/client/impl/JSONStringWriter.java b/src/main/java/com/marklogic/client/impl/JSONStringWriter.java index 49913a66b..4af11a02a 100644 --- a/src/main/java/com/marklogic/client/impl/JSONStringWriter.java +++ b/src/main/java/com/marklogic/client/impl/JSONStringWriter.java @@ -153,4 +153,5 @@ public class JSONStringWriter { return out.toString(); } + } diff --git a/src/test/java/com/marklogic/client/test/JSONDocumentTest.java b/src/test/java/com/marklogic/client/test/JSONDocumentTest.java index 80967104e..fe43c5e7e 100644 --- a/src/test/java/com/marklogic/client/test/JSONDocumentTest.java +++ b/src/test/java/com/marklogic/client/test/JSONDocumentTest.java @@ -35,6 +35,7 @@ import org.xml.sax.SAXException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.BooleanNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.marklogic.client.document.DocumentManager.Metadata; import com.marklogic.client.document.DocumentMetadataPatchBuilder.Cardinality; @@ -153,6 +154,9 @@ public class JSONDocumentTest { fragment = mapper.writeValueAsString(fragmentNode); patchBldr.insertFragment("$.[\\"arrayKey\\"]", Position.LAST_CHILD, Cardinality.ZERO_OR_ONE, fragment); + patchBldr.replaceValue("$.booleanKey", true); + patchBldr.replaceValue("$.numberKey2", 2); + patchBldr.replaceValue("$.nullKey", null); DocumentPatchHandle patchHandle = patchBldr.pathLanguage( PathLanguage.JSONPATH).build(); @@ -179,6 +183,10 @@ public class JSONDocumentTest { childNode.put("appendedKey", "appended item"); childArray.add(childNode); expectedNode.set("arrayKey", childArray); + expectedNode.put("booleanKey", true); + expectedNode.put("numberKey2", 2); + expectedNode.putNull("nullKey"); + String docText = docMgr.read(docId, new StringHandle()).get(); assertNotNull("Read null string for patched JSON content", docText); @@ -272,6 +280,9 @@ public class JSONDocumentTest { fragment = mapper.writeValueAsString(fragmentNode); patchBldr.insertFragment("/array-node('arrayKey')", Position.BEFORE, fragment); + patchBldr.replaceValue("/booleanKey", true); + patchBldr.replaceValue("/numberKey2", 2); + patchBldr.replaceValue("/nullKey", null); //patchBldr.replaceApply("/node()/arrayKey/node()[string(.) eq '3']", // patchBldr.call().add(2)); @@ -306,18 +317,19 @@ public class JSONDocumentTest { childNode.put("appendedKey", "appended item"); childArray.add(childNode); expectedNode.set("arrayKey", childArray); + expectedNode.put("booleanKey", true); + expectedNode.put("numberKey2", 2); + expectedNode.putNull("nullKey"); String docText = docMgr.read(docId, new StringHandle()).get(); - + assertNotNull("Read null string for patched JSON content", docText); JsonNode readNode = mapper.readTree(docText); - logger.debug("Before3:" + content); logger.debug("After3:"+docText); logger.debug("Expected3:" + mapper.writeValueAsString(expectedNode)); - - + assertTrue("Patched JSON document without expected result", expectedNode.equals(readNode)); @@ -400,6 +412,9 @@ public class JSONDocumentTest { childNode.put("itemObjectKey", "item object value"); childArray.add(childNode); sourceNode.set("arrayKey", childArray); + sourceNode.put("booleanKey", false); + sourceNode.put("numberKey2", 1); + sourceNode.put("nullKey", 0); return sourceNode; }
['src/main/java/com/marklogic/client/impl/DocumentPatchBuilderImpl.java', 'src/main/java/com/marklogic/client/impl/JSONStringWriter.java', 'src/test/java/com/marklogic/client/test/JSONDocumentTest.java']
{'.java': 3}
3
3
0
0
3
1,999,152
432,343
58,414
330
765
165
22
2
494
68
104
14
0
1
2015-04-30T16:50:09
55
Java
{'Java': 10343403, 'Kotlin': 164515, 'JavaScript': 67526, 'XQuery': 59700, 'XSLT': 13897, 'Shell': 1820, 'HTML': 374}
Apache License 2.0
805
ably/ably-java/900/474
ably
ably-java
https://github.com/ably/ably-java/issues/474
https://github.com/ably/ably-java/pull/900
https://github.com/ably/ably-java/pull/900
1
closes
Lib is not re-sending pending messages on new transport after a resume
Log posted by a customer [here](https://ably-real-time.slack.com/archives/C030C5YLY/p1558623828295800) (cf [conversation](https://app.intercom.io/a/apps/ua39m1ld/inbox/inbox/all/conversations/22156922233)) shows several issues: 1. At one point it disconnects the transport for inactivity at 14:29:08.086Z, 16s after getting a detached from realtime at 14:28:52.151. That shouldn't happen. 1. After it reconnects and resumes, it does not seem to be re-sending messages on the new transport that were pending on the previous transport, as required by RTN15f 1. Related to the previous one: messages called back with a failure due to getting an ack for a higher msgSerial than the pending queue are called back with "Unknown error / 50000 / 500", which could be more informative ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-430) by [Unito](https://www.unito.io)
63aa2a9784a4eec2b536884a74982dd568ead4bc
07ad898dcfc733fb0cc2a0fc6c9ca56aec93eed3
https://github.com/ably/ably-java/compare/63aa2a9784a4eec2b536884a74982dd568ead4bc...07ad898dcfc733fb0cc2a0fc6c9ca56aec93eed3
diff --git a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java index fc441118..4a1f9b02 100644 --- a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java +++ b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java @@ -231,6 +231,20 @@ public class AblyRealtime extends AblyRest { } } + /** + * By spec RTN15c3 + */ + @Override + public void reattachOnResumeFailure() { + for (Map.Entry<String, Channel> channelEntry : map.entrySet()) { + Channel channel = channelEntry.getValue(); + if (channel.state == ChannelState.attaching || channel.state == ChannelState.attached || channel.state == ChannelState.suspended) { + Log.d(TAG, "reAttach(); channel = " + channel.name); + channel.attach(true, null); + } + } + } + private void clear() { map.clear(); } diff --git a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java index c36cfabf..9c26cb3b 100644 --- a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java +++ b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java @@ -181,7 +181,7 @@ public abstract class ChannelBase extends EventEmitter<ChannelEvent, ChannelStat this.attach(false, listener); } - private void attach(boolean forceReattach, CompletionListener listener) { + void attach(boolean forceReattach, CompletionListener listener) { clearAttachTimers(); attachWithTimeout(forceReattach, listener); } diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index a3e171a2..9286e280 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -81,6 +81,8 @@ public class ConnectionManager implements ConnectListener { void onMessage(ProtocolMessage msg); void suspendAll(ErrorInfo error, boolean notifyStateChange); Iterable<Channel> values(); + + void reattachOnResumeFailure(); } /*********************************** @@ -1183,44 +1185,48 @@ public class ConnectionManager implements ConnectListener { } private synchronized void onConnected(ProtocolMessage message) { - /* if the returned connection id differs from - * the existing connection id, then this means - * we need to suspend all existing attachments to - * the old connection. - * If realtime did not reply with an error, it - * signifies that this was a result of an earlier - * connection being invalidated due to being stale. - * - * Suspend all channels attached to the previous id; - * this will be reattached in setConnection() */ - ErrorInfo error = message.error; - if(connection.id != null && !message.connectionId.equals(connection.id)) { - /* we need to suspend the original connection */ - if(error == null) { - error = REASON_SUSPENDED; + final ErrorInfo error = message.error; + connection.reason = error; + if (connection.id != null) { // there was a previous connection, so this is a resume and RTN15c applies + Log.d(TAG, "There was a connection resume"); + if(message.connectionId.equals(connection.id)) { + // resume succeeded + if(message.error == null) { + // RTN15c1: no action required wrt channel state + Log.d(TAG, "connection has reconnected and resumed successfully"); + } else { + // RTN15c2: no action required wrt channel state + Log.d(TAG, "connection resume success with non-fatal error: " + error.message); + } + // Add pending messages to the front of queued messages to be sent later + addPendingMessagesToQueuedMessages(false); + } else { + // RTN15c3: resume failed + if (error != null){ + Log.d(TAG, "connection resume failed with error: " + error.message); + }else { // This shouldn't happen but, putting it here for safety + Log.d(TAG, "connection resume failed without error" ); + } + + channels.reattachOnResumeFailure(); + // Add any messages still pending from the previous transport (RTN19a) to the front of queued messages + // however, this time the pending messages have to have newly assigned ` + // msgSerial`s. They can't simply be replayed, as they are in the successful resume case + addPendingMessagesToQueuedMessages(true); } - channels.suspendAll(error, false); } - /* set the new connection id */ - ConnectionDetails connectionDetails = message.connectionDetails; - connection.key = connectionDetails.connectionKey; - if (!message.connectionId.equals(connection.id)) { - /* The connection id has changed. Reset the message serial and the - * pending message queue (which fails the messages currently in - * there). */ - pendingMessages.reset(msgSerial, - new ErrorInfo("Connection resume failed", 500, 50000)); - msgSerial = 0; - } connection.id = message.connectionId; + if(message.connectionSerial != null) { - connection.serial = message.connectionSerial.longValue(); + connection.serial = message.connectionSerial; if (connection.key != null) connection.recoveryKey = connection.key + ":" + message.connectionSerial; } + ConnectionDetails connectionDetails = message.connectionDetails; /* Get any parameters from connectionDetails. */ + connection.key = connectionDetails.connectionKey; //RTN16d maxIdleInterval = connectionDetails.maxIdleInterval; connectionStateTtl = connectionDetails.connectionStateTtl; @@ -1232,12 +1238,39 @@ public class ConnectionManager implements ConnectListener { requestState(transport, new StateIndication(ConnectionState.failed, e.errorInfo)); return; } - /* indicated connected currentState */ setSuspendTime(); requestState(new StateIndication(ConnectionState.connected, error)); } + /** + * Add all pending queued messages to the front of QueuedMessages for them to be sent later + * Spec: RTN19a + * @param resetMessageSerial whether to reset message serial, this will determine whether to reset message serials + * on pending queue, for example when a connection resume failed + */ + private void addPendingMessagesToQueuedMessages(boolean resetMessageSerial) { + // Add messages from pending messages to front of queuedMessages in order to retry them + queuedMessages.addAll(0, pendingMessages.queue); + //rewind start serial back to the first serial since we are clearing the queue + if (!pendingMessages.queue.isEmpty()){ + //Reset current serial to the first pending message on previous queue as we are going to clear the queue now + msgSerial = pendingMessages.queue.get(0).msg.msgSerial; + pendingMessages.resetStartSerial((int) (msgSerial)); + pendingMessages.clearQueue(); + } + + //RTN19a + if (resetMessageSerial){ + pendingMessages.resetStartSerial(0); + msgSerial = 0; //msgSerial will increase in sendImpl when messages are sent + } + } + + public List<QueuedMessage> getPendingMessages() { + return pendingMessages.queue; + } + private synchronized void onDisconnected(ProtocolMessage message) { ErrorInfo reason = message.error; if(reason != null && isTokenError(reason)) { @@ -1718,6 +1751,13 @@ public class ConnectionManager implements ConnectListener { startSerial = 0; } + public void resetStartSerial(int from) { + startSerial = from; + } + + synchronized void clearQueue() { + queue.clear(); + } } /*********************** diff --git a/lib/src/main/java/io/ably/lib/transport/ITransport.java b/lib/src/main/java/io/ably/lib/transport/ITransport.java index 364c03ab..93b426f3 100644 --- a/lib/src/main/java/io/ably/lib/transport/ITransport.java +++ b/lib/src/main/java/io/ably/lib/transport/ITransport.java @@ -122,6 +122,8 @@ public interface ITransport { */ void send(ProtocolMessage msg) throws AblyException; + void receive(ProtocolMessage msg) throws AblyException; + /** * Get connection URL * @return diff --git a/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java b/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java index 55b23d68..85284b17 100644 --- a/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java +++ b/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java @@ -70,7 +70,7 @@ public class WebSocketTransport implements ITransport { Log.d(TAG, "connect(); wsUri = " + wsUri); synchronized(this) { - wsConnection = new WsClient(URI.create(wsUri)); + wsConnection = new WsClient(URI.create(wsUri), this::receive); if(isTls) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init( null, null, null ); @@ -99,6 +99,11 @@ public class WebSocketTransport implements ITransport { } } + @Override + public void receive(ProtocolMessage msg) throws AblyException { + connectionManager.onMessage(this, msg); + } + @Override public void send(ProtocolMessage msg) throws AblyException { Log.d(TAG, "send(); action = " + msg.action); @@ -137,14 +142,21 @@ public class WebSocketTransport implements ITransport { //Gives the chance to child classes to do message pre-processing } + //interface to transfer Protocol message from websocket + interface WebSocketReceiver { + void onMessage(ProtocolMessage protocolMessage) throws AblyException; + } + /************************** * WebSocketHandler methods **************************/ - class WsClient extends WebSocketClient { + class WsClient extends WebSocketClient { + private final WebSocketReceiver receiver; - WsClient(URI serverUri) { + WsClient(URI serverUri, WebSocketReceiver receiver) { super(serverUri); + this.receiver = receiver; } @Override @@ -180,7 +192,7 @@ public class WebSocketTransport implements ITransport { ProtocolMessage msg = ProtocolSerializer.readMsgpack(blob.array()); Log.d(TAG, "onMessage(): msg (binary) = " + msg); WebSocketTransport.this.preProcessReceivedMessage(msg); - connectionManager.onMessage(WebSocketTransport.this, msg); + receiver.onMessage(msg); } catch (AblyException e) { String msg = "Unexpected exception processing received binary message"; Log.e(TAG, msg, e); @@ -194,7 +206,7 @@ public class WebSocketTransport implements ITransport { ProtocolMessage msg = ProtocolSerializer.fromJSON(string); Log.d(TAG, "onMessage(): msg (text) = " + msg); WebSocketTransport.this.preProcessReceivedMessage(msg); - connectionManager.onMessage(WebSocketTransport.this, msg); + receiver.onMessage(msg); } catch (AblyException e) { String msg = "Unexpected exception processing received text message"; Log.e(TAG, msg, e); diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeResumeTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeResumeTest.java index 3277c902..eae88550 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeResumeTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeResumeTest.java @@ -4,12 +4,15 @@ import io.ably.lib.debug.DebugOptions; import io.ably.lib.realtime.AblyRealtime; import io.ably.lib.realtime.Channel; import io.ably.lib.realtime.ChannelState; +import io.ably.lib.realtime.ConnectionEvent; import io.ably.lib.realtime.ConnectionState; +import io.ably.lib.realtime.ConnectionStateListener; import io.ably.lib.test.common.Helpers.ChannelWaiter; import io.ably.lib.test.common.Helpers.CompletionSet; import io.ably.lib.test.common.Helpers.ConnectionWaiter; import io.ably.lib.test.common.Helpers.MessageWaiter; import io.ably.lib.test.common.ParameterizedTest; +import io.ably.lib.test.util.MockWebsocketFactory; import io.ably.lib.types.AblyException; import io.ably.lib.types.ClientOptions; import io.ably.lib.types.ErrorInfo; @@ -20,11 +23,14 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; +import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -82,7 +88,7 @@ public class RealtimeResumeTest extends ParameterizedTest { } catch (AblyException e) { e.printStackTrace(); - fail("init0: Unexpected exception instantiating library"); + fail("Unexpected exception: "+e.getMessage()); } finally { if(ably != null) { ably.close(); @@ -572,7 +578,6 @@ public class RealtimeResumeTest extends ParameterizedTest { * round of messages which should be queued and published after * we reconnect the sender. */ - @Ignore("FIXME: fix exception") @Test public void resume_publish_queue() { AblyRealtime receiver = null; @@ -684,6 +689,243 @@ public class RealtimeResumeTest extends ParameterizedTest { } } + /** + * In case of resume success, verify that pending messages are resent. By blocking ack/nacks before sending the + * message while connected and then disconnect, add some more messages + * */ + @Test + public void resume_publish_resend_pending_messages_when_resume_is_successful() { + final long delay = 200; + final String channelName = "resume_publish_queue"; + AblyRealtime sender = null; + try { + final MockWebsocketFactory mockWebsocketFactory = new MockWebsocketFactory(); + String keyStr = testVars.keys[0].keyStr; + DebugOptions senderOptions = createOptions(keyStr); + senderOptions.queueMessages = true; + senderOptions.transportFactory = mockWebsocketFactory; + sender = new AblyRealtime(senderOptions); + final Channel senderChannel = sender.channels.get(channelName); + senderChannel.attach(); + (new ChannelWaiter(senderChannel)).waitFor(ChannelState.attached); + assertEquals( + "The sender's channel should be attached", + senderChannel.state, ChannelState.attached + ); + + MockWebsocketFactory.MockWebsocketTransport transport = mockWebsocketFactory.getCreatedTransport(); + + final CompletionSet senderCompletion = new CompletionSet(); + //send 3 successful messages + for (int i = 0; i < 3; i++) { + senderChannel.publish("non_pending messages" + i, "Test pending queued messages " + i, + senderCompletion.add()); + } + + /* wait for the publish callback to be called.*/ + ErrorInfo[] errors = senderCompletion.waitFor(); + assertTrue( + "First completion has errors", + errors.length == 0 + ); + + //assert that messages sent till now are sent with correct size and serials + assertEquals("First round of messages has incorrect size", 3, transport.getPublishedMessages().size()); + + for (int i = 0; i < transport.getPublishedMessages().size(); i++) { + ProtocolMessage protocolMessage = transport.getPublishedMessages().get(i); + assertEquals("Sent serial incorrect", Long.valueOf(i), protocolMessage.msgSerial); + } + + //now clear published messages + transport.clearPublishedMessages(); + + //block ack/nack messages to simulate pending message + mockWebsocketFactory.blockReceive(message -> message.action == ProtocolMessage.Action.ack || + message.action == ProtocolMessage.Action.nack); + + for (int i = 0; i < 3; i++) { + senderChannel.publish("pending_queued_message_" + i, "Test pending queued messages " + i, + senderCompletion.add()); + } + assertEquals(sender.connection.connectionManager.getPendingMessages().size(),3); + + final String connectionId = sender.connection.id; + + //now let's disconnect + sender.connection.connectionManager.requestState(ConnectionState.disconnected); + (new ConnectionWaiter(sender.connection)).waitFor(ConnectionState.disconnected); + + //send 3 more messages while disconnected + for (int i = 0; i < 3; i++) { + senderChannel.publish("queued_message_" + i, "Test pending queued messages " + i, + senderCompletion.add()); + } + //now let's unblock the ack nacks and reconnect + mockWebsocketFactory.blockReceive(message -> false); + /* reconnect the sender */ + sender.connection.connect(); + (new ConnectionWaiter(sender.connection)).waitFor(ConnectionState.connected); + assertEquals("Connection must be connected", ConnectionState.connected, sender.connection.state); + //make sure connection id is a resume success + assertEquals("Connection id has changed", connectionId, sender.connection.id); + + //replace mock transport + transport = mockWebsocketFactory.getCreatedTransport(); + + /* wait for the publish callback to be called.*/ + ErrorInfo[] senderErrors = senderCompletion.waitFor(); + assertTrue( + "Second round of send has errors", + senderErrors.length == 0 + ); + + assertEquals("Second round of messages has incorrect size", 6, transport.getPublishedMessages().size()); + //make sure they were sent with correct serials + for (int i = 0; i < transport.getPublishedMessages().size(); i++) { + ProtocolMessage protocolMessage = transport.getPublishedMessages().get(i); + assertEquals("Sent serial incorrect", Long.valueOf(i+3), protocolMessage.msgSerial); + } + + //make sure that pending queue is cleared + assertEquals("There are still pending messages in the queue", + sender.connection.connectionManager.getPendingMessages().size(), + 0); + + } catch (AblyException e) { + fail("Unexpected exception: "+e.getMessage()); + } finally { + if (sender != null) { + sender.close(); + } + } + } + + /** + * In case of resume failure verify that messages are being resent + * */ + @Test + public void resume_publish_resend_pending_messages_when_resume_failed() throws AblyException { + final long delay = 200; + final String channelName = "sender_channel"; + final MockWebsocketFactory mockWebsocketFactory = new MockWebsocketFactory(); + final DebugOptions options = createOptions(testVars.keys[0].keyStr); + options.realtimeRequestTimeout = 2000L; + options.transportFactory = mockWebsocketFactory; + try(AblyRealtime ably = new AblyRealtime(options)) { + final long newTtl = 1000L; + final long newIdleInterval = 1000L; + /* We want this greater than newTtl + newIdleInterval */ + final long waitInDisconnectedState = 3000L; + + ably.connection.on(ConnectionEvent.connected, new ConnectionStateListener() { + @Override + public void onConnectionStateChanged(ConnectionStateChange state) { + try { + Field connectionStateField = ably.connection.connectionManager.getClass().getDeclaredField("connectionStateTtl"); + connectionStateField.setAccessible(true); + connectionStateField.setLong(ably.connection.connectionManager, newTtl); + Field maxIdleField = ably.connection.connectionManager.getClass().getDeclaredField("maxIdleInterval"); + maxIdleField.setAccessible(true); + maxIdleField.setLong(ably.connection.connectionManager, newIdleInterval); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Unexpected exception in checking connectionStateTtl"); + } + } + }); + + ConnectionWaiter connectionWaiter = new ConnectionWaiter(ably.connection); + connectionWaiter.waitFor(ConnectionState.connected); + + final Channel senderChannel = ably.channels.get(channelName); + senderChannel.attach(); + (new ChannelWaiter(senderChannel)).waitFor(ChannelState.attached); + assertEquals( + "The sender's channel should be attached", + senderChannel.state, ChannelState.attached + ); + + MockWebsocketFactory.MockWebsocketTransport transport = mockWebsocketFactory.getCreatedTransport(); + CompletionSet senderCompletion = new CompletionSet(); + //send 3 successful messages + for (int i = 0; i < 3; i++) { + senderChannel.publish("non_pending messages" + i, "Test pending queued messages " + i, + senderCompletion.add()); + } + + /* wait for the publish callback to be called.*/ + ErrorInfo[] errors = senderCompletion.waitFor(); + assertTrue( + "First completion has errors", + errors.length == 0 + ); + + //assert that messages sent till now are sent with correct size and serials + assertEquals("First round of messages has incorrect size", 3, transport.getPublishedMessages().size()); + for (int i = 0; i < transport.getPublishedMessages().size(); i++) { + ProtocolMessage protocolMessage = transport.getPublishedMessages().get(i); + assertEquals("Sent serial incorrect", Long.valueOf(i), protocolMessage.msgSerial); + } + + //block acks nacks before send + mockWebsocketFactory.blockReceive(message -> message.action == ProtocolMessage.Action.ack || + message.action == ProtocolMessage.Action.nack); + for (int i = 0; i < 3; i++) { + senderChannel.publish("pending_queued_message_" + i, "Test pending queued messages " + i, + senderCompletion.add()); + } + + final String firstConnectionId = ably.connection.id; + + /* suppress automatic retries by the connection manager and disconnect */ + try { + Method method = ably.connection.connectionManager.getClass().getDeclaredMethod("disconnectAndSuppressRetries"); + method.setAccessible(true); + method.invoke(ably.connection.connectionManager); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + fail("Unexpected exception in suppressing retries"); + } + connectionWaiter.waitFor(ConnectionState.disconnected); + assertEquals("Disconnected state was not reached", ConnectionState.disconnected, ably.connection.state); + + //send some more messages while disconnected + for (int i = 0; i < 3; i++) { + senderChannel.publish("queued_message_" + i, "Test pending queued messages " + i, + senderCompletion.add()); + } + //now let's unblock the ack nacks and reconnect + mockWebsocketFactory.blockReceive(message -> false); + /* Wait for the connection to go stale, then reconnect */ + try { + Thread.sleep(waitInDisconnectedState); + } catch (InterruptedException e) { + } + ably.connection.connect(); + connectionWaiter.waitFor(ConnectionState.connected); + assertEquals("Connected state was not reached", ConnectionState.connected, ably.connection.state); + //replace transport + transport = mockWebsocketFactory.getCreatedTransport(); + /* Verify the connection is new */ + assertNotNull(ably.connection.id); + assertNotEquals("Connection has the same id", firstConnectionId, ably.connection.id); + + /* wait for the publish callback to be called.*/ + + ErrorInfo[] resendErrors = senderCompletion.waitFor(); + assertTrue( + "Second round of messages (queued) has errors", + resendErrors.length == 0 + ); + + assertEquals("Second round of messages has incorrect size", 6, transport.getPublishedMessages().size()); + //make sure they were sent with reset serials + for (int i = 0; i < transport.getPublishedMessages().size(); i++) { + ProtocolMessage protocolMessage = transport.getPublishedMessages().get(i); + assertEquals("Sent serial incorrect", Long.valueOf(i), protocolMessage.msgSerial); + } + } + } + //RTL4j2 @Test public void resume_rewind_1 () diff --git a/lib/src/test/java/io/ably/lib/test/util/MockWebsocketFactory.java b/lib/src/test/java/io/ably/lib/test/util/MockWebsocketFactory.java index 3d0b0c44..102b3227 100644 --- a/lib/src/test/java/io/ably/lib/test/util/MockWebsocketFactory.java +++ b/lib/src/test/java/io/ably/lib/test/util/MockWebsocketFactory.java @@ -1,5 +1,8 @@ package io.ably.lib.test.util; +import java.util.ArrayList; +import java.util.List; + import io.ably.lib.transport.ConnectionManager; import io.ably.lib.transport.ITransport; import io.ably.lib.transport.WebSocketTransport; @@ -17,6 +20,13 @@ public class MockWebsocketFactory implements ITransport.Factory { block, fail } + + enum ReceiveBehaviour { + allow, + block, + fail + } + enum ConnectBehaviour { allow, fail @@ -35,8 +45,10 @@ public class MockWebsocketFactory implements ITransport.Factory { } SendBehaviour sendBehaviour = SendBehaviour.allow; + ReceiveBehaviour receiveBehaviour = ReceiveBehaviour.allow; ConnectBehaviour connectBehaviour = ConnectBehaviour.allow; - MessageFilter messageFilter = null; + MessageFilter sendMessageFilter = null; + MessageFilter receiveMessageFilter = null; HostFilter hostFilter = null; HostTransform hostTransform = null; @@ -63,26 +75,38 @@ public class MockWebsocketFactory implements ITransport.Factory { return lastCreatedTransport; } + //only use this when you know when transport is created - just for tests + public MockWebsocketTransport getCreatedTransport() { + return (MockWebsocketTransport) lastCreatedTransport; + } + public void blockSend(MessageFilter filter) { - messageFilter = filter; + sendMessageFilter = filter; sendBehaviour = SendBehaviour.block; } + + //use the same filters temporarily + public void blockReceive(MessageFilter filter) { + receiveMessageFilter = filter; + receiveBehaviour = ReceiveBehaviour.block; + } + public void blockSend() { blockSend(null); } public void allowSend(MessageFilter filter) { - messageFilter = filter; + sendMessageFilter = filter; sendBehaviour = SendBehaviour.allow; } public void allowSend() { allowSend(null);} public void failSend(MessageFilter filter) { - messageFilter = filter; + sendMessageFilter = filter; sendBehaviour = SendBehaviour.fail; } public void failSend() { failSend(null); } - public void setMessageFilter(MessageFilter filter) { - messageFilter = filter; + public void setSendMessageFilter(MessageFilter filter) { + sendMessageFilter = filter; } public void failConnect(HostFilter filter) { @@ -98,9 +122,10 @@ public class MockWebsocketFactory implements ITransport.Factory { /* * Special transport class that allows blocking send() and other operations */ - private class MockWebsocketTransport extends WebSocketTransport { + public class MockWebsocketTransport extends WebSocketTransport { private final TransportParams givenTransportParams; private final TransportParams transformedTransportParams; + private final List<ProtocolMessage> publishedMessages = new ArrayList<>(); private MockWebsocketTransport(TransportParams givenTransportParams, TransportParams transformedTransportParams, ConnectionManager connectionManager) { super(transformedTransportParams, connectionManager); @@ -108,23 +133,34 @@ public class MockWebsocketFactory implements ITransport.Factory { this.transformedTransportParams = transformedTransportParams; } + public List<ProtocolMessage> getPublishedMessages() { + return publishedMessages; + } + + public void clearPublishedMessages() { + publishedMessages.clear(); + } + @Override public void send(ProtocolMessage msg) throws AblyException { + if (msg.action == ProtocolMessage.Action.message){ + publishedMessages.add(msg); + } switch (sendBehaviour) { case allow: - if (messageFilter == null || messageFilter.matches(msg)) { + if (sendMessageFilter == null || sendMessageFilter.matches(msg)) { super.send(msg); } break; case block: - if (messageFilter == null || messageFilter.matches(msg)) { + if (sendMessageFilter == null || sendMessageFilter.matches(msg)) { /* do nothing */ } else { super.send(msg); } break; case fail: - if (messageFilter == null || messageFilter.matches(msg)) { + if (sendMessageFilter == null || sendMessageFilter.matches(msg)) { throw AblyException.fromErrorInfo(new ErrorInfo("Mock", 40000)); } else { super.send(msg); @@ -133,6 +169,32 @@ public class MockWebsocketFactory implements ITransport.Factory { } } + @Override + public void receive(ProtocolMessage msg) throws AblyException { + switch (receiveBehaviour) { + case allow: + if (receiveMessageFilter == null || receiveMessageFilter.matches(msg)) { + super.receive(msg); + } + break; + case block: + if (receiveMessageFilter == null || receiveMessageFilter.matches(msg)) { + /* do nothing */ + } else { + super.receive(msg); + } + break; + case fail: + if (receiveMessageFilter == null || receiveMessageFilter.matches(msg)) { + throw AblyException.fromErrorInfo(new ErrorInfo("Mock", 40000)); + } else { + super.receive(msg); + } + break; + } + } + + @Override public void connect(ConnectListener connectListener) { String host = givenTransportParams.getHost();
['lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java', 'lib/src/test/java/io/ably/lib/test/util/MockWebsocketFactory.java', 'lib/src/main/java/io/ably/lib/realtime/ChannelBase.java', 'lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java', 'lib/src/main/java/io/ably/lib/transport/ITransport.java', 'lib/src/test/java/io/ably/lib/test/realtime/RealtimeResumeTest.java', 'lib/src/main/java/io/ably/lib/transport/ConnectionManager.java']
{'.java': 7}
7
7
0
0
7
754,644
151,140
19,787
109
6,723
1,280
138
5
900
113
240
10
4
0
2023-01-13T21:17:54
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
804
ably/ably-java/909/908
ably
ably-java
https://github.com/ably/ably-java/issues/908
https://github.com/ably/ably-java/pull/909
https://github.com/ably/ably-java/pull/909
1
fixes
Presence messages superseded whilst channel in attaching state
presence.enter and presence.update (and the others) call presence.updatePresence. updatePresence will put messages on a queue to be sent later, in the event that the channel is currently attaching. This queue is a HashMap that is keyed by clientid. This means if a presence.enter and presence.update occur in quick succession before the channel attaches, the former is cancelled out by the latter (and any listeners are not called). There are two possible options: 1. Queue up all presence messages and then send in-order on channel attach. 2. Only send the latest message, but call all event listeners with the result. The spec needs updating to provide more clarification on what the behaviour should be (see: https://github.com/ably/specification/issues/130), but the current implementation in ably-js is to just send all of the pending messages.
a1e2c46266df1a6304b72aa1afd736f95f252c2e
d8445cd92989ddbd2ba7623c28b84e5274f68848
https://github.com/ably/ably-java/compare/a1e2c46266df1a6304b72aa1afd736f95f252c2e...d8445cd92989ddbd2ba7623c28b84e5274f68848
diff --git a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java index 3d219b33..fb28d966 100644 --- a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java +++ b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java @@ -196,8 +196,7 @@ public abstract class ChannelBase extends EventEmitter<ChannelEvent, ChannelStat PresenceMessage[] presenceMessages = queuedMessage.msg.presence; if (presenceMessages != null && presenceMessages.length > 0) { for (PresenceMessage presenceMessage : presenceMessages) { - this.presence.addPendingPresence(presenceMessage.clientId, presenceMessage, - queuedMessage.listener); + this.presence.addPendingPresence(presenceMessage, queuedMessage.listener); } } } diff --git a/lib/src/main/java/io/ably/lib/realtime/Presence.java b/lib/src/main/java/io/ably/lib/realtime/Presence.java index e34b8a49..aeaf2a8b 100644 --- a/lib/src/main/java/io/ably/lib/realtime/Presence.java +++ b/lib/src/main/java/io/ably/lib/realtime/Presence.java @@ -117,9 +117,11 @@ public class Presence { return get(new Param(GET_WAITFORSYNC, String.valueOf(wait)), new Param(GET_CLIENTID, clientId)); } - synchronized void addPendingPresence(String clientId, PresenceMessage presenceMessage, CompletionListener listener) { - final QueuedPresence queuedPresence = new QueuedPresence(presenceMessage,listener); - pendingPresence.put(clientId,queuedPresence); + void addPendingPresence(PresenceMessage presenceMessage, CompletionListener listener) { + synchronized(channel) { + final QueuedPresence queuedPresence = new QueuedPresence(presenceMessage,listener); + pendingPresence.add(queuedPresence); + } } /** @@ -739,13 +741,12 @@ public class Presence { * @throws AblyException */ public void updatePresence(PresenceMessage msg, CompletionListener listener) throws AblyException { - Log.v(TAG, "update(); channel = " + channel.name); + Log.v(TAG, "updatePresence(); channel = " + channel.name); AblyRealtime ably = channel.ably; boolean connected = (ably.connection.state == ConnectionState.connected); - String clientId; try { - clientId = ably.auth.checkClientId(msg, false, connected); + ably.auth.checkClientId(msg, false, connected); } catch(AblyException e) { if(listener != null) { listener.onError(e.errorInfo); @@ -759,8 +760,7 @@ public class Presence { case initialized: channel.attach(); case attaching: - QueuedPresence queued = new QueuedPresence(msg, listener); - pendingPresence.put(clientId, queued); + pendingPresence.add(new QueuedPresence(msg, listener)); break; case attached: ProtocolMessage message = new ProtocolMessage(ProtocolMessage.Action.presence, channel.name); @@ -852,7 +852,7 @@ public class Presence { QueuedPresence(PresenceMessage msg, CompletionListener listener) { this.msg = msg; this.listener = listener; } } - private final Map<String, QueuedPresence> pendingPresence = new HashMap<String, QueuedPresence>(); + private final List<QueuedPresence> pendingPresence = new ArrayList<QueuedPresence>(); private void sendQueuedMessages() { Log.v(TAG, "sendQueuedMessages()"); @@ -864,7 +864,7 @@ public class Presence { return; ProtocolMessage message = new ProtocolMessage(ProtocolMessage.Action.presence, channel.name); - Iterator<QueuedPresence> allQueued = pendingPresence.values().iterator(); + Iterator<QueuedPresence> allQueued = pendingPresence.iterator(); PresenceMessage[] presenceMessages = message.presence = new PresenceMessage[count]; CompletionListener listener; @@ -883,7 +883,9 @@ public class Presence { } listener = mListener.isEmpty() ? null : mListener; } + pendingPresence.clear(); + try { connectionManager.send(message, queueMessages, listener); } catch(AblyException e) { @@ -895,7 +897,7 @@ public class Presence { private void failQueuedMessages(ErrorInfo reason) { Log.v(TAG, "failQueuedMessages()"); - for(QueuedPresence msg : pendingPresence.values()) + for(QueuedPresence msg : pendingPresence) if(msg.listener != null) try { msg.listener.onError(reason); diff --git a/lib/src/test/java/io/ably/lib/test/common/Helpers.java b/lib/src/test/java/io/ably/lib/test/common/Helpers.java index 788a81bb..bc6cc8fe 100644 --- a/lib/src/test/java/io/ably/lib/test/common/Helpers.java +++ b/lib/src/test/java/io/ably/lib/test/common/Helpers.java @@ -164,15 +164,35 @@ public class Helpers { error = null; } - public synchronized ErrorInfo waitFor(int count) { + /** + * Wait for a specified amount of time, or until success occurs. + */ + public synchronized ErrorInfo waitFor(int count, long timeoutInMillis) { + long timeoutAt = System.currentTimeMillis() + timeoutInMillis; while(successCount<count && error == null) - try { wait(); } catch(InterruptedException e) {} + try { + if (System.currentTimeMillis() > timeoutAt) { + break; + } + + wait(); + } catch(InterruptedException e) {} success = successCount >= count; return error; } + /** + * Wait for a specified number of successes, with an arbitrarily long timeout. + */ + public synchronized ErrorInfo waitFor(int count) { + return waitFor(count, 600000); + } + + /** + * Wait for a single success with an arbitrarily long timeout. + */ public synchronized ErrorInfo waitFor() { - return waitFor(1); + return waitFor(1, 600000); } /** diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimePresenceTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimePresenceTest.java index 4342b580..7148b9e3 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimePresenceTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimePresenceTest.java @@ -1649,6 +1649,97 @@ public class RealtimePresenceTest extends ParameterizedTest { } } + /** + * <p> + * Validates a client sending multiple presence updates when the channel is in the attaching + * state will have all messages sent once the channel attaches, and all listeners will be called. + * </p> + * + * @throws AblyException + */ + @Test + public void realtime_presence_update_multiple_queued_messages() throws AblyException { + /* Ably instance that will emit presence events */ + AblyRealtime ably1 = null; + /* Ably instance that will receive presence events */ + AblyRealtime ably2 = null; + + String channelName = "test.presence.subscribe.update_multiple_queued_messages" + System.currentTimeMillis(); + EnumSet<PresenceMessage.Action> actions = EnumSet.of(Action.update, Action.enter); + + try { + ClientOptions option1 = createOptions(testVars.keys[0].keyStr); + option1.clientId = "emitter client"; + ClientOptions option2 = createOptions(testVars.keys[0].keyStr); + option2.clientId = "receiver client"; + + ably1 = new AblyRealtime(option1); + ably2 = new AblyRealtime(option2); + + Channel channel1 = ably1.channels.get(channelName); + + Channel channel2 = ably2.channels.get(channelName); + channel2.attach(); + (new ChannelWaiter(channel2)).waitFor(ChannelState.attached); + + CompletionWaiter messageCompletionListener = new CompletionWaiter(); + + final ArrayList<PresenceMessage> receivedMessageStack = new ArrayList<>(); + channel2.presence.subscribe(actions, new Presence.PresenceListener() { + @Override + public void onPresenceMessage(PresenceMessage message) { + synchronized (receivedMessageStack) { + receivedMessageStack.add(message); + receivedMessageStack.notify(); + } + } + }); + + /* + Start emitting channel with ably client 1 (emitter) + + This is synchronized against the channel so that channel.setState cant mark + the channel as attached until we're done queueing up events. + */ + synchronized (channel1) { + channel1.presence.enter("Hello, #2!", messageCompletionListener); + channel1.presence.update("Lorem ipsum", messageCompletionListener); + channel1.presence.update("Dolor sit!", messageCompletionListener); + } + + /* Wait until receiver client (ably2) observes {@code Action.leave} + * is emitted from emitter client (ably1) + */ + try { + synchronized (receivedMessageStack) { + while (receivedMessageStack.size() == 0 || + !receivedMessageStack.get(receivedMessageStack.size()-1).clientId.equals(ably1.options.clientId) || + !receivedMessageStack.get(receivedMessageStack.size()-1).data.equals("Dolor sit!")) + receivedMessageStack.wait(); + } + } catch(InterruptedException e) {} + + /* Validate that, + *- we received specific actions + */ + assertThat(receivedMessageStack.size(), is(equalTo(3))); + for (PresenceMessage message : receivedMessageStack) { + assertTrue(actions.contains(message.action)); + } + + /* + * Validate that + * - our listeners are called within 10 seconds + */ + messageCompletionListener.waitFor(3, 10000); + assertTrue(messageCompletionListener.success); + + } finally { + if (ably1 != null) ably1.close(); + if (ably2 != null) ably2.close(); + } + } + /** * <p> * Validates a client can observe presence messages of other client,
['lib/src/main/java/io/ably/lib/realtime/Presence.java', 'lib/src/main/java/io/ably/lib/realtime/ChannelBase.java', 'lib/src/test/java/io/ably/lib/test/common/Helpers.java', 'lib/src/test/java/io/ably/lib/test/realtime/RealtimePresenceTest.java']
{'.java': 4}
4
4
0
0
4
760,599
152,251
19,908
109
1,767
329
27
2
864
130
171
11
1
0
2023-02-01T18:37:23
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
806
ably/ably-java/895/888
ably
ably-java
https://github.com/ably/ably-java/issues/888
https://github.com/ably/ably-java/pull/895
https://github.com/ably/ably-java/pull/895
1
fixes
EventEmitter.on() does not permit the same listener to be added multiple times
https://github.com/ably/ably-java/blob/9786de65bd44c2f139a53ee235535cb7617cbc87/lib/src/main/java/io/ably/lib/util/EventEmitter.java#L41 The two implementations of EventEmitter.on() prevents the same listener from being registered multiple times (and thus being invoked multiple times per event). It should allow this to happen as per https://sdk.ably.com/builds/ably/specification/main/features/#RTE4.
ba58297e750218b9c86a30a89a1a58fb91c86c89
072d6e9ed3d16044ac673a439c0a5de4fbc130e6
https://github.com/ably/ably-java/compare/ba58297e750218b9c86a30a89a1a58fb91c86c89...072d6e9ed3d16044ac673a439c0a5de4fbc130e6
diff --git a/core/src/main/java/io/ably/lib/util/EventEmitter.java b/core/src/main/java/io/ably/lib/util/EventEmitter.java index 46fac0a7..fc6c7c87 100644 --- a/core/src/main/java/io/ably/lib/util/EventEmitter.java +++ b/core/src/main/java/io/ably/lib/util/EventEmitter.java @@ -1,10 +1,7 @@ package io.ably.lib.util; import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; -import java.util.Map; /** * A generic interface for event registration and delivery used in a number of the types in the Realtime client library. @@ -26,8 +23,8 @@ public abstract class EventEmitter<Event, Listener> { } /** - * Registers the provided listener all events. - * If on() is called more than once with the same listener and event, + * Registers the provided listener for all events. + * If on() is called more than once with the same listener, * the listener is added multiple times to its listener registry. * Therefore, as an example, assuming the same listener is registered twice using on(), * and an event is emitted once, the listener would be invoked twice. @@ -39,8 +36,7 @@ public abstract class EventEmitter<Event, Listener> { * This listener is invoked on a background thread. */ public synchronized void on(Listener listener) { - if(!listeners.contains(listener)) - listeners.add(listener); + listeners.add(listener); } /** @@ -58,7 +54,7 @@ public abstract class EventEmitter<Event, Listener> { * This listener is invoked on a background thread. */ public synchronized void once(Listener listener) { - filters.put(listener, new Filter(null, listener, true)); + filters.add(new Filter(null, listener, true)); } /** @@ -70,7 +66,7 @@ public abstract class EventEmitter<Event, Listener> { */ public synchronized void off(Listener listener) { listeners.remove(listener); - filters.remove(listener); + filters.removeIf(pair -> pair.listener == listener); } /** @@ -88,7 +84,7 @@ public abstract class EventEmitter<Event, Listener> { * This listener is invoked on a background thread. */ public synchronized void on(Event event, Listener listener) { - filters.put(listener, new Filter(event, listener, false)); + filters.add(new Filter(event, listener, false)); } /** @@ -106,7 +102,7 @@ public abstract class EventEmitter<Event, Listener> { * This listener is invoked on a background thread. */ public synchronized void once(Event event, Listener listener) { - filters.put(listener, new Filter(event, listener, true)); + filters.add(new Filter(event, listener, true)); } /** @@ -117,9 +113,7 @@ public abstract class EventEmitter<Event, Listener> { * @param event The named event. */ public synchronized void off(Event event, Listener listener) { - Filter filter = filters.get(listener); - if(filter != null && filter.event == event) - filters.remove(listener); + filters.removeIf(filter -> filter.listener == listener && filter.event != null && filter.event == event); } /** @@ -144,17 +138,19 @@ public abstract class EventEmitter<Event, Listener> { apply(listener, event, args); } - Map<Listener, Filter> clonedFilters = new HashMap<>(filters); - for (Iterator<Map.Entry<Listener, Filter>> it = clonedFilters.entrySet().iterator(); it.hasNext(); ) { - Map.Entry<Listener, Filter> entry = it.next(); - if (entry.getValue().apply(event, args)) { - filters.remove(entry.getKey()); + List<Filter> clonedFilters = new ArrayList<>(filters); + for (Filter entry: clonedFilters) { + if (entry.apply(event, args)) { + filters.remove(entry); } } } protected abstract void apply(Listener listener, Event event, Object... args); + /** + * Used to determine whether or not a listener is interested + */ protected class Filter { Filter(Event event, Listener listener, boolean once) { this.event = event; this.listener = listener; this.once = once; } private Event event; @@ -169,6 +165,6 @@ public abstract class EventEmitter<Event, Listener> { } } - Map<Listener, Filter> filters = new HashMap<Listener, Filter>(); + List<Filter> filters = new ArrayList<Filter>(); List<Listener> listeners = new ArrayList<Listener>(); } diff --git a/core/src/test/java/io/ably/lib/util/EventEmitterTest.java b/core/src/test/java/io/ably/lib/util/EventEmitterTest.java index d56a0e0c..d272a23b 100644 --- a/core/src/test/java/io/ably/lib/util/EventEmitterTest.java +++ b/core/src/test/java/io/ably/lib/util/EventEmitterTest.java @@ -73,6 +73,22 @@ public class EventEmitterTest { assertEquals(listener.counts.get(MyEvents.event_1), Integer.valueOf(1)); } + /** + * Register a listener twice, and verify it is called twice + * when the event is emitted + */ + @Test + public void on_multiple_registrations() { + MyEmitter emitter = new MyEmitter(); + CountingListener listener = new CountingListener(); + emitter.on(listener); + emitter.on(listener); + emitter.emit(MyEvents.event_0, "on_multiple_0"); + emitter.emit(MyEvents.event_1, "on_multiple_1"); + assertEquals(listener.counts.get(MyEvents.event_0), Integer.valueOf(2)); + assertEquals(listener.counts.get(MyEvents.event_1), Integer.valueOf(2)); + } + /** * Register and unregister listener, and verify it * is not called when the event is emitted @@ -111,7 +127,7 @@ public class EventEmitterTest { /** * Register a listener for a specific event, and verify it is called - * only when that event is emitted + * only when that event is emitted. */ @Test public void on_event_simple() { @@ -125,6 +141,23 @@ public class EventEmitterTest { assertNull(listener.counts.get(MyEvents.event_1)); } + /** + * Register a listener multiple times for a specific event, and verify it is called + * multiple times when that event is emitted + */ + @Test + public void on_event_multiple_registrations() { + MyEmitter emitter = new MyEmitter(); + CountingListener listener = new CountingListener(); + emitter.on(MyEvents.event_0, listener); + emitter.on(MyEvents.event_0, listener); + emitter.on(MyEvents.event_1, listener); + emitter.emit(MyEvents.event_0, "on_event_simple_0"); + emitter.emit(MyEvents.event_1, "on_event_simple_1"); + assertEquals(listener.counts.get(MyEvents.event_0), Integer.valueOf(2)); + assertEquals(listener.counts.get(MyEvents.event_1), Integer.valueOf(1)); + } + /** * Register a listener for a specific event, and verify * it is no longer called after it has been removed
['core/src/test/java/io/ably/lib/util/EventEmitterTest.java', 'core/src/main/java/io/ably/lib/util/EventEmitter.java']
{'.java': 2}
2
2
0
0
2
763,826
153,172
19,991
113
1,913
370
36
1
405
32
101
3
2
0
2023-01-12T10:27:12
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
807
ably/ably-java/825/823
ably
ably-java
https://github.com/ably/ably-java/issues/823
https://github.com/ably/ably-java/pull/825
https://github.com/ably/ably-java/pull/825
1
closes
waiter.close() is invoked early on onAuthUpdatedAsync method
After release of 1.2.15 Me and KacperKluka realized that waiter is closed too early, just after execute call from background thread. That was a copy/paste mistake from the previous method. We should move waiter.close method inside the background thread and close it after the while loop breaks. ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-2468) by [Unito](https://www.unito.io)
361ee12f4ae0bd227d964a538db015a6e837ec98
370a444d305bc47d29e5b0ed654cf25e5097cb33
https://github.com/ably/ably-java/compare/361ee12f4ae0bd227d964a538db015a6e837ec98...370a444d305bc47d29e5b0ed654cf25e5097cb33
diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index fe29b824..2004cf8c 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -988,71 +988,69 @@ public class ConnectionManager implements ConnectListener { **/ public void onAuthUpdatedAsync(final String token, final Auth.AuthUpdateResult authUpdateResult) { final ConnectionWaiter waiter = new ConnectionWaiter(); - try { - switch (currentState.state) { - case connected: - /* (RTC8a) If the connection is in the CONNECTED currentState and - * auth.authorize is called or Ably requests a re-authentication - * (see RTN22), the client must obtain a new token, then send an - * AUTH ProtocolMessage to Ably with an auth attribute - * containing an AuthDetails object with the token string. */ - try { - ProtocolMessage msg = new ProtocolMessage(ProtocolMessage.Action.auth); - msg.auth = new ProtocolMessage.AuthDetails(token); - send(msg, false, null); - } catch (AblyException e) { - /* The send failed. Close the transport; if a subsequent - * reconnect succeeds, it will be with the new token. */ - Log.v(TAG, "onAuthUpdated: closing transport after send failure"); - transport.close(); - } - break; + switch (currentState.state) { + case connected: + /* (RTC8a) If the connection is in the CONNECTED currentState and + * auth.authorize is called or Ably requests a re-authentication + * (see RTN22), the client must obtain a new token, then send an + * AUTH ProtocolMessage to Ably with an auth attribute + * containing an AuthDetails object with the token string. */ + try { + ProtocolMessage msg = new ProtocolMessage(ProtocolMessage.Action.auth); + msg.auth = new ProtocolMessage.AuthDetails(token); + send(msg, false, null); + } catch (AblyException e) { + /* The send failed. Close the transport; if a subsequent + * reconnect succeeds, it will be with the new token. */ + Log.v(TAG, "onAuthUpdated: closing transport after send failure"); + transport.close(); + } + break; - case connecting: - /* Close the connecting transport. */ - Log.v(TAG, "onAuthUpdated: closing connecting transport"); - ErrorInfo disconnectError = new ErrorInfo("Aborting incomplete connection with superseded auth params", 503, 80003); - requestState(new StateIndication(ConnectionState.disconnected, disconnectError, null, null)); - /* Start a new connection attempt. */ - connect(); - break; + case connecting: + /* Close the connecting transport. */ + Log.v(TAG, "onAuthUpdated: closing connecting transport"); + ErrorInfo disconnectError = new ErrorInfo("Aborting incomplete connection with superseded auth params", 503, 80003); + requestState(new StateIndication(ConnectionState.disconnected, disconnectError, null, null)); + /* Start a new connection attempt. */ + connect(); + break; - default: - /* Start a new connection attempt. */ - connect(); - break; - } + default: + /* Start a new connection attempt. */ + connect(); + break; + } - /* Wait for a currentState transition into anything other than connecting or - * disconnected in a background thread */ - singleThreadExecutor.execute(() -> { - boolean waitingForConnected = true; - while (waitingForConnected) { - final ErrorInfo reason = waiter.waitForChange(); - final ConnectionState connectionState = currentState.state; - switch (connectionState) { - case connected: - authUpdateResult.onUpdate(true, null); - Log.v(TAG, "onAuthUpdated: got connected"); - waitingForConnected = false; - break; + /* Wait for a currentState transition into anything other than connecting or + * disconnected in a background thread */ + singleThreadExecutor.execute(() -> { + boolean waitingForConnected = true; + while (waitingForConnected) { + final ErrorInfo reason = waiter.waitForChange(); + final ConnectionState connectionState = currentState.state; + switch (connectionState) { + case connected: + authUpdateResult.onUpdate(true, null); + Log.v(TAG, "onAuthUpdated: got connected"); + waitingForConnected = false; + break; - case connecting: - case disconnected: - Log.v(TAG, "onAuthUpdated: " + connectionState); - break; + case connecting: + case disconnected: + Log.v(TAG, "onAuthUpdated: " + connectionState); + break; - default: - /* suspended/closed/error: throw the error. */ - Log.v(TAG, "onAuthUpdated: throwing exception"); - authUpdateResult.onUpdate(false, reason); - waitingForConnected = false; - } + default: + /* suspended/closed/error: throw the error. */ + Log.v(TAG, "onAuthUpdated: throwing exception"); + authUpdateResult.onUpdate(false, reason); + waitingForConnected = false; } - }); - } finally { + } waiter.close(); - } + }); + } /** diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java index 4fa6acc3..f0cbf2b1 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java @@ -33,6 +33,10 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + public class RealtimeAuthTest extends ParameterizedTest { @Rule @@ -914,6 +918,7 @@ public class RealtimeAuthTest extends ParameterizedTest { try { opts.wait(); } catch(InterruptedException ie) {} + ably.auth.renewAuth((success, tokenDetails1, errorInfo) -> { //Ignore completion handling }); @@ -933,6 +938,84 @@ public class RealtimeAuthTest extends ParameterizedTest { } } + @Test + public void auth_renewAuth_callback_invoked() throws InterruptedException { + try { + /* get a TokenDetails */ + final String testKey = testVars.keys[0].keyStr; + final ClientOptions clientOptions = createOptions(testKey); + final AblyRest ablyRest = new AblyRest(clientOptions); + + final TokenDetails tokenDetails = ablyRest.auth.requestToken(new Auth.TokenParams() {{ + ttl = 1000L; + }}, null); + assertNotNull("Expected token value", tokenDetails.token); + + // create Ably realtime instance with token and authCallback + class ProtocolListener extends DebugOptions implements DebugOptions.RawProtocolListener { + ProtocolListener() { + Setup.getTestVars().fillInOptions(this); + protocolListener = this; + } + + @Override + public void onRawConnectRequested(String url) { + synchronized (this) { + notify(); + } + } + + @Override + public void onRawConnect(String url) { + } + + @Override + public void onRawMessageSend(ProtocolMessage message) { + } + + @Override + public void onRawMessageRecv(ProtocolMessage message) { + } + } + + final ProtocolListener protocolListener = new ProtocolListener(); + protocolListener.autoConnect = false; + protocolListener.tokenDetails = tokenDetails; + // implement callback, using Ably instance with key + protocolListener.authCallback = params -> tokenDetails; + + final AblyRealtime ably = new AblyRealtime(protocolListener); + synchronized (protocolListener) { + ably.connect(); + try { + protocolListener.wait(); + } catch (InterruptedException ie) { + fail("auth_expired_token_expire_renew protocolListener.wait(): interrupted -" + ie.getMessage()); + } + } + + final Helpers.ConnectionWaiter connectionWaiter = new Helpers.ConnectionWaiter(ably.connection); + boolean isConnected = connectionWaiter.waitFor(ConnectionState.connected, 1, 4000L); + if (isConnected) { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean isCalled = new AtomicBoolean(false); + ably.auth.renewAuth((success, tokenDetails1, errorInfo) -> { + latch.countDown(); + isCalled.set(true); + }); + latch.await(30, TimeUnit.SECONDS); + assertTrue("Callback not invoked", isCalled.get()); + ably.close(); + } else { + fail("auth_renewAuth_callback_invoked: unable to connect; final state = " + ably.connection.state); + } + } catch (AblyException e) { + e.printStackTrace(); + fail("auth_renewAuth_callback_invoked: Unexpected exception instantiating library: " + e.getMessage()); + } + } + + /** * Verify that with queryTime=false, when instancing with an already-expired token and authCallback, * connection can succeed
['lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java', 'lib/src/main/java/io/ably/lib/transport/ConnectionManager.java']
{'.java': 2}
2
2
0
0
2
661,290
129,448
17,808
107
6,174
971
114
1
421
56
102
9
2
0
2022-07-15T13:53:20
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
808
ably/ably-java/816/814
ably
ably-java
https://github.com/ably/ably-java/issues/814
https://github.com/ably/ably-java/pull/816
https://github.com/ably/ably-java/pull/816
1
closes
Early return from onAuthUpdated creates issues
`AblyBase` and `ConnectionManager` have a method called `onAuthUpdated` that contains a `waitForResponse` and is used to decide whether to wait for async response before returning from method. This seems to be set to `false` only when `Auth.renew()` is called. This feature doesn't seem to be on spec. Apart from this, this method is implicitly asynchronous. When the `waitForResponse` is set to `false` there is no opportunity for caller to know about the result. For our specific case we want to know when the token renewal is completed. As a result we either have to * Remove this parameter and wait for response for all cases, so that it is safe to call it synchronously or * Provide a callback so that callers are notified of completion. Please see [this thread](https://github.com/ably/ably-asset-tracking-android/pull/703/files#r907540279) to see where this discussion has started. ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-2385) by [Unito](https://www.unito.io)
faa89afa8b6dc4fb535a6f488e3b776c4a0ab8a7
1bbbd8ba1617fedc5fbd0cb0afb07e68fa676c04
https://github.com/ably/ably-java/compare/faa89afa8b6dc4fb535a6f488e3b776c4a0ab8a7...1bbbd8ba1617fedc5fbd0cb0afb07e68fa676c04
diff --git a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java index 2a27a50f..f91e3dbd 100644 --- a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java +++ b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java @@ -4,6 +4,7 @@ import java.util.Iterator; import java.util.Map; import io.ably.lib.rest.AblyRest; +import io.ably.lib.rest.Auth; import io.ably.lib.transport.ConnectionManager; import io.ably.lib.types.AblyException; import io.ably.lib.types.ChannelOptions; @@ -100,6 +101,14 @@ public class AblyRealtime extends AblyRest { connection.connectionManager.onAuthUpdated(token, waitForResponse); } + /** + * Authentication token has changed. Async version + */ + @Override + protected void onAuthUpdatedAsync(String token, Auth.AuthUpdateResult authUpdateResult) { + connection.connectionManager.onAuthUpdatedAsync(token,authUpdateResult); + } + /** * Authentication error occurred */ diff --git a/lib/src/main/java/io/ably/lib/rest/AblyBase.java b/lib/src/main/java/io/ably/lib/rest/AblyBase.java index 57b14b54..deee49b8 100644 --- a/lib/src/main/java/io/ably/lib/rest/AblyBase.java +++ b/lib/src/main/java/io/ably/lib/rest/AblyBase.java @@ -316,6 +316,15 @@ public abstract class AblyBase implements AutoCloseable { /* Default is to do nothing. Overridden by subclass. */ } + /** + * Override this method in AblyRealtime and pass updated token to ConnectionManager + * @param token new token + * @param authUpdateResult Callback result + */ + protected void onAuthUpdatedAsync(String token, Auth.AuthUpdateResult authUpdateResult) { + //this must be overriden by subclass + } + /** * Authentication error occurred */ diff --git a/lib/src/main/java/io/ably/lib/rest/Auth.java b/lib/src/main/java/io/ably/lib/rest/Auth.java index c9d7eec2..9ad0abc2 100644 --- a/lib/src/main/java/io/ably/lib/rest/Auth.java +++ b/lib/src/main/java/io/ably/lib/rest/Auth.java @@ -35,7 +35,6 @@ import io.ably.lib.util.Serialisation; * */ public class Auth { - /** * Authentication methods */ @@ -467,6 +466,33 @@ public class Auth { } } + /** + * An interface providing update result for onAuthUpdated + */ + public interface AuthUpdateResult{ + /** + * Signals an update from {@link io.ably.lib.transport.ConnectionManager#onAuthUpdatedAsync(String, AuthUpdateResult)} + * @param success If Update was successful + * @param errorInfo optional errorInfo if update wasn't successful + */ + void onUpdate(boolean success, ErrorInfo errorInfo); + } + + /** + * An interface providing completion callbackk for renewAuth + */ + public interface RenewAuthResult { + /** + * Signals completion of {@link Auth#renewAuth(RenewAuthResult)} + * @param success if token renewal was successful. Please note that success for this operation means that + * other operations relating to this also succeeded. + * @param tokenDetails New token details. Please note that this value can exist regardless of value of + * success state. + * @param errorInfo Error details if operation is completed with error. + */ + void onCompletion(boolean success,TokenDetails tokenDetails, ErrorInfo errorInfo); + } + /** * An interface implemented by a callback that provides either tokens, * or signed token requests, in response to a request with given token params. @@ -827,13 +853,31 @@ public class Auth { * Renew auth credentials. * Will obtain a new token, even if we already have an apparently valid one. * Authorization will use the parameters supplied on construction. + * @deprecated Because the method returns early before renew() completes and does not provide a completion + * handler for callers. + * Please use {@link Auth#renewAuth} instead */ + @Deprecated public TokenDetails renew() throws AblyException { TokenDetails tokenDetails = assertValidToken(this.tokenParams, this.authOptions, true); ably.onAuthUpdated(tokenDetails.token, false); return tokenDetails; } + /** + * Renew auth credentials. + * Will obtain a new token, even if we already have an apparently valid one. + * Authorization will use the parameters supplied on construction. + * @param result Asynchronous result the completion + * Please note that completion callback {@link RenewAuthResult#onCompletion(boolean, TokenDetails, ErrorInfo)} + * is called on a background thread. + */ + public void renewAuth(RenewAuthResult result) throws AblyException { + final TokenDetails tokenDetails = assertValidToken(this.tokenParams, this.authOptions, true); + + ably.onAuthUpdatedAsync(tokenDetails.token, (success, errorInfo) -> result.onCompletion(success,tokenDetails,errorInfo)); + } + public void onAuthError(ErrorInfo err) { /* we're only interested in token expiry errors */ if(err.code >= 40140 && err.code < 40150) diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index 7cc5ddaa..fe29b824 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -1,5 +1,16 @@ package io.ably.lib.transport; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import io.ably.lib.debug.DebugOptions; import io.ably.lib.debug.DebugOptions.RawProtocolListener; import io.ably.lib.http.HttpHelpers; @@ -10,8 +21,10 @@ import io.ably.lib.realtime.Connection; import io.ably.lib.realtime.ConnectionState; import io.ably.lib.realtime.ConnectionStateListener; import io.ably.lib.realtime.ConnectionStateListener.ConnectionStateChange; +import io.ably.lib.rest.Auth; import io.ably.lib.transport.ITransport.ConnectListener; import io.ably.lib.transport.ITransport.TransportParams; +import io.ably.lib.transport.NetworkConnectivity.NetworkConnectivityListener; import io.ably.lib.types.AblyException; import io.ably.lib.types.ClientOptions; import io.ably.lib.types.ConnectionDetails; @@ -19,18 +32,12 @@ import io.ably.lib.types.ErrorInfo; import io.ably.lib.types.ProtocolMessage; import io.ably.lib.types.ProtocolSerializer; import io.ably.lib.util.Log; -import io.ably.lib.transport.NetworkConnectivity.NetworkConnectivityListener; import io.ably.lib.util.PlatformAgentProvider; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; - public class ConnectionManager implements ConnectListener { + final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); + final ExecutorCompletionService<Void> executorCompletionService = + new ExecutorCompletionService<>(singleThreadExecutor); /************************************************************** * ConnectionManager @@ -975,6 +982,79 @@ public class ConnectionManager implements ConnectListener { } } + + /** + * Async version of onAuthUpdated that returns a Future that includes an option Ably exception + **/ + public void onAuthUpdatedAsync(final String token, final Auth.AuthUpdateResult authUpdateResult) { + final ConnectionWaiter waiter = new ConnectionWaiter(); + try { + switch (currentState.state) { + case connected: + /* (RTC8a) If the connection is in the CONNECTED currentState and + * auth.authorize is called or Ably requests a re-authentication + * (see RTN22), the client must obtain a new token, then send an + * AUTH ProtocolMessage to Ably with an auth attribute + * containing an AuthDetails object with the token string. */ + try { + ProtocolMessage msg = new ProtocolMessage(ProtocolMessage.Action.auth); + msg.auth = new ProtocolMessage.AuthDetails(token); + send(msg, false, null); + } catch (AblyException e) { + /* The send failed. Close the transport; if a subsequent + * reconnect succeeds, it will be with the new token. */ + Log.v(TAG, "onAuthUpdated: closing transport after send failure"); + transport.close(); + } + break; + + case connecting: + /* Close the connecting transport. */ + Log.v(TAG, "onAuthUpdated: closing connecting transport"); + ErrorInfo disconnectError = new ErrorInfo("Aborting incomplete connection with superseded auth params", 503, 80003); + requestState(new StateIndication(ConnectionState.disconnected, disconnectError, null, null)); + /* Start a new connection attempt. */ + connect(); + break; + + default: + /* Start a new connection attempt. */ + connect(); + break; + } + + /* Wait for a currentState transition into anything other than connecting or + * disconnected in a background thread */ + singleThreadExecutor.execute(() -> { + boolean waitingForConnected = true; + while (waitingForConnected) { + final ErrorInfo reason = waiter.waitForChange(); + final ConnectionState connectionState = currentState.state; + switch (connectionState) { + case connected: + authUpdateResult.onUpdate(true, null); + Log.v(TAG, "onAuthUpdated: got connected"); + waitingForConnected = false; + break; + + case connecting: + case disconnected: + Log.v(TAG, "onAuthUpdated: " + connectionState); + break; + + default: + /* suspended/closed/error: throw the error. */ + Log.v(TAG, "onAuthUpdated: throwing exception"); + authUpdateResult.onUpdate(false, reason); + waitingForConnected = false; + } + } + }); + } finally { + waiter.close(); + } + } + /** * Called when where was an error during authentication attempt * diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java index 44dedb2b..4fa6acc3 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java @@ -861,6 +861,78 @@ public class RealtimeAuthTest extends ParameterizedTest { } } + + /** + * Call renewAuth() whilst connecting; verify there's no crash (see https://github.com/ably/ably-java/issues/503) + */ + @Test + public void auth_renewAuth_whilst_connecting() { + try { + /* get a TokenDetails */ + final String testKey = testVars.keys[0].keyStr; + ClientOptions optsForToken = createOptions(testKey); + final AblyRest ablyForToken = new AblyRest(optsForToken); + + final TokenDetails tokenDetails = ablyForToken.auth.requestToken(new Auth.TokenParams(){{ ttl = 1000L; }}, null); + assertNotNull("Expected token value", tokenDetails.token); + + /* create Ably realtime instance with token and authCallback */ + class ProtocolListener extends DebugOptions implements DebugOptions.RawProtocolListener { + ProtocolListener() { + Setup.getTestVars().fillInOptions(this); + protocolListener = this; + } + @Override + public void onRawConnectRequested(String url) { + synchronized(this) { + notify(); + } + } + + @Override + public void onRawConnect(String url) {} + @Override + public void onRawMessageSend(ProtocolMessage message) {} + @Override + public void onRawMessageRecv(ProtocolMessage message) {} + } + + ProtocolListener opts = new ProtocolListener(); + opts.autoConnect = false; + opts.tokenDetails = tokenDetails; + opts.authCallback = new Auth.TokenCallback() { + /* implement callback, using Ably instance with key */ + @Override + public Object getTokenRequest(Auth.TokenParams params) { + return tokenDetails; + } + }; + + final AblyRealtime ably = new AblyRealtime(opts); + synchronized (opts) { + ably.connect(); + try { + opts.wait(); + } catch(InterruptedException ie) {} + ably.auth.renewAuth((success, tokenDetails1, errorInfo) -> { + //Ignore completion handling + }); + } + + Helpers.ConnectionWaiter connectionWaiter = new Helpers.ConnectionWaiter(ably.connection); + boolean isConnected = connectionWaiter.waitFor(ConnectionState.connected, 1, 4000L); + if(isConnected) { + /* done */ + ably.close(); + } else { + fail("auth_expired_token_expire_renew: unable to connect; final state = " + ably.connection.state); + } + } catch (AblyException e) { + e.printStackTrace(); + fail("auth_expired_token_expire_renew: Unexpected exception instantiating library"); + } + } + /** * Verify that with queryTime=false, when instancing with an already-expired token and authCallback, * connection can succeed
['lib/src/main/java/io/ably/lib/rest/Auth.java', 'lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java', 'lib/src/main/java/io/ably/lib/rest/AblyBase.java', 'lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java', 'lib/src/main/java/io/ably/lib/transport/ConnectionManager.java']
{'.java': 5}
5
5
0
0
5
651,515
127,563
17,567
107
7,341
1,289
162
4
1,022
146
244
16
3
0
2022-07-05T11:47:20
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
809
ably/ably-java/746/741
ably
ably-java
https://github.com/ably/ably-java/issues/741
https://github.com/ably/ably-java/pull/746
https://github.com/ably/ably-java/pull/746
1
fixes
`IllegalStateException` in `Crypto` `CBCCipher`'s `decrypt` method
We've had this reported by a customer using our Flutter Plugin. I've reported this issue in this repository, however, as the call stack falls entirely within code from this SDK. ``` Fatal Exception: java.lang.IllegalStateException Cipher not initialized javax.crypto.Cipher.checkCipherState (Cipher.java:1640) javax.crypto.Cipher.doFinal (Cipher.java:2104) io.ably.lib.util.Crypto$CBCCipher.decrypt (Crypto.java:255) io.ably.lib.types.BaseMessage.decode (BaseMessage.java:134) io.ably.lib.types.BaseMessage.decode (BaseMessage.java:80) io.ably.lib.types.MessageSerializer$MessageBodyHandler.handleResponseBody (MessageSerializer.java:172) io.ably.lib.types.MessageSerializer$MessageBodyHandler.handleResponseBody (MessageSerializer.java:157) io.ably.lib.http.BasePaginatedQuery.handleResponse (BasePaginatedQuery.java:159) io.ably.lib.http.BasePaginatedQuery.handleResponse (BasePaginatedQuery.java:25) io.ably.lib.http.HttpCore.handleResponse (HttpCore.java:293) io.ably.lib.http.HttpCore.httpExecute (HttpCore.java:270) io.ably.lib.http.HttpCore.httpExecute (HttpCore.java:165) io.ably.lib.http.HttpCore.httpExecuteWithRetry (HttpCore.java:83) io.ably.lib.http.HttpScheduler$AsyncRequest.httpExecuteWithRetry (HttpScheduler.java:312) io.ably.lib.http.HttpScheduler$AblyRequestWithFallback.run (HttpScheduler.java:205) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:919) ``` They have tens of thousands of Android app users and thus far have just seen one instance of this in their reported crash logs. See [this internal Slack message](https://ably-real-time.slack.com/archives/C012DA29VM0/p1643265205068800?thread_ts=1643101418.063300&cid=C012DA29VM0), which contains a link to the Firebase console for this Crashlytics entry, to which some the Ably internal team have access. Other details: * **Device**: Realme realme 3 * **OS**: Android 10 * **Device state**: background ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-1518) by [Unito](https://www.unito.io)
bcd3bd9c12d8f4b34201a5d4b13493aa03d6aad1
2c2d6fd8148e08cf14be5331d014e059e4c1d8ec
https://github.com/ably/ably-java/compare/bcd3bd9c12d8f4b34201a5d4b13493aa03d6aad1...2c2d6fd8148e08cf14be5331d014e059e4c1d8ec
diff --git a/lib/src/main/java/io/ably/lib/types/BaseMessage.java b/lib/src/main/java/io/ably/lib/types/BaseMessage.java index b5aa6c1c..1dc39eae 100644 --- a/lib/src/main/java/io/ably/lib/types/BaseMessage.java +++ b/lib/src/main/java/io/ably/lib/types/BaseMessage.java @@ -8,7 +8,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import io.ably.lib.util.Base64Coder; -import io.ably.lib.util.Crypto.ChannelCipher; +import io.ably.lib.util.Crypto.EncryptingChannelCipher; import io.ably.lib.util.Log; import io.ably.lib.util.Serialisation; import org.msgpack.core.MessageFormat; @@ -131,7 +131,7 @@ public class BaseMessage implements Cloneable { case "cipher": if(opts != null && opts.encrypted) { try { - data = opts.getCipher().decrypt((byte[]) data); + data = opts.getCipherSet().getDecipher().decrypt((byte[]) data); } catch(AblyException e) { throw MessageDecodeException.fromDescription(e.errorInfo.message); } @@ -179,7 +179,7 @@ public class BaseMessage implements Cloneable { } } if (opts != null && opts.encrypted) { - ChannelCipher cipher = opts.getCipher(); + EncryptingChannelCipher cipher = opts.getCipherSet().getEncipher(); data = cipher.encrypt((byte[]) data); encoding = ((encoding == null) ? "" : encoding + "/") + "cipher+" + cipher.getAlgorithm(); } diff --git a/lib/src/main/java/io/ably/lib/types/ChannelOptions.java b/lib/src/main/java/io/ably/lib/types/ChannelOptions.java index 2757d064..305cf194 100644 --- a/lib/src/main/java/io/ably/lib/types/ChannelOptions.java +++ b/lib/src/main/java/io/ably/lib/types/ChannelOptions.java @@ -5,16 +5,14 @@ import java.util.Map; import io.ably.lib.util.Base64Coder; import io.ably.lib.util.Crypto; import io.ably.lib.util.Crypto.ChannelCipher; +import io.ably.lib.util.Crypto.ChannelCipherSet; public class ChannelOptions { public Map<String, String> params; - + public ChannelMode[] modes; - /** - * Cipher in use. - */ - private ChannelCipher cipher; + private ChannelCipherSet cipherSet; /** * Parameters for the cipher. @@ -25,15 +23,15 @@ public class ChannelOptions { * Whether or not this ChannelOptions is encrypted. */ public boolean encrypted; - + public boolean hasModes() { return null != modes && 0 != modes.length; } - + public boolean hasParams() { return null != params && !params.isEmpty(); } - + public int getModeFlags() { int flags = 0; for (final ChannelMode mode : modes) { @@ -41,17 +39,57 @@ public class ChannelOptions { } return flags; } - + + /** + * Returns a wrapper around the cipher set to be used for this channel. This wrapper is only available in this API + * to support customers who may have been using it in their applications with version 1.2.10 or before. + * + * @deprecated Since version 1.2.11, this method (which was only ever intended for internal use within this library + * has been replaced by {@link #getCipherSet()}. It will be removed in the future. + */ + @Deprecated public ChannelCipher getCipher() throws AblyException { - if(!this.encrypted) { - return null; + return new ChannelCipher() { + @Override + public byte[] encrypt(byte[] plaintext) throws AblyException { + return getCipherSet().getEncipher().encrypt(plaintext); + } + + @Override + public byte[] decrypt(byte[] ciphertext) throws AblyException { + return getCipherSet().getDecipher().decrypt(ciphertext); + } + + @Override + public String getAlgorithm() { + try { + return getCipherSet().getEncipher().getAlgorithm(); + } catch (final AblyException e) { + throw new IllegalStateException("Unexpected exception when using legacy crypto cipher interface.", e); + } + } + }; + } + + /** + * Internal; this method is not intended for use by application developers. It may be changed or removed in future. + * + * Returns the cipher set to be used for encrypting and decrypting data on a channel, given the current state of + * this instance. On the first call to this method a new cipher set instance is created, with subsequent callers to + * this method being returned that same cipher set instance. This method is safe to be called from any thread. + * + * @apiNote Once this method has been called then the cipher set is fixed based on the value of the + * {@link #cipherParams} field at that time. If that field is then mutated, the cipher set will not be updated. + * This is not great API design and we should fix this under https://github.com/ably/ably-java/issues/745 + */ + public synchronized ChannelCipherSet getCipherSet() throws AblyException { + if (!encrypted) { + throw new IllegalStateException("ChannelOptions encrypted field value is false."); } - if(this.cipher != null) { - return this.cipher; - } else { - this.cipher = Crypto.getCipher(this); - return this.cipher; + if (null == cipherSet) { + cipherSet = Crypto.createChannelCipherSet(cipherParams); } + return cipherSet; } /** @@ -88,7 +126,6 @@ public class ChannelOptions { ChannelOptions options = new ChannelOptions(); options.encrypted = true; options.cipherParams = Crypto.getDefaultParams(key); - options.cipher = Crypto.getCipher(options); return options; } diff --git a/lib/src/main/java/io/ably/lib/util/Crypto.java b/lib/src/main/java/io/ably/lib/util/Crypto.java index 8fc19796..8c1054a7 100644 --- a/lib/src/main/java/io/ably/lib/util/Crypto.java +++ b/lib/src/main/java/io/ably/lib/util/Crypto.java @@ -4,7 +4,9 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; +import java.util.ConcurrentModificationException; import java.util.Locale; +import java.util.concurrent.Semaphore; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; @@ -15,7 +17,6 @@ import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import io.ably.lib.types.AblyException; -import io.ably.lib.types.ChannelOptions; import io.ably.lib.types.ErrorInfo; import io.ably.lib.types.Param; @@ -171,7 +172,13 @@ public class Crypto { /** * Interface for a ChannelCipher instance that may be associated with a Channel. * + * The operational methods implemented by channel cipher instances (encrypt and decrypt) are not designed to be + * safe to be called from any thread. + * + * @deprecated Since version 1.2.11, this interface (which was only ever intended for internal use within this + * library) has been replaced by {@link ChannelCipherSet}. It will be removed in the future. */ + @Deprecated public interface ChannelCipher { byte[] encrypt(byte[] plaintext) throws AblyException; byte[] decrypt(byte[] ciphertext) throws AblyException; @@ -179,87 +186,143 @@ public class Crypto { } /** - * Internal; get a ChannelCipher instance based on the given ChannelOptions - * @param opts - * @return - * @throws AblyException + * Internal; a cipher used to encrypt plaintext to ciphertext, for a channel. + */ + public interface EncryptingChannelCipher { + /** + * Enciphers plaintext. + * + * This method is not safe to be called from multiple threads at the same time, and it will throw a + * {@link ConcurrentModificationException} if that happens at runtime. + * + * @return ciphertext, being the result of encrypting plaintext. + * @throws ConcurrentModificationException If this method is called from more than one thread at a time. + */ + byte[] encrypt(byte[] plaintext) throws AblyException; + + String getAlgorithm(); + } + + /** + * Internal; a cipher used to decrypt plaintext from ciphertext, for a channel. */ - public static ChannelCipher getCipher(final ChannelOptions opts) throws AblyException { - final Object opaqueCipherParams = opts.cipherParams; - final CipherParams cipherParams; - if(null == opaqueCipherParams) - cipherParams = Crypto.getDefaultParams(); - else if(opts.cipherParams instanceof CipherParams) - cipherParams = (CipherParams)opts.cipherParams; + public interface DecryptingChannelCipher { + /** + * Deciphers ciphertext. + * + * This method is not safe to be called from multiple threads at the same time, and it will throw a + * {@link ConcurrentModificationException} if that happens at runtime. + * + * @return plaintext, being the result of decrypting ciphertext. + * @throws ConcurrentModificationException If this method is called from more than one thread at a time. + */ + byte[] decrypt(byte[] ciphertext) throws AblyException; + } + + /** + * Internal; a matching encipher and decipher pair, where both are guaranteed to have been configured with the same + * {@link CipherParams} as each other. + */ + public interface ChannelCipherSet { + EncryptingChannelCipher getEncipher(); + DecryptingChannelCipher getDecipher(); + } + + /** + * Internal; get an encrypting cipher instance based on the given channel options. + */ + public static ChannelCipherSet createChannelCipherSet(final Object cipherParams) throws AblyException { + final CipherParams nonNullParams; + if (null == cipherParams) + nonNullParams = Crypto.getDefaultParams(); + else if (cipherParams instanceof CipherParams) + nonNullParams = (CipherParams)cipherParams; else throw AblyException.fromErrorInfo(new ErrorInfo("ChannelOptions not supported", 400, 40000)); - return new CBCCipher(cipherParams); + return new ChannelCipherSet() { + private final EncryptingChannelCipher encipher = new EncryptingCBCCipher(nonNullParams); + private final DecryptingChannelCipher decipher = new DecryptingCBCCipher(nonNullParams); + + @Override + public EncryptingChannelCipher getEncipher() { + return encipher; + } + + @Override + public DecryptingChannelCipher getDecipher() { + return decipher; + } + }; } /** - * Internal: a class that implements a CBC mode ChannelCipher. + * Implements a CBC mode ChannelCipher. * A single block of secure random data is provided for an initial IV. * Consecutive messages are chained in a manner that allows each to be * emitted with an IV, allowing each to be deciphered independently, * whilst avoiding having to obtain further entropy for IVs, and reinit * the cipher, between successive messages. - * */ - private static class CBCCipher implements ChannelCipher { - private final SecretKeySpec keySpec; - private final Cipher encryptCipher; - private final Cipher decryptCipher; - private final String algorithm; - private final int blockLength; - private byte[] iv; - - private CBCCipher(CipherParams params) throws AblyException { + private static class CBCCipher { + protected final SecretKeySpec keySpec; + protected final IvParameterSpec ivSpec; + protected final Cipher cipher; + protected final int blockLength; + protected final String algorithm; + private final Semaphore semaphore = new Semaphore(1); + + protected CBCCipher(final CipherParams params) throws AblyException { final String cipherAlgorithm = params.getAlgorithm(); String transformation = cipherAlgorithm.toUpperCase(Locale.ROOT) + "/CBC/PKCS5Padding"; try { algorithm = cipherAlgorithm + '-' + params.getKeyLength() + "-cbc"; keySpec = params.keySpec; - encryptCipher = Cipher.getInstance(transformation); - encryptCipher.init(Cipher.ENCRYPT_MODE, params.keySpec, params.ivSpec); - decryptCipher = Cipher.getInstance(transformation); - iv = params.ivSpec.getIV(); - blockLength = iv.length; + ivSpec = params.ivSpec; + blockLength = ivSpec.getIV().length; + cipher = Cipher.getInstance(transformation); } - catch (NoSuchAlgorithmException|NoSuchPaddingException|InvalidAlgorithmParameterException|InvalidKeyException e) { + catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw AblyException.fromThrowable(e); } } - @Override - public byte[] encrypt(byte[] plaintext) { - if(plaintext == null) return null; - int plaintextLength = plaintext.length; - int paddedLength = getPaddedLength(plaintextLength); - byte[] cipherIn = new byte[paddedLength]; - byte[] ciphertext = new byte[paddedLength + blockLength]; - int padding = paddedLength - plaintextLength; - System.arraycopy(plaintext, 0, cipherIn, 0, plaintextLength); - System.arraycopy(pkcs5Padding[padding], 0, cipherIn, plaintextLength, padding); - System.arraycopy(getIv(), 0, ciphertext, 0, blockLength); - byte[] cipherOut = encryptCipher.update(cipherIn); - System.arraycopy(cipherOut, 0, ciphertext, blockLength, paddedLength); - return ciphertext; + /** + * Subclasses must call this method before performing any work that uses the {@link #cipher} or otherwise + * mutates the state of this instance. + * + * TODO: under https://github.com/ably/ably-java/issues/747 we can then: + * - remove the need for the {@link #releaseOperationalPermit()} method, and + * - make this method return an AutoCloseable implementation that releases the semaphore. + */ + protected void acquireOperationalPermit() { + if (!semaphore.tryAcquire()) { + throw new ConcurrentModificationException("ChannelCipher instances are not designed to be operated from multiple threads simultaneously."); + } } - @Override - public byte[] decrypt(byte[] ciphertext) throws AblyException { - if(ciphertext == null) return null; - byte[] plaintext = null; + /** + * Subclasses must call this method after performing any work that uses the {@link #cipher} or otherwise + * mutates the state of this instance. + */ + protected void releaseOperationalPermit() { + semaphore.release(); + } + } + + private static class EncryptingCBCCipher extends CBCCipher implements EncryptingChannelCipher { + private byte[] iv; + + EncryptingCBCCipher(final CipherParams params) throws AblyException { + super(params); + try { - decryptCipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ciphertext, 0, blockLength)); - plaintext = decryptCipher.doFinal(ciphertext, blockLength, ciphertext.length - blockLength); - } - catch (InvalidKeyException|InvalidAlgorithmParameterException|IllegalBlockSizeException|BadPaddingException e) { - Log.e(TAG, "decrypt()", e); + cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); + } catch (InvalidAlgorithmParameterException | InvalidKeyException e) { throw AblyException.fromThrowable(e); } - return plaintext; + + iv = params.ivSpec.getIV(); } @Override @@ -268,36 +331,12 @@ public class Crypto { } /** - * Internal: get an IV for the next message. - * Returns either the IV that was used to initialise the ChannelCipher, - * or generates an IV based on the current cipher state. - */ - private byte[] getIv() { - if(iv == null) - return encryptCipher.update(emptyBlock); - - final byte[] result = iv; - iv = null; - return result; - } - - /** - * Internal: calculate the padded length of a given plaintext - * using PKCS5. - * @param plaintextLength - * @return - */ - private static int getPaddedLength(int plaintextLength) { - return (plaintextLength + DEFAULT_BLOCKLENGTH) & -DEFAULT_BLOCKLENGTH; - } - - /** - * Internal: a block containing zeros + * A block containing zeros. */ private static final byte[] emptyBlock = new byte[DEFAULT_BLOCKLENGTH]; /** - * Internal: obtain the pkcs5 padding string for a given padded length; + * The PKCS5 padding strings for given padded lengths. */ private static final byte[][] pkcs5Padding = new byte[][] { new byte[] {16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16}, @@ -318,6 +357,72 @@ public class Crypto { new byte[] {15,15,15,15,15,15,15,15,15,15,15,15,15,15,15}, new byte[] {16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16} }; + + /** + * Returns the padded length of a given plaintext, using PKCS5. + */ + private static int getPaddedLength(int plaintextLength) { + return (plaintextLength + DEFAULT_BLOCKLENGTH) & -DEFAULT_BLOCKLENGTH; + } + + /** + * Get an IV for the next message. + * Returns either the IV that was used to initialise the ChannelCipher, + * or generates an IV based on the current cipher state. + */ + private byte[] getNextIv() { + if (iv == null) + return cipher.update(emptyBlock); + + final byte[] result = iv; + iv = null; + return result; + } + + @Override + public byte[] encrypt(byte[] plaintext) { + if (plaintext == null) return null; + + acquireOperationalPermit(); + try { + final int plaintextLength = plaintext.length; + final int paddedLength = getPaddedLength(plaintextLength); + final byte[] cipherIn = new byte[paddedLength]; + final byte[] ciphertext = new byte[paddedLength + blockLength]; + final int padding = paddedLength - plaintextLength; + System.arraycopy(plaintext, 0, cipherIn, 0, plaintextLength); + System.arraycopy(pkcs5Padding[padding], 0, cipherIn, plaintextLength, padding); + System.arraycopy(getNextIv(), 0, ciphertext, 0, blockLength); + final byte[] cipherOut = cipher.update(cipherIn); + System.arraycopy(cipherOut, 0, ciphertext, blockLength, paddedLength); + return ciphertext; + } finally { + // TODO: under https://github.com/ably/ably-java/issues/747 we will remove this call. + releaseOperationalPermit(); + } + } + } + + private static class DecryptingCBCCipher extends CBCCipher implements DecryptingChannelCipher { + DecryptingCBCCipher(final CipherParams params) throws AblyException { + super(params); + } + + @Override + public byte[] decrypt(byte[] ciphertext) throws AblyException { + if(ciphertext == null) return null; + + acquireOperationalPermit(); + try { + cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ciphertext, 0, blockLength)); + return cipher.doFinal(ciphertext, blockLength, ciphertext.length - blockLength); + } catch (InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) { + throw AblyException.fromThrowable(e); + } finally { + // TODO: under https://github.com/ably/ably-java/issues/747 we will remove this call. + releaseOperationalPermit(); + } + } } public static String getRandomId() { diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeCryptoTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeCryptoTest.java index 2270f6ef..52add81f 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeCryptoTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeCryptoTest.java @@ -33,7 +33,7 @@ import io.ably.lib.types.ChannelOptions; import io.ably.lib.types.ClientOptions; import io.ably.lib.types.ErrorInfo; import io.ably.lib.util.Crypto; -import io.ably.lib.util.Crypto.ChannelCipher; +import io.ably.lib.util.Crypto.ChannelCipherSet; import io.ably.lib.util.Crypto.CipherParams; public class RealtimeCryptoTest extends ParameterizedTest { @@ -805,12 +805,12 @@ public class RealtimeCryptoTest extends ParameterizedTest { @Test public void encodeDecodeVariableSizesWithAES256CBC() throws NoSuchAlgorithmException, AblyException { final CipherParams params = Crypto.getParams("aes", generateNonce(32), generateNonce(16)); - final ChannelCipher cipher = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params; }}); + final ChannelCipherSet cipherSet = Crypto.createChannelCipherSet(params); for (int i=1; i<1000; i++) { final int size = RANDOM.nextInt(2000) + 1; final byte[] message = generateNonce(size); - final byte[] encrypted = cipher.encrypt(message); - final byte[] decrypted = cipher.decrypt(encrypted); + final byte[] encrypted = cipherSet.getEncipher().encrypt(message); + final byte[] decrypted = cipherSet.getDecipher().decrypt(encrypted); try { assertArrayEquals(message, decrypted); } catch (final AssertionError e) { @@ -1066,12 +1066,12 @@ public class RealtimeCryptoTest extends ParameterizedTest { // We have to create a new ChannelCipher for each message we encode because // cipher instances only use the IV we've supplied via CipherParams for the // encryption of the very first message. - final ChannelCipher cipher = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params; }}); + final ChannelCipherSet cipherSet = Crypto.createChannelCipherSet(params); final byte[] appleMessage = hexStringToByteArray(entry.getKey()); final byte[] appleEncrypted = hexStringToByteArray(entry.getValue()); - final byte[] encrypted = cipher.encrypt(appleMessage); - final byte[] decrypted = cipher.decrypt(appleEncrypted); + final byte[] encrypted = cipherSet.getEncipher().encrypt(appleMessage); + final byte[] decrypted = cipherSet.getDecipher().decrypt(appleEncrypted); try { assertArrayEquals(appleMessage, decrypted); diff --git a/lib/src/test/java/io/ably/lib/test/rest/RestCryptoTest.java b/lib/src/test/java/io/ably/lib/test/rest/RestCryptoTest.java index 183c895a..a3ac5e5f 100644 --- a/lib/src/test/java/io/ably/lib/test/rest/RestCryptoTest.java +++ b/lib/src/test/java/io/ably/lib/test/rest/RestCryptoTest.java @@ -67,8 +67,12 @@ public class RestCryptoTest extends ParameterizedTest { /* verify message contents */ for (final Message message : messages.items()) messageContents.put(message.name, message.data); - assertEquals("This is a string message payload", messageContents.get("publish0")); - assertEquals("This is a byte[] message payload", new String((byte[])messageContents.get("publish1"))); + final Object payload0 = messageContents.get("publish0"); + final Object payload1 = messageContents.get("publish1"); + assertTrue("Unexpected " + payload0.getClass(), payload0 instanceof String); + assertTrue("Unexpected " + payload1.getClass(), payload1 instanceof byte[]); + assertEquals("This is a string message payload", payload0); + assertEquals("This is a byte[] message payload", new String((byte[])payload1)); } /** diff --git a/lib/src/test/java/io/ably/lib/util/CryptoTest.java b/lib/src/test/java/io/ably/lib/util/CryptoTest.java index e4b0cb53..6b471411 100644 --- a/lib/src/test/java/io/ably/lib/util/CryptoTest.java +++ b/lib/src/test/java/io/ably/lib/util/CryptoTest.java @@ -18,9 +18,9 @@ import org.msgpack.core.MessagePacker; import com.google.gson.stream.JsonWriter; import io.ably.lib.types.AblyException; -import io.ably.lib.types.ChannelOptions; -import io.ably.lib.util.Crypto.ChannelCipher; +import io.ably.lib.util.Crypto.ChannelCipherSet; import io.ably.lib.util.Crypto.CipherParams; +import io.ably.lib.util.Crypto.EncryptingChannelCipher; import io.ably.lib.util.CryptoMessageTest.FixtureSet; public class CryptoTest { @@ -57,10 +57,10 @@ public class CryptoTest { ); byte[] plaintext = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; - ChannelCipher channelCipher1 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params1; }}); - ChannelCipher channelCipher2 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params2; }}); - ChannelCipher channelCipher3 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params3; }}); - ChannelCipher channelCipher4 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params4; }}); + EncryptingChannelCipher channelCipher1 = Crypto.createChannelCipherSet(params1).getEncipher(); + EncryptingChannelCipher channelCipher2 = Crypto.createChannelCipherSet(params2).getEncipher(); + EncryptingChannelCipher channelCipher3 = Crypto.createChannelCipherSet(params3).getEncipher(); + EncryptingChannelCipher channelCipher4 = Crypto.createChannelCipherSet(params4).getEncipher(); byte[] ciphertext1 = channelCipher1.encrypt(plaintext); byte[] ciphertext2 = channelCipher2.encrypt(plaintext); @@ -127,18 +127,18 @@ public class CryptoTest { for (int i=1; i<=maxLength; i++) { // We need to create a new ChannelCipher for each message we encode, // so that our IV gets used (being start of CBC chain). - final ChannelCipher cipher = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params; }}); + final ChannelCipherSet cipherSet = Crypto.createChannelCipherSet(params); // Encrypt i bytes from the start of the message data. final byte[] encoded = Arrays.copyOfRange(message, 0, i); - final byte[] encrypted = cipher.encrypt(encoded); + final byte[] encrypted = cipherSet.getEncipher().encrypt(encoded); // Add encryption result to results in format ready for fixture. writeResult(writer, "byte 1 to " + i, encoded, encrypted, fixtureSet.cipherName); // Decrypt the encrypted data and verify the result is the same as what // we submitted for encryption. - final byte[] verify = cipher.decrypt(encrypted); + final byte[] verify = cipherSet.getDecipher().decrypt(encrypted); assertArrayEquals(verify, encoded); } writer.endArray();
['lib/src/test/java/io/ably/lib/test/rest/RestCryptoTest.java', 'lib/src/test/java/io/ably/lib/util/CryptoTest.java', 'lib/src/main/java/io/ably/lib/types/ChannelOptions.java', 'lib/src/main/java/io/ably/lib/types/BaseMessage.java', 'lib/src/test/java/io/ably/lib/test/realtime/RealtimeCryptoTest.java', 'lib/src/main/java/io/ably/lib/util/Crypto.java']
{'.java': 6}
6
6
0
0
6
636,482
124,595
17,211
105
15,664
3,028
342
3
2,156
148
525
41
3
1
2022-02-01T11:24:47
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
810
ably/ably-java/744/743
ably
ably-java
https://github.com/ably/ably-java/issues/743
https://github.com/ably/ably-java/pull/744
https://github.com/ably/ably-java/pull/744
1
fixes
`ConcurrentModificationException` when `unsubscribe` then `detach` channel presence listener
A customer is experiencing a crash with `ably-java` [version 1.2.10](https://github.com/ably/ably-java/releases/tag/v1.2.10), therefore my understanding is that this is pure JVM (i.e. a server type application - I think it's some kind of a bot), not Android. They have described the scenario to us: > When the UserA encounters a new user join to chatroom he was in , it registers the user presence listener. ```java presenceChannel.presence.subscribe(member -> { ``` > When UserA no longer needs to track the users presence (not a member of any active chat rooms), the listener is removed: ```java presenceChannel.presence.unsubscribe(); try { presenceChannel.detach(); } catch (AblyException e) { throw new BotException(e.toString()); } ``` > The error is encountered mostly when a user goes offline.... > The following is the exception stack: ``` 2022-01-25T15:37:29,129|INFO|SomeClient|WebSocketConnectReadThread-132|{"l":"DEBUG","msg":"receive presence event, action: leave, data: {\\"userId\\":\\"SomeUserIdValue\\",\\"status\\":\\"Online\\",\\"customStatus\\":\\"Available From SomeNamedTool\\"}","fnc":"SomeClient.registerUserPresence"} 2022-01-25T15:37:29,131|DEBUG|UserPresenceManager|WebSocketConnectReadThread-132|updateUserPresence: userId=PATESTFICA138, source=MESSAGING, state=OFFLINE (ERROR): io.ably.lib.transport.WebSocketTransport: Unexpected exception processing received binary message io.ably.lib.types.AblyException: java.util.ConcurrentModificationException at io.ably.lib.types.AblyException.fromThrowable(AblyException.java:54) at io.ably.lib.transport.ConnectionManager.onMessage(ConnectionManager.java:1080) at io.ably.lib.transport.WebSocketTransport$WsClient.onMessage(WebSocketTransport.java:161) at org.java_websocket.client.WebSocketClient.onWebsocketMessage(WebSocketClient.java:505) at org.java_websocket.drafts.Draft_6455.processFrameBinary(Draft_6455.java:835) at org.java_websocket.drafts.Draft_6455.processFrame(Draft_6455.java:794) at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:381) at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:218) at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:425) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997) at io.ably.lib.realtime.Presence$Multicaster.onPresenceMessage(Presence.java:359) at io.ably.lib.realtime.Presence.broadcastPresence(Presence.java:345) at io.ably.lib.realtime.Presence.setPresence(Presence.java:334) at io.ably.lib.realtime.ChannelBase.onPresence(ChannelBase.java:769) at io.ably.lib.realtime.ChannelBase.onChannelMessage(ChannelBase.java:1158) at io.ably.lib.realtime.AblyRealtime$InternalChannels.onMessage(AblyRealtime.java:187) at io.ably.lib.transport.ConnectionManager.onChannelMessage(ConnectionManager.java:1090) at io.ably.lib.transport.ConnectionManager.onMessage(ConnectionManager.java:1075) ... 8 more ``` (some details redacted above) Hubspot (internal) threads conversing with this customer are [here](https://app.hubspot.com/live-messages/6939709/inbox/2125159045#email-reply-editor) and, then, [here](https://app.hubspot.com/live-messages/6939709/inbox/2126124055#email-reply-editor). ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-1524) by [Unito](https://www.unito.io)
36275f5743101a6c76c3d913e85a438094c9db1f
1a8b857a7e38697994aab6a581bc11d687e83206
https://github.com/ably/ably-java/compare/36275f5743101a6c76c3d913e85a438094c9db1f...1a8b857a7e38697994aab6a581bc11d687e83206
diff --git a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java index f5a8cc0d..c32b6769 100644 --- a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java +++ b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java @@ -782,7 +782,7 @@ public abstract class ChannelBase extends EventEmitter<ChannelEvent, ChannelStat private static class MessageMulticaster extends io.ably.lib.util.Multicaster<MessageListener> implements MessageListener { @Override public void onMessage(Message message) { - for(MessageListener member : members) + for (final MessageListener member : getMembers()) try { member.onMessage(message); } catch (Throwable t) { diff --git a/lib/src/main/java/io/ably/lib/realtime/ChannelStateListener.java b/lib/src/main/java/io/ably/lib/realtime/ChannelStateListener.java index 963703eb..5de088c5 100644 --- a/lib/src/main/java/io/ably/lib/realtime/ChannelStateListener.java +++ b/lib/src/main/java/io/ably/lib/realtime/ChannelStateListener.java @@ -56,7 +56,7 @@ public interface ChannelStateListener { class Multicaster extends io.ably.lib.util.Multicaster<ChannelStateListener> implements ChannelStateListener { @Override public void onChannelStateChanged(ChannelStateChange stateChange) { - for(ChannelStateListener member : members) + for (final ChannelStateListener member : getMembers()) try { member.onChannelStateChanged(stateChange); } catch(Throwable t) {} diff --git a/lib/src/main/java/io/ably/lib/realtime/CompletionListener.java b/lib/src/main/java/io/ably/lib/realtime/CompletionListener.java index 431cb39f..38dc923a 100644 --- a/lib/src/main/java/io/ably/lib/realtime/CompletionListener.java +++ b/lib/src/main/java/io/ably/lib/realtime/CompletionListener.java @@ -29,7 +29,7 @@ public interface CompletionListener { @Override public void onSuccess() { - for(CompletionListener member : members) + for (final CompletionListener member : getMembers()) try { member.onSuccess(); } catch(Throwable t) {} @@ -37,7 +37,7 @@ public interface CompletionListener { @Override public void onError(ErrorInfo reason) { - for(CompletionListener member : members) + for (final CompletionListener member : getMembers()) try { member.onError(reason); } catch(Throwable t) {} diff --git a/lib/src/main/java/io/ably/lib/realtime/ConnectionStateListener.java b/lib/src/main/java/io/ably/lib/realtime/ConnectionStateListener.java index bcc444b9..10a9c403 100644 --- a/lib/src/main/java/io/ably/lib/realtime/ConnectionStateListener.java +++ b/lib/src/main/java/io/ably/lib/realtime/ConnectionStateListener.java @@ -38,7 +38,7 @@ public interface ConnectionStateListener { class Multicaster extends io.ably.lib.util.Multicaster<ConnectionStateListener> implements ConnectionStateListener { @Override public void onConnectionStateChanged(ConnectionStateChange state) { - for(ConnectionStateListener member : members) + for (final ConnectionStateListener member : getMembers()) try { member.onConnectionStateChanged(state); } catch(Throwable t) {} diff --git a/lib/src/main/java/io/ably/lib/realtime/Presence.java b/lib/src/main/java/io/ably/lib/realtime/Presence.java index 529a8d90..044f7d79 100644 --- a/lib/src/main/java/io/ably/lib/realtime/Presence.java +++ b/lib/src/main/java/io/ably/lib/realtime/Presence.java @@ -357,7 +357,7 @@ public class Presence { private static class Multicaster extends io.ably.lib.util.Multicaster<PresenceListener> implements PresenceListener { @Override public void onPresenceMessage(PresenceMessage message) { - for(PresenceListener member : members) + for (final PresenceListener member : getMembers()) try { member.onPresenceMessage(message); } catch(Throwable t) {} diff --git a/lib/src/main/java/io/ably/lib/util/Multicaster.java b/lib/src/main/java/io/ably/lib/util/Multicaster.java index be9fb046..9cd3f713 100644 --- a/lib/src/main/java/io/ably/lib/util/Multicaster.java +++ b/lib/src/main/java/io/ably/lib/util/Multicaster.java @@ -1,19 +1,27 @@ package io.ably.lib.util; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; +/** + * Collection of members who are listeners, with methods that are safe to be called from any thread. + * @param <T> The type of elements being added to this multicaster - the listeners. + */ public abstract class Multicaster<T> { - - protected final List<T> members = new ArrayList<T>(); + private final List<T> members = new ArrayList<>(); public Multicaster(T... members) { for(T m : members) this.members.add(m); } - - public void add(T member) { members.add(member); } - public void remove(T member) { members.remove(member); } - public void clear() { members.clear(); } - public boolean isEmpty() { return members.isEmpty(); } - public int size() { return members.size(); } - public Iterator<T> iterator() { return members.iterator(); } + + public synchronized void add(T member) { members.add(member); } + public synchronized void remove(T member) { members.remove(member); } + public synchronized void clear() { members.clear(); } + public synchronized boolean isEmpty() { return members.isEmpty(); } + public synchronized int size() { return members.size(); } + + /** + * Returns a snapshot of the members of this multicaster instance. + */ + protected synchronized List<T> getMembers() { + return new ArrayList<>(members); + } }
['lib/src/main/java/io/ably/lib/realtime/ChannelBase.java', 'lib/src/main/java/io/ably/lib/realtime/ConnectionStateListener.java', 'lib/src/main/java/io/ably/lib/util/Multicaster.java', 'lib/src/main/java/io/ably/lib/realtime/Presence.java', 'lib/src/main/java/io/ably/lib/realtime/ChannelStateListener.java', 'lib/src/main/java/io/ably/lib/realtime/CompletionListener.java']
{'.java': 6}
6
6
0
0
6
636,068
124,519
17,203
105
1,940
365
40
6
3,589
220
911
61
5
3
2022-01-31T15:32:42
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
802
ably/ably-java/922/920
ably
ably-java
https://github.com/ably/ably-java/issues/920
https://github.com/ably/ably-java/pull/922
https://github.com/ably/ably-java/pull/922
1
fixes
Provide an error code and error message for failed queued messages
The code below creates an empty error info when a pending message fails. It must also contain a convenient code and message (check spec and other SDKs) https://github.com/ably/ably-java/blob/94ecb6fada26982aaa698f3291f150f344eb2cd4/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java#L1800
f4a3671fb9ebacebb7adffb8655f56a5aba08441
acae4782bc003b6c9a93182facb1d78b7f222ba0
https://github.com/ably/ably-java/compare/f4a3671fb9ebacebb7adffb8655f56a5aba08441...acae4782bc003b6c9a93182facb1d78b7f222ba0
diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index 7dbe8b06..8891bd82 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -1682,7 +1682,7 @@ public class ConnectionManager implements ConnectListener { queuedMessages.clear(); //also pending messages - pendingMessages.fail(); + pendingMessages.fail(reason); } } @@ -1795,9 +1795,11 @@ public class ConnectionManager implements ConnectListener { } //fail all pending queued emssages - synchronized void fail() { + synchronized void fail(ErrorInfo reason) { for (QueuedMessage queuedMessage: queue){ - queuedMessage.listener.onError(new ErrorInfo()); + if (queuedMessage.listener != null) { + queuedMessage.listener.onError(reason); + } } queue.clear(); } diff --git a/lib/src/test/java/io/ably/lib/test/common/Helpers.java b/lib/src/test/java/io/ably/lib/test/common/Helpers.java index 2dce9b10..55c4f3df 100644 --- a/lib/src/test/java/io/ably/lib/test/common/Helpers.java +++ b/lib/src/test/java/io/ably/lib/test/common/Helpers.java @@ -174,10 +174,13 @@ public class Helpers { if (System.currentTimeMillis() > timeoutAt) { break; } - - wait(); + + wait(); } catch(InterruptedException e) {} success = successCount >= count; + if (error != null) { + assertNotNull(error.message); + } return error; }
['lib/src/test/java/io/ably/lib/test/common/Helpers.java', 'lib/src/main/java/io/ably/lib/transport/ConnectionManager.java']
{'.java': 2}
2
2
0
0
2
760,555
152,242
19,913
109
368
54
8
1
303
28
81
3
1
0
2023-02-24T10:26:02
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
811
ably/ably-java/742/741
ably
ably-java
https://github.com/ably/ably-java/issues/741
https://github.com/ably/ably-java/pull/742
https://github.com/ably/ably-java/pull/742
1
fixes
`IllegalStateException` in `Crypto` `CBCCipher`'s `decrypt` method
We've had this reported by a customer using our Flutter Plugin. I've reported this issue in this repository, however, as the call stack falls entirely within code from this SDK. ``` Fatal Exception: java.lang.IllegalStateException Cipher not initialized javax.crypto.Cipher.checkCipherState (Cipher.java:1640) javax.crypto.Cipher.doFinal (Cipher.java:2104) io.ably.lib.util.Crypto$CBCCipher.decrypt (Crypto.java:255) io.ably.lib.types.BaseMessage.decode (BaseMessage.java:134) io.ably.lib.types.BaseMessage.decode (BaseMessage.java:80) io.ably.lib.types.MessageSerializer$MessageBodyHandler.handleResponseBody (MessageSerializer.java:172) io.ably.lib.types.MessageSerializer$MessageBodyHandler.handleResponseBody (MessageSerializer.java:157) io.ably.lib.http.BasePaginatedQuery.handleResponse (BasePaginatedQuery.java:159) io.ably.lib.http.BasePaginatedQuery.handleResponse (BasePaginatedQuery.java:25) io.ably.lib.http.HttpCore.handleResponse (HttpCore.java:293) io.ably.lib.http.HttpCore.httpExecute (HttpCore.java:270) io.ably.lib.http.HttpCore.httpExecute (HttpCore.java:165) io.ably.lib.http.HttpCore.httpExecuteWithRetry (HttpCore.java:83) io.ably.lib.http.HttpScheduler$AsyncRequest.httpExecuteWithRetry (HttpScheduler.java:312) io.ably.lib.http.HttpScheduler$AblyRequestWithFallback.run (HttpScheduler.java:205) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:919) ``` They have tens of thousands of Android app users and thus far have just seen one instance of this in their reported crash logs. See [this internal Slack message](https://ably-real-time.slack.com/archives/C012DA29VM0/p1643265205068800?thread_ts=1643101418.063300&cid=C012DA29VM0), which contains a link to the Firebase console for this Crashlytics entry, to which some the Ably internal team have access. Other details: * **Device**: Realme realme 3 * **OS**: Android 10 * **Device state**: background ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-1518) by [Unito](https://www.unito.io)
36275f5743101a6c76c3d913e85a438094c9db1f
4b83312a6679624ef8b923e48f546541255dc9c7
https://github.com/ably/ably-java/compare/36275f5743101a6c76c3d913e85a438094c9db1f...4b83312a6679624ef8b923e48f546541255dc9c7
diff --git a/lib/src/main/java/io/ably/lib/util/Crypto.java b/lib/src/main/java/io/ably/lib/util/Crypto.java index 8fc19796..912b0a2c 100644 --- a/lib/src/main/java/io/ably/lib/util/Crypto.java +++ b/lib/src/main/java/io/ably/lib/util/Crypto.java @@ -171,10 +171,28 @@ public class Crypto { /** * Interface for a ChannelCipher instance that may be associated with a Channel. * + * The {@link #encrypt(byte[])} and {@link #decrypt(byte[])} methods must be implemented + * in a way that makes them safe to be called from any thread. */ public interface ChannelCipher { + /** + * Encrypt data. + * @param plaintext Data to be encrypted. + * @return Encrypted data. + * @throws AblyException Encapsulates an exception thrown by the encryption implementation, + * typically from either {@link java.security} or {@link javax.crypto} + */ byte[] encrypt(byte[] plaintext) throws AblyException; + + /** + * Decrypt data. + * @param ciphertext Encrypted data. + * @return Unencrypted data. + * @throws AblyException Encapsulates an exception thrown by the encryption implementation, + * typically from either {@link java.security} or {@link javax.crypto} + */ byte[] decrypt(byte[] ciphertext) throws AblyException; + String getAlgorithm(); } @@ -232,7 +250,7 @@ public class Crypto { } @Override - public byte[] encrypt(byte[] plaintext) { + public synchronized byte[] encrypt(byte[] plaintext) { if(plaintext == null) return null; int plaintextLength = plaintext.length; int paddedLength = getPaddedLength(plaintextLength); @@ -248,7 +266,7 @@ public class Crypto { } @Override - public byte[] decrypt(byte[] ciphertext) throws AblyException { + public synchronized byte[] decrypt(byte[] ciphertext) throws AblyException { if(ciphertext == null) return null; byte[] plaintext = null; try {
['lib/src/main/java/io/ably/lib/util/Crypto.java']
{'.java': 1}
1
1
0
0
1
636,068
124,519
17,203
105
1,076
212
22
1
2,156
148
525
41
3
1
2022-01-28T16:21:35
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
813
ably/ably-java/657/650
ably
ably-java
https://github.com/ably/ably-java/issues/650
https://github.com/ably/ably-java/pull/657
https://github.com/ably/ably-java/pull/657
1
fixes
Hosts class is not thread safe
The Hosts class is used by various threads when making api calls, however, the internals of this class are not handled in a thread safe way. the various calls to manipulate the primary and preferred hosts and the expirations will not work correctly for more than one thread at a time. ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-651) by [Unito](https://www.unito.io)
fcb4a1a7f7c15264236298083e7ef73a5bbde690
0f28d7b1c070d1287beba243334be35ca9056807
https://github.com/ably/ably-java/compare/fcb4a1a7f7c15264236298083e7ef73a5bbde690...0f28d7b1c070d1287beba243334be35ca9056807
diff --git a/lib/src/main/java/io/ably/lib/transport/Hosts.java b/lib/src/main/java/io/ably/lib/transport/Hosts.java index 3ce5bcaa..a4559b4f 100644 --- a/lib/src/main/java/io/ably/lib/transport/Hosts.java +++ b/lib/src/main/java/io/ably/lib/transport/Hosts.java @@ -10,18 +10,19 @@ import java.util.Collections; /** * Object to encapsulate primary host name and shuffled fallback host names. + * + * Methods on this class are safe to be called from any thread. */ public class Hosts { - private String primaryHost; - private String prefHost; - private long prefHostExpiry; - boolean primaryHostIsDefault; + private final String primaryHost; + private final boolean primaryHostIsDefault; private final String defaultHost; private final String[] fallbackHosts; private final boolean fallbackHostsIsDefault; private final boolean fallbackHostsUseDefault; private final long fallbackRetryTimeout; + private final Preferred preferred = new Preferred(); /** * Create Hosts object @@ -38,7 +39,7 @@ public class Hosts { * code, but the results are ignored because ConnectionManager then calls * setHost() and fallback is not used. */ - public Hosts(String primaryHost, String defaultHost, ClientOptions options) throws AblyException { + public Hosts(final String primaryHost, final String defaultHost, final ClientOptions options) throws AblyException { this.defaultHost = defaultHost; this.fallbackHostsUseDefault = options.fallbackHostsUseDefault; boolean hasCustomPrimaryHost = primaryHost != null && !primaryHost.equalsIgnoreCase(defaultHost); @@ -60,15 +61,16 @@ public class Hosts { } if (hasCustomPrimaryHost) { - setPrimaryHost(primaryHost); + this.primaryHost = primaryHost; if (options.environment != null) { /* TO3k2: It is never valid to provide both a restHost and environment value * TO3k3: It is never valid to provide both a realtimeHost and environment value */ throw AblyException.fromErrorInfo(new ErrorInfo("cannot set both restHost/realtimeHost and environment options", 40000, 400)); } } else { - setPrimaryHost(isProduction ? defaultHost : options.environment + "-" + defaultHost); + this.primaryHost = isProduction ? defaultHost : options.environment + "-" + defaultHost; } + primaryHostIsDefault = this.primaryHost.equalsIgnoreCase(defaultHost); fallbackHostsIsDefault = Arrays.equals(Defaults.HOST_FALLBACKS, tempFallbackHosts); fallbackHosts = tempFallbackHosts == null ? new String[] {} : tempFallbackHosts.clone(); @@ -77,36 +79,22 @@ public class Hosts { fallbackRetryTimeout = options.fallbackRetryTimeout; } - /** - * set primary hostname - */ - private void setPrimaryHost(String primaryHost) { - this.primaryHost = primaryHost; - primaryHostIsDefault = primaryHost.equalsIgnoreCase(defaultHost); - } - /** * set preferred hostname, which might not be the primary */ - public void setPreferredHost(String prefHost, boolean temporary) { - if(prefHost.equals(this.prefHost)) { + public synchronized void setPreferredHost(final String prefHost, final boolean temporary) { + if (preferred.isHost(prefHost)) { /* a successful request against a fallback; don't update the expiry time */ return; } - if(prefHost.equals(this.primaryHost)) { + if(prefHost.equals(primaryHost)) { /* a successful request against the primary host; reset */ - clearPreferredHost(); + preferred.clear(); } else { - this.prefHost = prefHost; - this.prefHostExpiry = temporary ? System.currentTimeMillis() + fallbackRetryTimeout : 0; + preferred.setHost(prefHost, temporary ? System.currentTimeMillis() + fallbackRetryTimeout : 0); } } - private void clearPreferredHost() { - this.prefHost = null; - this.prefHostExpiry = 0; - } - /** * Get primary host name */ @@ -117,18 +105,9 @@ public class Hosts { /** * Get preferred host name (taking into account any affinity to a fallback: see RSC15f) */ - public String getPreferredHost() { - checkPreferredHostExpiry(); - return (prefHost == null) ? primaryHost : prefHost; - } - - private String checkPreferredHostExpiry() { - /* reset if expired */ - if(prefHostExpiry > 0 && prefHostExpiry <= System.currentTimeMillis()) { - prefHostExpiry = 0; - prefHost = null; - } - return prefHost; + public synchronized String getPreferredHost() { + final String host = preferred.getHostOrClearIfExpired(); + return (host == null) ? primaryHost : host; } /** @@ -138,7 +117,7 @@ public class Hosts { * @return Successor host that can be used as a fallback. * null, if there is no successor fallback available. */ - public String getFallback(String lastHost) { + public synchronized String getFallback(String lastHost) { if (fallbackHosts == null) return null; int idx; @@ -149,9 +128,9 @@ public class Hosts { if (!primaryHostIsDefault && !fallbackHostsUseDefault && fallbackHostsIsDefault) return null; idx = 0; - } else if(lastHost.equals(checkPreferredHostExpiry())) { + } else if(lastHost.equals(preferred.getHostOrClearIfExpired())) { /* RSC15f: there was a failure on an unexpired, cached fallback; so try again using the primary */ - clearPreferredHost(); + preferred.clear(); return primaryHost; } else { /* Onto next fallback. */ @@ -167,13 +146,43 @@ public class Hosts { return fallbackHosts[idx]; } - public int fallbackHostsRemaining(String candidateHost) { + public synchronized int fallbackHostsRemaining(String candidateHost) { if(fallbackHosts == null) { return 0; } - if(candidateHost.equals(primaryHost) || candidateHost.equals(prefHost)) { + if(candidateHost.equals(primaryHost) || candidateHost.equals(preferred.getHost())) { return fallbackHosts.length; } return fallbackHosts.length - Arrays.asList(fallbackHosts).indexOf(candidateHost) - 1; } + + private static class Preferred { + private String host; + private long expiry; + + public void clear() { + host = null; + expiry = 0; + } + + public boolean isHost(final String host) { + return (this.host == null) ? (host == null) : this.host.equals(host); + } + + public void setHost(final String host, final long expiry) { + this.host = host; + this.expiry = expiry; + } + + public String getHostOrClearIfExpired() { + if(expiry > 0 && expiry <= System.currentTimeMillis()) { + clear(); // expired, so reset + } + return host; + } + + public String getHost() { + return host; + } + } }
['lib/src/main/java/io/ably/lib/transport/Hosts.java']
{'.java': 1}
1
1
0
0
1
621,507
121,572
16,762
99
3,963
769
95
1
409
60
95
6
2
0
2021-03-02T20:19:22
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
800
ably/ably-java/928/925
ably
ably-java
https://github.com/ably/ably-java/issues/925
https://github.com/ably/ably-java/pull/928
https://github.com/ably/ably-java/pull/928
1
fixes
Long-lived connections are immediately transitioned to `SUSPENDED` after disconnection
Relates to spec: - `DF1a` - `RTN14d` - `RTN15g` The default `connectionStateTtl` value (how long the connection is persisted on the Ably servers) is 120 seconds. This means that after 120 seconds of being `DISCONNECTED`, the connection state should transition to `SUSPENDED`. We maintain a timer (`ConnectionManager.suspendTime`) in `ably-java` that represents the time at which suspension should occur. This is checked whenever: - A `CONNECTING` state times out - The transport is unavailable If the time is not exceeded, the state is transitioned to `DISCONNECTED`. If it is exceeded, then the state becomes `SUSPENDED`. The `suspendTime` is reset (to `now + connetionStateTtl`) only: - On `ConnectionManager` initialisation - On successful connection - When a `DISCONNECTED` state is enacted, the previous state was `CONNECTED` and immediate retries are not suppressed. If the only thing a connection has done is successfully connect... and transport becomes unavailable (via connection rebalancing, internet issues etc)... and we've been connected for >`connectionStateTtl`... then `ConnectionManager.onTransportUnavailable` will check the timer, see that it has passed, and immediately suspend the connection. The correct behaviour here is to enter a `DISCONNECTED` state and immediately retry connections, only suspending at `disconnectTime + connectionStateTtl`.
ffb48cb1da7e47ced6277916b497ca59ed2d9f74
37cf4b7e72ff0f06d46057909521eb70ecf92c18
https://github.com/ably/ably-java/compare/ffb48cb1da7e47ced6277916b497ca59ed2d9f74...37cf4b7e72ff0f06d46057909521eb70ecf92c18
diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index 09ab6505..f326382c 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -309,10 +309,13 @@ public class ConnectionManager implements ConnectListener { void enact(StateIndication stateIndication, ConnectionStateChange change) { super.enact(stateIndication, change); clearTransport(); + + // If we were connected, immediately retry if(change.previous == ConnectionState.connected) { setSuspendTime(); - /* we were connected, so retry immediately */ - if(!suppressRetry) { + + if (!suppressRetry) { + Log.v(TAG, "Was previously connected, retrying immediately"); requestState(ConnectionState.connecting); } } @@ -1253,7 +1256,6 @@ public class ConnectionManager implements ConnectListener { return; } /* indicated connected currentState */ - setSuspendTime(); final StateIndication stateIndication = new StateIndication(ConnectionState.connected, error, null, null, reattachOnResumeFailure); requestState(stateIndication); @@ -1459,12 +1461,18 @@ public class ConnectionManager implements ConnectListener { @Override public synchronized void onTransportUnavailable(ITransport transport, ErrorInfo reason) { + Log.v(TAG, "onTransportUnavailable()"); if (this.transport != transport) { /* This is from a transport that we have already abandoned. */ Log.v(TAG, "onTransportUnavailable: ignoring disconnection event from superseded transport"); return; } + // If we're currently connected, start the suspend timer + if (currentState.state == ConnectionState.connected) { + setSuspendTime(); + } + /* if this is a failure of a pending connection attempt, decide whether or not to attempt a fallback host */ StateIndication fallbackAttempt = checkFallback(reason); if(fallbackAttempt != null) { diff --git a/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java b/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java index 602b9d4f..2182f537 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java @@ -20,14 +20,17 @@ import io.ably.lib.test.util.MockWebsocketFactory; import io.ably.lib.transport.ConnectionManager; import io.ably.lib.transport.Defaults; import io.ably.lib.transport.Hosts; +import io.ably.lib.transport.ITransport; import io.ably.lib.types.AblyException; import io.ably.lib.types.ClientOptions; +import io.ably.lib.types.ErrorInfo; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.mockito.Mockito; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -731,4 +734,81 @@ public class ConnectionManagerTest extends ParameterizedTest { assertEquals("Suspended channel histories do not match", suspendedChannelHistory, expectedSuspendedChannelHistory); } } + + /** + * <p> + * Verifies that the {@code ConnectionManager} enters the disconnected state and sets the suspend timer + * upon unavailable transport. + * </p> + * <p> + * Spec: RTN15g + * </p> + */ + @Test + public void connection_manager_enters_disconnected_state_on_transport_failure() throws AblyException, NoSuchFieldException, IllegalAccessException { + ClientOptions opts = createOptions(testVars.keys[0].keyStr); + try(AblyRealtime ably = new AblyRealtime(opts)) { + ConnectionManager connectionManager = ably.connection.connectionManager; + connectionManager.connect(); + new Helpers.ConnectionManagerWaiter(ably.connection.connectionManager).waitFor(ConnectionState.connected); + + // Here, we "fake" being online for 2 minutes - the suspendTime is set by onConnected and the default is 2 minutes + Field suspendTimeField = connectionManager.getClass().getDeclaredField("suspendTime"); + suspendTimeField.setAccessible(true); + suspendTimeField.set(connectionManager, System.currentTimeMillis() - 10); + + // We also have to grab the "real" transport to pass the superseded test + Field transportField = connectionManager.getClass().getDeclaredField("transport"); + transportField.setAccessible(true); + + connectionManager.onTransportUnavailable((ITransport) transportField.get(connectionManager), new ErrorInfo()); + new Helpers.ConnectionManagerWaiter(connectionManager).waitFor(ConnectionState.disconnected); + + assertTrue((long) suspendTimeField.get(connectionManager) >= System.currentTimeMillis()); + + connectionManager.close(); + } + } + + /** + * <p> + * Verifies that the {@code ConnectionManager} enters the suspended state if the transport is unavailable and the + * timer has been exceeded. + * </p> + * <p> + * Spec: RTN15g, RTN14d + * </p> + */ + @Test + public void connection_manager_enters_suspended_state_on_transport_failure_after_already_being_disconnected_for_2_minutes() throws AblyException, NoSuchFieldException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException { + ClientOptions opts = createOptions(testVars.keys[0].keyStr); + try(AblyRealtime ably = new AblyRealtime(opts)) { + ConnectionManager connectionManager = ably.connection.connectionManager; + connectionManager.connect(); + new Helpers.ConnectionManagerWaiter(ably.connection.connectionManager).waitFor(ConnectionState.connected); + + // Here, we "fake" being disconnected beyond the suspend timer + Class<?> connectionManagerClass = Class.forName("io.ably.lib.transport.ConnectionManager"); + Class<?> disconnectedState = Class.forName("io.ably.lib.transport.ConnectionManager$Disconnected"); + Constructor<?> disconnectedStateCtor = disconnectedState.getDeclaredConstructor(connectionManagerClass); + disconnectedStateCtor.setAccessible(true); + Field connectionStateField = connectionManager.getClass().getDeclaredField("currentState"); + connectionStateField.setAccessible(true); + connectionStateField.set(connectionManager, disconnectedStateCtor.newInstance(connectionManager)); + + Field suspendTimeField = connectionManager.getClass().getDeclaredField("suspendTime"); + suspendTimeField.setAccessible(true); + suspendTimeField.set(connectionManager, System.currentTimeMillis() - 5000); + + // We also have to grab the "real" transport to pass the superseded test + Field transportField = connectionManager.getClass().getDeclaredField("transport"); + transportField.setAccessible(true); + + connectionManager.onTransportUnavailable((ITransport) transportField.get(connectionManager), new ErrorInfo()); + + new Helpers.ConnectionManagerWaiter(connectionManager).waitFor(ConnectionState.suspended); + + connectionManager.close(); + } + } }
['lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java', 'lib/src/main/java/io/ably/lib/transport/ConnectionManager.java']
{'.java': 2}
2
2
0
0
2
760,689
152,270
19,920
109
532
97
14
1
1,401
192
321
24
0
0
2023-03-17T12:53:32
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
799
ably/ably-java/934/935
ably
ably-java
https://github.com/ably/ably-java/issues/935
https://github.com/ably/ably-java/pull/934
https://github.com/ably/ably-java/pull/934
1
fixes
Realtime with authUrl with token in connection string fails to connect
See failing https://github.com/ably/ably-java/actions/runs/4882297437/jobs/8712194485 When authUrl contains token in query string, realtime does not connect
deec71a40affe522c59160b9278334768b928d90
1a153cb5b1b133f3480f9f439496576941330f65
https://github.com/ably/ably-java/compare/deec71a40affe522c59160b9278334768b928d90...1a153cb5b1b133f3480f9f439496576941330f65
diff --git a/lib/src/main/java/io/ably/lib/http/HttpUtils.java b/lib/src/main/java/io/ably/lib/http/HttpUtils.java index 02889449..7852f375 100644 --- a/lib/src/main/java/io/ably/lib/http/HttpUtils.java +++ b/lib/src/main/java/io/ably/lib/http/HttpUtils.java @@ -4,6 +4,8 @@ import com.google.gson.JsonElement; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; @@ -78,6 +80,28 @@ public class HttpUtils { } } + /** + * Removes querystring from given url string and returns the url string without query string(s) + * @param url Url string that needs querystring part removed + * + * @return Url string with query string part removed, if existed in the first place + * + * @throws AblyException built from URISyntaxException if java.net.URI fails to build + * the URI given url + * */ + public static String urlWithQueryStringRemoved(String url) throws AblyException { + try { + final URI uri = new URI(url); + return new URI(uri.getScheme(), + uri.getAuthority(), + uri.getPath(), + null, // Ignore the query part of the input url + uri.getFragment()).toString(); + } catch (URISyntaxException e) { + throw AblyException.fromThrowable(e); + } + } + public static Map<String, Param> decodeParams(String query) { Map<String, Param> params = new HashMap<String, Param>(); String[] pairs = query.split("&"); diff --git a/lib/src/main/java/io/ably/lib/rest/Auth.java b/lib/src/main/java/io/ably/lib/rest/Auth.java index dc3fa9fc..7a8d0a5d 100644 --- a/lib/src/main/java/io/ably/lib/rest/Auth.java +++ b/lib/src/main/java/io/ably/lib/rest/Auth.java @@ -805,6 +805,7 @@ public class Auth { /* append all relevant params to token params */ Map<String, Param> urlParams = null; URL authUrl = HttpUtils.parseUrl(authOptions.authUrl); + final String urlWithoutQueryParams = HttpUtils.urlWithQueryStringRemoved(authOptions.authUrl); String queryString = authUrl.getQuery(); if(queryString != null && !queryString.isEmpty()) { urlParams = HttpUtils.decodeParams(queryString); @@ -820,10 +821,12 @@ public class Auth { } } if (HttpConstants.Methods.POST.equals(tokenOptions.authMethod)) { - authUrlResponse = HttpHelpers.postUri(ably.httpCore, tokenOptions.authUrl, tokenOptions.authHeaders, HttpUtils.flattenParams(urlParams), HttpUtils.flattenParams(tokenParams), responseHandler); + authUrlResponse = HttpHelpers.postUri(ably.httpCore, urlWithoutQueryParams, tokenOptions.authHeaders, + HttpUtils.flattenParams(urlParams), HttpUtils.flattenParams(tokenParams), responseHandler); } else { Map<String, Param> requestParams = (urlParams != null) ? HttpUtils.mergeParams(urlParams, tokenParams) : tokenParams; - authUrlResponse = HttpHelpers.getUri(ably.httpCore, tokenOptions.authUrl, tokenOptions.authHeaders, HttpUtils.flattenParams(requestParams), responseHandler); + authUrlResponse = HttpHelpers.getUri(ably.httpCore, urlWithoutQueryParams, tokenOptions.authHeaders, + HttpUtils.flattenParams(requestParams), responseHandler); } } catch(AblyException e) { throw AblyException.fromErrorInfo(e, new ErrorInfo("authUrl failed with an exception", e.errorInfo.statusCode, 80019)); diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java index 7b2bab0a..c8950eed 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java @@ -34,6 +34,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.net.URLEncoder; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -97,6 +98,40 @@ public class RealtimeAuthTest extends ParameterizedTest { } } + /** + * Given authUrl in the form of query string,ensure that realtime will connect without any problem + */ + @Test + public void realtime_connection_with_auth_url_in_query_string_connects() { + try { + /* init ably for token */ + ClientOptions optsForToken = createOptions(testVars.keys[0].keyStr); + final AblyRest ablyForToken = new AblyRest(optsForToken); + + /* get token */ + Auth.TokenParams tokenParams = new Auth.TokenParams(); + Auth.TokenDetails tokenDetails = ablyForToken.auth.requestToken(tokenParams, null); + assertNotNull("Expected token value", tokenDetails.token); + + /* create ably realtime with tokenDetails and clientId */ + ClientOptions opts = createOptions(); + opts.authUrl = "https://echo.ably.io/?body="+ URLEncoder.encode(tokenDetails.token); + opts.useTokenAuth = true; + AblyRealtime ablyRealtime = new AblyRealtime(opts); + System.out.println("done create ably"); + + /* wait for connected state */ + Helpers.ConnectionWaiter connectionWaiter = new Helpers.ConnectionWaiter(ablyRealtime.connection); + connectionWaiter.waitFor(ConnectionState.connected); + assertEquals("Verify connected state is reached", ConnectionState.connected, ablyRealtime.connection.state); + + ablyRealtime.close(); + } catch (AblyException e) { + e.printStackTrace(); + fail(); + } + } + /** * RSA4d: If a request by a realtime client to an authUrl results in an HTTP 403 response, * or any of an authUrl request, an authCallback, or a request to Ably to exchange
['lib/src/main/java/io/ably/lib/rest/Auth.java', 'lib/src/main/java/io/ably/lib/http/HttpUtils.java', 'lib/src/test/java/io/ably/lib/test/realtime/RealtimeAuthTest.java']
{'.java': 3}
3
3
0
0
3
760,958
152,319
19,928
109
1,903
359
31
2
159
14
40
3
1
0
2023-05-04T11:35:31
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
798
ably/ably-java/939/932
ably
ably-java
https://github.com/ably/ably-java/issues/932
https://github.com/ably/ably-java/pull/939
https://github.com/ably/ably-java/pull/939
1
fixes
RTN23a: Transport not disconnecting after TTL passed
Per RTN23a, a transport should be disconnected after receiving no activity for `maxIdleInterval` + `realtimeRequestTimeout`. This is implemented in `checkActivity()`: https://github.com/ably/ably-java/blob/deec71a40affe522c59160b9278334768b928d90/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java#L326 However, the timer that is set cannot do anything because it calls `checkActivity` again, which checks if a timer is set, which it is, so it does nothing (and starts no future timers). This means on a network drop event, the library will wait over a minute to begin the process of trying fallback hosts etc.
170e21f045b9a452db953b97607d2587ce5bb9aa
13943faa5070796ba440c9dcd43f9ec732f2251c
https://github.com/ably/ably-java/compare/170e21f045b9a452db953b97607d2587ce5bb9aa...13943faa5070796ba440c9dcd43f9ec732f2251c
diff --git a/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java b/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java index 85284b17..62a1d4b9 100644 --- a/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java +++ b/lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java @@ -306,36 +306,34 @@ public class WebSocketTransport implements ITransport { } private synchronized void checkActivity() { - long timeout = connectionManager.maxIdleInterval; + long timeout = getActivityTimeout(); if (timeout == 0) { Log.v(TAG, "checkActivity: infinite timeout"); return; } - if(activityTimerTask != null) { - /* timer already running */ + + // Check if timer already running + if (activityTimerTask != null) { return; } - timeout += connectionManager.ably.options.realtimeRequestTimeout; - long now = System.currentTimeMillis(); - long next = lastActivityTime + timeout; - if (now < next) { - /* We have not reached maxIdleInterval+realtimeRequestTimeout - * of inactivity. Schedule a new timer for that long after the - * last activity time. */ - Log.v(TAG, "checkActivity: ok"); + + // Start the activity timer task + startActivityTimer(timeout + 100); + } + + + private synchronized void startActivityTimer(long timeout) + { + if (activityTimerTask == null) { schedule((activityTimerTask = new TimerTask() { public void run() { try { - checkActivity(); + onActivityTimerExpiry(); } catch(Throwable t) { Log.e(TAG, "Unexpected exception in activity timer handler", t); } } - }), next - now); - } else { - /* Timeout has been reached. Close the connection. */ - Log.e(TAG, "No activity for " + timeout + "ms, closing connection"); - closeConnection(CloseFrame.ABNORMAL_CLOSE, "timed out"); + }), timeout); } } @@ -349,6 +347,29 @@ public class WebSocketTransport implements ITransport { } } + private synchronized void onActivityTimerExpiry() + { + activityTimerTask = null; + long timeSinceLastActivity = System.currentTimeMillis() - lastActivityTime; + long timeRemaining = getActivityTimeout() - timeSinceLastActivity; + + // If we have no time remaining, then close the connection + if (timeRemaining <= 0) { + Log.e(TAG, "No activity for " + getActivityTimeout() + "ms, closing connection"); + closeConnection(CloseFrame.ABNORMAL_CLOSE, "timed out"); + return; + } + + // Otherwise, we've had some activity, restart the timer for the next timeout + Log.v(TAG, "onActivityTimerExpiry: ok"); + startActivityTimer(timeRemaining + 100); + } + + private long getActivityTimeout() + { + return connectionManager.maxIdleInterval + connectionManager.ably.options.realtimeRequestTimeout; + } + /*************************** * WsClient private members ***************************/ diff --git a/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java b/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java index 2182f537..e7f7c133 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java @@ -553,6 +553,35 @@ public class ConnectionManagerTest extends ParameterizedTest { } } + /** + * RTN23 + */ + @Test + public void connection_is_closed_after_max_idle_interval() throws AblyException { + ClientOptions opts = createOptions(testVars.keys[0].keyStr); + opts.realtimeRequestTimeout = 2000; + try(AblyRealtime ably = new AblyRealtime(opts)) { + final long newIdleInterval = 500L; + + // When we connect, we set the max idle interval to be very small + ably.connection.on(ConnectionEvent.connected, state -> { + try { + Field maxIdleField = ably.connection.connectionManager.getClass().getDeclaredField("maxIdleInterval"); + maxIdleField.setAccessible(true); + maxIdleField.setLong(ably.connection.connectionManager, newIdleInterval); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Unexpected exception in checking connectionStateTtl"); + } + }); + + // The original max idle interval we receive from the server is 15s. + // We should wait for this, plus a tiny bit extra (as we set the new idle interval to be very low + // after connecting) to make sure that the connection is disconnected + ConnectionWaiter connectionWaiter = new ConnectionWaiter(ably.connection); + assertTrue(connectionWaiter.waitFor(ConnectionState.disconnected, 1, 25000)); + } + } + /** * RTN15g1, RTN15g2. Connect, disconnect, reconnect after (ttl + idle interval) period has passed, * check that the connection is a new one; @@ -683,13 +712,13 @@ public class ConnectionManagerTest extends ParameterizedTest { }); final Channel suspendedChannel = ably.channels.get("test-reattach-suspended-after-ttl" + testParams.name); suspendedChannel.state = ChannelState.suspended; - ChannelWaiter suspendedChannelWaiter = new Helpers.ChannelWaiter(suspendedChannel); suspendedChannel.on(new ChannelStateListener() { @Override public void onChannelStateChanged(ChannelStateChange stateChange) { suspendedChannelHistory.add(stateChange.current.name()); } }); + ChannelWaiter suspendedChannelWaiter = new Helpers.ChannelWaiter(suspendedChannel); /* attach first channel and wait for it to be attached */ attachedChannel.attach();
['lib/src/main/java/io/ably/lib/transport/WebSocketTransport.java', 'lib/src/test/java/io/ably/lib/test/realtime/ConnectionManagerTest.java']
{'.java': 2}
2
2
0
0
2
762,050
152,527
19,955
109
2,415
435
55
1
629
77
152
5
1
0
2023-05-15T16:31:55
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
797
ably/ably-java/951/950
ably
ably-java
https://github.com/ably/ably-java/issues/950
https://github.com/ably/ably-java/pull/951
https://github.com/ably/ably-java/pull/951
1
fixes
Connection manager switches to fallback hosts on close
https://github.com/ably/ably-java/blob/bbbcb4d1ee6e9bc7a8b98a2b4990259030e50725/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java#L1393 When the transport becomes unavailable due to a number of reasons (including a clean close, or an abnormal close) the connection immediately jumps to a fallback host if the internet is up. This is because the check for whether to use fallback includes checking for a `pendingConnect`, as well as the error reason being "server related". The `pendingConnect` is set when the connecting state is enacted, but not cleared apart from `checkFallback` if it's decided not to use a fallback. This means any time the connection closes for a number of reasons, then the connection will immediately fallback and not resume.
bbbcb4d1ee6e9bc7a8b98a2b4990259030e50725
f944ca164be68f1b82fdc41bd15962b8613b4355
https://github.com/ably/ably-java/compare/bbbcb4d1ee6e9bc7a8b98a2b4990259030e50725...f944ca164be68f1b82fdc41bd15962b8613b4355
diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index 69f91299..cb442abe 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -265,6 +265,12 @@ public class ConnectionManager implements ConnectListener { void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) { channel.setConnected(stateIndication.reattachOnResumeFailure); } + + @Override + void enact(StateIndication stateIndication, ConnectionStateChange change) { + super.enact(stateIndication, change); + pendingConnect = null; + } } /**************************************************
['lib/src/main/java/io/ably/lib/transport/ConnectionManager.java']
{'.java': 1}
1
1
0
0
1
762,308
152,581
19,972
109
203
38
6
1
771
102
176
7
1
0
2023-05-31T15:24:52
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
796
ably/ably-java/960/958
ably
ably-java
https://github.com/ably/ably-java/issues/958
https://github.com/ably/ably-java/pull/960
https://github.com/ably/ably-java/pull/960
1
fixes
Error code for message decoding failure
At the moment, https://github.com/ably/ably-java/blob/main/lib/src/main/java/io/ably/lib/types/MessageDecodeException.java uses code 91200 for decoding failure. This code is undocumented, and we should ideally be using 40013 instead.
c3f438a8b1992850f68a16f9e7517a5dc205727e
7122c951a610860283eccf502e41781f76bbc28f
https://github.com/ably/ably-java/compare/c3f438a8b1992850f68a16f9e7517a5dc205727e...7122c951a610860283eccf502e41781f76bbc28f
diff --git a/lib/src/main/java/io/ably/lib/types/MessageDecodeException.java b/lib/src/main/java/io/ably/lib/types/MessageDecodeException.java index 6d89d63a..3c404320 100644 --- a/lib/src/main/java/io/ably/lib/types/MessageDecodeException.java +++ b/lib/src/main/java/io/ably/lib/types/MessageDecodeException.java @@ -13,7 +13,7 @@ public class MessageDecodeException extends AblyException { public static MessageDecodeException fromDescription(String description) { return new MessageDecodeException( new Exception(description), - new ErrorInfo(description, 91200)); + new ErrorInfo(description, 40013)); } public static MessageDecodeException fromThrowableAndErrorInfo(Throwable e, ErrorInfo errorInfo) {
['lib/src/main/java/io/ably/lib/types/MessageDecodeException.java']
{'.java': 1}
1
1
0
0
1
762,506
152,618
19,978
109
97
20
2
1
233
22
54
1
1
0
2023-07-03T16:44:41
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
795
ably/ably-java/961/959
ably
ably-java
https://github.com/ably/ably-java/issues/959
https://github.com/ably/ably-java/pull/961
https://github.com/ably/ably-java/pull/961
1
fixes
Error code for channel attachment timed out
In https://github.com/ably/ably-java/blob/c3f438a8b1992850f68a16f9e7517a5dc205727e/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java#L482 we use code 91200 for a timeout whilst attaching to the channel prior to suspension. This code is not documented anywhere. The error code in question was removed somewhere around specification version 0.9, and should be removed in ably-java as well.
c3f438a8b1992850f68a16f9e7517a5dc205727e
483970922736f183142fa6ff27c8c40cf0eccd55
https://github.com/ably/ably-java/compare/c3f438a8b1992850f68a16f9e7517a5dc205727e...483970922736f183142fa6ff27c8c40cf0eccd55
diff --git a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java index fb28d966..453ee669 100644 --- a/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java +++ b/lib/src/main/java/io/ably/lib/realtime/ChannelBase.java @@ -479,7 +479,7 @@ public abstract class ChannelBase extends EventEmitter<ChannelEvent, ChannelStat } attachTimer = null; if(state == ChannelState.attaching) { - setSuspended(new ErrorInfo(errorMessage, 91200), true); + setSuspended(new ErrorInfo(errorMessage, 90007), true); reattachAfterTimeout(); } } diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java index 46ddaaac..181dbc49 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java @@ -1808,7 +1808,7 @@ public class RealtimeChannelTest extends ParameterizedTest { /* Should get to suspended soon because send() is blocked */ ErrorInfo suspendReason = channelWaiter.waitFor(ChannelState.suspended); - assertEquals("Verify the suspended event contains the detach reason", 91200, suspendReason.code); + assertEquals("Verify the suspended event contains the detach reason", 90007, suspendReason.code); /* Unblock send(), and expect a transition to attached */ mockTransport.allowSend();
['lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java', 'lib/src/main/java/io/ably/lib/realtime/ChannelBase.java']
{'.java': 2}
2
2
0
0
2
762,506
152,618
19,978
109
177
30
2
1
396
43
106
3
1
0
2023-07-03T16:59:04
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
815
ably/ably-java/655/649
ably
ably-java
https://github.com/ably/ably-java/issues/649
https://github.com/ably/ably-java/pull/655
https://github.com/ably/ably-java/pull/655
1
fixes
AblyBase.InternalChannels is not thread-safe
in the AblyBase class, the InternalChannels class holds a map of channels, which gets auto-populated on get. however, the underlying data structure is a simple HashMap (which is not thread-safe). when you do a get for a channel which does not currently exist in the map, a new one is created and then inserted into the underlying map. this has three problems. 1. it isn't atomic, i.e. two different threads making this call for a new channel the first time could end up with two different instances of Channel. 1. the put() call on the underlying HashMap isn't thread safe, risking corrupting the underlying map. 1. modifying the options of the channel before returning it is not safe if the channel is being used by multiple threads concurrently. note that 1,2 can be fairly simply and efficiently solved by using a ConcurrentHashMap and the computeIfAbsent method. also note that AblyRealtime.InternalChannels has two of these problems as well (it does use a ConcurrentHashMap so 2 isn't an issue). ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-650) by [Unito](https://www.unito.io)
fcb4a1a7f7c15264236298083e7ef73a5bbde690
e318ea3807e77705095c02cfe5652486db5f39f8
https://github.com/ably/ably-java/compare/fcb4a1a7f7c15264236298083e7ef73a5bbde690...e318ea3807e77705095c02cfe5652486db5f39f8
diff --git a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java index a97205cb..0ac891ea 100644 --- a/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java +++ b/lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java @@ -2,7 +2,6 @@ package io.ably.lib.realtime; import java.util.Iterator; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import io.ably.lib.rest.AblyRest; import io.ably.lib.transport.ConnectionManager; @@ -130,10 +129,6 @@ public class AblyRealtime extends AblyRest implements AutoCloseable { } private class InternalChannels extends InternalMap<String, Channel> implements Channels, ConnectionManager.Channels { - private InternalChannels() { - super(new ConcurrentHashMap<String, Channel>()); - } - /** * Get the named channel; if it does not already exist, * create it with default options. @@ -148,21 +143,24 @@ public class AblyRealtime extends AblyRest implements AutoCloseable { } @Override - public Channel get(String channelName, ChannelOptions channelOptions) throws AblyException { - Channel channel = map.get(channelName); - if (channel != null) { + public Channel get(final String channelName, final ChannelOptions channelOptions) throws AblyException { + // We're not using computeIfAbsent because that requires Java 1.8. + // Hence there's the slight inefficiency of creating newChannel when it may not be + // needed because there is an existingChannel. + final Channel newChannel = new Channel(AblyRealtime.this, channelName, channelOptions); + final Channel existingChannel = map.putIfAbsent(channelName, newChannel); + + if (existingChannel != null) { if (channelOptions != null) { - if (channel.shouldReattachToSetOptions(channelOptions)) { + if (existingChannel.shouldReattachToSetOptions(channelOptions)) { throw AblyException.fromErrorInfo(new ErrorInfo("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use Channel.setOptions() instead.", 40000, 400)); } - channel.setOptions(channelOptions); + existingChannel.setOptions(channelOptions); } - return channel; + return existingChannel; } - channel = new Channel(AblyRealtime.this, channelName, channelOptions); - map.put(channelName, channel); - return channel; + return newChannel; } @Override diff --git a/lib/src/main/java/io/ably/lib/rest/AblyBase.java b/lib/src/main/java/io/ably/lib/rest/AblyBase.java index d5be54d0..72c4d039 100644 --- a/lib/src/main/java/io/ably/lib/rest/AblyBase.java +++ b/lib/src/main/java/io/ably/lib/rest/AblyBase.java @@ -1,7 +1,5 @@ package io.ably.lib.rest; -import java.util.HashMap; - import io.ably.annotation.Experimental; import io.ably.lib.http.AsyncHttpScheduler; import io.ably.lib.http.Http; @@ -105,10 +103,6 @@ public abstract class AblyBase { } private class InternalChannels extends InternalMap<String, Channel> implements Channels { - InternalChannels() { - super(new HashMap<String, Channel>()); - } - @Override public Channel get(String channelName) { try { diff --git a/lib/src/main/java/io/ably/lib/util/InternalMap.java b/lib/src/main/java/io/ably/lib/util/InternalMap.java index 66d4c72c..d732e9b4 100644 --- a/lib/src/main/java/io/ably/lib/util/InternalMap.java +++ b/lib/src/main/java/io/ably/lib/util/InternalMap.java @@ -1,16 +1,23 @@ package io.ably.lib.util; -import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import io.ably.lib.types.ReadOnlyMap; +/** + * A map implemented using a {@link ConcurrentHashMap}. This class is a base class for other classes + * which are designed to be internal to the library, specifically as regards access to the map + * field. + * + * This class exposes a {@link ReadOnlyMap} which is safe to be exposed in our public API. + * + * @param <K> Key type. + * @param <V> Value type. + */ public abstract class InternalMap<K, V> implements ReadOnlyMap<K, V> { - protected final Map<K, V> map; - - public InternalMap(final Map<K, V> map) { - this.map = map; - } + protected final ConcurrentMap<K, V> map = new ConcurrentHashMap<>(); @Override public final boolean containsKey(final Object key) {
['lib/src/main/java/io/ably/lib/util/InternalMap.java', 'lib/src/main/java/io/ably/lib/realtime/AblyRealtime.java', 'lib/src/main/java/io/ably/lib/rest/AblyBase.java']
{'.java': 3}
3
3
0
0
3
621,507
121,572
16,762
99
2,285
428
51
3
1,131
176
250
15
2
0
2021-03-02T17:18:40
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
814
ably/ably-java/656/654
ably
ably-java
https://github.com/ably/ably-java/issues/654
https://github.com/ably/ably-java/pull/656
https://github.com/ably/ably-java/pull/656
1
fixes
Crypto.getRandomMessageId isn't working as intended
the value being generated by this method is returning the toString result of a char[], which probably is not the intended "random" value. ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-659) by [Unito](https://www.unito.io)
fcb4a1a7f7c15264236298083e7ef73a5bbde690
e497bdac19519962e71eadc30c1ade9da5e364e0
https://github.com/ably/ably-java/compare/fcb4a1a7f7c15264236298083e7ef73a5bbde690...e497bdac19519962e71eadc30c1ade9da5e364e0
diff --git a/lib/src/main/java/io/ably/lib/util/Crypto.java b/lib/src/main/java/io/ably/lib/util/Crypto.java index b20915b0..56ea62fb 100644 --- a/lib/src/main/java/io/ably/lib/util/Crypto.java +++ b/lib/src/main/java/io/ably/lib/util/Crypto.java @@ -321,7 +321,7 @@ public class Crypto { public static String getRandomMessageId() { byte[] entropy = new byte[9]; secureRandom.nextBytes(entropy); - return Base64Coder.encode(entropy).toString(); + return Base64Coder.encodeToString(entropy); } /** diff --git a/lib/src/test/java/io/ably/lib/util/CryptoTest.java b/lib/src/test/java/io/ably/lib/util/CryptoTest.java index a9fec56d..f89541be 100644 --- a/lib/src/test/java/io/ably/lib/util/CryptoTest.java +++ b/lib/src/test/java/io/ably/lib/util/CryptoTest.java @@ -199,4 +199,10 @@ public class CryptoTest { return out.toByteArray(); } + + @Test + public void getRandomId() { + String randomId = Crypto.getRandomMessageId(); + assertEquals(12, randomId.length()); + } }
['lib/src/main/java/io/ably/lib/util/Crypto.java', 'lib/src/test/java/io/ably/lib/util/CryptoTest.java']
{'.java': 2}
2
2
0
0
2
621,507
121,572
16,762
99
108
21
2
1
261
32
63
6
2
0
2021-03-02T17:21:07
55
Java
{'Java': 2119819, 'Shell': 2346, 'HTML': 1161, 'Groovy': 753, 'JavaScript': 178}
Apache License 2.0
8,603
ist-dresden/composum-nodes/77/73
ist-dresden
composum-nodes
https://github.com/ist-dresden/composum-nodes/issues/73
https://github.com/ist-dresden/composum-nodes/pull/77
https://github.com/ist-dresden/composum-nodes/pull/77
1
fix
Package Uploading is not respecting "force" and always forces an upload
Based on CRX Package Manager forcing an upload means that it will replace an already uploaded package and it not forced then the upload will fail. As far as I understand the code the force tag is actually migrating to Package Zip File strict which is does seem wrong. Anyhow it would be nice if Composum could act like CRX Package Manager or otherwise use a different name.
062e0b2eb6229906a4221c8da55d36647626516a
273808407f8d7bbcd73b92df825d0c5fab5e9243
https://github.com/ist-dresden/composum-nodes/compare/062e0b2eb6229906a4221c8da55d36647626516a...273808407f8d7bbcd73b92df825d0c5fab5e9243
diff --git a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java index e4c940428..2a6edd2f0 100644 --- a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java +++ b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java @@ -749,7 +749,7 @@ public class PackageServlet extends AbstractServiceServlet { RequestParameter file = parameters.getValue(AbstractServiceServlet.PARAM_FILE); if (file != null) { InputStream input = file.getInputStream(); - boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false); + boolean force = RequestUtil.getParameter(request, PARAM_FORCE, true); JcrPackageManager manager = PackageUtil.createPackageManager(request); JcrPackage jcrPackage = manager.upload(input, force);
['sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java']
{'.java': 1}
1
1
0
0
1
933,502
170,674
24,723
126
182
28
2
1
379
68
76
5
0
0
2017-04-25T19:01:51
54
JavaScript
{'JavaScript': 19206236, 'Java': 3257834, 'CSS': 536542, 'SCSS': 162416, 'Less': 78481, 'HTML': 51687, 'Shell': 13522, 'Groovy': 7195, 'XSLT': 451}
MIT License
8,605
ist-dresden/composum-nodes/75/73
ist-dresden
composum-nodes
https://github.com/ist-dresden/composum-nodes/issues/73
https://github.com/ist-dresden/composum-nodes/pull/75
https://github.com/ist-dresden/composum-nodes/pull/75
1
fixed
Package Uploading is not respecting "force" and always forces an upload
Based on CRX Package Manager forcing an upload means that it will replace an already uploaded package and it not forced then the upload will fail. As far as I understand the code the force tag is actually migrating to Package Zip File strict which is does seem wrong. Anyhow it would be nice if Composum could act like CRX Package Manager or otherwise use a different name.
a7268cb44a389f3ac79c81ba206db843e18c942f
2a94dd827a902d3436a3a5c63d8ac77a4abffb22
https://github.com/ist-dresden/composum-nodes/compare/a7268cb44a389f3ac79c81ba206db843e18c942f...2a94dd827a902d3436a3a5c63d8ac77a4abffb22
diff --git a/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java b/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java index 8e68c578b..1b2ea5d27 100644 --- a/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java +++ b/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java @@ -143,8 +143,8 @@ public class RequestUtil extends org.apache.sling.api.request.RequestUtil { public static Boolean getParameter(SlingHttpServletRequest request, String name, Boolean defaultValue) { Boolean result = null; String string = request.getParameter(name); - if (StringUtils.isNotBlank(string)) { - result = Boolean.parseBoolean(string); + if (string != null) { + result = StringUtils.isBlank(string) || name.equals(string) || Boolean.parseBoolean(string); } return result != null ? result : defaultValue; } diff --git a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java index c536daffb..e4c940428 100644 --- a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java +++ b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java @@ -479,7 +479,7 @@ public class PackageServlet extends AbstractServiceServlet { boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false); JcrPackageManager manager = PackageUtil.createPackageManager(request); - JcrPackage jcrPackage = manager.upload(input, true, force); + JcrPackage jcrPackage = manager.upload(input, force); JsonWriter writer = ResponseUtil.getJsonWriter(response); jsonAnswer(writer, "upload", "successful", manager, jcrPackage); @@ -752,7 +752,7 @@ public class PackageServlet extends AbstractServiceServlet { boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false); JcrPackageManager manager = PackageUtil.createPackageManager(request); - JcrPackage jcrPackage = manager.upload(input, true, force); + JcrPackage jcrPackage = manager.upload(input, force); installPackage(request, response, manager, jcrPackage);
['sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java', 'sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java']
{'.java': 2}
2
2
0
0
2
933,476
170,668
24,723
126
538
102
8
2
379
68
76
5
0
0
2017-04-25T13:36:28
54
JavaScript
{'JavaScript': 19206236, 'Java': 3257834, 'CSS': 536542, 'SCSS': 162416, 'Less': 78481, 'HTML': 51687, 'Shell': 13522, 'Groovy': 7195, 'XSLT': 451}
MIT License
8,606
ist-dresden/composum-nodes/74/73
ist-dresden
composum-nodes
https://github.com/ist-dresden/composum-nodes/issues/73
https://github.com/ist-dresden/composum-nodes/pull/74
https://github.com/ist-dresden/composum-nodes/pull/74
1
fixed
Package Uploading is not respecting "force" and always forces an upload
Based on CRX Package Manager forcing an upload means that it will replace an already uploaded package and it not forced then the upload will fail. As far as I understand the code the force tag is actually migrating to Package Zip File strict which is does seem wrong. Anyhow it would be nice if Composum could act like CRX Package Manager or otherwise use a different name.
46be78d0a946d2d0ee8afd38bf2b2f5cd0d1f08b
96ef9118addaded21b3f03e39cb2e7dd7ceea38d
https://github.com/ist-dresden/composum-nodes/compare/46be78d0a946d2d0ee8afd38bf2b2f5cd0d1f08b...96ef9118addaded21b3f03e39cb2e7dd7ceea38d
diff --git a/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java b/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java index 8e68c578b..1b2ea5d27 100644 --- a/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java +++ b/sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java @@ -143,8 +143,8 @@ public class RequestUtil extends org.apache.sling.api.request.RequestUtil { public static Boolean getParameter(SlingHttpServletRequest request, String name, Boolean defaultValue) { Boolean result = null; String string = request.getParameter(name); - if (StringUtils.isNotBlank(string)) { - result = Boolean.parseBoolean(string); + if (string != null) { + result = StringUtils.isBlank(string) || name.equals(string) || Boolean.parseBoolean(string); } return result != null ? result : defaultValue; } diff --git a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java index c536daffb..e4c940428 100644 --- a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java +++ b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java @@ -479,7 +479,7 @@ public class PackageServlet extends AbstractServiceServlet { boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false); JcrPackageManager manager = PackageUtil.createPackageManager(request); - JcrPackage jcrPackage = manager.upload(input, true, force); + JcrPackage jcrPackage = manager.upload(input, force); JsonWriter writer = ResponseUtil.getJsonWriter(response); jsonAnswer(writer, "upload", "successful", manager, jcrPackage); @@ -752,7 +752,7 @@ public class PackageServlet extends AbstractServiceServlet { boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false); JcrPackageManager manager = PackageUtil.createPackageManager(request); - JcrPackage jcrPackage = manager.upload(input, true, force); + JcrPackage jcrPackage = manager.upload(input, force); installPackage(request, response, manager, jcrPackage);
['sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java', 'sling/core/commons/src/main/java/com/composum/sling/core/util/RequestUtil.java']
{'.java': 2}
2
2
0
0
2
933,476
170,668
24,723
126
538
102
8
2
379
68
76
5
0
0
2017-04-24T15:43:38
54
JavaScript
{'JavaScript': 19206236, 'Java': 3257834, 'CSS': 536542, 'SCSS': 162416, 'Less': 78481, 'HTML': 51687, 'Shell': 13522, 'Groovy': 7195, 'XSLT': 451}
MIT License
8,604
ist-dresden/composum-nodes/76/73
ist-dresden
composum-nodes
https://github.com/ist-dresden/composum-nodes/issues/73
https://github.com/ist-dresden/composum-nodes/pull/76
https://github.com/ist-dresden/composum-nodes/pull/76
1
fix
Package Uploading is not respecting "force" and always forces an upload
Based on CRX Package Manager forcing an upload means that it will replace an already uploaded package and it not forced then the upload will fail. As far as I understand the code the force tag is actually migrating to Package Zip File strict which is does seem wrong. Anyhow it would be nice if Composum could act like CRX Package Manager or otherwise use a different name.
2a94dd827a902d3436a3a5c63d8ac77a4abffb22
aff3e5a3ecbfb98b433423a487b67b39be972582
https://github.com/ist-dresden/composum-nodes/compare/2a94dd827a902d3436a3a5c63d8ac77a4abffb22...aff3e5a3ecbfb98b433423a487b67b39be972582
diff --git a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java index e4c940428..2a6edd2f0 100644 --- a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java +++ b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java @@ -749,7 +749,7 @@ public class PackageServlet extends AbstractServiceServlet { RequestParameter file = parameters.getValue(AbstractServiceServlet.PARAM_FILE); if (file != null) { InputStream input = file.getInputStream(); - boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false); + boolean force = RequestUtil.getParameter(request, PARAM_FORCE, true); JcrPackageManager manager = PackageUtil.createPackageManager(request); JcrPackage jcrPackage = manager.upload(input, force);
['sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java']
{'.java': 1}
1
1
0
0
1
933,502
170,674
24,723
126
182
28
2
1
379
68
76
5
0
0
2017-04-25T19:00:17
54
JavaScript
{'JavaScript': 19206236, 'Java': 3257834, 'CSS': 536542, 'SCSS': 162416, 'Less': 78481, 'HTML': 51687, 'Shell': 13522, 'Groovy': 7195, 'XSLT': 451}
MIT License
9,715
netflix/conductor-community/242/241
netflix
conductor-community
https://github.com/Netflix/conductor-community/issues/241
https://github.com/Netflix/conductor-community/pull/242
https://github.com/Netflix/conductor-community/pull/242
2
fix
AMQPObservableQueue 'ack' implementation is inconsistent with the interface
**Describe the bug** The `AMQPObservableQueue` class incorrectly implements the `List<String> ack(List<Message> messages);` function from the `ObservableQueue` interface. The javadoc of `ObservableQueue#ack` states: ``` @return the id of the ones which could not be ack'ed ``` The behaviour of `AMQPObservableQueue` is instead to return the successfully-ack'ed messages. The consequence of this appears to be that `com.netflix.conductor.core.events.queue.DefaultEventQueueProcessor` in conductor-core generates a lot of log-error spam because of this line: https://github.com/Netflix/conductor/blob/631a04dd790f5d46e76691b47a748cad77e0e20d/core/src/main/java/com/netflix/conductor/core/events/queue/DefaultEventQueueProcessor.java#L155 ```java List<String> failures = queue.ack(Collections.singletonList(msg)); if (!failures.isEmpty()) { LOGGER.error("Not able to ack the messages {}", failures); } ``` The associated `AMQPObservableQueueTest` test-class has a `testAck` test which doesn't currently properly validate this behaviour insofar as all it does is validate that the returned `List<String>` is not-null. It doesn't validate that it is empty. **Details** Conductor version: current version on main Persistence implementation: N/A Queue implementation: N/A Lock: N/A Workflow definition: N/A Task definition: N/A Event handler definition: AMQP **To Reproduce** See associated test-case. **Expected behavior** `AMQPObservableQueue#ack` should only return messages that have thrown an error. **Screenshots** N/A **Additional context** N/A
c0fe98ca5c0e1d05cf48093b5bf74b695cda34e9
5a3792e4c803992ee4f36d6881870fe2c588c1fb
https://github.com/netflix/conductor-community/compare/c0fe98ca5c0e1d05cf48093b5bf74b695cda34e9...5a3792e4c803992ee4f36d6881870fe2c588c1fb
diff --git a/event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java b/event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java index ff26fc7c..c1ecadd7 100644 --- a/event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java +++ b/event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java @@ -187,16 +187,16 @@ public class AMQPObservableQueue implements ObservableQueue { } public List<String> ack(List<Message> messages) { - final List<String> processedDeliveryTags = new ArrayList<>(); + final List<String> failedMessages = new ArrayList<>(); for (final Message message : messages) { try { ackMsg(message); - processedDeliveryTags.add(message.getReceipt()); } catch (final Exception e) { LOGGER.error("Cannot ACK message with delivery tag {}", message.getReceipt(), e); + failedMessages.add(message.getReceipt()); } } - return processedDeliveryTags; + return failedMessages; } public void ackMsg(Message message) throws Exception { diff --git a/event-queue/amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java b/event-queue/amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java index 15893be8..0d936ccf 100644 --- a/event-queue/amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java +++ b/event-queue/amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java @@ -334,12 +334,12 @@ public class AMQPObservableQueueTest { } @Test - public void testGetMessagesFromExistingExchangeWithDefaultConfiguration() throws IOException, TimeoutException { + public void testGetMessagesFromExistingExchangeWithDefaultConfiguration() + throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); - testGetMessagesFromExchangeAndDefaultConfiguration( - channel, connection, true, true); + testGetMessagesFromExchangeAndDefaultConfiguration(channel, connection, true, true); } @Test @@ -386,8 +386,9 @@ public class AMQPObservableQueueTest { msg.setPayload("Payload"); msg.setReceipt("1"); messages.add(msg); - List<String> deliveredTags = observableQueue.ack(messages); - assertNotNull(deliveredTags); + List<String> failedMessages = observableQueue.ack(messages); + assertNotNull(failedMessages); + assertTrue(failedMessages.isEmpty()); } private void testGetMessagesFromExchangeAndDefaultConfiguration(
['event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java', 'event-queue/amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java']
{'.java': 2}
2
2
0
0
2
631,394
115,617
16,528
99
330
51
6
1
1,609
168
374
46
1
2
2023-07-06T09:57:58
52
Java
{'Java': 952349, 'Groovy': 29286, 'PLpgSQL': 1962, 'Shell': 168}
Apache License 2.0
9,328
ably/ably-flutter/358/356
ably
ably-flutter
https://github.com/ably/ably-flutter/issues/356
https://github.com/ably/ably-flutter/pull/358
https://github.com/ably/ably-flutter/pull/358
1
resolved
Android only - Returning a TokenDetails with 'issued' and 'expires' values in epoch milliseconds throws java error
Setup: * Device: Pixel 3XL * Android: 11 * Flutter: 2.10.3 * Ably package: 1.2.12 Configuration: Ably with token authentication {{authCallback}} property in {{ClientOptions}} pointing to a function that returns a {{TokenDetails}} object. As per documentation the object contains {{issued}} and {{expires}} properties set to an epoch timestamp in milliseconds (along the rest of the properties), for clarification, the following code works flawlessly on iOS, and its equivalent in the Javascript SDK also works correctly. Code: {code:dart} import 'package:ably_flutter/ably_flutter.dart' as Ably; String _clientId = ''; Future<Ably.TokenDetails> _getTokenDetails(Ably.TokenParams params) async { final result = await MyAPIController.getAblyAuthTokenFor(_clientId); return Ably.TokenDetails( result.data.token, issued: result.data.issued, // result.data.issued is an int with epoch timestamp in milliseconds (e.g.: 1648218289847) expires: result.data.expires, // result.data.expires same as result.data.issued but in the future clientId: result.data.clientId, capability: result.data.capability, ); } void initializeAbly(String clientId) { _clientId = clientId; final clientOptions = Ably.ClientOptions() ..clientId = _clientId ..tls = true ..useTokenAuth = true ..authCallback = _getTokenDetails; _realtime = Ably.Realtime(options: clientOptions); _realtime.connection .on(Ably.ConnectionEvent.connected) .listen((Ably.ConnectionStateChange stateChange) { // SUBSCRIBE TO CHANNELS } }); } {code} Error:: {code} E/MethodChannel#io.ably.flutter.plugin( 3539): Failed to handle method call result E/MethodChannel#io.ably.flutter.plugin( 3539): java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec.lambda$decodeTokenDetails$32(AblyMessageCodec.java:354) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.-$$Lambda$AblyMessageCodec$EZVHcAHH13F6P7lENmPZqTXnZg8.accept(Unknown Source:2) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec.readValueFromJson(AblyMessageCodec.java:160) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec.decodeTokenDetails(AblyMessageCodec.java:354) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec.access$2300(AblyMessageCodec.java:47) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec$1.lambda$new$5(AblyMessageCodec.java:102) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.-$$Lambda$AblyMessageCodec$1$DqnBUFL6jWi43rRYX8P4My0ezrE.decode(Unknown Source:2) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec$CodecPair.decode(AblyMessageCodec.java:80) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.ably.flutter.plugin.AblyMessageCodec.readValueOfType(AblyMessageCodec.java:152) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.flutter.plugin.common.StandardMessageCodec.readValue(StandardMessageCodec.java:333) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.flutter.plugin.common.StandardMethodCodec.decodeEnvelope(StandardMethodCodec.java:107) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.flutter.plugin.common.MethodChannel$IncomingResultHandler.reply(MethodChannel.java:239) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.flutter.embedding.engine.dart.DartMessenger.handlePlatformMessageResponse(DartMessenger.java:376) E/MethodChannel#io.ably.flutter.plugin( 3539): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessageResponse(FlutterJNI.java:993) E/MethodChannel#io.ably.flutter.plugin( 3539): at android.os.MessageQueue.nativePollOnce(Native Method) E/MethodChannel#io.ably.flutter.plugin( 3539): at android.os.MessageQueue.next(MessageQueue.java:335) E/MethodChannel#io.ably.flutter.plugin( 3539): at android.os.Looper.loopOnce(Looper.java:161) E/MethodChannel#io.ably.flutter.plugin( 3539): at android.os.Looper.loop(Looper.java:288) E/MethodChannel#io.ably.flutter.plugin( 3539): at android.app.ActivityThread.main(ActivityThread.java:7842) E/MethodChannel#io.ably.flutter.plugin( 3539): at java.lang.reflect.Method.invoke(Native Method) E/MethodChannel#io.ably.flutter.plugin( 3539): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) E/MethodChannel#io.ably.flutter.plugin( 3539): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) {code} It seems Java is trying to cast assign a {{long}} value as in {{int}} in the following function (lines 354 and 355): https://github.com/ably/ably-flutter/blob/4da3baa587165e32f21566144a42361f435aeaf3/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java#L350-L357 In my dart code, when I truncate the the values in {{issued}} and {{expires}} to be epoch in seconds instead of milliseconds the error goes away and ably connects successfully to the server. The token is renewed at the correct time as well. Thanks
fc8078a98f4db1702d904e81f49431d4f5ca529d
9397c4875119220b00b3e9028fc974da3d094109
https://github.com/ably/ably-flutter/compare/fc8078a98f4db1702d904e81f49431d4f5ca529d...9397c4875119220b00b3e9028fc974da3d094109
diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index 27447133..455a5f3a 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -351,8 +351,8 @@ public class AblyMessageCodec extends StandardMessageCodec { if (jsonMap == null) return null; final TokenDetails o = new TokenDetails(); readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.token, v -> o.token = (String) v); - readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.expires, v -> o.expires = (int) v); - readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.issued, v -> o.issued = (int) v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.expires, v -> o.expires = (long) v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.issued, v -> o.issued = (long) v); readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.capability, v -> o.capability = (String) v); readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.clientId, v -> o.clientId = (String) v);
['android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java']
{'.java': 1}
1
1
0
0
1
162,049
33,109
3,682
22
401
104
4
1
5,219
348
1,426
87
1
0
2022-03-31T16:28:17
50
Dart
{'Dart': 556498, 'Java': 177035, 'Objective-C': 121180, 'Swift': 36810, 'C': 19178, 'JavaScript': 4330, 'Ruby': 3899, 'Kotlin': 146, 'Shell': 60}
Apache License 2.0
9,332
ably/ably-flutter/164/156
ably
ably-flutter
https://github.com/ably/ably-flutter/issues/156
https://github.com/ably/ably-flutter/pull/164
https://github.com/ably/ably-flutter/pull/164
1
closes
Token Authentication with authCallback in Android: `java.lang.Exception: Invalid authCallback response`
When using token authentication by setting the authCallback in ably-flutter running on Android devices, an exception is always thrown. Token authentication still works because this method is called until this method does return the value. More detail: The ably-java expects a synchronous return value when it calls `Object authCallbackResponse = tokenOptions.authCallback.getTokenRequest(params);` to call the `authCallback` the user has set. In normal Android this returns a value immediately, but in Ably-flutter this is actually an asynchronous request to the dart side so it doesn’t return anything (null). Therefore, in `Auth.java` in ably-java, `authCallbackResponse` is null, and `throw AblyException.fromErrorInfo(new ErrorInfo("Invalid authCallback response", 400, 40000));` is called. https://github.com/ably/ably-flutter/blob/36b604fdaed87342edc2fd0c9ad94c34d362148d/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java#L425-L452 The relevant ably-java [code](https://github.com/ably/ably-java/blob/e73a3bdb205f188baea891003cbc1af058e0db73/lib/src/main/java/io/ably/lib/rest/Auth.java#L579-L589) is: ```java try { /* the callback can return either a signed token request, or a TokenDetails */ Object authCallbackResponse = tokenOptions.authCallback.getTokenRequest(params); if(authCallbackResponse instanceof String) return new TokenDetails((String)authCallbackResponse); if(authCallbackResponse instanceof TokenDetails) return (TokenDetails)authCallbackResponse; if(authCallbackResponse instanceof TokenRequest) signedTokenRequest = (TokenRequest)authCallbackResponse; else throw AblyException.fromErrorInfo(new ErrorInfo("Invalid authCallback response", 400, 40000)); // <-- This gets called because `authCallbackResponse` is null ``` Token authentication still works, but unfortunately the exception is not nice to see/ stack trace is scary. I first came across this error in May 2021, but misdiagnosed it to be about "not handling clientIds properly". So I will close https://github.com/ably/ably-flutter/issues/122 To reproduce this, I have a demo application which uses token auth: https://github.com/ben-xD/ably-flutter-token or you can just try to use token auth with your own token auth server. ┆Issue is synchronized with this [Jira Bug](https://ably.atlassian.net/browse/SDK-1154) by [Unito](https://www.unito.io)
165afcf5be3307566aaa3ee42becdbd35e59ba47
dcf217dfef1ae69bde54bdc2fe278435da048a20
https://github.com/ably/ably-flutter/compare/165afcf5be3307566aaa3ee42becdbd35e59ba47...dcf217dfef1ae69bde54bdc2fe278435da048a20
diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java index 08a49ff0..ae68c4dc 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.CountDownLatch; import io.ably.flutter.plugin.generated.PlatformConstants; import io.ably.flutter.plugin.push.PushActivationEventHandlers; @@ -183,18 +184,24 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { clientOptions.options.authCallback = (Auth.TokenParams params) -> { Object token = ablyLibrary.getRestToken(handle); if (token != null) return token; + + final CountDownLatch latch = new CountDownLatch(1); new Handler(Looper.getMainLooper()).post(() -> { AblyFlutterMessage<Auth.TokenParams> channelMessage = new AblyFlutterMessage<>(params, handle); channel.invokeMethod(PlatformConstants.PlatformMethod.authCallback, channelMessage, new MethodChannel.Result() { @Override public void success(@Nullable Object result) { ablyLibrary.setRestToken(handle, result); + latch.countDown(); } @Override public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) { System.out.println(errorDetails); - //Do nothing, let another request go to flutter side! + if (errorMessage != null) { + result.error("40000", String.format("Error from authCallback: %s", errorMessage), errorDetails); + } + latch.countDown(); } @Override @@ -204,7 +211,13 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { }); }); - return null; + try { + latch.await(); + } catch (InterruptedException e) { + throw AblyException.fromErrorInfo(e, new ErrorInfo("Exception while waiting for authCallback to return", 400, 40000)); + } + + return ablyLibrary.getRestToken(handle); }; } result.success(ablyLibrary.createRest(clientOptions.options)); @@ -431,7 +444,7 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { } private void createRealtimeWithOptions(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { - final AblyFlutterMessage message = (AblyFlutterMessage) call.arguments; + final AblyFlutterMessage<PlatformClientOptions> message = (AblyFlutterMessage<PlatformClientOptions>) call.arguments; this.<PlatformClientOptions>ablyDo(message, (ablyLibrary, clientOptions) -> { try { final long handle = ablyLibrary.getCurrentHandle(); @@ -439,20 +452,26 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { clientOptions.options.authCallback = (Auth.TokenParams params) -> { Object token = ablyLibrary.getRealtimeToken(handle); if (token != null) return token; + + final CountDownLatch latch = new CountDownLatch(1); new Handler(Looper.getMainLooper()).post(() -> { - AblyFlutterMessage channelMessage = new AblyFlutterMessage<>(params, handle); + AblyFlutterMessage<Auth.TokenParams> channelMessage = new AblyFlutterMessage<>(params, handle); channel.invokeMethod(PlatformConstants.PlatformMethod.realtimeAuthCallback, channelMessage, new MethodChannel.Result() { @Override public void success(@Nullable Object result) { if (result != null) { ablyLibrary.setRealtimeToken(handle, result); + latch.countDown(); } } @Override public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) { System.out.println(errorDetails); - //Do nothing, let another request go to flutter side! + if (errorMessage != null) { + result.error("40000", String.format("Error from authCallback: %s", errorMessage), errorDetails); + } + latch.countDown(); } @Override @@ -461,7 +480,14 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { } }); }); - return null; + + try { + latch.await(); + } catch (InterruptedException e) { + throw AblyException.fromErrorInfo(e, new ErrorInfo("Exception while waiting for authCallback to return", 400, 40000)); + } + + return ablyLibrary.getRealtimeToken(handle); }; } result.success(ablyLibrary.createRealtime(clientOptions.options));
['android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java']
{'.java': 1}
1
1
0
0
1
124,627
25,884
2,842
15
1,916
350
38
1
2,554
244
569
32
6
1
2021-09-01T18:12:21
50
Dart
{'Dart': 556498, 'Java': 177035, 'Objective-C': 121180, 'Swift': 36810, 'C': 19178, 'JavaScript': 4330, 'Ruby': 3899, 'Kotlin': 146, 'Shell': 60}
Apache License 2.0
9,330
ably/ably-flutter/321/308
ably
ably-flutter
https://github.com/ably/ably-flutter/issues/308
https://github.com/ably/ably-flutter/pull/321
https://github.com/ably/ably-flutter/pull/321
1
fixes
Android: `java.lang.ArrayIndexOutOfBoundsException` thrown by `AblyInstanceStore`'s `setPaginatedResult` method
We've had a customer report that a small subset of their app users have experienced this crash. Information provided via Firebase Crashlytics... {code} Fatal Exception: java.lang.ArrayIndexOutOfBoundsException src.length=11 srcPos=0 dst.length=25 dstPos=0 length=12 java.lang.System.arraycopy (System.java) com.android.internal.util.GrowingArrayUtils.insert (GrowingArrayUtils.java:141) android.util.LongSparseArray.put (LongSparseArray.java:218) io.ably.flutter.plugin.AblyInstanceStore.setPaginatedResult (AblyInstanceStore.java:105) io.ably.flutter.plugin.AblyMethodCallHandler$3.onSuccess (AblyMethodCallHandler.java:280) io.ably.flutter.plugin.AblyMethodCallHandler$3.onSuccess (AblyMethodCallHandler.java:277) io.ably.lib.http.BasePaginatedQuery$ResultRequest$1.onSuccess (BasePaginatedQuery.java:215) io.ably.lib.http.BasePaginatedQuery$ResultRequest$1.onSuccess (BasePaginatedQuery.java:212) io.ably.lib.http.HttpScheduler$AsyncRequest.setResult (HttpScheduler.java:321) io.ably.lib.http.HttpScheduler$AblyRequestWithFallback.run (HttpScheduler.java:206) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:919) {code} From the crash log for a Nokia 5.4 device running Android 10. Other potentially salient details: * 6 instances of this crash seen across 14,600 installations of the app * *OS*: 50% running Android 9 * *Devices*: 33% Samsung, 33% Xiaomi, 17% Vivo, 17% HMD Global * *Device states*: 50% background Also see [this internal Ably Support Team Slack thread|https://ably-real-time.slack.com/archives/C8SPU4589/p1643257377074100].
46c6947febdf87a34f7aa8a03d36a2b6c8a67488
1e1c6b9589104cd14cbc2eb62870e6c3d4f84ce3
https://github.com/ably/ably-flutter/compare/46c6947febdf87a34f7aa8a03d36a2b6c8a67488...1e1c6b9589104cd14cbc2eb62870e6c3d4f84ce3
diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyInstanceStore.java b/android/src/main/java/io/ably/flutter/plugin/AblyInstanceStore.java index f0fd689c..d3040f3b 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyInstanceStore.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyInstanceStore.java @@ -3,6 +3,8 @@ package io.ably.flutter.plugin; import android.content.Context; import android.util.LongSparseArray; +import java.util.concurrent.atomic.AtomicLong; + import io.ably.lib.push.Push; import io.ably.lib.push.PushChannel; import io.ably.lib.realtime.AblyRealtime; @@ -23,9 +25,7 @@ import io.ably.lib.types.ClientOptions; * client by calling @{AblyInstanceStore#getRealtime(final long handle)}. */ class AblyInstanceStore { - private static final AblyInstanceStore instance = new AblyInstanceStore(); - private long nextHandle = 1; // Android Studio warns against using HashMap with integer keys, and // suggests using LongSparseArray. More information at https://stackoverflow.com/a/31413003 @@ -34,38 +34,100 @@ class AblyInstanceStore { private final LongSparseArray<AblyRest> restInstances = new LongSparseArray<>(); private final LongSparseArray<AblyRealtime> realtimeInstances = new LongSparseArray<>(); private final LongSparseArray<AsyncPaginatedResult<Object>> paginatedResults = new LongSparseArray<>(); + private final AtomicLong nextHandle = new AtomicLong(1); static synchronized AblyInstanceStore getInstance() { return instance; } /** - * Returns a handle representing the next client that will be created. This handle can be used - * to get the client **after** it is instantiated using [createRest] or [createRealtime]. + * A reserved client handle. Safe to be used from any thread. + * + * Instances support the creation of a single Rest or Realtime instance, where only one of the + * create methods may be called and it may only be called once. */ - long getHandleForNextClient() { - return nextHandle; + interface ClientHandle { + /** + * Get the handle that will be used to store this client when it is created, or the handle + * that was used to store it when it was created. + * This property may be read at any time, from any thread. + */ + long getHandle(); + + /** + * Create an {@link AblyRest} instance and store it using this handle. + * @param clientOptions The Ably client options for the new Rest instance. + * @param applicationContext The Android application context to supply to the new Rest + * instance using its {@link AblyRest#setAndroidContext(Context)} method. + * @return The handle used to store the instance. Same as {@link #getHandle()}. + * @throws IllegalStateException If this handle has already been used to create a Rest or + * Realtime instance. + * @throws AblyException If the {@link AblyRest} instance creation failed. + */ + long createRest(ClientOptions clientOptions, Context applicationContext) throws AblyException; + + /** + * Create an {@link AblyRealtime} instance and store it using this handle. + * @param clientOptions The Ably client options for the new Realtime instance. + * @param applicationContext The Android application context to supply to the new Realtime + * instance using its {@link AblyRealtime#setAndroidContext(Context)} method. + * @return The handle used to store the instance. Same as {@link #getHandle()}. + * @throws IllegalStateException If this handle has already been used to create a Rest or + * Realtime instance. + * @throws AblyException If the {@link AblyRealtime} instance creation failed. + */ + long createRealtime(ClientOptions clientOptions, Context applicationContext) throws AblyException; } - long createRest(final ClientOptions clientOptions, Context applicationContext) throws AblyException { - final AblyRest rest = new AblyRest(clientOptions); - rest.setAndroidContext(applicationContext); - restInstances.put(nextHandle, rest); - return nextHandle++; + private class ReservedClientHandle implements ClientHandle { + private final long handle; + private volatile boolean used = false; + + ReservedClientHandle(final long handle) { + this.handle = handle; + } + + @Override + public long getHandle() { + return handle; + } + + @Override + public synchronized long createRest(final ClientOptions clientOptions, final Context applicationContext) throws AblyException { + final long handle = use(); + final AblyRest rest = new AblyRest(clientOptions); + rest.setAndroidContext(applicationContext); + restInstances.put(handle, rest); + return handle; + } + + @Override + public synchronized long createRealtime(final ClientOptions clientOptions, final Context applicationContext) throws AblyException { + final long handle = use(); + final AblyRealtime realtime = new AblyRealtime(clientOptions); + realtime.setAndroidContext(applicationContext); + realtimeInstances.put(handle, realtime); + return handle; + } + + synchronized long use() { + if (used) { + throw new IllegalStateException("Reserved handle has already been used to create a client instance (handle=" + handle + ")."); + } + used = true; + return handle; + } } - AblyRest getRest(final long handle) { - return restInstances.get(handle); + synchronized ClientHandle reserveClientHandle() { + return new ReservedClientHandle(nextHandle.getAndIncrement()); } - long createRealtime(final ClientOptions clientOptions, Context applicationContext) throws AblyException { - final AblyRealtime realtime = new AblyRealtime(clientOptions); - realtime.setAndroidContext(applicationContext); - realtimeInstances.put(nextHandle, realtime); - return nextHandle++; + synchronized AblyRest getRest(final long handle) { + return restInstances.get(handle); } - AblyRealtime getRealtime(final long handle) { + synchronized AblyRealtime getRealtime(final long handle) { return realtimeInstances.get(handle); } @@ -79,26 +141,26 @@ class AblyInstanceStore { * @param handle integer handle to either AblyRealtime or AblyRest * @return AblyBase */ - AblyBase getAblyClient(final long handle) { + synchronized AblyBase getAblyClient(final long handle) { AblyRealtime realtime = getRealtime(handle); return (realtime != null) ? realtime : getRest(handle); } - Push getPush(final long handle) { + synchronized Push getPush(final long handle) { AblyRealtime realtime = getRealtime(handle); return (realtime != null) ? realtime.push : getRest(handle).push; } - PushChannel getPushChannel(final long handle, final String channelName) { + synchronized PushChannel getPushChannel(final long handle, final String channelName) { return getAblyClient(handle) .channels .get(channelName).push; } - long setPaginatedResult(AsyncPaginatedResult result, Integer handle) { + synchronized long setPaginatedResult(AsyncPaginatedResult result, Integer handle) { long longHandle; if (handle == null) { - longHandle = nextHandle++; + longHandle = nextHandle.getAndIncrement(); } else { longHandle = handle.longValue(); } @@ -106,11 +168,11 @@ class AblyInstanceStore { return longHandle; } - AsyncPaginatedResult<Object> getPaginatedResult(long handle) { + synchronized AsyncPaginatedResult<Object> getPaginatedResult(long handle) { return paginatedResults.get(handle); } - void reset() { + synchronized void reset() { for (int i = 0; i < realtimeInstances.size(); i++) { long key = realtimeInstances.keyAt(i); AblyRealtime r = realtimeInstances.get(key); diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java index 4b3528a6..04bc3676 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java @@ -183,13 +183,13 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { final AblyFlutterMessage<PlatformClientOptions> message = (AblyFlutterMessage<PlatformClientOptions>) call.arguments; this.<PlatformClientOptions>ablyDo(message, (ablyLibrary, clientOptions) -> { try { - final long handle = ablyLibrary.getHandleForNextClient(); + final AblyInstanceStore.ClientHandle clientHandle = ablyLibrary.reserveClientHandle(); if (clientOptions.hasAuthCallback) { clientOptions.options.authCallback = (Auth.TokenParams params) -> { final Object[] token = {null}; final CountDownLatch latch = new CountDownLatch(1); new Handler(Looper.getMainLooper()).post(() -> { - AblyFlutterMessage<Auth.TokenParams> channelMessage = new AblyFlutterMessage<>(params, handle); + AblyFlutterMessage<Auth.TokenParams> channelMessage = new AblyFlutterMessage<>(params, clientHandle.getHandle()); methodChannel.invokeMethod(PlatformConstants.PlatformMethod.authCallback, channelMessage, new MethodChannel.Result() { @Override public void success(@Nullable Object result) { @@ -220,7 +220,7 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { return token[0]; }; } - result.success(ablyLibrary.createRest(clientOptions.options, applicationContext)); + result.success(clientHandle.createRest(clientOptions.options, applicationContext)); } catch (final AblyException e) { handleAblyException(result, e); } @@ -448,13 +448,13 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { final AblyFlutterMessage<PlatformClientOptions> message = (AblyFlutterMessage<PlatformClientOptions>) call.arguments; this.<PlatformClientOptions>ablyDo(message, (ablyLibrary, clientOptions) -> { try { - final long handle = ablyLibrary.getHandleForNextClient(); + final AblyInstanceStore.ClientHandle clientHandle = ablyLibrary.reserveClientHandle(); if (clientOptions.hasAuthCallback) { clientOptions.options.authCallback = (Auth.TokenParams params) -> { final Object[] token = {null}; final CountDownLatch latch = new CountDownLatch(1); new Handler(Looper.getMainLooper()).post(() -> { - AblyFlutterMessage<Auth.TokenParams> channelMessage = new AblyFlutterMessage<>(params, handle); + AblyFlutterMessage<Auth.TokenParams> channelMessage = new AblyFlutterMessage<>(params, clientHandle.getHandle()); methodChannel.invokeMethod(PlatformConstants.PlatformMethod.realtimeAuthCallback, channelMessage, new MethodChannel.Result() { @Override public void success(@Nullable Object result) { @@ -487,7 +487,7 @@ public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { return token[0]; }; } - result.success(ablyLibrary.createRealtime(clientOptions.options, applicationContext)); + result.success(clientHandle.createRealtime(clientOptions.options, applicationContext)); } catch (final AblyException e) { handleAblyException(result, e); }
['android/src/main/java/io/ably/flutter/plugin/AblyInstanceStore.java', 'android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java']
{'.java': 2}
2
2
0
0
2
156,621
32,129
3,549
21
7,073
1,356
126
2
1,698
118
430
31
1
0
2022-02-07T18:43:29
50
Dart
{'Dart': 556498, 'Java': 177035, 'Objective-C': 121180, 'Swift': 36810, 'C': 19178, 'JavaScript': 4330, 'Ruby': 3899, 'Kotlin': 146, 'Shell': 60}
Apache License 2.0
9,331
ably/ably-flutter/303/298
ably
ably-flutter
https://github.com/ably/ably-flutter/issues/298
https://github.com/ably/ably-flutter/pull/303
https://github.com/ably/ably-flutter/pull/303
1
fixes
Customer reporting issue with NPE on Android push notifications
Details: Hi , we also noticed that after the move to official ably plugin, we're getting a surge in the following error for Android: {code} Fatal Exception: java.lang.NullPointerException Attempt to invoke interface method 'void io.flutter.plugin.common.MethodChannel$Result.error(java.lang.String, java.lang.String, java.lang.Object)' on a null object reference io.ably.flutter.plugin.push.PushActivationEventHandlers$BroadcastReceiver.returnMethodCallResult (PushActivationEventHandlers.java:86) io.ably.flutter.plugin.push.PushActivationEventHandlers$BroadcastReceiver.onReceive (PushActivationEventHandlers.java:72) androidx.localbroadcastmanager.content.LocalBroadcastManager.executePendingBroadcasts (LocalBroadcastManager.java:313) androidx.localbroadcastmanager.content.LocalBroadcastManager$1.handleMessage (LocalBroadcastManager.java:121) android.os.Handler.dispatchMessage (Handler.java:106) android.os.Looper.loop (Looper.java:226) android.app.ActivityThread.main (ActivityThread.java:7191) java.lang.reflect.Method.invoke (Method.java) com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:499) com.android.internal.os.ZygoteInit.main (ZygoteInit.java:942) {code} Seems to be impacting mainly certain manufacturers/models {code} 62% Xiaomi 21% OPPO 5% Realme 5% realme 3% vivo 2% samsung 1% HUAWEI <1% INFINIX MOBILITY LIMITED <1% asus <1% Sony <1% Meizu {code} TODO: Make sure you handle the situation where result is null Check iOS implementation to see how this case is handled
afca512c95824e5bd5eeddae4cfd7b25e1ddd051
f9534e5ef650d32dfd330eec35595ce071dca3b0
https://github.com/ably/ably-flutter/compare/afca512c95824e5bd5eeddae4cfd7b25e1ddd051...f9534e5ef650d32dfd330eec35595ce071dca3b0
diff --git a/android/src/main/java/io/ably/flutter/plugin/push/PushActivationEventHandlers.java b/android/src/main/java/io/ably/flutter/plugin/push/PushActivationEventHandlers.java index 7fd1a7a4..01a7e7fa 100644 --- a/android/src/main/java/io/ably/flutter/plugin/push/PushActivationEventHandlers.java +++ b/android/src/main/java/io/ably/flutter/plugin/push/PushActivationEventHandlers.java @@ -64,13 +64,23 @@ public class PushActivationEventHandlers { switch (action) { case PUSH_ACTIVATE_ACTION: callCallbackOnDartSide(PlatformConstants.PlatformMethod.pushOnActivate, errorInfo); - returnMethodCallResult(resultForActivate, errorInfo); - resultForActivate = null; + if (resultForActivate != null) { + Log.d(TAG, "resultForActivate received on PUSH_ACTIVATE_ACTION."); + returnMethodCallResult(resultForActivate, errorInfo); + resultForActivate = null; + } else { + Log.e(TAG, "resultForActivate is null on PUSH_ACTIVATE_ACTION."); + } break; case PUSH_DEACTIVATE_ACTION: callCallbackOnDartSide(PlatformConstants.PlatformMethod.pushOnDeactivate, errorInfo); - returnMethodCallResult(resultForDeactivate, errorInfo); - resultForDeactivate = null; + if (resultForDeactivate != null) { + Log.d(TAG, "resultForDeactivate received on PUSH_DEACTIVATE_ACTION."); + returnMethodCallResult(resultForDeactivate, errorInfo); + resultForDeactivate = null; + } else { + Log.e(TAG, "resultForDeactivate is null on PUSH_DEACTIVATE_ACTION."); + } break; case PUSH_UPDATE_FAILED_ACTION: callCallbackOnDartSide(PlatformConstants.PlatformMethod.pushOnUpdateFailed, errorInfo);
['android/src/main/java/io/ably/flutter/plugin/push/PushActivationEventHandlers.java']
{'.java': 1}
1
1
0
0
1
156,141
32,026
3,539
21
905
183
18
1
1,523
117
356
37
0
0
2022-01-24T11:24:10
50
Dart
{'Dart': 556498, 'Java': 177035, 'Objective-C': 121180, 'Swift': 36810, 'C': 19178, 'JavaScript': 4330, 'Ruby': 3899, 'Kotlin': 146, 'Shell': 60}
Apache License 2.0
521
release-engineering/pom-manipulation-ext/124/122
release-engineering
pom-manipulation-ext
https://github.com/release-engineering/pom-manipulation-ext/issues/122
https://github.com/release-engineering/pom-manipulation-ext/pull/124
https://github.com/release-engineering/pom-manipulation-ext/pull/124#issuecomment-91650270
1
fixes
REGRESSION: versions no longer zero-filled for matching
given POM version: '7' given metadata versions: - '7' - '7.0.0.build-3' The new version should be '7.0.0.build-4', but it's '7.0.0.build-1' (it's not zero-filling the version when matching against the metadata versions). I've confirmed that this worked when we were using atlas for version parsing / sorting, but broke when we moved to the internal Version class for parsing/sorting.
621616d0a1dc6611fed872624e8b07e02bb4d99a
2b1360a54d66f8202a8a357ff6f1555599fbad17
https://github.com/release-engineering/pom-manipulation-ext/compare/621616d0a1dc6611fed872624e8b07e02bb4d99a...2b1360a54d66f8202a8a357ff6f1555599fbad17
diff --git a/src/main/java/org/commonjava/maven/ext/manip/impl/Version.java b/src/main/java/org/commonjava/maven/ext/manip/impl/Version.java index ace29106..c6aafb2a 100644 --- a/src/main/java/org/commonjava/maven/ext/manip/impl/Version.java +++ b/src/main/java/org/commonjava/maven/ext/manip/impl/Version.java @@ -611,10 +611,11 @@ public class Version { int highestBuildNum = 0; - // Build version pattern regex + // Build version pattern regex, matches something like "<mmm>.<qualifier>.<buildnum>". StringBuffer versionPatternBuf = new StringBuffer(); versionPatternBuf.append( "(" ); versionPatternBuf.append( Pattern.quote( getOriginalMMM() ) ); + versionPatternBuf.append( "(" + DELIMITER_REGEX + "0)*" ); // Match zeros appended to a major only version versionPatternBuf.append( ")?" ); versionPatternBuf.append( DELIMITER_REGEX ); if ( version.getQualifierBase() != null ) @@ -622,9 +623,7 @@ public class Version versionPatternBuf.append( Pattern.quote( version.getQualifierBase() ) ); versionPatternBuf.append( DELIMITER_REGEX ); } - versionPatternBuf.append( "(" ); - versionPatternBuf.append( "\\\\d+" ); - versionPatternBuf.append( ")" ); + versionPatternBuf.append( "(\\\\d+)" ); String candidatePatternStr = versionPatternBuf.toString(); logger.debug( "Using pattern: '{}' to find compatible versions from metadata.", candidatePatternStr ); @@ -635,7 +634,7 @@ public class Version final Matcher candidateSuffixMatcher = candidateSuffixPattern.matcher( compareVersion ); if ( candidateSuffixMatcher.matches() ) { - String buildNumberStr = candidateSuffixMatcher.group( 2 ); + String buildNumberStr = candidateSuffixMatcher.group( 3 ); int compareBuildNum = Integer.parseInt( buildNumberStr ); if ( compareBuildNum > highestBuildNum ) { diff --git a/src/test/java/org/commonjava/maven/ext/manip/impl/VersionTest.java b/src/test/java/org/commonjava/maven/ext/manip/impl/VersionTest.java index db51b0ee..3d3c968a 100644 --- a/src/test/java/org/commonjava/maven/ext/manip/impl/VersionTest.java +++ b/src/test/java/org/commonjava/maven/ext/manip/impl/VersionTest.java @@ -269,13 +269,21 @@ public class VersionTest } @Test - @Ignore( "PENDING: https://github.com/release-engineering/pom-manipulation-ext/issues/122" ) public void testZeroFill_FindHighestMatchingBuildNumber() { final Set<String> versionSet = new HashSet<String>(); - final Version version = new Version( "7" ); + final Version majorOnlyVersion = new Version( "7" ); + majorOnlyVersion.appendQualifierSuffix( "redhat" ); + System.out.println("OSGi version: " + majorOnlyVersion.getOSGiVersionString()); versionSet.add( "7.0.0.redhat-2" ); - assertThat( version.findHighestMatchingBuildNumber( version, versionSet ), equalTo( 2 ) ); + assertThat( majorOnlyVersion.findHighestMatchingBuildNumber( majorOnlyVersion, versionSet ), equalTo( 2 ) ); + versionSet.clear(); + + final Version majorMinorVersion = new Version( "7.1" ); + majorMinorVersion.appendQualifierSuffix( "redhat" ); + System.out.println("OSGi version: " + majorMinorVersion.getOSGiVersionString()); + versionSet.add( "7.1.0.redhat-2" ); + assertThat( majorMinorVersion.findHighestMatchingBuildNumber( majorMinorVersion, versionSet ), equalTo( 2 ) ); versionSet.clear(); }
['src/test/java/org/commonjava/maven/ext/manip/impl/VersionTest.java', 'src/main/java/org/commonjava/maven/ext/manip/impl/Version.java']
{'.java': 2}
2
2
0
0
2
264,163
50,441
7,419
38
579
122
9
1
385
58
103
7
0
0
2015-04-10T18:49:46
49
Java
{'Java': 1611249, 'Groovy': 295181}
Apache License 2.0
9,291
nasa-ammos/aerie/533/526
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/526
https://github.com/NASA-AMMOS/aerie/pull/533
https://github.com/NASA-AMMOS/aerie/pull/533
1
fixes
Negative delay moves simulation time backward
Labeling this as a bug - but maybe it's a feature...? 😅 ## Description Type-wise, everything is fine - delay is defined to work on Duration, and that includes negative durations. However, I think this violates other invariants of the system - such as the invariant that the start offsets of resource profile segments are monotonically increasing. `TaskStatus.Delayed` is perfectly happy to accept a negative duration: https://github.com/NASA-AMMOS/aerie/blob/ad2e9c4130a09afea401daf15b3d0dbf7ccd801b/merlin-sdk/src/main/java/gov/nasa/jpl/aerie/merlin/protocol/types/TaskStatus.java#L10 The SimulationEngine is perfectly happy to schedule that task to be resumed in the past: https://github.com/NASA-AMMOS/aerie/blob/ad2e9c4130a09afea401daf15b3d0dbf7ccd801b/merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/engine/SimulationEngine.java#L236-L238 This of course puts that task at the front of the job queue, so the next call to `extractNextJobs` contains this task, as well as the time (in the past) at which this task is scheduled. The "delta" computation in the simulation driver will compute a negative delta and add it to the timeline: https://github.com/NASA-AMMOS/aerie/blob/ad2e9c4130a09afea401daf15b3d0dbf7ccd801b/merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/SimulationDriver.java#L73-L75 Interestingly - the timeline keeps a perfect record of all this - if time travel were somehow semantically acceptable, the timeline would capture it faithfully (particularly - it faithfully captures the direction of causality even when time steps backwards). ## Possible solutions 1. We can throw an error and tank simulation as soon as a negative delay is requested 2. We can clamp negative durations to ZERO - and perhaps issue a warning to alert the client that we've done this 3. (Far-fetched) We can try to give a reasonable semantics to time travel
3c2bbff2df4f161fc7ee23cecc8fc878db492dac
051a0f17ca122d06b99ac830fc51c3966b1e8740
https://github.com/nasa-ammos/aerie/compare/3c2bbff2df4f161fc7ee23cecc8fc878db492dac...051a0f17ca122d06b99ac830fc51c3966b1e8740
diff --git a/merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/engine/SimulationEngine.java b/merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/engine/SimulationEngine.java index b45646aa3..de252a9c7 100644 --- a/merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/engine/SimulationEngine.java +++ b/merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/engine/SimulationEngine.java @@ -27,7 +27,6 @@ import gov.nasa.jpl.aerie.merlin.protocol.types.ValueSchema; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; -import java.lang.reflect.InvocationTargetException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; @@ -100,6 +99,8 @@ public final class SimulationEngine implements AutoCloseable { /** Schedule a new task to be performed at the given time. */ public <Return> TaskId scheduleTask(final Duration startTime, final TaskFactory<Return> state) { + if (startTime.isNegative()) throw new IllegalArgumentException("Cannot schedule a task before the start time of the simulation"); + final var task = TaskId.generate(); this.tasks.put(task, new ExecutionState.InProgress<>(startTime, state.create(this.executor))); this.scheduledJobs.schedule(JobId.forTask(task), SubInstant.Tasks.at(startTime)); @@ -234,6 +235,8 @@ public final class SimulationEngine implements AutoCloseable { this.tasks.put(task, progress.completedAt(currentTime, children)); this.scheduledJobs.schedule(JobId.forTask(task), SubInstant.Tasks.at(currentTime)); } else if (status instanceof TaskStatus.Delayed<Return> s) { + if (s.delay().isNegative()) throw new IllegalArgumentException("Cannot schedule a task in the past"); + this.tasks.put(task, progress.continueWith(s.continuation())); this.scheduledJobs.schedule(JobId.forTask(task), SubInstant.Tasks.at(currentTime.plus(s.delay()))); } else if (status instanceof TaskStatus.CallingTask<Return> s) {
['merlin-driver/src/main/java/gov/nasa/jpl/aerie/merlin/driver/engine/SimulationEngine.java']
{'.java': 1}
1
1
0
0
1
1,748,738
370,965
48,135
628
300
53
5
1
1,906
232
484
22
3
0
2022-12-12T20:11:46
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
9,290
nasa-ammos/aerie/623/457
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/457
https://github.com/NASA-AMMOS/aerie/pull/623
https://github.com/NASA-AMMOS/aerie/pull/623
1
closes
Cardinality goal does not respect applyWhen
I want to write a cardinality goal that is only able to satisfy itself with / create activity instances within a given time bounds specified in an `applyWhen` clause. Currently, this goal finds all of activity instances in the plan even if they are very far from the specified window. ```ts export default (): Goal => { return Goal.CardinalityGoal({ activityTemplate: ActivityTemplates.ResumeBG(), specification: { occurrence: 1 }, }).applyWhen( Windows.All( Real.Resource('/time/clock.seconds').greaterThan(0), Real.Resource('/time/clock.seconds').lessThan(3600), ), ); }; ``` Internal ticket: https://jira.jpl.nasa.gov/browse/AERIEQS-355
8f9baf32d4d80b918ee912c6cc163eae0159cf96
abe084f5d5ca35d29a21ab5c3fc403746f2e8ff7
https://github.com/nasa-ammos/aerie/compare/8f9baf32d4d80b918ee912c6cc163eae0159cf96...abe084f5d5ca35d29a21ab5c3fc403746f2e8ff7
diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityExpression.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityExpression.java index b98ca05fd..ed2ef2564 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityExpression.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityExpression.java @@ -334,6 +334,7 @@ public class ActivityExpression implements Expression<Spans> { endsIn = template.endRange; durationIn = template.durationRange; startsOrEndsIn = template.startOrEndRange; + startsOrEndsInW = template.startOrEndRangeW; arguments = template.arguments; return getThis(); } diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/goals/CardinalityGoal.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/goals/CardinalityGoal.java index 5c26028c3..e8d2decc3 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/goals/CardinalityGoal.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/goals/CardinalityGoal.java @@ -6,6 +6,7 @@ import gov.nasa.jpl.aerie.constraints.time.Interval; import gov.nasa.jpl.aerie.constraints.time.Windows; import gov.nasa.jpl.aerie.merlin.protocol.types.Duration; import gov.nasa.jpl.aerie.scheduler.conflicts.UnsatisfiableGoalConflict; +import gov.nasa.jpl.aerie.scheduler.constraints.activities.ActivityExpression; import gov.nasa.jpl.aerie.scheduler.model.SchedulingActivityInstanceId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -161,8 +162,8 @@ public class CardinalityGoal extends ActivityTemplateGoal { for(Interval subInterval : windows.iterateEqualTo(true)) { final var subIntervalWindows = new Windows(false).set(subInterval, true); - ActivityCreationTemplate actTB = - new ActivityCreationTemplate.Builder().basedOn(this.desiredActTemplate).startsOrEndsIn(subIntervalWindows).build(); + final var actTB = + new ActivityExpression.Builder().basedOn(this.desiredActTemplate).startsOrEndsIn(subIntervalWindows).build(); final var acts = new LinkedList<>(plan.find(actTB, simulationResults, new EvaluationEnvironment())); acts.sort(Comparator.comparing(ActivityInstance::startTime)); diff --git a/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java b/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java index 00f76bd15..f5c484874 100644 --- a/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java +++ b/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java @@ -2,12 +2,15 @@ package gov.nasa.jpl.aerie.scheduler; import com.google.common.testing.NullPointerTester; import com.google.common.truth.Correspondence; +import gov.nasa.jpl.aerie.constraints.time.Interval; import gov.nasa.jpl.aerie.constraints.time.Windows; import gov.nasa.jpl.aerie.constraints.tree.WindowsWrapperExpression; import gov.nasa.jpl.aerie.merlin.protocol.types.Duration; import gov.nasa.jpl.aerie.scheduler.constraints.activities.ActivityCreationTemplate; import gov.nasa.jpl.aerie.scheduler.constraints.activities.ActivityExpression; import gov.nasa.jpl.aerie.scheduler.constraints.timeexpressions.TimeAnchor; +import gov.nasa.jpl.aerie.scheduler.goals.CardinalityGoal; +import gov.nasa.jpl.aerie.scheduler.goals.ChildCustody; import gov.nasa.jpl.aerie.scheduler.goals.CoexistenceGoal; import gov.nasa.jpl.aerie.scheduler.goals.ProceduralCreationGoal; import gov.nasa.jpl.aerie.scheduler.goals.RecurrenceGoal; @@ -228,4 +231,46 @@ public class PrioritySolverTest { .containsAtLeastElementsIn(expectedPlan.getActivitiesByTime()); } + + @Test + public void testCardGoalWithApplyWhen(){ + var planningHorizon = h; + + final var fooMissionModel = SimulationUtility.getFooMissionModel(); + Problem problem = new Problem(fooMissionModel, planningHorizon, new SimulationFacade( + planningHorizon, + fooMissionModel), SimulationUtility.getFooSchedulerModel()); + final var activityType = problem.getActivityType("ControllableDurationActivity"); + + //act at t=1hr and at t=2hrs + problem.setInitialPlan(makePlanA12(problem)); + + //and the goal window in between [0, 50 min[ so the activities already present in the plan can't count towards satisfying the goal + final var goalWindow = new Windows(false).set(List.of( + Interval.between(Duration.of(0, Duration.SECONDS), Duration.of(50, Duration.MINUTE)) + ), true); + + CardinalityGoal cardGoal = new CardinalityGoal.Builder() + .duration(Interval.between(Duration.of(2, Duration.SECONDS), Duration.of(65, Duration.HOUR))) + .occurences(new Range<>(1, 3)) + .thereExistsOne(new ActivityCreationTemplate.Builder() + .ofType(problem.getActivityType("ControllableDurationActivity")) + .duration(d1min) + .build()) + .named("TestCardGoal") + .forAllTimeIn(new WindowsWrapperExpression(goalWindow)) + .owned(ChildCustody.Jointly) + .build(); + + TestUtility.createAutoMutexGlobalSchedulingCondition(activityType).forEach(problem::add); + problem.setGoals(List.of(cardGoal)); + final var solver = new PrioritySolver(problem); + + var plan = solver.getNextSolution().orElseThrow(); + //will insert an activity at the beginning of the plan in addition of the two already-present activities + assertThat(plan.getActivities().size()).isEqualTo(3); + } + + + }
['scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityExpression.java', 'scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java', 'scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/goals/CardinalityGoal.java']
{'.java': 3}
3
3
0
0
3
1,765,678
374,165
48,425
632
443
92
6
2
691
77
154
17
1
1
2023-01-30T22:32:00
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
9,288
nasa-ammos/aerie/835/834
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/834
https://github.com/NASA-AMMOS/aerie/pull/835
https://github.com/NASA-AMMOS/aerie/pull/835
1
fixes
Error when saving scheduling simulation results with child activities
Aerie version: 49bfe3f7ed4ccc1826727fd972d9036fb8e7edd0 To reproduce: create a plan with banananation, add a scheduling goal of any sort, e.g. ```typescript export default (): Goal => { return Goal.ActivityRecurrenceGoal({ interval: Temporal.Duration.from({hours: 48}), activityTemplate: ActivityTemplates.BiteBanana({ biteSize: 1 }) }) } ``` Add a `child` activity to the plan - which will decompose to add a grandchild activity. Run scheduling: ``` java.util.NoSuchElementException: No value present at java.base/java.util.Optional.get(Unknown Source) at gov.nasa.jpl.aerie.scheduler.server.services.GraphQLMerlinService.lambda$postActivities$10(GraphQLMerlinService.java:1107) at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Unknown Source) at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source) at java.base/java.util.HashMap$EntrySpliterator.forEachRemaining(Unknown Source) at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source) at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source) at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source) at java.base/java.util.stream.ReferencePipeline.collect(Unknown Source) at gov.nasa.jpl.aerie.scheduler.server.services.GraphQLMerlinService.postActivities(GraphQLMerlinService.java:1106) at gov.nasa.jpl.aerie.scheduler.server.services.GraphQLMerlinService.storeSimulationResults(GraphQLMerlinService.java:737) at gov.nasa.jpl.aerie.scheduler.worker.services.SynchronousSchedulerAgent.storeSimulationResults(SynchronousSchedulerAgent.java:287) at gov.nasa.jpl.aerie.scheduler.worker.services.SynchronousSchedulerAgent.schedule(SynchronousSchedulerAgent.java:229) at gov.nasa.jpl.aerie.scheduler.worker.SchedulerWorkerAppDriver.main(SchedulerWorkerAppDriver.java:88) ``` This line of code assumes that every simulated activity has a non-empty directiveId: https://github.com/NASA-AMMOS/aerie/blob/49bfe3f7ed4ccc1826727fd972d9036fb8e7edd0/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/GraphQLMerlinService.java#L1095
cc591d1bf8d477739da73b99eb647269cea96d98
cde58ebc3fbebd7cdbe4dd47fcf8552a45a254b2
https://github.com/nasa-ammos/aerie/compare/cc591d1bf8d477739da73b99eb647269cea96d98...cde58ebc3fbebd7cdbe4dd47fcf8552a45a254b2
diff --git a/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/GraphQLMerlinService.java b/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/GraphQLMerlinService.java index 94a1f92a4..2f609da81 100644 --- a/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/GraphQLMerlinService.java +++ b/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/GraphQLMerlinService.java @@ -1116,11 +1116,11 @@ public SimulationId getSimulationId(PlanId planId) throws PlanServiceException, { final var simulatedActivityRecords = simulatedActivities.entrySet().stream() .collect(Collectors.toMap( - e -> simulationActivityDirectiveIdToMerlinActivityDirectiveId.get(e.getValue().directiveId().get()).id(), + e -> e.getKey().id(), e -> simulatedActivityToRecord(e.getValue(), simulationActivityDirectiveIdToMerlinActivityDirectiveId))); final var allActivityRecords = unfinishedActivities.entrySet().stream() .collect(Collectors.toMap( - e -> simulationActivityDirectiveIdToMerlinActivityDirectiveId.get(e.getValue().directiveId().get()).id(), + e -> e.getKey().id(), e -> unfinishedActivityToRecord(e.getValue(), simulationActivityDirectiveIdToMerlinActivityDirectiveId))); allActivityRecords.putAll(simulatedActivityRecords); final var simIdToPgId = postSpans( @@ -1166,10 +1166,18 @@ public SimulationId getSimulationId(PlanId planId) throws PlanServiceException, final JsonObject response; response = postRequest(req, arguments).get(); - final var affected_rows = response.getJsonObject("data").getJsonObject("update_span_many").getInt("affected_rows"); - if(affected_rows != updateCounter) { - throw new PlanServiceException("not the same size"); - } + final var jsonValue = response.getJsonObject("data").get("update_span_many"); + var affected_rows = 0; + if (jsonValue.getValueType() == JsonValue.ValueType.ARRAY) { + for (final var jsonObject : response.getJsonObject("data").getJsonArray("update_span_many").getValuesAs(JsonObject.class)) { + affected_rows += jsonObject.getInt("affected_rows"); + } + } else { + affected_rows = response.getJsonObject("data").getJsonObject("update_span_many").getInt("affected_rows"); + } + if(affected_rows != updateCounter) { + throw new PlanServiceException("not the same size"); + } } private static SpanRecord simulatedActivityToRecord(final SimulatedActivity activity,
['scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/GraphQLMerlinService.java']
{'.java': 1}
1
1
0
0
1
1,845,295
390,776
50,095
647
1,358
248
20
1
2,260
115
513
40
1
2
2023-03-31T15:30:14
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
9,287
nasa-ammos/aerie/951/916
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/916
https://github.com/NASA-AMMOS/aerie/pull/951
https://github.com/NASA-AMMOS/aerie/pull/951
1
closes
Cannot use ActivityPresets with Enum Values in Scheduling EDSL
### Checked for duplicates Yes - I've already checked ### Is this a regression? No - This is a new bug ### Version develop ### Describe the bug Goals that use ActivityPresets to define the `activityTemplate` or `activityFinder` fields fail to compile with a type error if the ActivityType of the preset has an enum parameter. Example Error: ```json [{"errors": [{"location": {"column":52,"line":5}, "message":"TypeError: TS2345 Argument of type '{ peelDirection: string; }' is not assignable to parameter of type 'ParameterTypePeelBanana'.\\n Types of property 'peelDirection' are incompatible.\\n Type 'string' is not assignable to type '\\"fromStem\\" | \\"fromTip\\" | Discrete<\\"fromStem\\" | \\"fromTip\\">'.","stack":"at (5:52)"}],"goal_id":3}] ``` This may potentially also occur with `activityFinder`. ### Reproduction 1. Spin up Aerie. 2. Upload a BananaNation model and create a plan from it. 3. Create a preset for PeelBanana. 4. Create the following scheduling goal for the plan: ```typescript export default (): Goal => { return Goal.CoexistenceGoal({ forEach: Real.Resource("/peel").greaterThan(3), activityFinder: ActivityExpression.build(ActivityTypes.PeelBanana, ActivityPresets.PeelBanana["FromTip"]), activityTemplate: ActivityTemplates.PeelBanana(ActivityPresets.PeelBanana["FromTip"]), startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes: 5 })) }); } ``` 5. Attempt to run simulation. ### Logs _No response_ ### System Info ```shell Firefox M1 Mac ``` ### Severity Moderate
f9966834894f6f165920dbead80df01ecf91469a
abdbca1556be763c9fc51a825ca9951874cff2d7
https://github.com/nasa-ammos/aerie/compare/f9966834894f6f165920dbead80df01ecf91469a...abdbca1556be763c9fc51a825ca9951874cff2d7
diff --git a/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationService.java b/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationService.java index 52f4ac042..12602b164 100644 --- a/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationService.java +++ b/scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationService.java @@ -130,7 +130,7 @@ return (<T>makeAllDiscreteProfile(args)) for (final var activityTypeCode : activityTypeCodes) { result.add(indent("%s: Object.freeze({".formatted(activityTypeCode.activityTypeName))); for (final var preset: activityTypeCode.presets.entrySet()) { - result.add(indent(indent("get \\"%s\\"(): %s {".formatted(preset.getKey(), serializedValueToType(SerializedValue.of(preset.getValue())))))); + result.add(indent(indent("get \\"%s\\"(): %s {".formatted(preset.getKey(), TypescriptType.toString(activityTypeCode.getArgumentsType(), false))))); result.add(indent(indent(indent("return {")))); for (final var argument: preset.getValue().entrySet()) { final var deserializedJson = serializedValueP.unparse(argument.getValue()); @@ -153,7 +153,13 @@ return (<T>makeAllDiscreteProfile(args)) return joinLines(s.lines().map(line -> " " + line).toList()); } - private record ActivityTypeCode(String activityTypeName, List<ActivityParameter> parameterTypes, Map<String, Map<String, SerializedValue>> presets) {} + private record ActivityTypeCode(String activityTypeName, List<ActivityParameter> parameterTypes, Map<String, Map<String, SerializedValue>> presets) { + public TypescriptType getArgumentsType() { + return new TypescriptType.TSStruct( + parameterTypes.stream().map($ -> Pair.of($.name(), $.type())).toList() + ); + } + } private record ActivityParameter(String name, TypescriptType type) {} @@ -170,7 +176,7 @@ return (<T>makeAllDiscreteProfile(args)) /** * Print this type out in one line. */ - static String toString(final TypescriptType type) { + static String toString(final TypescriptType type, boolean topLevelStructIsProfile) { if (type instanceof TSString) { return "(string | Discrete<string>)"; } else if (type instanceof TSDouble) { @@ -183,16 +189,24 @@ return (<T>makeAllDiscreteProfile(args)) } else if (type instanceof TSDuration) { return "(Temporal.Duration | Discrete<Temporal.Duration>)"; } else if (type instanceof TSArray t) { - final var typeStr = toString(t.elementType()); + final var typeStr = toString(t.elementType(), true); return "((" +typeStr+ ")[] | Discrete<("+typeStr+")[]>)"; } else if (type instanceof TSStruct t) { - var typeStr = "{ "; - for(final var keyAndType : t.keysAndTypes()){ - typeStr += keyAndType.getLeft() + ":"+ toString(keyAndType.getRight())+","; + var typeStr = new StringBuilder("{ "); + for (final var keyAndType : t.keysAndTypes()) { + typeStr + .append(keyAndType.getLeft()) + .append(":") + .append(toString(keyAndType.getRight(), true)) + .append(","); + } + typeStr.append("}"); + if (topLevelStructIsProfile) { + return "(%s | Discrete<%s>)".formatted(typeStr, typeStr); + } else { + return typeStr.toString(); } - typeStr+="}"; - return "(%s | Discrete<%s>)".formatted(typeStr, typeStr); } else if (type instanceof TSEnum t) { final var typeStr = "(" + String.join(" | ", t.values().stream().map(x -> "\\"" + x + "\\"").toList()) + ")"; return "(%s | Discrete<%s>)".formatted(typeStr, typeStr); @@ -212,11 +226,11 @@ return (<T>makeAllDiscreteProfile(args)) .entrySet() .stream() .sorted(Map.Entry.comparingByKey()) - .map($ -> new ActivityParameter($.getKey(), valueSchemaToTypescriptTypeOrProfile($.getValue()))) + .map($ -> new ActivityParameter($.getKey(), valueSchemaToTypescriptType($.getValue()))) .toList(); } - private static TypescriptType valueSchemaToTypescriptTypeOrProfile(final ValueSchema valueSchema) { + private static TypescriptType valueSchemaToTypescriptType(final ValueSchema valueSchema) { return valueSchema.match(new ValueSchema.Visitor<>() { @Override public TypescriptType onReal() { @@ -250,7 +264,7 @@ return (<T>makeAllDiscreteProfile(args)) @Override public TypescriptType onSeries(final ValueSchema value) { - return new TypescriptType.TSArray(valueSchemaToTypescriptTypeOrProfile(value)); + return new TypescriptType.TSArray(valueSchemaToTypescriptType(value)); } @Override @@ -263,7 +277,7 @@ return (<T>makeAllDiscreteProfile(args)) .map($ -> Pair.of( $.getKey(), - valueSchemaToTypescriptTypeOrProfile($.getValue()))) + valueSchemaToTypescriptType($.getValue()))) .toList()); } diff --git a/scheduler-server/src/test/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTest.java b/scheduler-server/src/test/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTest.java index 6380da870..28242ddf9 100644 --- a/scheduler-server/src/test/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTest.java +++ b/scheduler-server/src/test/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTest.java @@ -18,6 +18,7 @@ import type { Windows } from './constraints-edsl-fluent-api.js'; import type * as ConstraintEDSL from './constraints-edsl-fluent-api.js' interface SampleActivity1 extends ActivityTemplate<ActivityType.SampleActivity1> {} interface SampleActivity2 extends ActivityTemplate<ActivityType.SampleActivity2> {} +interface SampleActivity3 extends ActivityTemplate<ActivityType.SampleActivity3> {} interface SampleActivityEmpty extends ActivityTemplate<ActivityType.SampleActivityEmpty> {} export function makeAllDiscreteProfile (argument: any) : any{ if (argument === undefined){ @@ -68,6 +69,11 @@ const ActivityTemplateConstructors = { // @ts-ignore return { activityType: ActivityType.SampleActivity2, args: makeArgumentsDiscreteProfiles(args) }; }, + SampleActivity3: function SampleActivity3Constructor(args: ConstraintEDSL.Gen.ActivityTypeParameterMap[ActivityType.SampleActivity3] + ): SampleActivity3 { + // @ts-ignore + return { activityType: ActivityType.SampleActivity3, args: makeArgumentsDiscreteProfiles(args) }; + }, SampleActivityEmpty: function SampleActivityEmptyConstructor(): SampleActivityEmpty { return { activityType: ActivityType.SampleActivityEmpty, args: {} }; }, @@ -76,14 +82,19 @@ const ActivityPresetMap = Object.freeze({ SampleActivity1: Object.freeze({ }), SampleActivity2: Object.freeze({ - get "my preset"(): { - "quantity": number, - } { + get "my preset"(): { quantity:(number | Real),} { return { "quantity": 5, }; }, }), + SampleActivity3: Object.freeze({ + get "my preset"(): { variant:(("option1" | "option2") | Discrete<("option1" | "option2")>),} { + return { + "variant": "option1", + }; + }, + }), SampleActivityEmpty: Object.freeze({ }), }); diff --git a/scheduler-server/src/testFixtures/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTestFixtures.java b/scheduler-server/src/testFixtures/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTestFixtures.java index 7082a45f4..659b20921 100644 --- a/scheduler-server/src/testFixtures/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTestFixtures.java +++ b/scheduler-server/src/testFixtures/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTestFixtures.java @@ -46,6 +46,20 @@ public final class TypescriptCodeGenerationServiceTestFixtures { Map.of("quantity", SerializedValue.of(5)) ) ), + new MissionModelService.ActivityType( + "SampleActivity3", + Map.of( + "variant", + ValueSchema.ofVariant(List.of( + new ValueSchema.Variant("option1", "option1"), + new ValueSchema.Variant("option2", "option2") + )) + ), + Map.of( + "my preset", + Map.of("variant", SerializedValue.of("option1")) + ) + ), new MissionModelService.ActivityType( "SampleActivityEmpty", Map.of(), diff --git a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingDSLCompilationServiceTests.java b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingDSLCompilationServiceTests.java index 92237ffad..8ac852ed8 100644 --- a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingDSLCompilationServiceTests.java +++ b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingDSLCompilationServiceTests.java @@ -153,6 +153,12 @@ class SchedulingDSLCompilationServiceTests { )); } + private static StructExpressionAt getSampleActivity3PresetParameters() { + return new StructExpressionAt(Map.ofEntries( + Map.entry("variant", new ProfileExpression<>(new DiscreteValue(SerializedValue.of("option1")))) + )); + } + @Test void testSchedulingDSL_basic() { @@ -1005,4 +1011,31 @@ class SchedulingDSLCompilationServiceTests { } } + @Test + void testPresetWithEnum() { + final var result = schedulingDSLCompilationService.compileSchedulingGoalDSL( + missionModelService, + PLAN_ID, """ + export default (): Goal => { + return Goal.ActivityRecurrenceGoal({ + activityTemplate: ActivityTemplates.SampleActivity3(ActivityPresets.SampleActivity3["my preset"]), + interval: Temporal.Duration.from({ hours: 1 }) + }) + } + """); + final var expectedGoalDefinition1 = new SchedulingDSL.GoalSpecifier.RecurrenceGoalDefinition( + new SchedulingDSL.ActivityTemplate( + "SampleActivity3", + getSampleActivity3PresetParameters() + ), + Optional.empty(), + HOUR, + false); + if (result instanceof SchedulingDSLCompilationService.SchedulingDSLCompilationResult.Success<SchedulingDSL.GoalSpecifier> r) { + assertEquals(expectedGoalDefinition1, r.value()); + } else if (result instanceof SchedulingDSLCompilationService.SchedulingDSLCompilationResult.Error<SchedulingDSL.GoalSpecifier> r) { + fail(r.toString()); + } + } + }
['scheduler-server/src/test/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTest.java', 'scheduler-server/src/testFixtures/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationServiceTestFixtures.java', 'scheduler-server/src/main/java/gov/nasa/jpl/aerie/scheduler/server/services/TypescriptCodeGenerationService.java', 'scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingDSLCompilationServiceTests.java']
{'.java': 4}
4
4
0
0
4
1,854,682
392,646
50,250
635
3,122
631
54
2
1,641
184
400
59
0
3
2023-05-25T00:04:12
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
9,286
nasa-ammos/aerie/979/859
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/859
https://github.com/NASA-AMMOS/aerie/pull/979
https://github.com/NASA-AMMOS/aerie/pull/979
1
fixes
Stop the ResumableSimulationDriver when it reaches the plan end bound
When using the simulateActivity method, the driver will stop only when the activity finishes which could happen after the plan end.
97b373540109bbd3b1fbc37885326381c3c048cb
96b5e582ac9660a3310c06a53317e183056f1aa5
https://github.com/nasa-ammos/aerie/compare/97b373540109bbd3b1fbc37885326381c3c048cb...96b5e582ac9660a3310c06a53317e183056f1aa5
diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityCreationTemplate.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityCreationTemplate.java index 7060df2c3..d70203d13 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityCreationTemplate.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityCreationTemplate.java @@ -286,41 +286,26 @@ public class ActivityCreationTemplate extends ActivityExpression implements Expr true); final var lastInsertion = history.getLastEvent(); Optional<Duration> computedDuration = Optional.empty(); - if(lastInsertion.isPresent()){ - try { - //remove and insert at the same time to avoid unnecessary potential resimulation. - // - // Current sim: A -> B1 -> C - // Sim at end of next iteration: A -> B2 -> C - //If we would do remove() and then insert(), we would simulation A -> C and then again A -> B2 -> C - facade.removeAndInsertActivitiesFromSimulation(List.of(lastInsertion.get().activity()), List.of(actToSim)); - computedDuration = facade.getActivityDuration(actToSim); - //record insertion: if successful, it will stay in the simulation, otherwise, it'll get deleted at the next iteration + final var toRemove = new ArrayList<SchedulingActivityDirective>(); + lastInsertion.ifPresent(eventWithActivity -> toRemove.add(eventWithActivity.activity())); + try { + facade.removeAndInsertActivitiesFromSimulation(toRemove, List.of(actToSim)); + computedDuration = facade.getActivityDuration(actToSim); + if(computedDuration.isPresent()) { history.add(new EventWithActivity(start, start.plus(computedDuration.get()), actToSim)); - } catch (SimulationFacade.SimulationException e) { - //still need to record so we can remove the activity at the next iteration - history.add(new EventWithActivity(start, null, actToSim)); - } - } else { - try { - facade.simulateActivity(actToSim); - computedDuration = facade.getActivityDuration(actToSim); - if(computedDuration.isPresent()) { - history.add(new EventWithActivity(start, start.plus(computedDuration.get()), actToSim)); - } else{ - logger.debug("No simulation error but activity duration could not be found in simulation, unfinished activity?"); - history.add(new EventWithActivity(start, null, actToSim)); - } - } catch (SimulationFacade.SimulationException e) { - logger.debug("Simulation error while trying to simulate activities: " + e); + } else{ + logger.debug("No simulation error but activity duration could not be found in simulation, likely caused by unfinished activity."); history.add(new EventWithActivity(start, null, actToSim)); } + } catch (SimulationFacade.SimulationException e) { + logger.debug("Simulation error while trying to simulate activities: " + e); + history.add(new EventWithActivity(start, null, actToSim)); } return computedDuration.map(start::plus).orElse(Duration.MAX_VALUE); } }; - return rootFindingHelper(f, history, solved); + return rootFindingHelper(f, history, solved, facade); //CASE 2: activity has a controllable duration } else if (this.type.getDurationType() instanceof DurationType.Controllable dt) { //select earliest start time, STN guarantees satisfiability @@ -421,7 +406,7 @@ public class ActivityCreationTemplate extends ActivityExpression implements Expr } }; - return rootFindingHelper(f, history, solved); + return rootFindingHelper(f, history, solved, facade); } else { throw new UnsupportedOperationException("Unsupported duration type found: " + this.type.getDurationType()); } @@ -450,7 +435,8 @@ public class ActivityCreationTemplate extends ActivityExpression implements Expr private Optional<SchedulingActivityDirective> rootFindingHelper( final EquationSolvingAlgorithms.Function<Duration, HistoryWithActivity> f, final HistoryWithActivity history, - final TaskNetworkAdapter.TNActData solved + final TaskNetworkAdapter.TNActData solved, + final SimulationFacade simulationFacade ) { try { var endInterval = solved.end(); @@ -486,6 +472,13 @@ public class ActivityCreationTemplate extends ActivityExpression implements Expr } catch (EquationSolvingAlgorithms.NoSolutionException e) { logger.debug("No solution"); } + if(!history.events.isEmpty()) { + try { + simulationFacade.removeActivitiesFromSimulation(List.of(history.getLastEvent().get().activity())); + } catch (SimulationFacade.SimulationException e) { + throw new RuntimeException("Exception while simulating original plan after activity insertion failure" ,e); + } + } return Optional.empty(); } diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java index 992c0a2f0..217f8d9ec 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java @@ -251,6 +251,9 @@ public class ResumableSimulationDriver<Model> implements AutoCloseable { // Update batch and increment real time, if necessary. batch = engine.extractNextJobs(Duration.MAX_VALUE); delta = batch.offsetFromStart().minus(curTime); + if(batch.offsetFromStart().longerThan(planDuration)){ + break; + } } lastSimResults = null; } diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java index 9f4e69590..6440c5e27 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java @@ -92,9 +92,6 @@ public class SimulationFacade implements AutoCloseable{ } final var duration = driver.getActivityDuration(planActDirectiveIdToSimulationActivityDirectiveId.get( schedulingActivityDirective.getId())); - if(duration.isEmpty()){ - logger.error("Simulation is probably outdated, check that no activity is removed between simulation and querying"); - } return duration; } @@ -136,10 +133,10 @@ public class SimulationFacade implements AutoCloseable{ final Collection<SchedulingActivityDirective> activitiesToRemove, final Collection<SchedulingActivityDirective> activitiesToAdd) throws SimulationException { - var atLeastOne = false; + var atLeastOneActualRemoval = false; for(final var act: activitiesToRemove){ if(insertedActivities.containsKey(act)){ - atLeastOne = true; + atLeastOneActualRemoval = true; insertedActivities.remove(act); } } @@ -147,16 +144,16 @@ public class SimulationFacade implements AutoCloseable{ for(final var act: activitiesToAdd){ earliestActStartTime = Duration.min(earliestActStartTime, act.startOffset()); } + final var allActivitiesToSimulate = new ArrayList<>(activitiesToAdd); //reset resumable simulation - if(atLeastOne || earliestActStartTime.shorterThan(this.driver.getCurrentSimulationEndTime())){ - final var allActivitiesToSimulate = new ArrayList<>(insertedActivities.keySet()); + if(atLeastOneActualRemoval || earliestActStartTime.shorterThan(this.driver.getCurrentSimulationEndTime())){ + allActivitiesToSimulate.addAll(insertedActivities.keySet()); insertedActivities.clear(); planActDirectiveIdToSimulationActivityDirectiveId.clear(); if (driver != null) driver.close(); driver = new ResumableSimulationDriver<>(missionModel, planningHorizon.getAerieHorizonDuration()); - allActivitiesToSimulate.addAll(activitiesToAdd); - simulateActivities(allActivitiesToSimulate); } + simulateActivities(allActivitiesToSimulate); } public void removeActivitiesFromSimulation(final Collection<SchedulingActivityDirective> activities) diff --git a/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationTest.java b/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationTest.java index cd3737aeb..38f141348 100644 --- a/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationTest.java +++ b/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationTest.java @@ -4,7 +4,7 @@ import gov.nasa.jpl.aerie.merlin.driver.ActivityDirectiveId; import gov.nasa.jpl.aerie.merlin.driver.SerializedActivity; import gov.nasa.jpl.aerie.merlin.driver.engine.SimulationEngine; import gov.nasa.jpl.aerie.merlin.protocol.types.Duration; -import gov.nasa.jpl.aerie.merlin.protocol.types.InstantiationException; +import gov.nasa.jpl.aerie.merlin.protocol.types.SerializedValue; import gov.nasa.jpl.aerie.scheduler.SimulationUtility; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ThreadPoolExecutor; +import static gov.nasa.jpl.aerie.merlin.protocol.types.Duration.MICROSECOND; import static gov.nasa.jpl.aerie.merlin.protocol.types.Duration.SECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -24,6 +25,7 @@ public class ResumableSimulationTest { Duration endOfLastAct; private final Duration tenHours = Duration.of(10, Duration.HOURS); + private final Duration fiveHours = Duration.of(5, Duration.HOURS); @BeforeEach public void init() { @@ -76,6 +78,21 @@ public class ResumableSimulationTest { assertTrue(act2Dur.get().isEqualTo(Duration.of(2, SECONDS))); } + @Test + public void testStopsAtEndOfPlanningHorizon(){ + final var activity = new TestSimulatedActivity( + Duration.of(0, SECONDS), + new SerializedActivity("ControllableDurationActivity", Map.of("duration", SerializedValue.of(tenHours.in(MICROSECOND)))), + new ActivityDirectiveId(1)); + final var fooMissionModel = SimulationUtility.getFooMissionModel(); + resumableSimulationDriver = new ResumableSimulationDriver<>(fooMissionModel, fiveHours); + resumableSimulationDriver.initSimulation(); + resumableSimulationDriver.clearActivitiesInserted(); + resumableSimulationDriver.simulateActivity(activity.start, activity.activity, null, true, activity.id); + assertEquals(fiveHours, resumableSimulationDriver.getCurrentSimulationEndTime()); + assert(resumableSimulationDriver.getSimulationResults(Instant.now()).unfinishedActivities.size() == 1); + } + @Test public void testThreadsReleased() { final var activity = new TestSimulatedActivity( diff --git a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java index 3653cb7d5..ccc775b0f 100644 --- a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java +++ b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java @@ -1774,6 +1774,30 @@ public class SchedulingIntegrationTests { assertEquals(96, results.updatedPlan().size()); } + @Test + void testUnfinishedActivity(){ + final PlanningHorizon PLANNING_HORIZON = new PlanningHorizon( + TimeUtility.fromDOY("2025-090T00:00:00"), + TimeUtility.fromDOY("2025-134T00:00:00")); + final var results = runScheduler( + BANANANATION, + List.of(), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default (): Goal => { + return Goal.ActivityRecurrenceGoal({ + activityTemplate: ActivityTemplates.parent({ + label: "label" + }), + interval: Temporal.Duration.from({ days: 30}) + }) + } + """, true)), PLANNING_HORIZON); + //parent takes much more than 134 - 90 = 44 days to finish + assertEquals(0, results.updatedPlan.size()); + final var goalResult = results.scheduleResults.goalResults().get(new GoalId(0L)); + assertFalse(goalResult.satisfied()); + } + /** * If you passed activities without duration to the scheduler in an initial plan, it would fail */
['scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java', 'scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java', 'scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/constraints/activities/ActivityCreationTemplate.java', 'scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java', 'scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationTest.java']
{'.java': 5}
5
5
0
0
5
1,851,003
391,233
50,081
636
4,190
794
69
3
131
21
24
1
0
0
2023-06-14T18:31:22
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
9,289
nasa-ammos/aerie/650/633
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/633
https://github.com/NASA-AMMOS/aerie/pull/650
https://github.com/NASA-AMMOS/aerie/pull/650
1
fixes
Cannot read field "durationInMicroseconds" because "right" is null
Running a scheduling goal twice in a row for Banananation on develop gives the error: ```text java.lang.NullPointerException: Cannot read field "durationInMicroseconds" because "right" is null at gov.nasa.jpl.aerie.merlin.protocol.types.Duration.add(Duration.java:230) at gov.nasa.jpl.aerie.merlin.protocol.types.Duration.plus(Duration.java:355) at gov.nasa.jpl.aerie.scheduler.model.ActivityInstance.getEndTime(ActivityInstance.java:127) at gov.nasa.jpl.aerie.scheduler.solver.PrioritySolver.satisfyGoalGeneral(PrioritySolver.java:506) at gov.nasa.jpl.aerie.scheduler.solver.PrioritySolver.satisfyGoal(PrioritySolver.java:332) at gov.nasa.jpl.aerie.scheduler.solver.PrioritySolver.solve(PrioritySolver.java:291) at gov.nasa.jpl.aerie.scheduler.solver.PrioritySolver.getNextSolution(PrioritySolver.java:127) at gov.nasa.jpl.aerie.scheduler.worker.services.SynchronousSchedulerAgent.schedule(SynchronousSchedulerAgent.java:198) at gov.nasa.jpl.aerie.scheduler.worker.SchedulerWorkerAppDriver.main(SchedulerWorkerAppDriver.java:91) ``` Here is the goal: ```ts export default (): Goal => Goal.ActivityRecurrenceGoal({ activityTemplate: ActivityTemplates.BakeBananaBread({ temperature: 325.0, tbSugar: 2, glutenFree: false }), interval: Temporal.Duration.from({ hours: 12 }), }); ``` This is causing the UI e2e tests to fail in PR.
91bc4e6d880b3af6a9828aff7bb85bf7644380fa
15ce8f7c0e1468338f5087b2dbc15330fcf1efb0
https://github.com/nasa-ammos/aerie/compare/91bc4e6d880b3af6a9828aff7bb85bf7644380fa...15ce8f7c0e1468338f5087b2dbc15330fcf1efb0
diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/model/ActivityInstance.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/model/ActivityInstance.java index 1ca2eda70..a2f85e713 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/model/ActivityInstance.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/model/ActivityInstance.java @@ -101,6 +101,24 @@ public record ActivityInstance( parameters, topParent); } + private static ActivityInstance of(SchedulingActivityInstanceId id, ActivityType type, Duration start, Duration duration, Map<String, SerializedValue> parameters, SchedulingActivityInstanceId topParent) { + return new ActivityInstance(id, + type, + start, + duration, + parameters, + topParent); + } + + public static ActivityInstance copyOf(ActivityInstance activityInstance, Duration duration){ + return ActivityInstance.of(activityInstance.id, + activityInstance.type, + activityInstance.startTime, + duration, + new HashMap<>(activityInstance.arguments), + activityInstance.topParent); + } + /** * create an activity instance based on the provided one (but adifferent id) * diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java index 49cf30172..a9ce14a97 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java @@ -130,6 +130,28 @@ public class SimulationFacade { } } + /** + * Replaces an activity instance with another, strictly when they have the same id + * @param toBeReplaced the activity to be replaced + * @param replacement the replacement activity + */ + public void replaceActivityFromSimulation(final ActivityInstance toBeReplaced, final ActivityInstance replacement){ + if(toBeReplaced.type() != replacement.type()|| + toBeReplaced.startTime() != replacement.startTime()|| + !(toBeReplaced.arguments().equals(replacement.arguments()))) { + throw new IllegalArgumentException("When replacing an activity, you can only update the duration"); + } + if(!insertedActivities.containsKey(toBeReplaced)){ + throw new IllegalArgumentException("Trying to replace an activity that has not been previously simulated"); + } + final var associated = insertedActivities.get(toBeReplaced); + insertedActivities.remove(toBeReplaced); + insertedActivities.put(replacement, associated); + final var simulationId = this.planActInstanceIdToSimulationActInstanceId.get(toBeReplaced.id()); + this.planActInstanceIdToSimulationActInstanceId.remove(toBeReplaced.id()); + this.planActInstanceIdToSimulationActInstanceId.put(replacement.id(), simulationId); + } + public void simulateActivities(final Collection<ActivityInstance> activities) throws SimulationException { final var activitiesSortedByStartTime = diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java index f9ac857ed..400b8bdd9 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java @@ -188,6 +188,7 @@ public class PrioritySolver implements Solver { } final var allGeneratedActivities = simulationFacade.getAllGeneratedActivities(simulationFacade.getCurrentSimulationEndTime()); processNewGeneratedActivities(allGeneratedActivities); + pullActivityDurationsIfNecessary(); } else{ //update simulation with regard to plan try { @@ -223,9 +224,38 @@ public class PrioritySolver implements Solver { simulationFacade.simulateActivities(plan.getActivities()); final var allGeneratedActivities = simulationFacade.getAllGeneratedActivities(problem.getPlanningHorizon().getEndAerie()); processNewGeneratedActivities(allGeneratedActivities); + pullActivityDurationsIfNecessary(); } } + /** + * For activities that have a null duration (in an initial plan for example) and that have been simulated, we pull the duration and + * replace the original instance with a new instance that includes the duraiton, both in the plan and the simulation facade + */ + public void pullActivityDurationsIfNecessary() { + final var toRemoveFromPlan = new ArrayList<ActivityInstance>(); + final var toAddToPlan = new ArrayList<ActivityInstance>(); + for (final var activity : plan.getActivities()) { + if (activity.duration() == null) { + final var duration = simulationFacade.getActivityDuration(activity); + if (duration.isPresent()) { + final var replacementAct = ActivityInstance.copyOf( + activity, + duration.get() + ); + simulationFacade.replaceActivityFromSimulation(activity, replacementAct); + toAddToPlan.add(replacementAct); + toRemoveFromPlan.add(activity); + generatedActivityInstances = generatedActivityInstances.stream().map(pair -> pair.getLeft().equals(activity) ? Pair.of(replacementAct, pair.getRight()): pair).collect(Collectors.toList()); + generatedActivityInstances = generatedActivityInstances.stream().map(pair -> pair.getRight().equals(activity) ? Pair.of(pair.getLeft(), replacementAct): pair).collect(Collectors.toList()); + } + } + } + + plan.remove(toRemoveFromPlan); + plan.add(toAddToPlan); + } + /** * Filters generated activities and makes sure that simulations are only adding activities and not removing them * @param allNewGeneratedActivities all the generated activities from the last simulation results. diff --git a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java index dd5f3268d..af8e28fee 100644 --- a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java +++ b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java @@ -1348,6 +1348,35 @@ public class SchedulingIntegrationTests { assertEquals(96, results.updatedPlan().size()); } + /** + * If you passed activities without duration to the scheduler in an initial plan, it would fail + */ + @Test + public void testBugDurationInMicroseconds(){ + final var results = runScheduler( + BANANANATION, + List.of(), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default (): Goal => + Goal.ActivityRecurrenceGoal({ + activityTemplate: ActivityTemplates.BakeBananaBread({ temperature: 325.0, tbSugar: 2, glutenFree: false }), + interval: Temporal.Duration.from({ hours: 12 }), + }); + """, true)), + PLANNING_HORIZON); + final var results2 = runScheduler( + BANANANATION, + results.updatedPlan.stream().toList(), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default (): Goal => + Goal.ActivityRecurrenceGoal({ + activityTemplate: ActivityTemplates.BakeBananaBread({ temperature: 325.0, tbSugar: 2, glutenFree: false }), + interval: Temporal.Duration.from({ hours: 12 }), + }); + """, true)), + PLANNING_HORIZON); + assertEquals(8, results.updatedPlan().size()); + } @Test void test_inf_loop(){
['scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/SimulationFacade.java', 'scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java', 'scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/model/ActivityInstance.java', 'scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java']
{'.java': 4}
4
4
0
0
4
1,775,913
376,384
48,659
635
3,627
659
70
3
1,378
82
321
26
0
2
2023-02-02T18:24:00
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
9,285
nasa-ammos/aerie/1098/1092
nasa-ammos
aerie
https://github.com/NASA-AMMOS/aerie/issues/1092
https://github.com/NASA-AMMOS/aerie/pull/1098
https://github.com/NASA-AMMOS/aerie/pull/1098
1
closes
Scheduling Goal Linked to Anchored Activity Failing
### Checked for duplicates No - I haven't checked ### Is this a regression? No - This is a new bug ### Version 1.6.1 ### Describe the bug When running a scheduling goal that is a coexistence goal to link an activity to an anchored activity (already in the plan pre-scheduling) results in a scheduling failure error "The scheduler should not be deleting activity instances". While debugging, when the activity anchoring was removed but the activity timing was kept the same the scheduling goal worked successfully - indicating this error arose from trying to schedule off of an anchored activity type. The plan prior to running the scheduling goal look like: ![image](https://github.com/NASA-AMMOS/aerie/assets/40210944/215ae4b5-e698-4716-83b7-9e32cbd00fcb) With three occurrences of SYS_TCMOTM_Define_MnvrKOZ anchored to occur prior to SYS_TCMOTM_Upd_BurnConditions. **Scheduling Goal:** ``` // Link TCMOTM_Upd_DoDV_Single_Slew_Conds 1.5 hours before TCMOTM_Upd_BurnConditions for RWA maneuver (OR 30mins after SYS_TCMOTM_Define_MnvrKOZ start) // 2 hours for RWA-2 slew maneuver; 1.0 hour for single RCS-2 slew maneuver; 0.75 hours for RWA-4 slew maneuver var linkUpd_DoDV_Single_Slew: Goal = Goal.CoexistenceGoal({ forEach: Spans.ForEachActivity(ActivityTypes.SYS_TCMOTM_Define_MnvrKOZ, mnvr => mnvr.parameters.TCMOTM_SlewType.equal("RWA_2").and(mnvr.window()).spans()).windows(), activityTemplate:ActivityTemplates.TCMOTM_Upd_DoDV_Sigle_Slew_Conds({ TCMOTM_DoDV_Single_Slew_Dur: {quantity: 90, units: "MINUTES"} // 1.5 hrs }), startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes: 30 })) }).and(Goal.CoexistenceGoal({ forEach: Spans.ForEachActivity(ActivityTypes.SYS_TCMOTM_Define_MnvrKOZ, gen2 => gen2.parameters.TCMOTM_SlewType.equal("RWA_4").and(gen2.window()).spans()).windows(), activityTemplate:ActivityTemplates.TCMOTM_Upd_DoDV_Sigle_Slew_Conds({ TCMOTM_DoDV_Single_Slew_Dur: {quantity: 45, units: "MINUTES"} // 0.75 hrs }), startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes: 30 })) })).and(Goal.CoexistenceGoal({ forEach: Spans.ForEachActivity(ActivityTypes.SYS_TCMOTM_Define_MnvrKOZ, gen3 => gen3.parameters.TCMOTM_SlewType.equal("RCS_2").and(gen3.window()).spans()).windows(), activityTemplate:ActivityTemplates.TCMOTM_Upd_DoDV_Sigle_Slew_Conds({ TCMOTM_DoDV_Single_Slew_Dur: {quantity: 60, units: "MINUTES"} // 1 hr }), startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes: 30 })) })) export default (): Goal => { return linkUpd_DoDV_Single_Slew } ``` ### Reproduction To reproduce this error: 1. Place two activity types into a plan manually - one anchored off of the other 2. Develop a simple scheduling goal that links an activity to the _anchored_ activity type in the plan 3. Observe the scheduling results/errors that come up as a result of the scheduling run. ### Logs ```shell gov.nasa.jpl.aerie.scheduler.server.exceptions.ResultsProtocolFailure: The scheduler should not be deleting activity instances at gov.nasa.jpl.aerie.scheduler.worker.services.SynchronousSchedulerAgent.storeFinalPlan(SynchronousSchedulerAgent.java:560) at gov.nasa.jpl.aerie.scheduler.worker.services.SynchronousSchedulerAgent.schedule(SynchronousSchedulerAgent.java:222) at gov.nasa.jpl.aerie.scheduler.worker.SchedulerWorkerAppDriver.main(SchedulerWorkerAppDriver.java:91) Caused by: gov.nasa.jpl.aerie.scheduler.server.services.PlanServiceException: The scheduler should not be deleting activity instances at gov.nasa.jpl.aerie.scheduler.server.services.GraphQLMerlinService.updatePlanActivityDirectives(GraphQLMerlinService.java:414) at gov.nasa.jpl.aerie.scheduler.worker.services.SynchronousSchedulerAgent.storeFinalPlan(SynchronousSchedulerAgent.java:549) ... 2 more ``` ### System Info ```shell Google Chrome browser, macOS Ventura 13.3.1 ``` ### Severity Minor
0ab198d46536d883fb4b8115d40db57e7385cc5f
4622ee04578e70ec7312cd930f3e108d4ab9faf4
https://github.com/nasa-ammos/aerie/compare/0ab198d46536d883fb4b8115d40db57e7385cc5f...4622ee04578e70ec7312cd930f3e108d4ab9faf4
diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java index 951535d5e..a507c7492 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java @@ -28,7 +28,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; public class ResumableSimulationDriver<Model> implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(ResumableSimulationDriver.class); @@ -223,9 +222,11 @@ public class ResumableSimulationDriver<Model> implements AutoCloseable { // Get all activities as close as possible to absolute time, then schedule all activities. // Using HashMap explicitly because it allows `null` as a key. // `null` key means that an activity is not waiting on another activity to finish to know its start time - final HashMap<ActivityDirectiveId, List<Pair<ActivityDirectiveId, Duration>>> resolved = new StartOffsetReducer( + HashMap<ActivityDirectiveId, List<Pair<ActivityDirectiveId, Duration>>> resolved = new StartOffsetReducer( planDuration, schedule).compute(); + // Filter out activities that are before the plan start + resolved = StartOffsetReducer.filterOutNegativeStartOffset(resolved); scheduleActivities( schedule, diff --git a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java index c39ae42f1..944e6a1a1 100644 --- a/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java +++ b/scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java @@ -133,10 +133,6 @@ public class PrioritySolver implements Solver { public record InsertActivityResult(boolean success, List<SchedulingActivityDirective> activitiesInserted){} - private InsertActivityResult checkAndInsertAct(SchedulingActivityDirective act){ - return checkAndInsertActs(List.of(act)); - } - /** * Tries to insert a collection of activity instances in plan. Simulates each of the activity and checks whether the expected * duration is equal to the simulated duration. @@ -220,10 +216,7 @@ public class PrioritySolver implements Solver { //turn off simulation checking for initial plan contents (must accept user input regardless) final var prevCheckFlag = this.checkSimBeforeInsertingActivities; this.checkSimBeforeInsertingActivities = false; - problem.getInitialPlan().getActivitiesByTime().stream() - .filter( act -> (act.startOffset()==null) - || problem.getPlanningHorizon().contains( act.startOffset() ) ) - .forEach(this::checkAndInsertAct); + checkAndInsertActs(problem.getInitialPlan().getActivitiesByTime()); this.checkSimBeforeInsertingActivities = prevCheckFlag; evaluation = new Evaluation(); diff --git a/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java b/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java index 06c9db498..1d76ac160 100644 --- a/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java +++ b/scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java @@ -5,6 +5,7 @@ import com.google.common.truth.Correspondence; import gov.nasa.jpl.aerie.constraints.time.Interval; import gov.nasa.jpl.aerie.constraints.time.Windows; import gov.nasa.jpl.aerie.constraints.tree.WindowsWrapperExpression; +import gov.nasa.jpl.aerie.merlin.driver.MissionModel; import gov.nasa.jpl.aerie.merlin.protocol.types.Duration; import gov.nasa.jpl.aerie.scheduler.constraints.activities.ActivityCreationTemplate; import gov.nasa.jpl.aerie.scheduler.constraints.activities.ActivityExpression; @@ -31,7 +32,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class PrioritySolverTest { private static PrioritySolver makeEmptyProblemSolver() { - return new PrioritySolver(new Problem(null, h, null, null)); + MissionModel<?> bananaMissionModel = SimulationUtility.getBananaMissionModel(); + return new PrioritySolver( + new Problem( + bananaMissionModel, + h, + new SimulationFacade(h, bananaMissionModel), + SimulationUtility.getBananaSchedulerModel())); } private static PrioritySolver makeProblemSolver(Problem problem) { diff --git a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java index ccc775b0f..3c2afe168 100644 --- a/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java +++ b/scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java @@ -1858,13 +1858,17 @@ public class SchedulingIntegrationTests { assertEquals(2, results.updatedPlan().size()); } + /** + * Test that the scheduler can correctly place activities off of activities anchored to start at + * the end of another activity. + */ @Test - void testRelativeActivityPlanSimpleCoexistenceGoalEnd() { + void testRelativeActivityPlanZeroStartOffsetEnd() { /* - Start with a plan with B -> A + Start with a plan with B anchored to end of A Goal: for each B, place a C And make sure that C ends up in the right place - */ + */ final var activityDuration = Duration.of(1, Duration.HOUR); final var results = runScheduler( BANANANATION, @@ -1938,10 +1942,14 @@ public class SchedulingIntegrationTests { assertEquals(Duration.of(125, Duration.MINUTES), peelBanana.startOffset()); } + /** + * Test that the scheduler can correctly place activities off of activities anchored to start + * at the same time of another activity. + */ @Test - void testRelativeActivityPlanSimpleCoexistenceGoalStart() { + void testRelativeActivityPlanZeroStartOffsetStart() { /* - Start with a plan with B -> A + Start with a plan with B anchored to start of A Goal: for each B, place a C And make sure that C ends up in the right place */ @@ -2018,6 +2026,293 @@ public class SchedulingIntegrationTests { assertEquals(Duration.of(65, Duration.MINUTES), peelBanana.startOffset()); } + /** + * Test that the scheduler can correctly place activities off of activities anchored to start before another activity. + */ + @Test + void testRelativeActivityPlanNegativeStartOffsetStart() { + /* + Start with a plan with B anchored to A + Goal: for each B, place a C + And make sure that C ends up in the right place + */ + final var activityDuration = Duration.of(1, Duration.HOUR); + final var tenMinutes = Duration.of(10, MINUTES); + final var results = runScheduler( + BANANANATION, + Map.of( + new ActivityDirectiveId(1L), + new ActivityDirective( + tenMinutes, + "DurationParameterActivity", + Map.of( + "duration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + null, + true), + new ActivityDirectiveId(2L), + new ActivityDirective( + Duration.of(-5, MINUTES), + "GrowBanana", + Map.of( + "quantity", SerializedValue.of(1), + "growingDuration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + new ActivityDirectiveId(1L), + true)), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default () => Goal.CoexistenceGoal({ + forEach: ActivityExpression.ofType(ActivityTypes.GrowBanana), + activityTemplate: ActivityTemplates.PeelBanana({peelDirection: "fromStem"}), + startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes : 5})) + }) + """, true)), + PLANNING_HORIZON); + + assertEquals(1, results.scheduleResults.goalResults().size()); + final var goalResult = results.scheduleResults.goalResults().get(new GoalId(0L)); + + assertTrue(goalResult.satisfied()); + assertEquals(1, goalResult.createdActivities().size()); + for (final var activity : goalResult.createdActivities()) { + assertNotNull(activity); + } + for (final var activity : goalResult.satisfyingActivities()) { + assertNotNull(activity); + } + + final var planByActivityType = partitionByActivityType(results.updatedPlan()); + final var peelBananas = planByActivityType.get("PeelBanana"); + final var growBananas = planByActivityType.get("GrowBanana"); + final var durationParamActivities = planByActivityType.get("DurationParameterActivity"); + + assertEquals(1, peelBananas.size()); + assertEquals(1, growBananas.size()); + assertEquals(1, durationParamActivities.size()); + final var peelBanana = peelBananas.iterator().next(); + final var growBanana = growBananas.iterator().next(); + final var durationParamActivity = durationParamActivities.iterator().next(); + + assertEquals(tenMinutes, durationParamActivity.startOffset()); + assertEquals(Duration.of(-5, MINUTES), growBanana.startOffset()); + assertTrue(growBanana.anchoredToStart()); + + assertEquals(SerializedValue.of(1), growBanana.serializedActivity().getArguments().get("quantity")); + assertEquals(tenMinutes, peelBanana.startOffset()); + assertEquals(SerializedValue.of("fromStem"), peelBanana.serializedActivity().getArguments().get("peelDirection")); + } + + /** + * Test that the scheduler can correctly place activities off of activities anchored to start after the start + * of another activity. + */ + @Test + void testRelativeActivityPlanPositiveStartOffsetStart() { + /* + Start with a plan with B anchored to A + Goal: for each B, place a C + And make sure that C ends up in the right place + */ + final var activityDuration = Duration.of(1, Duration.HOUR); + final var tenMinutes = Duration.of(10, MINUTES); + final var results = runScheduler( + BANANANATION, + Map.of( + new ActivityDirectiveId(1L), + new ActivityDirective( + Duration.ZERO, + "DurationParameterActivity", + Map.of( + "duration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + null, + true), + new ActivityDirectiveId(2L), + new ActivityDirective( + tenMinutes, + "GrowBanana", + Map.of( + "quantity", SerializedValue.of(1), + "growingDuration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + new ActivityDirectiveId(1L), + true)), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default () => Goal.CoexistenceGoal({ + forEach: ActivityExpression.ofType(ActivityTypes.GrowBanana), + activityTemplate: ActivityTemplates.PeelBanana({peelDirection: "fromStem"}), + startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes : 5})) + }) + """, true)), + PLANNING_HORIZON); + + assertEquals(1, results.scheduleResults.goalResults().size()); + final var goalResult = results.scheduleResults.goalResults().get(new GoalId(0L)); + + assertTrue(goalResult.satisfied()); + assertEquals(1, goalResult.createdActivities().size()); + for (final var activity : goalResult.createdActivities()) { + assertNotNull(activity); + } + for (final var activity : goalResult.satisfyingActivities()) { + assertNotNull(activity); + } + + final var planByActivityType = partitionByActivityType(results.updatedPlan()); + final var peelBananas = planByActivityType.get("PeelBanana"); + final var growBananas = planByActivityType.get("GrowBanana"); + final var durationParamActivities = planByActivityType.get("DurationParameterActivity"); + + assertEquals(1, peelBananas.size()); + assertEquals(1, growBananas.size()); + assertEquals(1, durationParamActivities.size()); + final var peelBanana = peelBananas.iterator().next(); + final var growBanana = growBananas.iterator().next(); + final var durationParamActivity = durationParamActivities.iterator().next(); + + assertEquals(Duration.ZERO, durationParamActivity.startOffset()); + + assertEquals(tenMinutes, growBanana.startOffset()); + assertEquals(SerializedValue.of(1), growBanana.serializedActivity().getArguments().get("quantity")); + + assertEquals(Duration.of(15, Duration.MINUTES), peelBanana.startOffset()); + assertEquals(SerializedValue.of("fromStem"), peelBanana.serializedActivity().getArguments().get("peelDirection")); + } + + /** + * Test that the scheduler can correctly place activities off of activities anchored to start after the start + * of another activity. + */ + @Test + void testRelativeActivityPlanPositiveEndOffsetEnd() { + /* + Start with a plan with B anchored to A + Goal: for each B, place a C + And make sure that C ends up in the right place + */ + final var activityDuration = Duration.of(1, Duration.HOUR); + final var tenMinutes = Duration.of(10, MINUTES); + final var results = runScheduler( + BANANANATION, + Map.of( + new ActivityDirectiveId(1L), + new ActivityDirective( + Duration.ZERO, + "DurationParameterActivity", + Map.of( + "duration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + null, + true), + new ActivityDirectiveId(2L), + new ActivityDirective( + tenMinutes, + "GrowBanana", + Map.of( + "quantity", SerializedValue.of(1), + "growingDuration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + new ActivityDirectiveId(1L), + false)), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default () => Goal.CoexistenceGoal({ + forEach: ActivityExpression.ofType(ActivityTypes.GrowBanana), + activityTemplate: ActivityTemplates.PeelBanana({peelDirection: "fromStem"}), + startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes : 5})) + }) + """, true)), + PLANNING_HORIZON); + + assertEquals(1, results.scheduleResults.goalResults().size()); + final var goalResult = results.scheduleResults.goalResults().get(new GoalId(0L)); + + assertTrue(goalResult.satisfied()); + assertEquals(1, goalResult.createdActivities().size()); + for (final var activity : goalResult.createdActivities()) { + assertNotNull(activity); + } + for (final var activity : goalResult.satisfyingActivities()) { + assertNotNull(activity); + } + + final var planByActivityType = partitionByActivityType(results.updatedPlan()); + final var peelBananas = planByActivityType.get("PeelBanana"); + final var growBananas = planByActivityType.get("GrowBanana"); + final var durationParamActivities = planByActivityType.get("DurationParameterActivity"); + + assertEquals(1, peelBananas.size()); + assertEquals(1, growBananas.size()); + assertEquals(1, durationParamActivities.size()); + final var peelBanana = peelBananas.iterator().next(); + final var growBanana = growBananas.iterator().next(); + final var durationParamActivity = durationParamActivities.iterator().next(); + + assertEquals(Duration.ZERO, durationParamActivity.startOffset()); + + assertEquals(Duration.of(10, MINUTES), growBanana.startOffset()); + assertFalse(growBanana.anchoredToStart()); + assertEquals(SerializedValue.of(1), growBanana.serializedActivity().getArguments().get("quantity")); + + assertEquals(Duration.of(75, Duration.MINUTES), peelBanana.startOffset()); + assertEquals(SerializedValue.of("fromStem"), peelBanana.serializedActivity().getArguments().get("peelDirection")); + } + + /** + * Test that the scheduler does not schedule activities based on activities which are outside plan bounds + */ + @Test + void testDontScheduleFromOutsidePlanBounds(){ + final var activityDuration = Duration.of(1, Duration.HOUR); + final var results = runScheduler( + BANANANATION, + Map.of( + // Activity Before Plan Start + new ActivityDirectiveId(1L), + new ActivityDirective( + Duration.of(-10, MINUTES), + "GrowBanana", + Map.of( + "quantity", SerializedValue.of(1), + "growingDuration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + null, + true), + // Activity Anchored to run after Plan End + new ActivityDirectiveId(2L), + new ActivityDirective( + Duration.of(10, MINUTES), + "GrowBanana", + Map.of( + "quantity", SerializedValue.of(2), + "growingDuration", SerializedValue.of(activityDuration.in(Duration.MICROSECONDS))), + null, + false)), + List.of(new SchedulingGoal(new GoalId(0L), """ + export default () => Goal.CoexistenceGoal({ + forEach: ActivityExpression.ofType(ActivityTypes.GrowBanana), + activityTemplate: ActivityTemplates.PeelBanana({peelDirection: "fromStem"}), + startsAt: TimingConstraint.singleton(WindowProperty.START).plus(Temporal.Duration.from({ minutes : 5})) + }) + """, true)), + PLANNING_HORIZON); + + assertEquals(1, results.scheduleResults.goalResults().size()); + final var goalResult = results.scheduleResults.goalResults().get(new GoalId(0L)); + + // The goal is satisfied, but placed no activities, + // because all activities it could've matched on are outside the plan bounds + assertTrue(goalResult.satisfied()); + assertEquals(0, goalResult.createdActivities().size()); + + final var planByActivityType = partitionByActivityType(results.updatedPlan()); + final var growBananas = planByActivityType.get("GrowBanana"); + final var gbIterator = growBananas.iterator(); + + assertNull(planByActivityType.get("PeelBanana")); + assertEquals(2, growBananas.size()); + + final var growBanana1 = gbIterator.next(); + assertEquals(Duration.of(-10, MINUTES), growBanana1.startOffset()); + assertEquals(SerializedValue.of(1), growBanana1.serializedActivity().getArguments().get("quantity")); + + final var growBanana2 = gbIterator.next(); + assertEquals(Duration.of(10, MINUTES), growBanana2.startOffset()); + assertEquals(SerializedValue.of(2), growBanana2.serializedActivity().getArguments().get("quantity")); + } + /** * Test the option to turn off simulation in between goals. *
['scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/solver/PrioritySolver.java', 'scheduler-driver/src/main/java/gov/nasa/jpl/aerie/scheduler/simulation/ResumableSimulationDriver.java', 'scheduler-driver/src/test/java/gov/nasa/jpl/aerie/scheduler/PrioritySolverTest.java', 'scheduler-worker/src/test/java/gov/nasa/jpl/aerie/scheduler/worker/services/SchedulingIntegrationTests.java']
{'.java': 4}
4
4
0
0
4
1,908,091
402,877
51,585
661
843
172
14
2
4,055
345
1,062
84
1
3
2023-08-17T21:54:49
46
Java
{'Java': 3072373, 'TypeScript': 826910, 'PLpgSQL': 504470, 'HCL': 21353, 'Python': 10525, 'Dockerfile': 3010, 'JavaScript': 2717, 'Shell': 1998, 'Makefile': 153}
MIT License
1,197
microsoftgraph/msgraph-sdk-java-core/219/217
microsoftgraph
msgraph-sdk-java-core
https://github.com/microsoftgraph/msgraph-sdk-java-core/issues/217
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/219
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/219
2
fixes
Serialization of TimeOfDay in update mailboxSettings.workingHours.startTime
Greetings! I tried to update the user `mailboxSetting.workingHours.startTime` but ended up with an error. See also https://github.com/microsoftgraph/msgraph-sdk-java/issues/168#issuecomment-852027168. Code: ``` GraphServiceClient<Request> client = connector.getGraphClient(); MailboxSettings mailboxSettings = new MailboxSettings(); mailboxSettings.workingHours = new WorkingHours(); mailboxSettings.workingHours.startTime = TimeOfDay.parse("08:30:00"); client.customRequest("/users/6947272f-1908-49d2-b610-55418494e15f/mailboxSettings", MailboxSettings.class) .buildRequest() .patch(mailboxSettings); ``` ### Expected behavior The update should be working as the mailboxSettings in general can be updated (other fields update successful). See also: https://docs.microsoft.com/en-us/graph/api/resources/workinghours?view=graph-rest-1.0 ### Actual behavior Error occurs: ``` Exception in thread "main" com.microsoft.graph.http.GraphServiceException: Error code: RequestBodyRead Error message: An unexpected 'StartObject' node was found for property named 'startTime' when reading from the JSON reader. A 'PrimitiveValue' node was expected. PATCH https://graph.microsoft.com/v1.0/users/6947272f-1908-49d2-b610-55418494e15f/mailboxSettings SdkVersion : graph-java/v3.5.0 [...] 400 : Bad Request [...] [Some information was truncated for brevity, enable debug logging for more details] at com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:419) at com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:378) at com.microsoft.graph.http.CoreHttpProvider.handleErrorResponse(CoreHttpProvider.java:503) at com.microsoft.graph.http.CoreHttpProvider.processResponse(CoreHttpProvider.java:432) at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal(CoreHttpProvider.java:398) at com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:220) at com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:197) at com.microsoft.graph.http.BaseRequest.send(BaseRequest.java:332) at com.microsoft.graph.http.CustomRequest.patch(CustomRequest.java:129) ... ``` ### Steps to reproduce the behavior Sdk version: 3.5 Java version: 8 Call above code on ms dev program tenant with an existing user that has assigned a license. ### Additional information The issue seems to be connected to https://github.com/microsoftgraph/msgraph-sdk-java/issues/168. The TimeOfDay serializer is probably still missing in GsonFactory. The sdk is probably serializing the TimeOfDay as json object instead of string. [AB#9658](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/9658)
2ce705b536a49935afab77622c70bd8860fcfa42
3925b79a683dfc45af225cb6fe7176db552fdcdd
https://github.com/microsoftgraph/msgraph-sdk-java-core/compare/2ce705b536a49935afab77622c70bd8860fcfa42...3925b79a683dfc45af225cb6fe7176db552fdcdd
diff --git a/src/main/java/com/microsoft/graph/serializer/GsonFactory.java b/src/main/java/com/microsoft/graph/serializer/GsonFactory.java index d4da626..4a040cc 100644 --- a/src/main/java/com/microsoft/graph/serializer/GsonFactory.java +++ b/src/main/java/com/microsoft/graph/serializer/GsonFactory.java @@ -256,6 +256,15 @@ final class GsonFactory { } }; + final JsonSerializer<TimeOfDay> timeOfDayJsonSerializer = new JsonSerializer<TimeOfDay>() { + @Override + public JsonElement serialize(final TimeOfDay src, + final Type typeOfSrc, + final JsonSerializationContext context) { + return new JsonPrimitive(src.toString()); + } + }; + final JsonDeserializer<Boolean> booleanJsonDeserializer = new JsonDeserializer<Boolean>() { @Override public Boolean deserialize(final JsonElement json, @@ -344,6 +353,7 @@ final class GsonFactory { .registerTypeHierarchyAdapter(BaseCollectionPage.class, collectionPageDeserializer) .registerTypeHierarchyAdapter(BaseCollectionResponse.class, collectionResponseDeserializer) .registerTypeAdapter(TimeOfDay.class, timeOfDayJsonDeserializer) + .registerTypeAdapter(TimeOfDay.class, timeOfDayJsonSerializer) .registerTypeAdapterFactory(new FallbackTypeAdapterFactory(logger)) .create(); } diff --git a/src/test/java/com/microsoft/graph/serializer/TimeOfDayTests.java b/src/test/java/com/microsoft/graph/serializer/TimeOfDayTests.java index 8a3f623..288c295 100644 --- a/src/test/java/com/microsoft/graph/serializer/TimeOfDayTests.java +++ b/src/test/java/com/microsoft/graph/serializer/TimeOfDayTests.java @@ -1,10 +1,12 @@ package com.microsoft.graph.serializer; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; import com.microsoft.graph.core.TimeOfDay; +import com.microsoft.graph.logger.ILogger; public class TimeOfDayTests { @@ -43,5 +45,11 @@ public class TimeOfDayTests { assertEquals(30, time.getMinute()); assertEquals(44, time.getSecond()); } - + @Test + public void testTimeOfDaySerialization() throws Exception { + final TimeOfDay time = new TimeOfDay(12, 30, 44); + final ILogger logger = mock(ILogger.class); + final ISerializer serializer = new DefaultSerializer(logger); + assertEquals("\\"12:30:44\\"", serializer.serializeObject(time)); + } }
['src/test/java/com/microsoft/graph/serializer/TimeOfDayTests.java', 'src/main/java/com/microsoft/graph/serializer/GsonFactory.java']
{'.java': 2}
2
2
0
0
2
442,262
86,928
11,648
102
502
75
10
1
2,844
206
632
58
5
2
2021-06-01T18:48:51
42
Java
{'Java': 629959, 'PowerShell': 5185}
MIT License
1,198
microsoftgraph/msgraph-sdk-java-core/215/209
microsoftgraph
msgraph-sdk-java-core
https://github.com/microsoftgraph/msgraph-sdk-java-core/issues/209
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/215
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/215
2
fixes
Unable to change the loglevel for graph sdk
Hi Team, I have enabled the DEBUG log using below code to debug the below error message: Error message: Invalid batch payload format. POST https://graph.microsoft.com/v1.0/$batch SdkVersion : graph-java/v3.5.0 [...] 400 : Bad Request [...] [Some information was truncated for brevity, enable debug logging for more details] Now I have enabled the debug mode using below code, GraphServiceClient graphClient = graphClientBuilder.buildClient(); graphClient.getLogger().setLoggingLevel(LoggerLevel.DEBUG); Now I am executing the batch request with 3.5.0 java SDK. I am not getting the debug statements. On debuging the source code i found BatchResponseStep class hard coded the verbose parameter with false by default. Please guide me to enable verbose logging for batch requests. Code snippet: throw GraphServiceException.createFromResponse("", "", new ArrayList<>(), "", headers, "", status, error, **false**); [AB#9533](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/9533)
b5e0deb6ffd9ed75a2225a51b49f53cf68045bbc
96ac49f93bda13862fe914b2a1e737f907f59e21
https://github.com/microsoftgraph/msgraph-sdk-java-core/compare/b5e0deb6ffd9ed75a2225a51b49f53cf68045bbc...96ac49f93bda13862fe914b2a1e737f907f59e21
diff --git a/src/main/java/com/microsoft/graph/content/BatchResponseStep.java b/src/main/java/com/microsoft/graph/content/BatchResponseStep.java index feb1d13..6597613 100644 --- a/src/main/java/com/microsoft/graph/content/BatchResponseStep.java +++ b/src/main/java/com/microsoft/graph/content/BatchResponseStep.java @@ -33,6 +33,9 @@ import com.google.gson.annotations.SerializedName; import com.microsoft.graph.http.GraphErrorResponse; import com.microsoft.graph.http.GraphFatalServiceException; import com.microsoft.graph.http.GraphServiceException; +import com.microsoft.graph.logger.ILogger; +import com.microsoft.graph.logger.LoggerLevel; +import com.microsoft.graph.serializer.DefaultSerializer; import com.microsoft.graph.serializer.ISerializer; /** Response for the batch step */ @@ -61,7 +64,13 @@ public class BatchResponseStep<T> extends BatchStep<T> { final GraphErrorResponse error = serializer.deserializeObject((JsonElement)body, GraphErrorResponse.class); if(error == null || error.error == null) { return serializer.deserializeObject((JsonElement)body, resultClass); - } else - throw GraphServiceException.createFromResponse("", "", new ArrayList<>(), "", headers, "", status, error, false); + } else { + boolean verboseError = false; + if(serializer instanceof DefaultSerializer) { + final ILogger logger = ((DefaultSerializer)serializer).getLogger(); + verboseError = logger != null && logger.getLoggingLevel() == LoggerLevel.DEBUG; + } + throw GraphServiceException.createFromResponse("", "", new ArrayList<>(), "", headers, "", status, error, verboseError); + } } } diff --git a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java index bf520e2..ec9f799 100644 --- a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java @@ -393,7 +393,6 @@ public class DefaultSerializer implements ISerializer { * * @return a logger */ - @VisibleForTesting @Nullable public ILogger getLogger() { return logger; diff --git a/src/test/java/com/microsoft/graph/content/BatchResponseContentTest.java b/src/test/java/com/microsoft/graph/content/BatchResponseContentTest.java index 6414b72..a39b925 100644 --- a/src/test/java/com/microsoft/graph/content/BatchResponseContentTest.java +++ b/src/test/java/com/microsoft/graph/content/BatchResponseContentTest.java @@ -14,7 +14,9 @@ import java.util.Iterator; import com.google.gson.JsonElement; import com.microsoft.graph.http.GraphErrorResponse; import com.microsoft.graph.http.GraphServiceException; +import com.microsoft.graph.logger.DefaultLogger; import com.microsoft.graph.logger.ILogger; +import com.microsoft.graph.logger.LoggerLevel; import com.microsoft.graph.serializer.DefaultSerializer; import com.microsoft.graph.serializer.ISerializer; @@ -114,4 +116,52 @@ public class BatchResponseContentTest { } else fail("batch response was null"); } + @Test + public void includeVerboseInformation() { + String responsebody = "{\\"responses\\":[{\\"id\\":\\"1\\",\\"status\\":400,\\"headers\\":{\\"Cache-Control\\":\\"no-cache\\",\\"x-ms-resource-unit\\":\\"1\\",\\"Content-Type\\":\\"application/json\\"},\\"body\\":{\\"error\\":{\\"code\\":\\"Request_BadRequest\\",\\"message\\":\\"Avalueisrequiredforproperty'displayName'ofresource'User'.\\",\\"innerError\\":{\\"date\\":\\"2021-02-02T19:19:38\\",\\"request-id\\":\\"408b8e64-4047-4c97-95b6-46e9f212ab48\\",\\"client-request-id\\":\\"102910da-260c-3028-0fb3-7d6903a02622\\"}}}}]}"; + ISerializer serializer = new DefaultSerializer(new DefaultLogger() {{ + setLoggingLevel(LoggerLevel.DEBUG); + }}); + BatchResponseContent batchresponse = serializer.deserializeObject(responsebody, BatchResponseContent.class); + if(batchresponse != null) { + if(batchresponse.responses != null) // this is done by the batch request in the fluent API + for(final BatchResponseStep<?> step : batchresponse.responses) { + step.serializer = serializer; + } + try { + batchresponse.getResponseById("1").getDeserializedBody(BatchRequestContent.class); + } catch(GraphServiceException ex) { + final GraphErrorResponse response = ex.getError(); + assertNotNull(response); + assertNotNull(response.error); + assertNotNull(response.error.message); + assertEquals(ex.getMessage(true), ex.getMessage()); + } + } else + fail("batch response was null"); + } + @Test + public void doesNotIncludeVerboseInformation() { + String responsebody = "{\\"responses\\":[{\\"id\\":\\"1\\",\\"status\\":400,\\"headers\\":{\\"Cache-Control\\":\\"no-cache\\",\\"x-ms-resource-unit\\":\\"1\\",\\"Content-Type\\":\\"application/json\\"},\\"body\\":{\\"error\\":{\\"code\\":\\"Request_BadRequest\\",\\"message\\":\\"Avalueisrequiredforproperty'displayName'ofresource'User'.\\",\\"innerError\\":{\\"date\\":\\"2021-02-02T19:19:38\\",\\"request-id\\":\\"408b8e64-4047-4c97-95b6-46e9f212ab48\\",\\"client-request-id\\":\\"102910da-260c-3028-0fb3-7d6903a02622\\"}}}}]}"; + ISerializer serializer = new DefaultSerializer(new DefaultLogger() {{ + setLoggingLevel(LoggerLevel.ERROR); + }}); + BatchResponseContent batchresponse = serializer.deserializeObject(responsebody, BatchResponseContent.class); + if(batchresponse != null) { + if(batchresponse.responses != null) // this is done by the batch request in the fluent API + for(final BatchResponseStep<?> step : batchresponse.responses) { + step.serializer = serializer; + } + try { + batchresponse.getResponseById("1").getDeserializedBody(BatchRequestContent.class); + } catch(GraphServiceException ex) { + final GraphErrorResponse response = ex.getError(); + assertNotNull(response); + assertNotNull(response.error); + assertNotNull(response.error.message); + assertEquals(ex.getMessage(false), ex.getMessage()); + } + } else + fail("batch response was null"); + } }
['src/main/java/com/microsoft/graph/content/BatchResponseStep.java', 'src/test/java/com/microsoft/graph/content/BatchResponseContentTest.java', 'src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java']
{'.java': 3}
3
3
0
0
3
441,874
86,881
11,643
102
774
136
14
2
1,052
121
245
24
2
0
2021-05-26T16:56:04
42
Java
{'Java': 629959, 'PowerShell': 5185}
MIT License
1,202
microsoftgraph/msgraph-sdk-java-core/188/178
microsoftgraph
msgraph-sdk-java-core
https://github.com/microsoftgraph/msgraph-sdk-java-core/issues/178
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/188
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/188
1
fixes
Canary url is missing in the authentication provider
https://www.github.com/microsoftgraph/msgraph-sdk-java-core/tree/dev/src%2Fmain%2Fjava%2Fcom%2Fmicrosoft%2Fgraph%2Fauthentication%2FBaseAuthenticationProvider.java https://github.com/microsoftgraph/msgraph-sdk-javascript/pull/413
46f445c2748e783e7b7fc97a3594971f3a0e3043
72f044bac2f36c418fa01372d6c54ca5c3d6eab7
https://github.com/microsoftgraph/msgraph-sdk-java-core/compare/46f445c2748e783e7b7fc97a3594971f3a0e3043...72f044bac2f36c418fa01372d6c54ca5c3d6eab7
diff --git a/src/main/java/com/microsoft/graph/authentication/BaseAuthenticationProvider.java b/src/main/java/com/microsoft/graph/authentication/BaseAuthenticationProvider.java index 4b73a21..78a596a 100644 --- a/src/main/java/com/microsoft/graph/authentication/BaseAuthenticationProvider.java +++ b/src/main/java/com/microsoft/graph/authentication/BaseAuthenticationProvider.java @@ -11,7 +11,7 @@ import javax.annotation.Nonnull; * Provides basic common methods for all authentication providers */ public abstract class BaseAuthenticationProvider implements IAuthenticationProvider { - private static final HashSet<String> validGraphHostNames = new HashSet<>(Arrays.asList("graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn")); + private static final HashSet<String> validGraphHostNames = new HashSet<>(Arrays.asList("graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn", "canary.graph.microsoft.com")); /** * Determines whether a request should be authenticated or not based on it's url. * If you're implementing a custom provider, call that method first before getting the token
['src/main/java/com/microsoft/graph/authentication/BaseAuthenticationProvider.java']
{'.java': 1}
1
1
0
0
1
441,049
86,739
11,631
102
473
105
2
1
230
2
65
3
2
0
2021-04-13T15:27:31
42
Java
{'Java': 629959, 'PowerShell': 5185}
MIT License
1,203
microsoftgraph/msgraph-sdk-java-core/163/160
microsoftgraph
msgraph-sdk-java-core
https://github.com/microsoftgraph/msgraph-sdk-java-core/issues/160
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/163
https://github.com/microsoftgraph/msgraph-sdk-java-core/pull/163
2
fixes
RetryHandler does not retry in case of 429 error
<!-- Read me before you submit this issue First off, thank you for taking the time to open this issue! We do appreciate it. Please bear with us if we don't get to this right away. If this is a question about the Microsoft Graph service API, or a question about how to use this SDK, please post your question to StackOverflow with the [microsoftgraph] tag. https://stackoverflow.com/questions/tagged/microsoft-graph This repo is for the Microsoft Graph Java SDK. Issues opened in this repo should only target this SDK. Before you open this issue, did you: - Search the issues to determine whether someone already opened this issue? - Search StackOverflow for an answer? - Capture the repro steps and gather the information requested in the steps below to reproduce your scenario? - Review the samples under github.com/microsoftgraph? They can help for some scenarios. - Take a look at the functional tests in this repo? They may have an example for you. See the [functional tests](https://github.com/microsoftgraph/msgraph-sdk-java/tree/master/src/test/java/com/microsoft/graph/functional) Please provide the following before submitting this issue: - Expected behavior. Please provide **links to the specific [Microsoft Graph documentation](https://developer.microsoft.com/en-us/graph/docs/concepts/overview)** you used to determine the expected behavior. - Actual behavior. Provide error codes, stack information, and a [Fiddler](http://www.telerik.com/fiddler) capture of the request and response (please remove personally identifiable information before posting). - Steps to reproduce the behavior. Include your code, IDE versions, client library versions, and any other information that might be helpful to understand your scenario. --> ### Issue Class : com.microsoft.graph.httpcore.RetryHandler When graph endpoint for adding tabs POST: /tabs gives throttling (429) error. When RetryHandler calls retryRequest it checks for isBuffered where it requires header Transfer-Encoding as Chunked, in order to send True and to set shouldRetry flag as True. ### Expected behavior This "Transfer-Encoding = Chunked" header missing case should be handle and it shouldRetry flag should get set as 'True'. So that further it wait for given time and retry again. ### Actual behavior Some times header "Transfer-Encoding = chunked" is missing in the response headers. Causing it to return False. As a result it sets shouldRetry flag as False and it never retry again. Response Headers : [ Cache-Control : private, client-request-id : 5a064a73-9106-40ec-8dff-4069c5752de4, Content-Length : 885, Content-Type : application/json, Date : Fri, 26 Feb 2021 14:03:23 GMT, request-id : 64638ad8-1f98-49d1-9185-238341d4938e, Retry-After : 60, Strict-Transport-Security : max-age=31536000, x-ms-ags-diagnostic : {"ServerInfo": {"DataCenter":"SouthIndia","Slice":"SliceC","Ring":"3", "ScaleUnit":"001","RoleInstance":"AGSFE_IN_7" }} ] Response Body : { "error": { "code": "TooManyRequests", "message": "Too many requests from Identifier:9155ce04-4eae-42ae-905e-ac219c282f72+786c9214-bb88-448d-9a43-3afeb1518b52+786c9214-bb88-448d-9a43-3afeb1518b52 under category:throttle.teams.ags.api_complex_level_10.tenant_normal.app_normal.operation_write_sustained. Please try again later.", "innerError": { "date": "2021-02-26T14:03:23", "request-id": "64638ad8-1f98-49d1-9185-238341d4938e", "client-request-id": "5a064a73-9106-40ec-8dff-4069c5752de4", "status": 429, "code": "429", "message": "Too many requests from Identifier:9155ce04-4eae-42ae-905e-ac219c282f72+786c9214-bb88-448d-9a43-3afeb1518b52+786c9214-bb88-448d-9a43-3afeb1518b52 under category:throttle.teams.ags.api_complex_level_10.tenant_normal.app_normal.operation_write_sustained. Please try again later." } } } ### Steps to reproduce the behavior 1. Throttle the /tabs end point, by sending multiple tab addition requests for microsoft teams channels. 2. Use microsoft graph SDK for java to add tab in channel. <code> IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient(); </code> </br> <code> TeamsTab responseTeamsTab = mGraphClient.teams(teamId).channels(channelId).tabs().buildRequest().post(lTeamsTab) </code> [AB#8330](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/8330)
09ad2c139e4447e0506dc4bced2cf335dfc86924
fd1e3c03397ab8d4301ee240236c602a2ea5496f
https://github.com/microsoftgraph/msgraph-sdk-java-core/compare/09ad2c139e4447e0506dc4bced2cf335dfc86924...fd1e3c03397ab8d4301ee240236c602a2ea5496f
diff --git a/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java b/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java index 6ba5900..314dffe 100644 --- a/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java +++ b/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java @@ -22,10 +22,8 @@ public class RetryHandler implements Interceptor{ */ private final String RETRY_ATTEMPT_HEADER = "Retry-Attempt"; private final String RETRY_AFTER = "Retry-After"; - private final String TRANSFER_ENCODING = "Transfer-Encoding"; - private final String TRANSFER_ENCODING_CHUNKED = "chunked"; - private final String APPLICATION_OCTET_STREAM = "application/octet-stream"; - private final String CONTENT_TYPE = "Content-Type"; + /** Content length request header value */ + private final String CONTENT_LENGTH = "Content-Length"; public static final int MSClientErrorCodeTooManyRequests = 429; public static final int MSClientErrorCodeServiceUnavailable = 503; @@ -66,7 +64,7 @@ public class RetryHandler implements Interceptor{ // without any retry attempt. shouldRetry = (executionCount <= retryOptions.maxRetries()) - && checkStatus(statusCode) && isBuffered(response, request) + && checkStatus(statusCode) && isBuffered(request) && shouldRetryCallback != null && shouldRetryCallback.shouldRetry(retryOptions.delay(), executionCount, request, response); @@ -106,27 +104,22 @@ public class RetryHandler implements Interceptor{ || statusCode == MSClientErrorCodeGatewayTimeout); } - boolean isBuffered(Response response, Request request) { - String methodName = request.method(); - if(methodName.equalsIgnoreCase("GET") || methodName.equalsIgnoreCase("DELETE") || methodName.equalsIgnoreCase("HEAD") || methodName.equalsIgnoreCase("OPTIONS")) - return true; + boolean isBuffered(Request request) { + final String methodName = request.method(); - boolean isHTTPMethodPutPatchOrPost = methodName.equalsIgnoreCase("POST") || + final boolean isHTTPMethodPutPatchOrPost = methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT") || methodName.equalsIgnoreCase("PATCH"); - if(isHTTPMethodPutPatchOrPost) { - boolean isStream = response.header(CONTENT_TYPE)!=null && response.header(CONTENT_TYPE).equalsIgnoreCase(APPLICATION_OCTET_STREAM); - if(!isStream) { - String transferEncoding = response.header(TRANSFER_ENCODING); - boolean isTransferEncodingChunked = (transferEncoding != null) && - transferEncoding.equalsIgnoreCase(TRANSFER_ENCODING_CHUNKED); - - if(request.body() != null && isTransferEncodingChunked) - return true; - } + if(isHTTPMethodPutPatchOrPost && request.body() != null) { + try { + return request.body().contentLength() != -1L; + } catch (IOException ex) { + // expected + return false; + } } - return false; + return true; } @Override diff --git a/src/test/java/com/microsoft/graph/httpcore/RetryHandlerTest.java b/src/test/java/com/microsoft/graph/httpcore/RetryHandlerTest.java index d5ddc39..4f25ec0 100644 --- a/src/test/java/com/microsoft/graph/httpcore/RetryHandlerTest.java +++ b/src/test/java/com/microsoft/graph/httpcore/RetryHandlerTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.io.IOException; import java.net.HttpURLConnection; import org.junit.Test; @@ -16,6 +17,7 @@ import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import okio.BufferedSink; public class RetryHandlerTest { @@ -76,7 +78,7 @@ public class RetryHandlerTest { // Default retry options with Number of maxretries default to 3 RetryOptions retryOptions = new RetryOptions(); // Try to execute one more than allowed default max retries - int executionCount = RetryOptions.DEFAULT_MAX_RETRIES + 1; + int executionCount = RetryOptions.DEFAULT_MAX_RETRIES + 1; assertFalse(retryhandler.retryRequest(response, executionCount, httpget, retryOptions)); } @@ -87,7 +89,7 @@ public class RetryHandlerTest { Response response = new Response.Builder() .protocol(Protocol.HTTP_1_1) // For status code 500 which is not in (429 503 504), So NO retry - .code(HTTP_SERVER_ERROR) + .code(HTTP_SERVER_ERROR) .message( "Internal Server Error") .request(httpget) .build(); @@ -100,7 +102,7 @@ public class RetryHandlerTest { Request httppost = new Request.Builder().url(testmeurl).post(RequestBody.create(MediaType.parse("application/json"), "TEST")).build(); Response response = new Response.Builder() .protocol(Protocol.HTTP_1_1) - .code(HttpURLConnection.HTTP_GATEWAY_TIMEOUT) + .code(HttpURLConnection.HTTP_GATEWAY_TIMEOUT) .message( "gateway timeout") .request(httppost) .addHeader("Transfer-Encoding", "chunked") @@ -114,15 +116,15 @@ public class RetryHandlerTest { Request httppost = new Request.Builder().url(testmeurl).post(RequestBody.create(MediaType.parse("application/json"), "TEST")).build(); Response response = new Response.Builder() .protocol(Protocol.HTTP_1_1) - .code(HttpURLConnection.HTTP_GATEWAY_TIMEOUT) + .code(HttpURLConnection.HTTP_GATEWAY_TIMEOUT) .message( "gateway timeout") .request(httppost) .addHeader("Transfer-Encoding", "chunked") .build(); - + assertTrue(retryhandler.retryRequest(response, 1, httppost, new RetryOptions())); } - + @Test public void testGetRetryAfterWithHeader() { RetryHandler retryHandler = new RetryHandler(); @@ -131,7 +133,7 @@ public class RetryHandlerTest { delay = retryHandler.getRetryAfter(TestResponse().newBuilder().addHeader("Retry-After", "1").build(), 2, 3); assertTrue(delay == 1000); } - + @Test public void testGetRetryAfterOnFirstExecution() { RetryHandler retryHandler = new RetryHandler(); @@ -140,14 +142,48 @@ public class RetryHandlerTest { delay = retryHandler.getRetryAfter(TestResponse(), 3, 2); assertTrue(delay > 3100); } - + @Test public void testGetRetryAfterMaxExceed() { RetryHandler retryHandler = new RetryHandler(); long delay = retryHandler.getRetryAfter(TestResponse(), 190, 1); assertTrue(delay == 180000); } - + @Test + public void testIsBuffered() { + final RetryHandler retryHandler = new RetryHandler(); + Request request = new Request.Builder().url("https://localhost").method("GET", null).build(); + assertTrue("Get Request is buffered", retryHandler.isBuffered(request)); + + request = new Request.Builder().url("https://localhost").method("DELETE", null).build(); + assertTrue("Delete Request is buffered", retryHandler.isBuffered(request)); + + request = new Request.Builder().url("https://localhost") + .method("POST", + RequestBody.create(MediaType.parse("application/json"), + "{\\"key\\": 42 }")) + .build(); + assertTrue("Post Request is buffered", retryHandler.isBuffered(request)); + + request = new Request.Builder().url("https://localhost") + .method("POST", + new RequestBody() { + + @Override + public MediaType contentType() { + return MediaType.parse("application/octet-stream"); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + // TODO Auto-generated method stub + + } + }) + .build(); + assertFalse("Post Stream Request is not buffered", retryHandler.isBuffered(request)); + } + Response TestResponse() { return new Response.Builder() .code(429)
['src/main/java/com/microsoft/graph/httpcore/RetryHandler.java', 'src/test/java/com/microsoft/graph/httpcore/RetryHandlerTest.java']
{'.java': 2}
2
2
0
0
2
41,973
8,879
1,232
17
1,809
363
35
1
4,496
487
1,183
80
5
0
2021-03-02T17:33:44
42
Java
{'Java': 629959, 'PowerShell': 5185}
MIT License
9,967
googleapis/sdk-platform-java/1557/1546
googleapis
sdk-platform-java
https://github.com/googleapis/sdk-platform-java/issues/1546
https://github.com/googleapis/sdk-platform-java/pull/1557
https://github.com/googleapis/sdk-platform-java/pull/1557
2
fixes
PathTemplate.toString() not reducing wildcards
`PathTemplate.toString()` does not pretty print the template pattern correctly. It does not reduce wildcard bindings `{name=*}` to `{name}` as mentioned in the code. #### Environment details OS type and version: MacOS Java version: Java 19 api-common-java version(s): 2.6.3 #### Steps to reproduce ```java Assertions.assertEquals("libraries/{library}/books/{book}", PathTemplate.create("libraries/{library}/books/{book}").toString()); ``` #### Stack trace ``` org.opentest4j.AssertionFailedError: Expected :libraries/{library}/books/{book} Actual :libraries/{library=*}/books/{book=*} ``` I believe the problem is in `PathTemplate.peek()`. It looks like the `success` flag is incorrectly initialized to `false`. https://github.com/googleapis/gapic-generator-java/blob/17d133bd625a9fe203019514aedf63e9fdad97f8/api-common-java/src/main/java/com/google/api/pathtemplate/PathTemplate.java#L1120-L1134
461a4e5ab1f81319ac43f008e143f90b2c4d73c6
ee7add83b438df14458359bc4d7a3146056f27b4
https://github.com/googleapis/sdk-platform-java/compare/461a4e5ab1f81319ac43f008e143f90b2c4d73c6...ee7add83b438df14458359bc4d7a3146056f27b4
diff --git a/api-common-java/src/main/java/com/google/api/pathtemplate/PathTemplate.java b/api-common-java/src/main/java/com/google/api/pathtemplate/PathTemplate.java index cc9f4c110..f43ad7ab8 100644 --- a/api-common-java/src/main/java/com/google/api/pathtemplate/PathTemplate.java +++ b/api-common-java/src/main/java/com/google/api/pathtemplate/PathTemplate.java @@ -1119,7 +1119,7 @@ public class PathTemplate { // the list iterator in its state. private static boolean peek(ListIterator<Segment> segments, SegmentKind... kinds) { int start = segments.nextIndex(); - boolean success = false; + boolean success = true; for (SegmentKind kind : kinds) { if (!segments.hasNext() || segments.next().kind() != kind) { success = false; diff --git a/api-common-java/src/test/java/com/google/api/pathtemplate/PathTemplateTest.java b/api-common-java/src/test/java/com/google/api/pathtemplate/PathTemplateTest.java index 47747a115..c6c0e29e5 100644 --- a/api-common-java/src/test/java/com/google/api/pathtemplate/PathTemplateTest.java +++ b/api-common-java/src/test/java/com/google/api/pathtemplate/PathTemplateTest.java @@ -840,6 +840,27 @@ public class PathTemplateTest { Truth.assertThat(url).isEqualTo("v1/shelves/s1/books/b1"); } + @Test + public void testTemplateStringConversionWithUnbound() { + PathTemplate template = PathTemplate.create("v1/shelves/*/books/**"); + Truth.assertThat(template.toRawString()).isEqualTo("v1/shelves/{$0=*}/books/{$1=**}"); + Truth.assertThat(template.toString()).isEqualTo("v1/shelves/*/books/**"); + } + + @Test + public void testTemplateStringConversionWithBinding() { + PathTemplate template = PathTemplate.create("v1/shelves/{shelf=*}/books/{book=**}"); + Truth.assertThat(template.toRawString()).isEqualTo("v1/shelves/{shelf=*}/books/{book=**}"); + Truth.assertThat(template.toString()).isEqualTo("v1/shelves/{shelf}/books/{book=**}"); + } + + @Test + public void testSubTemplate() { + PathTemplate template = PathTemplate.create("v1/shelves/{shelf}/books/{book=books/*/**}"); + Truth.assertThat(template.subTemplate("shelf").toString()).isEqualTo("*"); + Truth.assertThat(template.subTemplate("book").toString()).isEqualTo("books/*/**"); + } + private static void assertPositionalMatch(Map<String, String> match, String... expected) { Truth.assertThat(match).isNotNull(); int i = 0; diff --git a/gapic-generator-java/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java b/gapic-generator-java/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java index 87bcd76ab..b26363330 100644 --- a/gapic-generator-java/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java +++ b/gapic-generator-java/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java @@ -217,7 +217,7 @@ public class HttpRuleParser { if (pattern == null || pattern.isEmpty()) { return varPattern; } - Matcher m = TEMPLATE_VALS_PATTERN.matcher(PathTemplate.create(pattern).toString()); + Matcher m = TEMPLATE_VALS_PATTERN.matcher(PathTemplate.create(pattern).toRawString()); while (m.find()) { varPattern.put(m.group("var"), m.group("template"));
['api-common-java/src/main/java/com/google/api/pathtemplate/PathTemplate.java', 'api-common-java/src/test/java/com/google/api/pathtemplate/PathTemplateTest.java', 'gapic-generator-java/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java']
{'.java': 3}
3
3
0
0
3
16,202,334
3,597,170
466,768
1,315
238
46
4
2
932
75
232
25
1
2
2023-03-24T20:43:56
42
Java
{'Java': 24208010, 'Starlark': 76638, 'Shell': 37814, 'Python': 3497}
Apache License 2.0
1,383
cloudslang/cs-actions/231/229
cloudslang
cs-actions
https://github.com/CloudSlang/cs-actions/issues/229
https://github.com/CloudSlang/cs-actions/pull/231
https://github.com/CloudSlang/cs-actions/pull/231
1
close
RunInstances doesn't return the expected response
[cs-amazon] The Run Instances operation doesn't return the expected response in case of successfully execution. Instead of expected xml formatted response the return message is "empty response". Please investigate.
94be847b25c7a5c0d9f1327104cb9ef4ed3e05a1
6ff2ff5c920f29db06375aa066f19f903a41fb96
https://github.com/cloudslang/cs-actions/compare/94be847b25c7a5c0d9f1327104cb9ef4ed3e05a1...6ff2ff5c920f29db06375aa066f19f903a41fb96
diff --git a/cs-amazon/src/main/java/io/cloudslang/content/amazon/execute/QueryApiExecutor.java b/cs-amazon/src/main/java/io/cloudslang/content/amazon/execute/QueryApiExecutor.java index 8dcd67b68..35979b011 100644 --- a/cs-amazon/src/main/java/io/cloudslang/content/amazon/execute/QueryApiExecutor.java +++ b/cs-amazon/src/main/java/io/cloudslang/content/amazon/execute/QueryApiExecutor.java @@ -18,7 +18,7 @@ import static io.cloudslang.content.amazon.entities.constants.Constants.AwsParam import static io.cloudslang.content.amazon.entities.constants.Constants.Miscellaneous.AMPERSAND; import static io.cloudslang.content.amazon.entities.constants.Constants.Miscellaneous.COLON; import static io.cloudslang.content.amazon.entities.constants.Constants.Miscellaneous.EQUAL; -import static io.cloudslang.content.amazon.utils.OutputsUtil.putResponseIn; +import static io.cloudslang.content.amazon.utils.OutputsUtil.getValidResponse; import static org.apache.commons.lang3.StringUtils.isBlank; /** @@ -39,7 +39,7 @@ public class QueryApiExecutor { setQueryApiHeaders(inputs, headersMap, queryParamsMap); Map<String, String> queryMapResult = new CSHttpClient().execute(inputs.getHttpClientInputs()); - putResponseIn(queryMapResult); + queryMapResult = getValidResponse(queryMapResult); return queryMapResult; } diff --git a/cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/OutputsUtil.java b/cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/OutputsUtil.java index 36e03b309..8426d9c7f 100644 --- a/cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/OutputsUtil.java +++ b/cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/OutputsUtil.java @@ -19,6 +19,7 @@ import static io.cloudslang.content.xml.utils.Constants.Outputs.ERROR_MESSAGE; import static io.cloudslang.content.xml.utils.Constants.Outputs.SELECTED_VALUE; import static io.cloudslang.content.xml.utils.Constants.QueryTypes.VALUE; import static java.lang.String.valueOf; +import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isEmpty; import static org.apache.http.HttpStatus.SC_OK; @@ -43,18 +44,20 @@ public class OutputsUtil { return signatureReturnResultMap; } - public static void putResponseIn(Map<String, String> queryMapResult) { + public static Map<String, String> getValidResponse(Map<String, String> queryMapResult) { if (queryMapResult != null) { if (queryMapResult.containsKey(STATUS_CODE) && (valueOf(SC_OK).equals(queryMapResult.get(STATUS_CODE))) && queryMapResult.containsKey(RETURN_RESULT) && !isEmpty(queryMapResult.get(RETURN_RESULT))) { queryMapResult.put(RETURN_CODE, SUCCESS); } else { queryMapResult.put(RETURN_CODE, FAILURE); } + return queryMapResult; } else { - queryMapResult = new HashMap<>(); - queryMapResult.put(EXCEPTION, "Null response!"); - queryMapResult.put(RETURN_CODE, FAILURE); - queryMapResult.put(RETURN_RESULT, "The query returned null response!"); + Map<String, String> resultMap = new HashMap<>(); + resultMap.put(EXCEPTION, "Null response!"); + resultMap.put(RETURN_CODE, FAILURE); + resultMap.put(RETURN_RESULT, "The query returned null response!"); + return resultMap; } } @@ -63,7 +66,7 @@ public class OutputsUtil { String xmlString = queryMapResult.get(RETURN_RESULT); //We make this workaround because the xml has an xmlns property in the tag and our operation can not parse the xml //this should be removed when the xml operation will be enhanced - if (isEmpty(xmlString)) { + if (!isBlank(xmlString)) { xmlString = xmlString.replace(XMLNS, WORKAROUND); Map<String, String> result = xpathQueryAction.execute(xmlString, XML_DOCUMENT_SOURCE, xPathQuery, VALUE, DELIMITER, valueOf(true)); if (result.containsKey(RETURN_CODE) && SUCCESS.equals(result.get(RETURN_CODE))) {
['cs-amazon/src/main/java/io/cloudslang/content/amazon/execute/QueryApiExecutor.java', 'cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/OutputsUtil.java']
{'.java': 2}
2
2
0
0
2
1,826,924
354,050
37,982
363
1,122
218
19
2
214
29
38
1
0
0
2016-11-21T12:57:51
41
Java
{'Java': 10745706, 'Scala': 475874, 'XSLT': 544, 'HTML': 168}
Apache License 2.0
1,384
cloudslang/cs-actions/79/74
cloudslang
cs-actions
https://github.com/CloudSlang/cs-actions/issues/74
https://github.com/CloudSlang/cs-actions/pull/79
https://github.com/CloudSlang/cs-actions/pull/79
1
fixes
SSH: returnCode=-1 but no exception output [1]
sporadically the SSH call returns -1 but no other info (e.g. exception) ``` 24/08/15 14:11:03 [DEBUG] Event received: EVENT_ACTION_END Data is: {DESCRIPTION=Action performed, PATH=0.2.2.0.1.0.0, RETURN_VALUES={returnCode=-1, returnResult=, STDERR=, exitStatus=-1, STDOUT=}, STEP_NAME=null, STEP_TYPE=ACTION, TIMESTAMP=Mon Aug 24 14:11:03 UTC 2015, EXECUTION_ID=101600113, TYPE=EVENT_ACTION_END} ``` https://circle-artifacts.com/gh/CloudSlang/cloud-slang-content/1446/artifacts/1/home/ubuntu/cloud-slang-content/builder.log
32f4fea694e85c353cb728d6fe8a7756a3788da3
200d5442a674db4ec696821619acb4a1af7c4f08
https://github.com/cloudslang/cs-actions/compare/32f4fea694e85c353cb728d6fe8a7756a3788da3...200d5442a674db4ec696821619acb4a1af7c4f08
diff --git a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/SSHService.java b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/SSHService.java index a422e200e..6a57c5fc3 100644 --- a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/SSHService.java +++ b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/SSHService.java @@ -5,7 +5,6 @@ import com.jcraft.jsch.Channel; import com.jcraft.jsch.Session; import io.cloudslang.content.ssh.entities.CommandResult; import io.cloudslang.content.ssh.entities.SSHConnection; -import io.cloudslang.content.ssh.exceptions.TimeoutException; import java.util.Map; @@ -26,7 +25,7 @@ public interface SSHService extends AutoCloseable { * @param agentForwarding Weathers the agent forwarding is enabled or not. * @return the command result. */ - CommandResult runShellCommand(String command, String characterSet, boolean usePseudoTerminal, int connectTimeout, int commandTimeout, boolean agentForwarding) throws TimeoutException; + CommandResult runShellCommand(String command, String characterSet, boolean usePseudoTerminal, int connectTimeout, int commandTimeout, boolean agentForwarding); /** * Checks the SSH session. diff --git a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/actions/ScoreSSHShellCommand.java b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/actions/ScoreSSHShellCommand.java index 52039d9a2..5cfdd7bb0 100644 --- a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/actions/ScoreSSHShellCommand.java +++ b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/actions/ScoreSSHShellCommand.java @@ -1,7 +1,6 @@ package io.cloudslang.content.ssh.services.actions; import io.cloudslang.content.ssh.entities.*; -import io.cloudslang.content.ssh.exceptions.TimeoutException; import io.cloudslang.content.ssh.services.SSHService; import io.cloudslang.content.ssh.services.impl.SSHServiceImpl; import io.cloudslang.content.ssh.utils.Constants; @@ -72,8 +71,7 @@ public class ScoreSSHShellCommand extends SSHShellAbstract { SSHShellInputs sshShellInputs, Map<String, String> returnResult, SSHService service, String sessionId, - boolean saveSSHSession - ) throws TimeoutException { + boolean saveSSHSession) { int timeoutNumber = StringUtils.toInt(sshShellInputs.getTimeout(), Constants.DEFAULT_TIMEOUT); boolean usePseudoTerminal = StringUtils.toBoolean(sshShellInputs.getPty(), Constants.DEFAULT_USE_PSEUDO_TERMINAL); diff --git a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java index 510c0b2bd..c4a57fdb4 100644 --- a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java +++ b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java @@ -119,8 +119,7 @@ public class SSHServiceImpl implements SSHService { boolean usePseudoTerminal, int connectTimeout, int commandTimeout, - boolean agentForwarding - ) throws TimeoutException { + boolean agentForwarding) { try { if (!isConnected()) { session.connect(connectTimeout); @@ -142,14 +141,14 @@ public class SSHServiceImpl implements SSHService { // wait for response long currentTime = System.currentTimeMillis(); long timeLimit = currentTime + commandTimeout; - while (!channel.isEOF() && currentTime < timeLimit) { + while (!channel.isClosed() && currentTime < timeLimit) { try { Thread.sleep(POLLING_INTERVAL); } catch (InterruptedException ignore) { } currentTime = System.currentTimeMillis(); } - boolean timedOut = !channel.isEOF(); + boolean timedOut = !channel.isClosed(); // save the response CommandResult result = new CommandResult(); @@ -165,7 +164,7 @@ public class SSHServiceImpl implements SSHService { } return result; - } catch (JSchException | UnsupportedEncodingException e) { + } catch (JSchException | UnsupportedEncodingException | TimeoutException e) { throw new RuntimeException(e); } } diff --git a/score-ssh/src/test/java/io/cloudslang/content/ssh/services/impl/SSHServiceImplTest.java b/score-ssh/src/test/java/io/cloudslang/content/ssh/services/impl/SSHServiceImplTest.java index 71b5199c2..9b4d2de97 100644 --- a/score-ssh/src/test/java/io/cloudslang/content/ssh/services/impl/SSHServiceImplTest.java +++ b/score-ssh/src/test/java/io/cloudslang/content/ssh/services/impl/SSHServiceImplTest.java @@ -9,10 +9,11 @@ import io.cloudslang.content.ssh.entities.CommandResult; import io.cloudslang.content.ssh.entities.ConnectionDetails; import io.cloudslang.content.ssh.entities.KeyFile; import io.cloudslang.content.ssh.entities.KnownHostsFile; -import io.cloudslang.content.ssh.exceptions.TimeoutException; import io.cloudslang.content.ssh.services.SSHService; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; @@ -52,15 +53,19 @@ public class SSHServiceImplTest { @Mock private Session sessionMock; + @Mock private ChannelShell channelShellMock; + @Mock private CommandResult commandResultMock; - @Mock private JSch jSchMock; + @Rule + public ExpectedException exception = ExpectedException.none(); + @Before public void setUp() throws Exception { PowerMockito.whenNew(JSch.class).withNoArguments().thenReturn(jSchMock); @@ -68,7 +73,7 @@ public class SSHServiceImplTest { Mockito.doNothing().when(jSchMock).addIdentity(SHELL_PATH); PowerMockito.when(sessionMock.openChannel("shell")).thenReturn(channelShellMock); Mockito.doNothing().when(channelShellMock).connect(CONNECT_TIMEOUT); - PowerMockito.when(channelShellMock.isEOF()).thenReturn(true); + PowerMockito.when(channelShellMock.isClosed()).thenReturn(true); } @Test @@ -117,9 +122,12 @@ public class SSHServiceImplTest { assertEquals(commandResult.getStandardOutput(), ""); } - @Test(expected = RuntimeException.class) + @Test public void testRunShellCommandInvalidEncoding() throws Exception { SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); + + exception.expect(RuntimeException.class); + sshService.runShellCommand("", "test", true, CONNECT_TIMEOUT, COMMAND_TIMEOUT, AGENT_FORWARDING_TRUE); } @@ -163,10 +171,14 @@ public class SSHServiceImplTest { sshService.removeFromCache(Mockito.any(GlobalSessionObject.class), "sessionId"); } - @Test(expected = TimeoutException.class) + @Test public void testTimeoutExceptionIsThrown() throws Exception { - PowerMockito.when(channelShellMock.isEOF()).thenReturn(false); + PowerMockito.when(channelShellMock.isClosed()).thenReturn(false); SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); + + exception.expect(RuntimeException.class); + exception.expectMessage("Timeout"); + sshService.runShellCommand("ls", "UTF-8", true, CONNECT_TIMEOUT, 0, AGENT_FORWARDING_FALSE); }
['score-ssh/src/test/java/io/cloudslang/content/ssh/services/impl/SSHServiceImplTest.java', 'score-ssh/src/main/java/io/cloudslang/content/ssh/services/actions/ScoreSSHShellCommand.java', 'score-ssh/src/main/java/io/cloudslang/content/ssh/services/SSHService.java', 'score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java']
{'.java': 4}
4
4
0
0
4
462,986
91,920
11,034
112
1,090
207
16
3
525
41
165
8
1
1
2015-10-04T13:43:50
41
Java
{'Java': 10745706, 'Scala': 475874, 'XSLT': 544, 'HTML': 168}
Apache License 2.0
1,380
cloudslang/cs-actions/75/73
cloudslang
cs-actions
https://github.com/CloudSlang/cs-actions/issues/73
https://github.com/CloudSlang/cs-actions/pull/75
https://github.com/CloudSlang/cs-actions/pull/75#issuecomment-136035003
1
fixes
SSH: session is down
when executing "big" flow, we get the following error message sporadically: ``` 11/08/15 08:42:07 [DEBUG] Event received: EVENT_ACTION_END Data is: {DESCRIPTION=Action performed, PATH=0.11.2.1.0.0.1, RETURN_VALUES={returnCode=-1, returnResult=com.jcraft.jsch.JSchException: session is down, exception=java.lang.RuntimeException: com.jcraft.jsch.JSchException: session is down at io.cloudslang.content.ssh.services.impl.SSHServiceImpl.runShellCommand(SSHServiceImpl.java:150) at io.cloudslang.content.ssh.services.actions.ScoreSSHShellCommand.runSSHCommand(ScoreSSHShellCommand.java:78) at io.cloudslang.content.ssh.services.actions.ScoreSSHShellCommand.execute(ScoreSSHShellCommand.java:51) at io.cloudslang.content.ssh.actions.SSHShellCommandAction.runSshShellCommand(SSHShellCommandAction.java:103) at sun.reflect.GeneratedMethodAccessor73.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at io.cloudslang.lang.runtime.steps.ActionSteps.invokeActionMethod(ActionSteps.java:137) at io.cloudslang.lang.runtime.steps.ActionSteps.runJavaAction(ActionSteps.java:112) at io.cloudslang.lang.runtime.steps.ActionSteps.doAction(ActionSteps.java:77) at sun.reflect.GeneratedMethodAccessor72.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at io.cloudslang.worker.execution.reflection.ReflectionAdapterImpl.executeControlAction(ReflectionAdapterImpl.java:62) at io.cloudslang.worker.execution.services.ExecutionServiceImpl.executeStep(ExecutionServiceImpl.java:326) at io.cloudslang.worker.execution.services.ExecutionServiceImpl.execute(ExecutionServiceImpl.java:80) at io.cloudslang.worker.management.services.SimpleExecutionRunnable.executeRegularStep(SimpleExecutionRunnable.java:159) at io.cloudslang.worker.management.services.SimpleExecutionRunnable.run(SimpleExecutionRunnable.java:119) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at io.cloudslang.worker.management.services.WorkerThreadFactory$1.run(WorkerThreadFactory.java:33) at java.lang.Thread.run(Thread.java:745) Caused by: com.jcraft.jsch.JSchException: session is down at com.jcraft.jsch.Channel.sendChannelOpen(Channel.java:667) at com.jcraft.jsch.Channel.connect(Channel.java:151) at io.cloudslang.content.ssh.services.impl.SSHServiceImpl.runShellCommand(SSHServiceImpl.java:129) ... 23 more }, STEP_NAME=null, STEP_TYPE=ACTION, TIMESTAMP=Tue Aug 11 08:42:07 UTC 2015, EXECUTION_ID=101600025, TYPE=EVENT_ACTION_END} ``` now that we run our tests automatically, this often causes build failure, expected behavior would be to reestablish the session is such case issue in cloud-slang-content: CloudSlang/cloud-slang-content#318 https://circle-artifacts.com/gh/CloudSlang/cloud-slang-content/1381/artifacts/1/home/ubuntu/cloud-slang-content/builder.log
dfc611031f3e1b682975a76e91686cd770af628f
83471b19bf8ca6db61c552265596f6e6ff9d0c4f
https://github.com/cloudslang/cs-actions/compare/dfc611031f3e1b682975a76e91686cd770af628f...83471b19bf8ca6db61c552265596f6e6ff9d0c4f
diff --git a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java index ff738803e..ae2e39d13 100644 --- a/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java +++ b/score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java @@ -114,6 +114,9 @@ public class SSHServiceImpl implements SSHService { @Override public CommandResult runShellCommand(String command, String characterSet, boolean usePseudoTerminal, int connectTimeout, int commandTimeout, boolean agentForwarding) { try { + if (!isConnected()) { + session.connect(connectTimeout); + } // create shell channel Channel channel = session.openChannel(SHELL_CHANNEL); ((ChannelShell) channel).setPty(usePseudoTerminal);
['score-ssh/src/main/java/io/cloudslang/content/ssh/services/impl/SSHServiceImpl.java']
{'.java': 1}
1
1
0
0
1
461,340
91,628
10,971
111
99
15
3
1
3,315
138
771
43
1
1
2015-08-27T08:24:47
41
Java
{'Java': 10745706, 'Scala': 475874, 'XSLT': 544, 'HTML': 168}
Apache License 2.0
1,381
cloudslang/cs-actions/312/308
cloudslang
cs-actions
https://github.com/CloudSlang/cs-actions/issues/308
https://github.com/CloudSlang/cs-actions/pull/312
https://github.com/CloudSlang/cs-actions/pull/312
2
fixed
amazon/actions/instances/RunInstancesAction.java did not seem to set instance_type default to m1.small as expected
"amazon/actions/instances/RunInstancesAction.java" did not seem to set instance_type default to m1.small (if not specified) as expected? Instead, it set to "m1_small" be default which would be rejected by AWS 1. CLI: cslang>run --f /var/tmp/cslang-cli/content/io/cloudslang/amazon/aws/ec2/instances/run_instances.sl --i identity=xxx,credential=yyy,image_id=ami-31814f58 Operation outputs: - return_result = <?xml version="1.0" encoding="UTF-8"?> <Response><Errors><Error><Code>InvalidParameterValue</Code... - return_code = -1 in the execution logs: <Response><Errors><Error><Code>InvalidParameterValue</Code><Message>Invalid value 'm1_small' for InstanceType.</Message></Error></Errors><RequestID>c6fea88c-b38f-4f69-964b-07120a8b5606</RequestID></Response>, return_code=-1, exception=, instance_id_result=}, Result: FAILURE, Raw Data: {EXECUTION_ID=101600057, PATH=0, DESCRIPTION=Execution finished running, TIMESTAMP=Thu Jun 22 20:44:53 UTC 2017, STEP_TYPE=OPERATION, STEP_NAME=run_instances, TYPE=EVENT_EXECUTION_FINISHED, RESULT=FAILURE, OUTPUTS={return_result=<?xml version="1.0" encoding="UTF-8"?> <Response><Errors><Error><Code>InvalidParameterValue</Code><Message>Invalid value **'m1_small'** for InstanceType.</Message></Error></Errors><RequestID>c6fea88c-b38f-4f69-964b-07120a8b5606</RequestID></Response>, return_code=-1, exception=, instance_id_result=}} 2. Request was good once we specified "m1.small" as the instance_type input cslang>run --f /var/tmp/cslang-cli/content/io/cloudslang/amazon/aws/ec2/instances/run_instances.sl --i identity=xxx,credential=yyy,image_id=ami-31814f58,**instance_type=m1.small** Operation outputs: - return_result = <?xml version="1.0" encoding="UTF-8"?> <RunInstancesResponse xmlns="http://ec2.amazonaws.com/doc/... - instance_id_result = i-0f4c4353a8b194d7d - return_code = 0 Operation: run_instances finished with result: SUCCESS
52c57dc905233c02d39c191905619e981c755401
009ffbe007ceb6ca8217a0674624a3cda0d66fe0
https://github.com/cloudslang/cs-actions/compare/52c57dc905233c02d39c191905619e981c755401...009ffbe007ceb6ca8217a0674624a3cda0d66fe0
diff --git a/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/instances/RunInstancesAction.java b/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/instances/RunInstancesAction.java index 23658f999..86a75671c 100644 --- a/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/instances/RunInstancesAction.java +++ b/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/instances/RunInstancesAction.java @@ -28,6 +28,7 @@ import io.cloudslang.content.constants.ReturnCodes; import java.util.Map; +import static io.cloudslang.content.amazon.entities.constants.Constants.Miscellaneous.DEFAULT_INSTANCE_TYPE; import static io.cloudslang.content.amazon.utils.InputsUtil.getDefaultStringInput; import static io.cloudslang.content.amazon.utils.OutputsUtil.putResponseIn; @@ -483,6 +484,7 @@ public class RunInstancesAction { @Param(value = SECONDARY_PRIVATE_IP_ADDRESS_COUNT) String secondaryPrivateIpAddressCount) { try { version = getDefaultStringInput(version, INSTANCES_DEFAULT_API_VERSION); + instanceType = getDefaultStringInput(instanceType, DEFAULT_INSTANCE_TYPE); final CommonInputs commonInputs = new CommonInputs.Builder() .withEndpoint(endpoint, EC2_API, EMPTY) diff --git a/cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Constants.java b/cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Constants.java index 2d536ed40..8ec6c60f1 100644 --- a/cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Constants.java +++ b/cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Constants.java @@ -54,6 +54,7 @@ public class Constants { public static final String NOT_RELEVANT = "Not relevant"; public static final String PIPE_DELIMITER = "|"; public static final String SCOPE_SEPARATOR = "/"; + public static final String DEFAULT_INSTANCE_TYPE = "m1.small"; } public static class Values {
['cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Constants.java', 'cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/instances/RunInstancesAction.java']
{'.java': 2}
2
2
0
0
2
2,793,670
530,722
56,443
497
268
45
3
2
1,907
131
539
25
1
0
2017-08-04T11:58:04
41
Java
{'Java': 10745706, 'Scala': 475874, 'XSLT': 544, 'HTML': 168}
Apache License 2.0
771
workcraft/workcraft/527/97
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/97
https://github.com/workcraft/workcraft/pull/527
https://github.com/workcraft/workcraft/pull/527
1
fixes
Incorrect enabled/disabled menus on changing the work
To reproduce, open two STG works A and B. In work A activate Simulation tool and in work B activate Selection tool. Initially in work A the edit, transformation and verification tools are disabled. However if one switches to B and than back to A - some of the tools become enabled. --- This issue was imported from Launchpad bug. - date created: 2015-11-11T09:48:01Z - owner: danilovesky - assignee: danilovesky - the launchpad url was https://bugs.launchpad.net/bugs/1515156
bb88646d24f649d0b716df8b34814b0bf20af8d0
2578d77c747831f095f983c0672f69c342a7a4c1
https://github.com/workcraft/workcraft/compare/bb88646d24f649d0b716df8b34814b0bf20af8d0...2578d77c747831f095f983c0672f69c342a7a4c1
diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java index 87f5e48c6..e7a9d29e9 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java @@ -59,12 +59,19 @@ public class InitialisationAnalyserTool extends AbstractTool { @Override public void activated(final GraphEditor editor) { - editor.getWorkspaceEntry().setCanModify(false); Circuit circuit = (Circuit) editor.getModel().getMathModel(); updateState(circuit); super.activated(editor); } + @Override + public void setup(final GraphEditor editor) { + super.setup(editor); + editor.getWorkspaceEntry().setCanModify(false); + editor.getWorkspaceEntry().setCanSelect(false); + editor.getWorkspaceEntry().setCanCopy(false); + } + @Override public void deactivated(final GraphEditor editor) { initHighSet = null; diff --git a/DfsPlugin/src/org/workcraft/plugins/dfs/tools/CycleAnalyserTool.java b/DfsPlugin/src/org/workcraft/plugins/dfs/tools/CycleAnalyserTool.java index 608903d53..8909edce9 100644 --- a/DfsPlugin/src/org/workcraft/plugins/dfs/tools/CycleAnalyserTool.java +++ b/DfsPlugin/src/org/workcraft/plugins/dfs/tools/CycleAnalyserTool.java @@ -179,7 +179,14 @@ public class CycleAnalyserTool extends AbstractTool { cycleCountLabel.setText("Cycle count (out of " + cycles.size() + "):"); } super.activated(editor); + } + + @Override + public void setup(final GraphEditor editor) { + super.setup(editor); editor.getWorkspaceEntry().setCanModify(false); + editor.getWorkspaceEntry().setCanSelect(false); + editor.getWorkspaceEntry().setCanCopy(false); } @Override diff --git a/DtdPlugin/src/org/workcraft/plugins/dtd/tools/DtdSelectionTool.java b/DtdPlugin/src/org/workcraft/plugins/dtd/tools/DtdSelectionTool.java index 44d24a5d8..0b2810c5d 100644 --- a/DtdPlugin/src/org/workcraft/plugins/dtd/tools/DtdSelectionTool.java +++ b/DtdPlugin/src/org/workcraft/plugins/dtd/tools/DtdSelectionTool.java @@ -22,8 +22,8 @@ public class DtdSelectionTool extends SelectionTool { } @Override - public void activated(GraphEditor editor) { - super.activated(editor); + public void setup(final GraphEditor editor) { + super.setup(editor); editor.getWorkspaceEntry().setCanCopy(false); } diff --git a/PolicyPlugin/src/org/workcraft/plugins/policy/tools/TransitionBundlerTool.java b/PolicyPlugin/src/org/workcraft/plugins/policy/tools/TransitionBundlerTool.java index d50db3bfa..55e21ba62 100644 --- a/PolicyPlugin/src/org/workcraft/plugins/policy/tools/TransitionBundlerTool.java +++ b/PolicyPlugin/src/org/workcraft/plugins/policy/tools/TransitionBundlerTool.java @@ -1,6 +1,5 @@ package org.workcraft.plugins.policy.tools; -import org.workcraft.Framework; import org.workcraft.TransformationTool; import org.workcraft.plugins.policy.PolicyNet; import org.workcraft.plugins.policy.VisualPolicyNet; @@ -25,8 +24,6 @@ public class TransitionBundlerTool extends TransformationTool { @Override public void run(WorkspaceEntry we) { - final Framework framework = Framework.getInstance(); - framework.getMainWindow().getCurrentEditor().getToolBox().selectDefaultTool(); we.saveMemento(); final VisualPolicyNet visualModel = (VisualPolicyNet) we.getModelEntry().getVisualModel(); diff --git a/StgPlugin/src/org/workcraft/plugins/stg/tools/EncodingConflictAnalyserTool.java b/StgPlugin/src/org/workcraft/plugins/stg/tools/EncodingConflictAnalyserTool.java index 10532fb31..99aee8af4 100644 --- a/StgPlugin/src/org/workcraft/plugins/stg/tools/EncodingConflictAnalyserTool.java +++ b/StgPlugin/src/org/workcraft/plugins/stg/tools/EncodingConflictAnalyserTool.java @@ -181,10 +181,16 @@ public class EncodingConflictAnalyserTool extends AbstractTool { @Override public void activated(final GraphEditor editor) { - editor.getWorkspaceEntry().setCanModify(true); stg = (VisualStg) editor.getModel(); super.activated(editor); + } + + @Override + public void setup(final GraphEditor editor) { + super.setup(editor); editor.getWorkspaceEntry().setCanModify(false); + editor.getWorkspaceEntry().setCanSelect(false); + editor.getWorkspaceEntry().setCanCopy(false); } @Override diff --git a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java index e4fdd36a0..b5a20c3c2 100644 --- a/WorkcraftCore/src/org/workcraft/gui/MainWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/MainWindow.java @@ -87,6 +87,7 @@ import org.workcraft.gui.actions.Action; import org.workcraft.gui.actions.ScriptedActionListener; import org.workcraft.gui.graph.GraphEditorPanel; import org.workcraft.gui.graph.tools.GraphEditor; +import org.workcraft.gui.graph.tools.GraphEditorTool; import org.workcraft.gui.propertyeditor.SettingsEditorDialog; import org.workcraft.gui.tasks.TaskFailureNotifier; import org.workcraft.gui.tasks.TaskManagerWindow; @@ -844,9 +845,15 @@ public class MainWindow extends JFrame { if (editorInFocus != sender) { editorInFocus = sender; - toolControlsWindow.setContent(sender.getToolBox()); - editorToolsWindow.setContent(sender.getToolBox().getControlPanel()); - mainMenu.setMenuForWorkspaceEntry(editorInFocus.getWorkspaceEntry()); + WorkspaceEntry we = editorInFocus.getWorkspaceEntry(); + mainMenu.setMenuForWorkspaceEntry(we); + + ToolboxPanel toolBox = sender.getToolBox(); + toolControlsWindow.setContent(toolBox); + editorToolsWindow.setContent(toolBox.getControlPanel()); + + GraphEditorTool selectedTool = toolBox.getTool(); + selectedTool.setup(editorInFocus); sender.updatePropertyView(); final Framework framework = Framework.getInstance(); diff --git a/WorkcraftCore/src/org/workcraft/gui/ToolboxPanel.java b/WorkcraftCore/src/org/workcraft/gui/ToolboxPanel.java index 769e3c189..53ccdb49b 100644 --- a/WorkcraftCore/src/org/workcraft/gui/ToolboxPanel.java +++ b/WorkcraftCore/src/org/workcraft/gui/ToolboxPanel.java @@ -97,6 +97,18 @@ public class ToolboxPanel extends JPanel implements ToolProvider, GraphEditorKey private final GraphEditorPanel editor; + public ToolboxPanel(GraphEditorPanel editor) { + this.editor = editor; + this.setFocusable(false); + + selectionTool = new SelectionTool(); + labelTool = new CommentGeneratorTool(); + connectionTool = new ConnectionTool(); + selectedTool = null; + + setToolsForModel(editor.getModel()); + } + public void addTool(final GraphEditorTool tool, boolean selected) { tools.add(tool); int hotKeyCode = tool.getHotKeyCode(); @@ -197,15 +209,12 @@ public class ToolboxPanel extends JPanel implements ToolProvider, GraphEditorKey controlPanel.setTool(selectedTool, editor); setToolButtonSelected(selectedTool, true); + selectedTool.setup(editor); selectedTool.activated(editor); editor.updatePropertyView(); editor.repaint(); } - public void selectDefaultTool() { - selectTool(selectedTool); - } - public void addCommonTools() { addTool(selectionTool, true); addTool(labelTool, false); @@ -250,18 +259,6 @@ public class ToolboxPanel extends JPanel implements ToolProvider, GraphEditorKey this.repaint(); } - public ToolboxPanel(GraphEditorPanel editor) { - this.editor = editor; - this.setFocusable(false); - - selectionTool = new SelectionTool(); - labelTool = new CommentGeneratorTool(); - connectionTool = new ConnectionTool(); - selectedTool = null; - - setToolsForModel(editor.getModel()); - } - public GraphEditorTool getTool() { return selectedTool; } diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/tools/AbstractTool.java b/WorkcraftCore/src/org/workcraft/gui/graph/tools/AbstractTool.java index 79ecba56c..a653bc847 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/tools/AbstractTool.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/tools/AbstractTool.java @@ -48,6 +48,13 @@ public abstract class AbstractTool implements GraphEditorTool { public void reactivated(final GraphEditor editor) { } + @Override + public void setup(final GraphEditor editor) { + editor.getWorkspaceEntry().setCanModify(true); + editor.getWorkspaceEntry().setCanSelect(true); + editor.getWorkspaceEntry().setCanCopy(true); + } + @Override public void createInterfacePanel(final GraphEditor editor) { } diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/tools/ConnectionTool.java b/WorkcraftCore/src/org/workcraft/gui/graph/tools/ConnectionTool.java index c92a81dd3..912ca8a98 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/tools/ConnectionTool.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/tools/ConnectionTool.java @@ -106,8 +106,7 @@ public class ConnectionTool extends AbstractTool { warningMessage = null; mouseLeftFirstNode = false; editor.getModel().selectNone(); - editor.getWorkspaceEntry().setCanSelect(false); - editor.getWorkspaceEntry().setCanModify(true); + setup(editor); } protected void updateState(GraphEditor editor) { @@ -153,6 +152,14 @@ public class ConnectionTool extends AbstractTool { templateNode = null; } + @Override + public void setup(final GraphEditor editor) { + super.setup(editor); + editor.getWorkspaceEntry().setCanModify(firstNode == null); + editor.getWorkspaceEntry().setCanSelect(false); + editor.getWorkspaceEntry().setCanCopy(false); + } + @Override public void drawInUserSpace(GraphEditor editor, Graphics2D g) { if ((firstNode != null) && (currentPoint != null)) { diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/tools/GraphEditorTool.java b/WorkcraftCore/src/org/workcraft/gui/graph/tools/GraphEditorTool.java index a009251c9..e676fda2a 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/tools/GraphEditorTool.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/tools/GraphEditorTool.java @@ -30,6 +30,7 @@ public interface GraphEditorTool extends GraphEditorKeyListener, GraphEditorMous void activated(final GraphEditor editor); void deactivated(final GraphEditor editor); void reactivated(final GraphEditor editor); + void setup(final GraphEditor editor); void drawInUserSpace(final GraphEditor editor, Graphics2D g); void drawInScreenSpace(final GraphEditor editor, Graphics2D g); diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/tools/SelectionTool.java b/WorkcraftCore/src/org/workcraft/gui/graph/tools/SelectionTool.java index ae482772b..9ce8a5ccb 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/tools/SelectionTool.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/tools/SelectionTool.java @@ -281,8 +281,6 @@ public class SelectionTool extends AbstractTool { @Override public void activated(final GraphEditor editor) { super.activated(editor); - editor.getWorkspaceEntry().setCanModify(true); - editor.getWorkspaceEntry().setCanSelect(true); currentNode = null; } diff --git a/WorkcraftCore/src/org/workcraft/gui/graph/tools/SimulationTool.java b/WorkcraftCore/src/org/workcraft/gui/graph/tools/SimulationTool.java index 0ea9b08f3..972a6a1d9 100644 --- a/WorkcraftCore/src/org/workcraft/gui/graph/tools/SimulationTool.java +++ b/WorkcraftCore/src/org/workcraft/gui/graph/tools/SimulationTool.java @@ -387,7 +387,6 @@ public abstract class SimulationTool extends AbstractTool implements ClipboardOw @Override public void activated(final GraphEditor editor) { editor.getWorkspaceEntry().captureMemento(); - editor.getWorkspaceEntry().setCanModify(false); generateUnderlyingModel(editor.getModel()); initialState = readModelState(); super.activated(editor); @@ -409,6 +408,14 @@ public abstract class SimulationTool extends AbstractTool implements ClipboardOw underlyingModel = null; } + @Override + public void setup(final GraphEditor editor) { + super.setup(editor); + editor.getWorkspaceEntry().setCanModify(false); + editor.getWorkspaceEntry().setCanSelect(false); + editor.getWorkspaceEntry().setCanCopy(false); + } + public void generateUnderlyingModel(VisualModel model) { setUnderlyingModel(model); }
['WorkcraftCore/src/org/workcraft/gui/ToolboxPanel.java', 'WorkcraftCore/src/org/workcraft/gui/graph/tools/SimulationTool.java', 'WorkcraftCore/src/org/workcraft/gui/graph/tools/GraphEditorTool.java', 'StgPlugin/src/org/workcraft/plugins/stg/tools/EncodingConflictAnalyserTool.java', 'WorkcraftCore/src/org/workcraft/gui/MainWindow.java', 'WorkcraftCore/src/org/workcraft/gui/graph/tools/ConnectionTool.java', 'WorkcraftCore/src/org/workcraft/gui/graph/tools/AbstractTool.java', 'DtdPlugin/src/org/workcraft/plugins/dtd/tools/DtdSelectionTool.java', 'WorkcraftCore/src/org/workcraft/gui/graph/tools/SelectionTool.java', 'DfsPlugin/src/org/workcraft/plugins/dfs/tools/CycleAnalyserTool.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/tools/InitialisationAnalyserTool.java', 'PolicyPlugin/src/org/workcraft/plugins/policy/tools/TransitionBundlerTool.java']
{'.java': 12}
12
12
0
0
12
4,822,788
980,534
135,707
1,286
3,826
721
103
12
480
76
125
12
1
0
2016-06-03T19:16:56
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
772
workcraft/workcraft/505/500
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/500
https://github.com/workcraft/workcraft/pull/505
https://github.com/workcraft/workcraft/pull/505
1
fixes
Contracting a circuit component works incorrectly if circuit integrity is violated
E.g. when a connection from an input port to output port is created as the result of a contraction, or a fork to two output port. Maybe it would be better to report an error and leave the circuit unchanged.
0fbf64037572ddc399d9888b155cec2fcc666ac4
238be7e9f1273a4017c27c6cc46dda1e213a4226
https://github.com/workcraft/workcraft/compare/0fbf64037572ddc399d9888b155cec2fcc666ac4...238be7e9f1273a4017c27c6cc46dda1e213a4226
diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java index bede8cc5f..9075b87a2 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java @@ -143,7 +143,7 @@ public class VisualCircuit extends AbstractVisualModel { if (driven.isOutput() && driven.isPort()) { outputPortCount++; if (outputPortCount > 1) { - throw new InvalidConnectionException("Fork on the output port is not allowed."); + throw new InvalidConnectionException("Fork on output ports is not allowed."); } if ((driver != null) && driver.isInput() && driver.isPort()) { throw new InvalidConnectionException("Direct connection from input port to output port is not allowed."); @@ -164,7 +164,7 @@ public class VisualCircuit extends AbstractVisualModel { if (second instanceof VisualContact) { VisualContact secondContact = (VisualContact) second; if (firstComponent.getIsZeroDelay() && secondContact.isPort() && secondContact.isOutput()) { - throw new InvalidConnectionException("Zero delay components cannot be connected to the output ports."); + throw new InvalidConnectionException("Zero delay components cannot be connected to output ports."); } } } diff --git a/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/ComponentContractionTool.java b/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/ComponentContractionTool.java index 4459e9a90..68c68c10e 100644 --- a/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/ComponentContractionTool.java +++ b/CircuitPlugin/src/org/workcraft/plugins/circuit/tools/ComponentContractionTool.java @@ -24,6 +24,7 @@ package org.workcraft.plugins.circuit.tools; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; +import java.util.HashSet; import java.util.LinkedList; import org.workcraft.NodeTransformer; @@ -35,6 +36,10 @@ import org.workcraft.dom.visual.ConnectionHelper; import org.workcraft.dom.visual.VisualModel; import org.workcraft.dom.visual.connections.VisualConnection; import org.workcraft.exceptions.InvalidConnectionException; +import org.workcraft.plugins.circuit.Circuit; +import org.workcraft.plugins.circuit.CircuitUtils; +import org.workcraft.plugins.circuit.Contact; +import org.workcraft.plugins.circuit.FunctionComponent; import org.workcraft.plugins.circuit.VisualCircuit; import org.workcraft.plugins.circuit.VisualCircuitComponent; import org.workcraft.plugins.circuit.VisualCircuitConnection; @@ -48,7 +53,7 @@ public class ComponentContractionTool extends TransformationTool implements Node @Override public String getDisplayName() { - return "Contract selected single-input component"; + return "Contract selected single-input/single-output components"; } @Override @@ -102,35 +107,93 @@ public class ComponentContractionTool extends TransformationTool implements Node if ((model instanceof VisualCircuit) && (node instanceof VisualCircuitComponent)) { VisualCircuit circuit = (VisualCircuit) model; VisualCircuitComponent component = (VisualCircuitComponent) node; - Collection<VisualContact> inputContacts = component.getVisualInputs(); - if (inputContacts.size() < 2) { + if (isValidContraction(circuit, component)) { VisualContact inputContact = component.getFirstVisualInput(); for (VisualContact outputContact: component.getVisualOutputs()) { connectContacts(circuit, inputContact, outputContact); } circuit.remove(component); - } else { - LogUtils.logWarningLine("Cannot contract a component with more than 1 input."); } } } - private void connectContacts(VisualCircuit circuit, VisualContact inputContact, VisualContact outputContact) { - if ((inputContact != null) && (outputContact != null)) { - for (Connection inputConnection: circuit.getConnections(inputContact)) { - Node fromNode = inputConnection.getFirst(); - for (Connection outputConnection: new ArrayList<>(circuit.getConnections(outputContact))) { - Node toNode = outputConnection.getSecond(); - LinkedList<Point2D> locations = ConnectionHelper.getMergedControlPoints((VisualContact) outputContact, - (VisualConnection) inputConnection, (VisualConnection) outputConnection); - circuit.remove(outputConnection); - try { - VisualConnection newConnection = (VisualCircuitConnection) circuit.connect(fromNode, toNode); - newConnection.mixStyle((VisualConnection) inputConnection, (VisualConnection) outputConnection); - ConnectionHelper.addControlPoints(newConnection, locations); - } catch (InvalidConnectionException e) { - LogUtils.logWarningLine(e.getMessage()); + private boolean isValidContraction(VisualCircuit circuit, VisualCircuitComponent component) { + Collection<VisualContact> inputContacts = component.getVisualInputs(); + String componentName = circuit.getMathName(component); + if (inputContacts.size() > 2) { + LogUtils.logErrorLine("Cannot contract component '" + componentName + "' with " + inputContacts.size() + " inputs."); + return false; + } + VisualContact inputContact = component.getFirstVisualInput(); + Collection<VisualContact> outputContacts = component.getVisualOutputs(); + if (outputContacts.size() > 2) { + LogUtils.logErrorLine("Cannot contract component '" + componentName + "' with " + outputContacts.size() + " outputs."); + return false; + } + VisualContact outputContact = component.getFirstVisualOutput(); + + // Input and output ports + Circuit mathCircuit = (Circuit) circuit.getMathModel(); + Contact driver = CircuitUtils.findDriver(mathCircuit, inputContact.getReferencedComponent(), true); + HashSet<Contact> drivenSet = new HashSet<>(); + drivenSet.addAll(CircuitUtils.findDriven(mathCircuit, driver, true)); + drivenSet.addAll(CircuitUtils.findDriven(mathCircuit, outputContact.getReferencedContact(), true)); + int outputPortCount = 0; + for (Contact driven: drivenSet) { + if (driven.isOutput() && driven.isPort()) { + outputPortCount++; + if (outputPortCount > 1) { + LogUtils.logErrorLine("Cannot contract component '" + componentName + "' as it leads to fork on output ports."); + return false; + } + if ((driver != null) && driver.isInput() && driver.isPort()) { + LogUtils.logErrorLine("Cannot contract component '" + componentName + "' as it leads to direct connection from input port to output port."); + return false; + } + } + } + + // Handle zero-delay components + Contact directDriver = CircuitUtils.findDriver(mathCircuit, inputContact.getReferencedComponent(), false); + Node directDriverParent = directDriver.getParent(); + if (directDriverParent instanceof FunctionComponent) { + FunctionComponent directDriverComponent = (FunctionComponent) directDriverParent; + if (directDriverComponent.getIsZeroDelay()) { + Collection<Contact> directDrivenSet = CircuitUtils.findDriven(mathCircuit, outputContact.getReferencedContact(), false); + for (Contact directDriven: directDrivenSet) { + if (directDriven.isOutput() && directDriven.isPort()) { + LogUtils.logErrorLine("Cannot contract component '" + componentName + "' as it leads to connection of zero delay component to output port."); + return false; } + Node directDrivenParent = directDriven.getParent(); + if (directDrivenParent instanceof FunctionComponent) { + FunctionComponent directDrivenComponent = (FunctionComponent) directDrivenParent; + if (directDrivenComponent.getIsZeroDelay()) { + LogUtils.logErrorLine("Cannot contract component '" + componentName + "' as it leads to connection between zero delay components."); + return false; + } + } + } + } + } + + return true; + } + + private void connectContacts(VisualCircuit circuit, VisualContact inputContact, VisualContact outputContact) { + for (Connection inputConnection: circuit.getConnections(inputContact)) { + Node fromNode = inputConnection.getFirst(); + for (Connection outputConnection: new ArrayList<>(circuit.getConnections(outputContact))) { + Node toNode = outputConnection.getSecond(); + LinkedList<Point2D> locations = ConnectionHelper.getMergedControlPoints((VisualContact) outputContact, + (VisualConnection) inputConnection, (VisualConnection) outputConnection); + circuit.remove(outputConnection); + try { + VisualConnection newConnection = (VisualCircuitConnection) circuit.connect(fromNode, toNode); + newConnection.mixStyle((VisualConnection) inputConnection, (VisualConnection) outputConnection); + ConnectionHelper.addControlPoints(newConnection, locations); + } catch (InvalidConnectionException e) { + LogUtils.logWarningLine(e.getMessage()); } } }
['CircuitPlugin/src/org/workcraft/plugins/circuit/tools/ComponentContractionTool.java', 'CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java']
{'.java': 2}
2
2
0
0
2
4,839,949
984,581
136,151
1,293
7,185
1,231
107
2
207
40
45
2
0
0
2016-05-21T22:27:08
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
773
workcraft/workcraft/491/475
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/475
https://github.com/workcraft/workcraft/pull/491
https://github.com/workcraft/workcraft/pull/491
1
closes
Confusing error message on net synthesis of deadlocked STG
To reproduce: 1. Create an STG with a deadlock, e.g. an empty STG would do. 2. Run `Conversion->Net synsesis [Petrify]` tool. Observed behaviour: A cryptic message from .g parser. Expected behaviour: An error message explaining why net synthesis cannot be performed.
d35a8e27be6eac39228bc79a1b7e8dedfe40fcb8
9beb8272b25d3baef174bc2d8243f75d881518bc
https://github.com/workcraft/workcraft/compare/d35a8e27be6eac39228bc79a1b7e8dedfe40fcb8...9beb8272b25d3baef174bc2d8243f75d881518bc
diff --git a/CpogPlugin/src/org/workcraft/plugins/cpog/tools/PGMinerImportTool.java b/CpogPlugin/src/org/workcraft/plugins/cpog/tools/PGMinerImportTool.java index 7aa8cf3a9..c9af0fb9a 100644 --- a/CpogPlugin/src/org/workcraft/plugins/cpog/tools/PGMinerImportTool.java +++ b/CpogPlugin/src/org/workcraft/plugins/cpog/tools/PGMinerImportTool.java @@ -49,10 +49,7 @@ public class PGMinerImportTool implements Tool { @Override public void run(WorkspaceEntry we) { - - File inputFile; - inputFile = getInputFile(we); - + File inputFile = getInputFile(we); final Framework framework = Framework.getInstance(); final GraphEditorPanel editor = framework.getMainWindow().getCurrentEditor(); final ToolboxPanel toolbox = editor.getToolBox(); @@ -60,7 +57,6 @@ public class PGMinerImportTool implements Tool { try { if (inputFile != null) { - if (dialog.getExtractConcurrency()) { PGMinerTask task = new PGMinerTask(inputFile, dialog.getSplit()); @@ -68,16 +64,13 @@ public class PGMinerImportTool implements Tool { framework.getTaskManager().queue(task, "PGMiner", result); } else { Scanner k; - k = new Scanner(inputFile); int i = 0; double yPos = tool.getLowestVertex((VisualCpog) editor.getWorkspaceEntry().getModelEntry().getVisualModel()).getY() + 3; editor.getWorkspaceEntry().captureMemento(); while (k.hasNext()) { String line = k.nextLine(); - tool.insertEventLog((VisualCpog) editor.getWorkspaceEntry().getModelEntry().getVisualModel(), i++, line.split(" "), yPos); - yPos = yPos + 5; } k.close(); diff --git a/PetriPlugin/src/org/workcraft/plugins/petri/Place.java b/PetriPlugin/src/org/workcraft/plugins/petri/Place.java index 1ff061f34..2edca792a 100644 --- a/PetriPlugin/src/org/workcraft/plugins/petri/Place.java +++ b/PetriPlugin/src/org/workcraft/plugins/petri/Place.java @@ -28,7 +28,7 @@ import org.workcraft.observation.PropertyChangedEvent; @VisualClass(org.workcraft.plugins.petri.VisualPlace.class) public class Place extends MathNode { - public static final String PROPERTY_CAPACITY = "Capacity"; + public static final String PROPERTY_CAPACITY = "Promised capacity"; public static final String PROPERTY_TOKENS = "Tokens"; protected int tokens = 0; diff --git a/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java b/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java index 4d3e2421f..b921e8ee7 100644 --- a/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java +++ b/PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java @@ -38,6 +38,7 @@ import org.workcraft.plugins.petri.Place; import org.workcraft.plugins.petri.Transition; import org.workcraft.plugins.petri.VisualPlace; import org.workcraft.plugins.petri.VisualReplicaPlace; +import org.workcraft.util.LogUtils; public class PetriSimulationTool extends SimulationTool { @@ -141,7 +142,23 @@ public class PetriSimulationTool extends SimulationTool { } } if (isEnabledNode(transition)) { + HashMap<Place, Integer> capacity = new HashMap<>(); + for (Node node: getUnderlyingPetri().getPostset(transition)) { + if (node instanceof Place) { + Place place = (Place) node; + capacity.put(place, place.getCapacity()); + } + } getUnderlyingPetri().fire(transition); + for (Node node: getUnderlyingPetri().getPostset(transition)) { + if (node instanceof Place) { + Place place = (Place) node; + if (place.getCapacity() > capacity.get(place)) { + String placeRef = getUnderlyingPetri().getNodeReference(place); + LogUtils.logWarningLine("Capacity of place '" + placeRef + "' is incresed to " + place.getCapacity() + "."); + } + } + } result = true; } return result; diff --git a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/SynthesisTask.java b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/SynthesisTask.java index 8a0e6d53b..34e3c4bd8 100644 --- a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/SynthesisTask.java +++ b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/SynthesisTask.java @@ -144,7 +144,7 @@ public class SynthesisTask implements Task<SynthesisResult>, ExternalProcessList ExportTask exportTask = new ExportTask(stgExporter, model, stgFile.getAbsolutePath()); Result<? extends Object> exportResult = framework.getTaskManager().execute(exportTask, "Exporting .g"); if (exportResult.getOutcome() != Outcome.FINISHED) { - stgFile = null; + throw new RuntimeException("Unable to export the model."); } return stgFile; } diff --git a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/TransformationTask.java b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/TransformationTask.java index 84ddddbf4..978414e8d 100644 --- a/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/TransformationTask.java +++ b/PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/TransformationTask.java @@ -33,6 +33,7 @@ import org.workcraft.util.ToolUtils; import org.workcraft.workspace.WorkspaceEntry; public class TransformationTask implements Task<TransformationResult>, ExternalProcessListener { + private static final String EXPORT_FAILED_MESSAGE = "Unable to export the model."; private WorkspaceEntry we; String[] args; @@ -96,26 +97,28 @@ public class TransformationTask implements Task<TransformationResult>, ExternalP SubtaskMonitor<Object> mon = new SubtaskMonitor<>(monitor); Result<? extends ExternalProcessResult> res = task.run(mon); - if (res.getOutcome() == Outcome.CANCELLED) { - return new Result<TransformationResult>(Outcome.CANCELLED); - } else { - final Outcome outcome; + if (res.getOutcome() == Outcome.FINISHED) { StgModel outStg = null; - if (res.getReturnValue().getReturnCode() == 0) { - outcome = Outcome.FINISHED; - } else { - outcome = Outcome.FAILED; - } - try { - String out = outFile.exists() ? FileUtils.readAllText(outFile) : ""; + if (outFile.exists()) { + String out = FileUtils.readAllText(outFile); ByteArrayInputStream outStream = new ByteArrayInputStream(out.getBytes()); - outStg = new DotGImporter().importSTG(outStream); - } catch (DeserialisationException e) { - return Result.exception(e); + try { + outStg = new DotGImporter().importSTG(outStream); + } catch (DeserialisationException e) { + return Result.exception(e); + } } TransformationResult result = new TransformationResult(res, outStg); - return new Result<TransformationResult>(outcome, result); + if (res.getReturnValue().getReturnCode() == 0) { + return Result.finished(result); + } else { + return Result.failed(result); + } + } + if (res.getOutcome() == Outcome.CANCELLED) { + return Result.cancelled(); } + return Result.failed(null); } catch (Throwable e) { throw new RuntimeException(e); } finally { @@ -141,12 +144,12 @@ public class TransformationTask implements Task<TransformationResult>, ExternalP File modelFile = new File(directory, "original" + extension); try { ExportTask exportTask = Export.createExportTask(model, modelFile, format, framework.getPluginManager()); - final Result<? extends Object> exportResult = framework.getTaskManager().execute(exportTask, "Exporting model"); + Result<? extends Object> exportResult = framework.getTaskManager().execute(exportTask, "Exporting model"); if (exportResult.getOutcome() != Outcome.FINISHED) { - modelFile = null; + throw new RuntimeException(EXPORT_FAILED_MESSAGE); } } catch (SerialisationException e) { - throw new RuntimeException("Unable to export the model."); + throw new RuntimeException(EXPORT_FAILED_MESSAGE); } return modelFile; }
['PetriPlugin/src/org/workcraft/plugins/petri/tools/PetriSimulationTool.java', 'PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/TransformationTask.java', 'PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/SynthesisTask.java', 'CpogPlugin/src/org/workcraft/plugins/cpog/tools/PGMinerImportTool.java', 'PetriPlugin/src/org/workcraft/plugins/petri/Place.java']
{'.java': 5}
5
5
0
0
5
4,839,347
984,357
136,260
1,295
3,361
605
69
5
269
41
68
10
0
0
2016-05-14T20:26:20
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
774
workcraft/workcraft/487/476
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/476
https://github.com/workcraft/workcraft/pull/487
https://github.com/workcraft/workcraft/pull/487
1
fixes
In DFS wagging unselected intermediate arcs are not replicated
To reproduce: 1. Create an DFS with a couple of connected nodes. 2. Select the nodes, but not the connection. 3. Apply wagging tool. Observed behaviour: Only the nodes are replicated, but not the connection. Expected behaviour: Replicate the nodes and also the arcs whose source and destination nodes are both selected.
50c99ccac220a6870ce0dc1af0852ca312d1cb00
712aa880eeb94233e66c43960505476676058d80
https://github.com/workcraft/workcraft/compare/50c99ccac220a6870ce0dc1af0852ca312d1cb00...712aa880eeb94233e66c43960505476676058d80
diff --git a/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGenerator.java b/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGenerator.java index 81b7f39de..b362f0410 100644 --- a/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGenerator.java +++ b/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGenerator.java @@ -12,7 +12,6 @@ import org.workcraft.dom.math.MathConnection; import org.workcraft.dom.math.MathNode; import org.workcraft.dom.visual.BoundingBoxHelper; import org.workcraft.dom.visual.VisualComponent; -import org.workcraft.dom.visual.VisualNode; import org.workcraft.dom.visual.VisualTransformableNode; import org.workcraft.dom.visual.connections.ControlPoint; import org.workcraft.dom.visual.connections.Polyline; @@ -36,6 +35,7 @@ import org.workcraft.plugins.dfs.VisualPopRegister; import org.workcraft.plugins.dfs.VisualPushRegister; import org.workcraft.plugins.dfs.VisualRegister; import org.workcraft.util.Hierarchy; +import org.workcraft.util.Pair; public class WaggingGenerator { private final VisualDfs dfs; @@ -59,21 +59,28 @@ public class WaggingGenerator { this.count = count; for (Node node: dfs.getSelection()) { - if (node instanceof VisualNode) { - if (node instanceof VisualComponent) { - selectedComponents.add((VisualComponent) node); - } else if (node instanceof VisualConnection) { - selectedConnections.add((VisualConnection) node); - } + if (node instanceof VisualComponent) { + selectedComponents.add((VisualComponent) node); + } else if (node instanceof VisualConnection) { + selectedConnections.add((VisualConnection) node); + } + } + for (VisualConnection connection: Hierarchy.getDescendantsOfType(dfs.getRoot(), VisualConnection.class)) { + if (selectedComponents.contains(connection.getFirst()) && selectedComponents.contains(connection.getSecond())) { + selectedConnections.add(connection); } } } public void run() { replicateSelection(); - insertInterface(); - insertPushControl(); - insertPopControl(); + Pair<Boolean, Boolean> hasInterface = insertInterface(); + if (hasInterface.getFirst()) { + insertPushControl(); + } + if (hasInterface.getSecond()) { + insertPopControl(); + } createGroups(); } @@ -84,23 +91,25 @@ public class WaggingGenerator { for (VisualComponent component: selectedComponents) { bb = BoundingBoxHelper.union(bb, component.getBoundingBox()); } - double step = Math.ceil(bb.getHeight()); - for (int i = 0; i < count; ++i) { - HashMap<VisualComponent, VisualComponent> mapComponentToReplica = new HashMap<>(); - WaggingData waggingData = new WaggingData(); - for (VisualComponent component: selectedComponents) { - VisualComponent replicaComponenet = replicateComponent(component); - if (replicaComponenet != null) { - replicaComponenet.setY(replicaComponenet.getY() + step * (2 * i + 1 - count) / 2); - mapComponentToReplica.put(component, replicaComponenet); - replicaToOriginalMap.put(replicaComponenet, component); - waggingData.dataComponents.add(replicaComponenet); + if (bb != null) { + double step = Math.ceil(bb.getHeight()); + for (int i = 0; i < count; ++i) { + HashMap<VisualComponent, VisualComponent> mapComponentToReplica = new HashMap<>(); + WaggingData waggingData = new WaggingData(); + for (VisualComponent component: selectedComponents) { + VisualComponent replicaComponenet = replicateComponent(component); + if (replicaComponenet != null) { + replicaComponenet.setY(replicaComponenet.getY() + step * (2 * i + 1 - count) / 2); + mapComponentToReplica.put(component, replicaComponenet); + replicaToOriginalMap.put(replicaComponenet, component); + waggingData.dataComponents.add(replicaComponenet); + } } + for (VisualConnection connection: selectedConnections) { + replicateConnection(connection, mapComponentToReplica); + } + wagging.add(waggingData); } - for (VisualConnection connection: selectedConnections) { - replicateConnection(connection, mapComponentToReplica); - } - wagging.add(waggingData); } } @@ -146,7 +155,9 @@ public class WaggingGenerator { return replica; } - private void insertInterface() { + private Pair<Boolean, Boolean> insertInterface() { + boolean hasPred = false; + boolean hasSucc = false; for (WaggingData waggingData: wagging) { waggingData.pushRegisters.clear(); waggingData.popRegisters.clear(); @@ -158,6 +169,7 @@ public class WaggingGenerator { createConnection((VisualComponent) pred, push); createConnection(push, cur); waggingData.pushRegisters.add(push); + hasPred = true; } for (Node succ: dfs.getPostset(replicaToOriginalMap.get(cur))) { if (selectedComponents.contains(succ)) continue; @@ -166,9 +178,11 @@ public class WaggingGenerator { createConnection(cur, pop); createConnection(pop, (VisualComponent) succ); waggingData.popRegisters.add(pop); + hasSucc = true; } } } + return Pair.of(hasPred, hasSucc); } private void insertPushControl() { @@ -268,6 +282,10 @@ public class WaggingGenerator { } private void createGroups() { + dfs.selectNone(); + for (VisualComponent component: selectedComponents) { + dfs.addToSelection(component); + } dfs.deleteSelection(); // data components ArrayList<Node> dataNodes = new ArrayList<>(); diff --git a/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGeneratorTool.java b/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGeneratorTool.java index b1c668eda..fd0b1d31b 100644 --- a/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGeneratorTool.java +++ b/DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGeneratorTool.java @@ -4,8 +4,10 @@ import javax.swing.JOptionPane; import org.workcraft.Framework; import org.workcraft.Tool; +import org.workcraft.dom.Node; import org.workcraft.plugins.dfs.Dfs; import org.workcraft.plugins.dfs.VisualDfs; +import org.workcraft.plugins.dfs.VisualRegister; import org.workcraft.workspace.WorkspaceEntry; public class WaggingGeneratorTool implements Tool { @@ -28,10 +30,16 @@ public class WaggingGeneratorTool implements Tool { @Override public void run(WorkspaceEntry we) { final VisualDfs dfs = (VisualDfs) we.getModelEntry().getVisualModel(); - if (dfs.getSelection().size() < 1) { + int selectedRegisterCount = 0; + for (Node node: dfs.getSelection()) { + if (node instanceof VisualRegister) { + selectedRegisterCount++; + } + } + if (selectedRegisterCount < 1) { final Framework framework = Framework.getInstance(); JOptionPane.showMessageDialog(framework.getMainWindow(), - "Select at least one component for wagging!", "Wagging", JOptionPane.ERROR_MESSAGE); + "Select at least one register for wagging!", "Wagging", JOptionPane.ERROR_MESSAGE); } else { int count = getWayCount(); if (count >= 2) { diff --git a/WorkcraftCore/src/org/workcraft/util/Hierarchy.java b/WorkcraftCore/src/org/workcraft/util/Hierarchy.java index d1c945f6f..130238c52 100644 --- a/WorkcraftCore/src/org/workcraft/util/Hierarchy.java +++ b/WorkcraftCore/src/org/workcraft/util/Hierarchy.java @@ -88,15 +88,14 @@ public class Hierarchy { public static Node getCommonParent(Node... nodes) { ArrayList<Node[]> paths = new ArrayList<>(nodes.length); - int minPathLength = Integer.MAX_VALUE; + int minPathLength = -1; for (Node node : nodes) { final Node[] path = getPath(node); - if (minPathLength > path.length) { + if ((minPathLength < 0) || (minPathLength > path.length)) { minPathLength = path.length; } paths.add(path); } - Node result = null; for (int i = 0; i < minPathLength; i++) { Node node = paths.get(0)[i];
['DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGeneratorTool.java', 'DfsPlugin/src/org/workcraft/plugins/dfs/tools/WaggingGenerator.java', 'WorkcraftCore/src/org/workcraft/util/Hierarchy.java']
{'.java': 3}
3
3
0
0
3
4,837,555
984,000
136,187
1,295
4,568
867
87
3
322
52
68
11
0
0
2016-05-12T17:01:17
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
775
workcraft/workcraft/467/466
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/466
https://github.com/workcraft/workcraft/pull/467
https://github.com/workcraft/workcraft/pull/467
1
fixes
Multiple STG implicit places with the same name
Currently Workcraft allows creating several implicit place arcs between a pair of transitions. However, the implicit places are referenced as <from_transition,to_transition> in .g format. As a result it is impossible to distinguish implicit places on the arcs between the same pair of transitions. To avoid confusion we need to forbid several connections between transitions.
99cea7dd85de642fcc01c9bec622d63f78cca9eb
aa448735e8fe43f5bf2b57a63638bbc5918d5758
https://github.com/workcraft/workcraft/compare/99cea7dd85de642fcc01c9bec622d63f78cca9eb...aa448735e8fe43f5bf2b57a63638bbc5918d5758
diff --git a/PetriNetPlugin/src/org/workcraft/plugins/petri/PetriNetUtils.java b/PetriNetPlugin/src/org/workcraft/plugins/petri/PetriNetUtils.java index 5a9e17827..23d453eaa 100644 --- a/PetriNetPlugin/src/org/workcraft/plugins/petri/PetriNetUtils.java +++ b/PetriNetPlugin/src/org/workcraft/plugins/petri/PetriNetUtils.java @@ -9,7 +9,6 @@ import java.util.LinkedList; import org.workcraft.dom.Connection; import org.workcraft.dom.Container; import org.workcraft.dom.Node; -import org.workcraft.dom.visual.AbstractVisualModel; import org.workcraft.dom.visual.ConnectionHelper; import org.workcraft.dom.visual.Replica; import org.workcraft.dom.visual.TransformHelper; @@ -312,7 +311,7 @@ public class PetriNetUtils { return positionInRootSpace; } - public static boolean hasReadArcConnection(AbstractVisualModel visualModel, Node first, Node second) { + public static boolean hasReadArcConnection(VisualModel visualModel, Node first, Node second) { boolean found = false; VisualPlace place = null; VisualTransition transition = null; @@ -341,7 +340,7 @@ public class PetriNetUtils { return found; } - public static boolean hasProducingArcConnection(AbstractVisualModel visualModel, Node first, Node second) { + public static boolean hasProducingArcConnection(VisualModel visualModel, Node first, Node second) { boolean found = false; VisualPlace place = null; VisualTransition transition = null; @@ -370,7 +369,7 @@ public class PetriNetUtils { return found; } - public static boolean hasConsumingArcConnection(AbstractVisualModel visualModel, Node first, Node second) { + public static boolean hasConsumingArcConnection(VisualModel visualModel, Node first, Node second) { boolean found = false; VisualPlace place = null; VisualTransition transition = null; @@ -399,6 +398,23 @@ public class PetriNetUtils { return found; } + public static boolean hasImplicitPlaceArcConnection(VisualModel visualModel, Node first, Node second) { + boolean found = false; + VisualTransition predTransition = null; + VisualTransition succTransition = null; + if (first instanceof VisualTransition) { + predTransition = (VisualTransition) first; + } + if (second instanceof VisualTransition) { + succTransition = (VisualTransition) second; + } + if ((predTransition != null) && (succTransition != null)) { + Connection connection = visualModel.getConnection(predTransition, succTransition); + found = connection instanceof VisualConnection; + } + return found; + } + public static HashSet<VisualConnection> getVisualConsumingArcs(VisualModel visualModel) { HashSet<VisualConnection> connections = new HashSet<>(); for (VisualConnection connection: Hierarchy.getDescendantsOfType(visualModel.getRoot(), VisualConnection.class)) { diff --git a/STGPlugin/src/org/workcraft/plugins/stg/STG.java b/STGPlugin/src/org/workcraft/plugins/stg/STG.java index 255226271..022528f6a 100644 --- a/STGPlugin/src/org/workcraft/plugins/stg/STG.java +++ b/STGPlugin/src/org/workcraft/plugins/stg/STG.java @@ -360,15 +360,16 @@ public class STG extends AbstractMathModel implements STGModel { @Override public String getNodeReference(NamespaceProvider provider, Node node) { if (node instanceof STGPlace) { - if (((STGPlace) node).isImplicit()) { + if (node != null && ((STGPlace) node).isImplicit()) { Set<Node> preset = getPreset(node); Set<Node> postset = getPostset(node); if (!(preset.size() == 1 && postset.size() == 1)) { - throw new RuntimeException("An implicit place cannot have more that one transition in its preset or postset."); + throw new RuntimeException("An implicit place must have one transition in its preset and one transition in its postset."); } - - return "<" + NamespaceHelper.hierarchicalToFlatName(referenceManager.getNodeReference(null, preset.iterator().next())) - + "," + NamespaceHelper.hierarchicalToFlatName(referenceManager.getNodeReference(null, postset.iterator().next())) + ">"; + String predNodeRef = referenceManager.getNodeReference(null, preset.iterator().next()); + String succNodeRef = referenceManager.getNodeReference(null, postset.iterator().next()); + return "<" + NamespaceHelper.hierarchicalToFlatName(predNodeRef) + "," + + NamespaceHelper.hierarchicalToFlatName(succNodeRef) + ">"; } } return super.getNodeReference(provider, node); diff --git a/STGPlugin/src/org/workcraft/plugins/stg/VisualSTG.java b/STGPlugin/src/org/workcraft/plugins/stg/VisualSTG.java index 40a3a960d..7598d00b2 100644 --- a/STGPlugin/src/org/workcraft/plugins/stg/VisualSTG.java +++ b/STGPlugin/src/org/workcraft/plugins/stg/VisualSTG.java @@ -121,6 +121,9 @@ public class VisualSTG extends AbstractVisualModel { if (PetriNetUtils.hasConsumingArcConnection(this, first, second)) { throw new InvalidConnectionException("This consuming arc already exists."); } + if (PetriNetUtils.hasImplicitPlaceArcConnection(this, first, second)) { + throw new InvalidConnectionException("This implicit place arc already exists."); + } } @Override @@ -282,32 +285,34 @@ public class VisualSTG extends AbstractVisualModel { Collection<Node> postset = getPostset(place); Collection<Replica> replicas = place.getReplicas(); if ((preset.size() == 1) && (postset.size() == 1) && replicas.isEmpty()) { - final STGPlace stgPlace = (STGPlace) place.getReferencedPlace(); - stgPlace.setImplicit(true); VisualComponent first = (VisualComponent) preset.iterator().next(); VisualComponent second = (VisualComponent) postset.iterator().next(); - - VisualConnection con1 = null; - VisualConnection con2 = null; - Collection<Connection> connections = new ArrayList<>(getConnections(place)); - for (Connection con: connections) { - if (con.getFirst() == place) { - con2 = (VisualConnection) con; - } else if (con.getSecond() == place) { - con1 = (VisualConnection) con; + if (!PetriNetUtils.hasImplicitPlaceArcConnection(this, first, second)) { + final STGPlace stgPlace = (STGPlace) place.getReferencedPlace(); + stgPlace.setImplicit(true); + + VisualConnection con1 = null; + VisualConnection con2 = null; + Collection<Connection> connections = new ArrayList<>(getConnections(place)); + for (Connection con: connections) { + if (con.getFirst() == place) { + con2 = (VisualConnection) con; + } else if (con.getSecond() == place) { + con1 = (VisualConnection) con; + } } + MathConnection refCon1 = con1.getReferencedConnection(); + MathConnection refCon2 = con2.getReferencedConnection(); + VisualImplicitPlaceArc connection = new VisualImplicitPlaceArc(first, second, refCon1, refCon2, (STGPlace) place.getReferencedPlace()); + Container parent = Hierarchy.getNearestAncestor(Hierarchy.getCommonParent(first, second), Container.class); + parent.add(connection); + if (preserveConnectionShape) { + LinkedList<Point2D> locations = ConnectionHelper.getMergedControlPoints(place, con1, con2); + ConnectionHelper.addControlPoints(connection, locations); + } + // Remove explicit place, all its connections will get removed automatically by the hanging connection remover + remove(place); } - MathConnection refCon1 = con1.getReferencedConnection(); - MathConnection refCon2 = con2.getReferencedConnection(); - VisualImplicitPlaceArc connection = new VisualImplicitPlaceArc(first, second, refCon1, refCon2, (STGPlace) place.getReferencedPlace()); - Container parent = Hierarchy.getNearestAncestor(Hierarchy.getCommonParent(first, second), Container.class); - parent.add(connection); - if (preserveConnectionShape) { - LinkedList<Point2D> locations = ConnectionHelper.getMergedControlPoints(place, con1, con2); - ConnectionHelper.addControlPoints(connection, locations); - } - // Remove explicit place, all its connections will get removed automatically by the hanging connection remover - remove(place); } } diff --git a/STGPlugin/src/org/workcraft/plugins/stg/tools/MakePlacesImplicitTool.java b/STGPlugin/src/org/workcraft/plugins/stg/tools/MakePlacesImplicitTool.java index 110a45165..ef9b6c974 100644 --- a/STGPlugin/src/org/workcraft/plugins/stg/tools/MakePlacesImplicitTool.java +++ b/STGPlugin/src/org/workcraft/plugins/stg/tools/MakePlacesImplicitTool.java @@ -1,11 +1,16 @@ package org.workcraft.plugins.stg.tools; +import java.util.Collection; import java.util.HashSet; import org.workcraft.NodeTransformer; import org.workcraft.TransformationTool; import org.workcraft.dom.Model; import org.workcraft.dom.Node; +import org.workcraft.dom.visual.Replica; +import org.workcraft.dom.visual.VisualComponent; +import org.workcraft.dom.visual.VisualModel; +import org.workcraft.plugins.petri.PetriNetUtils; import org.workcraft.plugins.petri.VisualPlace; import org.workcraft.plugins.stg.STG; import org.workcraft.plugins.stg.VisualSTG; @@ -35,7 +40,21 @@ public class MakePlacesImplicitTool extends TransformationTool implements NodeTr @Override public boolean isEnabled(WorkspaceEntry we, Node node) { - return true; + if (node instanceof VisualPlace) { + VisualModel model = we.getModelEntry().getVisualModel(); + VisualPlace place = (VisualPlace) node; + Collection<Node> preset = model.getPreset(place); + Collection<Node> postset = model.getPostset(place); + Collection<Replica> replicas = place.getReplicas(); + if ((preset.size() == 1) && (postset.size() == 1) && replicas.isEmpty()) { + VisualComponent first = (VisualComponent) preset.iterator().next(); + VisualComponent second = (VisualComponent) postset.iterator().next(); + if (!PetriNetUtils.hasImplicitPlaceArcConnection(model, first, second)) { + return true; + } + } + } + return false; } @Override
['PetriNetPlugin/src/org/workcraft/plugins/petri/PetriNetUtils.java', 'STGPlugin/src/org/workcraft/plugins/stg/STG.java', 'STGPlugin/src/org/workcraft/plugins/stg/tools/MakePlacesImplicitTool.java', 'STGPlugin/src/org/workcraft/plugins/stg/VisualSTG.java']
{'.java': 4}
4
4
0
0
4
4,784,630
975,629
134,598
1,264
6,728
1,261
105
4
377
54
66
4
0
0
2016-04-26T10:26:23
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
777
workcraft/workcraft/386/384
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/384
https://github.com/workcraft/workcraft/pull/386
https://github.com/workcraft/workcraft/pull/386
1
fixes
Proxy with read-arc lost on dummy/signal conversion
### To reproduce: 1. Create an STG work with place `p0` and dummy `dum0` 2. Connect `p0` and `dum0` by a read-arc, so that a proxy is created (hold `Shift`) 3. Convert `dum0` to a signal transition (via popup menu) ### Observed behaviour: Transition is converted but the read-arc disappears. ### Expected behaviour: Transition should be converted and the read-arc should be preserved.
a47c38080245517e827c6db6dc9e1fd05dc0fc53
93a56951434f70e8d2022aa37df018c5f1d6ca86
https://github.com/workcraft/workcraft/compare/a47c38080245517e827c6db6dc9e1fd05dc0fc53...93a56951434f70e8d2022aa37df018c5f1d6ca86
diff --git a/STGPlugin/src/org/workcraft/plugins/stg/StgUtils.java b/STGPlugin/src/org/workcraft/plugins/stg/StgUtils.java index 83e1b306a..8cc88578a 100644 --- a/STGPlugin/src/org/workcraft/plugins/stg/StgUtils.java +++ b/STGPlugin/src/org/workcraft/plugins/stg/StgUtils.java @@ -4,6 +4,7 @@ import org.workcraft.dom.Container; import org.workcraft.dom.Node; import org.workcraft.dom.visual.connections.VisualConnection; import org.workcraft.exceptions.InvalidConnectionException; +import org.workcraft.plugins.petri.VisualReadArc; import org.workcraft.plugins.stg.SignalTransition.Direction; import org.workcraft.plugins.stg.SignalTransition.Type; @@ -49,9 +50,16 @@ public class StgUtils { for (Node pred: stg.getPreset(oldTransition)) { try { VisualConnection oldPredConnection = (VisualConnection) stg.getConnection(pred, oldTransition); - VisualConnection newPredConnection = stg.connect(pred, newTransition); - newPredConnection.copyStyle(oldPredConnection); - newPredConnection.copyShape(oldPredConnection); + VisualConnection newPredConnection = null; + if (oldPredConnection instanceof VisualReadArc) { + newPredConnection = stg.connectUndirected(pred, newTransition); + } else { + newPredConnection = stg.connect(pred, newTransition); + } + if (newPredConnection != null) { + newPredConnection.copyStyle(oldPredConnection); + newPredConnection.copyShape(oldPredConnection); + } } catch (InvalidConnectionException e) { e.printStackTrace(); } @@ -60,9 +68,16 @@ public class StgUtils { for (Node succ: stg.getPostset(oldTransition)) { try { VisualConnection oldSuccConnection = (VisualConnection) stg.getConnection(oldTransition, succ); - VisualConnection newSuccConnection = stg.connect(newTransition, succ); - newSuccConnection.copyStyle(oldSuccConnection); - newSuccConnection.copyShape(oldSuccConnection); + VisualConnection newSuccConnection = null; + if (oldSuccConnection instanceof VisualReadArc) { + newSuccConnection = stg.connectUndirected(newTransition, succ); + } else { + newSuccConnection = stg.connect(newTransition, succ); + } + if (newSuccConnection != null) { + newSuccConnection.copyStyle(oldSuccConnection); + newSuccConnection.copyShape(oldSuccConnection); + } } catch (InvalidConnectionException e) { e.printStackTrace(); }
['STGPlugin/src/org/workcraft/plugins/stg/StgUtils.java']
{'.java': 1}
1
1
0
0
1
5,249,303
1,102,134
151,854
1,301
1,564
269
27
1
388
63
104
11
0
0
2016-02-28T20:51:31
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
760
workcraft/workcraft/805/804
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/804
https://github.com/workcraft/workcraft/pull/805
https://github.com/workcraft/workcraft/pull/805
1
fixes
Unresponsive GUI if backend tool produces a lot of stdout/stderr
To reproduce run MPSat in technology mapping mode with `-v9` option. The Output window becomes flooded with updates and GUI becomes unresponsive. A solution may be to throttle update requests.
84473712d77da4917e76fa72a4513a96983d6793
4538557081b44fe6ba0c4cb4c163e843df0dcf14
https://github.com/workcraft/workcraft/compare/84473712d77da4917e76fa72a4513a96983d6793...4538557081b44fe6ba0c4cb4c163e843df0dcf14
diff --git a/WorkcraftCore/src/org/workcraft/interop/ExternalProcess.java b/WorkcraftCore/src/org/workcraft/interop/ExternalProcess.java index c0c93227a..cd2d25ffe 100644 --- a/WorkcraftCore/src/org/workcraft/interop/ExternalProcess.java +++ b/WorkcraftCore/src/org/workcraft/interop/ExternalProcess.java @@ -12,7 +12,8 @@ public class ExternalProcess { abstract static class StreamReaderThread extends Thread { private final ReadableByteChannel channel; - private final ByteBuffer buffer = ByteBuffer.allocate(1024); + // Buffer is increased to 1MiB to reduce the number of updates for external processes with heavy output. + private final ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); StreamReaderThread(ReadableByteChannel channel) { this.channel = channel;
['WorkcraftCore/src/org/workcraft/interop/ExternalProcess.java']
{'.java': 1}
1
1
0
0
1
5,058,848
1,024,487
141,561
1,464
260
51
3
1
194
30
38
2
0
0
2018-03-07T17:35:32
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
770
workcraft/workcraft/530/529
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/529
https://github.com/workcraft/workcraft/pull/530
https://github.com/workcraft/workcraft/pull/530
1
closes
Concurrent modification exception on import from Verilog
To reproduce synthesise a relatively complex STG (e.g. VME bus controller). When the resultant Verilog is imported sometimes (not always) the drawing thread tries to access those components that are still being imported. This results in concurrent modification of some collections of nodes.
5c7fef4036326384e87cb3c0deb31cb384ca9c1b
ad5bb40f0d92e29eb0cd0f1d2b77af195e92151f
https://github.com/workcraft/workcraft/compare/5c7fef4036326384e87cb3c0deb31cb384ca9c1b...ad5bb40f0d92e29eb0cd0f1d2b77af195e92151f
diff --git a/SonPlugin/src/org/workcraft/plugins/son/exception/TimeEstimationValueException.java b/SonPlugin/src/org/workcraft/plugins/son/exception/TimeEstimationValueException.java deleted file mode 100644 index ccc130f94..000000000 --- a/SonPlugin/src/org/workcraft/plugins/son/exception/TimeEstimationValueException.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.workcraft.plugins.son.exception; - -public class TimeEstimationValueException extends Exception { - - private static final long serialVersionUID = 1L; - - public TimeEstimationValueException(String msg) { - super(msg); - } - -} diff --git a/SonPlugin/src/org/workcraft/plugins/son/test/Dijkstra.java b/SonPlugin/src/org/workcraft/plugins/son/test/Dijkstra.java deleted file mode 100644 index fb0a0d252..000000000 --- a/SonPlugin/src/org/workcraft/plugins/son/test/Dijkstra.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.workcraft.plugins.son.test; - -import java.io.*; -import java.util.*; - -public class Dijkstra { - private static final Graph.Edge[] GRAPH = { - new Graph.Edge("a", "b", 7), - new Graph.Edge("a", "c", 9), - new Graph.Edge("a", "f", 14), - new Graph.Edge("b", "c", 10), - new Graph.Edge("b", "d", 15), - new Graph.Edge("c", "d", 11), - new Graph.Edge("c", "f", 2), - new Graph.Edge("d", "e", 1), - new Graph.Edge("f", "e", 1), - }; - private static final String START = "a"; - private static final String END = "e"; - - public static void main(String[] args) { - Graph g = new Graph(GRAPH); - g.dijkstra(START); - g.printPath(END); - g.printAllPaths(); - } - - private static class Graph { - private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges - - /** One edge of the graph (only used by Graph constructor) */ - public static class Edge { - public final String v1, v2; - public final int dist; - Edge(String v1, String v2, int dist) { - this.v1 = v1; - this.v2 = v2; - this.dist = dist; - } - } - - /** One vertex of the graph, complete with mappings to neighbouring vertices */ - public static class Vertex implements Comparable<Vertex> { - public final String name; - public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity - public Vertex previous = null; - public final Map<Vertex, Integer> neighbours = new HashMap<>(); - - Vertex(String name) { - this.name = name; - } - - private void printPath() { - if (this == this.previous) { - System.out.printf("%s", this.name); - } else if (this.previous == null) { - System.out.printf("%s(unreached)", this.name); - } else { - this.previous.printPath(); - System.out.printf(" -> %s(%d)", this.name, this.dist); - } - } - - public int compareTo(Vertex other) { - return Integer.compare(dist, other.dist); - } - } - - /** Builds a graph from a set of edges */ - Graph(Edge[] edges) { - graph = new HashMap<>(edges.length); - - //one pass to find all vertices - for (Edge e : edges) { - if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); - if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); - } - - //another pass to set neighbouring vertices - for (Edge e : edges) { - graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); - graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph - } - } - - /** Runs dijkstra using a specified source vertex */ - public void dijkstra(String startName) { - if (!graph.containsKey(startName)) { - System.err.printf("Graph doesn't contain start vertex \\"%s\\"\\n", startName); - return; - } - final Vertex source = graph.get(startName); - NavigableSet<Vertex> q = new TreeSet<>(); - - // set-up vertices - for (Vertex v : graph.values()) { - v.previous = v == source ? source : null; - v.dist = v == source ? 0 : Integer.MAX_VALUE; - q.add(v); - } - dijkstra(q); - } - - /** Implementation of dijkstra's algorithm using a binary heap. */ - private void dijkstra(final NavigableSet<Vertex> q) { - Vertex u, v; - - while (!q.isEmpty()) { - - u = q.pollFirst(); // vertex with shortest distance (first iteration will return source) - if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable - - //look at distances to each neighbour - for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { - v = a.getKey(); //the neighbour in this iteration - - final int alternateDist = u.dist + a.getValue(); - if (alternateDist < v.dist) { // shorter path to neighbour found - q.remove(v); - v.dist = alternateDist; - v.previous = u; - q.add(v); - } - } - } - } - - /** Prints a path from the source to the specified vertex */ - public void printPath(String endName) { - if (!graph.containsKey(endName)) { - System.err.printf("Graph doesn't contain end vertex \\"%s\\"\\n", endName); - return; - } - - graph.get(endName).printPath(); - System.out.println(); - } - /** Prints the path from the source to every vertex (output order is not guaranteed) */ - public void printAllPaths() { - for (Vertex v : graph.values()) { - v.printPath(); - System.out.println(); - } - } - } -} diff --git a/SonPlugin/src/org/workcraft/plugins/son/tools/SONSimulationTool.java b/SonPlugin/src/org/workcraft/plugins/son/tools/SONSimulationTool.java index c811513a8..f7e5ce41d 100644 --- a/SonPlugin/src/org/workcraft/plugins/son/tools/SONSimulationTool.java +++ b/SonPlugin/src/org/workcraft/plugins/son/tools/SONSimulationTool.java @@ -398,8 +398,7 @@ public class SONSimulationTool extends AbstractTool implements ClipboardOwner { } updateState(editor); editor.requestFocus(); - editor.forceRedraw(); - editor.getModel().setTemplateNode(null); + super.activated(editor); } protected void initialise() { @@ -421,8 +420,13 @@ public class SONSimulationTool extends AbstractTool implements ClipboardOwner { } @Override - public void deactivated(GraphEditor editor) { + public void deactivated(final GraphEditor editor) { super.deactivated(editor); + if (timer != null) { + timer.stop(); + timer = null; + } + editor.getWorkspaceEntry().cancelMemento(); mainTrace.clear(); branchTrace.clear(); isRev = false; diff --git a/SonPlugin/src/org/workcraft/plugins/son/util/EstimatedInterval.java b/SonPlugin/src/org/workcraft/plugins/son/util/EstimatedInterval.java deleted file mode 100644 index 82bd5e45c..000000000 --- a/SonPlugin/src/org/workcraft/plugins/son/util/EstimatedInterval.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.workcraft.plugins.son.util; - -public class EstimatedInterval extends Interval { - - public EstimatedInterval() { - super(); - // TODO Auto-generated constructor stub - } - - public EstimatedInterval(Integer start, Integer end) { - super(start, end); - // TODO Auto-generated constructor stub - } - -} diff --git a/WorkcraftCore/src/org/workcraft/dom/visual/DrawMan.java b/WorkcraftCore/src/org/workcraft/dom/visual/DrawMan.java index 02707544a..19d4fd178 100644 --- a/WorkcraftCore/src/org/workcraft/dom/visual/DrawMan.java +++ b/WorkcraftCore/src/org/workcraft/dom/visual/DrawMan.java @@ -23,6 +23,7 @@ package org.workcraft.dom.visual; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; +import java.util.ArrayList; import org.workcraft.dom.Node; import org.workcraft.dom.visual.connections.VisualConnection; @@ -105,14 +106,16 @@ final class DrawMan { boolean isCollapsed = (node instanceof Collapsible) && ((Collapsible) node).getIsCollapsed(); boolean isInsideCollapsed = isCollapsed && ((Collapsible) node).isCurrentLevelInside(); if (isInsideCollapsed || !isCollapsed) { + // Copy the collection of children nodes before drawing in order to avoid concurrent modification exception + ArrayList<Node> children = new ArrayList<>(node.getChildren()); // First draw nodes - for (Node childNode : node.getChildren()) { + for (Node childNode : children) { if (!(childNode instanceof VisualConnection)) { draw(decoration, childNode); } } // Then draw connections - for (Node childNode : node.getChildren()) { + for (Node childNode : children) { if (childNode instanceof VisualConnection) { draw(decoration, childNode); }
['SonPlugin/src/org/workcraft/plugins/son/exception/TimeEstimationValueException.java', 'SonPlugin/src/org/workcraft/plugins/son/util/EstimatedInterval.java', 'WorkcraftCore/src/org/workcraft/dom/visual/DrawMan.java', 'SonPlugin/src/org/workcraft/plugins/son/tools/SONSimulationTool.java', 'SonPlugin/src/org/workcraft/plugins/son/test/Dijkstra.java']
{'.java': 5}
5
5
0
0
5
4,823,937
980,774
135,748
1,286
1,414
255
43
4
291
43
55
2
0
0
2016-06-06T16:39:44
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
755
workcraft/workcraft/1141/1140
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1140
https://github.com/workcraft/workcraft/pull/1141
https://github.com/workcraft/workcraft/pull/1141
1
fixes
Incorrect reparent of FST signals
On copy-paste of FST events their associated Signal labels are incorrectly interpreted as Symbol of FSM model. As a result the type of signal (input/output/internal) may be lost if no such signal exists in the destination FST. To reproduce: * Create an FST model with two states and an event arc between them. * Copy the whole model and paste it in a new (empty) FST model. Expected behaviour: An exact replica of the source FST should be pasted into the destination FST. Observed behaviour: Exception that a Symbol cannot be cast to Signal.
0e0ea857e2d386df3f959680bebb4b32969f45f7
f549ef9bac1d35def230854d7eb7270120e9a912
https://github.com/workcraft/workcraft/compare/0e0ea857e2d386df3f959680bebb4b32969f45f7...f549ef9bac1d35def230854d7eb7270120e9a912
diff --git a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/Fsm.java b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/Fsm.java index fae5decda..20cfe7407 100644 --- a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/Fsm.java +++ b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/Fsm.java @@ -5,7 +5,6 @@ import org.workcraft.dom.Model; import org.workcraft.dom.Node; import org.workcraft.dom.math.AbstractMathModel; import org.workcraft.dom.math.MathNode; -import org.workcraft.dom.references.HierarchyReferenceManager; import org.workcraft.dom.references.NameManager; import org.workcraft.exceptions.ArgumentException; import org.workcraft.plugins.fsm.observers.InitialStateSupervisor; @@ -104,29 +103,36 @@ public class Fsm extends AbstractMathModel { if (srcModel == null) { srcModel = this; } - HierarchyReferenceManager refManager = getReferenceManager(); - NameManager nameManager = refManager.getNameManager(null); + reparentDependencies(srcModel, srcChildren); + return super.reparent(dstContainer, srcModel, srcRoot, srcChildren); + } + + public void reparentDependencies(Model srcModel, Collection<? extends MathNode> srcChildren) { for (MathNode srcNode: srcChildren) { if (srcNode instanceof Event) { Event srcEvent = (Event) srcNode; - Symbol dstSymbol = null; - Symbol srcSymbol = srcEvent.getSymbol(); - if (srcSymbol != null) { - String symbolName = srcModel.getNodeReference(srcSymbol); - Node dstNode = getNodeByReference(symbolName); - if (dstNode instanceof Symbol) { - dstSymbol = (Symbol) dstNode; - } else { - if (dstNode != null) { - symbolName = nameManager.getDerivedName(null, symbolName); - } - dstSymbol = createSymbol(symbolName); - } - } + Symbol dstSymbol = reparentSymbol(srcModel, srcEvent.getSymbol()); srcEvent.setSymbol(dstSymbol); } } - return super.reparent(dstContainer, srcModel, srcRoot, srcChildren); + } + + private Symbol reparentSymbol(Model srcModel, Symbol srcSymbol) { + Symbol dstSymbol = null; + if (srcSymbol != null) { + String symbolName = srcModel.getNodeReference(srcSymbol); + Node dstNode = getNodeByReference(symbolName); + if (dstNode instanceof Symbol) { + dstSymbol = (Symbol) dstNode; + } else { + if (dstNode != null) { + NameManager nameManager = getReferenceManager().getNameManager(null); + symbolName = nameManager.getDerivedName(null, symbolName); + } + dstSymbol = createSymbol(symbolName); + } + } + return dstSymbol; } } diff --git a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/FsmPropertyHelper.java b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/FsmPropertyHelper.java index 3ba99857a..f88c02c98 100644 --- a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/FsmPropertyHelper.java +++ b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/FsmPropertyHelper.java @@ -61,11 +61,7 @@ public class FsmPropertyHelper { }, () -> { Symbol symbol = event.getSymbol(); - String symbolName = ""; - if (symbol != null) { - symbolName = fsm.getName(symbol); - } - return symbolName; + return symbol == null ? "" : fsm.getName(symbol); }) .setCombinable().setTemplatable(); } diff --git a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/VisualFsm.java b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/VisualFsm.java index e8442af20..cfad6d5a8 100644 --- a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/VisualFsm.java +++ b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/VisualFsm.java @@ -93,19 +93,16 @@ public class VisualFsm extends AbstractVisualModel { @Override public ModelProperties getProperties(VisualNode node) { ModelProperties properties = super.getProperties(node); - Fsm mathFsm = getMathModel(); if (node == null) { properties.add(PropertyHelper.createSeparatorProperty("Symbols")); - List<Symbol> symbols = new ArrayList<>(mathFsm.getSymbols()); - symbols.sort((s1, s2) -> SortUtils.compareNatural( - mathFsm.getNodeReference(s1), mathFsm.getNodeReference(s2))); - + List<Symbol> symbols = new ArrayList<>(getMathModel().getSymbols()); + symbols.sort((s1, s2) -> SortUtils.compareNatural(getMathReference(s1), getMathReference(s2))); for (final Symbol symbol : symbols) { properties.add(FsmPropertyHelper.getSymbolProperty(this, symbol)); } } else if (node instanceof VisualEvent) { - Event event = ((VisualEvent) node).getReferencedConnection(); - properties.add(FsmPropertyHelper.getEventSymbolProperty(mathFsm, event)); + VisualEvent event = (VisualEvent) node; + properties.add(FsmPropertyHelper.getEventSymbolProperty(getMathModel(), event.getReferencedConnection())); } return properties; } diff --git a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/observers/InitialStateSupervisor.java b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/observers/InitialStateSupervisor.java index 40e3210dc..a162552dd 100644 --- a/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/observers/InitialStateSupervisor.java +++ b/workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/observers/InitialStateSupervisor.java @@ -1,12 +1,7 @@ package org.workcraft.plugins.fsm.observers; import org.workcraft.dom.Node; -import org.workcraft.observation.HierarchyEvent; -import org.workcraft.observation.NodesAddingEvent; -import org.workcraft.observation.NodesDeletingEvent; -import org.workcraft.observation.PropertyChangedEvent; -import org.workcraft.observation.StateEvent; -import org.workcraft.observation.StateSupervisor; +import org.workcraft.observation.*; import org.workcraft.plugins.fsm.Fsm; import org.workcraft.plugins.fsm.State; import org.workcraft.utils.Hierarchy; @@ -34,14 +29,14 @@ public class InitialStateSupervisor extends StateSupervisor { @Override public void handleHierarchyEvent(HierarchyEvent e) { if (e instanceof NodesDeletingEvent) { - for (Node node: e.getAffectedNodes()) { + for (Node node : e.getAffectedNodes()) { if (node instanceof State) { // Move the initial property to another state on state removal handleStateRemoval((State) node); } } } else if (e instanceof NodesAddingEvent) { - for (Node node: e.getAffectedNodes()) { + for (Node node : e.getAffectedNodes()) { if (node instanceof State) { // Make pasted states non-initial ((State) node).setInitialQuiet(false); @@ -51,25 +46,23 @@ public class InitialStateSupervisor extends StateSupervisor { } private void handleInitialStateChange(State state) { - for (State s: Hierarchy.getChildrenOfType(state.getParent(), State.class)) { - if (!s.equals(state)) { - if (state.isInitial()) { - s.setInitialQuiet(false); - } else { - s.setInitialQuiet(true); - break; - } + for (State otherState : Hierarchy.getChildrenOfType(state.getParent(), State.class)) { + if (otherState == state) continue; + if (state.isInitial()) { + otherState.setInitialQuiet(false); + } else { + otherState.setInitialQuiet(true); + break; } } } private void handleStateRemoval(State state) { if (state.isInitial()) { - for (State s: fsm.getStates()) { - if (!s.equals(state)) { - s.setInitial(true); - break; - } + for (State otherState : fsm.getStates()) { + if (otherState == state) continue; + otherState.setInitial(true); + break; } } } diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/Fst.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/Fst.java index 1bbc1ec77..671e07815 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/Fst.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/Fst.java @@ -1,7 +1,10 @@ package org.workcraft.plugins.fst; import org.workcraft.dom.Container; +import org.workcraft.dom.Model; import org.workcraft.dom.Node; +import org.workcraft.dom.math.MathNode; +import org.workcraft.dom.references.NameManager; import org.workcraft.exceptions.ArgumentException; import org.workcraft.plugins.fsm.Fsm; import org.workcraft.plugins.fsm.State; @@ -79,7 +82,36 @@ public class Fst extends Fsm { } public final Collection<SignalEvent> getSignalEvents(Signal signal) { - return Hierarchy.getDescendantsOfType(getRoot(), SignalEvent.class, event -> event.getSignal() == signal); + return Hierarchy.getDescendantsOfType(getRoot(), SignalEvent.class, event -> event.getSymbol() == signal); + } + + @Override + public void reparentDependencies(Model srcModel, Collection<? extends MathNode> srcChildren) { + for (MathNode srcNode: srcChildren) { + if (srcNode instanceof SignalEvent) { + SignalEvent srcSignalEvent = (SignalEvent) srcNode; + Signal dstSignal = reparentSignal(srcModel, srcSignalEvent.getSymbol()); + srcSignalEvent.setSymbol(dstSignal); + } + } + } + + private Signal reparentSignal(Model srcModel, Signal srcSignal) { + Signal dstSignal = null; + if (srcSignal != null) { + String signalName = srcModel.getNodeReference(srcSignal); + Node dstNode = getNodeByReference(signalName); + if (dstNode instanceof Signal) { + dstSignal = (Signal) dstNode; + } else { + if (dstNode != null) { + NameManager nameManager = getReferenceManager().getNameManager(null); + signalName = nameManager.getDerivedName(null, signalName); + } + dstSignal = createSignal(signalName, srcSignal.getType()); + } + } + return dstSignal; } } diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/FstPropertyHelper.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/FstPropertyHelper.java index 76c519ce2..793e1f685 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/FstPropertyHelper.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/FstPropertyHelper.java @@ -91,7 +91,7 @@ public class FstPropertyHelper { if (node instanceof Signal) { signal = (Signal) node; } else { - Signal oldSignal = signalEvent.getSignal(); + Signal oldSignal = signalEvent.getSymbol(); Signal.Type type = oldSignal.getType(); signal = fst.createSignal(value, type); } @@ -101,26 +101,20 @@ public class FstPropertyHelper { } }, () -> { - Signal signal = signalEvent.getSignal(); - if (signal != null) { - return fst.getName(signal); - } - return null; + Signal signal = signalEvent.getSymbol(); + return signal == null ? null : fst.getName(signal); }) .setCombinable().setTemplatable(); } public static PropertyDescriptor getSignalTypeProperty(Signal signal, String description) { return new PropertyDeclaration<>(Signal.Type.class, description, - value -> signal.setType(value), () -> signal.getType()) - .setCombinable().setTemplatable(); + signal::setType, signal::getType).setCombinable().setTemplatable(); } - public static PropertyDescriptor getEventDrectionProperty(SignalEvent signalEvent) { + public static PropertyDescriptor getEventDirectionProperty(SignalEvent signalEvent) { return new PropertyDeclaration<>(SignalEvent.Direction.class, SignalEvent.PROPERTY_DIRECTION, - value -> signalEvent.setDirection(value), - () -> signalEvent.getDirection()) - .setCombinable().setTemplatable(); + signalEvent::setDirection, signalEvent::getDirection).setCombinable().setTemplatable(); } } diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/SignalEvent.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/SignalEvent.java index 4dbb3845f..370c66b98 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/SignalEvent.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/SignalEvent.java @@ -49,8 +49,9 @@ public class SignalEvent extends Event { } } - public Signal getSignal() { - return (Signal) getSymbol(); + @Override + public Signal getSymbol() { + return (Signal) super.getSymbol(); } } diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualFst.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualFst.java index 9a5cd402d..2831ca518 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualFst.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualFst.java @@ -81,11 +81,12 @@ public class VisualFst extends VisualFsm { properties.addAll(FstPropertyHelper.getSignalProperties(this)); } else if (node instanceof VisualSignalEvent) { VisualSignalEvent signalEvent = (VisualSignalEvent) node; - Signal signal = signalEvent.getReferencedConnection().getSignal(); properties.add(FstPropertyHelper.getEventSignalProperty(getMathModel(), signalEvent.getReferencedConnection())); + + Signal signal = signalEvent.getReferencedConnection().getSymbol(); properties.add(FstPropertyHelper.getSignalTypeProperty(signal, Signal.PROPERTY_TYPE)); if (signal.hasDirection()) { - properties.add(FstPropertyHelper.getEventDrectionProperty(signalEvent.getReferencedConnection())); + properties.add(FstPropertyHelper.getEventDirectionProperty(signalEvent.getReferencedConnection())); } properties.removeByName(Event.PROPERTY_SYMBOL); } diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualSignalEvent.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualSignalEvent.java index 610f28a47..5485890a3 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualSignalEvent.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualSignalEvent.java @@ -1,15 +1,15 @@ package org.workcraft.plugins.fst; -import java.awt.Color; - import org.workcraft.dom.visual.DrawRequest; import org.workcraft.dom.visual.Stylable; +import org.workcraft.plugins.builtin.settings.SignalCommonSettings; import org.workcraft.plugins.fsm.VisualEvent; import org.workcraft.plugins.fsm.VisualState; import org.workcraft.plugins.fst.SignalEvent.Direction; -import org.workcraft.plugins.builtin.settings.SignalCommonSettings; import org.workcraft.plugins.fst.utils.FstUtils; +import java.awt.*; + public class VisualSignalEvent extends VisualEvent { public VisualSignalEvent() { @@ -27,7 +27,7 @@ public class VisualSignalEvent extends VisualEvent { @Override public Color getLabelColor() { - Signal signal = getReferencedSignal(); + Signal signal = getReferencedConnection().getSymbol(); if (signal != null) { return FstUtils.getTypeColor(signal.getType()); } @@ -39,14 +39,11 @@ public class VisualSignalEvent extends VisualEvent { return (SignalEvent) super.getReferencedConnection(); } - private Signal getReferencedSignal() { - return getReferencedConnection().getSignal(); - } - @Override public String getLabel(DrawRequest r) { String result = super.getLabel(r); - if (getReferencedSignal().hasDirection()) { + Signal signal = getReferencedConnection().getSymbol(); + if ((signal != null) && signal.hasDirection()) { if (SignalCommonSettings.getShowToggle() || (getReferencedConnection().getDirection() != Direction.TOGGLE)) { result += getReferencedConnection().getDirection(); } diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToFsmConverter.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToFsmConverter.java index 7fb387182..ee9203df5 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToFsmConverter.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToFsmConverter.java @@ -1,22 +1,12 @@ package org.workcraft.plugins.fst.converters; -import java.util.Map; - +import org.workcraft.dom.converters.DefaultModelConverter; import org.workcraft.dom.math.MathNode; import org.workcraft.dom.visual.connections.VisualConnection; -import org.workcraft.dom.converters.DefaultModelConverter; -import org.workcraft.plugins.fsm.Event; -import org.workcraft.plugins.fsm.Fsm; -import org.workcraft.plugins.fsm.State; -import org.workcraft.plugins.fsm.Symbol; -import org.workcraft.plugins.fsm.VisualEvent; -import org.workcraft.plugins.fsm.VisualFsm; -import org.workcraft.plugins.fsm.VisualState; -import org.workcraft.plugins.fst.Fst; -import org.workcraft.plugins.fst.Signal; -import org.workcraft.plugins.fst.SignalEvent; -import org.workcraft.plugins.fst.VisualFst; -import org.workcraft.plugins.fst.VisualSignalEvent; +import org.workcraft.plugins.fsm.*; +import org.workcraft.plugins.fst.*; + +import java.util.Map; public class FstToFsmConverter extends DefaultModelConverter<VisualFst, VisualFsm> { @@ -35,15 +25,25 @@ public class FstToFsmConverter extends DefaultModelConverter<VisualFst, VisualFs public VisualConnection convertConnection(VisualConnection srcConnection) { VisualConnection dstConnection = super.convertConnection(srcConnection); if ((srcConnection instanceof VisualSignalEvent) && (dstConnection instanceof VisualEvent)) { - Fst fst = (Fst) getSrcModel().getMathModel(); + Fst fst = getSrcModel().getMathModel(); SignalEvent srcSignalEvent = (SignalEvent) srcConnection.getReferencedConnection(); - Signal srcSignal = srcSignalEvent.getSignal(); - String name = fst.getName(srcSignal); + Signal srcSignal = srcSignalEvent.getSymbol(); + String directionSuffix = ""; if (srcSignal.hasDirection()) { - name += srcSignalEvent.getDirection(); - name = name.replace("+", "_PLUS").replace("-", "_MINUS").replace("~", "_TOGGLE"); + switch (srcSignalEvent.getDirection()) { + case PLUS: + directionSuffix = "_PLUS"; + break; + case MINUS: + directionSuffix = "_MINUS"; + break; + case TOGGLE: + directionSuffix = "_TOGGLE"; + break; + } } - Fsm fsm = (Fsm) getDstModel().getMathModel(); + String name = fst.getName(srcSignal) + directionSuffix; + Fsm fsm = getDstModel().getMathModel(); Event dstEvent = (Event) dstConnection.getReferencedConnection(); Symbol symbol = fsm.getOrCreateSymbol(name); dstEvent.setSymbol(symbol); diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToStgConverter.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToStgConverter.java index a12374424..c79833700 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToStgConverter.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToStgConverter.java @@ -50,7 +50,7 @@ public class FstToStgConverter { for (Entry<VisualSignalEvent, VisualNamedTransition> entry: eventToTransitionMap.entrySet()) { VisualSignalEvent signalEvent = entry.getKey(); VisualNamedTransition transition = entry.getValue(); - Signal signal = signalEvent.getReferencedConnection().getSignal(); + Signal signal = signalEvent.getReferencedConnection().getSymbol(); String dstName = dstModel.getMathName(transition); String srcName = srcModel.getMathName(signal); if (signal.hasDirection()) { @@ -98,7 +98,7 @@ public class FstToStgConverter { Map<VisualSignalEvent, VisualNamedTransition> result = new HashMap<>(); for (VisualSignalEvent signalEvent : srcModel.getVisualSignalEvents()) { VisualNamedTransition transition = null; - Signal signal = signalEvent.getReferencedConnection().getSignal(); + Signal signal = signalEvent.getReferencedConnection().getSymbol(); String name = srcModel.getMathName(signal); if (signal.hasDirection()) { Signal.Type srcType = signal.getType(); diff --git a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/serialisation/SgSerialiser.java b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/serialisation/SgSerialiser.java index 28fbdea41..1eeac3938 100644 --- a/workcraft/FstPlugin/src/org/workcraft/plugins/fst/serialisation/SgSerialiser.java +++ b/workcraft/FstPlugin/src/org/workcraft/plugins/fst/serialisation/SgSerialiser.java @@ -48,15 +48,15 @@ public class SgSerialiser implements ModelSerialiser { return SgFormat.getInstance().getUuid(); } - private String getSrialisedNodeName(Fsm fsm, Node node) { + private String getSerialisedNodeName(Fsm fsm, Node node) { return fsm.getNodeReference(node); } - private String getSrialisedEventName(Fsm fsm, Event event) { + private String getSerialisedEventName(Fsm fsm, Event event) { String result = null; if (event instanceof SignalEvent) { SignalEvent signalEvent = (SignalEvent) event; - Signal signal = signalEvent.getSignal(); + Signal signal = signalEvent.getSymbol(); result = fsm.getNodeReference(signal); if (signal.hasDirection()) { result += signalEvent.getDirection(); @@ -75,7 +75,7 @@ public class SgSerialiser implements ModelSerialiser { private void writeSignalHeader(PrintWriter out, Fst fst, Signal.Type type) { HashSet<String> names = new HashSet<>(); for (Signal signal: fst.getSignals(type)) { - String name = getSrialisedNodeName(fst, signal); + String name = getSerialisedNodeName(fst, signal); names.add(name); } if (!names.isEmpty()) { @@ -103,7 +103,7 @@ public class SgSerialiser implements ModelSerialiser { private void writeSymbolHeader(PrintWriter out, Fsm fsm) { HashSet<String> names = new HashSet<>(); for (Event event: fsm.getEvents()) { - String name = getSrialisedEventName(fsm, event); + String name = getSerialisedEventName(fsm, event); names.add(name); } if (!names.isEmpty()) { @@ -120,9 +120,9 @@ public class SgSerialiser implements ModelSerialiser { State firstState = (State) event.getFirst(); State secondState = (State) event.getSecond(); if ((firstState != null) && (secondState != null)) { - String eventName = getSrialisedEventName(fsm, event); - String firstStateName = getSrialisedNodeName(fsm, firstState); - String secondStateName = getSrialisedNodeName(fsm, secondState); + String eventName = getSerialisedEventName(fsm, event); + String firstStateName = getSerialisedNodeName(fsm, firstState); + String secondStateName = getSerialisedNodeName(fsm, secondState); out.write(firstStateName + " " + eventName + " " + secondStateName + "\\n"); } } @@ -130,7 +130,7 @@ public class SgSerialiser implements ModelSerialiser { private void writeMarking(PrintWriter out, Fsm fsm, State state) { if (state != null) { - String stateStr = getSrialisedNodeName(fsm, state); + String stateStr = getSerialisedNodeName(fsm, state); out.write(".marking {" + stateStr + "}\\n"); } }
['workcraft/FstPlugin/src/org/workcraft/plugins/fst/Fst.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualFst.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToStgConverter.java', 'workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/FsmPropertyHelper.java', 'workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/VisualFsm.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/SignalEvent.java', 'workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/Fsm.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/converters/FstToFsmConverter.java', 'workcraft/FsmPlugin/src/org/workcraft/plugins/fsm/observers/InitialStateSupervisor.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/VisualSignalEvent.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/FstPropertyHelper.java', 'workcraft/FstPlugin/src/org/workcraft/plugins/fst/serialisation/SgSerialiser.java']
{'.java': 12}
12
12
0
0
12
5,965,055
1,212,437
162,685
1,655
11,896
2,268
235
12
556
94
119
12
0
0
2020-10-15T14:39:50
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
748
workcraft/workcraft/1286/1285
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1285
https://github.com/workcraft/workcraft/pull/1286
https://github.com/workcraft/workcraft/pull/1286
1
fixes
Truncate hierarchy separator from instance name on SDC export
Exported SDC file for loop breaking has `_` at the end of all instances, as a flat replacer for hierarchy separator. Instead, the trailing hierarchy separator should be the instance name.
cf24c238f27cbcd8d55a9e19c82b0f2d6e77f8b0
01a8332c0ba98faa7a7a6ffc19f1653d395ac0f1
https://github.com/workcraft/workcraft/compare/cf24c238f27cbcd8d55a9e19c82b0f2d6e77f8b0...01a8332c0ba98faa7a7a6ffc19f1653d395ac0f1
diff --git a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/PathbreakConstraintSerialiser.java b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/PathbreakConstraintSerialiser.java index 6384450c2..ed26fdd3d 100644 --- a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/PathbreakConstraintSerialiser.java +++ b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/PathbreakConstraintSerialiser.java @@ -8,6 +8,7 @@ package org.workcraft.plugins.circuit.serialisation; import org.workcraft.Info; import org.workcraft.dom.hierarchy.NamespaceHelper; +import org.workcraft.dom.references.Identifier; import org.workcraft.plugins.circuit.Circuit; import org.workcraft.plugins.circuit.Contact; import org.workcraft.plugins.circuit.FunctionComponent; @@ -56,7 +57,7 @@ public class PathbreakConstraintSerialiser implements PathbreakSerialiser { private void writeInstance(PrintWriter out, Circuit circuit, FunctionComponent component, HashMap<String, SubstitutionRule> substitutionRules) { - String instanceRef = circuit.getNodeReference(component); + String instanceRef = Identifier.truncateNamespaceSeparator(circuit.getNodeReference(component)); String instanceFlatName = NamespaceHelper.flattenReference(instanceRef); String msg = "Processing instance '" + instanceFlatName + "': "; if (!component.isMapped()) { diff --git a/workcraft/WorkcraftCore/src/org/workcraft/Info.java b/workcraft/WorkcraftCore/src/org/workcraft/Info.java index ba5549fef..4260a1c8e 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/Info.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/Info.java @@ -13,7 +13,7 @@ public class Info { private static final String subtitle3 = "Return of the Hazard"; private static final String subtitle4 = "Revenge of the Timing Assumption"; - private static final Version version = new Version(3, 3, 5, Status.RELEASE); + private static final Version version = new Version(3, 3, 6, Status.ALPHA); private static final int startYear = 2006; private static final int currentYear = Calendar.getInstance().get(Calendar.YEAR); diff --git a/workcraft/WorkcraftCore/src/org/workcraft/dom/hierarchy/NamespaceHelper.java b/workcraft/WorkcraftCore/src/org/workcraft/dom/hierarchy/NamespaceHelper.java index ca5d15768..7e9c6a828 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/dom/hierarchy/NamespaceHelper.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/dom/hierarchy/NamespaceHelper.java @@ -57,12 +57,12 @@ public class NamespaceHelper { } public static String getParentReference(String reference) { - String result = ""; + StringBuilder result = new StringBuilder(); LinkedList<String> path = splitReference(reference); for (int i = 0; i < path.size() - 1; i++) { - result += path.get(i); + result.append(path.get(i)); } - return result; + return result.toString(); } public static String getReferenceHead(String reference) {
['workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/serialisation/PathbreakConstraintSerialiser.java', 'workcraft/WorkcraftCore/src/org/workcraft/Info.java', 'workcraft/WorkcraftCore/src/org/workcraft/dom/hierarchy/NamespaceHelper.java']
{'.java': 3}
3
3
0
0
3
6,127,139
1,244,570
166,806
1,696
599
113
11
3
188
31
40
1
0
0
2021-10-22T16:17:09
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
749
workcraft/workcraft/1281/1280
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1280
https://github.com/workcraft/workcraft/pull/1281
https://github.com/workcraft/workcraft/pull/1281
1
fixes
Pin insertion reduces the size of circuit component
**To reproduce:** 1. Create a Circuit model with a component rendered in Box style. 2. Spread the pins of the component, so its bounding box is bigger than the default size. 3. Add input or output pin. **Observed behaviour:** The new pin is inserted as if the component had the default size without taking the existing bounding box into account. **Expected behaviour:** The new pin should align with the existing pins on the same size of the component, and should not reduce the bounding box of the component.
71233103ff809ed81ec367b833fafcf0c76c783e
b46f2e54e17a47d93c6af4325dffe0203880661a
https://github.com/workcraft/workcraft/compare/71233103ff809ed81ec367b833fafcf0c76c783e...b46f2e54e17a47d93c6af4325dffe0203880661a
diff --git a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java index 6f7122516..dff9f93ed 100644 --- a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java +++ b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java @@ -215,9 +215,6 @@ public class VisualCircuit extends AbstractVisualModel { VisualComponent vComponent1 = (VisualComponent) first; VisualComponent vComponent2 = (VisualComponent) second; - Node vParent = Hierarchy.getCommonParent(vComponent1, vComponent2); - Container vContainer = (Container) Hierarchy.getNearestAncestor(vParent, - node -> (node instanceof VisualGroup) || (node instanceof VisualPage)); if (mConnection == null) { MathNode mComponent1 = vComponent1.getReferencedComponent(); MathNode mComponent2 = vComponent2.getReferencedComponent(); @@ -225,7 +222,14 @@ public class VisualCircuit extends AbstractVisualModel { } vConnection = new VisualCircuitConnection(mConnection, vComponent1, vComponent2); vConnection.setArrowLength(0.0); - vContainer.add(vConnection); + + Node vParent = Hierarchy.getCommonParent(vComponent1, vComponent2); + Container vContainer = (Container) Hierarchy.getNearestAncestor(vParent, + node -> (node instanceof VisualGroup) || (node instanceof VisualPage)); + + if (vContainer != null) { + vContainer.add(vConnection); + } } return vConnection; } diff --git a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuitComponent.java b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuitComponent.java index 4ca29d31e..f1d3c9381 100644 --- a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuitComponent.java +++ b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuitComponent.java @@ -20,6 +20,7 @@ import java.awt.geom.*; import java.io.File; import java.util.List; import java.util.*; +import java.util.stream.Collectors; public class VisualCircuitComponent extends VisualComponent implements Container, CustomTouchable, StateObserver, ObservableHierarchy { @@ -179,30 +180,50 @@ public class VisualCircuitComponent extends VisualComponent implements Container } } - public void setPositionByDirection(VisualContact vc, Direction direction, boolean reverseProgression) { - vc.setDirection(direction); - Rectangle2D bb = getContactExpandedBox(); - switch (vc.getDirection()) { + public void setPositionByDirection(VisualContact contact, Direction direction, boolean reverseProgression) { + contact.setDirection(direction); + Collection<VisualContact> contacts = Hierarchy.getChildrenOfType(this, VisualContact.class); + contacts.remove(contact); + double contactOffset = getContactBestOffset(contacts, direction); + switch (direction) { case WEST: - vc.setX(TransformHelper.snapP5(bb.getMinX() - contactLength)); - positionVertical(vc, reverseProgression); - break; - case NORTH: - vc.setY(TransformHelper.snapP5(bb.getMinY() - contactLength)); - positionHorizontal(vc, reverseProgression); - break; case EAST: - vc.setX(TransformHelper.snapP5(bb.getMaxX() + contactLength)); - positionVertical(vc, reverseProgression); + contact.setX(contactOffset); + positionVertical(contact, reverseProgression); break; + case NORTH: case SOUTH: - vc.setY(TransformHelper.snapP5(bb.getMaxY() + contactLength)); - positionHorizontal(vc, reverseProgression); + contact.setY(contactOffset); + positionHorizontal(contact, reverseProgression); break; } invalidateBoundingBox(); } + private double getContactBestOffset(Collection<VisualContact> contacts, Direction direction) { + Rectangle2D bb = getContactExpandedBox(contacts); + contacts = contacts.stream() + .filter(contact -> contact.getDirection() == direction) + .collect(Collectors.toSet()); + + switch (direction) { + case WEST: + double westOffset = contacts.stream().mapToDouble(VisualTransformableNode::getX).max().orElse(0.0); + return Math.min(TransformHelper.snapP5(bb.getMinX() - contactLength), westOffset); + case NORTH: + double northOffset = contacts.stream().mapToDouble(VisualTransformableNode::getY).max().orElse(0.0); + return Math.min(TransformHelper.snapP5(bb.getMinY() - contactLength), northOffset); + case EAST: + double eastOffset = contacts.stream().mapToDouble(VisualTransformableNode::getX).min().orElse(0.0); + return Math.max(TransformHelper.snapP5(bb.getMaxX() + contactLength), eastOffset); + case SOUTH: + double southOffset = contacts.stream().mapToDouble(VisualTransformableNode::getY).min().orElse(0.0); + return Math.max(TransformHelper.snapP5(bb.getMaxY() + contactLength), southOffset); + default: + return 0.0; + } + } + private void positionHorizontal(VisualContact vc, boolean reverseProgression) { LinkedList<VisualContact> contacts = getOrderedOutsideContacts(vc.getDirection()); contacts.remove(vc); @@ -255,34 +276,34 @@ public class VisualCircuitComponent extends VisualComponent implements Container internalBB = null; } - private Rectangle2D getContactMinimalBox() { + private Rectangle2D getContactMinimalBox(Collection<VisualContact> contacts) { double size = VisualCommonSettings.getNodeSize(); double xMin = -size / 2; double yMin = -size / 2; double xMax = size / 2; double yMax = size / 2; - for (VisualContact vc: Hierarchy.getChildrenOfType(this, VisualContact.class)) { - switch (vc.getDirection()) { + for (VisualContact contact : contacts) { + switch (contact.getDirection()) { case WEST: - double xWest = vc.getX() + contactLength; + double xWest = contact.getX() + contactLength; if ((xWest < -size / 2) && (xWest > xMin)) { xMin = xWest; } break; case NORTH: - double yNorth = vc.getY() + contactLength; + double yNorth = contact.getY() + contactLength; if ((yNorth < -size / 2) && (yNorth > yMin)) { yMin = yNorth; } break; case EAST: - double xEast = vc.getX() - contactLength; + double xEast = contact.getX() - contactLength; if ((xEast > size / 2) && (xEast < xMax)) { xMax = xEast; } break; case SOUTH: - double ySouth = vc.getY() - contactLength; + double ySouth = contact.getY() - contactLength; if ((ySouth > size / 2) && (ySouth < yMax)) { yMax = ySouth; } @@ -292,36 +313,36 @@ public class VisualCircuitComponent extends VisualComponent implements Container return new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin); } - private Rectangle2D getContactExpandedBox() { - Rectangle2D minBox = getContactMinimalBox(); + private Rectangle2D getContactExpandedBox(Collection<VisualContact> contacts) { + Rectangle2D minBox = getContactMinimalBox(contacts); double x1 = minBox.getMinX(); double y1 = minBox.getMinY(); double x2 = minBox.getMaxX(); double y2 = minBox.getMaxY(); - for (VisualContact vc: Hierarchy.getChildrenOfType(this, VisualContact.class)) { - double x = vc.getX(); - double y = vc.getY(); - switch (vc.getDirection()) { + for (VisualContact contact : contacts) { + double x = contact.getX(); + double y = contact.getY(); + switch (contact.getDirection()) { case WEST: - if (vc.getX() < minBox.getMinX()) { + if (contact.getX() < minBox.getMinX()) { y1 = Math.min(y1, y - contactMargin); y2 = Math.max(y2, y + contactMargin); } break; case NORTH: - if (vc.getY() < minBox.getMinY()) { + if (contact.getY() < minBox.getMinY()) { x1 = Math.min(x1, x - contactMargin); x2 = Math.max(x2, x + contactMargin); } break; case EAST: - if (vc.getX() > minBox.getMaxX()) { + if (contact.getX() > minBox.getMaxX()) { y1 = Math.min(y1, y - contactMargin); y2 = Math.max(y2, y + contactMargin); } break; case SOUTH: - if (vc.getY() > minBox.getMaxY()) { + if (contact.getY() > minBox.getMaxY()) { x1 = Math.min(x1, x - contactMargin); x2 = Math.max(x2, x + contactMargin); } @@ -332,21 +353,22 @@ public class VisualCircuitComponent extends VisualComponent implements Container } private Rectangle2D getContactBestBox() { - Rectangle2D expBox = getContactExpandedBox(); - double x1 = expBox.getMinX(); - double y1 = expBox.getMinY(); - double x2 = expBox.getMaxX(); - double y2 = expBox.getMaxY(); + Collection<VisualContact> contacts = Hierarchy.getChildrenOfType(this, VisualContact.class); + Rectangle2D bb = getContactExpandedBox(contacts); + double x1 = bb.getMinX(); + double y1 = bb.getMinY(); + double x2 = bb.getMaxX(); + double y2 = bb.getMaxY(); boolean westFirst = true; boolean northFirst = true; boolean eastFirst = true; boolean southFirst = true; - for (VisualContact vc: Hierarchy.getChildrenOfType(this, VisualContact.class)) { - double x = vc.getX(); - double y = vc.getY(); - switch (vc.getDirection()) { + for (VisualContact contact : contacts) { + double x = contact.getX(); + double y = contact.getY(); + switch (contact.getDirection()) { case WEST: if (westFirst) { x1 = x + contactLength; @@ -389,7 +411,7 @@ public class VisualCircuitComponent extends VisualComponent implements Container y1 = y2 = (y1 + y2) / 2; } Rectangle2D maxBox = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); - return BoundingBoxHelper.union(expBox, maxBox); + return BoundingBoxHelper.union(bb, maxBox); } private Point2D getContactLinePosition(VisualContact vc) { @@ -672,7 +694,8 @@ public class VisualCircuitComponent extends VisualComponent implements Container AffineTransform at = t.sender.getTransform(); double x = at.getTranslateX(); double y = at.getTranslateY(); - Rectangle2D bb = getContactExpandedBox(); + Collection<VisualContact> contacts = Hierarchy.getChildrenOfType(this, VisualContact.class); + Rectangle2D bb = getContactExpandedBox(contacts); if ((x <= bb.getMinX()) && (y > bb.getMinY()) && (y < bb.getMaxY())) { vc.setDirection(Direction.WEST); }
['workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuitComponent.java', 'workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualCircuit.java']
{'.java': 2}
2
2
0
0
2
6,117,224
1,242,499
166,595
1,695
6,655
1,329
121
2
520
88
108
10
0
0
2021-10-13T09:19:14
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
779
workcraft/workcraft/376/354
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/354
https://github.com/workcraft/workcraft/pull/376
https://github.com/workcraft/workcraft/pull/376
1
fixes
Names of the places that have proxies should always be shown
Never hide the names of places that have proxies. Otherwise it is impossible to track what the proxies are for.
9b03bdef8c4da4948ed98648a8b10204105848fa
bb55c7a0c85f88a5efdf0b0a691caddd199fe21f
https://github.com/workcraft/workcraft/compare/9b03bdef8c4da4948ed98648a8b10204105848fa...bb55c7a0c85f88a5efdf0b0a691caddd199fe21f
diff --git a/PetriNetPlugin/src/org/workcraft/plugins/petri/VisualPlace.java b/PetriNetPlugin/src/org/workcraft/plugins/petri/VisualPlace.java index b0a4916d5..bdc712cc5 100644 --- a/PetriNetPlugin/src/org/workcraft/plugins/petri/VisualPlace.java +++ b/PetriNetPlugin/src/org/workcraft/plugins/petri/VisualPlace.java @@ -93,6 +93,11 @@ public class VisualPlace extends VisualComponent { }); } + @Override + public boolean getNameVisibility() { + return super.getNameVisibility() || !getReplicas().isEmpty(); + } + @Override public void draw(DrawRequest r) { Graphics2D g = r.getGraphics();
['PetriNetPlugin/src/org/workcraft/plugins/petri/VisualPlace.java']
{'.java': 1}
1
1
0
0
1
5,257,334
1,103,953
151,837
1,301
136
27
5
1
112
20
22
2
0
0
2016-02-24T22:04:25
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
747
workcraft/workcraft/1293/1292
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1292
https://github.com/workcraft/workcraft/pull/1293
https://github.com/workcraft/workcraft/pull/1293
1
fixes
Use Normalised path for internal file references
Previously Absolute and Canonical paths were attempted. The former does not eliminate redundant .. and . in the path. The latter follows symbolic links in Unix file systems and may end up at a file with incorrect extension. Normalised path seems to resolve both issues. For example, this code would print `the/file`: ``` String path = Paths.get("path/../to/./../the/file").normalize().toString(); System.out.println(path); ```
f1f4006abb148f4af3dc5fcbe8ae2e761838b6f2
80f3a6af1aaf13aaec57b4cb7bb277817c4bfbd9
https://github.com/workcraft/workcraft/compare/f1f4006abb148f4af3dc5fcbe8ae2e761838b6f2...80f3a6af1aaf13aaec57b4cb7bb277817c4bfbd9
diff --git a/workcraft/WorkcraftCore/src/org/workcraft/utils/ExecutableUtils.java b/workcraft/WorkcraftCore/src/org/workcraft/utils/ExecutableUtils.java index 2ba44d64c..1580c6ad9 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/utils/ExecutableUtils.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/utils/ExecutableUtils.java @@ -1,20 +1,12 @@ package org.workcraft.utils; import java.io.File; -import java.io.IOException; public class ExecutableUtils { - public static String getAbsoluteCommandPath(String toolName) { - File toolFile = new File(toolName); - if (toolFile.exists()) { - try { - return toolFile.getCanonicalPath(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return toolFile.getPath(); + public static String getAbsoluteCommandPath(String path) { + File file = new File(path); + return file.exists() ? file.getAbsolutePath() : file.getPath(); } } diff --git a/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java b/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java index 938e04c45..d6078349a 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java @@ -291,24 +291,11 @@ public class FileUtils { } public static String getFullPath(File file) { - if (file == null) { - return null; - } - if (file.exists()) { - try { - return file.getCanonicalPath(); - } catch (IOException e) { - } - } - return file.getAbsolutePath(); + return file == null ? null : Paths.get(file.getAbsolutePath()).normalize().toString(); } public static String getBasePath(File file) { - try { - return file.getCanonicalFile().getParent(); - } catch (IOException e) { - return null; - } + return file == null ? null : Paths.get(file.getAbsolutePath()).normalize().getParent().toString(); } public static String stripBase(String path, String base) { @@ -349,17 +336,11 @@ public class FileUtils { if (path == null) { return null; } - File result = new File(path); - if (!result.isAbsolute()) { - result = new File(base, path); - } - if (result.exists()) { - try { - return result.getCanonicalFile(); - } catch (IOException e) { - } + Path result = Paths.get(path); + if (!result.isAbsolute() && (base != null)) { + result = Paths.get(base, path); } - return result; + return result.normalize().toFile(); } public static File getFileByAbsoluteOrRelativePath(String path, File directory) { diff --git a/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java b/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java index c0991c009..20c245e13 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java @@ -117,9 +117,9 @@ public final class WorkUtils { CompatibilityManager cm = framework.getCompatibilityManager(); InputStream is = cm.process(file); me = loadModel(is); - String base = file.getCanonicalFile().getParent(); + String base = FileUtils.getBasePath(file); adjustPropertyFilePaths(me.getVisualModel(), base, true); - } catch (OperationCancelledException | IOException e) { + } catch (OperationCancelledException e) { // Operation cancelled by the user } } else { @@ -354,7 +354,7 @@ public final class WorkUtils { try { FileOutputStream os = new FileOutputStream(file); - String base = file.getCanonicalFile().getParent(); + String base = FileUtils.getBasePath(file); adjustPropertyFilePaths(me.getVisualModel(), base, false); Collection<Resource> adjustedResources = adjustResourceFilePaths(resources, base, false); saveModel(me, adjustedResources, os);
['workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java', 'workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java', 'workcraft/WorkcraftCore/src/org/workcraft/utils/ExecutableUtils.java']
{'.java': 3}
3
3
0
0
3
6,127,513
1,244,637
166,821
1,696
2,059
373
51
3
436
59
90
10
0
1
2021-10-28T11:21:40
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
746
workcraft/workcraft/1449/1448
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1448
https://github.com/workcraft/workcraft/pull/1449
https://github.com/workcraft/workcraft/pull/1449
1
fixes
Incorrect display of UTF-8 symbols in Output window
With the move from Java 8 to Java 11 an interesting problem appeared -- the default charset in Windows, as identified by JVM, changed from *UTF-8* to *windows-1252*. As a result, some of UTF-8 characters (e.g. →) became corrupted in the *Output* window. One solution to this issue is to explicitly specify UTF-8 encoding on String-bytes conversion, and when dealing with streams. For this `StandardCharsets.UTF_8` should be passed as the last parameter, at least to the following functions (there may be more): * `String.getBytes()` * `new String(bytes)` * `new String(bytes, offset, length)` * `new PrintStream(file)` * `new InputStreamReader(stream)` Another (complementary) solution is to pass `-Dfile.encoding=UTF-8` to the JVM thus enforcing the default encoding.
243661578fd2711fd4266238d44595b9d066c7b4
7531d7bbc3d6e0fd0cd6661208904ffd2cc22c0e
https://github.com/workcraft/workcraft/compare/243661578fd2711fd4266238d44595b9d066c7b4...7531d7bbc3d6e0fd0cd6661208904ffd2cc22c0e
diff --git a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java index 5a9a9aded..37a73a88b 100644 --- a/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java +++ b/workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java @@ -44,6 +44,7 @@ import javax.swing.*; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.*; public class VerilogImporter implements Importer { @@ -592,7 +593,7 @@ public class VerilogImporter implements Importer { } private Expression convertFormulaToExpression(String formula) { - InputStream expressionStream = new ByteArrayInputStream(formula.getBytes()); + InputStream expressionStream = new ByteArrayInputStream(formula.getBytes(StandardCharsets.UTF_8)); ExpressionParser expressionParser = new ExpressionParser(expressionStream); if (DebugCommonSettings.getParserTracing()) { expressionParser.enable_tracing(); diff --git a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/AlgebraExpressionFromGraphsCommand.java b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/AlgebraExpressionFromGraphsCommand.java index fc485e286..eaa194fc5 100644 --- a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/AlgebraExpressionFromGraphsCommand.java +++ b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/AlgebraExpressionFromGraphsCommand.java @@ -12,8 +12,9 @@ import org.workcraft.utils.WorkspaceUtils; import org.workcraft.workspace.WorkspaceEntry; import java.io.File; -import java.io.FileNotFoundException; +import java.io.IOException; import java.io.PrintStream; +import java.nio.charset.StandardCharsets; public class AlgebraExpressionFromGraphsCommand extends AbstractAlgebraCommand { @@ -57,10 +58,10 @@ public class AlgebraExpressionFromGraphsCommand extends AbstractAlgebraCommand { } PrintStream expressions; try { - expressions = new PrintStream(file); + expressions = new PrintStream(file, StandardCharsets.UTF_8); expressions.print(exp); expressions.close(); - } catch (FileNotFoundException e) { + } catch (IOException e) { e.printStackTrace(); } } else { diff --git a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/ExtractSelectedGraphsPGMinerCommand.java b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/ExtractSelectedGraphsPGMinerCommand.java index b7febbb4b..d804fddc8 100644 --- a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/ExtractSelectedGraphsPGMinerCommand.java +++ b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/ExtractSelectedGraphsPGMinerCommand.java @@ -13,6 +13,7 @@ import org.workcraft.workspace.WorkspaceEntry; import java.io.File; import java.io.IOException; import java.io.PrintStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; public class ExtractSelectedGraphsPGMinerCommand extends AbstractPGMinerCommand { @@ -56,7 +57,7 @@ public class ExtractSelectedGraphsPGMinerCommand extends AbstractPGMinerCommand } File inputFile = File.createTempFile("input", ".tr"); - PrintStream expressions = new PrintStream(inputFile); + PrintStream expressions = new PrintStream(inputFile, StandardCharsets.UTF_8); for (String graph: graphs) { expressions.println(graph); } diff --git a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoExecutionSupport.java b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoExecutionSupport.java index 959f86d6d..6de149333 100644 --- a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoExecutionSupport.java +++ b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoExecutionSupport.java @@ -23,6 +23,7 @@ import org.workcraft.utils.Geometry; import java.awt.geom.Point2D; import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -88,9 +89,8 @@ public class ScencoExecutionSupport { if (f.exists() && !f.isDirectory()) { System.out.println("Boolean controller:"); try { - FileInputStream fstream = new FileInputStream(fileName); - DataInputStream in = new DataInputStream(fstream); - BufferedReader bre = new BufferedReader(new InputStreamReader(in)); + DataInputStream in = new DataInputStream(new FileInputStream(fileName)); + BufferedReader bre = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); String strLine; bre.readLine(); bre.readLine(); @@ -256,7 +256,7 @@ public class ScencoExecutionSupport { File scenarioFile, File encodingFile, EncoderSettings settings) { try { - PrintStream output = new PrintStream(scenarioFile); + PrintStream output = new PrintStream(scenarioFile, StandardCharsets.UTF_8); for (int k = 0; k < m; k++) { Map<String, Integer> nodes = new HashMap<>(); @@ -354,7 +354,7 @@ public class ScencoExecutionSupport { if (settings.getGenMode() != GenerationMode.SCENCO) { if (settings.isCustomEncMode()) { - PrintStream output1 = new PrintStream(encodingFile); + PrintStream output1 = new PrintStream(encodingFile, StandardCharsets.UTF_8); String[] enc = settings.getCustomEnc(); for (int k = 0; k < m; k++) { diff --git a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoSolver.java b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoSolver.java index 8ec8d9d6b..67cc07269 100644 --- a/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoSolver.java +++ b/workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoSolver.java @@ -18,8 +18,9 @@ import org.workcraft.workspace.WorkspaceEntry; import java.awt.geom.Point2D; import java.io.File; -import java.io.FileNotFoundException; +import java.io.IOException; import java.io.PrintStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; @@ -209,8 +210,8 @@ public class ScencoSolver { boolean[][] encoding = solution.getCode(); PrintStream output = null; try { - output = new PrintStream(encodingFile); - } catch (FileNotFoundException e) { + output = new PrintStream(encodingFile, StandardCharsets.UTF_8); + } catch (IOException e) { e.printStackTrace(); } diff --git a/workcraft/PlatoPlugin/src/org/workcraft/plugins/plato/tasks/PlatoResultHandler.java b/workcraft/PlatoPlugin/src/org/workcraft/plugins/plato/tasks/PlatoResultHandler.java index 58d749e89..42a6c4463 100644 --- a/workcraft/PlatoPlugin/src/org/workcraft/plugins/plato/tasks/PlatoResultHandler.java +++ b/workcraft/PlatoPlugin/src/org/workcraft/plugins/plato/tasks/PlatoResultHandler.java @@ -38,6 +38,7 @@ import javax.swing.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; @@ -155,7 +156,7 @@ public class PlatoResultHandler extends BasicProgressMonitor<ExternalProcessOutp private void addStg(String output, Framework framework, GraphEditor editor, String[] invariants) throws IOException, DeserialisationException, OperationCancelledException { - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(output.getBytes())) { + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8))) { ModelEntry me = new StgImporter().importFrom(inputStream, null); MathModel mathModel = me.getMathModel(); StgDescriptor stgModel = new StgDescriptor(); @@ -177,7 +178,7 @@ public class PlatoResultHandler extends BasicProgressMonitor<ExternalProcessOutp private void addFst(String output, Framework framework, GraphEditor editor) throws IOException, DeserialisationException, OperationCancelledException { - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(output.getBytes())) { + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8))) { ModelEntry me = new SgImporter().importFrom(inputStream, null); MathModel mathModel = me.getMathModel(); FstDescriptor fstModel = new FstDescriptor(); diff --git a/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/MathModelSerialisationTests.java b/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/MathModelSerialisationTests.java index d95c44117..7352be3cd 100644 --- a/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/MathModelSerialisationTests.java +++ b/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/MathModelSerialisationTests.java @@ -11,6 +11,8 @@ import org.workcraft.plugins.builtin.serialisation.XMLModelSerialiser; import org.workcraft.plugins.stg.Stg; import org.workcraft.shared.DataAccumulator; +import java.nio.charset.StandardCharsets; + class MathModelSerialisationTests { @Test @@ -33,7 +35,7 @@ class MathModelSerialisationTests { DataAccumulator accumulator = new DataAccumulator(); serialiser.serialise(stg, accumulator, null); - System.out.println(new String(accumulator.getData())); + System.out.println(new String(accumulator.getData(), StandardCharsets.UTF_8)); // deserialise XMLModelDeserialiser deserisaliser = new XMLModelDeserialiser(mock); diff --git a/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/StgSerialisationTests.java b/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/StgSerialisationTests.java index 13e8e230d..b6d5ade91 100644 --- a/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/StgSerialisationTests.java +++ b/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/StgSerialisationTests.java @@ -15,6 +15,8 @@ import org.workcraft.shared.DataAccumulator; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; +import java.nio.charset.StandardCharsets; + class StgSerialisationTests { @Test @@ -38,9 +40,9 @@ class StgSerialisationTests { DataAccumulator visualData = new DataAccumulator(); serialiser.serialise(stg, visualData, mathModelReferences); - System.out.println(new String(mathData.getData())); + System.out.println(new String(mathData.getData(), StandardCharsets.UTF_8)); System.out.println("---------------"); - System.out.println(new String(visualData.getData())); + System.out.println(new String(visualData.getData(), StandardCharsets.UTF_8)); // deserialise XMLModelDeserialiser deserialiser = new XMLModelDeserialiser(mockPluginManager); diff --git a/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/VisualModelSerialisationTests.java b/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/VisualModelSerialisationTests.java index 2948b0186..8a3f69b65 100644 --- a/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/VisualModelSerialisationTests.java +++ b/workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/VisualModelSerialisationTests.java @@ -16,6 +16,8 @@ import org.workcraft.shared.DataAccumulator; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; +import java.nio.charset.StandardCharsets; + class VisualModelSerialisationTests { @Test @@ -42,9 +44,9 @@ class VisualModelSerialisationTests { DataAccumulator visualData = new DataAccumulator(); serialiser.serialise(visualstg, visualData, mathModelReferences); - System.out.println(new String(mathData.getData())); + System.out.println(new String(mathData.getData(), StandardCharsets.UTF_8)); System.out.println("---------------"); - System.out.println(new String(visualData.getData())); + System.out.println(new String(visualData.getData(), StandardCharsets.UTF_8)); // deserialise XMLModelDeserialiser deserialiser = new XMLModelDeserialiser(mockPluginManager); diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/ErrorWindow.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/ErrorWindow.java index 3ee2e0745..074c2d377 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/ErrorWindow.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/ErrorWindow.java @@ -10,6 +10,7 @@ import java.awt.*; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.io.*; +import java.nio.charset.StandardCharsets; @SuppressWarnings("serial") public class ErrorWindow extends LogPanel implements ComponentListener { @@ -27,7 +28,7 @@ public class ErrorWindow extends LogPanel implements ComponentListener { if (systemErr != null) { systemErr.write(b); } - displayInEventDispatchThread(new String(b)); + displayInEventDispatchThread(new String(b, StandardCharsets.UTF_8)); } @Override @@ -35,7 +36,7 @@ public class ErrorWindow extends LogPanel implements ComponentListener { if (systemErr != null) { systemErr.write(b, off, len); } - displayInEventDispatchThread(new String(b, off, len)); + displayInEventDispatchThread(new String(b, off, len, StandardCharsets.UTF_8)); } private void displayInEventDispatchThread(String s) { diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/OutputWindow.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/OutputWindow.java index 45ab8d009..8504df41b 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/OutputWindow.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/OutputWindow.java @@ -9,6 +9,7 @@ import org.workcraft.utils.LogUtils; import javax.swing.*; import java.awt.*; import java.io.*; +import java.nio.charset.StandardCharsets; @SuppressWarnings("serial") public class OutputWindow extends LogPanel { @@ -28,7 +29,7 @@ public class OutputWindow extends LogPanel { if (systemOut != null) { systemOut.write(b); } - displayInEventDispatchThread(new String(b)); + displayInEventDispatchThread(new String(b, StandardCharsets.UTF_8)); } @Override @@ -36,7 +37,7 @@ public class OutputWindow extends LogPanel { if (systemOut != null) { systemOut.write(b, off, len); } - displayInEventDispatchThread(new String(b, off, len)); + displayInEventDispatchThread(new String(b, off, len, StandardCharsets.UTF_8)); } private void displayInEventDispatchThread(String text) { @@ -101,7 +102,7 @@ public class OutputWindow extends LogPanel { public void captureStream() { if (!streamCaptured) { OutputStreamView outView = new OutputStreamView(new ByteArrayOutputStream(), getTextArea()); - PrintStream outStream = new PrintStream(outView); + PrintStream outStream = new PrintStream(outView, true, StandardCharsets.UTF_8); systemOut = System.out; System.setOut(outStream); streamCaptured = true; diff --git a/workcraft/WorkcraftCore/src/org/workcraft/gui/tasks/TaskFailureNotifier.java b/workcraft/WorkcraftCore/src/org/workcraft/gui/tasks/TaskFailureNotifier.java index d877d0ea5..0e5ddb668 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/gui/tasks/TaskFailureNotifier.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/gui/tasks/TaskFailureNotifier.java @@ -5,6 +5,7 @@ import org.workcraft.tasks.Result; import org.workcraft.utils.DialogUtils; import javax.swing.*; +import java.nio.charset.StandardCharsets; public class TaskFailureNotifier extends BasicProgressMonitor<Object> { private final String description; @@ -16,7 +17,7 @@ public class TaskFailureNotifier extends BasicProgressMonitor<Object> { @Override public void stderr(byte[] data) { - errorMessage += new String(data); + errorMessage += new String(data, StandardCharsets.UTF_8); } @Override diff --git a/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessOutput.java b/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessOutput.java index 8f5447855..f6ac9fd9f 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessOutput.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessOutput.java @@ -2,6 +2,8 @@ package org.workcraft.tasks; import org.workcraft.utils.TextUtils; +import java.nio.charset.StandardCharsets; + public class ExternalProcessOutput { private final int returnCode; @@ -27,7 +29,7 @@ public class ExternalProcessOutput { } public String getStdoutString() { - return new String(stdout); + return new String(stdout, StandardCharsets.UTF_8); } public byte[] getStderr() { @@ -35,7 +37,7 @@ public class ExternalProcessOutput { } public String getStderrString() { - return new String(stderr); + return new String(stderr, StandardCharsets.UTF_8); } public String getErrorsHeadAndTail() { diff --git a/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessTask.java b/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessTask.java index 2fd9e3899..86e1e24bb 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessTask.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessTask.java @@ -7,6 +7,7 @@ import org.workcraft.utils.LogUtils; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.List; public class ExternalProcessTask implements Task<ExternalProcessOutput>, ExternalProcessListener { @@ -87,7 +88,7 @@ public class ExternalProcessTask implements Task<ExternalProcessOutput>, Externa } monitor.stdout(data); if (printStdout) { - String text = new String(data); + String text = new String(data, StandardCharsets.UTF_8); LogUtils.logStdout(text); } } @@ -101,7 +102,7 @@ public class ExternalProcessTask implements Task<ExternalProcessOutput>, Externa } monitor.stderr(data); if (printStderr) { - String text = new String(data); + String text = new String(data, StandardCharsets.UTF_8); LogUtils.logStderr(text); } } diff --git a/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java b/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java index a9a8b2552..80ce1da4f 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java @@ -45,7 +45,7 @@ public class FileUtils { public static void dumpString(File out, String string) throws IOException { try (FileOutputStream fos = new FileOutputStream(out)) { - fos.write(string.getBytes()); + fos.write(string.getBytes(StandardCharsets.UTF_8)); } } diff --git a/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java b/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java index f56b93f61..bc29d0adc 100644 --- a/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java +++ b/workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java @@ -521,7 +521,7 @@ public final class WorkUtils { String adjustedAttribute = attribute.replace(path, fileReference.getPath()); line = line.replace(attribute, adjustedAttribute); } - os.write(line.getBytes()); + os.write(line.getBytes(StandardCharsets.UTF_8)); } return new Resource(resource.getName(), os); }
['workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessTask.java', 'workcraft/WorkcraftCore/src/org/workcraft/utils/WorkUtils.java', 'workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoSolver.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/tasks/TaskFailureNotifier.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/OutputWindow.java', 'workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/tasks/ScencoExecutionSupport.java', 'workcraft/WorkcraftCore/src/org/workcraft/gui/ErrorWindow.java', 'workcraft/WorkcraftCore/src/org/workcraft/utils/FileUtils.java', 'workcraft/WorkcraftCore/src/org/workcraft/tasks/ExternalProcessOutput.java', 'workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/VisualModelSerialisationTests.java', 'workcraft/PlatoPlugin/src/org/workcraft/plugins/plato/tasks/PlatoResultHandler.java', 'workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/StgSerialisationTests.java', 'workcraft/StgPlugin/test-src/org/workcraft/plugins/stg/serialisation/MathModelSerialisationTests.java', 'workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/AlgebraExpressionFromGraphsCommand.java', 'workcraft/CpogPlugin/src/org/workcraft/plugins/cpog/commands/ExtractSelectedGraphsPGMinerCommand.java', 'workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/interop/VerilogImporter.java']
{'.java': 16}
16
16
0
0
16
6,505,747
1,321,941
176,174
1,751
4,972
856
81
16
780
113
186
10
0
0
2023-03-16T16:25:00
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
745
workcraft/workcraft/818/816
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/816
https://github.com/workcraft/workcraft/pull/818
https://github.com/workcraft/workcraft/pull/818#issuecomment-387678181
2
fixes
Selected non-leaf items without Checkbox are added to the checked list in TreeWindow component
To reproduce open _Parallel composition_ (or _N-way conformation_) dialog and select Workspace or External item. When Run button is clicked the composition process is interrupted with a null-pointer exception. This happens because the selected non-leaf item is interpreted as a path to a work file, even though it does not have an associated check-box.
3c135476689684d09ebba4acfe7daf7068c4d12a
ec7b1c4556a88d0bbd6ff1f2dc76e8eed6293ed5
https://github.com/workcraft/workcraft/compare/3c135476689684d09ebba4acfe7daf7068c4d12a...ec7b1c4556a88d0bbd6ff1f2dc76e8eed6293ed5
diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationNwayTask.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationNwayTask.java index 56f648611..013fea9aa 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationNwayTask.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationNwayTask.java @@ -95,7 +95,6 @@ public class MpsatConformationNwayTask implements Task<MpsatChainOutput> { // Generating .g for the whole system (model and environment) File stgFile = new File(directory, StgUtils.SYSTEM_FILE_PREFIX + stgFileExtension); File detailFile = new File(directory, StgUtils.DETAIL_FILE_PREFIX + StgUtils.XML_FILE_EXTENSION); - stgFile.deleteOnExit(); PcompTask pcompTask = new PcompTask(stgFiles.toArray(new File[0]), stgFile, detailFile, ConversionMode.OUTPUT, false, false, directory); diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationOutputHandler.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationOutputHandler.java index a4fe40b47..da052c031 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationOutputHandler.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationOutputHandler.java @@ -1,6 +1,7 @@ package org.workcraft.plugins.mpsat.tasks; import java.util.HashMap; +import java.util.HashSet; import org.workcraft.Trace; import org.workcraft.plugins.mpsat.MpsatParameters; @@ -11,6 +12,7 @@ import org.workcraft.plugins.petri.Place; import org.workcraft.plugins.stg.SignalTransition; import org.workcraft.plugins.stg.SignalTransition.Type; import org.workcraft.plugins.stg.StgModel; +import org.workcraft.plugins.stg.StgUtils; import org.workcraft.util.LogUtils; import org.workcraft.workspace.WorkspaceEntry; @@ -22,32 +24,42 @@ class MpsatConformationOutputHandler extends MpsatReachabilityOutputHandler { @Override public MpsatSolution processSolution(MpsatSolution solution, ComponentData data) { + final StgModel compStg = getMpsatOutput().getInputStg(); StgModel stg = getSrcStg(data); - if ((solution == null) || (stg == null)) { + if ((solution == null) || (compStg == null) || (stg == null)) { return solution; } - LogUtils.logMessage("Processing reported trace: " + solution.getMainTrace()); - Trace trace = getProjectedTrace(solution.getMainTrace(), data); MpsatSolution result = null; - HashMap<Place, Integer> marking = PetriUtils.getMarking(stg); - if (!PetriUtils.fireTrace(stg, trace)) { - LogUtils.logWarning("Cannot execute projected trace: " + trace); + Trace compTrace = solution.getMainTrace(); + LogUtils.logMessage("Processing reported composition trace: " + compTrace); + HashMap<Place, Integer> compMarking = PetriUtils.getMarking(compStg); + if (!PetriUtils.fireTrace(compStg, compTrace)) { + LogUtils.logError("Cannot execute reported composition trace: " + compTrace); } else { - for (SignalTransition transition: stg.getSignalTransitions()) { - if (stg.isEnabled(transition) && (transition.getSignalType() == Type.OUTPUT)) { - String signalRef = transition.getSignalName(); - LogUtils.logMessage("Output '" + signalRef + "' is unexpectedly enabled after projected trace: " + trace); - trace.add(stg.getNodeReference(transition)); - String comment = "Unexpected change of output '" + signalRef + "'"; - result = new MpsatSolution(trace, null, comment); - break; + HashSet<String> compEnabledSignals = StgUtils.getEnabledSignals(compStg); + Trace trace = getProjectedTrace(compTrace, data); + HashMap<Place, Integer> marking = PetriUtils.getMarking(stg); + if (!PetriUtils.fireTrace(stg, trace)) { + LogUtils.logError("Cannot execute projected trace: " + trace); + } else { + for (SignalTransition transition: stg.getSignalTransitions()) { + if (stg.isEnabled(transition) && (transition.getSignalType() == Type.OUTPUT) + && !compEnabledSignals.contains(transition.getSignalName())) { + String signalRef = transition.getSignalName(); + LogUtils.logWarning("Output '" + signalRef + "' is unexpectedly enabled after projected trace: " + trace); + trace.add(stg.getNodeReference(transition)); + String comment = "Unexpected change of output '" + signalRef + "'"; + result = new MpsatSolution(trace, null, comment); + break; + } + } + if (result == null) { + LogUtils.logMessage("No outputs are enabled after projected trace: " + trace); } } + PetriUtils.setMarking(stg, marking); } - PetriUtils.setMarking(stg, marking); - if (result == null) { - LogUtils.logMessage("No outputs are enabled after projected trace: " + trace); - } + PetriUtils.setMarking(compStg, compMarking); return result; } diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationTask.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationTask.java index 3446f51b4..331e5108e 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationTask.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationTask.java @@ -109,7 +109,6 @@ public class MpsatConformationTask extends MpsatChainTask { // Generating .g for the whole system (model and environment) File detailFile = new File(directory, StgUtils.DETAIL_FILE_PREFIX + StgUtils.XML_FILE_EXTENSION); File stgFile = new File(directory, StgUtils.SYSTEM_FILE_PREFIX + stgFileExtension); - stgFile.deleteOnExit(); PcompTask pcompTask = new PcompTask(new File[]{devStgFile, envStgFile}, stgFile, detailFile, ConversionMode.OUTPUT, true, false, directory); diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatCscConflictResolutionOutputHandler.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatCscConflictResolutionOutputHandler.java index 330fca014..9f1e7d944 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatCscConflictResolutionOutputHandler.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatCscConflictResolutionOutputHandler.java @@ -1,16 +1,13 @@ package org.workcraft.plugins.mpsat.tasks; -import java.io.ByteArrayInputStream; import java.util.Collection; import org.workcraft.Framework; -import org.workcraft.exceptions.DeserialisationException; import org.workcraft.gui.workspace.Path; import org.workcraft.plugins.stg.Mutex; import org.workcraft.plugins.stg.MutexUtils; import org.workcraft.plugins.stg.StgDescriptor; import org.workcraft.plugins.stg.StgModel; -import org.workcraft.plugins.stg.interop.StgImporter; import org.workcraft.util.DialogUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; @@ -29,22 +26,10 @@ public class MpsatCscConflictResolutionOutputHandler implements Runnable { this.mutexes = mutexes; } - private StgModel getResolvedStg() { - final byte[] content = output.getStgOutput(); - if (content == null) { - return null; - } - try { - return new StgImporter().importStg(new ByteArrayInputStream(content)); - } catch (final DeserialisationException e) { - throw new RuntimeException(e); - } - } - @Override public void run() { final Framework framework = Framework.getInstance(); - final StgModel model = getResolvedStg(); + final StgModel model = output.getOutputStg(); if (model == null) { final String errorMessage = output.getErrorsHeadAndTail(); DialogUtils.showWarning("Conflict resolution failed. MPSat output: \\n" + errorMessage); diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutput.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutput.java index c5720beac..93afdebdc 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutput.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutput.java @@ -1,28 +1,29 @@ package org.workcraft.plugins.mpsat.tasks; import org.workcraft.plugins.shared.tasks.ExternalProcessOutput; +import org.workcraft.plugins.stg.StgModel; public class MpsatOutput extends ExternalProcessOutput { - private final byte[] stgInput; - private final byte[] stgOutput; + private final StgModel inputStg; + private final StgModel outputStg; public MpsatOutput(ExternalProcessOutput output) { this(output, null, null); } - public MpsatOutput(ExternalProcessOutput output, byte[] stgInput, byte[] stgOutput) { + public MpsatOutput(ExternalProcessOutput output, StgModel inputStg, StgModel outputStg) { super(output.getReturnCode(), output.getStdout(), output.getStderr()); - this.stgInput = stgInput; - this.stgOutput = stgOutput; + this.inputStg = inputStg; + this.outputStg = outputStg; } - public byte[] getStgInput() { - return stgInput; + public StgModel getInputStg() { + return inputStg; } - public byte[] getStgOutput() { - return stgOutput; + public StgModel getOutputStg() { + return outputStg; } } diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutputPersistencyOutputHandler.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutputPersistencyOutputHandler.java index 9a72a7836..8be3b5837 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutputPersistencyOutputHandler.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutputPersistencyOutputHandler.java @@ -11,8 +11,8 @@ import org.workcraft.plugins.pcomp.tasks.PcompOutput; import org.workcraft.plugins.petri.PetriUtils; import org.workcraft.plugins.petri.Place; import org.workcraft.plugins.stg.SignalTransition; -import org.workcraft.plugins.stg.SignalTransition.Type; import org.workcraft.plugins.stg.StgModel; +import org.workcraft.plugins.stg.StgUtils; import org.workcraft.util.LogUtils; import org.workcraft.workspace.WorkspaceEntry; @@ -35,12 +35,12 @@ class MpsatOutputPersistencyOutputHandler extends MpsatReachabilityOutputHandler if (!PetriUtils.fireTrace(stg, trace)) { LogUtils.logWarning("Cannot execute projected trace: " + trace); } else { - HashSet<String> enabledLocalSignals = getEnabledLocalSignals(stg); - for (SignalTransition transition: getEnabledSignalTransitions(stg)) { + HashSet<String> enabledLocalSignals = StgUtils.getEnabledLocalSignals(stg); + for (SignalTransition transition: StgUtils.getEnabledSignalTransitions(stg)) { stg.fire(transition); HashSet<String> nonpersistentLocalSignals = new HashSet<>(enabledLocalSignals); nonpersistentLocalSignals.remove(transition.getSignalName()); - nonpersistentLocalSignals.removeAll(getEnabledLocalSignals(stg)); + nonpersistentLocalSignals.removeAll(StgUtils.getEnabledLocalSignals(stg)); if (!nonpersistentLocalSignals.isEmpty()) { String comment = null; String signalList = ReferenceHelper.getReferencesAsString(nonpersistentLocalSignals); @@ -64,24 +64,4 @@ class MpsatOutputPersistencyOutputHandler extends MpsatReachabilityOutputHandler return result; } - private HashSet<SignalTransition> getEnabledSignalTransitions(StgModel stg) { - HashSet<SignalTransition> result = new HashSet<>(); - for (SignalTransition transition: stg.getSignalTransitions()) { - if (stg.isEnabled(transition)) { - result.add(transition); - } - } - return result; - } - - private HashSet<String> getEnabledLocalSignals(StgModel stg) { - HashSet<String> result = new HashSet<>(); - for (SignalTransition transition: getEnabledSignalTransitions(stg)) { - if ((transition.getSignalType() == Type.OUTPUT) || (transition.getSignalType() == Type.INTERNAL)) { - result.add(transition.getSignalName()); - } - } - return result; - } - } diff --git a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatTask.java b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatTask.java index 6b1385db6..5fee4c948 100644 --- a/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatTask.java +++ b/MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatTask.java @@ -1,15 +1,19 @@ package org.workcraft.plugins.mpsat.tasks; import java.io.File; -import java.io.IOException; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.workcraft.exceptions.DeserialisationException; import org.workcraft.plugins.mpsat.MpsatSettings; import org.workcraft.plugins.punf.tasks.PunfTask; import org.workcraft.plugins.shared.tasks.ExternalProcessOutput; import org.workcraft.plugins.shared.tasks.ExternalProcessTask; +import org.workcraft.plugins.stg.StgModel; +import org.workcraft.plugins.stg.interop.StgImporter; import org.workcraft.tasks.ProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; @@ -135,21 +139,9 @@ public class MpsatTask implements Task<MpsatOutput> { if (!success) { return Result.failure(new MpsatOutput(output)); } else { - byte[] netInput = null; - byte[] stgOutput = null; - try { - if ((netFile != null) && netFile.exists()) { - netInput = FileUtils.readAllBytes(netFile); - } - File stgFile = new File(directory, STG_FILE_NAME); - if (stgFile.exists()) { - stgOutput = FileUtils.readAllBytes(stgFile); - } - } catch (IOException e) { - return Result.exception(e); - } - - return Result.success(new MpsatOutput(output, netInput, stgOutput)); + StgModel inputStg = readStg(netFile); + StgModel outputStg = readStg(new File(directory, STG_FILE_NAME)); + return Result.success(new MpsatOutput(output, inputStg, outputStg)); } } @@ -160,4 +152,17 @@ public class MpsatTask implements Task<MpsatOutput> { return Result.failure(); } + private StgModel readStg(File file) { + if ((file != null) && file.exists()) { + try { + StgImporter importer = new StgImporter(); + FileInputStream is = new FileInputStream(file); + return importer.importStg(is); + } catch (final DeserialisationException | FileNotFoundException e) { + throw new RuntimeException(e); + } + } + return null; + } + } diff --git a/StgPlugin/src/org/workcraft/plugins/stg/StgUtils.java b/StgPlugin/src/org/workcraft/plugins/stg/StgUtils.java index ad2778573..96001d8b8 100644 --- a/StgPlugin/src/org/workcraft/plugins/stg/StgUtils.java +++ b/StgPlugin/src/org/workcraft/plugins/stg/StgUtils.java @@ -4,6 +4,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Collection; +import java.util.HashSet; import java.util.Set; import org.workcraft.Framework; @@ -198,4 +199,32 @@ public class StgUtils { return result; } + public static HashSet<SignalTransition> getEnabledSignalTransitions(StgModel stg) { + HashSet<SignalTransition> result = new HashSet<>(); + for (SignalTransition transition: stg.getSignalTransitions()) { + if (stg.isEnabled(transition)) { + result.add(transition); + } + } + return result; + } + + public static HashSet<String> getEnabledLocalSignals(StgModel stg) { + HashSet<String> result = new HashSet<>(); + for (SignalTransition transition: getEnabledSignalTransitions(stg)) { + if ((transition.getSignalType() == Type.OUTPUT) || (transition.getSignalType() == Type.INTERNAL)) { + result.add(transition.getSignalName()); + } + } + return result; + } + + public static HashSet<String> getEnabledSignals(StgModel stg) { + HashSet<String> result = new HashSet<>(); + for (SignalTransition transition: getEnabledSignalTransitions(stg)) { + result.add(transition.getSignalName()); + } + return result; + } + } diff --git a/WorkcraftCore/src/org/workcraft/gui/trees/TreeWindow.java b/WorkcraftCore/src/org/workcraft/gui/trees/TreeWindow.java index cd31409eb..148078407 100644 --- a/WorkcraftCore/src/org/workcraft/gui/trees/TreeWindow.java +++ b/WorkcraftCore/src/org/workcraft/gui/trees/TreeWindow.java @@ -29,40 +29,43 @@ import info.clearthought.layout.TableLayout; public class TreeWindow<Node> extends JPanel { - private final class RefreshKeyAdapter extends KeyAdapter { + private final class TreeSourceAdapterImplementation extends TreeSourceAdapter<Node> { + private final TreeDecorator<Node> decorator; private final TreeSource<Node> source; - private RefreshKeyAdapter(TreeSource<Node> source) { + private TreeSourceAdapterImplementation(TreeSource<Node> source, TreeDecorator<Node> decorator) { + super(source); + this.decorator = decorator; this.source = source; } @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_F5) { - sourceWithRestructuredTrapped.getListener().restructured(Path.root(source.getRoot())); - } - } - } + public TreeListener<Node> getListener(final TreeListener<Node> chain) { + return new TreeListenerAdapter<Node>(chain) { + @Override + public void restructured(Path<Node> path) { + List<TreePath> expanded = new ArrayList<>(); + for (int i = 0; i < tree.getRowCount(); i++) { + final TreePath treePath = tree.getPathForRow(i); + if (tree.isExpanded(i)) { + expanded.add(treePath); + } + } - private final class ClickMouseAdapter extends MouseAdapter { - @SuppressWarnings("unchecked") - @Override - public void mouseClicked(MouseEvent e) { - final int x = e.getX(); - final int y = e.getY(); - int row = tree.getClosestRowForLocation(x, y); - if (row != -1) { - final Rectangle rowBounds = tree.getRowBounds(row); - if (rowBounds.contains(x, y)) { - Node node = (Node) tree.getPathForRow(row).getLastPathComponent(); - if (checkedNodes.contains(node)) { - checkedNodes.remove(node); - } else { - checkedNodes.add(node); + if (!externalExpanded) { + for (Node n : source.getChildren(getRoot())) { + if (Workspace.EXTERNAL_PATH.equals(decorator.getName(n))) { + expanded.add(new TreePath(Path.getPath(source.getPath(n)).toArray())); + externalExpanded = true; + } + } + } + super.restructured(path); + for (TreePath p : expanded) { + tree.expandPath(p); } - tree.repaint(rowBounds); } - } + }; } } @@ -99,6 +102,37 @@ public class TreeWindow<Node> extends JPanel { } } + private final class ClickMouseAdapter extends MouseAdapter { + private final TreeSource<Node> source; + + private ClickMouseAdapter(TreeSource<Node> source) { + this.source = source; + } + + @Override + public void mouseClicked(MouseEvent e) { + final int x = e.getX(); + final int y = e.getY(); + int row = tree.getClosestRowForLocation(x, y); + if (row != -1) { + final Rectangle rowBounds = tree.getRowBounds(row); + if (rowBounds.contains(x, y)) { + @SuppressWarnings("unchecked") + Node node = (Node) tree.getPathForRow(row).getLastPathComponent(); + if ((checkBoxMode == CheckBoxMode.ALL) + || ((checkBoxMode == CheckBoxMode.LEAF) && source.isLeaf(node))) { + if (checkedNodes.contains(node)) { + checkedNodes.remove(node); + } else { + checkedNodes.add(node); + } + tree.repaint(rowBounds); + } + } + } + } + } + private final class TreeCellRenderer extends DefaultTreeCellRenderer { private final TreeSource<Node> source; private final TreeDecorator<Node> decorator; @@ -119,12 +153,12 @@ public class TreeWindow<Node> extends JPanel { layout.setVGap(SizeHelper.getLayoutVGap()); } - @SuppressWarnings("unchecked") @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { + @SuppressWarnings("unchecked") Node node = (Node) value; String name = decorator.getName(node); @@ -144,67 +178,29 @@ public class TreeWindow<Node> extends JPanel { setIcon(icon); } cellRenderer.removeAll(); - - switch (checkBoxMode) { - case NONE: + if ((checkBoxMode == CheckBoxMode.NONE) || ((checkBoxMode == CheckBoxMode.LEAF) && !source.isLeaf(node))) { return res; - case LEAF: - if (source.isLeaf(node)) { - cellRenderer.add(checkBox, "0 0"); - cellRenderer.add(res, "1 0"); - } else { - return res; - } - - break; - case ALL: - cellRenderer.add(checkBox, "0 0"); - cellRenderer.add(res, "1 0"); - break; } - + cellRenderer.add(checkBox, "0 0"); + cellRenderer.add(res, "1 0"); checkBox.setSelected(checkedNodes.contains(node)); return cellRenderer; } } - private final class TreeSourceAdapterImplementation extends TreeSourceAdapter<Node> { - private final TreeDecorator<Node> decorator; + private final class RefreshKeyAdapter extends KeyAdapter { private final TreeSource<Node> source; - private TreeSourceAdapterImplementation(TreeSource<Node> source, TreeDecorator<Node> decorator) { - super(source); - this.decorator = decorator; + private RefreshKeyAdapter(TreeSource<Node> source) { this.source = source; } @Override - public TreeListener<Node> getListener(final TreeListener<Node> chain) { - return new TreeListenerAdapter<Node>(chain) { - @Override - public void restructured(Path<Node> path) { - List<TreePath> expanded = new ArrayList<>(); - for (int i = 0; i < tree.getRowCount(); i++) { - final TreePath treePath = tree.getPathForRow(i); - if (tree.isExpanded(i)) { - expanded.add(treePath); - } - } - - if (!externalExpanded) { - for (Node n : source.getChildren(getRoot())) { - if (Workspace.EXTERNAL_PATH.equals(decorator.getName(n))) { - expanded.add(new TreePath(Path.getPath(source.getPath(n)).toArray())); - externalExpanded = true; - } - } - } - super.restructured(path); - for (TreePath p : expanded) { - tree.expandPath(p); - } - } - }; + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_F5) { + Path<Node> root = Path.root(source.getRoot()); + sourceWithRestructuredTrapped.getListener().restructured(root); + } } } @@ -218,7 +214,6 @@ public class TreeWindow<Node> extends JPanel { private final TreePopupProvider<Node> popupProvider; private final Set<Node> checkedNodes = new HashSet<>(); private CheckBoxMode checkBoxMode = CheckBoxMode.NONE; - private JCheckBox checkBox; public TreeWindow(TreeSource<Node> source, TreeDecorator<Node> decorator, TreePopupProvider<Node> popupProvider) { @@ -242,7 +237,8 @@ public class TreeWindow<Node> extends JPanel { public void setCheckBoxMode(CheckBoxMode mode) { this.checkBoxMode = mode; checkedNodes.clear(); - sourceWithRestructuredTrapped.getListener().restructured(Path.root(sourceWithRestructuredTrapped.getRoot())); + Path<Node> root = Path.root(sourceWithRestructuredTrapped.getRoot()); + sourceWithRestructuredTrapped.getListener().restructured(root); } public void clearCheckBoxes() { @@ -271,7 +267,7 @@ public class TreeWindow<Node> extends JPanel { if (popupProvider != null) { tree.addMouseListener(new PopupMouseAdapter(source)); } - tree.addMouseListener(new ClickMouseAdapter()); + tree.addMouseListener(new ClickMouseAdapter(source)); tree.setCellRenderer(new TreeCellRenderer(source, decorator)); tree.addKeyListener(new RefreshKeyAdapter(source)); setLayout(new BorderLayout());
['MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutputPersistencyOutputHandler.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatCscConflictResolutionOutputHandler.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationOutputHandler.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatTask.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatOutput.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationNwayTask.java', 'WorkcraftCore/src/org/workcraft/gui/trees/TreeWindow.java', 'StgPlugin/src/org/workcraft/plugins/stg/StgUtils.java', 'MpsatVerificationPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatConformationTask.java']
{'.java': 9}
9
9
0
0
9
5,066,047
1,026,630
141,767
1,467
15,874
3,010
330
9
353
54
70
1
0
0
2018-05-03T17:37:17
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License
751
workcraft/workcraft/1232/1231
workcraft
workcraft
https://github.com/workcraft/workcraft/issues/1231
https://github.com/workcraft/workcraft/pull/1232
https://github.com/workcraft/workcraft/pull/1232
1
fixes
Simulation of Circuit model does not highlight suggested component
**To reproduce:** Start simulating a Circuit model and thengo few steps back in the simulation trace **Observed behaviour:** Excited components/ports/pins are highlighted in orange (but no "suggested" component/port/pin with green background). **Expected behaviour:** The next component/port/pin in the simulation trace should be highlighted with green background. The same issue is also applicable to DFS model.
a1e8e5cc701e67633c463dd786c2da33a6e5aeea
ac6ec12c632870e6d4a8efa6e27f1f7f7bdb4df4
https://github.com/workcraft/workcraft/compare/a1e8e5cc701e67633c463dd786c2da33a6e5aeea...ac6ec12c632870e6d4a8efa6e27f1f7f7bdb4df4
diff --git a/workcraft/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java b/workcraft/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java index 2171f42a4..352627395 100644 --- a/workcraft/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java +++ b/workcraft/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java @@ -397,7 +397,7 @@ public class StgSimulationTool extends PetriSimulationTool { @Override public MathNode getUnderlyingNode(String ref) { - return refToUnderlyingNodeMap == null ? null : refToUnderlyingNodeMap.get(ref); + return refToUnderlyingNodeMap == null ? super.getUnderlyingNode(ref) : refToUnderlyingNodeMap.get(ref); } @Override
['workcraft/StgPlugin/src/org/workcraft/plugins/stg/tools/StgSimulationTool.java']
{'.java': 1}
1
1
0
0
1
6,087,301
1,237,680
165,835
1,689
201
50
2
1
424
55
87
10
0
0
2021-04-27T13:53:39
40
Java
{'Java': 6571756, 'JavaScript': 53266, 'Verilog': 30738, 'Shell': 13097, 'GAP': 11313, 'Kotlin': 3511}
MIT License