Example usage for org.apache.commons.lang3.tuple Pair getValue

List of usage examples for org.apache.commons.lang3.tuple Pair getValue

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getValue.

Prototype

@Override
public R getValue() 

Source Link

Document

Gets the value from this pair.

This method implements the Map.Entry interface returning the right element as the value.

Usage

From source file:org.apache.syncope.client.console.panels.LoggerCategoryPanel.java

public LoggerCategoryPanel(final String id, final List<EventCategoryTO> eventCategoryTOs,
        final IModel<List<String>> model, final PageReference pageReference, final String pageId) {
    super(id);//from   w  w  w  .  j av  a 2s  .c om

    this.model = model;
    selectedEventsPanel = new SelectedEventsPanel("selectedEventsPanel", model);
    add(selectedEventsPanel);

    this.eventCategoryTOs = eventCategoryTOs;

    categoryContainer = new WebMarkupContainer("categoryContainer");
    categoryContainer.setOutputMarkupId(true);
    add(categoryContainer);

    eventsContainer = new WebMarkupContainer("eventsContainer");
    eventsContainer.setOutputMarkupId(true);
    add(eventsContainer);

    authorizeList();
    authorizeChanges();

    categoryContainer.add(new Label("typeLabel", new ResourceModel("type", "type")));

    type = new AjaxDropDownChoicePanel<EventCategoryType>("type", "type",
            new PropertyModel<EventCategoryType>(eventCategoryTO, "type"), false);
    type.setChoices(Arrays.asList(EventCategoryType.values()));
    type.setStyleSheet("ui-widget-content ui-corner-all");
    type.setChoiceRenderer(new IChoiceRenderer<EventCategoryType>() {

        private static final long serialVersionUID = 2317134950949778735L;

        @Override
        public String getDisplayValue(final EventCategoryType eventCategoryType) {
            return eventCategoryType.name();
        }

        @Override
        public String getIdValue(final EventCategoryType eventCategoryType, final int i) {
            return eventCategoryType.name();
        }
    });
    categoryContainer.add(type);

    type.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            send(LoggerCategoryPanel.this, Broadcast.EXACT, new ChangeCategoryEvent(target, type));
        }
    });

    categoryContainer.add(new Label("categoryLabel", new ResourceModel("category", "category")));

    category = new AjaxDropDownChoicePanel<String>("category", "category",
            new PropertyModel<String>(eventCategoryTO, "category"), false);
    category.setChoices(filter(eventCategoryTOs, type.getModelObject()));
    category.setStyleSheet("ui-widget-content ui-corner-all");
    categoryContainer.add(category);

    category.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306811L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            send(LoggerCategoryPanel.this, Broadcast.EXACT, new ChangeCategoryEvent(target, category));
        }
    });

    categoryContainer.add(new Label("subcategoryLabel", new ResourceModel("subcategory", "subcategory")));

    subcategory = new AjaxDropDownChoicePanel<String>("subcategory", "subcategory",
            new PropertyModel<String>(eventCategoryTO, "subcategory"), false);
    subcategory.setChoices(filter(eventCategoryTOs, type.getModelObject(), category.getModelObject()));
    subcategory.setStyleSheet("ui-widget-content ui-corner-all");
    categoryContainer.add(subcategory);

    subcategory.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306812L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            send(LoggerCategoryPanel.this, Broadcast.EXACT, new ChangeCategoryEvent(target, subcategory));
        }
    });

    categoryContainer.add(new Label("customLabel", new ResourceModel("custom", "custom")).setVisible(false));

    custom = new AjaxTextFieldPanel("custom", "custom", new Model<String>(null));
    custom.setStyleSheet("ui-widget-content ui-corner-all short_fixedsize");
    custom.setVisible(false);
    custom.setEnabled(false);

    categoryContainer.add(custom);

    actionPanel = new ActionLinksPanel("customActions", new Model(), pageReference);
    categoryContainer.add(actionPanel);

    actionPanel.add(new ActionLink() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            if (StringUtils.isNotBlank(custom.getModelObject())) {
                final Pair<EventCategoryTO, AuditElements.Result> parsed = AuditLoggerName
                        .parseEventCategory(custom.getModelObject());

                final String eventString = AuditLoggerName.buildEvent(parsed.getKey().getType(), null, null,
                        parsed.getKey().getEvents().isEmpty() ? StringUtils.EMPTY
                                : parsed.getKey().getEvents().iterator().next(),
                        parsed.getValue());

                custom.setModelObject(StringUtils.EMPTY);
                send(LoggerCategoryPanel.this.getPage(), Broadcast.BREADTH, new EventSelectionChanged(target,
                        Collections.<String>singleton(eventString), Collections.<String>emptySet()));
                target.add(categoryContainer);
            }
        }
    }, ActionLink.ActionType.CREATE, pageId, true);

    actionPanel.add(new ActionLink() {

        private static final long serialVersionUID = -3722207913631435502L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            if (StringUtils.isNotBlank(custom.getModelObject())) {
                Pair<EventCategoryTO, AuditElements.Result> parsed = AuditLoggerName
                        .parseEventCategory(custom.getModelObject());

                String eventString = AuditLoggerName.buildEvent(parsed.getKey().getType(), null, null,
                        parsed.getKey().getEvents().isEmpty() ? StringUtils.EMPTY
                                : parsed.getKey().getEvents().iterator().next(),
                        parsed.getValue());

                custom.setModelObject(StringUtils.EMPTY);
                send(LoggerCategoryPanel.this.getPage(), Broadcast.BREADTH, new EventSelectionChanged(target,
                        Collections.<String>emptySet(), Collections.<String>singleton(eventString)));
                target.add(categoryContainer);
            }
        }
    }, ActionLink.ActionType.DELETE, pageId, true);

    actionPanel.setVisible(false);
    actionPanel.setEnabled(false);

    eventsContainer.add(new EventSelectionPanel("eventsPanel", eventCategoryTO, model) {

        private static final long serialVersionUID = 3513194801190026082L;

        @Override
        protected void onEventAction(final IEvent<?> event) {
            LoggerCategoryPanel.this.onEventAction(event);
        }
    });
}

