forked from quarkusio/quarkus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UpdateMethodImplementor.java
268 lines (234 loc) · 12.7 KB
/
UpdateMethodImplementor.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package io.quarkus.rest.data.panache.deployment.methods;
import static io.quarkus.gizmo.MethodDescriptor.ofMethod;
import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.ofType;
import java.lang.annotation.Annotation;
import java.util.function.Supplier;
import javax.validation.Valid;
import javax.ws.rs.core.Response;
import io.quarkus.arc.Arc;
import io.quarkus.arc.ArcContainer;
import io.quarkus.arc.InstanceHandle;
import io.quarkus.gizmo.AssignableResultHandle;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.FunctionCreator;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.gizmo.TryBlock;
import io.quarkus.rest.data.panache.RestDataResource;
import io.quarkus.rest.data.panache.deployment.ResourceMetadata;
import io.quarkus.rest.data.panache.deployment.properties.ResourceProperties;
import io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator;
import io.quarkus.rest.data.panache.deployment.utils.UniImplementor;
import io.quarkus.rest.data.panache.runtime.UpdateExecutor;
import io.smallrye.mutiny.Uni;
public final class UpdateMethodImplementor extends StandardMethodImplementor {
private static final String METHOD_NAME = "update";
private static final String RESOURCE_UPDATE_METHOD_NAME = "update";
private static final String RESOURCE_GET_METHOD_NAME = "get";
private static final String REL = "update";
private static final String EXCEPTION_MESSAGE = "Failed to update an entity";
private final boolean withValidation;
public UpdateMethodImplementor(boolean withValidation, boolean isResteasyClassic, boolean isReactivePanache) {
super(isResteasyClassic, isReactivePanache);
this.withValidation = withValidation;
}
/**
* Generate JAX-RS UPDATE method.
*
* The RESTEasy Classic version exposes {@link RestDataResource#update(Object, Object)}.
* Expose {@link RestDataResource#update(Object, Object)} via JAX-RS method.
* Generated code looks more or less like this:
*
* <pre>
* {@code
* @PUT
* @Path("{id}")
* @Consumes({"application/json"})
* @Produces({"application/json"})
* @LinkResource(
* rel = "update",
* entityClassName = "com.example.Entity"
* )
* public Response update(@PathParam("id") ID id, Entity entityToSave) {
* try {
* Object newEntity = updateExecutor.execute(() -> {
* if (resource.get(id) == null) {
* return resource.update(id, entityToSave);
* } else {
* resource.update(id, entityToSave);
* return null;
* }
* });
*
* if (newEntity == null) {
* return Response.status(204).build();
* } else {
* String location = new ResourceLinksProvider().getSelfLink(newEntity);
* if (location != null) {
* ResponseBuilder responseBuilder = Response.status(201);
* responseBuilder.entity(newEntity);
* responseBuilder.location(URI.create(location));
* return responseBuilder.build();
* } else {
* throw new RuntimeException("Could not extract a new entity URL")
* }
* }
* } catch (Throwable t) {
* throw new RestDataPanacheException(t);
* }
* }
* }
* </pre>
*
* The RESTEasy Reactive version exposes
* {@link io.quarkus.rest.data.panache.ReactiveRestDataResource#update(Object, Object)}.
*
* <pre>
* {@code
* @PUT
* @Path("{id}")
* @Consumes({"application/json"})
* @Produces({"application/json"})
* @LinkResource(
* rel = "update",
* entityClassName = "com.example.Entity"
* )
* public Uni<Response> update(@PathParam("id") ID id, Entity entityToSave) {
* return resource.get(id).flatMap(entity -> {
* if (entity == null) {
* return Uni.createFrom().item(Response.status(204).build());
* } else {
* return resource.update(id, entityToSave).map(savedEntity -> {
* String location = new ResourceLinksProvider().getSelfLink(savedEntity);
* if (location != null) {
* ResponseBuilder responseBuilder = Response.status(201);
* responseBuilder.entity(savedEntity);
* responseBuilder.location(URI.create(location));
* return responseBuilder.build();
* } else {
* throw new RuntimeException("Could not extract a new entity URL")
* }
* });
* }
* }).onFailure().invoke(t -> throw new RestDataPanacheException(t));
* }
* }
* </pre>
*/
@Override
protected void implementInternal(ClassCreator classCreator, ResourceMetadata resourceMetadata,
ResourceProperties resourceProperties, FieldDescriptor resourceField) {
MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(METHOD_NAME, classCreator,
isNotReactivePanache() ? ofType(Response.class) : ofType(Uni.class, resourceMetadata.getEntityType()),
resourceMetadata.getIdType(), resourceMetadata.getEntityType());
// Add method annotations
addPathAnnotation(methodCreator, appendToPath(resourceProperties.getPath(RESOURCE_UPDATE_METHOD_NAME), "{id}"));
addPutAnnotation(methodCreator);
addPathParamAnnotation(methodCreator.getParameterAnnotations(0), "id");
addConsumesAnnotation(methodCreator, APPLICATION_JSON);
addProducesJsonAnnotation(methodCreator, resourceProperties);
addLinksAnnotation(methodCreator, resourceMetadata.getEntityType(), REL);
// Add parameter annotations
if (withValidation) {
methodCreator.getParameterAnnotations(1).addAnnotation(Valid.class);
}
ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis());
ResultHandle id = methodCreator.getMethodParam(0);
ResultHandle entityToSave = methodCreator.getMethodParam(1);
if (isNotReactivePanache()) {
implementClassicVersion(methodCreator, resourceMetadata, resource, id, entityToSave);
} else {
implementReactiveVersion(methodCreator, resourceMetadata, resource, id, entityToSave);
}
methodCreator.close();
}
@Override
protected String getResourceMethodName() {
return RESOURCE_UPDATE_METHOD_NAME;
}
private void implementReactiveVersion(MethodCreator methodCreator, ResourceMetadata resourceMetadata, ResultHandle resource,
ResultHandle id, ResultHandle entityToSave) {
ResultHandle uniResponse = methodCreator.invokeVirtualMethod(
ofMethod(resourceMetadata.getResourceClass(), RESOURCE_GET_METHOD_NAME, Uni.class, Object.class),
resource, id);
methodCreator
.returnValue(UniImplementor.flatMap(methodCreator, uniResponse, EXCEPTION_MESSAGE, (getBody, itemWasFound) -> {
ResultHandle uniUpdateEntity = getBody.invokeVirtualMethod(
ofMethod(resourceMetadata.getResourceClass(), RESOURCE_UPDATE_METHOD_NAME, Uni.class, Object.class,
Object.class),
resource, id, entityToSave);
getBody.returnValue(UniImplementor.map(getBody, uniUpdateEntity, EXCEPTION_MESSAGE,
(updateBody, itemUpdated) -> {
BranchResult ifEntityIsNew = updateBody.ifNull(itemWasFound);
ifEntityIsNew.trueBranch()
.returnValue(responseImplementor.created(ifEntityIsNew.trueBranch(), itemUpdated));
ifEntityIsNew.falseBranch()
.returnValue(responseImplementor.noContent(ifEntityIsNew.falseBranch()));
}));
}));
}
private void implementClassicVersion(MethodCreator methodCreator, ResourceMetadata resourceMetadata, ResultHandle resource,
ResultHandle id, ResultHandle entityToSave) {
// Invoke resource methods inside a supplier function which will be given to an update executor.
// For ORM, this update executor will have the @Transactional annotation to make
// sure that all database operations are executed in a single transaction.
TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE);
ResultHandle updateExecutor = getUpdateExecutor(tryBlock);
ResultHandle updateFunction = getUpdateFunction(tryBlock, resourceMetadata.getResourceClass(), resource, id,
entityToSave);
ResultHandle newEntity = tryBlock.invokeInterfaceMethod(
ofMethod(UpdateExecutor.class, "execute", Object.class, Supplier.class),
updateExecutor, updateFunction);
BranchResult createdNewEntity = tryBlock.ifNotNull(newEntity);
createdNewEntity.trueBranch().returnValue(responseImplementor.created(createdNewEntity.trueBranch(), newEntity));
createdNewEntity.falseBranch().returnValue(responseImplementor.noContent(createdNewEntity.falseBranch()));
}
private ResultHandle getUpdateFunction(BytecodeCreator creator, String resourceClass, ResultHandle resource,
ResultHandle id, ResultHandle entity) {
FunctionCreator functionCreator = creator.createFunction(Supplier.class);
BytecodeCreator functionBytecodeCreator = functionCreator.getBytecode();
AssignableResultHandle entityToSave = functionBytecodeCreator.createVariable(Object.class);
functionBytecodeCreator.assign(entityToSave, entity);
BranchResult shouldUpdate = entityExists(functionBytecodeCreator, resourceClass, resource, id);
// Update and return null
updateAndReturn(shouldUpdate.trueBranch(), resourceClass, resource, id, entityToSave);
// Update and return new entity
createAndReturn(shouldUpdate.falseBranch(), resourceClass, resource, id, entityToSave);
return functionCreator.getInstance();
}
private BranchResult entityExists(BytecodeCreator creator, String resourceClass, ResultHandle resource,
ResultHandle id) {
return creator.ifNotNull(creator.invokeVirtualMethod(
ofMethod(resourceClass, RESOURCE_GET_METHOD_NAME, Object.class, Object.class), resource, id));
}
private void createAndReturn(BytecodeCreator creator, String resourceClass, ResultHandle resource,
ResultHandle id, ResultHandle entityToSave) {
ResultHandle newEntity = creator.invokeVirtualMethod(
ofMethod(resourceClass, RESOURCE_UPDATE_METHOD_NAME, Object.class, Object.class, Object.class),
resource, id, entityToSave);
creator.returnValue(newEntity);
}
private void updateAndReturn(BytecodeCreator creator, String resourceClass, ResultHandle resource,
ResultHandle id, ResultHandle entityToSave) {
creator.invokeVirtualMethod(
ofMethod(resourceClass, RESOURCE_UPDATE_METHOD_NAME, Object.class, Object.class, Object.class),
resource, id, entityToSave);
creator.returnValue(creator.loadNull());
}
private ResultHandle getUpdateExecutor(BytecodeCreator creator) {
ResultHandle arcContainer = creator.invokeStaticMethod(ofMethod(Arc.class, "container", ArcContainer.class));
ResultHandle instanceHandle = creator.invokeInterfaceMethod(
ofMethod(ArcContainer.class, "instance", InstanceHandle.class, Class.class, Annotation[].class),
arcContainer, creator.loadClassFromTCCL(UpdateExecutor.class), creator.newArray(Annotation.class, 0));
ResultHandle instance = creator.invokeInterfaceMethod(
ofMethod(InstanceHandle.class, "get", Object.class), instanceHandle);
creator.ifNull(instance)
.trueBranch()
.throwException(RuntimeException.class,
UpdateExecutor.class.getSimpleName() + " instance was not found");
return instance;
}
}