Search in sources :

Example 61 with Collections

use of java.util.Collections in project n4js by eclipse.

the class RunnerHelper method getProjectExtendedDepsAndApiImplMapping.

/**
 * Returns a mapping from all API projects among <code>dependencies</code> to their corresponding implementation
 * project for implementation ID <code>implementationId</code>.
 * <p>
 * Special cases: if there are no API projects among the dependencies, this method will return an empty map in
 * {@link ApiUsage#concreteApiImplProjectMapping} and {@link ApiUsage#implementationIdRequired}<code>==false</code>;
 * otherwise, if <code>implementationId</code> is <code>null</code>, then this method will assert that there exists
 * exactly one implementation for the API projects among the dependencies and use that (stored in
 * {@link ApiUsage#implementationId}).
 * <p>
 * Throws exception in case of error given <code>throwOnError==true</code>, never returns null.
 *
 * @param runtimeEnvironment
 *            active runtime environment.
 * @param moduleToRun
 *            what to run.
 * @param implementationId
 *            might be <code>null</code>
 * @param throwOnError
 *            if true fast fail in erroneous situations. Otherwise tries to proceed in a meaningful way. State can
 *            then be queried on the ApiUsage instance.
 *
 * @return result wrapped in an {@link ApiUsage} instance.
 */