From source file:org.apache.syncope.client.console.panels.LoggerCategoryPanel.java

@Override
@SuppressWarnings("unchecked")
public void onEvent(final IEvent<?> event) {
    if (event.getPayload() instanceof ChangeCategoryEvent) {
        // update objects ....
        eventCategoryTO.getEvents().clear();

        final ChangeCategoryEvent change = (ChangeCategoryEvent) event.getPayload();

        final Panel changedPanel = change.getChangedPanel();
        if ("type".equals(changedPanel.getId())) {
            eventCategoryTO.setType(type.getModelObject());
            eventCategoryTO.setCategory(null);
            eventCategoryTO.setSubcategory(null);

            if (type.getModelObject() == EventCategoryType.CUSTOM) {
                category.setChoices(Collections.<String>emptyList());
                subcategory.setChoices(Collections.<String>emptyList());
                category.setEnabled(false);
                subcategory.setEnabled(false);
                custom.setVisible(true);
                custom.setEnabled(true);
                actionPanel.setVisible(true);
                actionPanel.setEnabled(true);

            } else {
                category.setChoices(filter(eventCategoryTOs, type.getModelObject()));
                subcategory.setChoices(Collections.<String>emptyList());
                category.setEnabled(true);
                subcategory.setEnabled(true);
                custom.setVisible(false);
                custom.setEnabled(false);
                actionPanel.setVisible(false);
                actionPanel.setEnabled(false);
            }/*from ww w . j  a va2s  . c  om*/
            change.getTarget().add(categoryContainer);
        } else if ("category".equals(changedPanel.getId())) {
            subcategory.setChoices(filter(eventCategoryTOs, type.getModelObject(), category.getModelObject()));
            eventCategoryTO.setCategory(category.getModelObject());
            eventCategoryTO.setSubcategory(null);
            change.getTarget().add(categoryContainer);
        } else {
            eventCategoryTO.setSubcategory(subcategory.getModelObject());
        }

        updateEventsContainer(change.getTarget());
    } else if (event.getPayload() instanceof InspectSelectedEvent) {
        // update objects ....
        eventCategoryTO.getEvents().clear();

        InspectSelectedEvent inspectSelectedEvent = (InspectSelectedEvent) event.getPayload();

        Pair<EventCategoryTO, AuditElements.Result> categoryEvent = AuditLoggerName
                .parseEventCategory(inspectSelectedEvent.getEvent());

        eventCategoryTO.setType(categoryEvent.getKey().getType());
        category.setChoices(filter(eventCategoryTOs, type.getModelObject()));

        eventCategoryTO.setCategory(categoryEvent.getKey().getCategory());
        subcategory.setChoices(filter(eventCategoryTOs, type.getModelObject(), category.getModelObject()));

        eventCategoryTO.setSubcategory(categoryEvent.getKey().getSubcategory());

        if (categoryEvent.getKey().getType() == EventCategoryType.CUSTOM) {
            custom.setModelObject(
                    AuditLoggerName.buildEvent(categoryEvent.getKey().getType(),
                            categoryEvent.getKey().getCategory(), categoryEvent.getKey().getSubcategory(),
                            categoryEvent.getKey().getEvents().isEmpty() ? StringUtils.EMPTY
                                    : categoryEvent.getKey().getEvents().iterator().next(),
                            categoryEvent.getValue()));

            category.setEnabled(false);
            subcategory.setEnabled(false);
            custom.setVisible(true);
            custom.setEnabled(true);
            actionPanel.setVisible(true);
            actionPanel.setEnabled(true);
        } else {
            category.setEnabled(true);
            subcategory.setEnabled(true);
            custom.setVisible(false);
            custom.setEnabled(false);
            actionPanel.setVisible(false);
            actionPanel.setEnabled(false);
        }

        inspectSelectedEvent.getTarget().add(categoryContainer);
        updateEventsContainer(inspectSelectedEvent.getTarget());
    }
}

