Search in sources :

Example 1 with BinaryMessage

use of software.amazon.awssdk.aws.greengrass.model.BinaryMessage in project aws-greengrass-nucleus by aws-greengrass.

the class IPCTestUtils method publishToTopicOverIpcAsBinaryMessage.

public static void publishToTopicOverIpcAsBinaryMessage(GreengrassCoreIPCClient ipcClient, String topic, String message) throws InterruptedException, ExecutionException, TimeoutException {
    PublishToTopicRequest publishToTopicRequest = new PublishToTopicRequest();
    publishToTopicRequest.setTopic(topic);
    PublishMessage publishMessage = new PublishMessage();
    BinaryMessage binaryMessage = new BinaryMessage();
    binaryMessage.setMessage(message.getBytes(StandardCharsets.UTF_8));
    publishMessage.setBinaryMessage(binaryMessage);
    publishToTopicRequest.setPublishMessage(publishMessage);
    ipcClient.publishToTopic(publishToTopicRequest, Optional.empty()).getResponse().get(5, TimeUnit.SECONDS);
}
Also used : PublishMessage(software.amazon.awssdk.aws.greengrass.model.PublishMessage) PublishToTopicRequest(software.amazon.awssdk.aws.greengrass.model.PublishToTopicRequest) BinaryMessage(software.amazon.awssdk.aws.greengrass.model.BinaryMessage)

Example 2 with BinaryMessage

use of software.amazon.awssdk.aws.greengrass.model.BinaryMessage in project aws-greengrass-nucleus by aws-greengrass.

the class PubSubIPCEventStreamAgent method handlePublishToTopicRequest.