// TODO this methods could require some cleanup after the concepts of API-Implementation mappings stabilized...
public ApiUsage getProjectExtendedDepsAndApiImplMapping(RuntimeEnvironment runtimeEnvironment, URI moduleToRun, String implementationId, boolean throwOnError) {
    final LinkedHashSet<IN4JSProject> deps = new LinkedHashSet<>();
    // 1) add project containing the moduleToRun and its direct AND indirect dependencies
    final Optional<? extends IN4JSProject> project = n4jsCore.findProject(moduleToRun);
    if (project.isPresent() == false) {
        throw new RuntimeException("can't obtain containing project for moduleToRun: " + moduleToRun);
    }
    recursiveDependencyCollector(project.get(), deps, new RecursionGuard<>());
    // TODO need to add not only REs but also RLs they provide
    // 2) add the runtime environment project, REs it extends and RLs provided
    final Optional<IN4JSProject> reProject = getCustomRuntimeEnvironmentProject(runtimeEnvironment);
    if (reProject.isPresent()) {
        IN4JSProject re = reProject.get();
        recursiveExtendedREsCollector(re, deps);
    } else {
    // IDE-1359: don't throw exception to make runners work without user-defined runtime environment
    // (will be changed later when library manager is available!)
    // throw new RuntimeException("can't obtain runtime environment project for " + moduleToRun2);
    }
    // TODO actually we would like to return the dependencies in load order:
    // - RuntimeEnvironment boot
    // - all RuntimeLibrary boots (take deps2 between RLs into account)
    // - all other deps2 (order does not matter they just needs to be on path later)
    // - project to be called
    // maybe some in order DFS or something above?
    // manually transform to list, or is this one ok?
    final ApiImplMapping apiImplMapping = ApiImplMapping.of(deps, n4jsCore.findAllProjects());
    if (apiImplMapping.hasErrors()) {
        if (throwOnError)
            throw new IllegalStateException("the workspace setup contains errors related to API / implementation projects (check manifests of related projects):\n    " + Joiner.on("\n    ").join(apiImplMapping.getErrorMessages()));
    }
    if (apiImplMapping.isEmpty()) {
        return ApiUsage.of(new ArrayList<>(deps), Collections.<IN4JSProject, IN4JSProject>emptyMap(), apiImplMapping);
    }
    // there must be exactly one implementation for the API projects in the workspace
    if (implementationId == null) {
        final List<String> allImplIds = apiImplMapping.getAllImplIds();
        if (allImplIds.size() != 1) {
            if (throwOnError) {
                throw new IllegalStateException("no implementationId specified while several are available in the workspace: " + allImplIds);
            } else {
                // back out, further processing not possible without implementations id.
                return ApiUsage.of(new ArrayList<>(deps), Collections.emptyMap(), apiImplMapping, true);
            }
        } else {
            implementationId = allImplIds.get(0);
        }
    }
    final Map<IN4JSProject, IN4JSProject> apiImplProjectMapping = new LinkedHashMap<>();
    // projectIds of projects without an implementation
    final List<String> missing = new ArrayList<>();
    for (IN4JSProject dep : deps) {
        if (dep != null) {
            final String depId = dep.getProjectId();
            if (depId != null && apiImplMapping.isApi(depId)) {
                // so: dep is an API project ...
                final IN4JSProject impl = apiImplMapping.getImpl(depId, implementationId);
                if (impl != null) {
                    // so: impl is the implementation project for dep for implementation ID 'implementationId'
                    apiImplProjectMapping.put(dep, impl);
                } else {
                    // bad: no implementation for dep for implementation ID 'implementationId'
                    missing.add(depId);
                }
            }
        }
    }
    if (!missing.isEmpty()) {
        if (throwOnError) {
            throw new IllegalStateException("no implementation for implementation ID \"" + implementationId + "\" found for the following projects: " + Joiner.on(", ").join(missing));
        }
    }
    // / #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
    // IDEBUG-506 look for additional dependencies, pulled in from api-impl project not yet processed:
    HashSet<IN4JSProject> processedDepProjects = deps;
    LinkedHashSet<IN4JSProject> tobeInspectedApiImplProjects = new LinkedHashSet<>();
    apiImplProjectMapping.entrySet().forEach(p -> {
        IN4JSProject v = p.getValue();
        if (!processedDepProjects.contains(v))
            tobeInspectedApiImplProjects.add(v);
    });
    // Collect transitive mappings. Populate with original ones.
    final Map<IN4JSProject, IN4JSProject> joinedApiImplProjectMapping = new LinkedHashMap<>(apiImplProjectMapping);
    while (!tobeInspectedApiImplProjects.isEmpty()) {
        // compute dependencies if necessary
        LinkedHashSet<IN4JSProject> batchedPivotDependencies = new LinkedHashSet<>();
        RecursionGuard<URI> guard = new RecursionGuard<>();
        for (IN4JSProject pivotProject : tobeInspectedApiImplProjects) {
            recursiveDependencyCollector(pivotProject, batchedPivotDependencies, guard);
        }
        tobeInspectedApiImplProjects.clear();
        List<IN4JSProject> batchedPivotNewDepList = batchedPivotDependencies.stream().filter(p -> null != p && !processedDepProjects.contains(p)).collect(Collectors.toList());
        // new Api-mapping
        apiImplMapping.enhance(batchedPivotNewDepList, n4jsCore.findAllProjects());
        // go over new dependencies and decide:
        for (IN4JSProject pivNewDep : batchedPivotNewDepList) {
            final String depId = pivNewDep.getProjectId();
            if (apiImplMapping.isApi(depId)) {
                // API-mapping
                if (joinedApiImplProjectMapping.containsKey(pivNewDep)) {
                // already done.
                } else {
                    // put new entry
                    IN4JSProject pivImpl = apiImplMapping.getImpl(depId, implementationId);
                    if (null != pivImpl) {
                        joinedApiImplProjectMapping.put(pivNewDep, pivImpl);
                        tobeInspectedApiImplProjects.add(pivImpl);
                    } else {
                        missing.add(depId);
                    }
                }
            } else {
                // no API.
                if (!processedDepProjects.contains(pivNewDep)) {
                    // add to deps
                    processedDepProjects.add(pivNewDep);
                }
            }
        }
    }
    if (!missing.isEmpty()) {
        if (throwOnError) {
            throw new IllegalStateException("no implementation for implementation ID \"" + implementationId + "\" found for the following projects: " + Joiner.on(", ").join(missing));
        }
    }
    return ApiUsage.of(implementationId, new ArrayList<>(deps), apiImplProjectMapping, apiImplMapping, missing);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BootstrapModule(org.eclipse.n4js.n4mf.BootstrapModule) URI(org.eclipse.emf.common.util.URI) Inject(com.google.inject.Inject) ResourceNameComputer(org.eclipse.n4js.utils.ResourceNameComputer) IN4JSCore(org.eclipse.n4js.projectModel.IN4JSCore) IN4JSSourceContainerAware(org.eclipse.n4js.projectModel.IN4JSSourceContainerAware) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) RunnerRegistry(org.eclipse.n4js.runner.extension.RunnerRegistry) N4JSGlobals(org.eclipse.n4js.N4JSGlobals) Optional(com.google.common.base.Optional) Map(java.util.Map) RecursionGuard(org.eclipse.n4js.utils.RecursionGuard) IRunnerDescriptor(org.eclipse.n4js.runner.extension.IRunnerDescriptor) RuntimeEnvironment(org.eclipse.n4js.runner.extension.RuntimeEnvironment) ApiImplMapping(org.eclipse.n4js.compare.ApiImplMapping) Path(java.nio.file.Path) LinkedHashSet(java.util.LinkedHashSet) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) IN4JSProject(org.eclipse.n4js.projectModel.IN4JSProject) Set(java.util.Set) Collectors(java.util.stream.Collectors) File(java.io.File) ProjectType(org.eclipse.n4js.n4mf.ProjectType) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) IN4JSArchive(org.eclipse.n4js.projectModel.IN4JSArchive) AbstractSubGenerator(org.eclipse.n4js.generator.AbstractSubGenerator) Collections(java.util.Collections) FindArtifactHelper(org.eclipse.n4js.utils.FindArtifactHelper) Joiner(com.google.common.base.Joiner) ApiImplMapping(org.eclipse.n4js.compare.ApiImplMapping) ArrayList(java.util.ArrayList) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) RecursionGuard(org.eclipse.n4js.utils.RecursionGuard) URI(org.eclipse.emf.common.util.URI) LinkedHashMap(java.util.LinkedHashMap) IN4JSProject(org.eclipse.n4js.projectModel.IN4JSProject)