From source file:org.apache.syncope.client.console.panels.RealmChoicePanel.java

public RealmChoicePanel(final String id, final PageReference pageRef) {
    super(id);//from   w w w.j av a  2s .  c  o m
    this.pageRef = pageRef;
    tree = new HashMap<>();

    RealmTO fakeRootRealm = new RealmTO();
    fakeRootRealm.setName(SyncopeConstants.ROOT_REALM);
    fakeRootRealm.setFullPath(SyncopeConstants.ROOT_REALM);
    model = Model.of(fakeRootRealm);

    realmTree = new LoadableDetachableModel<List<Pair<String, RealmTO>>>() {

        private static final long serialVersionUID = -7688359318035249200L;

        private void getChildren(final List<Pair<String, RealmTO>> full, final String key,
                final Map<String, Pair<RealmTO, List<RealmTO>>> tree, final String indent) {

            if (tree.containsKey(key)) {
                Pair<RealmTO, List<RealmTO>> subtree = tree.get(key);
                subtree.getValue().forEach(child -> {
                    full.add(Pair.of(indent + child.getName(), child));
                    getChildren(full, child.getKey(), tree,
                            "     " + indent + (indent.isEmpty() ? "|--- " : ""));
                });
            }
        }

        @Override
        protected List<Pair<String, RealmTO>> load() {
            Map<String, Pair<RealmTO, List<RealmTO>>> map = reloadRealmParentMap();
            model.setObject(map.get(null).getKey());

            final List<Pair<String, RealmTO>> full = new ArrayList<>();
            getChildren(full, null, map, StringUtils.EMPTY);
            return full;
        }
    };

    dynRealmTree = new LoadableDetachableModel<List<DynRealmTO>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<DynRealmTO> load() {
            List<DynRealmTO> dynRealms = realmRestClient.listDynReams();
            dynRealms.sort((left, right) -> {
                if (left == null) {
                    return -1;
                } else if (right == null) {
                    return 1;
                } else {
                    return left.getKey().compareTo(right.getKey());
                }
            });

            return dynRealms;
        }
    };

    container = new WebMarkupContainer("container", realmTree);
    container.setOutputMarkupId(true);
    add(container);

    availableRealms = SyncopeConsoleSession.get().getAuthRealms();

    reloadRealmTree();
}

From source file:org.apache.syncope.client.console.panels.RealmChoicePanel.java

