-
Notifications
You must be signed in to change notification settings - Fork 188
/
ModelRestService.java
817 lines (673 loc) · 29.1 KB
/
ModelRestService.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
/*
* Copyright (c) 2013-2016 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.model.impl;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.model.api.*;
import com.evolveum.midpoint.model.impl.util.RestServiceUtil;
import com.evolveum.midpoint.prism.Item;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.*;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ExecuteScriptsResponseType;
import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ItemListType;
import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingExpressionType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
import org.apache.commons.lang.Validate;
import org.apache.cxf.jaxrs.ext.MessageContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.evolveum.midpoint.model.impl.rest.PATCH;
import com.evolveum.midpoint.model.impl.security.SecurityHelper;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.QueryJaxbConvertor;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
/**
* @author katkav
* @author semancik
*/
@Service
@Produces({"application/xml", "application/json"})
public class ModelRestService {
public static final String CLASS_DOT = ModelRestService.class.getName() + ".";
public static final String OPERATION_REST_SERVICE = CLASS_DOT + "restService";
public static final String OPERATION_GET = CLASS_DOT + "get";
public static final String OPERATION_ADD_OBJECT = CLASS_DOT + "addObject";
public static final String OPERATION_DELETE_OBJECT = CLASS_DOT + "deleteObject";
public static final String OPERATION_MODIFY_OBJECT = CLASS_DOT + "modifyObject";
public static final String OPERATION_NOTIFY_CHANGE = CLASS_DOT + "notifyChange";
public static final String OPERATION_FIND_SHADOW_OWNER = CLASS_DOT + "findShadowOwner";
public static final String OPERATION_SEARCH_OBJECTS = CLASS_DOT + "searchObjects";
public static final String OPERATION_IMPORT_FROM_RESOURCE = CLASS_DOT + "importFromResource";
public static final String OPERATION_TEST_RESOURCE = CLASS_DOT + "testResource";
public static final String OPERATION_SUSPEND_TASKS = CLASS_DOT + "suspendTasks";
public static final String OPERATION_SUSPEND_AND_DELETE_TASKS = CLASS_DOT + "suspendAndDeleteTasks";
public static final String OPERATION_RESUME_TASKS = CLASS_DOT + "resumeTasks";
public static final String OPERATION_SCHEDULE_TASKS_NOW = CLASS_DOT + "scheduleTasksNow";
public static final String OPERATION_EXECUTE_SCRIPT = CLASS_DOT + "executeScript";
public static final String OPERATION_COMPARE = CLASS_DOT + "compare";
public static final String OPERATION_GET_LOG_FILE_CONTENT = CLASS_DOT + "getLogFileContent";
public static final String OPERATION_GET_LOG_FILE_SIZE = CLASS_DOT + "getLogFileSize";
@Autowired
private ModelCrudService model;
@Autowired
private ScriptingService scriptingService;
@Autowired
private ModelService modelService;
@Autowired
private ModelDiagnosticService modelDiagnosticService;
@Autowired
private ModelInteractionService modelInteraction;
@Autowired
private PrismContext prismContext;
@Autowired
private SecurityHelper securityHelper;
private static final Trace LOGGER = TraceManager.getTrace(ModelRestService.class);
public static final long WAIT_FOR_TASK_STOP = 2000L;
public ModelRestService() {
// nothing to do
}
@GET
@Path("/users/{id}/policy")
public Response getValuePolicyForUser(@PathParam("id") String oid, @Context MessageContext mc) {
LOGGER.debug("getValuePolicyForUser start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_GET);
Response response;
try {
Collection<SelectorOptions<GetOperationOptions>> options =
SelectorOptions.createCollection(GetOperationOptions.createRaw());
PrismObject<UserType> user = model.getObject(UserType.class, oid, options, task, parentResult);
CredentialsPolicyType policy = modelInteraction.getCredentialsPolicy(user, task, parentResult);
ResponseBuilder builder = Response.ok();
builder.entity(policy);
response = builder.build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
LOGGER.debug("getValuePolicyForUser finish");
return response;
}
@GET
@Path("/{type}/{id}")
public <T extends ObjectType> Response getObject(@PathParam("type") String type, @PathParam("id") String id,
@QueryParam("options") List<String> options,
@QueryParam("include") List<String> include,
@QueryParam("exclude") List<String> exclude,
@Context MessageContext mc){
LOGGER.debug("model rest service for get operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_GET);
Class<T> clazz = ObjectTypes.getClassFromRestType(type);
Collection<SelectorOptions<GetOperationOptions>> getOptions = GetOperationOptions.fromRestOptions(options, include, exclude);
Response response;
try {
PrismObject<T> object = model.getObject(clazz, id, getOptions, task, parentResult);
removeExcludes(object, exclude); // temporary measure until fixed in repo
ResponseBuilder builder = Response.ok();
builder.entity(object);
response = builder.build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@POST
@Path("/{type}")
// @Produces({"text/html", "application/xml"})
@Consumes({"application/xml", "application/json"})
public <T extends ObjectType> Response addObject(@PathParam("type") String type, PrismObject<T> object,
@QueryParam("options") List<String> options,
@Context UriInfo uriInfo, @Context MessageContext mc) {
LOGGER.debug("model rest service for add operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_ADD_OBJECT);
Class clazz = ObjectTypes.getClassFromRestType(type);
if (!object.getCompileTimeClass().equals(clazz)){
finishRequest(task);
return RestServiceUtil.buildErrorResponse(Status.BAD_REQUEST, "Request to add object of type "
+ object.getCompileTimeClass().getSimpleName() + " to the collection of " + type);
}
ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options);
String oid;
Response response;
try {
oid = model.addObject(object, modelExecuteOptions, task, parentResult);
LOGGER.debug("returned oid : {}", oid );
ResponseBuilder builder;
if (oid != null) {
URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oid).build(oid);
builder = clazz.isAssignableFrom(TaskType.class) ?
Response.accepted().location(resourceURI) : Response.created(resourceURI);
} else {
// OID might be null e.g. if the object creation is a subject of workflow approval
builder = Response.accepted(); // TODO is this ok ?
}
response = builder.build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@PUT
@Path("/{type}/{id}")
// @Produces({"text/html", "application/xml"})
public <T extends ObjectType> Response addObject(@PathParam("type") String type, @PathParam("id") String id,
PrismObject<T> object, @QueryParam("options") List<String> options, @Context UriInfo uriInfo,
@Context Request request, @Context MessageContext mc){
LOGGER.debug("model rest service for add operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_ADD_OBJECT);
Class clazz = ObjectTypes.getClassFromRestType(type);
if (!object.getCompileTimeClass().equals(clazz)){
finishRequest(task);
return RestServiceUtil.buildErrorResponse(Status.BAD_REQUEST, "Request to add object of type "
+ object.getCompileTimeClass().getSimpleName()
+ " to the collection of " + type);
}
ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options);
if (modelExecuteOptions == null) {
modelExecuteOptions = ModelExecuteOptions.createOverwrite();
} else if (!ModelExecuteOptions.isOverwrite(modelExecuteOptions)){
modelExecuteOptions.setOverwrite(Boolean.TRUE);
}
String oid;
Response response;
try {
oid = model.addObject(object, modelExecuteOptions, task, parentResult);
LOGGER.debug("returned oid : {}", oid );
URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oid).build(oid);
ResponseBuilder builder = clazz.isAssignableFrom(TaskType.class) ?
Response.accepted().location(resourceURI) : Response.created(resourceURI);
response = builder.build();
} catch (ObjectAlreadyExistsException e) {
response = Response.serverError().entity(e.getMessage()).build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@DELETE
@Path("/{type}/{id}")
// @Produces({"text/html", "application/xml"})
public Response deleteObject(@PathParam("type") String type, @PathParam("id") String id,
@QueryParam("options") List<String> options, @Context MessageContext mc){
LOGGER.debug("model rest service for delete operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_DELETE_OBJECT);
Class clazz = ObjectTypes.getClassFromRestType(type);
Response response;
try {
if (clazz.isAssignableFrom(TaskType.class)){
model.suspendAndDeleteTasks(MiscUtil.createCollection(id), WAIT_FOR_TASK_STOP, true, parentResult);
parentResult.computeStatus();
finishRequest(task);
if (parentResult.isSuccess()){
return Response.noContent().build();
}
return Response.serverError().entity(parentResult.getMessage()).build();
}
ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options);
model.deleteObject(clazz, id, modelExecuteOptions, task, parentResult);
response = Response.noContent().build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@POST
@Path("/{type}/{oid}")
public <T extends ObjectType> Response modifyObjectPost(@PathParam("type") String type, @PathParam("oid") String oid,
ObjectModificationType modificationType, @QueryParam("options") List<String> options, @Context MessageContext mc) {
return modifyObjectPatch(type, oid, modificationType, options, mc);
}
@PATCH
@Path("/{type}/{oid}")
// @Produces({"text/html", "application/xml"})
public <T extends ObjectType> Response modifyObjectPatch(@PathParam("type") String type, @PathParam("oid") String oid,
ObjectModificationType modificationType, @QueryParam("options") List<String> options, @Context MessageContext mc) {
LOGGER.debug("model rest service for modify operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_MODIFY_OBJECT);
Class clazz = ObjectTypes.getClassFromRestType(type);
Response response;
try {
ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options);
Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(modificationType, clazz, prismContext);
model.modifyObject(clazz, oid, modifications, modelExecuteOptions, task, parentResult);
response = Response.noContent().build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@POST
@Path("/notifyChange")
public Response notifyChange(ResourceObjectShadowChangeDescriptionType changeDescription,
@Context UriInfo uriInfo, @Context MessageContext mc) {
LOGGER.debug("model rest service for notify change operation start");
Validate.notNull(changeDescription, "Chnage description must not be null");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_NOTIFY_CHANGE);
Response response;
try {
model.notifyChange(changeDescription, parentResult, task);
return Response.ok().build();
// String oldShadowOid = changeDescription.getOldShadowOid();
// if (oldShadowOid != null){
// URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oldShadowOid).build(oldShadowOid);
// return Response.accepted().location(resourceURI).build();
// } else {
// changeDescription.get
// }
// response = Response.seeOther((uriInfo.getBaseUriBuilder().path(this.getClass(), "getObject").build(ObjectTypes.TASK.getRestType(), task.getOid()))).build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@GET
@Path("/shadows/{oid}/owner")
// @Produces({"text/html", "application/xml"})
public Response findShadowOwner(@PathParam("oid") String shadowOid, @Context MessageContext mc){
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_FIND_SHADOW_OWNER);
Response response;
try {
PrismObject<UserType> user = model.findShadowOwner(shadowOid, task, parentResult);
response = Response.ok().entity(user).build();
} catch (ConfigurationException e) {
response = RestServiceUtil.buildErrorResponse(Status.INTERNAL_SERVER_ERROR, e.getMessage());
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@POST
@Path("/{type}/search")
// @Produces({"text/html", "application/xml"})
public Response searchObjects(@PathParam("type") String type, QueryType queryType,
@QueryParam("options") List<String> options,
@QueryParam("include") List<String> include,
@QueryParam("exclude") List<String> exclude,
@Context MessageContext mc){
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_SEARCH_OBJECTS);
Class clazz = ObjectTypes.getClassFromRestType(type);
Response response;
try {
ObjectQuery query = QueryJaxbConvertor.createObjectQuery(clazz, queryType, prismContext);
Collection<SelectorOptions<GetOperationOptions>> searchOptions = GetOperationOptions.fromRestOptions(options, include, exclude);
List<PrismObject<? extends ShadowType>> objects = model.searchObjects(clazz, query, searchOptions, task, parentResult);
ObjectListType listType = new ObjectListType();
for (PrismObject<? extends ObjectType> o : objects) {
removeExcludes(o, exclude); // temporary measure until fixed in repo
listType.getObject().add(o.asObjectable());
}
response = Response.ok().entity(listType).build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
private void removeExcludes(PrismObject<? extends ObjectType> object, List<String> exclude) {
for (ItemPath path : ItemPath.fromStringList(exclude)) {
Item item = object.findItem(path); // reduce to "removeItem" after fixing that method implementation
if (item != null) {
object.removeItem(item.getPath(), Item.class);
}
}
}
@POST
@Path("/resources/{resourceOid}/import/{objectClass}")
// @Produces({"text/html", "application/xml"})
public Response importFromResource(@PathParam("resourceOid") String resourceOid, @PathParam("objectClass") String objectClass,
@Context MessageContext mc, @Context UriInfo uriInfo) {
LOGGER.debug("model rest service for import from resource operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_IMPORT_FROM_RESOURCE);
QName objClass = new QName(MidPointConstants.NS_RI, objectClass);
Response response;
try {
model.importFromResource(resourceOid, objClass, task, parentResult);
response = Response.seeOther((uriInfo.getBaseUriBuilder().path(this.getClass(), "getObject")
.build(ObjectTypes.TASK.getRestType(), task.getOid()))).build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
parentResult.computeStatus();
finishRequest(task);
return response;
}
@POST
@Path("/resources/{resourceOid}/test")
// @Produces({"text/html", "application/xml"})
public Response testResource(@PathParam("resourceOid") String resourceOid, @Context MessageContext mc) {
LOGGER.debug("model rest service for test resource operation start");
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_TEST_RESOURCE);
Response response;
OperationResult testResult = null;
try {
testResult = model.testResource(resourceOid, task);
response = Response.ok(testResult).build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
if (testResult != null) {
parentResult.getSubresults().add(testResult);
}
finishRequest(task);
return response;
}
@POST
@Path("/tasks/{oid}/suspend")
public Response suspendTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_SUSPEND_TASKS);
Response response;
Collection<String> taskOids = MiscUtil.createCollection(taskOid);
try {
model.suspendTasks(taskOids, WAIT_FOR_TASK_STOP, parentResult);
parentResult.computeStatus();
if (parentResult.isSuccess()){
response = Response.noContent().build();
} else {
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build();
}
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
finishRequest(task);
return response;
}
// @DELETE
// @Path("tasks/{oid}/suspend")
public Response suspendAndDeleteTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_SUSPEND_AND_DELETE_TASKS);
Response response;
Collection<String> taskOids = MiscUtil.createCollection(taskOid);
try {
model.suspendAndDeleteTasks(taskOids, WAIT_FOR_TASK_STOP, true, parentResult);
parentResult.computeStatus();
if (parentResult.isSuccess()) {
response = Response.accepted().build();
} else {
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build();
}
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
finishRequest(task);
return response;
}
@POST
@Path("/tasks/{oid}/resume")
public Response resumeTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_RESUME_TASKS);
Response response;
Collection<String> taskOids = MiscUtil.createCollection(taskOid);
try {
model.resumeTasks(taskOids, parentResult);
parentResult.computeStatus();
if (parentResult.isSuccess()) {
response = Response.accepted().build();
} else {
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build();
}
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
finishRequest(task);
return response;
}
@POST
@Path("tasks/{oid}/run")
public Response scheduleTasksNow(@PathParam("oid") String taskOid, @Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult parentResult = task.getResult().createSubresult(OPERATION_SCHEDULE_TASKS_NOW);
Collection<String> taskOids = MiscUtil.createCollection(taskOid);
Response response;
try {
model.scheduleTasksNow(taskOids, parentResult);
parentResult.computeStatus();
if (parentResult.isSuccess()) {
response = Response.accepted().build();
} else {
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build();
}
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
finishRequest(task);
return response;
}
@POST
@Path("/scriptExecutions")
// @Produces({"text/html", "application/xml"})
@Consumes({"application/xml" })
public <T extends ObjectType> Response executeScript(ScriptingExpressionType scriptingExpression,
@QueryParam("asynchronous") Boolean asynchronous,
@Context UriInfo uriInfo, @Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult result = task.getResult().createSubresult(OPERATION_EXECUTE_SCRIPT);
String oid;
Response response;
try {
ResponseBuilder builder;
if (Boolean.TRUE.equals(asynchronous)) {
scriptingService.evaluateExpression(scriptingExpression, task, result);
URI resourceUri = uriInfo.getAbsolutePathBuilder().path(task.getOid()).build(task.getOid());
builder = Response.created(resourceUri);
} else {
ScriptExecutionResult executionResult = scriptingService.evaluateExpression(scriptingExpression, task, result);
ExecuteScriptsResponseType operationOutput = new ExecuteScriptsResponseType();
operationOutput.setResult(result.createOperationResultType());
ScriptOutputsType outputs = new ScriptOutputsType();
operationOutput.setOutputs(outputs);
SingleScriptOutputType output = new SingleScriptOutputType();
output.setTextOutput(executionResult.getConsoleOutput());
output.setXmlData(prepareXmlData(executionResult.getDataOutput()));
outputs.getOutput().add(output);
builder = Response.ok();
builder.entity(operationOutput);
}
response = builder.build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
result.computeStatus();
finishRequest(task);
return response;
}
private ItemListType prepareXmlData(List<Item> output) throws JAXBException, SchemaException {
ItemListType itemListType = new ItemListType();
if (output != null) {
for (Item item : output) {
RawType rawType = prismContext.toRawType(item);
itemListType.getItem().add(rawType);
}
}
return itemListType;
}
@POST
@Path("/comparisons")
// @Produces({"text/html", "application/xml"})
@Consumes({"application/xml" })
public <T extends ObjectType> Response compare(PrismObject<T> clientObject,
@QueryParam("readOptions") List<String> restReadOptions,
@QueryParam("compareOptions") List<String> restCompareOptions,
@QueryParam("ignoreItems") List<String> restIgnoreItems,
@Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult result = task.getResult().createSubresult(OPERATION_COMPARE);
Response response;
try {
ResponseBuilder builder;
List<ItemPath> ignoreItemPaths = ItemPath.fromStringList(restIgnoreItems);
final GetOperationOptions getOpOptions = GetOperationOptions.fromRestOptions(restReadOptions);
Collection<SelectorOptions<GetOperationOptions>> readOptions =
getOpOptions != null ? SelectorOptions.createCollection(getOpOptions) : null;
ModelCompareOptions compareOptions = ModelCompareOptions.fromRestOptions(restCompareOptions);
CompareResultType compareResult = modelService.compareObject(clientObject, readOptions, compareOptions, ignoreItemPaths, task, result);
builder = Response.ok();
builder.entity(compareResult);
response = builder.build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
result.computeStatus();
finishRequest(task);
return response;
}
@GET
@Path("/log/size")
@Produces({"text/plain"})
public Response getLogFileSize(@Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult result = task.getResult().createSubresult(OPERATION_GET_LOG_FILE_SIZE);
Response response;
try {
long size = modelDiagnosticService.getLogFileSize(task, result);
ResponseBuilder builder = Response.ok();
builder.entity(String.valueOf(size));
response = builder.build();
} catch (Exception ex) {
response = RestServiceUtil.handleException(ex);
}
result.computeStatus();
finishRequest(task);
return response;
}
@GET
@Path("/log")
@Produces({"text/plain"})
public Response getLog(@QueryParam("fromPosition") Long fromPosition, @QueryParam("maxSize") Long maxSize, @Context MessageContext mc) {
Task task = RestServiceUtil.initRequest(mc);
OperationResult result = task.getResult().createSubresult(OPERATION_GET_LOG_FILE_CONTENT);
Response response;
try {
LogFileContentType content = modelDiagnosticService.getLogFileContent(fromPosition, maxSize, task, result);
ResponseBuilder builder = Response.ok();
builder.entity(content.getContent());
builder.header("ReturnedDataPosition", content.getAt());
builder.header("ReturnedDataComplete", content.isComplete());
builder.header("CurrentLogFileSize", content.getLogFileSize());
response = builder.build();
} catch (Exception ex) {
LoggingUtils.logUnexpectedException(LOGGER, "Cannot get log file content: fromPosition={}, maxSize={}", ex, fromPosition, maxSize);
response = RestServiceUtil.handleException(ex);
}
result.computeStatus();
finishRequest(task);
return response;
}
// @GET
// @Path("tasks/{oid}")
// public Response getTaskByIdentifier(@PathParam("oid") String identifier) throws SchemaException, ObjectNotFoundException {
// OperationResult parentResult = new OperationResult("getTaskByIdentifier");
// PrismObject<TaskType> task = model.getTaskByIdentifier(identifier, null, parentResult);
//
// return Response.ok(task).build();
// }
//
//
// public boolean deactivateServiceThreads(long timeToWait, OperationResult parentResult) {
// return model.deactivateServiceThreads(timeToWait, parentResult);
// }
//
// public void reactivateServiceThreads(OperationResult parentResult) {
// model.reactivateServiceThreads(parentResult);
// }
//
// public boolean getServiceThreadsActivationState() {
// return model.getServiceThreadsActivationState();
// }
//
// public void stopSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) {
// model.stopSchedulers(nodeIdentifiers, parentResult);
// }
//
// public boolean stopSchedulersAndTasks(Collection<String> nodeIdentifiers, long waitTime, OperationResult parentResult) {
// return model.stopSchedulersAndTasks(nodeIdentifiers, waitTime, parentResult);
// }
//
// public void startSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) {
// model.startSchedulers(nodeIdentifiers, parentResult);
// }
//
// public void synchronizeTasks(OperationResult parentResult) {
// model.synchronizeTasks(parentResult);
// }
private void finishRequest(Task task) {
RestServiceUtil.finishRequest(task, securityHelper);
}
}