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

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

Introduction

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

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

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

private String getGroupOwnerValue(final Provision provision, final Any<?> any) {
    Pair<String, Attribute> preparedAttr = prepareAttr(provision, getConnObjectKeyItem(provision), any, null);
    String connObjectKey = preparedAttr.getKey();

    return evaluateNAME(any, provision, connObjectKey).getNameValue();
}

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 a v a2 s. com*/
    }
}

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

@SuppressWarnings("unchecked")
@Override//from   w ww .  j a  v a  2  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.MappingManagerImpl.java

private String getGroupOwnerValue(final Provision provision, final Any<?> any) {
    Pair<String, Attribute> preparedAttr = prepareAttr(provision,
            MappingUtils.getConnObjectKeyItem(provision).get(), any, null);
    String connObjectKey = preparedAttr.getKey();

    return MappingUtils.evaluateNAME(any, provision, connObjectKey).getNameValue();
}

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

/**
 * Create propagation tasks.// w w w .j  a  v  a  2s.  co  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   ww w. j a v a2  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;
}

From source file:org.apache.syncope.core.rest.cxf.service.UserSelfServiceImpl.java

@Override
public Response read() {
    Pair<String, UserTO> self = logic.selfRead();
    return Response.ok().header(RESTHeaders.RESOURCE_KEY, self.getValue().getKey())
            .header(RESTHeaders.OWNED_ENTITLEMENTS, self.getKey()).entity(self.getValue()).build();
}

From source file:org.apache.syncope.core.spring.security.SyncopeAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain();
    if (StringUtils.isBlank(domainKey)) {
        domainKey = SyncopeConstants.MASTER_DOMAIN;
    }/*ww w .j av a 2s  .c  o m*/
    SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).setDomain(domainKey);

    Boolean authenticated;
    if (anonymousUser.equals(authentication.getName())) {
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(authentication.getName())) {
        if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) {
            authenticated = encryptor.verify(authentication.getCredentials().toString(),
                    CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
        } else {
            final String domainToFind = domainKey;
            authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN,
                    new Executable<Boolean>() {

                        @Override
                        public Boolean exec() {
                            Domain domain = dataAccessor.findDomain(domainToFind);

                            return encryptor.verify(authentication.getCredentials().toString(),
                                    domain.getAdminCipherAlgorithm(), domain.getAdminPwd());
                        }
                    });
        }
    } else {
        final Pair<String, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey,
                new Executable<Pair<String, Boolean>>() {

                    @Override
                    public Pair<String, Boolean> exec() {
                        return dataAccessor.authenticate(authentication);
                    }
                });
        authenticated = authResult.getValue();
        if (authenticated != null && !authenticated) {
            AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() {

                @Override
                public Void exec() {
                    provisioningManager.internalSuspend(authResult.getKey());
                    return null;
                }
            });
        }
    }

    final boolean isAuthenticated = authenticated != null && authenticated;
    UsernamePasswordAuthenticationToken token;
    if (isAuthenticated) {
        token = AuthContextUtils.execWithAuthContext(domainKey,
                new Executable<UsernamePasswordAuthenticationToken>() {

                    @Override
                    public UsernamePasswordAuthenticationToken exec() {
                        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                authentication.getPrincipal(), null,
                                userDetailsService.loadUserByUsername(authentication.getPrincipal().toString())
                                        .getAuthorities());
                        token.setDetails(authentication.getDetails());

                        dataAccessor.audit(AuditElements.EventCategoryType.LOGIC,
                                AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT,
                                Result.SUCCESS, null, isAuthenticated, authentication,
                                "Successfully authenticated, with entitlements: " + token.getAuthorities());
                        return token;
                    }
                });

        LOG.debug("User {} successfully authenticated, with entitlements {}", authentication.getPrincipal(),
                token.getAuthorities());
    } else {
        AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() {

            @Override
            public Void exec() {
                dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                        null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication,
                        "User " + authentication.getPrincipal() + " not authenticated");
                return null;
            }
        });

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return token;
}

From source file:org.apache.syncope.core.workflow.activiti.ActivitiUserWorkflowAdapter.java

