-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathShoppingCartEntity.java
207 lines (176 loc) · 7.65 KB
/
ShoppingCartEntity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package io.cloudstate.shopping;
import com.google.protobuf.Empty;
import io.cloudstate.connector.Connector;
import io.cloudstate.connector.RestConnectorGrpc;
import io.cloudstate.javasupport.EntityId;
import io.cloudstate.javasupport.eventsourced.*;
import io.cloudstate.shopping.domain.Domain;
import io.grpc.ManagedChannelBuilder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static io.cloudstate.connector.Connector.*;
/**
* Entity ready to be used for Event Sourcing
*/
@EventSourcedEntity(persistenceId = "shopping-cart", snapshotEvery = 20)
public class ShoppingCartEntity {
private final String entityId;
private final Map<String, Protocol.LineItem> cart = new LinkedHashMap<>();
public ShoppingCartEntity(@EntityId String entityId) {
this.entityId = entityId;
}
/**
* Using gRPC we create a connection with the rest connector. Since both services are running in localhost
* the latency in communication is pretty much the same as is executed in the same JVM.
* The client only need to know the host where service domain and port to communicate.
* The rest of the communication DSL is done by protobuf client/server generated code by the proto contract file.
*/
private RestConnectorGrpc.RestConnectorBlockingStub restConnector =
RestConnectorGrpc.newBlockingStub(ManagedChannelBuilder
.forAddress("cloudstate-rest-connector-service.cloudstate", 2981)
.usePlaintext(true)
.build());
// COMMANDS
//-----------
/**
* Query handler to return the Cart of the Shopping.
* We will find in the Map all values items for a user
*
* @return Cart
*/
@CommandHandler
public Protocol.Cart getCart(Protocol.GetShoppingCart getShoppingCartQuery) {
System.out.println("Get current Cart state for user:" + getShoppingCartQuery.getUserId());
String price = makeRestConnectorCall();
System.out.println(price);
return Protocol.Cart.newBuilder().addAllItems(cart.values()).build();
}
/**
* A command handler may emit an event by taking in a CommandContext parameter, and invoking the emit method on it.
* Invoking emit will immediately invoke the associated event handler for that event
* <p>
* [ShoppingDomain] is the factory class responsible for the creation of events. Here using for instance [ItemAdded.newBuilder()]
* we use builder pattern to create a new Event using the command info.
*
* @param addItemCommand Command to transform into event
* @param ctx of command to link the Command and Event Handler.
* @return Empty
*/
@CommandHandler
public Empty addItem(Protocol.AddLineItem addItemCommand, CommandContext ctx) {
System.out.println("Add item command:" + addItemCommand);
if (addItemCommand.getQuantity() <= 0) {
ctx.fail("Cannot add negative quantity of to addItemCommand" + addItemCommand.getProductId());
}
ctx.emit(Domain.ItemAdded.newBuilder()
.setItem(Domain.LineItem.newBuilder()
.setProductId(addItemCommand.getProductId())
.setName(addItemCommand.getName())
.setQuantity(addItemCommand.getQuantity())
.build())
.build());
return Empty.getDefaultInstance();
}
/**
* Command handle method to transform the productId from the command in the ItemRemoved event which it could be persisted,
* to be reused in a rehydrate a Cart.
* We create the event and we pass to the Event handle to apply the action of that event.
*
* @param removeLineItemCommand Command to transform into event
* @param ctx of command to link the Command and Event Handler.
* @return Empty
*/
@CommandHandler
public Empty removeItem(Protocol.RemoveLineItem removeLineItemCommand, CommandContext ctx) {
System.out.println("Remove item command:" + removeLineItemCommand);
ctx.emit(Domain.ItemRemoved.newBuilder()
.setProductId(removeLineItemCommand.getProductId())
.build());
return Empty.getDefaultInstance();
}
@CommandHandler
public Protocol.LineItem getItem(Protocol.GetLineItem getItemQuery) {
System.out.println("Get Item by productId:" + getItemQuery.getProductId());
return cart.get(getItemQuery.getProductId());
}
// HANDLERS
//-------------
/**
* Handle method that is invoked once a Command create an event of type [ItemAdded] and ise emit into
* the [CommandContext]
*/
@EventHandler
public void itemAdded(Domain.ItemAdded event) {
System.out.println("Processing ItemAdded event:" + event);
Protocol.LineItem item = cart.get(event.getItem().getProductId());
item = item == null ?
transformDomainItemToProtocol(event.getItem()) :
updateItem(event, item);
cart.put(item.getProductId(), item);
}
private Protocol.LineItem updateItem(Domain.ItemAdded event, Protocol.LineItem item) {
return item.toBuilder()
.setQuantity(item.getQuantity() + event.getItem().getQuantity())
.build();
}
/**
* Event handle function responsible to receive the Event and apply the remove of the item from the cart
*/
@EventHandler
public void itemRemoved(Domain.ItemRemoved event) {
System.out.println("Processing ItemRemoved event:" + event);
cart.remove(event.getProductId());
}
// SNAPSHOT
//----------
/**
* Snapshots are an important optimisation for event sourced entities that may contain many events,
* to ensure that they can be loaded quickly even when they have very long journals
*/
@Snapshot
public Domain.Cart snapshot() {
return Domain.Cart.newBuilder()
.addAllItems(cart.values().stream().map(this::transformProtocolItemToDomain).collect(Collectors.toList()))
.build();
}
/**
* When the entity is rehydrate again, the snapshot will first be loaded before any other events are received, and passed to a snapshot handler
**/
@SnapshotHandler
public void handleSnapshot(Domain.Cart cart) {
System.out.println("Rehydrate shopping cart from Data store:" + cart);
this.cart.clear();
for (Domain.LineItem item : cart.getItemsList()) {
this.cart.put(item.getProductId(), transformDomainItemToProtocol(item));
}
}
// UTILS
//----------
private Protocol.LineItem transformDomainItemToProtocol(Domain.LineItem item) {
return Protocol.LineItem.newBuilder()
.setProductId(item.getProductId())
.setName(item.getName())
.setQuantity(item.getQuantity())
.build();
}
private Domain.LineItem transformProtocolItemToDomain(Protocol.LineItem item) {
return Domain.LineItem.newBuilder()
.setProductId(item.getProductId())
.setName(item.getName())
.setQuantity(item.getQuantity())
.build();
}
// CONNECTOR INVOCATION
//------------------------
private String makeRestConnectorCall() {
RestResponse response = restConnector.makeRequest(RestRequest.newBuilder()
.setUserId("politrons")
.setHost("www.mocky.io")
.setPort(80)
.setUri("/v2/5185415ba171ea3a00704eed")
.setMethod(Method.GET)
.build());
return response.getResponse();
}
}