Example usage for org.apache.commons.lang3.tuple ImmutablePair of

List of usage examples for org.apache.commons.lang3.tuple ImmutablePair of

Introduction

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

Prototype

public static <L, R> ImmutablePair<L, R> of(final L left, final R right) 

Source Link

Document

Obtains an immutable pair of from two objects inferring the generic types.

This factory allows the pair to be created using inference to obtain the generic types.

Usage

From source file:org.apache.syncope.core.misc.security.AuthDataAccessor.java

/**
 * Attempts to authenticate the given credentials against internal storage and pass-through resources (if
 * configured): the first succeeding causes global success.
 *
 * @param authentication given credentials
 * @return {@code null} if no matching user was found, authentication result otherwise
 */// w w w . j  a v a  2 s.  c  om
@Transactional(noRollbackFor = DisabledException.class)
public Pair<Long, Boolean> authenticate(final Authentication authentication) {
    Long key = null;
    Boolean authenticated = null;

    User user = userDAO.find(authentication.getName());
    if (user != null) {
        key = user.getKey();
        authenticated = false;

        if (user.isSuspended() != null && user.isSuspended()) {
            throw new DisabledException("User " + user.getUsername() + " is suspended");
        }

        CPlainAttr authStatuses = confDAO.find("authentication.statuses");
        if (authStatuses != null && !authStatuses.getValuesAsStrings().contains(user.getStatus())) {
            throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
        }

        boolean userModified = false;
        authenticated = authenticate(user, authentication.getCredentials().toString());
        if (authenticated) {
            if (confDAO.find("log.lastlogindate", Boolean.toString(true)).getValues().get(0)
                    .getBooleanValue()) {
                user.setLastLoginDate(new Date());
                userModified = true;
            }

            if (user.getFailedLogins() != 0) {
                user.setFailedLogins(0);
                userModified = true;
            }

        } else {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userModified = true;
        }

        if (userModified) {
            userDAO.save(user);
        }
    }

    return ImmutablePair.of(key, authenticated);
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAUserDAO.java

@Transactional(readOnly = true)
@Override/* w  w  w . j a v  a 2 s. c  om*/
public Pair<Boolean, Boolean> enforcePolicies(final User user) {
    // ------------------------------
    // Verify password policies
    // ------------------------------
    LOG.debug("Password Policy enforcement");

    try {
        int maxPPSpecHistory = 0;
        for (PasswordPolicy policy : getPasswordPolicies(user)) {
            if (user.getPassword() == null && !policy.isAllowNullPassword()) {
                throw new PasswordPolicyException("Password mandatory");
            }

            for (Implementation impl : policy.getRules()) {
                Optional<PasswordRule> rule = ImplementationManager.buildPasswordRule(impl);
                if (rule.isPresent()) {
                    rule.get().enforce(user);
                }
            }

            if (user.verifyPasswordHistory(user.getClearPassword(), policy.getHistoryLength())) {
                throw new PasswordPolicyException("Password value was used in the past: not allowed");
            }

            if (policy.getHistoryLength() > maxPPSpecHistory) {
                maxPPSpecHistory = policy.getHistoryLength();
            }
        }

        // update user's password history with encrypted password
        if (maxPPSpecHistory > 0 && user.getPassword() != null
                && !user.getPasswordHistory().contains(user.getPassword())) {
            user.getPasswordHistory().add(user.getPassword());
        }
        // keep only the last maxPPSpecHistory items in user's password history
        if (maxPPSpecHistory < user.getPasswordHistory().size()) {
            for (int i = 0; i < user.getPasswordHistory().size() - maxPPSpecHistory; i++) {
                user.getPasswordHistory().remove(i);
            }
        }
    } catch (Exception e) {
        LOG.error("Invalid password for {}", user, e);
        throw new InvalidEntityException(User.class, EntityViolationType.InvalidPassword, e.getMessage());
    } finally {
        // password has been validated, let's remove its clear version
        user.removeClearPassword();
    }

    // ------------------------------
    // Verify account policies
    // ------------------------------
    LOG.debug("Account Policy enforcement");

    boolean suspend = false;
    boolean propagateSuspension = false;
    try {
        if (user.getUsername() == null) {
            throw new AccountPolicyException("Null username");
        }

        if (adminUser.equals(user.getUsername()) || anonymousUser.equals(user.getUsername())) {
            throw new AccountPolicyException("Not allowed: " + user.getUsername());
        }

        if (!USERNAME_PATTERN.matcher(user.getUsername()).matches()) {
            throw new AccountPolicyException("Character(s) not allowed");
        }

        for (AccountPolicy policy : getAccountPolicies(user)) {
            for (Implementation impl : policy.getRules()) {
                Optional<AccountRule> rule = ImplementationManager.buildAccountRule(impl);
                if (rule.isPresent()) {
                    rule.get().enforce(user);
                }
            }

            suspend |= user.getFailedLogins() != null && policy.getMaxAuthenticationAttempts() > 0
                    && user.getFailedLogins() > policy.getMaxAuthenticationAttempts() && !user.isSuspended();
            propagateSuspension |= policy.isPropagateSuspension();
        }
    } catch (Exception e) {
        LOG.error("Invalid username for {}", user, e);
        throw new InvalidEntityException(User.class, EntityViolationType.InvalidUsername, e.getMessage());
    }

    return ImmutablePair.of(suspend, propagateSuspension);
}

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

@Override
public void process(final Exchange exchange) {
    Long key = exchange.getIn().getBody(Long.class);
    Boolean changePwd = exchange.getProperty("changePwd", Boolean.class);
    String password = exchange.getProperty("password", String.class);
    @SuppressWarnings("unchecked")
    List<String> resources = exchange.getProperty("resources", List.class);
    Boolean nullPriorityAsync = exchange.getProperty("nullPriorityAsync", Boolean.class);

    UserPatch userPatch = new UserPatch();
    userPatch.setKey(key);// w  ww .  ja va  2 s . co  m
    userPatch.getResources()
            .addAll(CollectionUtils.collect(resources, new Transformer<String, StringPatchItem>() {

                @Override
                public StringPatchItem transform(final String resource) {
                    return new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value(resource)
                            .build();
                }
            }));

    if (changePwd) {
        userPatch.setPassword(
                new PasswordPatch.Builder().onSyncope(true).value(password).resources(resources).build());
    }

    PropagationByResource propByRes = new PropagationByResource();
    for (String resource : resources) {
        propByRes.add(ResourceOperation.UPDATE, resource);
    }

    WorkflowResult<Pair<UserPatch, Boolean>> wfResult = new WorkflowResult<Pair<UserPatch, Boolean>>(
            ImmutablePair.of(userPatch, (Boolean) null), propByRes, "update");

    List<PropagationTask> tasks = propagationManager.getUserUpdateTasks(wfResult, changePwd, null);
    PropagationReporter propagationReporter = ApplicationContextProvider.getBeanFactory()
            .getBean(PropagationReporter.class);
    taskExecutor.execute(tasks, propagationReporter, nullPriorityAsync);

    exchange.getOut().setBody(propagationReporter.getStatuses());
}

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

@SuppressWarnings("unchecked")
@Override//from  w ww.  j  av  a 2  s. c o  m
public void process(final Exchange exchange) throws Exception {
    String key = exchange.getIn().getBody(String.class);
    List<String> resources = exchange.getProperty("resources", List.class);
    Boolean nullPriorityAsync = exchange.getProperty("nullPriorityAsync", Boolean.class);

    if (getAnyTypeKind() == AnyTypeKind.USER) {
        Boolean changePwd = exchange.getProperty("changePwd", Boolean.class);
        String password = exchange.getProperty("password", String.class);

        UserPatch userPatch = new UserPatch();
        userPatch.setKey(key);
        userPatch.getResources()
                .addAll(resources
                        .stream().map(resource -> new StringPatchItem.Builder()
                                .operation(PatchOperation.ADD_REPLACE).value(resource).build())
                        .collect(Collectors.toList()));

        if (changePwd) {
            userPatch.setPassword(
                    new PasswordPatch.Builder().onSyncope(true).value(password).resources(resources).build());
        }

        PropagationByResource propByRes = new PropagationByResource();
        propByRes.addAll(ResourceOperation.UPDATE, resources);

        WorkflowResult<Pair<UserPatch, Boolean>> wfResult = new WorkflowResult<>(
                ImmutablePair.of(userPatch, (Boolean) null), propByRes, "update");

        List<PropagationTaskTO> tasks = getPropagationManager().getUserUpdateTasks(wfResult, changePwd, null);
        PropagationReporter propagationReporter = getPropagationTaskExecutor().execute(tasks,
                nullPriorityAsync);

        exchange.getOut().setBody(propagationReporter.getStatuses());
    } else {
        PropagationByResource propByRes = new PropagationByResource();
        propByRes.addAll(ResourceOperation.UPDATE, resources);

        AnyTypeKind anyTypeKind = AnyTypeKind.GROUP;
        if (getAnyTypeKind() != null) {
            anyTypeKind = getAnyTypeKind();
        }

        List<PropagationTaskTO> tasks = getPropagationManager().getUpdateTasks(anyTypeKind, key, false, null,
                propByRes, null, null);
        PropagationReporter propagationReporter = getPropagationTaskExecutor().execute(tasks,
                nullPriorityAsync);

        exchange.getOut().setBody(propagationReporter.getStatuses());
    }
}

From source file:org.apache.syncope.core.provisioning.java.DefaultUserProvisioningManager.java

@Override
public List<PropagationStatus> provision(final String key, final boolean changePwd, final String password,
        final Collection<String> resources, final boolean nullPriorityAsync) {

    UserPatch userPatch = new UserPatch();
    userPatch.setKey(key);//from  w  w w.j av  a2  s .  c om
    userPatch.getResources()
            .addAll(resources
                    .stream().map(resource -> new StringPatchItem.Builder()
                            .operation(PatchOperation.ADD_REPLACE).value(resource).build())
                    .collect(Collectors.toSet()));

    if (changePwd) {
        PasswordPatch passwordPatch = new PasswordPatch();
        passwordPatch.setOnSyncope(false);
        passwordPatch.getResources().addAll(resources);
        passwordPatch.setValue(password);
        userPatch.setPassword(passwordPatch);
    }

    PropagationByResource propByRes = new PropagationByResource();
    propByRes.addAll(ResourceOperation.UPDATE, resources);

    WorkflowResult<Pair<UserPatch, Boolean>> wfResult = new WorkflowResult<>(
            ImmutablePair.of(userPatch, (Boolean) null), propByRes, "update");

    List<PropagationTaskTO> tasks = propagationManager.getUserUpdateTasks(wfResult, changePwd, null);
    PropagationReporter propagationReporter = taskExecutor.execute(tasks, nullPriorityAsync);

    return propagationReporter.getStatuses();
}

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

@Override
public void writeTo(final Swagger data, final Class<?> type, final Type genericType,
        final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers,
        final OutputStream out) throws IOException {

    if (dynamicBasePath) {
        MessageContext ctx = JAXRSUtils.createContextValue(JAXRSUtils.getCurrentMessage(), null,
                MessageContext.class);
        data.setBasePath(StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/"));
    }/*w w w.j a  v a2  s .  c o  m*/

    if (replaceTags || javadocProvider != null) {
        Map<String, ClassResourceInfo> operations = new HashMap<>();
        Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>();
        for (ClassResourceInfo cri : cris) {
            for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) {
                String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(),
                        ori.getURITemplate().getValue());

                operations.put(normalizedPath, cri);
                methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori);
            }
        }

        if (replaceTags && data.getTags() != null) {
            data.getTags().clear();
        }
        for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) {
            Tag tag = null;
            if (replaceTags && operations.containsKey(entry.getKey())) {
                ClassResourceInfo cri = operations.get(entry.getKey());

                tag = new Tag();
                tag.setName(cri.getURITemplate().getValue());
                if (javadocProvider != null) {
                    tag.setDescription(javadocProvider.getClassDoc(cri));
                }

                data.addTag(tag);
            }

            for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) {
                if (replaceTags && tag != null) {
                    subentry.getValue().setTags(Collections.singletonList(tag.getName()));
                }

                Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey());
                if (methods.containsKey(key) && javadocProvider != null) {
                    OperationResourceInfo ori = methods.get(key);

                    subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori));

                    boolean domainHeaderParameterFound = false;
                    for (int i = 0; i < subentry.getValue().getParameters().size(); i++) {
                        subentry.getValue().getParameters().get(i)
                                .setDescription(javadocProvider.getMethodParameterDoc(ori, i));

                        if (subentry.getValue().getParameters().get(i) instanceof HeaderParameter
                                && RESTHeaders.DOMAIN
                                        .equals(subentry.getValue().getParameters().get(i).getName())) {

                            domainHeaderParameterFound = true;
                        }
                    }
                    if (!domainHeaderParameterFound) {
                        HeaderParameter domainHeaderParameter = new HeaderParameter();
                        domainHeaderParameter.setName(RESTHeaders.DOMAIN);
                        domainHeaderParameter.setRequired(true);
                        domainHeaderParameter.setType("string");
                        domainHeaderParameter.setEnum(domains);
                        domainHeaderParameter.setDefault(SyncopeConstants.MASTER_DOMAIN);

                        subentry.getValue().getParameters().add(domainHeaderParameter);
                    }

                    if (subentry.getValue().getResponses() != null
                            && !subentry.getValue().getResponses().isEmpty()) {

                        subentry.getValue().getResponses().entrySet().iterator().next().getValue()
                                .setDescription(javadocProvider.getMethodResponseDoc(ori));
                    }
                }
            }
        }
    }
    if (replaceTags && data.getTags() != null) {
        Collections.sort(data.getTags(), new Comparator<Tag>() {

            @Override
            public int compare(final Tag tag1, final Tag tag2) {
                return ComparatorUtils.<String>naturalComparator().compare(tag1.getName(), tag2.getName());
            }
        });
    }

    super.writeTo(data, type, genericType, annotations, mediaType, headers, out);
}

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