Example 62 with Collections

use of java.util.Collections in project syncope by apache.

the class ResourceTest method delete.

@Test
public void delete() {
    ExternalResource resource = resourceDAO.find("resource-testdb");
    assertNotNull(resource);
    // -------------------------------------
    // Get originally associated connector
    // -------------------------------------
    ConnInstance connector = resource.getConnector();
    assertNotNull(connector);
    // -------------------------------------
    // -------------------------------------
    // Get originally associated users
    // -------------------------------------
    List<User> users = userDAO.findByResource(resource);
    assertNotNull(users);
    Set<String> userKeys = users.stream().map(Entity::getKey).collect(Collectors.toSet());
    // -------------------------------------
    // Get tasks
    List<PropagationTask> propagationTasks = taskDAO.findAll(TaskType.PROPAGATION, resource, null, null, null, -1, -1, Collections.<OrderByClause>emptyList());
    assertFalse(propagationTasks.isEmpty());
    // delete resource
    resourceDAO.delete(resource.getKey());
    // close the transaction
    resourceDAO.flush();
    // resource must be removed
    ExternalResource actual = resourceDAO.find("resource-testdb");
    assertNull(actual);
    // resource must be not referenced any more from users
    userKeys.stream().map(key -> userDAO.find(key)).map(actualUser -> {
        assertNotNull(actualUser);
        return actualUser;
    }).forEachOrdered((actualUser) -> {
        userDAO.findAllResources(actualUser).forEach(res -> assertFalse(res.getKey().equalsIgnoreCase(resource.getKey())));
    });
    // resource must be not referenced any more from the connector
    ConnInstance actualConnector = connInstanceDAO.find(connector.getKey());
    assertNotNull(actualConnector);
    actualConnector.getResources().forEach(res -> assertFalse(res.getKey().equalsIgnoreCase(resource.getKey())));
    // there must be no tasks
    propagationTasks.forEach(task -> assertNull(taskDAO.find(task.getKey())));
}
Also used : JPAMappingItem(org.apache.syncope.core.persistence.jpa.entity.resource.JPAMappingItem) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) OrderByClause(org.apache.syncope.core.persistence.api.dao.search.OrderByClause) Autowired(org.springframework.beans.factory.annotation.Autowired) Entity(org.apache.syncope.core.persistence.api.entity.Entity) PropagationTask(org.apache.syncope.core.persistence.api.entity.task.PropagationTask) TaskDAO(org.apache.syncope.core.persistence.api.dao.TaskDAO) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) JPAOrgUnit(org.apache.syncope.core.persistence.jpa.entity.resource.JPAOrgUnit) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Mapping(org.apache.syncope.core.persistence.api.entity.resource.Mapping) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) Set(java.util.Set) User(org.apache.syncope.core.persistence.api.entity.user.User) ConnInstanceDAO(org.apache.syncope.core.persistence.api.dao.ConnInstanceDAO) Collectors(java.util.stream.Collectors) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) Test(org.junit.jupiter.api.Test) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) MappingPurpose(org.apache.syncope.common.lib.types.MappingPurpose) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) PolicyDAO(org.apache.syncope.core.persistence.api.dao.PolicyDAO) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest) Collections(java.util.Collections) ExternalResourceDAO(org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO) TaskType(org.apache.syncope.common.lib.types.TaskType) Transactional(org.springframework.transaction.annotation.Transactional) User(org.apache.syncope.core.persistence.api.entity.user.User) PropagationTask(org.apache.syncope.core.persistence.api.entity.task.PropagationTask) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Example 63 with Collections

use of java.util.Collections in project syncope by apache.

the class SAML2SPLogic method validateLoginResponse.