@Override
public WorkflowResult<UserPatch> submitForm(final WorkflowFormTO form) {
    String authUser = AuthContextUtils.getUsername();
    Pair<Task, TaskFormData> checked = checkTask(form.getTaskId(), authUser);

    if (!checked.getKey().getOwner().equals(authUser)) {
        throw new WorkflowException(new IllegalArgumentException("Task " + form.getTaskId() + " assigned to "
                + checked.getKey().getOwner() + " but submitted by " + authUser));
    }// www. j ava2s .  co  m

    User user = userDAO.findByWorkflowId(checked.getKey().getProcessInstanceId());
    if (user == null) {
        throw new NotFoundException("User with workflow id " + checked.getKey().getProcessInstanceId());
    }

    Set<String> preTasks = getPerformedTasks(user);
    try {
        engine.getFormService().submitTaskFormData(form.getTaskId(), form.getPropertiesForSubmit());
        engine.getRuntimeService().setVariable(user.getWorkflowId(), FORM_SUBMITTER, authUser);
    } catch (ActivitiException e) {
        throwException(e, "While submitting form for task " + form.getTaskId());
    }

    Set<String> postTasks = getPerformedTasks(user);
    postTasks.removeAll(preTasks);
    postTasks.add(form.getTaskId());

    updateStatus(user);
    User updated = userDAO.save(user);

    // see if there is any propagation to be done
    PropagationByResource propByRes = engine.getRuntimeService().getVariable(user.getWorkflowId(),
            PROP_BY_RESOURCE, PropagationByResource.class);

    // fetch - if available - the encrypted password
    String clearPassword = null;
    String encryptedPwd = engine.getRuntimeService().getVariable(user.getWorkflowId(), ENCRYPTED_PWD,
            String.class);
    if (StringUtils.isNotBlank(encryptedPwd)) {
        clearPassword = decrypt(encryptedPwd);
    }

    // supports approval chains
    saveForFormSubmit(user, clearPassword, propByRes);

    UserPatch userPatch = engine.getRuntimeService().getVariable(user.getWorkflowId(), USER_PATCH,
            UserPatch.class);
    if (userPatch == null) {
        userPatch = new UserPatch();
        userPatch.setKey(updated.getKey());
        userPatch.setPassword(new PasswordPatch.Builder().onSyncope(true).value(clearPassword).build());

        if (propByRes != null) {
            userPatch.getPassword().getResources().addAll(propByRes.get(ResourceOperation.CREATE));
        }
    }

    return new WorkflowResult<>(userPatch, propByRes, postTasks);
}

From source file:org.apache.syncope.core.workflow.flowable.FlowableUserWorkflowAdapter.java

@Override
public WorkflowResult<UserPatch> submitForm(final WorkflowFormTO form) {
    String authUser = AuthContextUtils.getUsername();
    Pair<Task, TaskFormData> checked = checkTask(form.getTaskId(), authUser);

    if (!checked.getKey().getOwner().equals(authUser)) {
        throw new WorkflowException(new IllegalArgumentException("Task " + form.getTaskId() + " assigned to "
                + checked.getKey().getOwner() + " but submitted by " + authUser));
    }//from  w w  w.j av  a  2s  .  c o  m

    User user = userDAO.findByWorkflowId(checked.getKey().getProcessInstanceId());
    if (user == null) {
        throw new NotFoundException("User with workflow id " + checked.getKey().getProcessInstanceId());
    }

    Set<String> preTasks = getPerformedTasks(user);
    try {
        engine.getFormService().submitTaskFormData(form.getTaskId(), getPropertiesForSubmit(form));
        engine.getRuntimeService().setVariable(user.getWorkflowId(), FORM_SUBMITTER, authUser);
    } catch (FlowableException e) {
        throwException(e, "While submitting form for task " + form.getTaskId());
    }

    Set<String> postTasks = getPerformedTasks(user);
    postTasks.removeAll(preTasks);
    postTasks.add(form.getTaskId());

    updateStatus(user);
    User updated = userDAO.save(user);

    // see if there is any propagation to be done
    PropagationByResource propByRes = engine.getRuntimeService().getVariable(user.getWorkflowId(),
            PROP_BY_RESOURCE, PropagationByResource.class);

    // fetch - if available - the encrypted password
    String clearPassword = null;
    String encryptedPwd = engine.getRuntimeService().getVariable(user.getWorkflowId(), ENCRYPTED_PWD,
            String.class);
    if (StringUtils.isNotBlank(encryptedPwd)) {
        clearPassword = decrypt(encryptedPwd);
    }

    // supports approval chains
    saveForFormSubmit(user, clearPassword, propByRes);

    UserPatch userPatch = engine.getRuntimeService().getVariable(user.getWorkflowId(), USER_PATCH,
            UserPatch.class);
    if (userPatch == null) {
        userPatch = new UserPatch();
        userPatch.setKey(updated.getKey());
        userPatch.setPassword(new PasswordPatch.Builder().onSyncope(true).value(clearPassword).build());

        if (propByRes != null) {
            userPatch.getPassword().getResources().addAll(propByRes.get(ResourceOperation.CREATE));
        }
    }

    return new WorkflowResult<>(userPatch, propByRes, postTasks);
}