/**
 * Attempts to authenticate the given credentials against internal storage and pass-through resources (if
 * configured): the first succeeding causes global success.
 *
 * @param authentication given credentials
 * @return {@code null} if no matching user was found, authentication result otherwise
 *//* ww  w .java 2s  . c o m*/
@Transactional(noRollbackFor = DisabledException.class)
public Pair<User, Boolean> authenticate(final Authentication authentication) {
    User user = null;

    Optional<? extends CPlainAttr> authAttrs = confDAO.find("authentication.attributes");
    List<String> authAttrValues = authAttrs.isPresent() ? authAttrs.get().getValuesAsStrings()
            : Collections.singletonList("username");
    for (int i = 0; user == null && i < authAttrValues.size(); i++) {
        if ("username".equals(authAttrValues.get(i))) {
            user = userDAO.findByUsername(authentication.getName());
        } else {
            AttributeCond attrCond = new AttributeCond(AttributeCond.Type.EQ);
            attrCond.setSchema(authAttrValues.get(i));
            attrCond.setExpression(authentication.getName());
            List<User> users = searchDAO.search(SearchCond.getLeafCond(attrCond), AnyTypeKind.USER);
            if (users.size() == 1) {
                user = users.get(0);
            } else {
                LOG.warn("Value {} provided for {} does not uniquely identify a user", authentication.getName(),
                        authAttrValues.get(i));
            }
        }
    }

    Boolean authenticated = null;
    if (user != null) {
        authenticated = false;

        if (user.isSuspended() != null && user.isSuspended()) {
            throw new DisabledException("User " + user.getUsername() + " is suspended");
        }

        Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
        if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
            throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
        }

        boolean userModified = false;
        authenticated = AuthDataAccessor.this.authenticate(user, authentication.getCredentials().toString());
        if (authenticated) {
            if (confDAO.find("log.lastlogindate", true)) {
                user.setLastLoginDate(new Date());
                userModified = true;
            }

            if (user.getFailedLogins() != 0) {
                user.setFailedLogins(0);
                userModified = true;
            }

        } else {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userModified = true;
        }

        if (userModified) {
            userDAO.save(user);
        }
    }

    return ImmutablePair.of(user, authenticated);
}