@SuppressWarnings("PMD.PreserveStackTrace")
private PublishToTopicResponse handlePublishToTopicRequest(String topic, String serviceName, Optional<Map<String, Object>> jsonMessage, Optional<byte[]> binaryMessage) {
    if (topic == null) {
        throw new InvalidArgumentsError("Publish topic must not be null");
    }
    if (topic.contains(MQTT_SINGLELEVEL_WILDCARD) || topic.contains(MQTT_MULTILEVEL_WILDCARD) || topic.contains(GLOB_WILDCARD)) {
        throw new InvalidArgumentsError("Publish topic must not contain a wildcard.");
    }
    Set<Object> contexts = listeners.get(topic);
    if (contexts == null || contexts.isEmpty()) {
        log.atDebug().kv(COMPONENT_NAME, serviceName).log("No one subscribed to topic {}. Returning.", topic);
        // Still technically successful, just no one was subscribed
        return new PublishToTopicResponse();
    }
    SubscriptionResponseMessage message = new SubscriptionResponseMessage();
    PublishEvent publishedEvent = PublishEvent.builder().topic(topic).build();
    if (jsonMessage.isPresent()) {
        JsonMessage message1 = new JsonMessage();
        message1.setMessage(jsonMessage.get());
        message1.setEventTopic(topic);
        message.setJsonMessage(message1);
        try {
            publishedEvent.setPayload(SERIALIZER.writeValueAsBytes(jsonMessage.get()));
        } catch (JsonProcessingException e) {
            log.atError().cause(e).kv(COMPONENT_NAME, serviceName).log("Unable to serialize JSON message.");
            throw new InvalidArgumentsError("Unable to serialize payload as JSON");
        }
    }
    if (binaryMessage.isPresent()) {
        BinaryMessage binaryMessage1 = new BinaryMessage();
        binaryMessage1.setMessage(binaryMessage.get());
        binaryMessage1.setEventTopic(topic);
        message.setBinaryMessage(binaryMessage1);
        publishedEvent.setPayload(binaryMessage.get());
    }
    contexts.forEach(context -> {
        log.atDebug().kv(COMPONENT_NAME, serviceName).log("Sending publish event for topic {}", topic);
        if (context instanceof StreamEventPublisher) {
            StreamEventPublisher<SubscriptionResponseMessage> publisher = (StreamEventPublisher<SubscriptionResponseMessage>) context;
            orderedExecutorService.execute(() -> publisher.sendStreamEvent(message), publisher);
        } else if (context instanceof Consumer) {
            Consumer<PublishEvent> consumer = (Consumer<PublishEvent>) context;
            orderedExecutorService.execute(() -> consumer.accept(publishedEvent), consumer);
        }
    });
    return new PublishToTopicResponse();
}
Also used : InvalidArgumentsError(software.amazon.awssdk.aws.greengrass.model.InvalidArgumentsError) PublishToTopicResponse(software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) Consumer(java.util.function.Consumer) JsonMessage(software.amazon.awssdk.aws.greengrass.model.JsonMessage) EventStreamJsonMessage(software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StreamEventPublisher(software.amazon.awssdk.eventstreamrpc.StreamEventPublisher) BinaryMessage(software.amazon.awssdk.aws.greengrass.model.BinaryMessage)

Example 3 with BinaryMessage

use of software.amazon.awssdk.aws.greengrass.model.BinaryMessage in project aws-greengrass-nucleus by aws-greengrass.

the class PubSubIPCEventStreamAgentTest method GIVEN_subscribed_to_topic_from_all_sources_WHEN_publish_many_binary_message_THEN_publishes_message_inorder.

@Test
void GIVEN_subscribed_to_topic_from_all_sources_WHEN_publish_many_binary_message_THEN_publishes_message_inorder() throws InterruptedException, AuthorizationException {
    StreamEventPublisher publisher = mock(StreamEventPublisher.class);
    Set<Object> set = new HashSet<>();
    set.add(publisher);
    pubSubIPCEventStreamAgent.getListeners().add(TEST_TOPIC, set);
    when(publisher.sendStreamEvent(subscriptionResponseMessageCaptor.capture())).thenReturn(new CompletableFuture());
    List<PublishToTopicRequest> publishToTopicRequests = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        PublishToTopicRequest publishToTopicRequest = new PublishToTopicRequest();
        publishToTopicRequest.setTopic(TEST_TOPIC);
        PublishMessage publishMessage = new PublishMessage();
        BinaryMessage binaryMessage = new BinaryMessage();
        binaryMessage.setMessage(String.valueOf(i).getBytes());
        publishMessage.setBinaryMessage(binaryMessage);
        publishToTopicRequest.setPublishMessage(publishMessage);
        publishToTopicRequests.add(publishToTopicRequest);
    }
    try (PubSubIPCEventStreamAgent.PublishToTopicOperationHandler publishToTopicHandler = pubSubIPCEventStreamAgent.getPublishToTopicHandler(mockContext)) {
        for (PublishToTopicRequest publishToTopicRequest : publishToTopicRequests) {
            PublishToTopicResponse publishToTopicResponse = publishToTopicHandler.handleRequest(publishToTopicRequest);
            assertNotNull(publishToTopicResponse);
        }
        verify(authorizationHandler, times(10)).isAuthorized(eq(PUB_SUB_SERVICE_NAME), permissionArgumentCaptor.capture(), eq(ResourceLookupPolicy.MQTT_STYLE));
        Permission capturedPermission = permissionArgumentCaptor.getValue();
        assertThat(capturedPermission.getOperation(), is(GreengrassCoreIPCService.PUBLISH_TO_TOPIC));
        assertThat(capturedPermission.getPrincipal(), is(TEST_SERVICE));
        assertThat(capturedPermission.getResource(), is(TEST_TOPIC));
        TimeUnit.SECONDS.sleep(2);
        assertNotNull(subscriptionResponseMessageCaptor.getAllValues());
        assertEquals(10, subscriptionResponseMessageCaptor.getAllValues().size());
        int i = 0;
        for (SubscriptionResponseMessage responseMessage : subscriptionResponseMessageCaptor.getAllValues()) {
            assertNull(responseMessage.getJsonMessage());
            assertNotNull(responseMessage.getBinaryMessage());
            assertEquals(String.valueOf(i), new String(responseMessage.getBinaryMessage().getMessage()));
            assertEquals(TEST_TOPIC, responseMessage.getBinaryMessage().getEventTopic());
            i++;
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) BinaryMessage(software.amazon.awssdk.aws.greengrass.model.BinaryMessage) PublishMessage(software.amazon.awssdk.aws.greengrass.model.PublishMessage) CompletableFuture(java.util.concurrent.CompletableFuture) PublishToTopicResponse(software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) Permission(com.aws.greengrass.authorization.Permission) StreamEventPublisher(software.amazon.awssdk.eventstreamrpc.StreamEventPublisher) PublishToTopicRequest(software.amazon.awssdk.aws.greengrass.model.PublishToTopicRequest) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Example 4 with BinaryMessage

use of software.amazon.awssdk.aws.greengrass.model.BinaryMessage 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();
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) Gson(com.google.gson.Gson) EventStreamJsonMessage(software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage) BinaryMessage(software.amazon.awssdk.aws.greengrass.model.BinaryMessage) CreateLocalDeploymentRequest(software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) CreateLocalDeploymentResponse(software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) GeneratedAbstractCreateLocalDeploymentOperationHandler(greengrass.GeneratedAbstractCreateLocalDeploymentOperationHandler) RpcServer(software.amazon.awssdk.eventstreamrpc.RpcServer) GreengrassCoreIPCService(greengrass.GreengrassCoreIPCService) GeneratedAbstractSubscribeToTopicOperationHandler(greengrass.GeneratedAbstractSubscribeToTopicOperationHandler) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) GreengrassEventStreamConnectMessage(software.amazon.awssdk.eventstreamrpc.GreengrassEventStreamConnectMessage) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 5 with BinaryMessage