public final void reloadRealmTree() {
    final Label realmLabel = new Label("realmLabel", new Model<>());
    realmLabel.setOutputMarkupId(true);// www.  ja  v  a 2 s  .  com

    container.addOrReplace(realmLabel);

    if (model.getObject().getFullPath().startsWith(SyncopeConstants.ROOT_REALM)) {
        realmLabel.setDefaultModel(new ResourceModel("realmLabel", "Realm"));
    } else {
        realmLabel.setDefaultModel(new ResourceModel("dynRealmLabel", "Dynamic Realm"));
    }

    final Label label = new Label("realm", model.getObject().getFullPath());
    label.setOutputMarkupId(true);
    container.addOrReplace(label);

    final DropDownButton realms = new DropDownButton("realms", new ResourceModel("select", ""),
            new Model<IconType>(GlyphIconType.folderopen)) {

        private static final long serialVersionUID = -5560086780455361131L;

        @Override
        protected List<AbstractLink> newSubMenuButtons(final String buttonMarkupId) {
            RealmChoicePanel.this.links.clear();

            RealmChoicePanel.this.links.add(new BootstrapAjaxLink<RealmTO>(ButtonList.getButtonMarkupId(),
                    new Model<RealmTO>(), Buttons.Type.Link, new ResourceModel("realms", "Realms")) {

                private static final long serialVersionUID = -7978723352517770744L;

                @Override
                public void onClick(final AjaxRequestTarget target) {
                }

                @Override
                public boolean isEnabled() {
                    return false;
                }

                @Override
                protected void onComponentTag(final ComponentTag tag) {
                    tag.put("class", "panel box box-primary box-header with-border");
                    tag.put("style", "margin: 20px 5px 0px 5px; width: 90%");
                }
            });

            for (Pair<String, RealmTO> link : realmTree.getObject()) {
                final RealmTO realmTO = link.getValue();
                RealmChoicePanel.this.links.add(new BootstrapAjaxLink<RealmTO>(ButtonList.getButtonMarkupId(),
                        Model.of(realmTO), Buttons.Type.Link, new Model<>(link.getKey())) {

                    private static final long serialVersionUID = -7978723352517770644L;

                    @Override
                    public void onClick(final AjaxRequestTarget target) {
                        model.setObject(realmTO);
                        label.setDefaultModelObject(model.getObject().getFullPath());
                        realmLabel.setDefaultModel(new ResourceModel("realmLabel", "Realm"));
                        target.add(label);
                        send(pageRef.getPage(), Broadcast.EXACT, new ChosenRealm<>(realmTO, target));
                    }

                    @Override
                    public boolean isEnabled() {
                        return availableRealms.stream()
                                .anyMatch(availableRealm -> realmTO.getFullPath().startsWith(availableRealm));
                    }
                });
            }

            if (!dynRealmTree.getObject().isEmpty()) {
                RealmChoicePanel.this.links.add(
                        new BootstrapAjaxLink<RealmTO>(ButtonList.getButtonMarkupId(), new Model<RealmTO>(),
                                Buttons.Type.Link, new ResourceModel("dynrealms", "Dynamic Realms")) {

                            private static final long serialVersionUID = -7978723352517770744L;

                            @Override
                            public void onClick(final AjaxRequestTarget target) {

                            }

                            @Override
                            public boolean isEnabled() {
                                return false;
                            }

                            @Override
                            protected void onComponentTag(final ComponentTag tag) {
                                tag.put("class", "panel box box-primary box-header with-border");
                                tag.put("style", "margin: 20px 5px 0px 5px; width: 90%");
                            }
                        });

                for (DynRealmTO dynRealmTO : dynRealmTree.getObject()) {
                    final RealmTO realmTO = new RealmTO();
                    realmTO.setKey(dynRealmTO.getKey());
                    realmTO.setName(dynRealmTO.getKey());
                    realmTO.setFullPath(dynRealmTO.getKey());

                    RealmChoicePanel.this.links
                            .add(new BootstrapAjaxLink<RealmTO>(ButtonList.getButtonMarkupId(),
                                    new Model<RealmTO>(), Buttons.Type.Link, new Model<>(realmTO.getKey())) {

                                private static final long serialVersionUID = -7978723352517770644L;

                                @Override
                                public void onClick(final AjaxRequestTarget target) {
                                    model.setObject(realmTO);
                                    label.setDefaultModelObject(realmTO.getKey());
                                    realmLabel.setDefaultModel(
                                            new ResourceModel("dynRealmLabel", "Dynamic Realm"));
                                    target.add(label);
                                    send(pageRef.getPage(), Broadcast.EXACT,
                                            new ChosenRealm<>(realmTO, target));
                                }

                                @Override
                                public boolean isEnabled() {
                                    return availableRealms.stream().anyMatch(availableRealm -> {
                                        return SyncopeConstants.ROOT_REALM.equals(availableRealm)
                                                || realmTO.getKey().equals(availableRealm);
                                    });
                                }
                            });
                }
            }

            return RealmChoicePanel.this.links;
        }
    };
    realms.setOutputMarkupId(true);
    realms.setAlignment(AlignmentBehavior.Alignment.RIGHT);
    realms.setType(Buttons.Type.Menu);

    MetaDataRoleAuthorizationStrategy.authorize(realms, ENABLE, StandardEntitlement.REALM_LIST);

    container.addOrReplace(realms);
}