@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2LoginResponseTO validateLoginResponse(final SAML2ReceivedResponseTO response) {
    check();
    // 1. first checks for the provided relay state
    if (response.getRelayState() == null) {
        throw new IllegalArgumentException("No Relay State was provided");
    }
    Boolean useDeflateEncoding = false;
    String requestId = null;
    if (!IDP_INITIATED_RELAY_STATE.equals(response.getRelayState())) {
        JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
        if (!relayState.verifySignatureWith(jwsSignatureVerifier)) {
            throw new IllegalArgumentException("Invalid signature found in Relay State");
        }
        useDeflateEncoding = Boolean.valueOf(relayState.getJwtClaims().getClaim(JWT_CLAIM_IDP_DEFLATE).toString());
        requestId = relayState.getJwtClaims().getSubject();
        Long expiryTime = relayState.getJwtClaims().getExpiryTime();
        if (expiryTime == null || (expiryTime * 1000L) < new Date().getTime()) {
            throw new IllegalArgumentException("Relay State is expired");
        }
    }
    // 2. parse the provided SAML response
    if (response.getSamlResponse() == null) {
        throw new IllegalArgumentException("No SAML Response was provided");
    }
    Response samlResponse;
    try {
        XMLObject responseObject = saml2rw.read(useDeflateEncoding, response.getSamlResponse());
        if (!(responseObject instanceof Response)) {
            throw new IllegalArgumentException("Expected " + Response.class.getName() + ", got " + responseObject.getClass().getName());
        }
        samlResponse = (Response) responseObject;
    } catch (Exception e) {
        LOG.error("While parsing AuthnResponse", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    // 3. validate the SAML response and, if needed, decrypt the provided assertion(s)
    if (samlResponse.getIssuer() == null || samlResponse.getIssuer().getValue() == null) {
        throw new IllegalArgumentException("The SAML Response must contain an Issuer");
    }
    final SAML2IdPEntity idp = getIdP(samlResponse.getIssuer().getValue());
    if (idp.getConnObjectKeyItem() == null) {
        throw new IllegalArgumentException("No mapping provided for SAML 2.0 IdP '" + idp.getId() + "'");
    }
    if (IDP_INITIATED_RELAY_STATE.equals(response.getRelayState()) && !idp.isSupportUnsolicited()) {
        throw new IllegalArgumentException("An unsolicited request is not allowed for idp: " + idp.getId());
    }
    SSOValidatorResponse validatorResponse = null;
    try {
        validatorResponse = saml2rw.validate(samlResponse, idp, getAssertionConsumerURL(response.getSpEntityID(), response.getUrlContext()), requestId, response.getSpEntityID());
    } catch (Exception e) {
        LOG.error("While validating AuthnResponse", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    // 4. prepare the result: find matching user (if any) and return the received attributes
    final SAML2LoginResponseTO responseTO = new SAML2LoginResponseTO();
    responseTO.setIdp(idp.getId());
    responseTO.setSloSupported(idp.getSLOLocation(idp.getBindingType()) != null);
    Assertion assertion = validatorResponse.getOpensamlAssertion();
    NameID nameID = assertion.getSubject().getNameID();
    if (nameID == null) {
        throw new IllegalArgumentException("NameID not found");
    }
    String keyValue = null;
    if (StringUtils.isNotBlank(nameID.getValue()) && idp.getConnObjectKeyItem().getExtAttrName().equals("NameID")) {
        keyValue = nameID.getValue();
    }
    if (assertion.getConditions().getNotOnOrAfter() != null) {
        responseTO.setNotOnOrAfter(assertion.getConditions().getNotOnOrAfter().toDate());
    }
    assertion.getAuthnStatements().forEach(authnStmt -> {
        responseTO.setSessionIndex(authnStmt.getSessionIndex());
        responseTO.setAuthInstant(authnStmt.getAuthnInstant().toDate());
        if (authnStmt.getSessionNotOnOrAfter() != null) {
            responseTO.setNotOnOrAfter(authnStmt.getSessionNotOnOrAfter().toDate());
        }
    });
    for (AttributeStatement attrStmt : assertion.getAttributeStatements()) {
        for (Attribute attr : attrStmt.getAttributes()) {
            if (!attr.getAttributeValues().isEmpty()) {
                String attrName = attr.getFriendlyName() == null ? attr.getName() : attr.getFriendlyName();
                if (attrName.equals(idp.getConnObjectKeyItem().getExtAttrName())) {
                    if (attr.getAttributeValues().get(0) instanceof XSString) {
                        keyValue = ((XSString) attr.getAttributeValues().get(0)).getValue();
                    } else if (attr.getAttributeValues().get(0) instanceof XSAny) {
                        keyValue = ((XSAny) attr.getAttributeValues().get(0)).getTextContent();
                    }
                }
                AttrTO attrTO = new AttrTO();
                attrTO.setSchema(attrName);
                attr.getAttributeValues().stream().filter(value -> value.getDOM() != null).forEachOrdered(value -> {
                    attrTO.getValues().add(value.getDOM().getTextContent());
                });
                responseTO.getAttrs().add(attrTO);
            }
        }
    }
    final List<String> matchingUsers = keyValue == null ? Collections.<String>emptyList() : userManager.findMatchingUser(keyValue, idp.getKey());
    LOG.debug("Found {} matching users for {}", matchingUsers.size(), keyValue);
    String username;
    if (matchingUsers.isEmpty()) {
        if (idp.isCreateUnmatching()) {
            LOG.debug("No user matching {}, about to create", keyValue);
            username = AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> userManager.create(idp, responseTO, nameID.getValue()));
        } else if (idp.isSelfRegUnmatching()) {
            responseTO.setNameID(nameID.getValue());
            UserTO userTO = new UserTO();
            userManager.fill(idp.getKey(), responseTO, userTO);
            responseTO.getAttrs().clear();
            responseTO.getAttrs().addAll(userTO.getPlainAttrs());
            responseTO.getAttrs().addAll(userTO.getVirAttrs());
            if (StringUtils.isNotBlank(userTO.getUsername())) {
                responseTO.setUsername(userTO.getUsername());
            }
            responseTO.setSelfReg(true);
            return responseTO;
        } else {
            throw new NotFoundException("User matching the provided value " + keyValue);
        }
    } else if (matchingUsers.size() > 1) {
        throw new IllegalArgumentException("Several users match the provided value " + keyValue);
    } else {
        if (idp.isUpdateMatching()) {
            LOG.debug("About to update {} for {}", matchingUsers.get(0), keyValue);
            username = AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> userManager.update(matchingUsers.get(0), idp, responseTO));
        } else {
            username = matchingUsers.get(0);
        }
    }
    responseTO.setUsername(username);
    responseTO.setNameID(nameID.getValue());
    // 5. generate JWT for further access
    Map<String, Object> claims = new HashMap<>();
    claims.put(JWT_CLAIM_IDP_ENTITYID, idp.getId());
    claims.put(JWT_CLAIM_NAMEID_FORMAT, nameID.getFormat());
    claims.put(JWT_CLAIM_NAMEID_VALUE, nameID.getValue());
    claims.put(JWT_CLAIM_SESSIONINDEX, responseTO.getSessionIndex());
    byte[] authorities = null;
    try {
        authorities = ENCRYPTOR.encode(POJOHelper.serialize(authDataAccessor.getAuthorities(responseTO.getUsername())), CipherAlgorithm.AES).getBytes();
    } catch (Exception e) {
        LOG.error("Could not fetch authorities", e);
    }
    Pair<String, Date> accessTokenInfo = accessTokenDataBinder.create(responseTO.getUsername(), claims, authorities, true);
    responseTO.setAccessToken(accessTokenInfo.getLeft());
    responseTO.setAccessTokenExpiryTime(accessTokenInfo.getRight());
    return responseTO;
}
Also used : SAMLVersion(org.opensaml.saml.common.SAMLVersion) XSAny(org.opensaml.core.xml.schema.XSAny) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Date(java.util.Date) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Autowired(org.springframework.beans.factory.annotation.Autowired) SAML2ReaderWriter(org.apache.syncope.core.logic.saml2.SAML2ReaderWriter) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) SAML2IdP(org.apache.syncope.core.persistence.api.entity.SAML2IdP) KeyInfoGenerator(org.opensaml.xmlsec.keyinfo.KeyInfoGenerator) StringUtils(org.apache.commons.lang3.StringUtils) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) Attribute(org.opensaml.saml.saml2.core.Attribute) AuthnContextComparisonTypeEnumeration(org.opensaml.saml.saml2.core.AuthnContextComparisonTypeEnumeration) Pair(org.apache.commons.lang3.tuple.Pair) SAML2ReceivedResponseTO(org.apache.syncope.common.lib.to.SAML2ReceivedResponseTO) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Map(java.util.Map) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) SAML2IdPDAO(org.apache.syncope.core.persistence.api.dao.SAML2IdPDAO) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) XSString(org.opensaml.core.xml.schema.XSString) Method(java.lang.reflect.Method) Triple(org.apache.commons.lang3.tuple.Triple) Response(org.opensaml.saml.saml2.core.Response) AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) RandomBasedGenerator(com.fasterxml.uuid.impl.RandomBasedGenerator) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) NameIDFormat(org.opensaml.saml.saml2.metadata.NameIDFormat) Resource(javax.annotation.Resource) AccessTokenDataBinder(org.apache.syncope.core.provisioning.api.data.AccessTokenDataBinder) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SSOValidatorResponse(org.apache.cxf.rs.security.saml.sso.SSOValidatorResponse) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) List(java.util.List) Issuer(org.opensaml.saml.saml2.core.Issuer) NameIDFormatBuilder(org.opensaml.saml.saml2.metadata.impl.NameIDFormatBuilder) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) AuthnContextClassRefBuilder(org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder) AbstractBaseBean(org.apache.syncope.common.lib.AbstractBaseBean) AuthnContext(org.opensaml.saml.saml2.core.AuthnContext) StandardEntitlement(org.apache.syncope.common.lib.types.StandardEntitlement) POJOHelper(org.apache.syncope.core.provisioning.api.serialization.POJOHelper) AttrTO(org.apache.syncope.common.lib.to.AttrTO) SAML2RequestTO(org.apache.syncope.common.lib.to.SAML2RequestTO) SAML2BindingType(org.apache.syncope.common.lib.types.SAML2BindingType) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) HashMap(java.util.HashMap) NameIDPolicyBuilder(org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder) StatusCode(org.opensaml.saml.saml2.core.StatusCode) SPSSODescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.SPSSODescriptorBuilder) EntityDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder) SingleLogoutServiceBuilder(org.opensaml.saml.saml2.metadata.impl.SingleLogoutServiceBuilder) SAML2LoginResponseTO(org.apache.syncope.common.lib.to.SAML2LoginResponseTO) Assertion(org.opensaml.saml.saml2.core.Assertion) OutputStreamWriter(java.io.OutputStreamWriter) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) SAML2IdPCache(org.apache.syncope.core.logic.saml2.SAML2IdPCache) XMLObject(org.opensaml.core.xml.XMLObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) CipherAlgorithm(org.apache.syncope.common.lib.types.CipherAlgorithm) OutputStream(java.io.OutputStream) KeyDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.KeyDescriptorBuilder) Encryptor(org.apache.syncope.core.spring.security.Encryptor) SingleLogoutService(org.opensaml.saml.saml2.metadata.SingleLogoutService) DateTime(org.joda.time.DateTime) SessionIndexBuilder(org.opensaml.saml.saml2.core.impl.SessionIndexBuilder) SAML2UserManager(org.apache.syncope.core.logic.saml2.SAML2UserManager) LogoutRequestBuilder(org.opensaml.saml.saml2.core.impl.LogoutRequestBuilder) AuthDataAccessor(org.apache.syncope.core.spring.security.AuthDataAccessor) AccessTokenDAO(org.apache.syncope.core.persistence.api.dao.AccessTokenDAO) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) NameIDBuilder(org.opensaml.saml.saml2.core.impl.NameIDBuilder) ResourceUtils(org.springframework.util.ResourceUtils) SessionIndex(org.opensaml.saml.saml2.core.SessionIndex) URLEncoder(java.net.URLEncoder) Component(org.springframework.stereotype.Component) X509KeyInfoGeneratorFactory(org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory) RequestedAuthnContextBuilder(org.opensaml.saml.saml2.core.impl.RequestedAuthnContextBuilder) NameIDType(org.opensaml.saml.saml2.core.NameIDType) Generators(com.fasterxml.uuid.Generators) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) UserTO(org.apache.syncope.common.lib.to.UserTO) Collections(java.util.Collections) NameID(org.opensaml.saml.saml2.core.NameID) SAML2IdPEntity(org.apache.syncope.core.logic.saml2.SAML2IdPEntity) Attribute(org.opensaml.saml.saml2.core.Attribute) HashMap(java.util.HashMap) AttrTO(org.apache.syncope.common.lib.to.AttrTO) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) XSString(org.opensaml.core.xml.schema.XSString) XSAny(org.opensaml.core.xml.schema.XSAny) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) SSOValidatorResponse(org.apache.cxf.rs.security.saml.sso.SSOValidatorResponse) SAML2LoginResponseTO(org.apache.syncope.common.lib.to.SAML2LoginResponseTO) NameID(org.opensaml.saml.saml2.core.NameID) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Assertion(org.opensaml.saml.saml2.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) XSString(org.opensaml.core.xml.schema.XSString) Date(java.util.Date) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) Response(org.opensaml.saml.saml2.core.Response) SSOValidatorResponse(org.apache.cxf.rs.security.saml.sso.SSOValidatorResponse) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) SAML2IdPEntity(org.apache.syncope.core.logic.saml2.SAML2IdPEntity) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) UserTO(org.apache.syncope.common.lib.to.UserTO) XMLObject(org.opensaml.core.xml.XMLObject) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 64 with Collections