From source file:org.apache.syncope.core.workflow.java.AbstractUserWorkflowAdapter.java

@Override
public Pair<WorkflowResult<String>, Boolean> internalSuspend(final String key) {
    User user = userDAO.authFind(key);/* www .j  a v  a  2 s  .c  om*/

    Pair<WorkflowResult<String>, Boolean> result = null;

    Pair<Boolean, Boolean> enforce = userDAO.enforcePolicies(user);
    if (enforce.getKey()) {
        LOG.debug("User {} {} is over the max failed logins", user.getKey(), user.getUsername());

        // reduce failed logins number to avoid multiple request       
        user.setFailedLogins(user.getFailedLogins() - 1);

        // set suspended flag
        user.setSuspended(Boolean.TRUE);

        result = ImmutablePair.of(doSuspend(user), enforce.getValue());
    }

    return result;
}

From source file:org.dbg4j.core.adapters.impl.DefaultDebuggingAdapter.java

/**
 * Append debugged method arguments to debug data in declaration order. Arguments annotated with {@link Ignore}
 * annotation are not evaluated,//from   w  ww.  java 2 s  . c o  m
 * the string <code>"@Ignore"</code> is set instead their value (we cannot just ignore them b/c we should not break
 * method signature). By default parameter value evaluates by {@link DefaultEvaluationAdapter} unless another
 * evaluator is set by {@link Adapter} annotation.
 *
 * @see Ignore
 * @see Adapter
 * @see DefaultEvaluationAdapter
 */