From source file:org.apache.syncope.core.misc.MappingUtils.java

/**
 * Prepare attributes for sending to a connector instance.
 *
 * @param any given any object//from  w  w w  .j a v  a 2  s .c  o m
 * @param password clear-text password
 * @param changePwd whether password should be included for propagation attributes or not
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @param enable whether any object must be enabled or not
 * @param provision provision information
 * @return connObjectLink + prepared attributes
 */
public static Pair<String, Set<Attribute>> prepareAttrs(final Any<?, ?, ?> any, final String password,
        final boolean changePwd, final Set<String> vAttrsToBeRemoved,
        final Map<String, AttrMod> vAttrsToBeUpdated, final Boolean enable, final Provision provision) {

    LOG.debug("Preparing resource attributes for {} with provision {} for attributes {}", any, provision,
            any.getPlainAttrs());

    ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    VirAttrCache virAttrCache = context.getBean(VirAttrCache.class);
    PasswordGenerator passwordGenerator = context.getBean(PasswordGenerator.class);

    Set<Attribute> attributes = new HashSet<>();
    String connObjectKey = null;

    for (MappingItem mapping : getMappingItems(provision, MappingPurpose.PROPAGATION)) {
        LOG.debug("Processing schema {}", mapping.getIntAttrName());

        try {
            if (mapping.getIntMappingType() == IntMappingType.UserVirtualSchema
                    || mapping.getIntMappingType() == IntMappingType.GroupVirtualSchema
                    || mapping.getIntMappingType() == IntMappingType.AnyObjectVirtualSchema) {

                LOG.debug("Expire entry cache {}-{}", any.getKey(), mapping.getIntAttrName());
                virAttrCache.expire(any.getType().getKey(), any.getKey(), mapping.getIntAttrName());
            }

            Pair<String, Attribute> preparedAttr = prepareAttr(provision, mapping, any, password,
                    passwordGenerator, vAttrsToBeRemoved, vAttrsToBeUpdated);

            if (preparedAttr != null && preparedAttr.getKey() != null) {
                connObjectKey = preparedAttr.getKey();
            }

            if (preparedAttr != null && preparedAttr.getValue() != null) {
                Attribute alreadyAdded = AttributeUtil.find(preparedAttr.getValue().getName(), attributes);

                if (alreadyAdded == null) {
                    attributes.add(preparedAttr.getValue());
                } else {
                    attributes.remove(alreadyAdded);

                    Set<Object> values = new HashSet<>(alreadyAdded.getValue());
                    values.addAll(preparedAttr.getValue().getValue());

                    attributes.add(AttributeBuilder.build(preparedAttr.getValue().getName(), values));
                }
            }
        } catch (Exception e) {
            LOG.debug("Attribute '{}' processing failed", mapping.getIntAttrName(), e);
        }
    }

    Attribute connObjectKeyExtAttr = AttributeUtil.find(getConnObjectKeyItem(provision).getExtAttrName(),
            attributes);
    if (connObjectKeyExtAttr != null) {
        attributes.remove(connObjectKeyExtAttr);
        attributes.add(AttributeBuilder.build(getConnObjectKeyItem(provision).getExtAttrName(), connObjectKey));
    }
    attributes.add(evaluateNAME(any, provision, connObjectKey));

    if (enable != null) {
        attributes.add(AttributeBuilder.buildEnabled(enable));
    }
    if (!changePwd) {
        Attribute pwdAttr = AttributeUtil.find(OperationalAttributes.PASSWORD_NAME, attributes);
        if (pwdAttr != null) {
            attributes.remove(pwdAttr);
        }
    }

    return new ImmutablePair<>(connObjectKey, attributes);
}