use of java.util.Collections in project syncope by apache.

the class SAML2UserManager method findMatchingUser.

@Transactional(readOnly = true)
public List<String> findMatchingUser(final String keyValue, final String idpKey) {
    List<String> result = new ArrayList<>();
    SAML2IdP idp = idpDAO.find(idpKey);
    if (idp == null) {
        LOG.warn("Invalid IdP: {}", idpKey);
        return result;
    }
    String transformed = keyValue;
    for (ItemTransformer transformer : MappingUtils.getItemTransformers(idp.getConnObjectKeyItem().get())) {
        List<Object> output = transformer.beforePull(null, null, Collections.<Object>singletonList(transformed));
        if (output != null && !output.isEmpty()) {
            transformed = output.get(0).toString();
        }
    }
    IntAttrName intAttrName;
    try {
        intAttrName = intAttrNameParser.parse(idp.getConnObjectKeyItem().get().getIntAttrName(), AnyTypeKind.USER);
    } catch (ParseException e) {
        LOG.error("Invalid intAttrName '{}' specified, ignoring", idp.getConnObjectKeyItem().get().getIntAttrName(), e);
        return result;
    }
    if (intAttrName.getField() != null) {
        switch(intAttrName.getField()) {
            case "key":
                User byKey = userDAO.find(transformed);
                if (byKey != null) {
                    result.add(byKey.getUsername());
                }
                break;
            case "username":
                User byUsername = userDAO.findByUsername(transformed);
                if (byUsername != null) {
                    result.add(byUsername.getUsername());
                }
                break;
            default:
        }
    } else if (intAttrName.getSchemaType() != null) {
        switch(intAttrName.getSchemaType()) {
            case PLAIN:
                PlainAttrValue value = entityFactory.newEntity(UPlainAttrValue.class);
                PlainSchema schema = plainSchemaDAO.find(intAttrName.getSchemaName());
                if (schema == null) {
                    value.setStringValue(transformed);
                } else {
                    try {
                        value.parseValue(schema, transformed);
                    } catch (ParsingValidationException e) {
                        LOG.error("While parsing provided key value {}", transformed, e);
                        value.setStringValue(transformed);
                    }
                }
                result.addAll(userDAO.findByPlainAttrValue(intAttrName.getSchemaName(), value).stream().map(user -> user.getUsername()).collect(Collectors.toList()));
                break;
            case DERIVED:
                result.addAll(userDAO.findByDerAttrValue(intAttrName.getSchemaName(), transformed).stream().map(user -> user.getUsername()).collect(Collectors.toList()));
                break;
            default:
        }
    }
    return result;
}
Also used : ItemTransformer(org.apache.syncope.core.provisioning.api.data.ItemTransformer) AttrTO(org.apache.syncope.common.lib.to.AttrTO) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) SerializationUtils(org.apache.commons.lang3.SerializationUtils) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) SAML2IdP(org.apache.syncope.core.persistence.api.entity.SAML2IdP) ArrayList(java.util.ArrayList) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) UPlainAttrValue(org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue) Pair(org.apache.commons.lang3.tuple.Pair) Propagation(org.springframework.transaction.annotation.Propagation) UserDataBinder(org.apache.syncope.core.provisioning.api.data.UserDataBinder) SAML2LoginResponseTO(org.apache.syncope.common.lib.to.SAML2LoginResponseTO) PropagationStatus(org.apache.syncope.common.lib.to.PropagationStatus) SAML2IdPDAO(org.apache.syncope.core.persistence.api.dao.SAML2IdPDAO) ParseException(java.text.ParseException) TemplateUtils(org.apache.syncope.core.provisioning.java.utils.TemplateUtils) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) Logger(org.slf4j.Logger) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) PlainSchemaDAO(org.apache.syncope.core.persistence.api.dao.PlainSchemaDAO) User(org.apache.syncope.core.persistence.api.entity.user.User) PlainAttrValue(org.apache.syncope.core.persistence.api.entity.PlainAttrValue) Collectors(java.util.stream.Collectors) MappingUtils(org.apache.syncope.core.provisioning.java.utils.MappingUtils) EntityFactory(org.apache.syncope.core.persistence.api.entity.EntityFactory) List(java.util.List) Component(org.springframework.stereotype.Component) SAML2IdPActions(org.apache.syncope.core.provisioning.api.SAML2IdPActions) UserProvisioningManager(org.apache.syncope.core.provisioning.api.UserProvisioningManager) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Optional(java.util.Optional) IntAttrNameParser(org.apache.syncope.core.provisioning.java.IntAttrNameParser) UserTO(org.apache.syncope.common.lib.to.UserTO) ApplicationContextProvider(org.apache.syncope.core.spring.ApplicationContextProvider) Collections(java.util.Collections) AnyOperations(org.apache.syncope.common.lib.AnyOperations) ParsingValidationException(org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException) IntAttrName(org.apache.syncope.core.provisioning.api.IntAttrName) Transactional(org.springframework.transaction.annotation.Transactional) UPlainAttrValue(org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue) User(org.apache.syncope.core.persistence.api.entity.user.User) ItemTransformer(org.apache.syncope.core.provisioning.api.data.ItemTransformer) ArrayList(java.util.ArrayList) IntAttrName(org.apache.syncope.core.provisioning.api.IntAttrName) ParsingValidationException(org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException) SAML2IdP(org.apache.syncope.core.persistence.api.entity.SAML2IdP) UPlainAttrValue(org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue) PlainAttrValue(org.apache.syncope.core.persistence.api.entity.PlainAttrValue) ParseException(java.text.ParseException) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Transactional(org.springframework.transaction.annotation.Transactional)