protected void appendArgumentsInfo(DebugData data, MethodInvocationPoint methodInvocationPoint) {

    if (methodInvocationPoint.getParameters() == null || methodInvocationPoint.getParameters().length == 0) {
        return;
    }

    Class[] parameterTypes = methodInvocationPoint.getMethod().getParameterTypes();
    if (parameterTypes == null || parameterTypes.length == 0) {
        return;
    }

    List<Pair<Class, String>> arguments = new ArrayList<Pair<Class, String>>();

    Annotation[][] parameterAnnotations = methodInvocationPoint.getMethod().getParameterAnnotations();

    for (int i = 0; i < parameterTypes.length; i++) {
        try {
            if (containsAnnotation(parameterAnnotations[i], Ignore.class)) {
                arguments.add(ImmutablePair.of(parameterTypes[i], IGNORED_VALUE));
                continue;
            }

            EvaluationAdapter evaluationAdapter = null;
            if (containsAnnotation(parameterAnnotations[i], Adapter.class)) {
                Adapter adapterAnnotation = getAnnotation(parameterAnnotations[i], Adapter.class);
                evaluationAdapter = adapterAnnotation.value().newInstance();
            }
            if (evaluationAdapter == null) {
                evaluationAdapter = new DefaultEvaluationAdapter();
            }

            arguments.add(ImmutablePair.<Class, String>of(parameterTypes[i],
                    evaluationAdapter.evaluate(parameterTypes[i], methodInvocationPoint.getParameters()[i])));
        } catch (Exception ignored) {
        }
    }

    if (arguments.size() > 0) {
        List<DebugData> args = new ArrayList<DebugData>(arguments.size());
        for (Pair<Class, String> argument : arguments) {
            args.add(new DebugData(argument.getLeft().getSimpleName(), argument.getRight()));
        }
        data.set("Arguments", args);
    }
}