use of software.amazon.awssdk.aws.greengrass.model.BinaryMessage in project aws-greengrass-nucleus by aws-greengrass.

the class PubSubIPCEventStreamAgentTest method GIVEN_subscribed_to_topic_from_all_sources_WHEN_publish_binary_message_THEN_publishes_message.

@Test
void GIVEN_subscribed_to_topic_from_all_sources_WHEN_publish_binary_message_THEN_publishes_message() throws InterruptedException, AuthorizationException {
    StreamEventPublisher publisher = mock(StreamEventPublisher.class);
    Set<Object> set = new HashSet<>();
    set.add(publisher);
    pubSubIPCEventStreamAgent.getListeners().add(TEST_TOPIC, set);
    when(publisher.sendStreamEvent(subscriptionResponseMessageCaptor.capture())).thenReturn(new CompletableFuture());
    PublishToTopicRequest publishToTopicRequest = new PublishToTopicRequest();
    publishToTopicRequest.setTopic(TEST_TOPIC);
    PublishMessage publishMessage = new PublishMessage();
    BinaryMessage binaryMessage = new BinaryMessage();
    binaryMessage.setMessage("ABCD".getBytes());
    publishMessage.setBinaryMessage(binaryMessage);
    publishToTopicRequest.setPublishMessage(publishMessage);
    try (PubSubIPCEventStreamAgent.PublishToTopicOperationHandler publishToTopicHandler = pubSubIPCEventStreamAgent.getPublishToTopicHandler(mockContext)) {
        PublishToTopicResponse publishToTopicResponse = publishToTopicHandler.handleRequest(publishToTopicRequest);
        assertNotNull(publishToTopicResponse);
        verify(authorizationHandler).isAuthorized(eq(PUB_SUB_SERVICE_NAME), permissionArgumentCaptor.capture(), eq(ResourceLookupPolicy.MQTT_STYLE));
        Permission capturedPermission = permissionArgumentCaptor.getValue();
        assertThat(capturedPermission.getOperation(), is(GreengrassCoreIPCService.PUBLISH_TO_TOPIC));
        assertThat(capturedPermission.getPrincipal(), is(TEST_SERVICE));
        assertThat(capturedPermission.getResource(), is(TEST_TOPIC));
        TimeUnit.SECONDS.sleep(2);
        assertNotNull(subscriptionResponseMessageCaptor.getValue());
        SubscriptionResponseMessage message = subscriptionResponseMessageCaptor.getValue();
        assertNull(message.getJsonMessage());
        assertNotNull(message.getBinaryMessage());
        assertEquals("ABCD", new String(message.getBinaryMessage().getMessage()));
        assertEquals(TEST_TOPIC, message.getBinaryMessage().getEventTopic());
    }
}
Also used : Matchers.containsString(org.hamcrest.Matchers.containsString) BinaryMessage(software.amazon.awssdk.aws.greengrass.model.BinaryMessage) PublishMessage(software.amazon.awssdk.aws.greengrass.model.PublishMessage) CompletableFuture(java.util.concurrent.CompletableFuture) PublishToTopicResponse(software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) Permission(com.aws.greengrass.authorization.Permission) StreamEventPublisher(software.amazon.awssdk.eventstreamrpc.StreamEventPublisher) PublishToTopicRequest(software.amazon.awssdk.aws.greengrass.model.PublishToTopicRequest) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

BinaryMessage (software.amazon.awssdk.aws.greengrass.model.BinaryMessage)7 SubscriptionResponseMessage (software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage)6 PublishMessage (software.amazon.awssdk.aws.greengrass.model.PublishMessage)5 PublishToTopicRequest (software.amazon.awssdk.aws.greengrass.model.PublishToTopicRequest)5 PublishToTopicResponse (software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse)5 StreamEventPublisher (software.amazon.awssdk.eventstreamrpc.StreamEventPublisher)5 Permission (com.aws.greengrass.authorization.Permission)4 HashSet (java.util.HashSet)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 Test (org.junit.jupiter.api.Test)4 ArrayList (java.util.ArrayList)2 EventStreamJsonMessage (software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 Gson (com.google.gson.Gson)1 GeneratedAbstractCreateLocalDeploymentOperationHandler (greengrass.GeneratedAbstractCreateLocalDeploymentOperationHandler)1 GeneratedAbstractSubscribeToTopicOperationHandler (greengrass.GeneratedAbstractSubscribeToTopicOperationHandler)1 GreengrassCoreIPCService (greengrass.GreengrassCoreIPCService)1 Consumer (java.util.function.Consumer)1 BeforeEach (org.junit.jupiter.api.BeforeEach)1