Search in sources :

Example 1 with MessageReference

use of com.iluwatar.claimcheckpattern.domain.MessageReference in project java-design-patterns by iluwatar.

the class UsageDetailPublisherFunction method run.

/**
 * Azure function which create message, drop it in persistent storage
 * and publish the event to Event Grid topic.
 * @param request represents HttpRequestMessage
 * @param context represents ExecutionContext
 * @return HttpResponseMessage
 */
@FunctionName("UsageDetailPublisherFunction")
public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) {
    try {
        var eventGridEvents = EventGridEvent.fromString(request.getBody().get());
        for (EventGridEvent eventGridEvent : eventGridEvents) {
            // Handle system events
            if (eventGridEvent.getEventType().equals("Microsoft.EventGrid.SubscriptionValidationEvent")) {
                SubscriptionValidationEventData subscriptionValidationEventData = eventGridEvent.getData().toObject(SubscriptionValidationEventData.class);
                // Handle the subscription validation event
                var responseData = new SubscriptionValidationResponse();
                responseData.setValidationResponse(subscriptionValidationEventData.getValidationCode());
                return request.createResponseBuilder(HttpStatus.OK).body(responseData).build();
            } else if (eventGridEvent.getEventType().equals("UsageDetail")) {
                // Create message body
                var messageBody = new MessageBody<UsageDetail>();
                var usageDetailsList = new ArrayList<UsageDetail>();
                var random = new Random();
                for (int i = 0; i < 51; i++) {
                    var usageDetail = new UsageDetail();
                    usageDetail.setUserId("userId" + i);
                    usageDetail.setData(random.nextInt(500));
                    usageDetail.setDuration(random.nextInt(500));
                    usageDetailsList.add(usageDetail);
                }
                messageBody.setData(usageDetailsList);
                // Create message header
                var messageHeader = new MessageHeader();
                messageHeader.setId(UUID.randomUUID().toString());
                messageHeader.setSubject("UsageDetailPublisher");
                messageHeader.setTopic("usagecostprocessorfunction-topic");
                messageHeader.setEventType("UsageDetail");
                messageHeader.setEventTime(OffsetDateTime.now().toString());
                var messageReference = new MessageReference("callusageapp", messageHeader.getId() + "/input.json");
                messageHeader.setData(messageReference);
                messageHeader.setDataVersion("v1.0");
                // Create entire message
                var message = new Message<UsageDetail>();
                message.setMessageHeader(messageHeader);
                message.setMessageBody(messageBody);
                // Drop data to persistent storage
                this.messageHandlerUtility.dropToPersistantStorage(message, context.getLogger());
                // Publish event to event grid topic
                eventHandlerUtility.publishEvent(messageHeader, context.getLogger());
                context.getLogger().info("Message is dropped and event is published successfully");
                return request.createResponseBuilder(HttpStatus.OK).body(message).build();
            }
        }
    } catch (Exception e) {
        context.getLogger().warning(e.getMessage());
    }
    return request.createResponseBuilder(HttpStatus.OK).body(null).build();
}
Also used : SubscriptionValidationResponse(com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse) Random(java.util.Random) SubscriptionValidationEventData(com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData) UsageDetail(com.iluwatar.claimcheckpattern.domain.UsageDetail) MessageHeader(com.iluwatar.claimcheckpattern.domain.MessageHeader) MessageReference(com.iluwatar.claimcheckpattern.domain.MessageReference) EventGridEvent(com.azure.messaging.eventgrid.EventGridEvent) FunctionName(com.microsoft.azure.functions.annotation.FunctionName)

Example 2 with MessageReference

use of com.iluwatar.claimcheckpattern.domain.MessageReference in project java-design-patterns by iluwatar.

the class MessageHandlerUtility method dropToPersistantStorage.

/**
 * Drop message to blob storage.
 * @param message represents Message
 * @param logger represents Logger
 */
