1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.client.console.panels;
20
21 import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal;
22 import java.io.Serializable;
23 import java.lang.reflect.Field;
24 import java.time.OffsetDateTime;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Date;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Optional;
32 import org.apache.commons.lang3.SerializationUtils;
33 import org.apache.commons.lang3.StringUtils;
34 import org.apache.commons.lang3.tuple.Pair;
35 import org.apache.syncope.client.console.PreferenceManager;
36 import org.apache.syncope.client.console.SyncopeConsoleSession;
37 import org.apache.syncope.client.console.SyncopeWebApplication;
38 import org.apache.syncope.client.console.audit.AuditHistoryModal;
39 import org.apache.syncope.client.console.commons.DirectoryDataProvider;
40 import org.apache.syncope.client.console.commons.IdRepoConstants;
41 import org.apache.syncope.client.console.commons.RealmsUtils;
42 import org.apache.syncope.client.console.commons.StatusProvider;
43 import org.apache.syncope.client.console.pages.Anys;
44 import org.apache.syncope.client.console.pages.BasePage;
45 import org.apache.syncope.client.console.rest.AuditRestClient;
46 import org.apache.syncope.client.console.rest.RealmRestClient;
47 import org.apache.syncope.client.console.rest.SchemaRestClient;
48 import org.apache.syncope.client.console.tasks.RealmPropagationTasks;
49 import org.apache.syncope.client.console.tasks.TemplatesTogglePanel;
50 import org.apache.syncope.client.console.wicket.extensions.markup.html.repeater.data.table.AttrColumn;
51 import org.apache.syncope.client.console.wicket.extensions.markup.html.repeater.data.table.BooleanPropertyColumn;
52 import org.apache.syncope.client.console.wicket.extensions.markup.html.repeater.data.table.DatePropertyColumn;
53 import org.apache.syncope.client.console.wicket.extensions.markup.html.repeater.data.table.KeyPropertyColumn;
54 import org.apache.syncope.client.console.wicket.markup.html.bootstrap.dialog.BaseModal;
55 import org.apache.syncope.client.console.wicket.markup.html.form.ActionLink;
56 import org.apache.syncope.client.console.wicket.markup.html.form.ActionsPanel;
57 import org.apache.syncope.client.console.wizards.any.ConnObjectPanel;
58 import org.apache.syncope.client.ui.commons.ConnIdSpecialName;
59 import org.apache.syncope.client.ui.commons.Constants;
60 import org.apache.syncope.client.ui.commons.status.StatusUtils;
61 import org.apache.syncope.client.ui.commons.wizards.AjaxWizard;
62 import org.apache.syncope.common.lib.SyncopeConstants;
63 import org.apache.syncope.common.lib.to.DerSchemaTO;
64 import org.apache.syncope.common.lib.to.PlainSchemaTO;
65 import org.apache.syncope.common.lib.to.PropagationStatus;
66 import org.apache.syncope.common.lib.to.ProvisioningResult;
67 import org.apache.syncope.common.lib.to.RealmTO;
68 import org.apache.syncope.common.lib.types.ExecStatus;
69 import org.apache.syncope.common.lib.types.IdRepoEntitlement;
70 import org.apache.syncope.common.lib.types.OpEvent;
71 import org.apache.syncope.common.lib.types.SchemaType;
72 import org.apache.syncope.common.rest.api.beans.RealmQuery;
73 import org.apache.wicket.Component;
74 import org.apache.wicket.PageReference;
75 import org.apache.wicket.ajax.AjaxRequestTarget;
76 import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy;
77 import org.apache.wicket.event.Broadcast;
78 import org.apache.wicket.event.IEvent;
79 import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
80 import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
81 import org.apache.wicket.markup.html.basic.Label;
82 import org.apache.wicket.markup.html.panel.Panel;
83 import org.apache.wicket.model.CompoundPropertyModel;
84 import org.apache.wicket.model.IModel;
85 import org.apache.wicket.model.Model;
86 import org.apache.wicket.model.ResourceModel;
87 import org.apache.wicket.model.StringResourceModel;
88 import org.apache.wicket.request.cycle.RequestCycle;
89 import org.apache.wicket.request.mapper.parameter.PageParameters;
90 import org.apache.wicket.spring.injection.annot.SpringBean;
91 import org.springframework.util.ReflectionUtils;
92
93 public class RealmDirectoryPanel
94 extends DirectoryPanel<RealmTO, RealmTO, RealmDirectoryPanel.RealmDataProvider, RealmRestClient> {
95
96 private static final long serialVersionUID = -619348700593732362L;
97
98 @SpringBean
99 protected SchemaRestClient schemaRestClient;
100
101 @SpringBean
102 protected AuditRestClient auditRestClient;
103
104 protected final List<PlainSchemaTO> plainSchemas = new ArrayList<>();
105
106 protected final List<DerSchemaTO> derSchemas = new ArrayList<>();
107
108 protected final BaseModal<Serializable> utilityModal = new BaseModal<>(Constants.OUTER);
109
110 protected final RealmWizardBuilder wizardBuilder;
111
112 protected final Model<String> base = Model.of(StringUtils.EMPTY);
113
114 protected final Model<String> fiql = Model.of(StringUtils.EMPTY);
115
116 public RealmDirectoryPanel(final String id, final RealmRestClient restClient, final PageReference pageRef) {
117 super(id, restClient, pageRef, true, true);
118
119 plainSchemas.addAll(schemaRestClient.getSchemas(SchemaType.PLAIN, null, new String[0]));
120 derSchemas.addAll(schemaRestClient.getSchemas(SchemaType.DERIVED, null, new String[0]));
121
122 disableCheckBoxes();
123 setShowResultPanel(true);
124
125 utilityModal.size(Modal.Size.Large);
126 addOuterObject(utilityModal);
127 setWindowClosedReloadCallback(utilityModal);
128
129 modal.size(Modal.Size.Large);
130 wizardBuilder = new RealmWizardBuilder(restClient, pageRef);
131 addNewItemPanelBuilder(wizardBuilder, true);
132 MetaDataRoleAuthorizationStrategy.authorize(addAjaxLink, RENDER, IdRepoEntitlement.REALM_CREATE);
133
134 initResultTable();
135 }
136
137 @Override
138 protected RealmDataProvider dataProvider() {
139 return new RealmDataProvider(rows);
140 }
141
142 public void search(final String base, final String fiql, final AjaxRequestTarget target) {
143 this.base.setObject(StringUtils.trimToEmpty(base));
144 this.fiql.setObject(StringUtils.trimToEmpty(fiql));
145 if (dataProvider != null) {
146 dataProvider.setBase(this.base.getObject());
147 dataProvider.setFIQL(this.fiql.getObject());
148 }
149 super.search(target);
150 }
151
152 public void search(final String fiql, final AjaxRequestTarget target) {
153 search(StringUtils.EMPTY, fiql, target);
154 }
155
156 @Override
157 protected String paginatorRowsKey() {
158 return IdRepoConstants.PREF_REALM_PAGINATOR_ROWS;
159 }
160
161 @Override
162 protected List<IColumn<RealmTO, String>> getColumns() {
163 List<IColumn<RealmTO, String>> columns = new ArrayList<>();
164 columns.add(new KeyPropertyColumn<>(
165 new ResourceModel(Constants.KEY_FIELD_NAME, Constants.KEY_FIELD_NAME), Constants.KEY_FIELD_NAME));
166
167 List<IColumn<RealmTO, String>> prefcolumns = new ArrayList<>();
168 PreferenceManager.getList(IdRepoConstants.PREF_REALM_DETAILS_VIEW).stream().
169 filter(name -> !Constants.KEY_FIELD_NAME.equalsIgnoreCase(name)).
170 forEach(name -> addPropertyColumn(
171 name,
172 ReflectionUtils.findField(RealmTO.class, name),
173 prefcolumns));
174
175 PreferenceManager.getList(IdRepoConstants.PREF_REALM_PLAIN_ATTRS_VIEW).stream().
176 map(a -> plainSchemas.stream().filter(p -> p.getKey().equals(a)).findFirst()).
177 flatMap(Optional::stream).
178 forEach(s -> prefcolumns.add(new AttrColumn<>(
179 s.getKey(), s.getLabel(SyncopeConsoleSession.get().getLocale()), SchemaType.PLAIN)));
180
181 PreferenceManager.getList(IdRepoConstants.PREF_REALM_DER_ATTRS_VIEW).stream().
182 map(a -> derSchemas.stream().filter(p -> p.getKey().equals(a)).findFirst()).
183 flatMap(Optional::stream).
184 forEach(s -> prefcolumns.add(new AttrColumn<>(
185 s.getKey(), s.getLabel(SyncopeConsoleSession.get().getLocale()), SchemaType.DERIVED)));
186
187
188 if (prefcolumns.isEmpty()) {
189 for (String name : RealmDisplayAttributesModalPanel.DEFAULT_COLUMNS) {
190 addPropertyColumn(
191 name,
192 ReflectionUtils.findField(RealmTO.class, name),
193 prefcolumns);
194 }
195
196 PreferenceManager.set(
197 IdRepoConstants.PREF_REALM_DETAILS_VIEW,
198 RealmDisplayAttributesModalPanel.DEFAULT_COLUMNS);
199 }
200
201 columns.addAll(prefcolumns);
202 return columns;
203 }
204
205 protected void addPropertyColumn(
206 final String name,
207 final Field field,
208 final List<IColumn<RealmTO, String>> columns) {
209
210 if (Constants.KEY_FIELD_NAME.equalsIgnoreCase(name)) {
211 columns.add(new KeyPropertyColumn<>(new ResourceModel(name, name), name, name));
212 } else if (field != null && !field.isSynthetic()
213 && (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class))) {
214
215 columns.add(new BooleanPropertyColumn<>(new ResourceModel(name, name), name, name));
216 } else if (field != null && !field.isSynthetic()
217 && (field.getType().equals(Date.class) || field.getType().equals(OffsetDateTime.class))) {
218
219 columns.add(new DatePropertyColumn<>(new ResourceModel(name, name), name, name));
220 } else {
221 columns.add(new PropertyColumn<>(new ResourceModel(name, name), name, name));
222 }
223 }
224
225 @Override
226 public ActionsPanel<Serializable> getHeader(final String componentId) {
227 final ActionsPanel<Serializable> panel = super.getHeader(componentId);
228 panel.add(new ActionLink<>() {
229
230 private static final long serialVersionUID = -8740543624521405980L;
231
232 @Override
233 public void onClick(final AjaxRequestTarget target, final Serializable ignore) {
234 target.add(displayAttributeModal.setContent(new RealmDisplayAttributesModalPanel<>(
235 displayAttributeModal,
236 page.getPageReference(),
237 RealmDisplayAttributesModalPanel.AVAILABLE_COLUMNS,
238 plainSchemas.stream().map(PlainSchemaTO::getKey).sorted().toList(),
239 derSchemas.stream().map(DerSchemaTO::getKey).sorted().toList())));
240 displayAttributeModal.header(new ResourceModel("any.attr.display"));
241 displayAttributeModal.show(true);
242 }
243 }, ActionLink.ActionType.CHANGE_VIEW, IdRepoEntitlement.REALM_SEARCH).hideLabel();
244 return panel;
245 }
246
247 @Override
248 protected Collection<ActionLink.ActionType> getBatches() {
249 return List.of();
250 }
251
252 @Override
253 public ActionsPanel<RealmTO> getActions(final IModel<RealmTO> model) {
254 ActionsPanel<RealmTO> panel = super.getActions(model);
255
256 panel.add(new ActionLink<>() {
257
258 private static final long serialVersionUID = 6459651989453003611L;
259
260 @Override
261 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
262 PageParameters parameters = new PageParameters();
263 parameters.add(Anys.INITIAL_REALM, realmTO.getFullPath());
264 setResponsePage(Anys.class, parameters);
265 }
266 }, ActionLink.ActionType.ZOOM_IN, IdRepoEntitlement.REALM_SEARCH, false).
267 setRealm(model.getObject().getFullPath());
268
269 panel.add(new ActionLink<>() {
270
271 private static final long serialVersionUID = 7596172676990094774L;
272
273 @Override
274 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
275 send(RealmDirectoryPanel.this, Broadcast.EXACT, new AjaxWizard.EditItemActionEvent<>(realmTO, target) {
276
277 @Override
278 public String getEventDescription() {
279 return "realm.edit";
280 }
281 });
282 }
283 }, ActionLink.ActionType.EDIT, IdRepoEntitlement.REALM_UPDATE, false).setRealm(model.getObject().getFullPath());
284
285 panel.add(new ActionLink<>() {
286
287 private static final long serialVersionUID = -4956983251621530095L;
288
289 @Override
290 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
291 wizardBuilder.setParentPath(realmTO.getFullPath());
292
293 send(RealmDirectoryPanel.this,
294 Broadcast.EXACT,
295 new AjaxWizard.NewItemActionEvent<>(new RealmTO(), target) {
296
297 @Override
298 public String getEventDescription() {
299 return "realm.new";
300 }
301 });
302 }
303
304 @Override
305 protected boolean statusCondition(final RealmTO realmTO) {
306 return StringUtils.isNotBlank(realmTO.getKey());
307 }
308 }, ActionLink.ActionType.CREATE, IdRepoEntitlement.REALM_CREATE, false)
309 .setRealm(model.getObject().getFullPath());
310
311 panel.add(new ActionLink<>() {
312
313 private static final long serialVersionUID = -6115685745909501940L;
314
315 @Override
316 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
317 target.add(utilityModal.setContent(new RealmPropagationTasks(
318 utilityModal, realmTO.getKey(), pageRef)));
319 utilityModal.header(new StringResourceModel("realm.propagation.tasks", model));
320 utilityModal.show(true);
321 }
322
323 @Override
324 protected boolean statusCondition(final RealmTO realmTO) {
325 return StringUtils.isNotBlank(realmTO.getKey());
326 }
327 }, ActionLink.ActionType.PROPAGATION_TASKS, IdRepoEntitlement.TASK_LIST)
328 .setRealm(model.getObject().getFullPath());
329
330 panel.add(new ActionLink<>() {
331
332 private static final long serialVersionUID = 6267403882972164669L;
333
334 @Override
335 public void onClick(final AjaxRequestTarget target, final RealmTO ignore) {
336 target.add(altDefaultModal.setContent(new AuditHistoryModal<>(
337 OpEvent.CategoryType.LOGIC,
338 "RealmLogic",
339 model.getObject(),
340 IdRepoEntitlement.REALM_UPDATE,
341 auditRestClient) {
342
343 private static final long serialVersionUID = -2209244156234833875L;
344
345 @Override
346 protected void restore(final String json, final AjaxRequestTarget target) {
347 try {
348 RealmTO updated = MAPPER.readValue(json, RealmTO.class);
349 ProvisioningResult<RealmTO> result = restClient.update(updated);
350 model.getObject().setFullPath(result.getEntity().getFullPath());
351 SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED));
352 target.add(container);
353 } catch (Exception e) {
354 LOG.error("While restoring realm {}", model.getObject().getKey(), e);
355 SyncopeConsoleSession.get().onException(e);
356 }
357 ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
358 }
359 }));
360
361 altDefaultModal.header(new StringResourceModel("realm.auditHistory.title", model));
362 altDefaultModal.show(true);
363 }
364 }, ActionLink.ActionType.VIEW_AUDIT_HISTORY,
365 "%s,%s".formatted(IdRepoEntitlement.REALM_UPDATE, IdRepoEntitlement.AUDIT_LIST)).
366 setRealm(model.getObject().getFullPath());
367
368 panel.add(new ActionLink<>() {
369
370 private static final long serialVersionUID = 6267403882972164669L;
371
372 @Override
373 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
374 actionTogglePanel.close(target);
375 send(RealmDirectoryPanel.this, Broadcast.BUBBLE,
376 new TemplatesTogglePanel.ShowTemplatesTogglePanelEvent(realmTO, target));
377 }
378 }, ActionLink.ActionType.TEMPLATE, IdRepoEntitlement.REALM_UPDATE).setRealm(model.getObject().getFullPath());
379
380 panel.add(new ActionLink<>() {
381
382 private static final long serialVersionUID = -8998343172643697605L;
383
384 @Override
385 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
386 RealmTO clone = SerializationUtils.clone(realmTO);
387 clone.setKey(null);
388 clone.setFullPath(null);
389 clone.setName(realmTO.getName() + "_clone");
390 clone.getActions().clear();
391
392 String parentPath = StringUtils.substringBeforeLast(
393 StringUtils.defaultString(realmTO.getFullPath()), "/");
394 wizardBuilder.setParentPath(StringUtils.isBlank(parentPath) ? "/" : parentPath);
395 send(RealmDirectoryPanel.this, Broadcast.EXACT, new AjaxWizard.NewItemActionEvent<>(clone, target) {
396
397 @Override
398 public String getEventDescription() {
399 return "realm.new";
400 }
401 });
402 }
403
404 @Override
405 protected boolean statusCondition(final RealmTO realmTO) {
406 return StringUtils.isNotBlank(realmTO.getKey()) && StringUtils.isNotBlank(realmTO.getFullPath());
407 }
408 }, ActionLink.ActionType.CLONE, IdRepoEntitlement.REALM_CREATE).setRealm(model.getObject().getFullPath());
409
410 panel.add(new ActionLink<>() {
411
412 private static final long serialVersionUID = 5649072994971851604L;
413
414 @Override
415 public void onClick(final AjaxRequestTarget target, final RealmTO realmTO) {
416 try {
417 restClient.delete(realmTO.getFullPath());
418 SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED));
419 target.add(container);
420 } catch (Exception e) {
421 LOG.error("While deleting realm {}", realmTO.getFullPath(), e);
422 SyncopeConsoleSession.get().onException(e);
423 }
424 ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
425 }
426
427 @Override
428 protected boolean statusCondition(final RealmTO realmTO) {
429 return StringUtils.isNotBlank(realmTO.getKey());
430 }
431 }, ActionLink.ActionType.DELETE, IdRepoEntitlement.REALM_DELETE, true)
432 .setRealm(model.getObject().getFullPath());
433
434 return panel;
435 }
436
437 @Override
438 protected Panel customResultBody(final String panelId, final RealmTO item, final Serializable result) {
439 if (!(result instanceof ProvisioningResult<?> provisioningResult)) {
440 throw new IllegalStateException("Unsupported result type");
441 }
442
443 MultilevelPanel mlp = new MultilevelPanel(panelId);
444 add(mlp);
445
446 PropagationStatus syncope = new PropagationStatus();
447 syncope.setStatus(ExecStatus.SUCCESS);
448 syncope.setResource(Constants.SYNCOPE);
449
450 List<PropagationStatus> propagations = new ArrayList<>();
451 propagations.add(syncope);
452 propagations.addAll(provisioningResult.getPropagationStatuses());
453
454 ListViewPanel.Builder<PropagationStatus> builder =
455 new ListViewPanel.Builder<>(PropagationStatus.class, pageRef) {
456
457 private static final long serialVersionUID = -6809736686861678498L;
458
459 @Override
460 protected Component getValueComponent(final String key, final PropagationStatus bean) {
461 if ("objectLink".equalsIgnoreCase(key)) {
462 String remoteId = Optional.ofNullable(bean.getAfterObj()).
463 flatMap(afterObj -> afterObj.getAttr(ConnIdSpecialName.NAME).
464 filter(s -> !s.getValues().isEmpty()).map(s -> s.getValues().getFirst())).
465 orElse(StringUtils.EMPTY);
466
467 return new Label("field", remoteId);
468 }
469
470 if ("status".equalsIgnoreCase(key)) {
471 return StatusUtils.getStatusImagePanel("field", bean.getStatus());
472 }
473
474 return super.getValueComponent(key, bean);
475 }
476 };
477
478 builder.setItems(propagations);
479
480 builder.includes("resource", "objectLink", "status");
481 builder.withChecks(ListViewPanel.CheckAvailability.NONE);
482 builder.setReuseItem(false);
483
484 ActionLink<PropagationStatus> connObjectLink = new ActionLink<>() {
485
486 private static final long serialVersionUID = -3722207913631435501L;
487
488 @Override
489 protected boolean statusCondition(final PropagationStatus bean) {
490 return !Constants.SYNCOPE.equals(bean.getResource())
491 && (ExecStatus.CREATED == bean.getStatus()
492 || ExecStatus.SUCCESS == bean.getStatus());
493 }
494
495 @Override
496 public void onClick(final AjaxRequestTarget target, final PropagationStatus status) {
497 mlp.next(status.getResource(), new RemoteRealmPanel(status), target);
498 }
499 };
500 SyncopeWebApplication.get().getStatusProvider().addConnObjectLink(builder, connObjectLink);
501
502 builder.addAction(new ActionLink<>() {
503
504 private static final long serialVersionUID = -3722207913631435501L;
505
506 @Override
507 protected boolean statusCondition(final PropagationStatus status) {
508 return StringUtils.isNotBlank(status.getFailureReason());
509 }
510
511 @Override
512 public void onClick(final AjaxRequestTarget target, final PropagationStatus status) {
513 mlp.next(status.getResource(), new PropagationErrorPanel(status.getFailureReason()), target);
514 }
515 }, ActionLink.ActionType.PROPAGATION_TASKS, StringUtils.EMPTY);
516
517 mlp.setFirstLevel(builder.build(MultilevelPanel.FIRST_LEVEL_ID));
518 return mlp;
519 }
520
521 protected static class RemoteRealmPanel extends RemoteObjectPanel {
522
523 private static final long serialVersionUID = 4303365227411467563L;
524
525 protected final PropagationStatus bean;
526
527 protected RemoteRealmPanel(final PropagationStatus bean) {
528 this.bean = bean;
529 add(new ConnObjectPanel(
530 REMOTE_OBJECT_PANEL_ID,
531 Pair.of(new ResourceModel("before"), new ResourceModel("after")),
532 getStatusProviderInfo(),
533 false));
534 }
535
536 @Override
537 protected StatusProvider.Info getStatusProviderInfo() {
538 return new StatusProvider.Info(bean.getBeforeObj(), bean.getAfterObj());
539 }
540 }
541
542 @Override
543 public void onEvent(final IEvent<?> event) {
544 if (event.getPayload() instanceof AjaxWizard.NewItemActionEvent<?> actionEvent
545 && actionEvent.getItem() == null) {
546 actionEvent.getTarget().ifPresent(target -> {
547 wizardBuilder.setParent(null);
548 wizardBuilder.setParentPath(StringUtils.isBlank(base.getObject())
549 ? SyncopeConstants.ROOT_REALM
550 : StringUtils.trim(base.getObject()));
551
552 send(this, Broadcast.EXACT, new AjaxWizard.NewItemActionEvent<RealmTO>(new RealmTO(), target) {
553
554 @Override
555 public String getEventDescription() {
556 return "realm.new";
557 }
558 });
559 });
560 return;
561 }
562
563 super.onEvent(event);
564 }
565
566 protected class RealmDataProvider extends DirectoryDataProvider<RealmTO> {
567
568 private static final long serialVersionUID = 2400683093229736283L;
569
570 protected String base;
571
572 protected String fiql;
573
574 protected int currentPage;
575
576 protected boolean searchErrorNotified;
577
578 RealmDataProvider(final int paginatorRows) {
579 super(paginatorRows);
580 base = RealmDirectoryPanel.this.base.getObject();
581 fiql = RealmDirectoryPanel.this.fiql.getObject();
582 }
583
584 void setBase(final String base) {
585 this.base = base;
586 this.searchErrorNotified = false;
587 }
588
589 void setFIQL(final String fiql) {
590 this.fiql = fiql;
591 this.searchErrorNotified = false;
592 }
593
594 @Override
595 public Iterator<RealmTO> iterator(final long first, final long count) {
596 try {
597 currentPage = ((int) first / paginatorRows);
598 if (currentPage < 0) {
599 currentPage = 0;
600 }
601
602 RealmQuery query = buildQuery();
603 query.setPage(currentPage + 1);
604 query.setSize((int) count);
605 if (getSort() != null && StringUtils.isNotBlank(getSort().getProperty())) {
606 query.setOrderBy(getSort().getProperty() + (getSort().isAscending() ? " ASC" : " DESC"));
607 }
608
609 Iterator<RealmTO> iterator = restClient.search(query).getResult().iterator();
610 searchErrorNotified = false;
611 return iterator;
612 } catch (Exception e) {
613 handleSearchException(e);
614 return Collections.emptyIterator();
615 }
616 }
617
618 @Override
619 public long size() {
620 try {
621 RealmQuery query = buildQuery();
622 query.setPage(1);
623 query.setSize(1);
624 long totalCount = restClient.search(query).getTotalCount();
625 searchErrorNotified = false;
626 return totalCount;
627 } catch (Exception e) {
628 handleSearchException(e);
629 return 0;
630 }
631 }
632
633 @Override
634 public IModel<RealmTO> model(final RealmTO object) {
635 return new CompoundPropertyModel<>(object);
636 }
637
638 protected RealmQuery buildQuery() {
639 RealmQuery query;
640 if (StringUtils.isBlank(base)) {
641 query = RealmsUtils.buildBaseQuery();
642 } else {
643 query = new RealmQuery.Builder().base(StringUtils.trim(base)).build();
644 }
645 if (StringUtils.isNotBlank(fiql)) {
646 query.setFiql(StringUtils.trim(fiql));
647 }
648 return query;
649 }
650
651 protected void handleSearchException(final Exception e) {
652 LOG.error("While searching realms with base {} and FIQL {}", base, fiql, e);
653 if (!searchErrorNotified) {
654 searchErrorNotified = true;
655 SyncopeConsoleSession.get().error(e.getMessage());
656 RequestCycle.get().find(AjaxRequestTarget.class)
657 .ifPresent(target -> ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target));
658 }
659 }
660 }
661 }