/
PageAdminFocus.java
1959 lines (1661 loc) · 67.9 KB
/
PageAdminFocus.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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010-2015 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.web.page.admin;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.model.api.context.EvaluatedAbstractRole;
import com.evolveum.midpoint.model.api.context.EvaluatedAssignment;
import com.evolveum.midpoint.model.api.context.EvaluatedConstruction;
import com.evolveum.midpoint.model.api.context.ModelContext;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.path.ItemPathSegment;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.RetrieveOption;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.AjaxSubmitButton;
import com.evolveum.midpoint.web.component.FocusSummaryPanel;
import com.evolveum.midpoint.web.component.TabbedPanel;
import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto;
import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDtoType;
import com.evolveum.midpoint.web.component.assignment.AssignmentEditorPanel;
import com.evolveum.midpoint.web.component.data.TablePanel;
import com.evolveum.midpoint.web.component.dialog.ConfirmationDialog;
import com.evolveum.midpoint.web.component.form.Form;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenu;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction;
import com.evolveum.midpoint.web.component.prism.*;
import com.evolveum.midpoint.web.component.progress.ProgressReporter;
import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage;
import com.evolveum.midpoint.web.component.util.LoadableModel;
import com.evolveum.midpoint.web.component.util.ObjectWrapperUtil;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.server.PageTasks;
import com.evolveum.midpoint.web.page.admin.server.dto.TaskDto;
import com.evolveum.midpoint.web.page.admin.server.dto.TaskDtoProvider;
import com.evolveum.midpoint.web.page.admin.server.dto.TaskDtoProviderOptions;
import com.evolveum.midpoint.web.page.admin.users.component.*;
import com.evolveum.midpoint.web.page.admin.users.dto.FocusProjectionDto;
import com.evolveum.midpoint.web.page.admin.users.dto.SimpleUserResourceProvider;
import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus;
import com.evolveum.midpoint.web.resource.img.ImgResources;
import com.evolveum.midpoint.web.security.MidPointApplication;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.web.util.WebModelUtils;
import com.evolveum.midpoint.web.util.validation.MidpointFormValidator;
import com.evolveum.midpoint.web.util.validation.SimpleValidationError;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.util.string.StringValue;
import javax.xml.namespace.QName;
import java.io.Serializable;
import java.util.*;
public abstract class PageAdminFocus<T extends FocusType> extends PageAdmin
implements ProgressReportingAwarePage {
public static final String AUTH_USERS_ALL = AuthorizationConstants.AUTZ_UI_USERS_ALL_URL;
public static final String AUTH_USERS_ALL_LABEL = "PageAdminUsers.auth.usersAll.label";
public static final String AUTH_USERS_ALL_DESCRIPTION = "PageAdminUsers.auth.usersAll.description";
public static final String AUTH_ORG_ALL = AuthorizationConstants.AUTZ_UI_ORG_ALL_URL;
public static final String AUTH_ORG_ALL_LABEL = "PageAdminUsers.auth.orgAll.label";
public static final String AUTH_ORG_ALL_DESCRIPTION = "PageAdminUsers.auth.orgAll.description";
private LoadableModel<ObjectWrapper<T>> focusModel;
private LoadableModel<List<FocusProjectionDto>> shadowModel;
private LoadableModel<List<FocusProjectionDto>> orgModel;
private LoadableModel<List<AssignmentEditorDto>> assignmentsModel;
private ProgressReporter progressReporter;
private static final String DOT_CLASS = PageAdminFocus.class.getName() + ".";
private static final String OPERATION_LOAD_FOCUS = DOT_CLASS + "loadFocus";
private static final String OPERATION_LOAD_PARENT_ORGS = DOT_CLASS + "loadParentOrgs";
private static final String OPERATION_LOAD_ASSIGNMENTS = DOT_CLASS + "loadAssignments";
private static final String OPERATION_LOAD_ASSIGNMENT = DOT_CLASS + "loadAssignment";
private static final String OPERATION_SAVE = DOT_CLASS + "save";
private static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit";
// private static final String OPERATION_MODIFY_ACCOUNT = DOT_CLASS + "modifyAccount";
// private static final String OPERATION_PREPARE_ACCOUNTS = DOT_CLASS + "getAccountsForSubmit";
private static final String OPERATION_RECOMPUTE_ASSIGNMENTS = DOT_CLASS + "recomputeAssignments";
private static final String OPERATION_LOAD_SHADOW = DOT_CLASS + "loadShadow";
protected static final String ID_MAIN_FORM = "mainForm";
private static final String ID_TAB_PANEL = "tabPanel";
private static final String ID_ASSIGNMENT_EDITOR = "assignmentEditor";
private static final String ID_ASSIGNMENT_LIST = "assignmentList";
private static final String ID_TASK_TABLE = "taskTable";
private static final String ID_EXECUTE_OPTIONS = "executeOptions";
private static final String ID_SHADOW_LIST = "shadowList";
private static final String ID_SHADOWS = "shadows";
private static final String ID_ASSIGNMENTS = "assignments";
private static final String ID_SHADOW_MENU = "shadowMenu";
private static final String ID_ASSIGNMENT_MENU = "assignmentMenu";
private static final String ID_SHADOW_CHECK_ALL = "shadowCheckAll";
private static final String ID_ASSIGNMENT_CHECK_ALL = "assignmentCheckAll";
protected static final String ID_SUMMARY_PANEL = "summaryPanel";
private static final String MODAL_ID_CONFIRM_DELETE_SHADOW = "confirmDeleteShadowPopup";
private static final String MODAL_ID_CONFIRM_DELETE_ASSIGNMENT = "confirmDeleteAssignmentPopup";
private static final Trace LOGGER = TraceManager.getTrace(PageAdminFocus.class);
// used to determine whether to leave this page or stay on it (after
// operation finishing)
private ObjectDelta delta;
private LoadableModel<ExecuteChangeOptionsDto> executeOptionsModel = new LoadableModel<ExecuteChangeOptionsDto>(
false) {
@Override
protected ExecuteChangeOptionsDto load() {
return new ExecuteChangeOptionsDto();
}
};
@Override
protected IModel<String> createPageTitleModel() {
return new LoadableModel<String>() {
@Override
protected String load() {
if (!isEditingFocus()) {
return createStringResource("pageAdminFocus.title.newFocusType").getObject();
}
return createStringResource("pageAdminFocus.title.editFocusType").getObject();
}
};
}
@Override
protected IModel<String> createPageSubTitleModel() {
return new LoadableModel<String>() {
@Override
protected String load() {
if (!isEditingFocus()) {
return createStringResource(
"pageAdminFocus.subTitle.new" + getCompileTimeClass().getSimpleName())
.getObject();
}
String name = null;
if (getFocusWrapper() != null && getFocusWrapper().getObject() != null) {
name = WebMiscUtil.getName(getFocusWrapper().getObject());
}
return createStringResource(
"pageAdminFocus.subTitle.edit" + getCompileTimeClass().getSimpleName(), name)
.getObject();
}
};
}
public LoadableModel<ObjectWrapper<T>> getFocusModel() {
return focusModel;
}
public void initialize(final PrismObject<T> userToEdit) {
try {
focusModel = new LoadableModel<ObjectWrapper<T>>(false) {
@Override
protected ObjectWrapper<T> load() {
return loadFocusWrapper(userToEdit);
}
};
shadowModel = new LoadableModel<List<FocusProjectionDto>>(false) {
@Override
protected List<FocusProjectionDto> load() {
return loadShadowWrappers();
}
};
orgModel = new LoadableModel<List<FocusProjectionDto>>(false) {
@Override
protected List<FocusProjectionDto> load() {
return loadOrgWrappers();
}
};
assignmentsModel = new LoadableModel<List<AssignmentEditorDto>>(false) {
@Override
protected List<AssignmentEditorDto> load() {
return loadAssignments();
}
};
performCustomInitialization();
initLayout();
LOGGER.trace("Page {} initialized", this);
} catch (Exception e) {
LoggingUtils.logException(LOGGER, "Error initializing page "+this, e);
}
}
protected void performCustomInitialization() {
}
protected abstract T createNewFocus();
protected void initCustomLayout(Form mainForm) {
// Nothing to do here
}
protected void initSummaryPanel(Form mainForm) {
FocusSummaryPanel<T> summaryPanel = createSummaryPanel();
summaryPanel.setOutputMarkupId(true);
summaryPanel.add(new VisibleEnableBehaviour() {
@Override
public boolean isVisible() {
return isEditingFocus();
}
});
mainForm.add(summaryPanel);
}
protected abstract FocusSummaryPanel<T> createSummaryPanel();
protected abstract void initTabs(List<ITab> tabs);
private void initLayout() {
final Form mainForm = new Form(ID_MAIN_FORM, true);
mainForm.setMaxSize(MidPointApplication.FOCUS_PHOTO_MAX_FILE_SIZE);
mainForm.setMultiPart(true);
add(mainForm);
progressReporter = ProgressReporter.create(this, mainForm, "progressPanel");
// PrismObjectPanel userForm = new PrismObjectPanel(ID_FOCUS_FORM,
// focusModel, new PackageResourceReference(
// ImgResources.class, ImgResources.USER_PRISM), mainForm, this) {
//
// @Override
// protected IModel<String> createDescription(IModel<ObjectWrapper>
// model) {
// return createStringResource("pageAdminFocus.description");
// }
// };
// mainForm.add(userForm);
List<ITab> tabs = new ArrayList<>();
tabs.add(new AbstractTab(createStringResource("pageAdminFocus.basic")) {
@Override
public WebMarkupContainer getPanel(String panelId) {
return new BaseFocusPanel<T>(panelId, mainForm, focusModel, shadowModel, orgModel, assignmentsModel,
PageAdminFocus.this) {
@Override
protected T createNewFocus() {
return PageAdminFocus.this.createNewFocus();
}
@Override
protected void reviveCustomModels() throws SchemaException {
PageAdminFocus.this.reviveCustomModels();
}
@Override
protected Class<T> getCompileTimeClass() {
return PageAdminFocus.this.getCompileTimeClass();
}
@Override
protected Class getRestartResponsePage() {
return PageAdminFocus.this.getRestartResponsePage();
}
};
}
});
initTabs(tabs);
TabbedPanel focusTabPanel = new TabbedPanel(ID_TAB_PANEL, tabs) {
@Override
protected WebMarkupContainer newLink(String linkId, final int index) {
return new AjaxSubmitLink(linkId) {
@Override
protected void onError(AjaxRequestTarget target,
org.apache.wicket.markup.html.form.Form<?> form) {
super.onError(target, form);
target.add(getFeedbackPanel());
}
@Override
protected void onSubmit(AjaxRequestTarget target,
org.apache.wicket.markup.html.form.Form<?> form) {
super.onSubmit(target, form);
setSelectedTab(index);
if (target != null) {
target.add(findParent(TabbedPanel.class));
}
}
};
}
};
focusTabPanel.setOutputMarkupId(true);
mainForm.add(focusTabPanel);
// WebMarkupContainer shadows = new WebMarkupContainer(ID_SHADOWS);
// shadows.setOutputMarkupId(true);
// mainForm.add(shadows);
// initShadows(shadows);
//
// WebMarkupContainer assignments = new
// WebMarkupContainer(ID_ASSIGNMENTS);
// assignments.setOutputMarkupId(true);
// mainForm.add(assignments);
// initAssignments(assignments);
//
// WebMarkupContainer tasks = new WebMarkupContainer(ID_TASKS);
// tasks.setOutputMarkupId(true);
// mainForm.add(tasks);
// initTasks(tasks);
//
initButtons(mainForm);
initOptions(mainForm);
initSummaryPanel(mainForm);
initCustomLayout(mainForm);
//
// initResourceModal();
// initAssignableModal();
// initConfirmationDialogs();
//
// initCustomLayout(mainForm);
}
public ObjectWrapper getFocusWrapper() {
return focusModel.getObject();
}
public List<FocusProjectionDto> getFocusShadows() {
return shadowModel.getObject();
}
public List<FocusProjectionDto> getFocusOrgs() {
return orgModel.getObject();
}
public List<AssignmentEditorDto> getFocusAssignments() {
return assignmentsModel.getObject();
}
protected void reviveCustomModels() throws SchemaException {
// Nothing to do here;
}
protected void reviveModels() throws SchemaException {
WebMiscUtil.revive(focusModel, getPrismContext());
WebMiscUtil.revive(shadowModel, getPrismContext());
WebMiscUtil.revive(assignmentsModel, getPrismContext());
reviveCustomModels();
}
protected abstract Class<T> getCompileTimeClass();
protected abstract Class getRestartResponsePage();
protected String getFocusOidParameter() {
PageParameters parameters = getPageParameters();
LOGGER.trace("Page parameters: {}", parameters);
StringValue oidValue = getPageParameters().get(OnePageParameterEncoder.PARAMETER);
LOGGER.trace("OID parameter: {}", oidValue);
if (oidValue == null) {
return null;
}
String oid = oidValue.toString();
if (StringUtils.isBlank(oid)) {
return null;
}
return oid;
}
public boolean isEditingFocus() {
return getFocusOidParameter() != null;
}
protected ObjectWrapper<T> loadFocusWrapper(PrismObject<T> userToEdit) {
Task task = createSimpleTask(OPERATION_LOAD_FOCUS);
OperationResult result = task.getResult();
PrismObject<T> focus = null;
try {
if (!isEditingFocus()) {
if (userToEdit == null) {
LOGGER.trace("Loading focus: New focus (creating)");
// UserType userType = new UserType();'
T focusType = createNewFocus();
getMidpointApplication().getPrismContext().adopt(focusType);
focus = focusType.asPrismObject();
} else {
LOGGER.trace("Loading focus: New focus (supplied): {}", userToEdit);
focus = userToEdit;
}
} else {
Collection options = SelectorOptions.createCollection(UserType.F_JPEG_PHOTO,
GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
String focusOid = getFocusOidParameter();
focus = WebModelUtils.loadObject(getCompileTimeClass(), focusOid, options, this, task,
result);
LOGGER.trace("Loading focus: Existing focus (loadled): {} -> {}", focusOid, focus);
}
result.recordSuccess();
} catch (Exception ex) {
result.recordFatalError("Couldn't get focus.", ex);
LoggingUtils.logException(LOGGER, "Couldn't load focus", ex);
}
if (!result.isSuccess()) {
showResultInSession(result);
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Loaded focus:\n{}", focus.debugDump());
}
if (focus == null) {
if (isEditingFocus()) {
getSession().error(getString("pageAdminFocus.message.cantEditFocus"));
} else {
getSession().error(getString("pageAdminFocus.message.cantNewFocus"));
}
throw new RestartResponseException(getRestartResponsePage());
}
ContainerStatus status = isEditingFocus() ? ContainerStatus.MODIFYING : ContainerStatus.ADDING;
ObjectWrapper<T> wrapper = null;
try {
wrapper = ObjectWrapperUtil.createObjectWrapper("pageAdminFocus.focusDetails", null, focus,
status, this);
} catch (Exception ex) {
result.recordFatalError("Couldn't get user.", ex);
LoggingUtils.logException(LOGGER, "Couldn't load user", ex);
wrapper = new ObjectWrapper<>("pageAdminFocus.focusDetails", null, focus, null, status, this);
}
// ObjectWrapper wrapper = new ObjectWrapper("pageUser.userDetails",
// null, user, status);
if (wrapper.getResult() != null && !WebMiscUtil.isSuccessOrHandledError(wrapper.getResult())) {
showResultInSession(wrapper.getResult());
}
loadParentOrgs(wrapper, task, result);
wrapper.setShowEmpty(!isEditingFocus());
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump());
}
return wrapper;
}
private void loadParentOrgs(ObjectWrapper<T> wrapper, Task task, OperationResult result) {
OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS);
PrismObject<T> focus = wrapper.getObject();
// Load parent organizations (full objects). There are used in the
// summary panel and also in the main form.
// Do it here explicitly instead of using resolve option to have ability
// to better handle (ignore) errors.
for (ObjectReferenceType parentOrgRef : focus.asObjectable().getParentOrgRef()) {
PrismObject<OrgType> parentOrg = null;
try {
parentOrg = getModelService().getObject(OrgType.class, parentOrgRef.getOid(), null, task,
subResult);
LOGGER.trace("Loaded parent org with result {}",
new Object[] { subResult.getLastSubresult() });
} catch (AuthorizationException e) {
// This can happen if the user has permission to read parentOrgRef but it does not have
// the permission to read target org
// It is OK to just ignore it.
subResult.muteLastSubresultError();
LOGGER.debug("User {} does not have permission to read parent org unit {} (ignoring error)", task.getOwner().getName(), parentOrgRef.getOid());
} catch (Exception ex) {
subResult.recordWarning("Cannot load parent org " + parentOrgRef.getOid(), ex);
LOGGER.warn("Cannot load parent org {}: {}", parentOrgRef.getOid(), ex.getMessage(), ex);
}
if (parentOrg != null) {
wrapper.getParentOrgs().add(parentOrg);
}
}
subResult.computeStatus();
}
// protected void finishProcessing(ObjectDelta objectDelta,
// AjaxRequestTarget target, OperationResult result){
// delta = objectDelta;
// finishProcessing(target, result);
// }
public Object findParam(String param, String oid, OperationResult result) {
Object object = null;
for (OperationResult subResult : result.getSubresults()) {
if (subResult != null && subResult.getParams() != null) {
if (subResult.getParams().get(param) != null
&& subResult.getParams().get(OperationResult.PARAM_OID) != null
&& subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) {
return subResult.getParams().get(param);
}
object = findParam(param, oid, subResult);
}
}
return object;
}
@Override
public void finishProcessing(AjaxRequestTarget target, OperationResult result) {
boolean userAdded = delta != null && delta.isAdd() && StringUtils.isNotEmpty(delta.getOid());
if (!executeOptionsModel.getObject().isKeepDisplayingResults() && progressReporter.isAllSuccess()
&& (userAdded || !result.isFatalError())) { // TODO
showResultInSession(result);
// todo refactor this...what is this for? why it's using some
// "shadow" param from result???
PrismObject<T> focus = getFocusWrapper().getObject();
T focusType = focus.asObjectable();
for (ObjectReferenceType ref : focusType.getLinkRef()) {
Object o = findParam("shadow", ref.getOid(), result);
if (o != null && o instanceof ShadowType) {
ShadowType accountType = (ShadowType) o;
OperationResultType fetchResult = accountType.getFetchResult();
if (fetchResult != null
&& !OperationResultStatusType.SUCCESS.equals(fetchResult.getStatus())) {
showResultInSession(OperationResult.createOperationResult(fetchResult));
}
}
}
setSpecificResponsePage();
} else {
showResult(result);
target.add(getFeedbackPanel());
// if we only stayed on the page because of displaying results, hide
// the Save button
// (the content of the page might not be consistent with reality,
// e.g. concerning the accounts part...
// this page was not created with the repeated save possibility in
// mind)
if (userAdded || !result.isFatalError()) {
progressReporter.hideSaveButton(target);
}
}
}
private List<FocusProjectionDto> loadShadowWrappers() {
return loadProjectionWrappers(ShadowType.class, UserType.F_LINK_REF);
}
private List<FocusProjectionDto> loadOrgWrappers() {
return loadProjectionWrappers(OrgType.class, UserType.F_PARENT_ORG_REF);
}
private <P extends ObjectType> List<FocusProjectionDto> loadProjectionWrappers(Class<P> type,
QName propertyToLoad) {
List<FocusProjectionDto> list = new ArrayList<FocusProjectionDto>();
ObjectWrapper focus = focusModel.getObject();
PrismObject<T> prismUser = focus.getObject();
PrismReference prismReference = prismUser.findReference(new ItemPath(propertyToLoad));
if (prismReference == null) {
return new ArrayList<>();
}
List<PrismReferenceValue> references = prismReference.getValues();
Task task = createSimpleTask(OPERATION_LOAD_SHADOW);
for (PrismReferenceValue reference : references) {
OperationResult subResult = new OperationResult(OPERATION_LOAD_SHADOW);
String resourceName = null;
try {
Collection<SelectorOptions<GetOperationOptions>> options = null;
if (ShadowType.class.equals(type)) {
options = SelectorOptions.createCollection(ShadowType.F_RESOURCE,
GetOperationOptions.createResolve());
}
if (reference.getOid() == null) {
continue;
}
PrismObject<P> projection = WebModelUtils.loadObject(type, reference.getOid(), options, this,
task, subResult);
if (projection == null) {
// No access, just skip it
continue;
}
P projectionType = projection.asObjectable();
OperationResultType fetchResult = projectionType.getFetchResult();
StringBuilder description = new StringBuilder();
if (ShadowType.class.equals(type)) {
ShadowType shadowType = (ShadowType) projectionType;
ResourceType resource = shadowType.getResource();
resourceName = WebMiscUtil.getName(resource);
if (shadowType.getIntent() != null) {
description.append(shadowType.getIntent()).append(", ");
}
} else if (OrgType.class.equals(type)) {
OrgType orgType = (OrgType) projectionType;
resourceName = orgType.getDisplayName() != null
? WebMiscUtil.getOrigStringFromPoly(orgType.getDisplayName()) : "";
}
description.append(WebMiscUtil.getOrigStringFromPoly(projectionType.getName()));
ObjectWrapper wrapper = ObjectWrapperUtil.createObjectWrapper(resourceName,
description.toString(), projection, ContainerStatus.MODIFYING, true, this);
wrapper.setFetchResult(OperationResult.createOperationResult(fetchResult));
wrapper.setSelectable(true);
wrapper.setMinimalized(true);
if (ShadowType.class.equals(type)) {
PrismContainer<ShadowAssociationType> associationContainer = projection
.findContainer(ShadowType.F_ASSOCIATION);
if (associationContainer != null && associationContainer.getValues() != null) {
List<PrismContainerValue<ShadowAssociationType>> associations = new ArrayList<>(
associationContainer.getValues().size());
for (PrismContainerValue<ShadowAssociationType> associationVal : associationContainer.getValues()) {
ShadowAssociationType associationType = (ShadowAssociationType) associationVal
.asContainerable();
ObjectReferenceType shadowRef = associationType.getShadowRef();
// shadowRef can be null in case of "broken"
// associations we can safely eliminate fetching
// from resource, because we need only the name
if (shadowRef != null) {
PrismObject<ShadowType> associationTargetShadow = getModelService().getObject(ShadowType.class,
shadowRef.getOid(), SelectorOptions.createCollection(GetOperationOptions.createNoFetch()),
task, subResult);
shadowRef.asReferenceValue().setObject(associationTargetShadow);
associations.add(associationVal);
}
}
wrapper.setAssociations(associations);
}
}
wrapper.initializeContainers(this);
list.add(new FocusProjectionDto(wrapper, UserDtoStatus.MODIFY));
subResult.recomputeStatus();
} catch (ObjectNotFoundException ex) {
// this is fix for MID-854, full user/accounts/assignments
// reload if accountRef reference is broken
// because consistency already fixed it.
focusModel.reset();
shadowModel.reset();
orgModel.reset();
assignmentsModel.reset();
} catch (Exception ex) {
subResult.recordFatalError("Couldn't load account." + ex.getMessage(), ex);
LoggingUtils.logException(LOGGER, "Couldn't load account", ex);
list.add(new FocusProjectionDto(false, resourceName, subResult));
} finally {
subResult.computeStatus();
}
}
return list;
}
private List<AssignmentEditorDto> loadAssignments() {
List<AssignmentEditorDto> list = new ArrayList<AssignmentEditorDto>();
OperationResult result = new OperationResult(OPERATION_LOAD_ASSIGNMENTS);
ObjectWrapper focusWrapper = focusModel.getObject();
PrismObject<T> focus = focusWrapper.getObject();
List<AssignmentType> assignments = focus.asObjectable().getAssignment();
for (AssignmentType assignment : assignments) {
list.add(new AssignmentEditorDto(UserDtoStatus.MODIFY, assignment, this));
}
Collections.sort(list);
return list;
}
private PrismObject getReference(ObjectReferenceType ref, OperationResult result) {
OperationResult subResult = result.createSubresult(OPERATION_LOAD_ASSIGNMENT);
subResult.addParam("targetRef", ref.getOid());
PrismObject target = null;
try {
Task task = createSimpleTask(OPERATION_LOAD_ASSIGNMENT);
Class type = ObjectType.class;
if (ref.getType() != null) {
type = getPrismContext().getSchemaRegistry().determineCompileTimeClass(ref.getType());
}
target = getModelService().getObject(type, ref.getOid(), null, task, subResult);
subResult.recordSuccess();
} catch (Exception ex) {
LoggingUtils.logException(LOGGER, "Couldn't get assignment target ref", ex);
subResult.recordFatalError("Couldn't get assignment target ref.", ex);
}
if (!subResult.isHandledError() && !subResult.isSuccess()) {
showResult(subResult);
}
return target;
}
protected void savePerformed(AjaxRequestTarget target) {
LOGGER.debug("Save focus.");
OperationResult result = new OperationResult(OPERATION_SAVE);
ObjectWrapper userWrapper = getFocusWrapper();
// todo: improve, delta variable is quickfix for MID-1006
// redirecting to user list page everytime user is created in repository
// during user add in gui,
// and we're not taking care about account/assignment create errors
// (error message is still displayed)
delta = null;
Task task = createSimpleTask(OPERATION_SEND_TO_SUBMIT);
ExecuteChangeOptionsDto executeOptions = executeOptionsModel.getObject();
ModelExecuteOptions options = executeOptions.createOptions();
LOGGER.debug("Using options {}.", new Object[] { executeOptions });
try {
reviveModels();
delta = userWrapper.getObjectDelta();
if (userWrapper.getOldDelta() != null) {
delta = ObjectDelta.summarize(userWrapper.getOldDelta(), delta);
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) });
}
} catch (Exception ex) {
result.recordFatalError(getString("pageUser.message.cantCreateUser"), ex);
LoggingUtils.logException(LOGGER, "Create user failed", ex);
showResult(result);
return;
}
switch (userWrapper.getStatus()) {
case ADDING:
try {
PrismObject<T> focus = delta.getObjectToAdd();
WebMiscUtil.encryptCredentials(focus, true, getMidpointApplication());
prepareFocusForAdd(focus);
getPrismContext().adopt(focus, getCompileTimeClass());
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) });
}
if (!delta.isEmpty()) {
delta.revive(getPrismContext());
Collection<SimpleValidationError> validationErrors = performCustomValidation(focus,
WebMiscUtil.createDeltaCollection(delta));
if (validationErrors != null && !validationErrors.isEmpty()) {
for (SimpleValidationError error : validationErrors) {
LOGGER.error("Validation error, attribute: '" + error.printAttribute()
+ "', message: '" + error.getMessage() + "'.");
error("Validation error, attribute: '" + error.printAttribute()
+ "', message: '" + error.getMessage() + "'.");
}
target.add(getFeedbackPanel());
return;
}
progressReporter.executeChanges(WebMiscUtil.createDeltaCollection(delta), options,
task, result, target);
} else {
result.recordSuccess();
}
} catch (Exception ex) {
result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex);
LoggingUtils.logException(LOGGER, "Create user failed", ex);
}
break;
case MODIFYING:
try {
WebMiscUtil.encryptCredentials(delta, true, getMidpointApplication());
prepareFocusDeltaForModify(delta);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) });
}
List<ObjectDelta<? extends ObjectType>> accountDeltas = modifyShadows(result);
Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>();
if (!delta.isEmpty()) {
delta.revive(getPrismContext());
deltas.add(delta);
}
for (ObjectDelta accDelta : accountDeltas) {
if (!accDelta.isEmpty()) {
// accDelta.setPrismContext(getPrismContext());
accDelta.revive(getPrismContext());
deltas.add(accDelta);
}
}
if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) {
ObjectDelta emptyDelta = ObjectDelta.createEmptyModifyDelta(getCompileTimeClass(),
userWrapper.getObject().getOid(), getPrismContext());
deltas.add(emptyDelta);
Collection<SimpleValidationError> validationErrors = performCustomValidation(null,
deltas);
if (validationErrors != null && !validationErrors.isEmpty()) {
for (SimpleValidationError error : validationErrors) {
LOGGER.error("Validation error, attribute: '" + error.printAttribute()
+ "', message: '" + error.getMessage() + "'.");
error("Validation error, attribute: '" + error.printAttribute()
+ "', message: '" + error.getMessage() + "'.");
}
target.add(getFeedbackPanel());
return;
}
progressReporter.executeChanges(deltas, options, task, result, target);
} else if (!deltas.isEmpty()) {
Collection<SimpleValidationError> validationErrors = performCustomValidation(null,
deltas);
if (validationErrors != null && !validationErrors.isEmpty()) {
for (SimpleValidationError error : validationErrors) {
LOGGER.error("Validation error, attribute: '" + error.printAttribute()
+ "', message: '" + error.getMessage() + "'.");
error("Validation error, attribute: '" + error.printAttribute()
+ "', message: '" + error.getMessage() + "'.");
}
target.add(getFeedbackPanel());
return;
}
progressReporter.executeChanges(deltas, options, task, result, target);
} else {
LOGGER.debug("Skipping modification because deltas are empty");
result.recordSuccess();
}
} catch (Exception ex) {
if (!executeForceDelete(userWrapper, task, options, result)) {
result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex);
LoggingUtils.logException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex);
} else {
result.recomputeStatus();
}
}
break;
// support for add/delete containers (e.g. delete credentials)
default:
error(getString("pageAdminFocus.message.unsupportedState", userWrapper.getStatus()));
}
result.recomputeStatus();
if (!result.isInProgress()) {
finishProcessing(target, result);
}
}
private boolean executeForceDelete(ObjectWrapper userWrapper, Task task, ModelExecuteOptions options,
OperationResult parentResult) {
if (executeOptionsModel.getObject().isForce()) {
OperationResult result = parentResult.createSubresult("Force delete operation");
// List<UserAccountDto> accountDtos = accountsModel.getObject();
// List<ReferenceDelta> refDeltas = new ArrayList<ReferenceDelta>();
// ObjectDelta<UserType> forceDeleteDelta = null;
// for (UserAccountDto accDto : accountDtos) {
// if (accDto.getStatus() == UserDtoStatus.DELETE) {
// ObjectWrapper accWrapper = accDto.getObject();
// ReferenceDelta refDelta =
// ReferenceDelta.createModificationDelete(UserType.F_ACCOUNT_REF,
// userWrapper.getObject().getDefinition(), accWrapper.getObject());
// refDeltas.add(refDelta);
// }
// }
// if (!refDeltas.isEmpty()) {
// forceDeleteDelta =
// ObjectDelta.createModifyDelta(userWrapper.getObject().getOid(),
// refDeltas,
// UserType.class, getPrismContext());
// }
// PrismContainerDefinition def =
// userWrapper.getObject().findContainer(UserType.F_ASSIGNMENT).getDefinition();
// if (forceDeleteDelta == null) {
// forceDeleteDelta =
// ObjectDelta.createEmptyModifyDelta(UserType.class,
// userWrapper.getObject().getOid(),
// getPrismContext());
// }
try {
ObjectDelta<UserType> forceDeleteDelta = getChange(userWrapper);
forceDeleteDelta.revive(getPrismContext());
if (forceDeleteDelta != null && !forceDeleteDelta.isEmpty()) {
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(forceDeleteDelta),
options, task, result);
}
} catch (Exception ex) {
result.recordFatalError("Failed to execute delete operation with force.");
LoggingUtils.logException(LOGGER, "Failed to execute delete operation with force", ex);
return false;
}
result.recomputeStatus();
result.recordSuccessIfUnknown();
return true;
}
return false;
}
private ObjectDelta getChange(ObjectWrapper focusWrapper) throws SchemaException {
List<FocusProjectionDto> accountDtos = getFocusShadows();
List<ReferenceDelta> refDeltas = new ArrayList<ReferenceDelta>();
ObjectDelta<T> forceDeleteDelta = null;
for (FocusProjectionDto accDto : accountDtos) {
if (!accDto.isLoadedOK()) {
continue;
}