From source file:org.gvnix.addon.jpa.addon.entitylistener.JpaOrmEntityListenerOperationsImpl.java

/**
 * Adjust listener order as is registered on
 * {@link JpaOrmEntityListenerRegistry}// ww w.  j a v  a  2 s  .c  om
 * 
 * @param ormXml
 * @param entityListenerElement
 * @param entityListenerElements
 * @return true if xml elements had been changed
 */
private boolean adjustEntityListenerOrder(Document ormXml, Element entityListenerElement,
        List<Element> entityListenerElements) {

    // Prepare a Pair list which is a representation of current
    // entity-listener
    List<Pair<String, String>> currentOrder = new ArrayList<Pair<String, String>>();
    for (Element currentElement : entityListenerElements) {
        // Each Pair: key (left) = entity-listener class; value (right)
        // metadataProvider id
        currentOrder.add(ImmutablePair.of(currentElement.getAttribute(CLASS_ATTRIBUTE),
                getEntityListenerElementType(currentElement)));
    }

    // Create a comparator which can sort the list based on order configured
    // on registry
    ListenerOrderComparator comparator = new ListenerOrderComparator(registry.getListenerOrder());

    // Clone the Pair list and sort it
    List<Pair<String, String>> ordered = new ArrayList<Pair<String, String>>(currentOrder);
    Collections.sort(ordered, comparator);

    // Check if elements order is different form original
    boolean changeOrder = false;
    Pair<String, String> currentPair, orderedPair;
    for (int i = 0; i < currentOrder.size(); i++) {
        currentPair = currentOrder.get(i);
        orderedPair = ordered.get(i);
        if (!StringUtils.equals(currentPair.getKey(), orderedPair.getKey())) {
            changeOrder = true;
            break;
        }
    }

    if (!changeOrder) {
        // Order is correct: nothing to do
        return false;
    }

    // List for new elements to add
    List<Node> newList = new ArrayList<Node>(entityListenerElements.size());

    // Iterate over final ordered list
    int curIndex;
    Node cloned, old;
    for (int i = 0; i < ordered.size(); i++) {
        orderedPair = ordered.get(i);
        // Gets old listener XML node
        curIndex = indexOfListener(entityListenerElements, orderedPair.getKey());
        old = entityListenerElements.get(curIndex);

        // Clone old node and add to new elements list
        cloned = old.cloneNode(true);
        newList.add(cloned);

        // Remove old listener node from parent
        entityListenerElement.removeChild(old);
    }

    // Add listeners xml nodes to parent again in final order
    for (Node node : newList) {
        entityListenerElement.appendChild(node);
    }

    return true;
}