use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse in project aws-greengrass-nucleus by aws-greengrass.
the class IPCPubSubTest method GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds.
@SuppressWarnings({ "PMD.AvoidCatchingGenericException" })
@Test
void GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds() throws Exception {
LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
String topicName = "topicName";
SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
subscribeToTopicRequest.setTopic(topicName);
CountDownLatch subscriptionLatch = new CountDownLatch(1);
Slf4jLogAdapter.addGlobalListener(m -> {
if (m.getMessage().contains("Subscribed to topic")) {
subscriptionLatch.countDown();
}
});
String authToken = IPCTestUtils.getAuthTokeForService(kernel, "OnlyPublish");
SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse();
ExecutionException executionException = assertThrows(ExecutionException.class, () -> fut.get(3, TimeUnit.SECONDS));
assertTrue(executionException.getCause() instanceof UnauthorizedError);
UnauthorizedError unauthorizedError = (UnauthorizedError) executionException.getCause();
assertEquals("Principal OnlyPublish is not authorized to perform aws.greengrass.ipc.pubsub:aws.greengrass#SubscribeToTopic on resource topicName", unauthorizedError.getMessage());
}
Topics aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
Map<String, Object> newAcl = OBJECT_MAPPER.readValue(newAclStr, new TypeReference<Map<String, Object>>() {
});
aclTopic.updateFromMap(newAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
// Block until events are completed
kernel.getContext().waitForPublishQueueToClear();
assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse();
try {
fut.get(3, TimeUnit.SECONDS);
} catch (Exception e) {
logger.atError().setCause(e).log("Error when subscribing to component updates");
fail("Caught exception when subscribing to component updates");
}
assertTrue(subscriptionLatch.await(10, TimeUnit.SECONDS));
}
aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
Map<String, Object> oldAcl = OBJECT_MAPPER.readValue(oldAclStr, new TypeReference<Map<String, Object>>() {
});
aclTopic.updateFromMap(oldAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
// Block until events are completed
kernel.getContext().runOnPublishQueueAndWait(() -> {
});
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse in project aws-greengrass-nucleus by aws-greengrass.
the class PubSubIPCEventStreamAgentTest method GIVEN_subscribe_topic_to_all_sources_WHEN_subscribe_THEN_added_all_services_listeners.
@Test
void GIVEN_subscribe_topic_to_all_sources_WHEN_subscribe_THEN_added_all_services_listeners() throws AuthorizationException {
SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
subscribeToTopicRequest.setTopic(TEST_TOPIC);
try (PubSubIPCEventStreamAgent.SubscribeToTopicOperationHandler subscribeToTopicHandler = pubSubIPCEventStreamAgent.getSubscribeToTopicHandler(mockContext)) {
SubscribeToTopicResponse subscribeToTopicResponse = subscribeToTopicHandler.handleRequest(subscribeToTopicRequest);
assertNotNull(subscribeToTopicResponse);
verify(authorizationHandler).isAuthorized(eq(PUB_SUB_SERVICE_NAME), permissionArgumentCaptor.capture(), eq(ResourceLookupPolicy.MQTT_STYLE));
Permission capturedPermission = permissionArgumentCaptor.getValue();
assertThat(capturedPermission.getOperation(), is(GreengrassCoreIPCService.SUBSCRIBE_TO_TOPIC));
assertThat(capturedPermission.getPrincipal(), is(TEST_SERVICE));
assertThat(capturedPermission.getResource(), is(TEST_TOPIC));
assertTrue(pubSubIPCEventStreamAgent.getListeners().containsKey(TEST_TOPIC));
assertEquals(1, pubSubIPCEventStreamAgent.getListeners().get(TEST_TOPIC).size());
}
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse in project aws-iot-device-sdk-java-v2 by aws.
the class GreengrassV2ClientTest method testV2Client.
@Test
public void testV2Client() throws InterruptedException, ExecutionException, TimeoutException {
assertEquals(authenticationRequest.getAuthToken(), "myAuthToken");
CreateLocalDeploymentResponse depResp = client.createLocalDeployment(new CreateLocalDeploymentRequest());
assertEquals("deployment", depResp.getDeploymentId());
CompletableFuture<CreateLocalDeploymentResponse> asyncDepResp = client.createLocalDeploymentAsync(new CreateLocalDeploymentRequest());
assertEquals("deployment", asyncDepResp.get().getDeploymentId());
CompletableFuture<String> receivedMessage = new CompletableFuture<>();
CompletableFuture<String> finalReceivedMessage = receivedMessage;
GreengrassCoreIPCClientV2.StreamingResponse<SubscribeToTopicResponse, SubscribeToTopicResponseHandler> subResp = client.subscribeToTopic(new SubscribeToTopicRequest().withTopic("abc"), (x) -> {
if (!Thread.currentThread().getName().contains("pool")) {
System.out.println(Thread.currentThread().getName());
finalReceivedMessage.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
}
finalReceivedMessage.complete(new String(x.getBinaryMessage().getMessage()));
}, Optional.empty(), Optional.empty());
assertEquals("message", receivedMessage.get());
subResp.getHandler().closeStream().get();
subscriptionClosed.get(1, TimeUnit.SECONDS);
subscriptionClosed = new CompletableFuture<>();
receivedMessage = new CompletableFuture<>();
CompletableFuture<String> finalReceivedMessage1 = receivedMessage;
subResp = client.subscribeToTopic(new SubscribeToTopicRequest().withTopic("abc"), new StreamResponseHandler<SubscriptionResponseMessage>() {
@Override
public void onStreamEvent(SubscriptionResponseMessage streamEvent) {
if (!Thread.currentThread().getName().contains("pool")) {
finalReceivedMessage1.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
}
finalReceivedMessage1.complete(new String(streamEvent.getBinaryMessage().getMessage()));
}
@Override
public boolean onStreamError(Throwable error) {
return false;
}
@Override
public void onStreamClosed() {
}
});
assertEquals("message", receivedMessage.get());
subResp.getHandler().closeStream().get();
subscriptionClosed.get(1, TimeUnit.SECONDS);
subscriptionClosed = new CompletableFuture<>();
receivedMessage = new CompletableFuture<>();
CompletableFuture<String> finalReceivedMessage2 = receivedMessage;
GreengrassCoreIPCClientV2.StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> subRespAsync = client.subscribeToTopicAsync(new SubscribeToTopicRequest().withTopic("abc"), new StreamResponseHandler<SubscriptionResponseMessage>() {
@Override
public void onStreamEvent(SubscriptionResponseMessage streamEvent) {
if (!Thread.currentThread().getName().contains("pool")) {
finalReceivedMessage2.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
}
finalReceivedMessage2.complete(new String(streamEvent.getBinaryMessage().getMessage()));
}
@Override
public boolean onStreamError(Throwable error) {
return false;
}
@Override
public void onStreamClosed() {
}
});
assertEquals("message", receivedMessage.get());
subRespAsync.getHandler().closeStream().get();
subscriptionClosed.get(1, TimeUnit.SECONDS);
subscriptionClosed = new CompletableFuture<>();
receivedMessage = new CompletableFuture<>();
CompletableFuture<String> finalReceivedMessage3 = receivedMessage;
subRespAsync = client.subscribeToTopicAsync(new SubscribeToTopicRequest().withTopic("abc"), (x) -> {
if (!Thread.currentThread().getName().contains("pool")) {
finalReceivedMessage3.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
}
finalReceivedMessage3.complete(new String(x.getBinaryMessage().getMessage()));
}, Optional.empty(), Optional.empty());
assertEquals("message", receivedMessage.get());
subRespAsync.getHandler().closeStream().get();
subscriptionClosed.get(1, TimeUnit.SECONDS);
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse in project aws-iot-device-sdk-java-v2 by aws.
the class GreengrassV2ClientTest method before.
@BeforeEach
public void before() throws IOException {
port = randomPort();
try (final EventLoopGroup elGroup = new EventLoopGroup(1);
SocketOptions socketOptions = new SocketOptions()) {
socketOptions.connectTimeoutMs = 3000;
socketOptions.domain = SocketOptions.SocketDomain.IPv4;
socketOptions.type = SocketOptions.SocketType.STREAM;
GreengrassCoreIPCService service = new GreengrassCoreIPCService();
service.setCreateLocalDeploymentHandler((c) -> new GeneratedAbstractCreateLocalDeploymentOperationHandler(c) {
@Override
protected void onStreamClosed() {
}
@Override
public CreateLocalDeploymentResponse handleRequest(CreateLocalDeploymentRequest request) {
return new CreateLocalDeploymentResponse().withDeploymentId("deployment");
}
@Override
public void handleStreamEvent(EventStreamJsonMessage streamRequestEvent) {
}
});
service.setSubscribeToTopicHandler((c) -> new GeneratedAbstractSubscribeToTopicOperationHandler(c) {
@Override
protected void onStreamClosed() {
subscriptionClosed.complete(null);
}
@Override
public SubscribeToTopicResponse handleRequest(SubscribeToTopicRequest request) {
new Thread(() -> {
sendStreamEvent(new SubscriptionResponseMessage().withBinaryMessage(new BinaryMessage().withMessage("message".getBytes(StandardCharsets.UTF_8))));
}).start();
return new SubscribeToTopicResponse().withTopicName(request.getTopic());
}
@Override
public void handleStreamEvent(EventStreamJsonMessage streamRequestEvent) {
}
});
service.setAuthenticationHandler((headers, bytes) -> {
authenticationRequest = new Gson().fromJson(new String(bytes), GreengrassEventStreamConnectMessage.class);
return () -> "connected";
});
service.setAuthorizationHandler(authenticationData -> Authorization.ACCEPT);
ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service);
ipcServer.runServer();
client = GreengrassCoreIPCClientV2.builder().withPort(port).withSocketPath("127.0.0.1").withSocketDomain(SocketOptions.SocketDomain.IPv4).withAuthToken("myAuthToken").build();
}
}
use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse in project aws-greengrass-nucleus by aws-greengrass.
the class IPCPubSubTest method GIVEN_PubSubEventStreamClient_WHEN_subscribe_and_unsubscribe_THEN_publishes_only_once.
@Test
@SuppressWarnings({ "PMD.AvoidCatchingGenericException" })
void GIVEN_PubSubEventStreamClient_WHEN_subscribe_and_unsubscribe_THEN_publishes_only_once() throws Exception {
LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
String topicName = "topicName";
SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
subscribeToTopicRequest.setTopic(topicName);
CountDownLatch cdl = new CountDownLatch(1);
AtomicInteger atomicInteger = new AtomicInteger();
CountDownLatch subscriptionLatch = new CountDownLatch(1);
String authToken = IPCTestUtils.getAuthTokeForService(kernel, "SubscribeAndPublish");
SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel);
AutoCloseable l = TestUtils.createCloseableLogListener(m -> {
if (m.getMessage().contains("Subscribed to topic")) {
subscriptionLatch.countDown();
}
})) {
GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, Optional.of(new StreamResponseHandler<SubscriptionResponseMessage>() {
@Override
public void onStreamEvent(SubscriptionResponseMessage message) {
assertNotNull(message.getBinaryMessage());
assertNull(message.getJsonMessage());
assertEquals("ABCDEFG", new String(message.getBinaryMessage().getMessage()));
atomicInteger.incrementAndGet();
cdl.countDown();
}
@Override
public boolean onStreamError(Throwable error) {
logger.atError().log("Received a stream error", error);
return false;
}
@Override
public void onStreamClosed() {
}
})).getResponse();
try {
fut.get(3, TimeUnit.SECONDS);
} catch (Exception e) {
logger.atError().setCause(e).log("Error when subscribing to component updates");
fail("Caught exception when subscribing to component updates");
}
assertTrue(subscriptionLatch.await(10, TimeUnit.SECONDS));
publishToTopicOverIpcAsBinaryMessage(greengrassCoreIPCClient, topicName, "ABCDEFG");
assertTrue(cdl.await(20, TimeUnit.SECONDS));
}
}
Aggregations