From source file:org.apache.syncope.core.misc.utils.MappingUtils.java

/**
 * Prepare attributes for sending to a connector instance.
 *
 * @param any given any object//from   w  ww  .ja  va2s.  c om
 * @param password clear-text password
 * @param changePwd whether password should be included for propagation attributes or not
 * @param enable whether any object must be enabled or not
 * @param provision provision information
 * @return connObjectLink + prepared attributes
 */
@Transactional(readOnly = true)
public Pair<String, Set<Attribute>> prepareAttrs(final Any<?> any, final String password,
        final boolean changePwd, final Boolean enable, final Provision provision) {

    LOG.debug("Preparing resource attributes for {} with provision {} for attributes {}", any, provision,
            any.getPlainAttrs());

    Set<Attribute> attributes = new HashSet<>();
    String connObjectKey = null;

    for (MappingItem mappingItem : getMappingItems(provision, MappingPurpose.PROPAGATION)) {
        LOG.debug("Processing schema {}", mappingItem.getIntAttrName());

        try {
            Pair<String, Attribute> preparedAttr = prepareAttr(provision, mappingItem, any, password);

            if (preparedAttr != null && preparedAttr.getKey() != null) {
                connObjectKey = preparedAttr.getKey();
            }

            if (preparedAttr != null && preparedAttr.getValue() != null) {
                Attribute alreadyAdded = AttributeUtil.find(preparedAttr.getValue().getName(), attributes);

                if (alreadyAdded == null) {
                    attributes.add(preparedAttr.getValue());
                } else {
                    attributes.remove(alreadyAdded);

                    Set<Object> values = new HashSet<>(alreadyAdded.getValue());
                    values.addAll(preparedAttr.getValue().getValue());

                    attributes.add(AttributeBuilder.build(preparedAttr.getValue().getName(), values));
                }
            }
        } catch (Exception e) {
            LOG.debug("Attribute '{}' processing failed", mappingItem.getIntAttrName(), e);
        }
    }

    Attribute connObjectKeyExtAttr = AttributeUtil.find(getConnObjectKeyItem(provision).getExtAttrName(),
            attributes);
    if (connObjectKeyExtAttr != null) {
        attributes.remove(connObjectKeyExtAttr);
        attributes.add(AttributeBuilder.build(getConnObjectKeyItem(provision).getExtAttrName(), connObjectKey));
    }
    attributes.add(evaluateNAME(any, provision, connObjectKey));

    if (enable != null) {
        attributes.add(AttributeBuilder.buildEnabled(enable));
    }
    if (!changePwd) {
        Attribute pwdAttr = AttributeUtil.find(OperationalAttributes.PASSWORD_NAME, attributes);
        if (pwdAttr != null) {
            attributes.remove(pwdAttr);
        }
    }

    return new ImmutablePair<>(connObjectKey, attributes);
}

From source file:org.apache.syncope.core.provisioning.camel.processor.UserInternalSuspendProcessor.java

@Override
public void process(final Exchange exchange) {
    @SuppressWarnings("unchecked")
    Pair<WorkflowResult<Long>, Boolean> updated = (Pair) exchange.getIn().getBody();

    // propagate suspension if and only if it is required by policy
    if (updated != null && updated.getValue()) {
        UserPatch userPatch = new UserPatch();
        userPatch.setKey(updated.getKey().getResult());

        List<PropagationTask> tasks = propagationManager.getUserUpdateTasks(
                new WorkflowResult<Pair<UserPatch, Boolean>>(new ImmutablePair<>(userPatch, Boolean.FALSE),
                        updated.getKey().getPropByRes(), updated.getKey().getPerformedTasks()));
        taskExecutor.execute(tasks);//from   ww  w. j  ava 2 s  . c o m
    }
}

From source file:org.apache.syncope.core.provisioning.camel.producer.SuspendProducer.java