public void dropToPersistantStorage(Message<T> message, Logger logger) {
    try {
        // Get message reference
        MessageReference messageReference = (MessageReference) message.getMessageHeader().getData();
        // Create a unique name for the container
        String containerName = messageReference.getDataLocation();
        // Create the container and return a container client object
        BlobContainerClient containerClient = this.blobServiceClient.getBlobContainerClient(containerName);
        if (!containerClient.exists()) {
            containerClient.create();
        }
        // Get a reference to a blob
        BlobClient blobClient = containerClient.getBlobClient(messageReference.getDataFileName());
        // Upload the blob
        blobClient.upload(BinaryData.fromObject(message));
    } catch (Exception e) {
        logger.info(e.getMessage());
    }
}
Also used : BlobContainerClient(com.azure.storage.blob.BlobContainerClient) BlobClient(com.azure.storage.blob.BlobClient) MessageReference(com.iluwatar.claimcheckpattern.domain.MessageReference)

Example 3 with MessageReference

use of com.iluwatar.claimcheckpattern.domain.MessageReference in project java-design-patterns by iluwatar.

the class UsageCostProcessorFunction method run.

/**
 * Azure function which gets triggered when event grid event send event to it.
 * After receiving event, it read input file from blob storage, calculate call cost details.
 * It creates new message with cost details and drop message to blob storage.
 * @param request represents HttpRequestMessage
 * @param context represents ExecutionContext
 * @return HttpResponseMessage
 */
@FunctionName("UsageCostProcessorFunction")
public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { HttpMethod.GET, HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) {
    try {
        var eventGridEvents = EventGridEvent.fromString(request.getBody().get());
        for (var eventGridEvent : eventGridEvents) {
            // Handle system events
            if (eventGridEvent.getEventType().equals("Microsoft.EventGrid.SubscriptionValidationEvent")) {
                SubscriptionValidationEventData subscriptionValidationEventData = eventGridEvent.getData().toObject(SubscriptionValidationEventData.class);
                // Handle the subscription validation event
                var responseData = new SubscriptionValidationResponse();
                responseData.setValidationResponse(subscriptionValidationEventData.getValidationCode());
                return request.createResponseBuilder(HttpStatus.OK).body(responseData).build();
            } else if (eventGridEvent.getEventType().equals("UsageDetail")) {
                // Get message header and reference
                var messageReference = eventGridEvent.getData().toObject(MessageReference.class);
                // Read message from persistent storage
                var message = this.messageHandlerUtilityForUsageDetail.readFromPersistantStorage(messageReference, context.getLogger());
                // Get Data and generate cost details
                List<UsageDetail> usageDetailsList = BinaryData.fromObject(message.getMessageBody().getData()).toObject(new TypeReference<>() {
                });
                var usageCostDetailsList = calculateUsageCostDetails(usageDetailsList);
                // Create message body
                var newMessageBody = new MessageBody<UsageCostDetail>();
                newMessageBody.setData(usageCostDetailsList);
                // Create message header
                var newMessageReference = new MessageReference("callusageapp", eventGridEvent.getId() + "/output.json");
                var newMessageHeader = new MessageHeader();
                newMessageHeader.setId(eventGridEvent.getId());
                newMessageHeader.setSubject("UsageCostProcessor");
                newMessageHeader.setTopic("");
                newMessageHeader.setEventType("UsageCostDetail");
                newMessageHeader.setEventTime(OffsetDateTime.now().toString());
                newMessageHeader.setData(newMessageReference);
                newMessageHeader.setDataVersion("v1.0");
                // Create entire message
                var newMessage = new Message<UsageCostDetail>();
                newMessage.setMessageHeader(newMessageHeader);
                newMessage.setMessageBody(newMessageBody);
                // Drop data to persistent storage
                this.messageHandlerUtilityForUsageCostDetail.dropToPersistantStorage(newMessage, context.getLogger());
                context.getLogger().info("Message is dropped successfully");
                return request.createResponseBuilder(HttpStatus.OK).body("Message is dropped successfully").build();
            }
        }
    } catch (Exception e) {
        context.getLogger().warning(e.getMessage());
    }
    return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body(null).build();
}
Also used : SubscriptionValidationResponse(com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse) SubscriptionValidationEventData(com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData) ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(com.azure.core.util.serializer.TypeReference) MessageHeader(com.iluwatar.claimcheckpattern.domain.MessageHeader) MessageReference(com.iluwatar.claimcheckpattern.domain.MessageReference) UsageCostDetail(com.iluwatar.claimcheckpattern.domain.UsageCostDetail) FunctionName(com.microsoft.azure.functions.annotation.FunctionName)