Example 65 with Collections

use of java.util.Collections in project syncope by apache.

the class GroupServiceImpl method replace.

@Override
public Response replace(final String id, final SCIMGroup group) {
    if (!id.equals(group.getId())) {
        throw new BadRequestException(ErrorType.invalidPath, "Expected " + id + ", found " + group.getId());
    }
    ResponseBuilder builder = checkETag(Resource.Group, id);
    if (builder != null) {
        return builder.build();
    }
    // save current group members
    Set<String> beforeMembers = new HashSet<>();
    MembershipCond membCond = new MembershipCond();
    membCond.setGroup(id);
    SearchCond searchCond = SearchCond.getLeafCond(membCond);
    int count = userLogic().search(searchCond, 1, 1, Collections.<OrderByClause>emptyList(), SyncopeConstants.ROOT_REALM, false).getLeft();
    for (int page = 1; page <= (count / AnyDAO.DEFAULT_PAGE_SIZE) + 1; page++) {
        beforeMembers.addAll(userLogic().search(searchCond, page, AnyDAO.DEFAULT_PAGE_SIZE, Collections.<OrderByClause>emptyList(), SyncopeConstants.ROOT_REALM, false).getRight().stream().map(EntityTO::getKey).collect(Collectors.toSet()));
    }
    // update group, don't change members
    ProvisioningResult<GroupTO> result = groupLogic().update(AnyOperations.diff(binder().toGroupTO(group), groupLogic().read(id), false), false);
    // assign new members
    Set<String> afterMembers = new HashSet<>();
    group.getMembers().forEach(member -> {
        afterMembers.add(member.getValue());
        if (!beforeMembers.contains(member.getValue())) {
            UserPatch patch = new UserPatch();
            patch.setKey(member.getValue());
            patch.getMemberships().add(new MembershipPatch.Builder().operation(PatchOperation.ADD_REPLACE).group(result.getEntity().getKey()).build());
            try {
                userLogic().update(patch, false);
            } catch (Exception e) {
                LOG.error("While setting membership of {} to {}", result.getEntity().getKey(), member.getValue(), e);
            }
        }
    });
    // remove unconfirmed members
    beforeMembers.stream().filter(member -> !afterMembers.contains(member)).forEach(user -> {
        UserPatch patch = new UserPatch();
        patch.setKey(user);
        patch.getMemberships().add(new MembershipPatch.Builder().operation(PatchOperation.DELETE).group(result.getEntity().getKey()).build());
        try {
            userLogic().update(patch, false);
        } catch (Exception e) {
            LOG.error("While removing membership of {} from {}", result.getEntity().getKey(), user, e);
        }
    });
    return updateResponse(result.getEntity().getKey(), binder().toSCIMGroup(result.getEntity(), uriInfo.getAbsolutePathBuilder().path(result.getEntity().getKey()).build().toASCIIString(), Collections.<String>emptyList(), Collections.<String>emptyList()));
}
Also used : Arrays(java.util.Arrays) BadRequestException(org.apache.syncope.ext.scimv2.api.BadRequestException) ErrorType(org.apache.syncope.ext.scimv2.api.type.ErrorType) OrderByClause(org.apache.syncope.core.persistence.api.dao.search.OrderByClause) ArrayUtils(org.apache.commons.lang3.ArrayUtils) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) ProvisioningResult(org.apache.syncope.common.lib.to.ProvisioningResult) StringUtils(org.apache.commons.lang3.StringUtils) HashSet(java.util.HashSet) MembershipPatch(org.apache.syncope.common.lib.patch.MembershipPatch) EntityTO(org.apache.syncope.common.lib.to.EntityTO) SortOrder(org.apache.syncope.ext.scimv2.api.type.SortOrder) ListResponse(org.apache.syncope.ext.scimv2.api.data.ListResponse) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) SCIMGroup(org.apache.syncope.ext.scimv2.api.data.SCIMGroup) SearchCond(org.apache.syncope.core.persistence.api.dao.search.SearchCond) Set(java.util.Set) GroupTO(org.apache.syncope.common.lib.to.GroupTO) Collectors(java.util.stream.Collectors) Resource(org.apache.syncope.ext.scimv2.api.type.Resource) Response(javax.ws.rs.core.Response) AnyDAO(org.apache.syncope.core.persistence.api.dao.AnyDAO) PatchOperation(org.apache.syncope.common.lib.types.PatchOperation) SCIMSearchRequest(org.apache.syncope.ext.scimv2.api.data.SCIMSearchRequest) Member(org.apache.syncope.ext.scimv2.api.data.Member) GroupService(org.apache.syncope.ext.scimv2.api.service.GroupService) MembershipCond(org.apache.syncope.core.persistence.api.dao.search.MembershipCond) Collections(java.util.Collections) AnyOperations(org.apache.syncope.common.lib.AnyOperations) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) MembershipCond(org.apache.syncope.core.persistence.api.dao.search.MembershipCond) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) BadRequestException(org.apache.syncope.ext.scimv2.api.BadRequestException) GroupTO(org.apache.syncope.common.lib.to.GroupTO) EntityTO(org.apache.syncope.common.lib.to.EntityTO) OrderByClause(org.apache.syncope.core.persistence.api.dao.search.OrderByClause) BadRequestException(org.apache.syncope.ext.scimv2.api.BadRequestException) SearchCond(org.apache.syncope.core.persistence.api.dao.search.SearchCond) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) HashSet(java.util.HashSet)

Aggregations

Collections (java.util.Collections)113 List (java.util.List)59 ArrayList (java.util.ArrayList)41 Test (org.junit.Test)39 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)34 Arrays (java.util.Arrays)28 HashMap (java.util.HashMap)26 Set (java.util.Set)25 HashSet (java.util.HashSet)23 IOException (java.io.IOException)19 Collection (java.util.Collection)19 Optional (java.util.Optional)19 TimeUnit (java.util.concurrent.TimeUnit)16 URI (java.net.URI)13 Assert (org.junit.Assert)13 Function (java.util.function.Function)12 Stream (java.util.stream.Stream)12 Before (org.junit.Before)12 Logger (org.slf4j.Logger)12