@SuppressWarnings("unchecked")
@Override/*ww w  .  j  a va2  s  . co  m*/
public void process(final Exchange exchange) throws Exception {
    if (getAnyTypeKind() == AnyTypeKind.USER) {
        Pair<WorkflowResult<String>, Boolean> updated = (Pair<WorkflowResult<String>, Boolean>) exchange.getIn()
                .getBody();

        // propagate suspension if and only if it is required by policy
        if (updated != null && updated.getValue()) {
            UserPatch userPatch = new UserPatch();
            userPatch.setKey(updated.getKey().getResult());

            List<PropagationTaskTO> tasks = getPropagationManager()
                    .getUserUpdateTasks(new WorkflowResult<>(Pair.of(userPatch, Boolean.FALSE),
                            updated.getKey().getPropByRes(), updated.getKey().getPerformedTasks()));
            getPropagationTaskExecutor().execute(tasks, false);
        }
    }
}

From source file:org.apache.syncope.core.provisioning.java.propagation.PropagationManagerImpl.java

/**
 * Create propagation tasks.// ww w.j  a  v a2 s  .c  o m
 *
 * @param any to be provisioned
 * @param password clear text password to be provisioned
 * @param changePwd whether password should be included for propagation attributes or not
 * @param enable whether user must be enabled or not
 * @param deleteOnResource whether any must be deleted anyway from external resource or not
 * @param propByRes operation to be performed per resource
 * @param vAttrs virtual attributes to be set
 * @return list of propagation tasks created
 */
protected List<PropagationTaskTO> createTasks(final Any<?> any, final String password, final boolean changePwd,
        final Boolean enable, final boolean deleteOnResource, final PropagationByResource propByRes,
        final Collection<AttrTO> vAttrs) {

    LOG.debug("Provisioning {}:\n{}", any, propByRes);

    // Avoid duplicates - see javadoc
    propByRes.purge();
    LOG.debug("After purge {}:\n{}", any, propByRes);

    // Virtual attributes
    Set<String> virtualResources = new HashSet<>();
    virtualResources.addAll(propByRes.get(ResourceOperation.CREATE));
    virtualResources.addAll(propByRes.get(ResourceOperation.UPDATE));
    virtualResources.addAll(dao(any.getType().getKind()).findAllResourceKeys(any.getKey()));

    Map<String, Set<Attribute>> vAttrMap = new HashMap<>();
    if (vAttrs != null) {
        vAttrs.forEach(vAttr -> {
            VirSchema schema = virSchemaDAO.find(vAttr.getSchema());
            if (schema == null) {
                LOG.warn("Ignoring invalid {} {}", VirSchema.class.getSimpleName(), vAttr.getSchema());
            } else if (schema.isReadonly()) {
                LOG.warn("Ignoring read-only {} {}", VirSchema.class.getSimpleName(), vAttr.getSchema());
            } else if (anyUtilsFactory.getInstance(any).getAllowedSchemas(any, VirSchema.class).contains(schema)
                    && virtualResources.contains(schema.getProvision().getResource().getKey())) {

                Set<Attribute> values = vAttrMap.get(schema.getProvision().getResource().getKey());
                if (values == null) {
                    values = new HashSet<>();
                    vAttrMap.put(schema.getProvision().getResource().getKey(), values);
                }
                values.add(AttributeBuilder.build(schema.getExtAttrName(), vAttr.getValues()));

                propByRes.add(ResourceOperation.UPDATE, schema.getProvision().getResource().getKey());
            } else {
                LOG.warn("{} not owned by or {} not allowed for {}", schema.getProvision().getResource(),
                        schema, any);
            }
        });
    }
    LOG.debug("With virtual attributes {}:\n{}\n{}", any, propByRes, vAttrMap);

    List<PropagationTaskTO> tasks = new ArrayList<>();

    propByRes.asMap().entrySet().forEach(entry -> {
        ExternalResource resource = resourceDAO.find(entry.getKey());
        Provision provision = resource == null ? null : resource.getProvision(any.getType()).orElse(null);
        List<? extends Item> mappingItems = provision == null ? Collections.<Item>emptyList()
                : MappingUtils.getPropagationItems(provision.getMapping().getItems());

        if (resource == null) {
            LOG.error("Invalid resource name specified: {}, ignoring...", entry.getKey());
        } else if (provision == null) {
            LOG.error("No provision specified on resource {} for type {}, ignoring...", resource,
                    any.getType());
        } else if (mappingItems.isEmpty()) {
            LOG.warn("Requesting propagation for {} but no propagation mapping provided for {}", any.getType(),
                    resource);
        } else {
            PropagationTaskTO task = new PropagationTaskTO();
            task.setResource(resource.getKey());
            task.setObjectClassName(provision.getObjectClass().getObjectClassValue());
            task.setAnyTypeKind(any.getType().getKind());
            task.setAnyType(any.getType().getKey());
            if (!deleteOnResource) {
                task.setEntityKey(any.getKey());
            }
            task.setOperation(entry.getValue());
            task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resource.getKey()));

            Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrs(any, password, changePwd,
                    enable, provision);
            task.setConnObjectKey(preparedAttrs.getKey());

            // Check if any of mandatory attributes (in the mapping) is missing or not received any value: 
            // if so, add special attributes that will be evaluated by PropagationTaskExecutor
            List<String> mandatoryMissing = new ArrayList<>();
            List<String> mandatoryNullOrEmpty = new ArrayList<>();
            mappingItems.stream()
                    .filter(item -> (!item.isConnObjectKey()
                            && JexlUtils.evaluateMandatoryCondition(item.getMandatoryCondition(), any)))
                    .forEachOrdered(item -> {
                        Attribute attr = AttributeUtil.find(item.getExtAttrName(), preparedAttrs.getValue());
                        if (attr == null) {
                            mandatoryMissing.add(item.getExtAttrName());
                        } else if (attr.getValue() == null || attr.getValue().isEmpty()) {
                            mandatoryNullOrEmpty.add(item.getExtAttrName());
                        }
                    });
            if (!mandatoryMissing.isEmpty()) {
                preparedAttrs.getValue().add(AttributeBuilder
                        .build(PropagationTaskExecutor.MANDATORY_MISSING_ATTR_NAME, mandatoryMissing));
            }
            if (!mandatoryNullOrEmpty.isEmpty()) {
                preparedAttrs.getValue().add(AttributeBuilder.build(
                        PropagationTaskExecutor.MANDATORY_NULL_OR_EMPTY_ATTR_NAME, mandatoryNullOrEmpty));
            }

            if (vAttrMap.containsKey(resource.getKey())) {
                preparedAttrs.getValue().addAll(vAttrMap.get(resource.getKey()));
            }

            task.setAttributes(POJOHelper.serialize(preparedAttrs.getValue()));

            tasks.add(task);

            LOG.debug("PropagationTask created: {}", task);
        }
    });

    return tasks;
}