Example 4 with MessageReference

use of com.iluwatar.claimcheckpattern.domain.MessageReference in project java-design-patterns by iluwatar.

the class UsageCostProcessorFunctionTest method setUp.

@BeforeEach
public void setUp() {
    var messageBodyUsageDetail = new MessageBody<UsageDetail>();
    var usageDetailsList = new ArrayList<UsageDetail>();
    var messageBodyUsageCostDetail = new MessageBody<UsageCostDetail>();
    var usageCostDetailsList = new ArrayList<UsageCostDetail>();
    for (int i = 0; i < 2; i++) {
        var usageDetail = new UsageDetail();
        usageDetail.setUserId("userId" + i);
        usageDetail.setData(i + 1);
        usageDetail.setDuration(i + 1);
        usageDetailsList.add(usageDetail);
        var usageCostDetail = new UsageCostDetail();
        usageCostDetail.setUserId(usageDetail.getUserId());
        usageCostDetail.setDataCost(usageDetail.getData() * 0.20);
        usageCostDetail.setCallCost(usageDetail.getDuration() * 0.30);
        usageCostDetailsList.add(usageCostDetail);
    }
    messageBodyUsageDetail.setData(usageDetailsList);
    messageBodyUsageCostDetail.setData(usageCostDetailsList);
    // Create message header
    var messageHeader = new MessageHeader();
    messageHeader.setId(UUID.randomUUID().toString());
    messageHeader.setSubject("UsageDetailPublisher");
    messageHeader.setTopic("usagecostprocessorfunction-topic");
    messageHeader.setEventType("UsageDetail");
    messageHeader.setEventTime(OffsetDateTime.now().toString());
    this.messageReference = new MessageReference("callusageapp", "d8284456-dfff-4bd4-9cef-ea99f70f4835/input.json");
    messageHeader.setData(messageReference);
    messageHeader.setDataVersion("v1.0");
    // Create entire message
    messageToRead = new Message<>();
    messageToRead.setMessageHeader(messageHeader);
    messageToRead.setMessageBody(messageBodyUsageDetail);
    messageToDrop = new Message<>();
    messageToDrop.setMessageHeader(messageHeader);
    messageToDrop.setMessageBody(messageBodyUsageCostDetail);
}
Also used : UsageDetail(com.iluwatar.claimcheckpattern.domain.UsageDetail) MessageHeader(com.iluwatar.claimcheckpattern.domain.MessageHeader) UsageCostDetail(com.iluwatar.claimcheckpattern.domain.UsageCostDetail) MessageReference(com.iluwatar.claimcheckpattern.domain.MessageReference) MessageBody(com.iluwatar.claimcheckpattern.domain.MessageBody) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

MessageReference (com.iluwatar.claimcheckpattern.domain.MessageReference)4 MessageHeader (com.iluwatar.claimcheckpattern.domain.MessageHeader)3 SubscriptionValidationEventData (com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData)2 SubscriptionValidationResponse (com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse)2 UsageCostDetail (com.iluwatar.claimcheckpattern.domain.UsageCostDetail)2 UsageDetail (com.iluwatar.claimcheckpattern.domain.UsageDetail)2 FunctionName (com.microsoft.azure.functions.annotation.FunctionName)2 TypeReference (com.azure.core.util.serializer.TypeReference)1 EventGridEvent (com.azure.messaging.eventgrid.EventGridEvent)1 BlobClient (com.azure.storage.blob.BlobClient)1 BlobContainerClient (com.azure.storage.blob.BlobContainerClient)1 MessageBody (com.iluwatar.claimcheckpattern.domain.MessageBody)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Random (java.util.Random)1 BeforeEach (org.junit.jupiter.api.BeforeEach)1