diff --git a/.all-contributorsrc b/.all-contributorsrc index 065fa7bc8..e66fe45f5 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1740,6 +1740,52 @@ "review", "code" ] + }, + { + "login": "Shrirang97", + "name": "Shrirang", + "avatar_url": "https://avatars.githubusercontent.com/u/28738668?v=4", + "profile": "https://github.com/Shrirang97", + "contributions": [ + "review", + "code" + ] + }, + { + "login": "interactwithankush", + "name": "interactwithankush", + "avatar_url": "https://avatars.githubusercontent.com/u/18613127?v=4", + "profile": "https://github.com/interactwithankush", + "contributions": [ + "code" + ] + }, + { + "login": "yuhangbin", + "name": "CharlieYu", + "avatar_url": "https://avatars.githubusercontent.com/u/17566866?v=4", + "profile": "https://github.com/yuhangbin", + "contributions": [ + "code" + ] + }, + { + "login": "Leisterbecker", + "name": "Leisterbecker", + "avatar_url": "https://avatars.githubusercontent.com/u/20650323?v=4", + "profile": "https://github.com/Leisterbecker", + "contributions": [ + "code" + ] + }, + { + "login": "castleKing1997", + "name": "DragonDreamer", + "avatar_url": "https://avatars.githubusercontent.com/u/35420129?v=4", + "profile": "http://rosaecrucis.cn", + "contributions": [ + "code" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index d5d465410..193182b52 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-191-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-196-orange.svg?style=flat-square)](#contributors-)
@@ -321,6 +321,14 @@ This project is licensed under the terms of the MIT license.
Abhinav Vashisth

📖
Kevin

👀 💻 +
Kevin

👀 +
Shrirang

👀 💻 +
interactwithankush

💻 +
CharlieYu

💻 +
Leisterbecker

💻 + + +
DragonDreamer

💻 diff --git a/adapter/README.md b/adapter/README.md index df8efe1b7..11fb7581b 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -18,10 +18,10 @@ couldn't otherwise because of incompatible interfaces. ## Explanation -Real world example +Real-world example -> Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter. -> Another example would be the famous power adapter; a three legged plug can't be connected to a two pronged outlet, it needs to use a power adapter that makes it compatible with the two pronged outlet. +> Consider that you have some pictures on your memory card and you need to transfer them to your computer. To transfer them, you need some kind of adapter that is compatible with your computer ports so that you can attach a memory card to your computer. In this case card reader is an adapter. +> Another example would be the famous power adapter; a three-legged plug can't be connected to a two-pronged outlet, it needs to use a power adapter that makes it compatible with the two-pronged outlets. > Yet another example would be a translator translating words spoken by one person to another In plain words @@ -36,7 +36,7 @@ Wikipedia says Consider a captain that can only use rowing boats and cannot sail at all. -First we have interfaces `RowingBoat` and `FishingBoat` +First, we have interfaces `RowingBoat` and `FishingBoat` ```java public interface RowingBoat { @@ -68,7 +68,7 @@ public class Captain { } ``` -Now let's say the pirates are coming and our captain needs to escape but there is only fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills. +Now let's say the pirates are coming and our captain needs to escape but there is only a fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills. ```java @Slf4j @@ -100,10 +100,10 @@ captain.row(); ## Applicability Use the Adapter pattern when -* you want to use an existing class, and its interface does not match the one you need -* you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces -* you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class. -* most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code. +* You want to use an existing class, and its interface does not match the one you need +* You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces +* You need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. An object adapter can adapt the interface of its parent class. +* Most of the applications using third-party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code. ## Tutorials @@ -114,17 +114,17 @@ Use the Adapter pattern when ## Consequences Class and object adapters have different trade-offs. A class adapter -* adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses. -* let’s Adapter override some of Adaptee’s behavior, since Adapter is a subclass of Adaptee. -* introduces only one object, and no additional pointer indirection is needed to get to the adaptee. +* Adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses. +* Let’s Adapter override some of Adaptee’s behavior since Adapter is a subclass of Adaptee. +* Introduces only one object, and no additional pointer indirection is needed to get to the adaptee. An object adapter -* let’s a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. -* makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself. +* Lets a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. +* Makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making the Adapter refer to the subclass rather than the Adaptee itself. -## Known uses +## Real-world examples * [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) * [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) diff --git a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java index fc55cd69e..661e91319 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** - * Test class + * Tests for the adapter pattern. */ class AdapterPatternTest { diff --git a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java index 8b224e451..802a743dc 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java @@ -33,9 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; class AppTest { /** - * Issue: Add at least one assertion to this test case. - * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} + * Check whether the execution of the main method in {@link App} * throws an exception. */ diff --git a/cloud-claim-check-pattern/.gitignore b/cloud-claim-check-pattern/.gitignore new file mode 100644 index 000000000..f508cf94f --- /dev/null +++ b/cloud-claim-check-pattern/.gitignore @@ -0,0 +1,38 @@ +# Build output +target/ +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# IDE +.idea/ +*.iml +.settings/ +.project +.classpath + +# macOS +.DS_Store + +# Azure Functions +local.settings.json +bin/ +obj/ diff --git a/cloud-claim-check-pattern/README.md b/cloud-claim-check-pattern/README.md new file mode 100644 index 000000000..81f49e068 --- /dev/null +++ b/cloud-claim-check-pattern/README.md @@ -0,0 +1,83 @@ +--- +layout: pattern +title: Claim Check Pattern +folder: cloud-claim-check-pattern +permalink: /patterns/cloud-claim-check-pattern/ +categories: Cloud +language: en +tags: + - Cloud distributed + - Microservices +--- + +## Name + +[Claim Check Pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/claim-check) + +## Also known as + +[Reference-Based Messaging](https://www.enterpriseintegrationpatterns.com/patterns/messaging/StoreInLibrary.html) + +## Intent + +- Reduce the load of data transfer through the Internet. Instead of sending actual data directly, just send the message reference. +- Improve data security. As only message reference is shared, no data is exposed to the Internet. + +## Explanation + +Real-World Example + +> Suppose if you want to build a photo processing system. A photo processing system takes an image as input, processes it, and outputs a different set of images. Consider system has one persistent storage, one input component, ten processing components, messaging platform. Once a photo is given to the input component, it stores that image on persistent storage. It then creates ten different messages/events with the same image location and publishes them to the messaging platform. The messaging platform triggers ten different processing components. The ten processing components extract information about image location from the received event and then read an image from persistent storage. They generate ten different images from the original image and drop these images again to persistent storage. + +In Plain words + +> Split a large message into a claim check and a payload. Send the claim check to the messaging platform and store the payload to an external service. This pattern allows large messages to be processed while protecting the message bus and the client from being overwhelmed or slowed down. This pattern also helps to reduce costs, as storage is usually cheaper than resource units used by the messaging platform.([ref](https://docs.microsoft.com/en-us/azure/architecture/patterns/claim-check)) + +## Architecture Diagram + +![alt text](./etc/Claim-Check-Pattern.png "Claim Check Pattern") + +## Applicability + +Use the Claim Check Pattern when + +- Huge processing data causes a lot of bandwidth consumption to transfer data through the Internet. +- To secure your data transfer by storing in common persistent storage. +- Using a cloud platform - Azure Functions or AWS Lambda, Azure EventGrid or AWS Event Bridge, Azure Blob Storage or AWS S3 Bucket. +- Each service must be independent and idempotent. Output data is dropped to persistent storage by the service. +- Publish-subscribe messaging pattern needs to be used. + +## Consequences + +- This pattern is stateless. Any compute API will not store any data. +- You must have persistent storage and a reliable messaging platform. + +## Tutorials + +### Workflow + +Suppose a telecom company wants to build call cost calculator system which generate the call cost daily. At the end of each day, details of the calls made by the consumers are stored somewhere. The call calculator system will read this data and generate call cost data for each user. Consumers will be billed using this generated data in case of postpaid service. + +Producer class( `UsageDetailPublisherFunction` Azure Function) will generate call usage details (here we are generating call data in producer class itself. In real world scenario, it will read from storage). `UsageDetailPublisherFunction` creates a message. Message consists of message header and message body. Message header is basically an event grid event or claim or message reference. Message body contains actual data. `UsageDetailPublisherFunction` sends a message header to Event Grid topic `usage-detail` and drops an entire message to the blob storage. Event Grid then sent this message header to the `UsageCostProcessorFunction` Azure function. It will read the entire message from blob storage with the help of the header, will calculate call cost and drop the result to the blob storage. + +### Class Diagrams + +![alt text](./etc/class-diagram.png "Claim-Check-Class-Diagram") + +### Setup + +- Any operating system can be used macOS, Windows, Linux as everything is deployed on Azure. +- Install Java JDK 11 and set up Java environmental variables. +- Install Git. +- Install Visual Studio Code. +- Install [ Azure Functions extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions) to be able to deploy using Visual studio. + +### Storage Data + +The data is stored in the Azure blob storage in the container `callusageapp`. For every trigger, one GUID is created. Under the `GUID folder`, 2 files will be created `input.json` and `output.json`. +`Input.json` is dropped `producer` azure function which contains call usage details.` Output.json` contains call cost details which are dropped by the `consumer` azure function. + +## Credits + +- [Messaging Pattern - Claim Check](https://www.enterpriseintegrationpatterns.com/patterns/messaging/StoreInLibrary.html) +- [Azure Architecture Pattern - Claim Check Pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/claim-check) diff --git a/cloud-claim-check-pattern/call-usage-app/.gitignore b/cloud-claim-check-pattern/call-usage-app/.gitignore new file mode 100644 index 000000000..f508cf94f --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/.gitignore @@ -0,0 +1,38 @@ +# Build output +target/ +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# IDE +.idea/ +*.iml +.settings/ +.project +.classpath + +# macOS +.DS_Store + +# Azure Functions +local.settings.json +bin/ +obj/ diff --git a/cloud-claim-check-pattern/call-usage-app/etc/call-usage-app.urm.puml b/cloud-claim-check-pattern/call-usage-app/etc/call-usage-app.urm.puml new file mode 100644 index 000000000..0ffec48b1 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/etc/call-usage-app.urm.puml @@ -0,0 +1,117 @@ +@startuml +package com.iluwatar.claimcheckpattern.producer.calldetails.functions { + class UsageDetailPublisherFunction { + - eventHandlerUtility : EventHandlerUtility + - messageHandlerUtility : MessageHandlerUtility + + UsageDetailPublisherFunction() + + UsageDetailPublisherFunction(messageHandlerUtility : MessageHandlerUtility, eventHandlerUtility : EventHandlerUtility) + + run(request : HttpRequestMessage>, context : ExecutionContext) : HttpResponseMessage + } +} +package com.iluwatar.claimcheckpattern.domain { + class Message { + - messageBody : MessageBody + - messageHeader : MessageHeader + + Message() + + getMessageBody() : MessageBody + + getMessageHeader() : MessageHeader + + setMessageBody(messageBody : MessageBody) + + setMessageHeader(messageHeader : MessageHeader) + } + class MessageBody { + - data : List + + MessageBody() + + getData() : List + + setData(data : List) + } + class MessageHeader { + - data : Object + - dataVersion : String + - eventTime : String + - eventType : String + - id : String + - subject : String + - topic : String + + MessageHeader() + + getData() : Object + + getDataVersion() : String + + getEventTime() : String + + getEventType() : String + + getId() : String + + getSubject() : String + + getTopic() : String + + setData(data : Object) + + setDataVersion(dataVersion : String) + + setEventTime(eventTime : String) + + setEventType(eventType : String) + + setId(id : String) + + setSubject(subject : String) + + setTopic(topic : String) + } + class MessageReference { + - dataFileName : String + - dataLocation : String + + MessageReference() + + MessageReference(dataLocation : String, dataFileName : String) + + getDataFileName() : String + + getDataLocation() : String + + setDataFileName(dataFileName : String) + + setDataLocation(dataLocation : String) + } + class UsageCostDetail { + - callCost : double + - dataCost : double + - userId : String + + UsageCostDetail() + + getCallCost() : double + + getDataCost() : double + + getUserId() : String + + setCallCost(callCost : double) + + setDataCost(dataCost : double) + + setUserId(userId : String) + } + class UsageDetail { + - data : int + - duration : int + - userId : String + + UsageDetail() + + getData() : int + + getDuration() : int + + getUserId() : String + + setData(data : int) + + setDuration(duration : int) + + setUserId(userId : String) + } +} +package com.iluwatar.claimcheckpattern.utility { + class EventHandlerUtility { + - customEventClient : EventGridPublisherClient + + EventHandlerUtility() + + EventHandlerUtility(customEventClient : EventGridPublisherClient) + + publishEvent(customEvent : T, logger : Logger) + } + class MessageHandlerUtility { + - blobServiceClient : BlobServiceClient + + MessageHandlerUtility() + + MessageHandlerUtility(blobServiceClient : BlobServiceClient) + + dropToPersistantStorage(message : Message, logger : Logger) + + readFromPersistantStorage(messageReference : MessageReference, logger : Logger) : Message + } +} +package com.iluwatar.claimcheckpattern.consumer.callcostprocessor.functions { + class UsageCostProcessorFunction { + - messageHandlerUtilityForUsageCostDetail : MessageHandlerUtility + - messageHandlerUtilityForUsageDetail : MessageHandlerUtility + + UsageCostProcessorFunction() + + UsageCostProcessorFunction(messageHandlerUtilityForUsageDetail : MessageHandlerUtility, messageHandlerUtilityForUsageCostDetail : MessageHandlerUtility) + - calculateUsageCostDetails(usageDetailsList : List) : List + + run(request : HttpRequestMessage>, context : ExecutionContext) : HttpResponseMessage + } +} +UsageCostProcessorFunction --> "-messageHandlerUtilityForUsageDetail" MessageHandlerUtility +Message --> "-messageBody" MessageBody +UsageDetailPublisherFunction --> "-eventHandlerUtility" EventHandlerUtility +Builder ..+ HttpResponseMessage +UsageDetailPublisherFunction --> "-messageHandlerUtility" MessageHandlerUtility +Message --> "-messageHeader" MessageHeader +@enduml \ No newline at end of file diff --git a/cloud-claim-check-pattern/call-usage-app/host.json b/cloud-claim-check-pattern/call-usage-app/host.json new file mode 100644 index 000000000..4ac89572d --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/host.json @@ -0,0 +1,7 @@ +{ + "version": "2.0", + "extensionBundle": { + "id": "Microsoft.Azure.Functions.ExtensionBundle", + "version": "[1.*, 2.0.0)" + } +} \ No newline at end of file diff --git a/cloud-claim-check-pattern/call-usage-app/pom.xml b/cloud-claim-check-pattern/call-usage-app/pom.xml new file mode 100644 index 000000000..a1bc7fc10 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/pom.xml @@ -0,0 +1,150 @@ + + + + 4.0.0 + + + + com.iluwatar + claim-check-pattern + 1.25.0-SNAPSHOT + + + call-usage-app + call-usage-app + jar + + + UTF-8 + 1.14.0 + 1.4.2 + CallUsageApp + + + + + + com.azure + azure-sdk-bom + 1.0.4 + pom + import + + + + + + + com.microsoft.azure.functions + azure-functions-java-library + ${azure.functions.java.library.version} + + + + com.azure + azure-messaging-eventgrid + + + + com.azure + azure-storage-blob + 12.13.0 + + + + org.slf4j + slf4j-simple + test + + + + + org.mockito + mockito-core + test + + + + + + + + + com.microsoft.azure + azure-functions-maven-plugin + ${azure.functions.maven.plugin.version} + + + ${functionAppName} + + java-functions-group + + java-functions-app-service-plan + + + westus + + + + + + + + + windows + 11 + + + + FUNCTIONS_EXTENSION_VERSION + ~3 + + + + + + package-functions + + package + + + + + + + maven-clean-plugin + 3.1.0 + + + + obj + + + + + + + diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunction.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunction.java new file mode 100644 index 000000000..652095727 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunction.java @@ -0,0 +1,168 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.consumer.callcostprocessor.functions; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse; +import com.iluwatar.claimcheckpattern.domain.Message; +import com.iluwatar.claimcheckpattern.domain.MessageBody; +import com.iluwatar.claimcheckpattern.domain.MessageHeader; +import com.iluwatar.claimcheckpattern.domain.MessageReference; +import com.iluwatar.claimcheckpattern.domain.UsageCostDetail; +import com.iluwatar.claimcheckpattern.domain.UsageDetail; +import com.iluwatar.claimcheckpattern.utility.MessageHandlerUtility; +import com.microsoft.azure.functions.ExecutionContext; +import com.microsoft.azure.functions.HttpMethod; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import com.microsoft.azure.functions.annotation.AuthorizationLevel; +import com.microsoft.azure.functions.annotation.FunctionName; +import com.microsoft.azure.functions.annotation.HttpTrigger; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Azure Functions with HTTP Trigger. + * This is Consumer class. + */ +public class UsageCostProcessorFunction { + + private MessageHandlerUtility messageHandlerUtilityForUsageDetail; + private MessageHandlerUtility messageHandlerUtilityForUsageCostDetail; + + public UsageCostProcessorFunction() { + this.messageHandlerUtilityForUsageDetail = new MessageHandlerUtility<>(); + this.messageHandlerUtilityForUsageCostDetail = new MessageHandlerUtility<>(); + } + + public UsageCostProcessorFunction( + MessageHandlerUtility messageHandlerUtilityForUsageDetail, + MessageHandlerUtility messageHandlerUtilityForUsageCostDetail) { + this.messageHandlerUtilityForUsageDetail = messageHandlerUtilityForUsageDetail; + this.messageHandlerUtilityForUsageCostDetail = messageHandlerUtilityForUsageCostDetail; + } + + /** + * 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> 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 usageDetailsList = BinaryData.fromObject( + message.getMessageBody().getData()) + .toObject(new TypeReference<>() { + }); + var usageCostDetailsList = calculateUsageCostDetails(usageDetailsList); + + // Create message body + var newMessageBody = new MessageBody(); + 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(); + 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(); + } + + private List calculateUsageCostDetails(List usageDetailsList) { + if (usageDetailsList == null) { + return null; + } + var usageCostDetailsList = new ArrayList(); + + usageDetailsList.forEach(usageDetail -> { + var usageCostDetail = new UsageCostDetail(); + usageCostDetail.setUserId(usageDetail.getUserId()); + usageCostDetail.setCallCost(usageDetail.getDuration() * 0.30); // 0.30₹ per minute + usageCostDetail.setDataCost(usageDetail.getData() * 0.20); // 0.20₹ per MB + + usageCostDetailsList.add(usageCostDetail); + }); + + return usageCostDetailsList; + } +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/Message.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/Message.java new file mode 100644 index 000000000..d85653dcd --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/Message.java @@ -0,0 +1,43 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * It is the message which gets dropped or read by Producer or Consumer Azure functions. + * It is stored in the json format. + * @param represents UsageDetail or UsageCostDetail + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Message { + private MessageHeader messageHeader; + + private MessageBody messageBody; + +} \ No newline at end of file diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageBody.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageBody.java new file mode 100644 index 000000000..e8284e04e --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageBody.java @@ -0,0 +1,43 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.domain; + +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * It is message body of the message. + * It stores actual data in our case UsageCostDetail or UsageDetail. + * @param represents UsageDetail or UsageCostDetail + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class MessageBody { + + private List data; + +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageHeader.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageHeader.java new file mode 100644 index 000000000..71e897ca9 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageHeader.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * This is message header or event which is sent to Event Grid. + * Its structure is same as Azure Event Grid Event Class. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class MessageHeader { + + private String id; + private String subject; + private String topic; + private String eventType; + private String eventTime; + private Object data; + private String dataVersion; + +} \ No newline at end of file diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageReference.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageReference.java new file mode 100644 index 000000000..9eab15a3a --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/MessageReference.java @@ -0,0 +1,45 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * This is claim/message reference class. + * It contains the information about data where it is stored in persistent storage + * and file name. + * dataLocation is blob storage container name. + * dataFileName is file name in above container. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class MessageReference { + + private String dataLocation; + private String dataFileName; + +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/UsageCostDetail.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/UsageCostDetail.java new file mode 100644 index 000000000..8930ea3f5 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/UsageCostDetail.java @@ -0,0 +1,43 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * This is call cost details class. + * It stores userId of the caller, call duration cost and data cost. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UsageCostDetail { + + private String userId; + private double callCost; + private double dataCost; + +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/UsageDetail.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/UsageDetail.java new file mode 100644 index 000000000..c8f0395db --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/domain/UsageDetail.java @@ -0,0 +1,44 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * This is call usage detail calls. + * It stores userId of the caller, call duration and data used. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UsageDetail { + + private String userId; + + private int duration; + + private int data; +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunction.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunction.java new file mode 100644 index 000000000..2f58f8f48 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunction.java @@ -0,0 +1,146 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.producer.calldetails.functions; + +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse; +import com.iluwatar.claimcheckpattern.domain.Message; +import com.iluwatar.claimcheckpattern.domain.MessageBody; +import com.iluwatar.claimcheckpattern.domain.MessageHeader; +import com.iluwatar.claimcheckpattern.domain.MessageReference; +import com.iluwatar.claimcheckpattern.domain.UsageDetail; +import com.iluwatar.claimcheckpattern.utility.EventHandlerUtility; +import com.iluwatar.claimcheckpattern.utility.MessageHandlerUtility; +import com.microsoft.azure.functions.ExecutionContext; +import com.microsoft.azure.functions.HttpMethod; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import com.microsoft.azure.functions.annotation.AuthorizationLevel; +import com.microsoft.azure.functions.annotation.FunctionName; +import com.microsoft.azure.functions.annotation.HttpTrigger; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Random; +import java.util.UUID; + +/** + * Azure Functions with HTTP Trigger. + * This is Producer class. + */ +public class UsageDetailPublisherFunction { + + private MessageHandlerUtility messageHandlerUtility; + private EventHandlerUtility eventHandlerUtility; + + public UsageDetailPublisherFunction() { + this.messageHandlerUtility = new MessageHandlerUtility<>(); + this.eventHandlerUtility = new EventHandlerUtility<>(); + } + + public UsageDetailPublisherFunction(MessageHandlerUtility messageHandlerUtility, + EventHandlerUtility eventHandlerUtility) { + this.messageHandlerUtility = messageHandlerUtility; + this.eventHandlerUtility = eventHandlerUtility; + } + + /** + * 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> 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(); + var usageDetailsList = new ArrayList(); + 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(); + 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(); + } +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtility.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtility.java new file mode 100644 index 000000000..c037db10d --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtility.java @@ -0,0 +1,66 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.utility; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.util.BinaryData; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder; +import java.util.logging.Logger; + +/** + * This class is event publisher utility which published message header to Event Grid topic. + * @param represents UsageDetail or UsageCostDetail + */ +public class EventHandlerUtility { + + private EventGridPublisherClient customEventClient; + + /** Default constructor. + */ + public EventHandlerUtility() { + this.customEventClient = new EventGridPublisherClientBuilder() + .endpoint(System.getenv("EventGridURL")) + .credential(new AzureKeyCredential(System.getenv("EventGridKey"))) + .buildCustomEventPublisherClient(); + } + + /** + Parameterized constructor. + */ + public EventHandlerUtility(EventGridPublisherClient customEventClient) { + this.customEventClient = customEventClient; + } + + /** + Method for publishing event to Event Grid Topic. + */ + public void publishEvent(T customEvent, Logger logger) { + try { + customEventClient.sendEvent(BinaryData.fromObject(customEvent)); + } catch (Exception e) { + logger.info(e.getMessage()); + } + } +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtility.java b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtility.java new file mode 100644 index 000000000..40aac8ab9 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/main/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtility.java @@ -0,0 +1,127 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.utility; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerClient; +import com.azure.storage.blob.BlobServiceClient; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.iluwatar.claimcheckpattern.domain.Message; +import com.iluwatar.claimcheckpattern.domain.MessageReference; +import java.util.logging.Logger; + +/** + * This class read and drop message from Azure blob storage. + * @param represents UsageDetail or UsageCostDetail + */ +public class MessageHandlerUtility { + + private BlobServiceClient blobServiceClient; + + /** + * Parameterized constructor. + * @param blobServiceClient represents BlobServiceClient + */ + public MessageHandlerUtility(BlobServiceClient blobServiceClient) { + this.blobServiceClient = blobServiceClient; + } + + /** + * Default constructor. + */ + public MessageHandlerUtility() { + // Create a BlobServiceClient object which will be used to create a container + // client + this.blobServiceClient = new BlobServiceClientBuilder() + .connectionString(System.getenv("BlobStorageConnectionString")).buildClient(); + + } + + /** + * Read message from blob storage. + * @param messageReference represents MessageReference + * @param logger represents Logger + * @return Message + */ + public Message readFromPersistantStorage(MessageReference messageReference, Logger logger) { + Message message = null; + try { + + // Get container name from message reference + String containerName = messageReference.getDataLocation(); + + // Get blob name from message reference + String blobName = messageReference.getDataFileName(); + + // Get container client + BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName); + + // Get a reference to a blob + BlobClient blobClient = containerClient.getBlobClient(blobName); + + // download the blob + message = blobClient.downloadContent().toObject(new TypeReference>() { + }); + } catch (Exception e) { + logger.info(e.getMessage()); + } + return message; + + } + + /** + * Drop message to blob storage. + * @param message represents Message + * @param logger represents Logger + */ + public void dropToPersistantStorage(Message 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()); + } + + } + +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/HttpResponseMessageMock.java b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/HttpResponseMessageMock.java new file mode 100644 index 000000000..94cb48240 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/HttpResponseMessageMock.java @@ -0,0 +1,105 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern; + +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import com.microsoft.azure.functions.HttpStatusType; +import java.util.HashMap; +import java.util.Map; + +/** + * The mock for HttpResponseMessage, can be used in unit tests to verify if the + * returned response by HTTP trigger function is correct or not. + */ +public class HttpResponseMessageMock implements HttpResponseMessage { + private int httpStatusCode; + private HttpStatusType httpStatus; + private Object body; + private Map headers; + + public HttpResponseMessageMock(HttpStatusType status, Map headers, Object body) { + this.httpStatus = status; + this.httpStatusCode = status.value(); + this.headers = headers; + this.body = body; + } + + @Override + public HttpStatusType getStatus() { + return this.httpStatus; + } + + @Override + public int getStatusCode() { + return httpStatusCode; + } + + @Override + public String getHeader(String key) { + return this.headers.get(key); + } + + @Override + public Object getBody() { + return this.body; + } + + public static class HttpResponseMessageBuilderMock implements HttpResponseMessage.Builder { + private Object body; + private int httpStatusCode; + private Map headers = new HashMap<>(); + private HttpStatusType httpStatus; + + public Builder status(HttpStatus status) { + this.httpStatusCode = status.value(); + this.httpStatus = status; + return this; + } + + @Override + public Builder status(HttpStatusType httpStatusType) { + this.httpStatusCode = httpStatusType.value(); + this.httpStatus = httpStatusType; + return this; + } + + @Override + public HttpResponseMessage.Builder header(String key, String value) { + this.headers.put(key, value); + return this; + } + + @Override + public HttpResponseMessage.Builder body(Object body) { + this.body = body; + return this; + } + + @Override + public HttpResponseMessage build() { + return new HttpResponseMessageMock(this.httpStatus, this.headers, this.body); + } + } +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunctionTest.java b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunctionTest.java new file mode 100644 index 000000000..940a39af7 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunctionTest.java @@ -0,0 +1,181 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.consumer.callcostprocessor.functions; + +import com.iluwatar.claimcheckpattern.HttpResponseMessageMock; +import com.iluwatar.claimcheckpattern.domain.Message; +import com.iluwatar.claimcheckpattern.domain.MessageBody; +import com.iluwatar.claimcheckpattern.domain.MessageHeader; +import com.iluwatar.claimcheckpattern.domain.MessageReference; +import com.iluwatar.claimcheckpattern.domain.UsageCostDetail; +import com.iluwatar.claimcheckpattern.domain.UsageDetail; +import com.iluwatar.claimcheckpattern.utility.MessageHandlerUtility; +import com.microsoft.azure.functions.ExecutionContext; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.stubbing.Answer; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.logging.Logger; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** + * Unit test for Function class. + */ +@ExtendWith(MockitoExtension.class) +public class UsageCostProcessorFunctionTest { + + @Mock + MessageHandlerUtility mockMessageHandlerUtilityForUsageADetail; + @Mock + MessageHandlerUtility mockMessageHandlerUtilityForUsageCostDetail; + @Mock + ExecutionContext context; + + Message messageToDrop; + Message messageToRead; + MessageReference messageReference; + @InjectMocks + UsageCostProcessorFunction usageCostProcessorFunction; + + @BeforeEach + public void setUp() { + var messageBodyUsageDetail = new MessageBody(); + var usageDetailsList = new ArrayList(); + + var messageBodyUsageCostDetail = new MessageBody(); + var usageCostDetailsList = new ArrayList(); + 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); + + } + + /** + * Unit test for HttpTriggerJava method. + */ + @Test + public void shouldTriggerHttpAzureFunctionJavaWithSubscriptionValidationEventType() throws Exception { + + // Setup + @SuppressWarnings("unchecked") + final HttpRequestMessage> req = mock(HttpRequestMessage.class); + String fileAbsolutePath = getClass().getResource("/subscriptionValidationEvent.json").getPath() + .replaceAll("%20", " "), jsonBody = Files.readString(Paths.get(fileAbsolutePath)).replaceAll("\n", " "); + doReturn(Optional.of(jsonBody)).when(req).getBody(); + doAnswer(new Answer() { + @Override + public HttpResponseMessage.Builder answer(InvocationOnMock invocation) { + HttpStatus status = (HttpStatus) invocation.getArguments()[0]; + return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status); + } + }).when(req).createResponseBuilder(any(HttpStatus.class)); + + final ExecutionContext context = mock(ExecutionContext.class); + + // Invoke + final HttpResponseMessage ret = this.usageCostProcessorFunction.run(req, context); + + // Verify + assertEquals(ret.getStatus(), HttpStatus.OK); + } + + @Test + public void shouldTriggerHttpAzureFunctionJavaWithUsageDetailEventType() throws Exception { + // Setup + @SuppressWarnings("unchecked") + final HttpRequestMessage> req = mock(HttpRequestMessage.class); + String fileAbsolutePath = getClass().getResource("/usageDetailEvent.json").getPath().replaceAll("%20", " "), + jsonBody = Files.readString(Paths.get(fileAbsolutePath)).replaceAll("\n", " "); + doReturn(Optional.of(jsonBody)).when(req).getBody(); + doReturn(Logger.getGlobal()).when(context).getLogger(); + + when(this.mockMessageHandlerUtilityForUsageADetail.readFromPersistantStorage(any(MessageReference.class), + eq(Logger.getGlobal()))).thenReturn(messageToRead); + doAnswer(new Answer() { + @Override + public HttpResponseMessage.Builder answer(InvocationOnMock invocation) { + HttpStatus status = (HttpStatus) invocation.getArguments()[0]; + return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status); + } + }).when(req).createResponseBuilder(any(HttpStatus.class)); + + assertNotNull(this.mockMessageHandlerUtilityForUsageADetail); + assertEquals(this.messageToRead, this.mockMessageHandlerUtilityForUsageADetail + .readFromPersistantStorage(this.messageReference, Logger.getGlobal())); + + // Invoke + final HttpResponseMessage ret = this.usageCostProcessorFunction.run(req, context); + + // Verify + assertEquals(HttpStatus.OK, ret.getStatus()); + assertEquals("Message is dropped successfully", ret.getBody()); + } + +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunctionTest.java b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunctionTest.java new file mode 100644 index 000000000..60083a81b --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunctionTest.java @@ -0,0 +1,119 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.producer.calldetails.functions; + +import com.iluwatar.claimcheckpattern.HttpResponseMessageMock; +import com.iluwatar.claimcheckpattern.domain.MessageHeader; +import com.iluwatar.claimcheckpattern.domain.UsageDetail; +import com.iluwatar.claimcheckpattern.utility.EventHandlerUtility; +import com.iluwatar.claimcheckpattern.utility.MessageHandlerUtility; +import com.microsoft.azure.functions.ExecutionContext; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.stubbing.Answer; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; +import java.util.logging.Logger; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** + * Unit test for Function class. + */ +@ExtendWith(MockitoExtension.class) +public class UsageDetailPublisherFunctionTest { + @Mock + MessageHandlerUtility mockMessageHandlerUtility; + @Mock + EventHandlerUtility mockEventHandlerUtility; + + @InjectMocks + UsageDetailPublisherFunction usageDetailPublisherFunction; + + /** + * Unit test for HttpTriggerJava method. + */ + @Test + public void shouldTriggerHttpAzureFunctionJavaWithSubscriptionValidationEventType() throws Exception { + + // Setup + @SuppressWarnings("unchecked") + final HttpRequestMessage> req = mock(HttpRequestMessage.class); + String fileAbsolutePath = getClass().getResource("/subscriptionValidationEvent.json").getPath() + .replaceAll("%20", " "), jsonBody = Files.readString(Paths.get(fileAbsolutePath)).replaceAll("\n", " "); + doReturn(Optional.of(jsonBody)).when(req).getBody(); + doAnswer(new Answer() { + @Override + public HttpResponseMessage.Builder answer(InvocationOnMock invocation) { + HttpStatus status = (HttpStatus) invocation.getArguments()[0]; + return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status); + } + }).when(req).createResponseBuilder(any(HttpStatus.class)); + + final ExecutionContext context = mock(ExecutionContext.class); + + // Invoke + final HttpResponseMessage ret = this.usageDetailPublisherFunction.run(req, context); + + // Verify + assertEquals(ret.getStatus(), HttpStatus.OK); + } + + @Test + public void shouldTriggerHttpAzureFunctionJavaWithUsageDetailEventType() throws Exception { + + // Setup + @SuppressWarnings("unchecked") + final HttpRequestMessage> req = mock(HttpRequestMessage.class); + String fileAbsolutePath = getClass().getResource("/usageDetailEvent.json").getPath().replaceAll("%20", " "), + jsonBody = Files.readString(Paths.get(fileAbsolutePath)).replaceAll("\n", " "); + doReturn(Optional.of(jsonBody)).when(req).getBody(); + doAnswer(new Answer() { + @Override + public HttpResponseMessage.Builder answer(InvocationOnMock invocation) { + HttpStatus status = (HttpStatus) invocation.getArguments()[0]; + return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status); + } + }).when(req).createResponseBuilder(any(HttpStatus.class)); + + final ExecutionContext context = mock(ExecutionContext.class); + doReturn(Logger.getGlobal()).when(context).getLogger(); + + // Invoke + final HttpResponseMessage ret = this.usageDetailPublisherFunction.run(req, context); + + // Verify + assertEquals(ret.getStatus(), HttpStatus.OK); + } + +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtilityTest.java b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtilityTest.java new file mode 100644 index 000000000..f16f60f6d --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtilityTest.java @@ -0,0 +1,70 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.utility; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.azure.core.util.BinaryData; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.iluwatar.claimcheckpattern.domain.Message; +import com.iluwatar.claimcheckpattern.domain.UsageDetail; +import java.util.logging.Logger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class EventHandlerUtilityTest { + + @Mock + EventGridPublisherClient mockCustomEventClient; + + @InjectMocks + EventHandlerUtility> eventHandlerUtility; + + @BeforeEach + public void setUp() { + + System.setProperty("EventGridURL", "https://www.dummyEndpoint.com/api/events"); + System.setProperty("EventGridKey", "EventGridURL"); + } + + @Test + void shouldPublishEvent() { + doNothing().when(mockCustomEventClient).sendEvent(any(BinaryData.class)); + eventHandlerUtility.publishEvent(null, Logger.getLogger("logger")); + verify(mockCustomEventClient, times(1)).sendEvent(any(BinaryData.class)); + + } + + @Test + void shouldPublishEventWithNullLogger() { + eventHandlerUtility.publishEvent(null, null); + verify(mockCustomEventClient, times(1)).sendEvent(any(BinaryData.class)); + } +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtilityTest.java b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtilityTest.java new file mode 100644 index 000000000..4faab105d --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtilityTest.java @@ -0,0 +1,114 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.claimcheckpattern.utility; + +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerClient; +import com.azure.storage.blob.BlobServiceClient; +import com.iluwatar.claimcheckpattern.domain.*; +import com.iluwatar.claimcheckpattern.utility.MessageHandlerUtility; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.logging.Logger; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +public class MessageHandlerUtilityTest { + @Mock + private BlobClient mockBlobClient; + + @Mock + private BlobContainerClient mockContainerClient; + + @Mock + private BlobServiceClient mockBlobServiceClient; + + @InjectMocks + private MessageHandlerUtility messageHandlerUtility; + + private Message messageToPublish; + private MessageReference messageReference; + + @BeforeEach + public void setUp() { + System.setProperty("BlobStorageConnectionString", "https://www.dummyEndpoint.com/api/blobs"); + + var messageBody = new MessageBody(); + var usageDetailsList = new ArrayList(); + 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()); + this.messageReference = new MessageReference("callusageapp", messageHeader.getId() + "/input.json"); + messageHeader.setData(messageReference); + messageHeader.setDataVersion("v1.0"); + + // Create entire message + this.messageToPublish = new Message<>(); + this.messageToPublish.setMessageHeader(messageHeader); + this.messageToPublish.setMessageBody(messageBody); + + when(mockContainerClient.getBlobClient(anyString())).thenReturn(mockBlobClient); + when(mockBlobServiceClient.getBlobContainerClient(anyString())).thenReturn(mockContainerClient); + } + + @Test + void shouldDropMessageToPersistantStorage() { + messageHandlerUtility.dropToPersistantStorage(messageToPublish, Logger.getLogger("logger")); + verify(mockBlobServiceClient, times(1)).getBlobContainerClient(anyString()); + // verify(mockContainerClient, times(0)).exists(); + } + + @Test + void shouldReadMessageFromPersistantStorage() { + + messageHandlerUtility.readFromPersistantStorage(messageReference, Logger.getLogger("logger")); + verify(mockBlobServiceClient, times(1)).getBlobContainerClient(anyString()); + } +} diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/cloud-claim-check-pattern/call-usage-app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 000000000..ca6ee9cea --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/resources/subscriptionValidationEvent.json b/cloud-claim-check-pattern/call-usage-app/src/test/resources/subscriptionValidationEvent.json new file mode 100644 index 000000000..52bd6ee6a --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/resources/subscriptionValidationEvent.json @@ -0,0 +1,15 @@ +[ + { + "data": { + "validationCode": "C12F266E-79D9-4C0A-9922-5EF6201A34C2", + "validationUrl": "https://rp-centralindia.eventgrid.azure.net:553/eventsubscriptions/usagedetailpublisherfunction-subscription/validate?idu003dC12F266E-79D9-4C0A-9922-5EF6201A34C2u0026tu003d2021-10-26T08:10:52.4999377Zu0026apiVersionu003d2020-10-15-previewu0026tokenu003d30kEVoL8rAOWzQv0buurhrKnbP%2bGMtHObbA%2bax6wb4Y%3d" + }, + "dataVersion": "2", + "eventTime": "2021-10-26T08:10:52.4999377Z", + "eventType": "Microsoft.EventGrid.SubscriptionValidationEvent", + "id": "e2a8466b-3dc0-46b7-bb7d-b999e51a2848", + "metadataVersion": "1", + "subject": "", + "topic": "/subscriptions/0fef643d-a6b1-48f9-a256-53fbd0d22f48/resourceGroups/resource-group-ccp/providers/Microsoft.EventGrid/domains/event-grid-domains-ccp/topics/usagedetailpublisherfunction-topic" + } +] diff --git a/cloud-claim-check-pattern/call-usage-app/src/test/resources/usageDetailEvent.json b/cloud-claim-check-pattern/call-usage-app/src/test/resources/usageDetailEvent.json new file mode 100644 index 000000000..137649e29 --- /dev/null +++ b/cloud-claim-check-pattern/call-usage-app/src/test/resources/usageDetailEvent.json @@ -0,0 +1,15 @@ +[ + { + "data": { + "dataFileName": "d8284456-dfff-4bd4-9cef-ea99f70f4835/input.json", + "dataLocation": "callusageapp" + }, + "dataVersion": "v1.0", + "eventTime": "2021-10-25T19:17:15.7468501Z", + "eventType": "UsageDetail", + "id": "d8284456-dfff-4bd4-9cef-ea99f70f4835", + "metadataVersion": "1", + "subject": "UsageDetailPublisher", + "topic": "/subscriptions/0fef643d-a6b1-48f9-a256-ea99f70f4835/resourceGroups/resource-group-ccp/providers/Microsoft.EventGrid/domains/event-grid-domains-ccp/topics/usagecostprocessorfunction-topic" + } +] diff --git a/cloud-claim-check-pattern/etc/Claim-Check-Pattern.png b/cloud-claim-check-pattern/etc/Claim-Check-Pattern.png new file mode 100644 index 000000000..a2d8040af Binary files /dev/null and b/cloud-claim-check-pattern/etc/Claim-Check-Pattern.png differ diff --git a/cloud-claim-check-pattern/etc/claim-check-pattern.urm.puml b/cloud-claim-check-pattern/etc/claim-check-pattern.urm.puml new file mode 100644 index 000000000..14df8b68b --- /dev/null +++ b/cloud-claim-check-pattern/etc/claim-check-pattern.urm.puml @@ -0,0 +1,117 @@ +@startuml +class UsageDetailPublisherFunction [[java:com.iluwatar.producer.calldetails.functions]] { + -messageHandlerUtility: MessageHandlerUtility + -eventHandlerUtility: EventHandlerUtility + +run(): HttpResponseMessage +} + +class UsageCostProcessorFunction [[java:com.iluwatar.consumer.callcostprocessor.functions]] { + -messageHandlerUtilityForUsageDetail: MessageHandlerUtility + -messageHandlerUtilityForUsageCostDetail: MessageHandlerUtility + +run(): HttpResponseMessage +} + +class "MessageHandlerUtility" as MessageHandlerUtility_T [[java:com.iluwatar.claimcheckpattern.utility]] { + +readFromPersistantStorage(messageReference: MessageReference, logger: Logger): Message + +dropToPersistantStorage(message: Message, logger: Logger): void +} + +class "EventHandlerUtility" as EventHandlerUtility_T [[java:com.callusage.utility.PersistentLocalStorageUtility]] { + +publishEvent(customEvent: T, logger: Logger): void +} + +class "Message" as Message_T [[java:com.iluwatar.claimcheckpattern.domain]] { + -messageHeader: MessageHeader + -messageData: MessageData + +Message(messageHeader: MessageHeader, messageData: MessageData) + +getMessageData(): MessageData + +getMessageHeader(): MessageHeader +} + + +class MessageHeader [[java:com.iluwatar.claimcheckpattern.domain]] { + -id: String + -subject: String + -topic: String + -eventType: String + -eventTime: String + -data: Object + -dataVersion: String + +getId(): String + +setId(id: String): void + +getSubject(): String + +setSubject(subject: String): void + +getTopic(): String + +setTopic(topic: String): void + +getEventType(): String + +setEventType(eventType: String): void + +getEventTime(): String + +setEventTime(eventTime: String): void + +getData(): Object + +setData(data: Object): void + +getDataVersion(): String + +setDataVersion(dataVersion:String): void + +} + + +class "MessageBody" as MessageBody_T [[java:com.iluwatar.claimcheckpattern.domain]] { + -data: List[] T + +getData(): List[] T + +setData(data:List[] T): void +} + +class MessageReference [[java:com.iluwatar.claimcheckpattern.domain]] { + -dataLocation: String + -dataFileName: String + +getDataLocation(): String + +setDataLocation(dataLocation:String): void + +getDataFileName(): String + +setDataFileName(dataFileName:String): void +} + +class UsageDetail [[java:com.iluwatar.claimcheckpattern.domain]] { + -userId: String + -duration: int + -data: int + +getUserId(): String + +setUserId(userId: String): void + +getDuration(): long + +setDuration(duration: long): void + +getData(): long + +setData(data: long): void +} + +class UsageCostDetail [[java:com.iluwatar.claimcheckpattern.domain]] { + -userId: String + -callCost: double + -dataCost: double + +getUserId(): String + +setUserId(userId: String): void + +getCallCost(): double + +setCallCost(callCost:double): void + +getDataCost(): double + +setDataCost(dataCost:double) : void +} + + + + + + + +Message_T "1" *-- "1" MessageHeader : has +Message_T "1" *-- "1" MessageBody_T : has +MessageHeader "1" *-- "1" MessageReference : has as data object +MessageBody_T "1" *-- "1" UsageDetail: has +MessageBody_T "1" *-- "1" UsageCostDetail: has + +EventHandlerUtility_T "1" *-- "1" MessageHeader: has +MessageHandlerUtility_T "1" *-- "1" Message_T: has + +UsageDetailPublisherFunction "1" *-- "1" MessageHandlerUtility_T : has +UsageDetailPublisherFunction "1" *-- "1" EventHandlerUtility_T : has + +UsageCostProcessorFunction "1" *-- "1" MessageHandlerUtility_T : has +UsageCostProcessorFunction "1" *-- "1" MessageHandlerUtility_T : has +@enduml \ No newline at end of file diff --git a/cloud-claim-check-pattern/etc/class-diagram.png b/cloud-claim-check-pattern/etc/class-diagram.png new file mode 100644 index 000000000..d627b1b70 Binary files /dev/null and b/cloud-claim-check-pattern/etc/class-diagram.png differ diff --git a/cloud-claim-check-pattern/pom.xml b/cloud-claim-check-pattern/pom.xml new file mode 100644 index 000000000..3f41053c0 --- /dev/null +++ b/cloud-claim-check-pattern/pom.xml @@ -0,0 +1,69 @@ + + + + + + com.iluwatar + java-design-patterns + 1.25.0-SNAPSHOT + + + 4.0.0 + claim-check-pattern + pom + + + call-usage-app + + + + com.google.code.gson + gson + 2.8.8 + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + org.mockito + mockito-junit-jupiter + 4.0.0 + test + + + + org.mockito + mockito-inline + 4.0.0 + test + + + + \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java index 4ea84e8c3..aa1f338ea 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -36,9 +36,6 @@ public class Wizard { private final Deque undoStack = new LinkedList<>(); private final Deque redoStack = new LinkedList<>(); - public Wizard() { - } - /** * Cast spell. */ diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java index 59cdc9b22..291704884 100644 --- a/commander/src/main/java/com/iluwatar/commander/Commander.java +++ b/commander/src/main/java/com/iluwatar/commander/Commander.java @@ -90,6 +90,13 @@ public class Commander { private static final Logger LOG = LoggerFactory.getLogger(Commander.class); //we could also have another db where it stores all orders + private static final String ORDER_ID = "Order {}"; + private static final String REQUEST_ID = " request Id: {}"; + private static final String ERROR_CONNECTING_MSG_SVC = + ": Error in connecting to messaging service "; + private static final String TRY_CONNECTING_MSG_SVC = + ": Trying to connect to messaging service.."; + Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService, MessagingService messagingService, QueueDatabase qdb, int numOfRetries, long retryDuration, long queueTime, long queueTaskTime, long paymentTime, @@ -118,17 +125,17 @@ public class Commander { Retry.Operation op = (l) -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to shipping service, " - + "trying again.."); + LOG.debug(ORDER_ID + ": Error in connecting to shipping service, " + + "trying again..", order.id); } else { - LOG.debug("Order " + order.id + ": Error in creating shipping request.."); + LOG.debug(ORDER_ID + ": Error in creating shipping request..", order.id); } throw l.remove(0); } String transactionId = shippingService.receiveRequest(order.item, order.user.address); //could save this transaction id in a db too - LOG.info("Order " + order.id + ": Shipping placed successfully, transaction id: " - + transactionId); + LOG.info(ORDER_ID + ": Shipping placed successfully, transaction id: {}", + order.id, transactionId); LOG.info("Order has been placed and will be shipped to you. Please wait while we make your" + " payment... "); sendPaymentRequest(order); @@ -138,19 +145,19 @@ public class Commander { LOG.info("Shipping is currently not possible to your address. We are working on the problem" + " and will get back to you asap."); finalSiteMsgShown = true; - LOG.info("Order " + order.id + ": Shipping not possible to address, trying to add problem " - + "to employee db.."); + LOG.info(ORDER_ID + ": Shipping not possible to address, trying to add problem " + + "to employee db..", order.id); employeeHandleIssue(o); } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { LOG.info("This item is currently unavailable. We will inform you as soon as the item " + "becomes available again."); finalSiteMsgShown = true; - LOG.info("Order " + order.id + ": Item " + order.item + " unavailable, trying to add " - + "problem to employee handle.."); + LOG.info(ORDER_ID + ": Item {}" + " unavailable, trying to add " + + "problem to employee handle..", order.id, order.item); employeeHandleIssue(o); } else { LOG.info("Sorry, there was a problem in creating your order. Please try later."); - LOG.error("Order " + order.id + ": Shipping service unavailable, order not placed.."); + LOG.error(ORDER_ID + ": Shipping service unavailable, order not placed..", order.id); finalSiteMsgShown = true; } }; @@ -164,7 +171,7 @@ public class Commander { if (order.paid.equals(PaymentStatus.TRYING)) { order.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(order); - LOG.error("Order " + order.id + ": Payment time for order over, failed and returning.."); + LOG.error(ORDER_ID + ": Payment time for order over, failed and returning..", order.id); } //if succeeded or failed, would have been dequeued, no attempt to make payment return; } @@ -173,17 +180,18 @@ public class Commander { Retry.Operation op = (l) -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to payment service," - + " trying again.."); + LOG.debug(ORDER_ID + ": Error in connecting to payment service," + + " trying again..", order.id); } else { - LOG.debug("Order " + order.id + ": Error in creating payment request.."); + LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id); } throw l.remove(0); } if (order.paid.equals(PaymentStatus.TRYING)) { var transactionId = paymentService.receiveRequest(order.price); order.paid = PaymentStatus.DONE; - LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId); + LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", + order.id, transactionId); if (!finalSiteMsgShown) { LOG.info("Payment made successfully, thank you for shopping with us!!"); finalSiteMsgShown = true; @@ -199,7 +207,7 @@ public class Commander { + "Meanwhile, your order has been converted to COD and will be shipped."); finalSiteMsgShown = true; } - LOG.error("Order " + order.id + ": Payment details incorrect, failed.."); + LOG.error(ORDER_ID + ": Payment details incorrect, failed..", order.id); o.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(o); } else { @@ -209,7 +217,7 @@ public class Commander { + "asap. Don't worry, your order has been placed and will be shipped."); finalSiteMsgShown = true; } - LOG.warn("Order " + order.id + ": Payment error, going to queue.."); + LOG.warn(ORDER_ID + ": Payment error, going to queue..", order.id); sendPaymentPossibleErrorMsg(o); } if (o.paid.equals(PaymentStatus.TRYING) && System @@ -234,7 +242,7 @@ public class Commander { if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) { // since payment time is lesser than queuetime it would have already failed.. // additional check not needed - LOG.trace("Order " + qt.order.id + ": Queue time for order over, failed.."); + LOG.trace(ORDER_ID + ": Queue time for order over, failed..", qt.order.id); return; } else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING) || qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1 @@ -242,30 +250,30 @@ public class Commander { || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) || qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) { - LOG.trace("Order " + qt.order.id + ": Not queueing task since task already done.."); + LOG.trace(ORDER_ID + ": Not queueing task since task already done..", qt.order.id); return; } var list = queue.exceptionsList; Thread t = new Thread(() -> { Retry.Operation op = (list1) -> { if (!list1.isEmpty()) { - LOG.warn("Order " + qt.order.id + ": Error in connecting to queue db, trying again.."); + LOG.warn(ORDER_ID + ": Error in connecting to queue db, trying again..", qt.order.id); throw list1.remove(0); } queue.add(qt); queueItems++; - LOG.info("Order " + qt.order.id + ": " + qt.getType() + " task enqueued.."); + LOG.info(ORDER_ID + ": {}" + " task enqueued..", qt.order.id, qt.getType()); tryDoingTasksInQueue(); }; Retry.HandleErrorIssue handleError = (qt1, err) -> { if (qt1.taskType.equals(TaskType.PAYMENT)) { qt1.order.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(qt1.order); - LOG.error("Order " + qt1.order.id + ": Unable to enqueue payment task," - + " payment failed.."); + LOG.error(ORDER_ID + ": Unable to enqueue payment task," + + " payment failed..", qt1.order.id); } - LOG.error("Order " + qt1.order.id + ": Unable to enqueue task of type " + qt1.getType() - + ", trying to add to employee handle.."); + LOG.error(ORDER_ID + ": Unable to enqueue task of type {}" + + ", trying to add to employee handle..", qt1.order.id, qt1.getType()); employeeHandleIssue(qt1.order); }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, @@ -328,7 +336,7 @@ public class Commander { private void sendSuccessMessage(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { - LOG.trace("Order " + order.id + ": Message time for order over, returning.."); + LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id); return; } var list = messagingService.exceptionsList; @@ -354,8 +362,8 @@ public class Commander { && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 2); updateQueue(qt); - LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to" - + " queue task and add to employee handle.."); + LOG.info(ORDER_ID + ": Error in sending Payment Success message, trying to" + + " queue task and add to employee handle..", order.id); employeeHandleIssue(order); } } @@ -364,11 +372,11 @@ public class Commander { return (l) -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to messaging service " - + "(Payment Success msg), trying again.."); + LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + + "(Payment Success msg), trying again..", order.id); } else { - LOG.debug("Order " + order.id + ": Error in creating Payment Success" - + " messaging request.."); + LOG.debug(ORDER_ID + ": Error in creating Payment Success" + + " messaging request..", order.id); } throw l.remove(0); } @@ -376,15 +384,15 @@ public class Commander { && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { var requestId = messagingService.receiveRequest(2); order.messageSent = MessageSent.PAYMENT_SUCCESSFUL; - LOG.info("Order " + order.id + ": Payment Success message sent," - + " request Id: " + requestId); + LOG.info(ORDER_ID + ": Payment Success message sent," + + REQUEST_ID, order.id, requestId); } }; } private void sendPaymentFailureMessage(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { - LOG.trace("Order " + order.id + ": Message time for order over, returning.."); + LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id); return; } var list = messagingService.exceptionsList; @@ -412,8 +420,8 @@ public class Commander { && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 0); updateQueue(qt); - LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, " - + "trying to queue task and add to employee handle.."); + LOG.warn(ORDER_ID + ": Error in sending Payment Failure message, " + + "trying to queue task and add to employee handle..", order.id); employeeHandleIssue(o); } } @@ -421,11 +429,11 @@ public class Commander { private void handlePaymentFailureRetryOperation(Order order, List l) throws Exception { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to messaging service " - + "(Payment Failure msg), trying again.."); + LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + + "(Payment Failure msg), trying again..", order.id); } else { - LOG.debug("Order " + order.id + ": Error in creating Payment Failure" - + " message request.."); + LOG.debug(ORDER_ID + ": Error in creating Payment Failure" + + " message request..", order.id); } throw l.remove(0); } @@ -433,8 +441,8 @@ public class Commander { && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { var requestId = messagingService.receiveRequest(0); order.messageSent = MessageSent.PAYMENT_FAIL; - LOG.info("Order " + order.id + ": Payment Failure message sent successfully," - + " request Id: " + requestId); + LOG.info(ORDER_ID + ": Payment Failure message sent successfully," + + REQUEST_ID, order.id, requestId); } } @@ -469,7 +477,7 @@ public class Commander { var qt = new QueueTask(order, TaskType.MESSAGING, 1); updateQueue(qt); LOG.warn("Order " + order.id + ": Error in sending Payment Error message, " - + "trying to queue task and add to employee handle.."); + + "trying to queue task and add to employee handle.."); employeeHandleIssue(o); } } @@ -478,11 +486,11 @@ public class Commander { throws Exception { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug("Order " + order.id + ": Error in connecting to messaging service " - + "(Payment Error msg), trying again.."); + LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + + "(Payment Error msg), trying again..", order.id); } else { - LOG.debug("Order " + order.id + ": Error in creating Payment Error" - + " messaging request.."); + LOG.debug(ORDER_ID + ": Error in creating Payment Error" + + " messaging request..", order.id); } throw l.remove(0); } @@ -490,28 +498,28 @@ public class Commander { .equals(MessageSent.NONE_SENT)) { var requestId = messagingService.receiveRequest(1); order.messageSent = MessageSent.PAYMENT_TRYING; - LOG.info("Order " + order.id + ": Payment Error message sent successfully," - + " request Id: " + requestId); + LOG.info(ORDER_ID + ": Payment Error message sent successfully," + + REQUEST_ID, order.id, requestId); } } private void employeeHandleIssue(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) { - LOG.trace("Order " + order.id + ": Employee handle time for order over, returning.."); + LOG.trace(ORDER_ID + ": Employee handle time for order over, returning..", order.id); return; } var list = employeeDb.exceptionsList; var t = new Thread(() -> { Retry.Operation op = (l) -> { if (!l.isEmpty()) { - LOG.warn("Order " + order.id + ": Error in connecting to employee handle," - + " trying again.."); + LOG.warn(ORDER_ID + ": Error in connecting to employee handle," + + " trying again..", order.id); throw l.remove(0); } if (!order.addedToEmployeeHandle) { employeeDb.receiveRequest(order); order.addedToEmployeeHandle = true; - LOG.info("Order " + order.id + ": Added order to employee database"); + LOG.info(ORDER_ID + ": Added order to employee database", order.id); } }; Retry.HandleErrorIssue handleError = (o, err) -> { @@ -519,8 +527,8 @@ public class Commander { .currentTimeMillis() - order.createdTime < employeeTime) { var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1); updateQueue(qt); - LOG.warn("Order " + order.id + ": Error in adding to employee db," - + " trying to queue task.."); + LOG.warn(ORDER_ID + ": Error in adding to employee db," + + " trying to queue task..", order.id); } }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, @@ -538,51 +546,51 @@ public class Commander { if (queueItems != 0) { var qt = queue.peek(); //this should probably be cloned here //this is why we have retry for doTasksInQueue - LOG.trace("Order " + qt.order.id + ": Started doing task of type " + qt.getType()); + LOG.trace(ORDER_ID + ": Started doing task of type {}", qt.order.id, qt.getType()); if (qt.getFirstAttemptTime() == -1) { qt.setFirstAttemptTime(System.currentTimeMillis()); } if (System.currentTimeMillis() - qt.getFirstAttemptTime() >= queueTaskTime) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This queue task of type " + qt.getType() - + " does not need to be done anymore (timeout), dequeue.."); + LOG.trace(ORDER_ID + ": This queue task of type {}" + + " does not need to be done anymore (timeout), dequeue..", qt.order.id, qt.getType()); } else { if (qt.taskType.equals(TaskType.PAYMENT)) { if (!qt.order.paid.equals(PaymentStatus.TRYING)) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This payment task already done, dequeueing.."); + LOG.trace(ORDER_ID + ": This payment task already done, dequeueing..", qt.order.id); } else { sendPaymentRequest(qt.order); - LOG.debug("Order " + qt.order.id + ": Trying to connect to payment service.."); + LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id); } } else if (qt.taskType.equals(TaskType.MESSAGING)) { if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This messaging task already done, dequeue.."); + LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id); } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) || !qt.order.paid.equals(PaymentStatus.TRYING))) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done," - + " dequeue.."); + LOG.trace(ORDER_ID + ": This messaging task does not need to be done," + + " dequeue..", qt.order.id); } else if (qt.messageType == 0) { sendPaymentFailureMessage(qt.order); - LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service.."); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); } else if (qt.messageType == 1) { sendPaymentPossibleErrorMsg(qt.order); - LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service.."); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); } else if (qt.messageType == 2) { sendSuccessMessage(qt.order); - LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service.."); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); } } else if (qt.taskType.equals(TaskType.EMPLOYEE_DB)) { if (qt.order.addedToEmployeeHandle) { tryDequeue(); - LOG.trace("Order " + qt.order.id + ": This employee handle task already done," - + " dequeue.."); + LOG.trace(ORDER_ID + ": This employee handle task already done," + + " dequeue..", qt.order.id); } else { employeeHandleIssue(qt.order); - LOG.debug("Order " + qt.order.id + ": Trying to connect to employee handle.."); + LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id); } } } diff --git a/commander/src/test/java/com/iluwatar/commander/CommanderTest.java b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java new file mode 100644 index 000000000..094cf7cf6 --- /dev/null +++ b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java @@ -0,0 +1,526 @@ +package com.iluwatar.commander; + +import com.iluwatar.commander.employeehandle.EmployeeDatabase; +import com.iluwatar.commander.employeehandle.EmployeeHandle; +import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import com.iluwatar.commander.exceptions.ItemUnavailableException; +import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; +import com.iluwatar.commander.exceptions.ShippingNotPossibleException; +import com.iluwatar.commander.messagingservice.MessagingDatabase; +import com.iluwatar.commander.messagingservice.MessagingService; +import com.iluwatar.commander.paymentservice.PaymentDatabase; +import com.iluwatar.commander.paymentservice.PaymentService; +import com.iluwatar.commander.queue.QueueDatabase; +import com.iluwatar.commander.shippingservice.ShippingDatabase; +import com.iluwatar.commander.shippingservice.ShippingService; + +import org.junit.jupiter.api.Test; +import org.junit.platform.commons.util.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +class CommanderTest { + + private final int numOfRetries = 1; + private final long retryDuration = 1_000; + private long queueTime = 1_00; + private long queueTaskTime = 1_000; + private long paymentTime = 6_000; + private long messageTime = 5_000; + private long employeeTime = 2_000; + + private static final List exceptionList = new ArrayList<>(); + + static { + exceptionList.add(new DatabaseUnavailableException()); + exceptionList.add(new ShippingNotPossibleException()); + exceptionList.add(new ItemUnavailableException()); + exceptionList.add(new PaymentDetailsErrorException()); + exceptionList.add(new IllegalStateException()); + } + + private Commander buildCommanderObject() { + return buildCommanderObject(false); + } + + private Commander buildCommanderObject(boolean nonPaymentException) { + PaymentService paymentService = new PaymentService + (new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + + ShippingService shippingService; + MessagingService messagingService; + if (nonPaymentException) { + shippingService = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); + messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + + } else { + shippingService = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); + messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + + } + var employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = new QueueDatabase + (new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectVanilla() { + PaymentService paymentService = new PaymentService + (new PaymentDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = new QueueDatabase + (new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException(), + new DatabaseUnavailableException(), new DatabaseUnavailableException()); + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectUnknownException() { + PaymentService paymentService = new PaymentService + (new PaymentDatabase(), new IllegalStateException()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase + (new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectNoPaymentException1() { + PaymentService paymentService = new PaymentService + (new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase + (new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectNoPaymentException2() { + PaymentService paymentService = new PaymentService + (new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase(), new IllegalStateException()); + var employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase + (new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectNoPaymentException3() { + PaymentService paymentService = new PaymentService + (new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase + (new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, qdb, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectWithDB() { + return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + } + + private Commander buildCommanderObjectWithDB(boolean includeException, boolean includeDBException, Exception e) { + var l = includeDBException ? new DatabaseUnavailableException() : e; + PaymentService paymentService; + ShippingService shippingService; + MessagingService messagingService; + EmployeeHandle employeeHandle; + if (includeException) { + paymentService = new PaymentService + (new PaymentDatabase(), l); + shippingService = new ShippingService(new ShippingDatabase(), l); + messagingService = new MessagingService(new MessagingDatabase(), l); + employeeHandle = new EmployeeHandle + (new EmployeeDatabase(), l); + } else { + paymentService = new PaymentService + (null); + shippingService = new ShippingService(null); + messagingService = new MessagingService(null); + employeeHandle = new EmployeeHandle + (null); + } + + + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, null, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + private Commander buildCommanderObjectWithoutDB() { + return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + } + + private Commander buildCommanderObjectWithoutDB(boolean includeException, boolean includeDBException, Exception e) { + var l = includeDBException ? new DatabaseUnavailableException() : e; + PaymentService paymentService; + ShippingService shippingService; + MessagingService messagingService; + EmployeeHandle employeeHandle; + if (includeException) { + paymentService = new PaymentService + (null, l); + shippingService = new ShippingService(null, l); + messagingService = new MessagingService(null, l); + employeeHandle = new EmployeeHandle + (null, l); + } else { + paymentService = new PaymentService + (null); + shippingService = new ShippingService(null); + messagingService = new MessagingService(null); + employeeHandle = new EmployeeHandle + (null); + } + + + return new Commander(employeeHandle, paymentService, shippingService, + messagingService, null, numOfRetries, retryDuration, + queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + } + + @Test + void testPlaceOrderVanilla() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectVanilla(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrder() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObject(true); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrder2() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObject(false); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException1() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException1(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException2() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException2(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException3() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException3(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoException4() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException3(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + c.placeOrder(order); + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderUnknownException() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectUnknownException(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderShortDuration() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObject(true); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderShortDuration2() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObject(false); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoExceptionShortMsgDuration() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectNoPaymentException1(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoExceptionShortQueueDuration() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectUnknownException(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithDatabase() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectWithDB(); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithDatabaseAndExceptions() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + + for (Exception e : exceptionList) { + + Commander c = buildCommanderObjectWithDB(true, true, e); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithDB(true, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithDB(false, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithDB(false, true, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + } + + @Test + void testPlaceOrderWithoutDatabase() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectWithoutDB(); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception { + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + + for (Exception e : exceptionList) { + + Commander c = buildCommanderObjectWithoutDB(true, true, e); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithoutDB(true, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithoutDB(false, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + + c = buildCommanderObjectWithoutDB(false, true, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + } + +} diff --git a/composite-view/README.md b/composite-view/README.md new file mode 100644 index 000000000..e4ccced28 --- /dev/null +++ b/composite-view/README.md @@ -0,0 +1,325 @@ +--- +layout: pattern +title: Composite View +folder: composite-view +permalink: /patterns/composite-view/ +categories: Structural +language: en +tags: +- Enterprise Integration Pattern +- Presentation +--- + +## Name +**Composite View** + +## Intent +The purpose of the Composite View Pattern is to increase re-usability and flexibility when creating views for websites/webapps. +This pattern seeks to decouple the content of the page from its layout, allowing changes to be made to either the content +or layout of the page without impacting the other. This pattern also allows content to be easily reused across different views easily. + +## Explanation +Real World Example +> A news site wants to display the current date and news to different users +> based on that user's preferences. The news site will substitute in different news feed +> components depending on the user's interest, defaulting to local news. + +In Plain Words +> Composite View Pattern is having a main view being composed of smaller subviews. +> The layout of this composite view is based on a template. A View-manager then decides which +> subviews to include in this template. + +Wikipedia Says +> Composite views that are composed of multiple atomic subviews. Each component of +> the template may be included dynamically into the whole and the layout of the page may be managed independently of the content. +> This solution provides for the creation of a composite view based on the inclusion and substitution of +> modular dynamic and static template fragments. +> It promotes the reuse of atomic portions of the view by encouraging modular design. + +**Programmatic Example** + +Since this is a web development pattern, a server is required to demonstrate it. +This example uses Tomcat 10.0.13 to run the servlet, and this programmatic example will only work with Tomcat 10+. + +Firstly there is `AppServlet` which is an `HttpServlet` that runs on Tomcat 10+. +```java +public class AppServlet extends HttpServlet { + private String msgPartOne = "

This Server Doesn't Support"; + private String msgPartTwo = "Requests

\n" + + "

Use a GET request with boolean values for the following parameters

\n" + + "

'name'

\n

'bus'

\n

'sports'

\n

'sci'

\n

'world'

"; + + private String destination = "newsDisplay.jsp"; + + public AppServlet() { + + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); + ClientPropertiesBean reqParams = new ClientPropertiesBean(req); + req.setAttribute("properties", reqParams); + requestDispatcher.forward(req, resp); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Post " + msgPartTwo); + + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Delete " + msgPartTwo); + + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + PrintWriter out = resp.getWriter(); + out.println(msgPartOne + " Put " + msgPartTwo); + + } +} + +``` +This servlet is not part of the pattern, and simply forwards GET requests to the correct JSP. +PUT, POST, and DELETE requests are not supported and will simply show an error message. + +The view management in this example is done via a javabean class: `ClientPropertiesBean`, which stores user preferences. +```java +public class ClientPropertiesBean implements Serializable { + + private static final String WORLD_PARAM = "world"; + private static final String SCIENCE_PARAM = "sci"; + private static final String SPORTS_PARAM = "sport"; + private static final String BUSINESS_PARAM = "bus"; + private static final String NAME_PARAM = "name"; + + private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private boolean worldNewsInterest; + private boolean sportsInterest; + private boolean businessInterest; + private boolean scienceNewsInterest; + private String name; + + public ClientPropertiesBean() { + worldNewsInterest = true; + sportsInterest = true; + businessInterest = true; + scienceNewsInterest = true; + name = DEFAULT_NAME; + + } + + public ClientPropertiesBean(HttpServletRequest req) { + worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM)); + sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM)); + businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM)); + scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM)); + String tempName = req.getParameter(NAME_PARAM); + if (tempName == null || tempName == "") { + tempName = DEFAULT_NAME; + } + name = tempName; + } + // getters and setters generated by Lombok +} +``` +This javabean has a default constructor, and another that takes an `HttpServletRequest`. +This second constructor takes the request object, parses out the request parameters which contain the +user preferences for different types of news. + +The template for the news page is in `newsDisplay.jsp` +```html + + + + + + <%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%> +

Welcome <%= propertiesBean.getName()%>

+ + + + + + <% if(propertiesBean.isWorldNewsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isBusinessInterest()) { %> + + <% } else { %> + + <% } %> + + <% if(propertiesBean.isSportsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isScienceNewsInterest()) { %> + + <% } else { %> + + <% } %> + + +
<%@include file="worldNews.jsp"%><%@include file="localNews.jsp"%>
<%@include file="businessNews.jsp"%><%@include file="localNews.jsp"%><%@include file="sportsNews.jsp"%><%@include file="localNews.jsp"%>
<%@include file="scienceNews.jsp"%><%@include file="localNews.jsp"%>
+ + +``` +This JSP page is the template. It declares a table with three rows, with one component in the first row, +two components in the second row, and one component in the third row. + +The scriplets in the file are part of the +view management strategy that include different atomic subviews based on the user preferences in the Javabean. + +Here are two examples of the mock atomic subviews used in the composite: +`businessNews.jsp` +```html + + + + + +

+ Generic Business News +

+ + + + + + + + + +
Stock prices up across the worldNew tech companies to invest in
Industry leaders unveil new projectPrice fluctuations and what they mean
+ + +``` +`localNews.jsp` +```html + + +
+

+ Generic Local News +

+
    +
  • + Mayoral elections coming up in 2 weeks +
  • +
  • + New parking meter rates downtown coming tomorrow +
  • +
  • + Park renovations to finish by the next year +
  • +
  • + Annual marathon sign ups available online +
  • +
+
+ + +``` +The results are as such: + +1) The user has put their name as `Tammy` in the request parameters and no preferences: +![alt text](etc/images/noparam.PNG) +2) The user has put their name as `Johnny` in the request parameters and has a preference for world, business, and science news: +![alt text](etc/images/threeparams.PNG) + +The different subviews such as `worldNews.jsp`, `businessNews.jsp`, etc. are included conditionally +based on the request parameters. + +**How To Use** + +To try this example, make sure you have Tomcat 10+ installed. +Set up your IDE to build a WAR file from the module and deploy that file to the server + +IntelliJ: + +Under `Run` and `edit configurations` Make sure Tomcat server is one of the run configurations. +Go to the deployment tab, and make sure there is one artifact being built called `composite-view:war exploded`. +If not present, add one. + +Ensure that the artifact is being built from the content of the `web` directory and the compilation results of the module. +Point the output of the artifact to a convenient place. Run the configuration and view the landing page, +follow instructions on that page to continue. + +## Class diagram + +![alt text](./etc/composite_view.png) + +The class diagram here displays the Javabean which is the view manager. +The views are JSP's held inside the web directory. + +## Applicability + +This pattern is applicable to most websites that require content to be displayed dynamically/conditionally. +If there are components that need to be re-used for multiple views, or if the project requires reusing a template, +or if it needs to include content depending on certain conditions, then this pattern is a good choice. + +## Known uses + +Most modern websites use composite views in some shape or form, as they have templates for views and small atomic components +that are included in the page dynamically. Most modern Javascript libraries, like React, support this design pattern +with components. + +## Consequences +**Pros** +* Easy to re-use components +* Change layout/content without affecting the other +* Reduce code duplication +* Code is more maintainable and modular + +**Cons** +* Overhead cost at runtime +* Slower response compared to directly embedding elements +* Increases potential for display errors + +## Related patterns +* [Composite (GoF)](https://java-design-patterns.com/patterns/composite/) +* [View Helper](https://www.oracle.com/java/technologies/viewhelper.html) + +## Credits +* [Core J2EE Patterns - Composite View](https://www.oracle.com/java/technologies/composite-view.html) +* [Composite View Design Pattern – Core J2EE Patterns](https://www.dineshonjava.com/composite-view-design-pattern/) + diff --git a/composite-view/etc/composite-view.urm.puml b/composite-view/etc/composite-view.urm.puml new file mode 100644 index 000000000..e92b13ea5 --- /dev/null +++ b/composite-view/etc/composite-view.urm.puml @@ -0,0 +1,29 @@ +@startuml +package com.iluwatar.compositeview { + class ClientPropertiesBean { + - BUSINESS_PARAM : String {static} + - DEFAULT_NAME : String {static} + - NAME_PARAM : String {static} + - SCIENCE_PARAM : String {static} + - SPORTS_PARAM : String {static} + - WORLD_PARAM : String {static} + - businessInterest : boolean + - name : String + - scienceNewsInterest : boolean + - sportsInterest : boolean + - worldNewsInterest : boolean + + ClientPropertiesBean() + + ClientPropertiesBean(req : HttpServletRequest) + + getName() : String + + isBusinessInterest() : boolean + + isScienceNewsInterest() : boolean + + isSportsInterest() : boolean + + isWorldNewsInterest() : boolean + + setBusinessInterest(businessInterest : boolean) + + setName(name : String) + + setScienceNewsInterest(scienceNewsInterest : boolean) + + setSportsInterest(sportsInterest : boolean) + + setWorldNewsInterest(worldNewsInterest : boolean) + } +} +@enduml \ No newline at end of file diff --git a/composite-view/etc/composite_view.png b/composite-view/etc/composite_view.png new file mode 100644 index 000000000..66215d941 Binary files /dev/null and b/composite-view/etc/composite_view.png differ diff --git a/composite-view/etc/images/noparam.PNG b/composite-view/etc/images/noparam.PNG new file mode 100644 index 000000000..2979cf2bc Binary files /dev/null and b/composite-view/etc/images/noparam.PNG differ diff --git a/composite-view/etc/images/threeparams.PNG b/composite-view/etc/images/threeparams.PNG new file mode 100644 index 000000000..9338dedb8 Binary files /dev/null and b/composite-view/etc/images/threeparams.PNG differ diff --git a/composite-view/pom.xml b/composite-view/pom.xml new file mode 100644 index 000000000..cbb6159b8 --- /dev/null +++ b/composite-view/pom.xml @@ -0,0 +1,80 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + composite-view + + + org.junit.jupiter + junit-jupiter-engine + test + + + junit + junit + test + + + jakarta.servlet + jakarta.servlet-api + 5.0.0 + compile + + + org.mockito + mockito-core + 4.1.0 + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.compositeview.App + + + + + + + + + + \ No newline at end of file diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java new file mode 100644 index 000000000..c15e44c9c --- /dev/null +++ b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java @@ -0,0 +1,64 @@ +package com.iluwatar.compositeview; + +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * A servlet object that extends HttpServlet. + * Runs on Tomcat 10 and handles Http requests + */ + +public final class AppServlet extends HttpServlet { + private String msgPartOne = "

This Server Doesn't Support"; + private String msgPartTwo = "Requests

\n" + + "

Use a GET request with boolean values for the following parameters

\n" + + "

'name'

\n

'bus'

\n

'sports'

\n

'sci'

\n

'world'

"; + + private String destination = "newsDisplay.jsp"; + + public AppServlet() { + + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); + ClientPropertiesBean reqParams = new ClientPropertiesBean(req); + req.setAttribute("properties", reqParams); + requestDispatcher.forward(req, resp); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + try (PrintWriter out = resp.getWriter()) { + out.println(msgPartOne + " Post " + msgPartTwo); + } + + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + try (PrintWriter out = resp.getWriter()) { + out.println(msgPartOne + " Delete " + msgPartTwo); + } + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html"); + try (PrintWriter out = resp.getWriter()) { + out.println(msgPartOne + " Put " + msgPartTwo); + } + } +} diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java b/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java new file mode 100644 index 000000000..c8e694713 --- /dev/null +++ b/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java @@ -0,0 +1,53 @@ +package com.iluwatar.compositeview; + +import jakarta.servlet.http.HttpServletRequest; +import java.io.Serializable; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + + +/** + * A Java beans class that parses a http request and stores parameters. + * Java beans used in JSP's to dynamically include elements in view. + * DEFAULT_NAME = a constant, default name to be used for the default constructor + * worldNewsInterest = whether current request has world news interest + * sportsInterest = whether current request has a sportsInterest + * businessInterest = whether current request has a businessInterest + * scienceNewsInterest = whether current request has a scienceNewsInterest + */ +@Getter +@Setter +@NoArgsConstructor +public class ClientPropertiesBean implements Serializable { + + private static final String WORLD_PARAM = "world"; + private static final String SCIENCE_PARAM = "sci"; + private static final String SPORTS_PARAM = "sport"; + private static final String BUSINESS_PARAM = "bus"; + private static final String NAME_PARAM = "name"; + + private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private boolean worldNewsInterest = true; + private boolean sportsInterest = true; + private boolean businessInterest = true; + private boolean scienceNewsInterest = true; + private String name = DEFAULT_NAME; + + /** + * Constructor that parses an HttpServletRequest and stores all the request parameters. + * + * @param req the HttpServletRequest object that is passed in + */ + public ClientPropertiesBean(HttpServletRequest req) { + worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM)); + sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM)); + businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM)); + scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM)); + String tempName = req.getParameter(NAME_PARAM); + if (tempName == null || tempName.equals("")) { + tempName = DEFAULT_NAME; + } + name = tempName; + } +} diff --git a/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java b/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java new file mode 100644 index 000000000..38c1a1bc2 --- /dev/null +++ b/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java @@ -0,0 +1,83 @@ +package com.iluwatar.compositeview; + +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import static org.junit.Assert.*; + +/* Written with reference from https://stackoverflow.com/questions/5434419/how-to-test-my-servlet-using-junit +and https://stackoverflow.com/questions/50211433/servlets-unit-testing + */ + +public class AppServletTest extends Mockito{ + private String msgPartOne = "

This Server Doesn't Support"; + private String msgPartTwo = "Requests

\n" + + "

Use a GET request with boolean values for the following parameters

\n" + + "

'name'

\n

'bus'

\n

'sports'

\n

'sci'

\n

'world'

"; + private String destination = "newsDisplay.jsp"; + + @Test + public void testDoGet() throws Exception { + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + RequestDispatcher mockDispatcher = Mockito.mock(RequestDispatcher.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); + when(mockReq.getRequestDispatcher(destination)).thenReturn(mockDispatcher); + AppServlet curServlet = new AppServlet(); + curServlet.doGet(mockReq, mockResp); + verify(mockReq, times(1)).getRequestDispatcher(destination); + verify(mockDispatcher).forward(mockReq, mockResp); + + + } + + @Test + public void testDoPost() throws Exception { + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); + + AppServlet curServlet = new AppServlet(); + curServlet.doPost(mockReq, mockResp); + printWriter.flush(); + assertTrue(stringWriter.toString().contains(msgPartOne + " Post " + msgPartTwo)); + } + + @Test + public void testDoPut() throws Exception { + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); + + AppServlet curServlet = new AppServlet(); + curServlet.doPut(mockReq, mockResp); + printWriter.flush(); + assertTrue(stringWriter.toString().contains(msgPartOne + " Put " + msgPartTwo)); + } + + @Test + public void testDoDelete() throws Exception { + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); + + AppServlet curServlet = new AppServlet(); + curServlet.doDelete(mockReq, mockResp); + printWriter.flush(); + assertTrue(stringWriter.toString().contains(msgPartOne + " Delete " + msgPartTwo)); + } +} diff --git a/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java b/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java new file mode 100644 index 000000000..6583ab45d --- /dev/null +++ b/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java @@ -0,0 +1,71 @@ +package com.iluwatar.compositeview; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.Assert.*; + +public class JavaBeansTest { + @Test + public void testDefaultConstructor() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertEquals("DEFAULT_NAME", newBean.getName()); + assertTrue(newBean.isBusinessInterest()); + assertTrue(newBean.isScienceNewsInterest()); + assertTrue(newBean.isSportsInterest()); + assertTrue(newBean.isWorldNewsInterest()); + + } + + @Test + public void testNameGetterSetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertEquals("DEFAULT_NAME", newBean.getName()); + newBean.setName("TEST_NAME_ONE"); + assertEquals("TEST_NAME_ONE", newBean.getName()); + } + + @Test + public void testBusinessSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isBusinessInterest()); + newBean.setBusinessInterest(false); + assertFalse(newBean.isBusinessInterest()); + } + + @Test + public void testScienceSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isScienceNewsInterest()); + newBean.setScienceNewsInterest(false); + assertFalse(newBean.isScienceNewsInterest()); + } + + @Test + public void testSportsSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isSportsInterest()); + newBean.setSportsInterest(false); + assertFalse(newBean.isSportsInterest()); + } + + @Test + public void testWorldSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isWorldNewsInterest()); + newBean.setWorldNewsInterest(false); + assertFalse(newBean.isWorldNewsInterest()); + } + + @Test + public void testRequestConstructor(){ + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + ClientPropertiesBean newBean = new ClientPropertiesBean((mockReq)); + assertEquals("DEFAULT_NAME", newBean.getName()); + assertFalse(newBean.isWorldNewsInterest()); + assertFalse(newBean.isBusinessInterest()); + assertFalse(newBean.isScienceNewsInterest()); + assertFalse(newBean.isSportsInterest()); + } +} diff --git a/composite-view/web/WEB-INF/web.xml b/composite-view/web/WEB-INF/web.xml new file mode 100644 index 000000000..7cdd74c7b --- /dev/null +++ b/composite-view/web/WEB-INF/web.xml @@ -0,0 +1,14 @@ + + + + appServlet + com.iluwatar.compositeview.AppServlet + + + appServlet + /news + + \ No newline at end of file diff --git a/composite-view/web/businessNews.jsp b/composite-view/web/businessNews.jsp new file mode 100644 index 000000000..f9c67bc3c --- /dev/null +++ b/composite-view/web/businessNews.jsp @@ -0,0 +1,33 @@ +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 2:51 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

+ Generic Business News +

+ + + + + + + + + +
Stock prices up across the worldNew tech companies to invest in
Industry leaders unveil new projectPrice fluctuations and what they mean
+ + diff --git a/composite-view/web/header.jsp b/composite-view/web/header.jsp new file mode 100644 index 000000000..07b24f878 --- /dev/null +++ b/composite-view/web/header.jsp @@ -0,0 +1,23 @@ +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 1:28 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ page import="java.util.Date"%> + + + + + + <% String todayDateStr = (new Date().toString()); %> +

Today's Personalized Frontpage

+

<%=todayDateStr%>

+ + diff --git a/composite-view/web/index.jsp b/composite-view/web/index.jsp new file mode 100644 index 000000000..527db3b33 --- /dev/null +++ b/composite-view/web/index.jsp @@ -0,0 +1,20 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

Welcome To The Composite Patterns Mock News Site

+

Send a GET request to the "/news" path to see the composite view with mock news

+

Use the following parameters:

+

name: string name to be dynamically displayed

+

bus: boolean for whether you want to see the mock business news

+

world: boolean for whether you want to see the mock world news

+

sci: boolean for whether you want to see the mock world news

+

sport: boolean for whether you want to see the mock world news

+ + diff --git a/composite-view/web/localNews.jsp b/composite-view/web/localNews.jsp new file mode 100644 index 000000000..3ab3ea1e9 --- /dev/null +++ b/composite-view/web/localNews.jsp @@ -0,0 +1,25 @@ + +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +
+

+ Generic Local News +

+
    +
  • + Mayoral elections coming up in 2 weeks +
  • +
  • + New parking meter rates downtown coming tomorrow +
  • +
  • + Park renovations to finish by the next year +
  • +
  • + Annual marathon sign ups available online +
  • +
+
+ + diff --git a/composite-view/web/newsDisplay.jsp b/composite-view/web/newsDisplay.jsp new file mode 100644 index 000000000..936a98e1d --- /dev/null +++ b/composite-view/web/newsDisplay.jsp @@ -0,0 +1,57 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ page import="com.iluwatar.compositeview.ClientPropertiesBean"%> + + + + + + <%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%> +

Welcome <%= propertiesBean.getName()%>

+ + + + + + <% if(propertiesBean.isWorldNewsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isBusinessInterest()) { %> + + <% } else { %> + + <% } %> + + <% if(propertiesBean.isSportsInterest()) { %> + + <% } else { %> + + <% } %> + + + + <% if(propertiesBean.isScienceNewsInterest()) { %> + + <% } else { %> + + <% } %> + + +
<%@include file="worldNews.jsp"%><%@include file="localNews.jsp"%>
<%@include file="businessNews.jsp"%><%@include file="localNews.jsp"%><%@include file="sportsNews.jsp"%><%@include file="localNews.jsp"%>
<%@include file="scienceNews.jsp"%><%@include file="localNews.jsp"%>
+ + diff --git a/composite-view/web/scienceNews.jsp b/composite-view/web/scienceNews.jsp new file mode 100644 index 000000000..2c81d8ff5 --- /dev/null +++ b/composite-view/web/scienceNews.jsp @@ -0,0 +1,34 @@ +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 4:18 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +
+

+ Generic Science News +

+
    +
  • + New model of gravity proposed for dark matter +
  • +
  • + Genetic modifying technique proved on bacteria +
  • +
  • + Neurology study maps brain with new precision +
  • +
  • + Survey of rainforest discovers 15 new species +
  • +
  • + New signalling pathway for immune system discovered +
  • +
+
+ + diff --git a/composite-view/web/sportsNews.jsp b/composite-view/web/sportsNews.jsp new file mode 100644 index 000000000..3d3aa12e8 --- /dev/null +++ b/composite-view/web/sportsNews.jsp @@ -0,0 +1,32 @@ +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 3:53 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

+ Generic Sports News +

+
+ International football match delayed due to weather, will be held next week +
+
+ New rising stars in winter sports, ten new athletes that will shake up the scene +
+
+ Biggest upset in basketball history, upstart team sweeps competition +
+ + diff --git a/composite-view/web/worldNews.jsp b/composite-view/web/worldNews.jsp new file mode 100644 index 000000000..a75060d76 --- /dev/null +++ b/composite-view/web/worldNews.jsp @@ -0,0 +1,34 @@ +<%-- + Created by IntelliJ IDEA. + User: Kevin + Date: 11/29/2021 + Time: 2:51 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + +

+ Generic World News +

+ + + + + + + + + + +
New trade talks happening at UN on Thursday
European Union to announce new resolution next week
UN delivers report on world economic status
+ + diff --git a/event-aggregator/README.md b/event-aggregator/README.md index 2e54ed904..f3b941497 100644 --- a/event-aggregator/README.md +++ b/event-aggregator/README.md @@ -9,6 +9,10 @@ tags: - Reactive --- +## Name + +Event Aggregator + ## Intent A system with lots of objects can lead to complexities when a client wants to subscribe to events. The client has to find and register for @@ -17,6 +21,136 @@ requires a separate subscription. An Event Aggregator acts as a single source of events for many objects. It registers for all the events of the many objects allowing clients to register with just the aggregator. +## Explanation + +Real-world example + +> King Joffrey sits on the iron throne and rules the seven kingdoms of Westeros. He receives most +> of his critical information from King's Hand, the second in command. King's hand has many +> close advisors himself, feeding him with relevant information about events occurring in the +> kingdom. + +In Plain Words + +> Event Aggregator is an event mediator that collects events from multiple sources and delivers +> them to registered observers. + +**Programmatic Example** + +In our programmatic example, we demonstrate the implementation of an event aggregator pattern. Some of +the objects are event listeners, some are event emitters, and the event aggregator does both. + +```java +public interface EventObserver { + void onEvent(Event e); +} + +public abstract class EventEmitter { + + private final Map> observerLists; + + public EventEmitter() { + observerLists = new HashMap<>(); + } + + public final void registerObserver(EventObserver obs, Event e) { + ... + } + + protected void notifyObservers(Event e) { + ... + } +} +``` + +`KingJoffrey` is listening to events from `KingsHand`. + +```java +@Slf4j +public class KingJoffrey implements EventObserver { + @Override + public void onEvent(Event e) { + LOGGER.info("Received event from the King's Hand: {}", e.toString()); + } +} +``` + +`KingsHand` is listening to events from his subordinates `LordBaelish`, `LordVarys`, and `Scout`. +Whatever he hears from them, he delivers to `KingJoffrey`. + +```java +public class KingsHand extends EventEmitter implements EventObserver { + + public KingsHand() { + } + + public KingsHand(EventObserver obs, Event e) { + super(obs, e); + } + + @Override + public void onEvent(Event e) { + notifyObservers(e); + } +} +``` + +For example, `LordVarys` finds a traitor every Sunday and notifies the `KingsHand`. + +```java +@Slf4j +public class LordVarys extends EventEmitter implements EventObserver { + @Override + public void timePasses(Weekday day) { + if (day == Weekday.SATURDAY) { + notifyObservers(Event.TRAITOR_DETECTED); + } + } +} +``` + +The following snippet demonstrates how the objects are constructed and wired together. + +```java + var kingJoffrey = new KingJoffrey(); + + var kingsHand = new KingsHand(); + kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); + kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); + + var varys = new LordVarys(); + varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); + varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); + + var scout = new Scout(); + scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); + scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); + + var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); + + var emitters = List.of( + kingsHand, + baelish, + varys, + scout + ); + + Arrays.stream(Weekday.values()) + .>map(day -> emitter -> emitter.timePasses(day)) + .forEachOrdered(emitters::forEach); +``` + +The console output after running the example. + +``` +18:21:52.955 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Warships approaching +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: White walkers sighted +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Stark sighted +18:21:52.960 [main] INFO com.iluwatar.event.aggregator.KingJoffrey - Received event from the King's Hand: Traitor detected +``` + ## Class diagram ![alt text](./etc/classes.png "Event Aggregator") @@ -26,9 +160,13 @@ Use the Event Aggregator pattern when * Event Aggregator is a good choice when you have lots of objects that are potential event sources. Rather than have the observer deal with registering with them all, you can centralize the registration logic to the Event - Aggregator. As well as simplifying registration, a Event Aggregator also + Aggregator. As well as simplifying registration, an Event Aggregator also simplifies the memory management issues in using observers. +## Related patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/) + ## Credits * [Martin Fowler - Event Aggregator](http://martinfowler.com/eaaDev/EventAggregator.html) diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java index fb7193b2e..ae9046a8c 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java @@ -49,13 +49,28 @@ public class App { public static void main(String[] args) { var kingJoffrey = new KingJoffrey(); - var kingsHand = new KingsHand(kingJoffrey); + + var kingsHand = new KingsHand(); + kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED); + kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED); + + var varys = new LordVarys(); + varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED); + varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED); + + var scout = new Scout(); + scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING); + scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED); + + var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); var emitters = List.of( kingsHand, - new LordBaelish(kingsHand), - new LordVarys(kingsHand), - new Scout(kingsHand) + baelish, + varys, + scout ); Arrays.stream(Weekday.values()) diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java index 61b9d713a..f79a7bb4e 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java @@ -31,6 +31,7 @@ import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public enum Event { + WHITE_WALKERS_SIGHTED("White walkers sighted"), STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED("Traitor detected"); diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java index 79093885d..9ac047df9 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java @@ -23,31 +23,48 @@ package com.iluwatar.event.aggregator; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Map; /** * EventEmitter is the base class for event producers that can be observed. */ public abstract class EventEmitter { - private final List observers; + private final Map> observerLists; public EventEmitter() { - observers = new LinkedList<>(); + observerLists = new HashMap<>(); } - public EventEmitter(EventObserver obs) { + public EventEmitter(EventObserver obs, Event e) { this(); - registerObserver(obs); + registerObserver(obs, e); } - public final void registerObserver(EventObserver obs) { - observers.add(obs); + /** + * Registers observer for specific event in the related list. + * + * @param obs the observer that observers this emitter + * @param e the specific event for that observation occurs + * */ + public final void registerObserver(EventObserver obs, Event e) { + if (!observerLists.containsKey(e)) { + observerLists.put(e, new LinkedList<>()); + } + if (!observerLists.get(e).contains(obs)) { + observerLists.get(e).add(obs); + } } protected void notifyObservers(Event e) { - observers.forEach(obs -> obs.onEvent(e)); + if (observerLists.containsKey(e)) { + observerLists + .get(e) + .forEach(observer -> observer.onEvent(e)); + } } public abstract void timePasses(Weekday day); diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java index 192e9681a..c7fe007f1 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java @@ -31,8 +31,8 @@ public class KingsHand extends EventEmitter implements EventObserver { public KingsHand() { } - public KingsHand(EventObserver obs) { - super(obs); + public KingsHand(EventObserver obs, Event e) { + super(obs, e); } @Override @@ -42,6 +42,5 @@ public class KingsHand extends EventEmitter implements EventObserver { @Override public void timePasses(Weekday day) { - // NOP } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java index b00a05330..ed046fd66 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java @@ -31,8 +31,8 @@ public class LordBaelish extends EventEmitter { public LordBaelish() { } - public LordBaelish(EventObserver obs) { - super(obs); + public LordBaelish(EventObserver obs, Event e) { + super(obs, e); } @Override diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java index b56635eab..9fb3d2625 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java @@ -23,16 +23,19 @@ package com.iluwatar.event.aggregator; +import lombok.extern.slf4j.Slf4j; + /** * LordVarys produces events. */ -public class LordVarys extends EventEmitter { +@Slf4j +public class LordVarys extends EventEmitter implements EventObserver { public LordVarys() { } - public LordVarys(EventObserver obs) { - super(obs); + public LordVarys(EventObserver obs, Event e) { + super(obs, e); } @Override @@ -41,4 +44,10 @@ public class LordVarys extends EventEmitter { notifyObservers(Event.TRAITOR_DETECTED); } } + + + @Override + public void onEvent(Event e) { + notifyObservers(e); + } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java index 88061e40e..8d47fff66 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java @@ -31,8 +31,8 @@ public class Scout extends EventEmitter { public Scout() { } - public Scout(EventObserver obs) { - super(obs); + public Scout(EventObserver obs, Event e) { + super(obs, e); } @Override @@ -40,5 +40,8 @@ public class Scout extends EventEmitter { if (day == Weekday.TUESDAY) { notifyObservers(Event.WARSHIPS_APPROACHING); } + if (day == Weekday.WEDNESDAY) { + notifyObservers(Event.WHITE_WALKERS_SIGHTED); + } } } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java index 1378ead9e..02cda6752 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java @@ -31,6 +31,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import java.util.Objects; +import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import org.junit.jupiter.api.Test; @@ -46,7 +47,7 @@ abstract class EventEmitterTest { /** * Factory used to create a new instance of the test object with a default observer */ - private final Function factoryWithDefaultObserver; + private final BiFunction factoryWithDefaultObserver; /** * Factory used to create a new instance of the test object without passing a default observer @@ -67,7 +68,7 @@ abstract class EventEmitterTest { * Create a new event emitter test, using the given test object factories, special day and event */ EventEmitterTest(final Weekday specialDay, final Event event, - final Function factoryWithDefaultObserver, + final BiFunction factoryWithDefaultObserver, final Supplier factoryWithoutDefaultObserver) { this.specialDay = specialDay; @@ -129,8 +130,8 @@ abstract class EventEmitterTest { final var observer2 = mock(EventObserver.class); final var emitter = this.factoryWithoutDefaultObserver.get(); - emitter.registerObserver(observer1); - emitter.registerObserver(observer2); + emitter.registerObserver(observer1, event); + emitter.registerObserver(observer2, event); testAllDays(specialDay, event, emitter, observer1, observer2); } @@ -146,9 +147,9 @@ abstract class EventEmitterTest { final var observer1 = mock(EventObserver.class); final var observer2 = mock(EventObserver.class); - final var emitter = this.factoryWithDefaultObserver.apply(defaultObserver); - emitter.registerObserver(observer1); - emitter.registerObserver(observer2); + final var emitter = this.factoryWithDefaultObserver.apply(defaultObserver, event); + emitter.registerObserver(observer1, event); + emitter.registerObserver(observer2, event); testAllDays(specialDay, event, emitter, defaultObserver, observer1, observer2); } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java index 51229b155..819e66309 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -55,7 +55,11 @@ class KingsHandTest extends EventEmitterTest { @Test void testPassThrough() throws Exception { final var observer = mock(EventObserver.class); - final var kingsHand = new KingsHand(observer); + final var kingsHand = new KingsHand(); + kingsHand.registerObserver(observer, Event.STARK_SIGHTED); + kingsHand.registerObserver(observer, Event.WARSHIPS_APPROACHING); + kingsHand.registerObserver(observer, Event.TRAITOR_DETECTED); + kingsHand.registerObserver(observer, Event.WHITE_WALKERS_SIGHTED); // The kings hand should not pass any events before he received one verifyZeroInteractions(observer); diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java index 3a13869d2..0c5976c52 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java @@ -34,7 +34,9 @@ class ScoutTest extends EventEmitterTest { * Create a new test instance, using the correct object factory */ public ScoutTest() { - super(Weekday.TUESDAY, Event.WARSHIPS_APPROACHING, Scout::new, Scout::new); + + super(Weekday.TUESDAY, Event.WARSHIPS_APPROACHING, Scout::new, Scout::new); + } } \ No newline at end of file diff --git a/execute-around/README.md b/execute-around/README.md index 16d4803c3..06b0b2154 100644 --- a/execute-around/README.md +++ b/execute-around/README.md @@ -17,10 +17,10 @@ the user to specify only what to do with the resource. ## Explanation -Real world example +Real-world example -> We need to provide a class that can be used to write text strings to files. To make it easy for -> the user we let our service class open and close the file automatically, the user only has to +> A class needs to be provided for writing text strings to files. To make it easy for +> the user, the service class opens and closes the file automatically. The user only has to > specify what is written into which file. In plain words @@ -35,35 +35,50 @@ In plain words **Programmatic Example** -Let's introduce our file writer class. +`SimpleFileWriter` class implements the Execute Around idiom. It takes `FileWriterAction` as a +constructor argument allowing the user to specify what gets written into the file. ```java @FunctionalInterface public interface FileWriterAction { - void writeFile(FileWriter writer) throws IOException; - } +@Slf4j public class SimpleFileWriter { - - public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { - try (var writer = new FileWriter(filename)) { - action.writeFile(writer); + public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { + LOGGER.info("Opening the file"); + try (var writer = new FileWriter(filename)) { + LOGGER.info("Executing the action"); + action.writeFile(writer); + LOGGER.info("Closing the file"); + } } - } } ``` -To utilize the file writer the following code is needed. +The following code demonstrates how `SimpleFileWriter` is used. `Scanner` is used to print the file +contents after the writing finishes. ```java - FileWriterAction writeHello = writer -> { - writer.write("Hello"); - writer.append(" "); - writer.append("there!"); - }; - new SimpleFileWriter("testfile.txt", writeHello); +FileWriterAction writeHello = writer -> { + writer.write("Gandalf was here"); +}; +new SimpleFileWriter("testfile.txt", writeHello); + +var scanner = new Scanner(new File("testfile.txt")); +while (scanner.hasNextLine()) { +LOGGER.info(scanner.nextLine()); +} +``` + +Here's the console output. + +``` +21:18:07.185 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Opening the file +21:18:07.188 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Executing the action +21:18:07.189 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Closing the file +21:18:07.199 [main] INFO com.iluwatar.execute.around.App - Gandalf was here ``` ## Class diagram @@ -74,8 +89,7 @@ To utilize the file writer the following code is needed. Use the Execute Around idiom when -* You use an API that requires methods to be called in pairs such as open/close or -allocate/deallocate. +* An API requires methods to be called in pairs such as open/close or allocate/deallocate. ## Credits diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/App.java b/execute-around/src/main/java/com/iluwatar/execute/around/App.java index f3de8d450..88eb11591 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/App.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/App.java @@ -23,10 +23,14 @@ package com.iluwatar.execute.around; +import java.io.File; import java.io.IOException; +import java.util.Scanner; + +import lombok.extern.slf4j.Slf4j; /** - * The Execute Around idiom specifies some code to be executed before and after a method. Typically + * The Execute Around idiom specifies executable code before and after a method. Typically * the idiom is used when the API has methods to be executed in pairs, such as resource * allocation/deallocation or lock acquisition/release. * @@ -34,6 +38,7 @@ import java.io.IOException; * the user. The user specifies only what to do with the file by providing the {@link * FileWriterAction} implementation. */ +@Slf4j public class App { /** @@ -41,11 +46,16 @@ public class App { */ public static void main(String[] args) throws IOException { + // create the file writer and execute the custom action FileWriterAction writeHello = writer -> { - writer.write("Hello"); - writer.append(" "); - writer.append("there!"); + writer.write("Gandalf was here"); }; new SimpleFileWriter("testfile.txt", writeHello); + + // print the file contents + var scanner = new Scanner(new File("testfile.txt")); + while (scanner.hasNextLine()) { + LOGGER.info(scanner.nextLine()); + } } } diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java index f84b7427d..0a427b81a 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java @@ -26,18 +26,24 @@ package com.iluwatar.execute.around; import java.io.FileWriter; import java.io.IOException; +import lombok.extern.slf4j.Slf4j; + /** * SimpleFileWriter handles opening and closing file for the user. The user only has to specify what * to do with the file resource through {@link FileWriterAction} parameter. */ +@Slf4j public class SimpleFileWriter { /** * Constructor. */ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { + LOGGER.info("Opening the file"); try (var writer = new FileWriter(filename)) { + LOGGER.info("Executing the action"); action.writeFile(writer); + LOGGER.info("Closing the file"); } } } diff --git a/factory-kit/README.md b/factory-kit/README.md index 346012c07..861ddb862 100644 --- a/factory-kit/README.md +++ b/factory-kit/README.md @@ -10,19 +10,115 @@ tags: --- ## Intent + Define a factory of immutable content with separated builder and factory interfaces. +## Explanation + +Real-world example + +> Imagine a magical weapon factory that can create any type of weapon wished for. When the factory +> is unboxed, the master recites the weapon types needed to prepare it. After that, any of those +> weapon types can be summoned in an instant. + +In plain words + +> Factory kit is a configurable object builder. + +**Programmatic Example** + +Let's first define the simple `Weapon` hierarchy. + +```java +public interface Weapon { +} + +public enum WeaponType { + SWORD, + AXE, + BOW, + SPEAR +} + +public class Sword implements Weapon { + @Override + public String toString() { + return "Sword"; + } +} + +// Axe, Bow, and Spear are defined similarly +``` + +Next, we define a functional interface that allows adding a builder with a name to the factory. + +```java +public interface Builder { + void add(WeaponType name, Supplier supplier); +} +``` + +The meat of the example is the `WeaponFactory` interface that effectively implements the factory +kit pattern. The method `#factory` is used to configure the factory with the classes it needs to +be able to construct. The method `#create` is then used to create object instances. + +```java +public interface WeaponFactory { + + static WeaponFactory factory(Consumer consumer) { + var map = new HashMap>(); + consumer.accept(map::put); + return name -> map.get(name).get(); + } + + Weapon create(WeaponType name); +} +``` + +Now, we can show how `WeaponFactory` can be used. + +```java +var factory = WeaponFactory.factory(builder -> { + builder.add(WeaponType.SWORD, Sword::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.BOW, Bow::new); +}); +var list = new ArrayList(); +list.add(factory.create(WeaponType.AXE)); +list.add(factory.create(WeaponType.SPEAR)); +list.add(factory.create(WeaponType.SWORD)); +list.add(factory.create(WeaponType.BOW)); +list.stream().forEach(weapon -> LOGGER.info("{}", weapon.toString())); +``` + +Here is the console output when the example is run. + +``` +21:15:49.709 [main] INFO com.iluwatar.factorykit.App - Axe +21:15:49.713 [main] INFO com.iluwatar.factorykit.App - Spear +21:15:49.713 [main] INFO com.iluwatar.factorykit.App - Sword +21:15:49.713 [main] INFO com.iluwatar.factorykit.App - Bow +``` + ## Class diagram + ![alt text](./etc/factory-kit.png "Factory Kit") ## Applicability + Use the Factory Kit pattern when -* a class can't anticipate the class of objects it must create -* you just want a new instance of a custom builder instead of the global one -* you explicitly want to define types of objects, that factory can build -* you want a separated builder and creator interface +* The factory class can't anticipate the types of objects it must create +* A new instance of a custom builder is needed instead of a global one +* The types of objects that the factory can build need to be defined outside the class +* The builder and creator interfaces need to be separated + +## Related patterns + +* [Builder](https://java-design-patterns.com/patterns/builder/) +* [Factory](https://java-design-patterns.com/patterns/factory/) ## Credits -* [Design Pattern Reloaded by Remi Forax: ](https://www.youtube.com/watch?v=-k2X7guaArU) +* [Design Pattern Reloaded by Remi Forax](https://www.youtube.com/watch?v=-k2X7guaArU) diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java index e5f0b4285..7c636609a 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java @@ -23,14 +23,16 @@ package com.iluwatar.factorykit; +import java.util.ArrayList; + import lombok.extern.slf4j.Slf4j; /** - * Factory-kit is a creational pattern which defines a factory of immutable content with separated + * Factory kit is a creational pattern that defines a factory of immutable content with separated * builder and factory interfaces to deal with the problem of creating one of the objects specified - * directly in the factory-kit instance. + * directly in the factory kit instance. * - *

In the given example {@link WeaponFactory} represents the factory-kit, that contains four + *

In the given example {@link WeaponFactory} represents the factory kit, that contains four * {@link Builder}s for creating new objects of the classes implementing {@link Weapon} interface. * *

Each of them can be called with {@link WeaponFactory#create(WeaponType)} method, with @@ -52,7 +54,11 @@ public class App { builder.add(WeaponType.SPEAR, Spear::new); builder.add(WeaponType.BOW, Bow::new); }); - var axe = factory.create(WeaponType.AXE); - LOGGER.info(axe.toString()); + var list = new ArrayList(); + list.add(factory.create(WeaponType.AXE)); + list.add(factory.create(WeaponType.SPEAR)); + list.add(factory.create(WeaponType.SWORD)); + list.add(factory.create(WeaponType.BOW)); + list.stream().forEach(weapon -> LOGGER.info("{}", weapon.toString())); } } diff --git a/metadata-mapping/README.md b/metadata-mapping/README.md new file mode 100644 index 000000000..5dcd932a7 --- /dev/null +++ b/metadata-mapping/README.md @@ -0,0 +1,182 @@ +--- +layout: pattern +title: Metadata Mapping +folder: metadata-mapping +permalink: /patterns/metadata-mapping/ +categories: Architectural +language: en +tags: + - Data access +--- + +## Intent + +Holds details of object-relational mapping in the metadata. + +## Explanation + +Real world example + +> Hibernate ORM Tool uses Metadata Mapping Pattern to specify the mapping between classes and tables either using XML or annotations in code. + +In plain words + +> Metadata Mapping specifies the mapping between classes and tables so that we could treat a table of any database like a Java class. + +Wikipedia says + +> Create a "virtual [object database](https://en.wikipedia.org/wiki/Object_database)" that can be used from within the programming language. + +**Programmatic Example** + +We give an example about visiting the information of `USER` table in `h2` database. Firstly, we create `USER` table with `h2`: + +```java +@Slf4j +public class DatabaseUtil { + private static final String DB_URL = "jdbc:h2:mem:metamapping"; + private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user`;" + + "CREATE TABLE `user` (\n" + + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + + " `username` varchar(255) NOT NULL,\n" + + " `password` varchar(255) NOT NULL,\n" + + " PRIMARY KEY (`id`)\n" + + ");"; + + /** + * Create database. + */ + static { + LOGGER.info("create h2 database"); + var source = new JdbcDataSource(); + source.setURL(DB_URL); + try (var statement = source.getConnection().createStatement()) { + statement.execute(CREATE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.error("unable to create h2 data source", e); + } + } +} +``` + +Correspondingly, here's the basic `User` entity. + +```java +@Setter +@Getter +@ToString +public class User { + private Integer id; + private String username; + private String password; + + /** + * Get a user. + * @param username user name + * @param password user password + */ + public User(String username, String password) { + this.username = username; + this.password = password; + } +} +``` + +Then we write a `xml` file to show the mapping between the table and the object: + +```xml + + + + + + + + + + + + +``` + +We use `Hibernate` to resolve the mapping and connect to our database, here's its configuration: + +```xml + + + + + + jdbc:h2:mem:metamapping + org.h2.Driver + + 1 + + org.hibernate.dialect.H2Dialect + + false + + create-drop + + + +``` + +Then we can get access to the table just like an object with `Hibernate`, here's some CRUDs: + +```java +@Slf4j +public class UserService { + private static final SessionFactory factory = HibernateUtil.getSessionFactory(); + + /** + * List all users. + * @return list of users + */ + public List listUser() { + LOGGER.info("list all users."); + List users = new ArrayList<>(); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + List userIter = session.createQuery("FROM User").list(); + for (var iterator = userIter.iterator(); iterator.hasNext();) { + users.add(iterator.next()); + } + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to get users", e); + } + return users; + } + + // other CRUDs -> + ... + + public void close() { + HibernateUtil.shutdown(); + } +} +``` + +## Class diagram + +![metamapping](etc/metamapping.png) + +## Applicability + +Use the Metadata Mapping when: + +- you want reduce the amount of work needed to handle database mapping. + +## Known uses + +[Hibernate](https://hibernate.org/), [EclipseLink](https://www.eclipse.org/eclipselink/), [MyBatis](https://blog.mybatis.org/)...... + +## Credits + +- [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) + diff --git a/metadata-mapping/etc/metamapping.png b/metadata-mapping/etc/metamapping.png new file mode 100644 index 000000000..b1e89f8af Binary files /dev/null and b/metadata-mapping/etc/metamapping.png differ diff --git a/metadata-mapping/etc/metamapping.puml b/metadata-mapping/etc/metamapping.puml new file mode 100644 index 000000000..daa8c37de --- /dev/null +++ b/metadata-mapping/etc/metamapping.puml @@ -0,0 +1,32 @@ +@startuml +interface com.iluwatar.metamapping.service.UserService { ++ List listUser() ++ int createUser(User) ++ void updateUser(Integer,User) ++ void deleteUser(Integer) ++ User getUser(Integer) ++ void close() +} +class com.iluwatar.metamapping.utils.DatabaseUtil { ++ {static} void createDataSource() +} +class com.iluwatar.metamapping.model.User { +- Integer id +- String username +- String password ++ User(String username, String password) +} +class com.iluwatar.metamapping.utils.HibernateUtil { ++ {static} SessionFactory getSessionFactory() ++ {static} void shutdown() +} +class com.iluwatar.metamapping.App { ++ {static} void main(String[]) ++ {static} List generateSampleUsers() +} + +com.iluwatar.metamapping.service.UserService <.. com.iluwatar.metamapping.App +com.iluwatar.metamapping.model.User <.. com.iluwatar.metamapping.service.UserService +com.iluwatar.metamapping.utils.HibernateUtil <.. com.iluwatar.metamapping.service.UserService +com.iluwatar.metamapping.utils.DatabaseUtil <-- com.iluwatar.metamapping.utils.HibernateUtil +@enduml \ No newline at end of file diff --git a/metadata-mapping/pom.xml b/metadata-mapping/pom.xml new file mode 100644 index 000000000..43c9621df --- /dev/null +++ b/metadata-mapping/pom.xml @@ -0,0 +1,87 @@ + + + + + java-design-patterns + com.iluwatar + 1.26.0-SNAPSHOT + + 4.0.0 + + metadata-mapping + + + org.junit.jupiter + junit-jupiter-engine + test + + + com.h2database + h2 + + + org.hibernate + hibernate-core + + + com.h2database + h2 + + + javax.xml.bind + jaxb-api + + + com.sun.xml.bind + jaxb-impl + + + com.sun.istack + istack-commons-runtime + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.metamapping.App + + + + + + + + + \ No newline at end of file diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java new file mode 100644 index 000000000..ff0377590 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java @@ -0,0 +1,72 @@ +package com.iluwatar.metamapping; + +import com.iluwatar.metamapping.model.User; +import com.iluwatar.metamapping.service.UserService; +import com.iluwatar.metamapping.utils.DatabaseUtil; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.hibernate.service.ServiceRegistry; + +/** + * Metadata Mapping specifies the mapping + * between classes and tables so that + * we could treat a table of any database like a Java class. + * + *

With hibernate, we achieve list/create/update/delete/get operations: + * 1)Create the H2 Database in {@link DatabaseUtil}. + * 2)Hibernate resolve hibernate.cfg.xml and generate service like save/list/get/delete. + * For learning metadata mapping pattern, we go deeper into Hibernate here: + * a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml + * b)create session factory to generate session interacting with database + * c)generate session with factory pattern + * d)create query object or use basic api with session, + * hibernate will convert all query to database query according to metadata + * 3)We encapsulate hibernate service in {@link UserService} for our use. + * @see org.hibernate.cfg.Configuration#configure(String) + * @see org.hibernate.cfg.Configuration#buildSessionFactory(ServiceRegistry) + * @see org.hibernate.internal.SessionFactoryImpl#openSession() + */ +@Slf4j +public class App { + /** + * Program entry point. + * + * @param args command line args. + * @throws Exception if any error occurs. + */ + public static void main(String[] args) throws Exception { + // get service + var userService = new UserService(); + // use create service to add users + for (var user: generateSampleUsers()) { + var id = userService.createUser(user); + LOGGER.info("Add user" + user + "at" + id + "."); + } + // use list service to get users + var users = userService.listUser(); + LOGGER.info(String.valueOf(users)); + // use get service to get a user + var user = userService.getUser(1); + LOGGER.info(String.valueOf(user)); + // change password of user 1 + user.setPassword("new123"); + // use update service to update user 1 + userService.updateUser(1, user); + // use delete service to delete user 2 + userService.deleteUser(2); + // close service + userService.close(); + } + + /** + * Generate users. + * + * @return list of users. + */ + public static List generateSampleUsers() { + final var user1 = new User("ZhangSan", "zhs123"); + final var user2 = new User("LiSi", "ls123"); + final var user3 = new User("WangWu", "ww123"); + return List.of(user1, user2, user3); + } +} \ No newline at end of file diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java new file mode 100644 index 000000000..0bf2575b1 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java @@ -0,0 +1,29 @@ +package com.iluwatar.metamapping.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * User Entity. + */ +@Setter +@Getter +@ToString +public class User { + private Integer id; + private String username; + private String password; + + public User() {} + + /** + * Get a user. + * @param username user name + * @param password user password + */ + public User(String username, String password) { + this.username = username; + this.password = password; + } +} \ No newline at end of file diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java new file mode 100644 index 000000000..1f85be0d5 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java @@ -0,0 +1,114 @@ +package com.iluwatar.metamapping.service; + +import com.iluwatar.metamapping.model.User; +import com.iluwatar.metamapping.utils.HibernateUtil; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.hibernate.HibernateException; +import org.hibernate.SessionFactory; + +/** + * Service layer for user. + */ +@Slf4j +public class UserService { + private static final SessionFactory factory = HibernateUtil.getSessionFactory(); + + /** + * List all users. + * @return list of users + */ + public List listUser() { + LOGGER.info("list all users."); + List users = new ArrayList<>(); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + List userIter = session.createQuery("FROM User").list(); + for (var iterator = userIter.iterator(); iterator.hasNext();) { + users.add(iterator.next()); + } + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to get users", e); + } + return users; + } + + /** + * Add a user. + * @param user user entity + * @return user id + */ + public int createUser(User user) { + LOGGER.info("create user: " + user.getUsername()); + var id = -1; + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + id = (Integer) session.save(user); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to create user", e); + } + LOGGER.info("create user " + user.getUsername() + " at " + id); + return id; + } + + /** + * Update user. + * @param id user id + * @param user new user entity + */ + public void updateUser(Integer id, User user) { + LOGGER.info("update user at " + id); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + user.setId(id); + session.update(user); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to update user", e); + } + } + + /** + * Delete user. + * @param id user id + */ + public void deleteUser(Integer id) { + LOGGER.info("delete user at: " + id); + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + var user = session.get(User.class, id); + session.delete(user); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to delete user", e); + } + } + + /** + * Get user. + * @param id user id + * @return deleted user + */ + public User getUser(Integer id) { + LOGGER.info("get user at: " + id); + User user = null; + try (var session = factory.openSession()) { + var tx = session.beginTransaction(); + user = session.get(User.class, id); + tx.commit(); + } catch (HibernateException e) { + LOGGER.debug("fail to get user", e); + } + return user; + } + + /** + * Close hibernate. + */ + public void close() { + HibernateUtil.shutdown(); + } +} \ No newline at end of file diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java new file mode 100644 index 000000000..b6d0200e8 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java @@ -0,0 +1,39 @@ +package com.iluwatar.metamapping.utils; + +import java.sql.SQLException; +import lombok.extern.slf4j.Slf4j; +import org.h2.jdbcx.JdbcDataSource; + +/** + * Create h2 database. + */ +@Slf4j +public class DatabaseUtil { + private static final String DB_URL = "jdbc:h2:mem:metamapping"; + private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user`;" + + "CREATE TABLE `user` (\n" + + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + + " `username` varchar(255) NOT NULL,\n" + + " `password` varchar(255) NOT NULL,\n" + + " PRIMARY KEY (`id`)\n" + + ");"; + + /** + * Hide constructor. + */ + private DatabaseUtil() {} + + /** + * Create database. + */ + static { + LOGGER.info("create h2 database"); + var source = new JdbcDataSource(); + source.setURL(DB_URL); + try (var statement = source.getConnection().createStatement()) { + statement.execute(CREATE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.error("unable to create h2 data source", e); + } + } +} \ No newline at end of file diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java new file mode 100644 index 000000000..ba405eb74 --- /dev/null +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java @@ -0,0 +1,45 @@ +package com.iluwatar.metamapping.utils; + +import lombok.extern.slf4j.Slf4j; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +/** + * Manage hibernate. + */ +@Slf4j +public class HibernateUtil { + + private static final SessionFactory sessionFactory = buildSessionFactory(); + + /** + * Hide constructor. + */ + private HibernateUtil() {} + + /** + * Build session factory. + * @return session factory + */ + private static SessionFactory buildSessionFactory() { + // Create the SessionFactory from hibernate.cfg.xml + return new Configuration().configure().buildSessionFactory(); + } + + /** + * Get session factory. + * @return session factory + */ + public static SessionFactory getSessionFactory() { + return sessionFactory; + } + + /** + * Close session factory. + */ + public static void shutdown() { + // Close caches and connection pools + getSessionFactory().close(); + } + +} \ No newline at end of file diff --git a/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml b/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml new file mode 100644 index 000000000..cd63c552d --- /dev/null +++ b/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/metadata-mapping/src/main/resources/hibernate.cfg.xml b/metadata-mapping/src/main/resources/hibernate.cfg.xml new file mode 100644 index 000000000..18dc198e8 --- /dev/null +++ b/metadata-mapping/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,20 @@ + + + + + + jdbc:h2:mem:metamapping + org.h2.Driver + + 1 + + org.hibernate.dialect.H2Dialect + + false + + create-drop + + + \ No newline at end of file diff --git a/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java b/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java new file mode 100644 index 000000000..127ddad0f --- /dev/null +++ b/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java @@ -0,0 +1,20 @@ +package com.iluwatar.metamapping; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +/** + * Tests that metadata mapping example runs without errors. + */ +class AppTest { + /** + * Issue: Add at least one assertion to this test case. + * + * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} + * throws an exception. + */ + @Test + void shouldExecuteMetaMappingWithoutException() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} diff --git a/pom.xml b/pom.xml index 5c3634b95..e58146c72 100644 --- a/pom.xml +++ b/pom.xml @@ -75,6 +75,7 @@ 3.0 1.4.8 2.7 + 4.0.1 https://sonarcloud.io iluwatar @@ -227,6 +228,8 @@ lockable-object fanout-fanin domain-model + composite-view + metadata-mapping @@ -377,6 +380,11 @@ commons-io ${commons-io.version} + + com.sun.istack + istack-commons-runtime + ${istack-commons-runtime.version} + diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java index 2db01bf88..afcaf0015 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -96,9 +96,11 @@ public class NioReactor { * @throws IOException if any I/O error occurs. */ public void stop() throws InterruptedException, IOException { - reactorMain.shutdownNow(); + reactorMain.shutdown(); selector.wakeup(); - reactorMain.awaitTermination(4, TimeUnit.SECONDS); + if (!reactorMain.awaitTermination(4, TimeUnit.SECONDS)) { + reactorMain.shutdownNow(); + } selector.close(); LOGGER.info("Reactor stopped"); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java b/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java index d8af72c96..7d4f610d1 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java @@ -64,6 +64,8 @@ public class ThreadPoolDispatcher implements Dispatcher { @Override public void stop() throws InterruptedException { executorService.shutdown(); - executorService.awaitTermination(4, TimeUnit.SECONDS); + if (executorService.awaitTermination(4, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } } } diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java index 5faef509d..897466a99 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java @@ -34,11 +34,11 @@ import java.util.HashMap; public class SpatialPartitionBubbles extends SpatialPartitionGeneric { private final HashMap bubbles; - private final QuadTree quadTree; + private final QuadTree bubblesQuadTree; - SpatialPartitionBubbles(HashMap bubbles, QuadTree quadTree) { + SpatialPartitionBubbles(HashMap bubbles, QuadTree bubblesQuadTree) { this.bubbles = bubbles; - this.quadTree = quadTree; + this.bubblesQuadTree = bubblesQuadTree; } void handleCollisionsUsingQt(Bubble b) { @@ -46,7 +46,7 @@ public class SpatialPartitionBubbles extends SpatialPartitionGeneric { // centre of bubble and length = radius of bubble var rect = new Rect(b.coordinateX, b.coordinateY, 2D * b.radius, 2D * b.radius); var quadTreeQueryResult = new ArrayList(); - this.quadTree.query(rect, quadTreeQueryResult); + this.bubblesQuadTree.query(rect, quadTreeQueryResult); //handling these collisions b.handleCollision(quadTreeQueryResult, this.bubbles); } diff --git a/thread-pool/README.md b/thread-pool/README.md index d6cb11c1f..248c3a5d4 100644 --- a/thread-pool/README.md +++ b/thread-pool/README.md @@ -18,11 +18,11 @@ threads and eliminating the latency of creating new threads. ## Explanation -Real world example +Real-world example > We have a large number of relatively short tasks at hand. We need to peel huge amounts of potatoes -> and serve mighty amount of coffee cups. Creating a new thread for each task would be a waste so we -> establish a thread pool. +> and serve a mighty amount of coffee cups. Creating a new thread for each task would be a waste so +> we establish a thread pool. In plain words @@ -99,7 +99,7 @@ public class PotatoPeelingTask extends Task { } ``` -Next we present a runnable `Worker` class that the thread pool will utilize to handle all the potato +Next, we present a runnable `Worker` class that the thread pool will utilize to handle all the potato peeling and coffee making. ```java diff --git a/throttling/README.md b/throttling/README.md index 66c02a1c0..333b714f1 100644 --- a/throttling/README.md +++ b/throttling/README.md @@ -16,10 +16,12 @@ Ensure that a given client is not able to access service resources more than the ## Explanation -Real world example +Real-world example -> A large multinational corporation offers API to its customers. The API is rate-limited and each -> customer can only make certain amount of calls per second. +> A young human and an old dwarf walk into a bar. They start ordering beers from the bartender. +> The bartender immediately sees that the young human shouldn't consume too many drinks too fast +> and refuses to serve if enough time has not passed. For the old dwarf, the serving rate can +> be higher. In plain words @@ -33,30 +35,25 @@ In plain words **Programmatic Example** -Tenant class presents the clients of the API. CallsCount tracks the number of API calls per tenant. +`BarCustomer` class presents the clients of the `Bartender` API. `CallsCount` tracks the number of +calls per `BarCustomer`. ```java -public class Tenant { +public class BarCustomer { - private final String name; - private final int allowedCallsPerSecond; + @Getter + private final String name; + @Getter + private final int allowedCallsPerSecond; - public Tenant(String name, int allowedCallsPerSecond, CallsCount callsCount) { - if (allowedCallsPerSecond < 0) { - throw new InvalidParameterException("Number of calls less than 0 not allowed"); + public BarCustomer(String name, int allowedCallsPerSecond, CallsCount callsCount) { + if (allowedCallsPerSecond < 0) { + throw new InvalidParameterException("Number of calls less than 0 not allowed"); + } + this.name = name; + this.allowedCallsPerSecond = allowedCallsPerSecond; + callsCount.addTenant(name); } - this.name = name; - this.allowedCallsPerSecond = allowedCallsPerSecond; - callsCount.addTenant(name); - } - - public String getName() { - return name; - } - - public int getAllowedCallsPerSecond() { - return allowedCallsPerSecond; - } } @Slf4j @@ -76,14 +73,14 @@ public final class CallsCount { } public void reset() { - LOGGER.debug("Resetting the map."); tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0)); + LOGGER.info("reset counters"); } } ``` -Next we introduce the service that the tenants are calling. To track the call count we use the -throttler timer. +Next, the service that the tenants are calling is introduced. To track the call count, a throttler +timer is used. ```java public interface Throttler { @@ -111,71 +108,103 @@ public class ThrottleTimerImpl implements Throttler { }, 0, throttlePeriod); } } +``` -class B2BService { +`Bartender` offers the `orderDrink` service to the `BarCustomer`s. The customers probably don't +know that the beer serving rate is limited by their appearances. - private static final Logger LOGGER = LoggerFactory.getLogger(B2BService.class); - private final CallsCount callsCount; +```java +class Bartender { - public B2BService(Throttler timer, CallsCount callsCount) { - this.callsCount = callsCount; - timer.start(); - } + private static final Logger LOGGER = LoggerFactory.getLogger(Bartender.class); + private final CallsCount callsCount; - public int dummyCustomerApi(Tenant tenant) { - var tenantName = tenant.getName(); - var count = callsCount.getCount(tenantName); - LOGGER.debug("Counter for {} : {} ", tenant.getName(), count); - if (count >= tenant.getAllowedCallsPerSecond()) { - LOGGER.error("API access per second limit reached for: {}", tenantName); - return -1; + public Bartender(Throttler timer, CallsCount callsCount) { + this.callsCount = callsCount; + timer.start(); } - callsCount.incrementCount(tenantName); - return getRandomCustomerId(); - } - private int getRandomCustomerId() { - return ThreadLocalRandom.current().nextInt(1, 10000); - } + public int orderDrink(BarCustomer barCustomer) { + var tenantName = barCustomer.getName(); + var count = callsCount.getCount(tenantName); + if (count >= barCustomer.getAllowedCallsPerSecond()) { + LOGGER.error("I'm sorry {}, you've had enough for today!", tenantName); + return -1; + } + callsCount.incrementCount(tenantName); + LOGGER.debug("Serving beer to {} : [{} consumed] ", barCustomer.getName(), count+1); + return getRandomCustomerId(); + } + + private int getRandomCustomerId() { + return ThreadLocalRandom.current().nextInt(1, 10000); + } } ``` -Now we are ready to see the full example in action. Tenant Adidas is rate-limited to 5 calls per -second and Nike to 6. +Now it is possible to see the full example in action. `BarCustomer` young human is rate-limited to 2 +calls per second and the old dwarf to 4. ```java - public static void main(String[] args) { +public static void main(String[] args) { var callsCount = new CallsCount(); - var adidas = new Tenant("Adidas", 5, callsCount); - var nike = new Tenant("Nike", 6, callsCount); + var human = new BarCustomer("young human", 2, callsCount); + var dwarf = new BarCustomer("dwarf soldier", 4, callsCount); var executorService = Executors.newFixedThreadPool(2); - executorService.execute(() -> makeServiceCalls(adidas, callsCount)); - executorService.execute(() -> makeServiceCalls(nike, callsCount)); - executorService.shutdown(); - - try { - executorService.awaitTermination(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - LOGGER.error("Executor Service terminated: {}", e.getMessage()); - } - } - private static void makeServiceCalls(Tenant tenant, CallsCount callsCount) { - var timer = new ThrottleTimerImpl(10, callsCount); - var service = new B2BService(timer, callsCount); + executorService.execute(() -> makeServiceCalls(human, callsCount)); + executorService.execute(() -> makeServiceCalls(dwarf, callsCount)); + + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Executor service terminated: {}", e.getMessage()); + } +} + +private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) { + var timer = new ThrottleTimerImpl(1000, callsCount); + var service = new Bartender(timer, callsCount); // Sleep is introduced to keep the output in check and easy to view and analyze the results. - IntStream.range(0, 20).forEach(i -> { - service.dummyCustomerApi(tenant); - try { - Thread.sleep(1); - } catch (InterruptedException e) { - LOGGER.error("Thread interrupted: {}", e.getMessage()); - } + IntStream.range(0, 50).forEach(i -> { + service.orderDrink(barCustomer); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + LOGGER.error("Thread interrupted: {}", e.getMessage()); + } }); - } +} ``` +An excerpt from the example's console output: + +``` +18:46:36.218 [Timer-0] INFO com.iluwatar.throttling.CallsCount - reset counters +18:46:36.218 [Timer-1] INFO com.iluwatar.throttling.CallsCount - reset counters +18:46:36.242 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [1 consumed] +18:46:36.242 [pool-1-thread-1] DEBUG com.iluwatar.throttling.Bartender - Serving beer to young human : [1 consumed] +18:46:36.342 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [2 consumed] +18:46:36.342 [pool-1-thread-1] DEBUG com.iluwatar.throttling.Bartender - Serving beer to young human : [2 consumed] +18:46:36.443 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.443 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [3 consumed] +18:46:36.544 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.544 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [4 consumed] +18:46:36.645 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.645 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.745 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.745 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.846 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:36.846 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.947 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:36.947 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:37.048 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +18:46:37.048 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:37.148 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today! +18:46:37.148 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today! +``` ## Class diagram @@ -185,7 +214,7 @@ second and Nike to 6. The Throttling pattern should be used: -* When a service access needs to be restricted to not have high impacts on the performance of the service. +* When service access needs to be restricted not to have high impact on the performance of the service. * When multiple clients are consuming the same service resources and restriction has to be made according to the usage per client. ## Credits diff --git a/throttling/src/main/java/com/iluwatar/throttling/App.java b/throttling/src/main/java/com/iluwatar/throttling/App.java index ab8aa8601..1db6ecf93 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/App.java +++ b/throttling/src/main/java/com/iluwatar/throttling/App.java @@ -34,11 +34,11 @@ import lombok.extern.slf4j.Slf4j; * complete service by users or a particular tenant. This can allow systems to continue to function * and meet service level agreements, even when an increase in demand places load on resources. *

- * In this example we have ({@link App}) as the initiating point of the service. This is a time + * In this example there is a {@link Bartender} serving beer to {@link BarCustomer}s. This is a time * based throttling, i.e. only a certain number of calls are allowed per second. *

- * ({@link Tenant}) is the Tenant POJO class with which many tenants can be created ({@link - * B2BService}) is the service which is consumed by the tenants and is throttled. + * ({@link BarCustomer}) is the service tenant class having a name and the number of calls allowed. + * ({@link Bartender}) is the service which is consumed by the tenants and is throttled. */ @Slf4j public class App { @@ -50,33 +50,35 @@ public class App { */ public static void main(String[] args) { var callsCount = new CallsCount(); - var adidas = new Tenant("Adidas", 5, callsCount); - var nike = new Tenant("Nike", 6, callsCount); + var human = new BarCustomer("young human", 2, callsCount); + var dwarf = new BarCustomer("dwarf soldier", 4, callsCount); var executorService = Executors.newFixedThreadPool(2); - executorService.execute(() -> makeServiceCalls(adidas, callsCount)); - executorService.execute(() -> makeServiceCalls(nike, callsCount)); + executorService.execute(() -> makeServiceCalls(human, callsCount)); + executorService.execute(() -> makeServiceCalls(dwarf, callsCount)); executorService.shutdown(); try { - executorService.awaitTermination(10, TimeUnit.SECONDS); + if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } } catch (InterruptedException e) { - LOGGER.error("Executor Service terminated: {}", e.getMessage()); + executorService.shutdownNow(); } } /** - * Make calls to the B2BService dummy API. + * Make calls to the bartender. */ - private static void makeServiceCalls(Tenant tenant, CallsCount callsCount) { - var timer = new ThrottleTimerImpl(10, callsCount); - var service = new B2BService(timer, callsCount); + private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) { + var timer = new ThrottleTimerImpl(1000, callsCount); + var service = new Bartender(timer, callsCount); // Sleep is introduced to keep the output in check and easy to view and analyze the results. - IntStream.range(0, 20).forEach(i -> { - service.dummyCustomerApi(tenant); + IntStream.range(0, 50).forEach(i -> { + service.orderDrink(barCustomer); try { - Thread.sleep(1); + Thread.sleep(100); } catch (InterruptedException e) { LOGGER.error("Thread interrupted: {}", e.getMessage()); } diff --git a/throttling/src/main/java/com/iluwatar/throttling/Tenant.java b/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java similarity index 81% rename from throttling/src/main/java/com/iluwatar/throttling/Tenant.java rename to throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java index 60a08704f..b46670861 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/Tenant.java +++ b/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java @@ -25,22 +25,26 @@ package com.iluwatar.throttling; import java.security.InvalidParameterException; -/** - * A Pojo class to create a basic Tenant with the allowed calls per second. - */ -public class Tenant { +import lombok.Getter; +/** + * BarCustomer is a tenant with a name and a number of allowed calls per second. + */ +public class BarCustomer { + + @Getter private final String name; + @Getter private final int allowedCallsPerSecond; /** * Constructor. * - * @param name Name of the tenant - * @param allowedCallsPerSecond The number of calls allowed for a particular tenant. + * @param name Name of the BarCustomer + * @param allowedCallsPerSecond The number of calls allowed for this particular tenant. * @throws InvalidParameterException If number of calls is less than 0, throws exception. */ - public Tenant(String name, int allowedCallsPerSecond, CallsCount callsCount) { + public BarCustomer(String name, int allowedCallsPerSecond, CallsCount callsCount) { if (allowedCallsPerSecond < 0) { throw new InvalidParameterException("Number of calls less than 0 not allowed"); } @@ -48,12 +52,4 @@ public class Tenant { this.allowedCallsPerSecond = allowedCallsPerSecond; callsCount.addTenant(name); } - - public String getName() { - return name; - } - - public int getAllowedCallsPerSecond() { - return allowedCallsPerSecond; - } } diff --git a/throttling/src/main/java/com/iluwatar/throttling/B2BService.java b/throttling/src/main/java/com/iluwatar/throttling/Bartender.java similarity index 75% rename from throttling/src/main/java/com/iluwatar/throttling/B2BService.java rename to throttling/src/main/java/com/iluwatar/throttling/Bartender.java index 70657afd8..e81d770d7 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/B2BService.java +++ b/throttling/src/main/java/com/iluwatar/throttling/Bartender.java @@ -29,33 +29,32 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A service which accepts a tenant and throttles the resource based on the time given to the - * tenant. + * Bartender is a service which accepts a BarCustomer (tenant) and throttles + * the resource based on the time given to the tenant. */ -class B2BService { +class Bartender { - private static final Logger LOGGER = LoggerFactory.getLogger(B2BService.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Bartender.class); private final CallsCount callsCount; - public B2BService(Throttler timer, CallsCount callsCount) { + public Bartender(Throttler timer, CallsCount callsCount) { this.callsCount = callsCount; timer.start(); } /** - * Calls dummy customer api. - * + * Orders a drink from the bartender. * @return customer id which is randomly generated */ - public int dummyCustomerApi(Tenant tenant) { - var tenantName = tenant.getName(); + public int orderDrink(BarCustomer barCustomer) { + var tenantName = barCustomer.getName(); var count = callsCount.getCount(tenantName); - LOGGER.debug("Counter for {} : {} ", tenant.getName(), count); - if (count >= tenant.getAllowedCallsPerSecond()) { - LOGGER.error("API access per second limit reached for: {}", tenantName); + if (count >= barCustomer.getAllowedCallsPerSecond()) { + LOGGER.error("I'm sorry {}, you've had enough for today!", tenantName); return -1; } callsCount.incrementCount(tenantName); + LOGGER.debug("Serving beer to {} : [{} consumed] ", barCustomer.getName(), count + 1); return getRandomCustomerId(); } diff --git a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java index 88a80d481..4196e10dd 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java +++ b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java @@ -69,7 +69,7 @@ public final class CallsCount { * Resets the count of all the tenants in the map. */ public void reset() { - LOGGER.debug("Resetting the map."); tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0)); + LOGGER.info("reset counters"); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java b/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java similarity index 94% rename from throttling/src/test/java/com/iluwatar/throttling/TenantTest.java rename to throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java index 2ea33ec3d..9818fdf6b 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java @@ -23,20 +23,21 @@ package com.iluwatar.throttling; -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; import java.security.InvalidParameterException; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * TenantTest to test the creation of Tenant with valid parameters. */ -public class TenantTest { +public class BarCustomerTest { @Test void constructorTest() { assertThrows(InvalidParameterException.class, () -> { - new Tenant("FailTenant", -1, new CallsCount()); + new BarCustomer("sirBrave", -1, new CallsCount()); }); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java b/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java similarity index 89% rename from throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java rename to throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java index 93cf3efaa..b2d80fbd4 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java @@ -32,19 +32,18 @@ import org.junit.jupiter.api.Test; /** * B2BServiceTest class to test the B2BService */ -public class B2BServiceTest { +public class BartenderTest { private final CallsCount callsCount = new CallsCount(); @Test void dummyCustomerApiTest() { - var tenant = new Tenant("testTenant", 2, callsCount); + var tenant = new BarCustomer("pirate", 2, callsCount); // In order to assure that throttling limits will not be reset, we use an empty throttling implementation - var timer = (Throttler) () -> { - }; - var service = new B2BService(timer, callsCount); + var timer = (Throttler) () -> {}; + var service = new Bartender(timer, callsCount); - IntStream.range(0, 5).mapToObj(i -> tenant).forEach(service::dummyCustomerApi); + IntStream.range(0, 5).mapToObj(i -> tenant).forEach(service::orderDrink); var counter = callsCount.getCount(tenant.getName()); assertEquals(2, counter, "Counter limit must be reached"); } diff --git a/trampoline/README.md b/trampoline/README.md index 6eb870227..eceaf3f1f 100644 --- a/trampoline/README.md +++ b/trampoline/README.md @@ -17,19 +17,19 @@ and to interleave the execution of functions without hard coding them together. ## Explanation Recursion is a frequently adopted technique for solving algorithmic problems in a divide and conquer -style. For example calculating fibonacci accumulating sum and factorials. In these kinds of problems -recursion is more straightforward than their loop counterpart. Furthermore recursion may need less -code and looks more concise. There is a saying that every recursion problem can be solved using -a loop with the cost of writing code that is more difficult to understand. +style. For example, calculating Fibonacci accumulating sum and factorials. In these kinds of +problems, recursion is more straightforward than its loop counterpart. Furthermore, recursion may +need less code and looks more concise. There is a saying that every recursion problem can be solved +using a loop with the cost of writing code that is more difficult to understand. -However recursion type solutions have one big caveat. For each recursive call it typically needs +However, recursion-type solutions have one big caveat. For each recursive call, it typically needs an intermediate value stored and there is a limited amount of stack memory available. Running out of stack memory creates a stack overflow error and halts the program execution. -Trampoline pattern is a trick that allows us define recursive algorithms in Java without blowing the +Trampoline pattern is a trick that allows defining recursive algorithms in Java without blowing the stack. -Real world example +Real-world example > A recursive Fibonacci calculation without the stack overflow problem using the Trampoline pattern. @@ -105,24 +105,26 @@ public interface Trampoline { Using the `Trampoline` to get Fibonacci values. ```java - public static Trampoline loop(int times, int prod) { +public static void main(String[] args) { + LOGGER.info("Start calculating war casualties"); + var result = loop(10, 1).result(); + LOGGER.info("The number of orcs perished in the war: {}", result); +} + +public static Trampoline loop(int times, int prod) { if (times == 0) { - return Trampoline.done(prod); + return Trampoline.done(prod); } else { - return Trampoline.more(() -> loop(times - 1, prod * times)); + return Trampoline.more(() -> loop(times - 1, prod * times)); } - } - - log.info("start pattern"); - var result = loop(10, 1).result(); - log.info("result {}", result); +} ``` Program output: ``` -start pattern -result 3628800 +19:22:24.462 [main] INFO com.iluwatar.trampoline.TrampolineApp - Start calculating war casualties +19:22:24.472 [main] INFO com.iluwatar.trampoline.TrampolineApp - The number of orcs perished in the war: 3628800 ``` ## Class diagram @@ -133,8 +135,8 @@ result 3628800 Use the Trampoline pattern when -* For implementing tail recursive function. This pattern allows to switch on a stackless operation. -* For interleaving the execution of two or more functions on the same thread. +* For implementing tail-recursive functions. This pattern allows to switch on a stackless operation. +* For interleaving execution of two or more functions on the same thread. ## Known uses diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java index 1d2ea91d3..d60ef3602 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java @@ -107,6 +107,4 @@ public interface Trampoline { } }; } - - } diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java index 32a3f1850..bfeed4d69 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java @@ -39,9 +39,9 @@ public class TrampolineApp { * Main program for showing pattern. It does loop with factorial function. */ public static void main(String[] args) { - LOGGER.info("start pattern"); + LOGGER.info("Start calculating war casualties"); var result = loop(10, 1).result(); - LOGGER.info("result {}", result); + LOGGER.info("The number of orcs perished in the war: {}", result); } @@ -55,5 +55,4 @@ public class TrampolineApp { return Trampoline.more(() -> loop(times - 1, prod * times)); } } - } diff --git a/unit-of-work/README.md b/unit-of-work/README.md index df2d03df2..f60667810 100644 --- a/unit-of-work/README.md +++ b/unit-of-work/README.md @@ -12,20 +12,20 @@ tags: ## Intent -When a business transaction is completed, all the the updates are sent as one big unit of work to be +When a business transaction is completed, all the updates are sent as one big unit of work to be persisted in one go to minimize database round-trips. ## Explanation -Real world example +Real-world example -> We have a database containing student information. Administrators all over the country are -> constantly updating this information and it causes high load on the database server. To make the +> Arms dealer has a database containing weapon information. Merchants all over the town are +> constantly updating this information and it causes a high load on the database server. To make the > load more manageable we apply to Unit of Work pattern to send many small updates in batches. In plain words -> Unit of Work merges many small database updates in single batch to optimize the number of +> Unit of Work merges many small database updates in a single batch to optimize the number of > round-trips. [MartinFowler.com](https://martinfowler.com/eaaCatalog/unitOfWork.html) says @@ -35,37 +35,20 @@ In plain words **Programmatic Example** -Here's the `Student` entity that is being persisted to the database. +Here's the `Weapon` entity that is being persisted in the database. ```java -public class Student { - private final Integer id; - private final String name; - private final String address; - - public Student(Integer id, String name, String address) { - this.id = id; - this.name = name; - this.address = address; - } - - public String getName() { - return name; - } - - public Integer getId() { - return id; - } - - public String getAddress() { - return address; - } +@Getter +@RequiredArgsConstructor +public class Weapon { + private final Integer id; + private final String name; } ``` -The essence of the implementation is the `StudentRepository` implementing the Unit of Work pattern. +The essence of the implementation is the `ArmsDealer` implementing the Unit of Work pattern. It maintains a map of database operations (`context`) that need to be done and when `commit` is -called it applies them in single batch. +called it applies them in a single batch. ```java public interface IUnitOfWork { @@ -84,96 +67,117 @@ public interface IUnitOfWork { } @Slf4j -public class StudentRepository implements IUnitOfWork { +@RequiredArgsConstructor +public class ArmsDealer implements IUnitOfWork { - private final Map> context; - private final StudentDatabase studentDatabase; + private final Map> context; + private final WeaponDatabase weaponDatabase; - public StudentRepository(Map> context, StudentDatabase studentDatabase) { - this.context = context; - this.studentDatabase = studentDatabase; - } - - @Override - public void registerNew(Student student) { - LOGGER.info("Registering {} for insert in context.", student.getName()); - register(student, IUnitOfWork.INSERT); - } - - @Override - public void registerModified(Student student) { - LOGGER.info("Registering {} for modify in context.", student.getName()); - register(student, IUnitOfWork.MODIFY); - - } - - @Override - public void registerDeleted(Student student) { - LOGGER.info("Registering {} for delete in context.", student.getName()); - register(student, IUnitOfWork.DELETE); - } - - private void register(Student student, String operation) { - var studentsToOperate = context.get(operation); - if (studentsToOperate == null) { - studentsToOperate = new ArrayList<>(); - } - studentsToOperate.add(student); - context.put(operation, studentsToOperate); - } - - @Override - public void commit() { - if (context == null || context.size() == 0) { - return; - } - LOGGER.info("Commit started"); - if (context.containsKey(IUnitOfWork.INSERT)) { - commitInsert(); + @Override + public void registerNew(Weapon weapon) { + LOGGER.info("Registering {} for insert in context.", weapon.getName()); + register(weapon, UnitActions.INSERT.getActionValue()); } - if (context.containsKey(IUnitOfWork.MODIFY)) { - commitModify(); - } - if (context.containsKey(IUnitOfWork.DELETE)) { - commitDelete(); - } - LOGGER.info("Commit finished."); - } + @Override + public void registerModified(Weapon weapon) { + LOGGER.info("Registering {} for modify in context.", weapon.getName()); + register(weapon, UnitActions.MODIFY.getActionValue()); - private void commitInsert() { - var studentsToBeInserted = context.get(IUnitOfWork.INSERT); - for (var student : studentsToBeInserted) { - LOGGER.info("Saving {} to database.", student.getName()); - studentDatabase.insert(student); } - } - private void commitModify() { - var modifiedStudents = context.get(IUnitOfWork.MODIFY); - for (var student : modifiedStudents) { - LOGGER.info("Modifying {} to database.", student.getName()); - studentDatabase.modify(student); + @Override + public void registerDeleted(Weapon weapon) { + LOGGER.info("Registering {} for delete in context.", weapon.getName()); + register(weapon, UnitActions.DELETE.getActionValue()); } - } - private void commitDelete() { - var deletedStudents = context.get(IUnitOfWork.DELETE); - for (var student : deletedStudents) { - LOGGER.info("Deleting {} to database.", student.getName()); - studentDatabase.delete(student); + private void register(Weapon weapon, String operation) { + var weaponsToOperate = context.get(operation); + if (weaponsToOperate == null) { + weaponsToOperate = new ArrayList<>(); + } + weaponsToOperate.add(weapon); + context.put(operation, weaponsToOperate); + } + + /** + * All UnitOfWork operations are batched and executed together on commit only. + */ + @Override + public void commit() { + if (context == null || context.size() == 0) { + return; + } + LOGGER.info("Commit started"); + if (context.containsKey(UnitActions.INSERT.getActionValue())) { + commitInsert(); + } + + if (context.containsKey(UnitActions.MODIFY.getActionValue())) { + commitModify(); + } + if (context.containsKey(UnitActions.DELETE.getActionValue())) { + commitDelete(); + } + LOGGER.info("Commit finished."); + } + + private void commitInsert() { + var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue()); + for (var weapon : weaponsToBeInserted) { + LOGGER.info("Inserting a new weapon {} to sales rack.", weapon.getName()); + weaponDatabase.insert(weapon); + } + } + + private void commitModify() { + var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue()); + for (var weapon : modifiedWeapons) { + LOGGER.info("Scheduling {} for modification work.", weapon.getName()); + weaponDatabase.modify(weapon); + } + } + + private void commitDelete() { + var deletedWeapons = context.get(UnitActions.DELETE.getActionValue()); + for (var weapon : deletedWeapons) { + LOGGER.info("Scrapping {}.", weapon.getName()); + weaponDatabase.delete(weapon); + } } - } } ``` -Finally, here's how we use the `StudentRepository` and `commit` the transaction. +Here is how the whole app is put together. ```java - studentRepository.registerNew(ram); - studentRepository.registerModified(shyam); - studentRepository.registerDeleted(gopi); - studentRepository.commit(); +// create some weapons +var enchantedHammer = new Weapon(1, "enchanted hammer"); +var brokenGreatSword = new Weapon(2, "broken great sword"); +var silverTrident = new Weapon(3, "silver trident"); + +// create repository +var weaponRepository = new ArmsDealer(new HashMap>(), new WeaponDatabase()); + +// perform operations on the weapons +weaponRepository.registerNew(enchantedHammer); +weaponRepository.registerModified(silverTrident); +weaponRepository.registerDeleted(brokenGreatSword); +weaponRepository.commit(); +``` + +Here is the console output. + +``` +21:39:21.984 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering enchanted hammer for insert in context. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering silver trident for modify in context. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering broken great sword for delete in context. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit started +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Inserting a new weapon enchanted hammer to sales rack. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scheduling silver trident for modification work. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scrapping broken great sword. +21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit finished. ``` ## Class diagram @@ -186,7 +190,7 @@ Use the Unit Of Work pattern when * To optimize the time taken for database transactions. * To send changes to database as a unit of work which ensures atomicity of the transaction. -* To reduce number of database calls. +* To reduce the number of database calls. ## Tutorials diff --git a/unit-of-work/etc/unit-of-work.ucls b/unit-of-work/etc/unit-of-work.ucls index 98181f805..0a80d680d 100644 --- a/unit-of-work/etc/unit-of-work.ucls +++ b/unit-of-work/etc/unit-of-work.ucls @@ -1,7 +1,7 @@ - - @@ -38,7 +38,7 @@ - >(); - var studentDatabase = new StudentDatabase(); - var studentRepository = new StudentRepository(context, studentDatabase); + // create repository + var weaponRepository = new ArmsDealer(new HashMap>(), + new WeaponDatabase()); - studentRepository.registerNew(ram); - studentRepository.registerModified(shyam); - studentRepository.registerDeleted(gopi); - studentRepository.commit(); + // perform operations on the weapons + weaponRepository.registerNew(enchantedHammer); + weaponRepository.registerModified(silverTrident); + weaponRepository.registerDeleted(brokenGreatSword); + weaponRepository.commit(); } } diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java similarity index 55% rename from unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java rename to unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java index 991aef12a..c222e47d4 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java @@ -30,41 +30,41 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** - * {@link StudentRepository} Student database repository. supports unit of work for student data. + * {@link ArmsDealer} Weapon repository that supports unit of work for weapons. */ @Slf4j @RequiredArgsConstructor -public class StudentRepository implements IUnitOfWork { +public class ArmsDealer implements IUnitOfWork { - private final Map> context; - private final StudentDatabase studentDatabase; + private final Map> context; + private final WeaponDatabase weaponDatabase; @Override - public void registerNew(Student student) { - LOGGER.info("Registering {} for insert in context.", student.getName()); - register(student, UnitActions.INSERT.getActionValue()); + public void registerNew(Weapon weapon) { + LOGGER.info("Registering {} for insert in context.", weapon.getName()); + register(weapon, UnitActions.INSERT.getActionValue()); } @Override - public void registerModified(Student student) { - LOGGER.info("Registering {} for modify in context.", student.getName()); - register(student, UnitActions.MODIFY.getActionValue()); + public void registerModified(Weapon weapon) { + LOGGER.info("Registering {} for modify in context.", weapon.getName()); + register(weapon, UnitActions.MODIFY.getActionValue()); } @Override - public void registerDeleted(Student student) { - LOGGER.info("Registering {} for delete in context.", student.getName()); - register(student, UnitActions.DELETE.getActionValue()); + public void registerDeleted(Weapon weapon) { + LOGGER.info("Registering {} for delete in context.", weapon.getName()); + register(weapon, UnitActions.DELETE.getActionValue()); } - private void register(Student student, String operation) { - var studentsToOperate = context.get(operation); - if (studentsToOperate == null) { - studentsToOperate = new ArrayList<>(); + private void register(Weapon weapon, String operation) { + var weaponsToOperate = context.get(operation); + if (weaponsToOperate == null) { + weaponsToOperate = new ArrayList<>(); } - studentsToOperate.add(student); - context.put(operation, studentsToOperate); + weaponsToOperate.add(weapon); + context.put(operation, weaponsToOperate); } /** @@ -90,26 +90,26 @@ public class StudentRepository implements IUnitOfWork { } private void commitInsert() { - var studentsToBeInserted = context.get(UnitActions.INSERT.getActionValue()); - for (var student : studentsToBeInserted) { - LOGGER.info("Saving {} to database.", student.getName()); - studentDatabase.insert(student); + var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue()); + for (var weapon : weaponsToBeInserted) { + LOGGER.info("Inserting a new weapon {} to sales rack.", weapon.getName()); + weaponDatabase.insert(weapon); } } private void commitModify() { - var modifiedStudents = context.get(UnitActions.MODIFY.getActionValue()); - for (var student : modifiedStudents) { - LOGGER.info("Modifying {} to database.", student.getName()); - studentDatabase.modify(student); + var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue()); + for (var weapon : modifiedWeapons) { + LOGGER.info("Scheduling {} for modification work.", weapon.getName()); + weaponDatabase.modify(weapon); } } private void commitDelete() { - var deletedStudents = context.get(UnitActions.DELETE.getActionValue()); - for (var student : deletedStudents) { - LOGGER.info("Deleting {} to database.", student.getName()); - studentDatabase.delete(student); + var deletedWeapons = context.get(UnitActions.DELETE.getActionValue()); + for (var weapon : deletedWeapons) { + LOGGER.info("Scrapping {}.", weapon.getName()); + weaponDatabase.delete(weapon); } } } diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/Student.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java similarity index 93% rename from unit-of-work/src/main/java/com/iluwatar/unitofwork/Student.java rename to unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java index b3de369b4..bf4a3e071 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/Student.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java @@ -27,14 +27,12 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; /** - * {@link Student} is an entity. + * {@link Weapon} is an entity. */ @Getter @RequiredArgsConstructor -public class Student { +public class Weapon { private final Integer id; private final String name; - private final String address; - } diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentDatabase.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java similarity index 87% rename from unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentDatabase.java rename to unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java index c64c47e30..c9a8cee4b 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentDatabase.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java @@ -24,19 +24,19 @@ package com.iluwatar.unitofwork; /** - * Act as Database for student records. + * Act as database for weapon records. */ -public class StudentDatabase { +public class WeaponDatabase { - public void insert(Student student) { + public void insert(Weapon weapon) { //Some insert logic to DB } - public void modify(Student student) { + public void modify(Weapon weapon) { //Some modify logic to DB } - public void delete(Student student) { + public void delete(Weapon weapon) { //Some delete logic to DB } } diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java similarity index 51% rename from unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java rename to unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java index 760d4a21b..65b65a623 100644 --- a/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java @@ -36,102 +36,102 @@ import java.util.Map; import org.junit.jupiter.api.Test; /** - * tests {@link StudentRepository} + * tests {@link ArmsDealer} */ -class StudentRepositoryTest { - private final Student student1 = new Student(1, "Ram", "street 9, cupertino"); - private final Student student2 = new Student(1, "Sham", "Z bridge, pune"); +class ArmsDealerTest { + private final Weapon weapon1 = new Weapon(1, "battle ram"); + private final Weapon weapon2 = new Weapon(1, "wooden lance"); - private final Map> context = new HashMap<>(); - private final StudentDatabase studentDatabase = mock(StudentDatabase.class); - private final StudentRepository studentRepository = new StudentRepository(context, studentDatabase);; + private final Map> context = new HashMap<>(); + private final WeaponDatabase weaponDatabase = mock(WeaponDatabase.class); + private final ArmsDealer armsDealer = new ArmsDealer(context, weaponDatabase);; @Test void shouldSaveNewStudentWithoutWritingToDb() { - studentRepository.registerNew(student1); - studentRepository.registerNew(student2); + armsDealer.registerNew(weapon1); + armsDealer.registerNew(weapon2); assertEquals(2, context.get(UnitActions.INSERT.getActionValue()).size()); - verifyNoMoreInteractions(studentDatabase); + verifyNoMoreInteractions(weaponDatabase); } @Test void shouldSaveDeletedStudentWithoutWritingToDb() { - studentRepository.registerDeleted(student1); - studentRepository.registerDeleted(student2); + armsDealer.registerDeleted(weapon1); + armsDealer.registerDeleted(weapon2); assertEquals(2, context.get(UnitActions.DELETE.getActionValue()).size()); - verifyNoMoreInteractions(studentDatabase); + verifyNoMoreInteractions(weaponDatabase); } @Test void shouldSaveModifiedStudentWithoutWritingToDb() { - studentRepository.registerModified(student1); - studentRepository.registerModified(student2); + armsDealer.registerModified(weapon1); + armsDealer.registerModified(weapon2); assertEquals(2, context.get(UnitActions.MODIFY.getActionValue()).size()); - verifyNoMoreInteractions(studentDatabase); + verifyNoMoreInteractions(weaponDatabase); } @Test void shouldSaveAllLocalChangesToDb() { - context.put(UnitActions.INSERT.getActionValue(), List.of(student1)); - context.put(UnitActions.MODIFY.getActionValue(), List.of(student1)); - context.put(UnitActions.DELETE.getActionValue(), List.of(student1)); + context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1)); + context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1)); + context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1)); - studentRepository.commit(); + armsDealer.commit(); - verify(studentDatabase, times(1)).insert(student1); - verify(studentDatabase, times(1)).modify(student1); - verify(studentDatabase, times(1)).delete(student1); + verify(weaponDatabase, times(1)).insert(weapon1); + verify(weaponDatabase, times(1)).modify(weapon1); + verify(weaponDatabase, times(1)).delete(weapon1); } @Test void shouldNotWriteToDbIfContextIsNull() { - var studentRepository = new StudentRepository(null, studentDatabase); + var weaponRepository = new ArmsDealer(null, weaponDatabase); - studentRepository.commit(); + weaponRepository.commit(); - verifyNoMoreInteractions(studentDatabase); + verifyNoMoreInteractions(weaponDatabase); } @Test void shouldNotWriteToDbIfNothingToCommit() { - var studentRepository = new StudentRepository(new HashMap<>(), studentDatabase); + var weaponRepository = new ArmsDealer(new HashMap<>(), weaponDatabase); - studentRepository.commit(); + weaponRepository.commit(); - verifyNoMoreInteractions(studentDatabase); + verifyNoMoreInteractions(weaponDatabase); } @Test void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() { - context.put(UnitActions.MODIFY.getActionValue(), List.of(student1)); - context.put(UnitActions.DELETE.getActionValue(), List.of(student1)); + context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1)); + context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1)); - studentRepository.commit(); + armsDealer.commit(); - verify(studentDatabase, never()).insert(student1); + verify(weaponDatabase, never()).insert(weapon1); } @Test void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() { - context.put(UnitActions.INSERT.getActionValue(), List.of(student1)); - context.put(UnitActions.DELETE.getActionValue(), List.of(student1)); + context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1)); + context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1)); - studentRepository.commit(); + armsDealer.commit(); - verify(studentDatabase, never()).modify(student1); + verify(weaponDatabase, never()).modify(weapon1); } @Test void shouldNotDeleteFromDbIfNotRegisteredStudentsToBeCommitted() { - context.put(UnitActions.INSERT.getActionValue(), List.of(student1)); - context.put(UnitActions.MODIFY.getActionValue(), List.of(student1)); + context.put(UnitActions.INSERT.getActionValue(), List.of(weapon1)); + context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1)); - studentRepository.commit(); + armsDealer.commit(); - verify(studentDatabase, never()).delete(student1); + verify(weaponDatabase, never()).delete(weapon1); } } diff --git a/value-object/README.md b/value-object/README.md index 9b85d82b1..c98674381 100644 --- a/value-object/README.md +++ b/value-object/README.md @@ -10,19 +10,80 @@ tags: --- ## Intent + Provide objects which follow value semantics rather than reference semantics. -This means value objects' equality are not based on identity. Two value objects are +This means value objects' equality is not based on identity. Two value objects are equal when they have the same value, not necessarily being the same object. +## Explanation + +Real-world example + +> There is a class for hero statistics in a role-playing game. The statistics contain attributes +> such as strength, intelligence, and luck. The statistics of different heroes should be equal +> when all the attributes are equal. + +In plain words + +> Value objects are equal when their attributes have the same value + +Wikipedia says + +> In computer science, a value object is a small object that represents a simple entity whose +> equality is not based on identity: i.e. two value objects are equal when they have the same +> value, not necessarily being the same object. + +**Programmatic Example** + +Here is the `HeroStat` class that is the value object. Notice the use of +[Lombok's `@Value`](https://projectlombok.org/features/Value) annotation. + +```java +@Value(staticConstructor = "valueOf") +class HeroStat { + + int strength; + int intelligence; + int luck; +} +``` + +The example creates three different `HeroStat`s and compares their equality. + +```java +var statA = HeroStat.valueOf(10, 5, 0); +var statB = HeroStat.valueOf(10, 5, 0); +var statC = HeroStat.valueOf(5, 1, 8); + +LOGGER.info(statA.toString()); +LOGGER.info(statB.toString()); +LOGGER.info(statC.toString()); + +LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); +LOGGER.info("Is statA and statC equal : {}", statA.equals(statC)); +``` + +Here's the console output. + +``` +20:11:12.199 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=5, intelligence=1, luck=8) +20:11:12.202 [main] INFO com.iluwatar.value.object.App - Is statA and statB equal : true +20:11:12.203 [main] INFO com.iluwatar.value.object.App - Is statA and statC equal : false +``` + ## Class diagram + ![alt text](./etc/value-object.png "Value Object") ## Applicability + Use the Value Object when -* You need to measure the objects' equality based on the objects' value +* The object's equality needs to be based on the object's value -## Real world examples +## Known uses * [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) * [java.time.LocalDate](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) @@ -31,6 +92,7 @@ Use the Value Object when ## Credits * [Patterns of Enterprise Application Architecture](http://www.martinfowler.com/books/eaa.html) +* [ValueObject](https://martinfowler.com/bliki/ValueObject.html) * [VALJOs - Value Java Objects : Stephen Colebourne's blog](http://blog.joda.org/2014/03/valjos-value-java-objects.html) * [Value Object : Wikipedia](https://en.wikipedia.org/wiki/Value_object) * [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/value-object/src/main/java/com/iluwatar/value/object/App.java b/value-object/src/main/java/com/iluwatar/value/object/App.java index 49375e94c..cc952fd47 100644 --- a/value-object/src/main/java/com/iluwatar/value/object/App.java +++ b/value-object/src/main/java/com/iluwatar/value/object/App.java @@ -43,7 +43,7 @@ import lombok.extern.slf4j.Slf4j; public class App { /** - * This practice creates three HeroStats(Value object) and checks equality between those. + * This example creates three HeroStats (value objects) and checks equality between those. */ public static void main(String[] args) { var statA = HeroStat.valueOf(10, 5, 0); @@ -51,6 +51,8 @@ public class App { var statC = HeroStat.valueOf(5, 1, 8); LOGGER.info(statA.toString()); + LOGGER.info(statB.toString()); + LOGGER.info(statC.toString()); LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); LOGGER.info("Is statA and statC equal : {}", statA.equals(statC)); diff --git a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java index 4d060ee0f..4620b4e4a 100644 --- a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java +++ b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java @@ -23,10 +23,7 @@ package com.iluwatar.value.object; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.ToString; +import lombok.Value; /** * HeroStat is a value object. @@ -35,23 +32,10 @@ import lombok.ToString; * http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html * */ -@Getter -@ToString -@EqualsAndHashCode -@RequiredArgsConstructor -public class HeroStat { - - // Stats for a hero - - private final int strength; - private final int intelligence; - private final int luck; - - // Static factory method to create new instances. - public static HeroStat valueOf(int strength, int intelligence, int luck) { - return new HeroStat(strength, intelligence, luck); - } - - // The clone() method should not be public. Just don't override it. +@Value(staticConstructor = "valueOf") +class HeroStat { + int strength; + int intelligence; + int luck; }