From source file:org.apache.syncope.core.provisioning.java.propagation.PropagationManagerImpl.java

@Override
public List<PropagationTaskTO> createTasks(final Realm realm, final PropagationByResource propByRes,
        final Collection<String> noPropResourceKeys) {

    if (noPropResourceKeys != null) {
        propByRes.removeAll(noPropResourceKeys);
    }//from   www. j  a  v a 2  s .c  o m

    LOG.debug("Provisioning {}:\n{}", realm, propByRes);

    // Avoid duplicates - see javadoc
    propByRes.purge();
    LOG.debug("After purge {}:\n{}", realm, propByRes);

    List<PropagationTaskTO> tasks = new ArrayList<>();

    propByRes.asMap().entrySet().forEach(entry -> {
        ExternalResource resource = resourceDAO.find(entry.getKey());
        OrgUnit orgUnit = resource == null ? null : resource.getOrgUnit();

        if (resource == null) {
            LOG.error("Invalid resource name specified: {}, ignoring...", entry.getKey());
        } else if (orgUnit == null) {
            LOG.error("No orgUnit specified on resource {}, ignoring...", resource);
        } else if (StringUtils.isBlank(orgUnit.getConnObjectLink())) {
            LOG.warn("Requesting propagation for {} but no ConnObjectLink provided for {}", realm.getFullPath(),
                    resource);
        } else {
            PropagationTaskTO task = new PropagationTaskTO();
            task.setResource(resource.getKey());
            task.setObjectClassName(orgUnit.getObjectClass().getObjectClassValue());
            task.setEntityKey(realm.getKey());
            task.setOperation(entry.getValue());
            task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resource.getKey()));

            Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrs(realm, orgUnit);
            task.setConnObjectKey(preparedAttrs.getKey());
            task.setAttributes(POJOHelper.serialize(preparedAttrs.getValue()));

            tasks.add(task);

            LOG.debug("PropagationTask created: {}", task);
        }
    });

    return tasks;
}