Example usage for java.util List containsAll

List of usage examples for java.util List containsAll

Introduction

In this page you can find the example usage for java.util List containsAll.

Prototype

boolean containsAll(Collection<?> c);

Source Link

Document

Returns true if this list contains all of the elements of the specified collection.

Usage

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

private boolean authorizeCaller(HttpServletRequest request, byte[] serviceToken, GSSName name,
        final Subject clientSubject) {

    // create Subject with principals from name
    final Subject kerberosServiceSubject = createSubject(name);

    final Set<Principal> kerberosServicePrincipals = kerberosServiceSubject.getPrincipals();

    if (kerberosServicePrincipals.size() > 0) {
        final Set<Principal> clientPrincipals = clientSubject.getPrincipals();

        clientPrincipals.addAll(kerberosServicePrincipals);

        // Pickup the first Principal as the caller
        final Principal caller = kerberosServicePrincipals.iterator().next();

        if (caller != null) {
            // Fetch the list of extra groups
            final Set<String> extraGroups = fetchExtraGroups(request, this.serviceSubject, this.options);

            // Let's add all the groups as valid Principal as part of the
            // clientSubject
            final String[] groups = buildGroupsFromPAC(serviceToken, this.serviceSubject, extraGroups);

            final List<String> groupList = Arrays.asList(groups);

            if (this.mandatoryGroups != null && this.mandatoryGroups.size() > 0) {
                // There was some mandatory group to check
                if (!groupList.containsAll(this.mandatoryGroups)) {
                    // None of the global constraint was found, so exiting
                    debug("Not all the mandatory groups required ({1}) where found in the user groups {0} so failing the authentication.",
                            groupList, this.mandatoryGroups);
                    return false;
                }/*from   w  w w . jav a2 s .  c  om*/
            }

            // Check global constraints
            if (this.smartcardSecuredUsersOnly || this.delegatedSecuredUsersOnly) {

                final List<String> contraintGroupList = new ArrayList<String>();
                if (this.smartcardSecuredUsersOnly) {
                    contraintGroupList.add(GROUP_SMARTCARD_AUTHENTICATED);
                }
                if (this.delegatedSecuredUsersOnly) {
                    contraintGroupList.add(GROUP_DELEGATED_AUTHENTICATED);
                }

                // Test if at least one of the constraints are matched
                if (Collections.disjoint(groupList, contraintGroupList)) {
                    // None of the global constraint was found, so exiting
                    debug("The global contrainted group {1} where not found in the user groups {0} so failing the authentication.",
                            groupList, contraintGroupList);
                    return false;
                }

            }

            final GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject,
                    groups);
            try {
                // notify caller for the groups
                this.handler.handle(new Callback[] { groupPrincipalCallback });
                debug("Groups found {0}", groupList);
            } catch (final IOException e) {
                LOG.log(Level.WARNING, "Unable to set the groups " + groupList, e);
            } catch (final UnsupportedCallbackException e) {
                LOG.log(Level.WARNING, "Unable to set the groups " + groupList, e);
            }
        }

        // Create the caller principal to pass to caller
        final CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(clientSubject,
                caller);

        try {
            // notify caller for the Principal
            this.handler.handle(new Callback[] { callerPrincipalCallback });
            debug("Caller principal is {0}", (Object) caller);
            return true;
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to set caller principal {0}", e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to set caller principal {0}", e);
        }
    }
    return false;
}

From source file:com.redhat.rhn.frontend.xmlrpc.kickstart.profile.ProfileHandler.java

/**
 * Set advanced options in a kickstart profile
 * @param loggedInUser The current user//from ww  w  .  j a  v a  2 s. c  om
 * @param ksLabel the kickstart label
 * @param options the advanced options to set
 * @return 1 if success, exception otherwise
 * @throws FaultException A FaultException is thrown if
 *         the profile associated with ksLabel cannot be found
 *         or invalid advanced option is provided
 *
 * @xmlrpc.doc Set advanced options for a kickstart profile.
 * If 'md5_crypt_rootpw' is set to 'True', 'root_pw' is taken as plaintext and
 * will md5 encrypted on server side, otherwise a hash encoded password
 * (according to the auth option) is expected
 * @xmlrpc.param #session_key()
 * @xmlrpc.param #param("string","ksLabel")
 * @xmlrpc.param
 *   #array()
 *      #struct("advanced options")
 *          #prop_desc("string", "name", "Name of the advanced option.
 *              Valid Option names: autostep, interactive, install, upgrade, text,
 *              network, cdrom, harddrive, nfs, url, lang, langsupport keyboard,
 *              mouse, device, deviceprobe, zerombr, clearpart, bootloader,
 *              timezone, auth, rootpw, selinux, reboot, firewall, xconfig, skipx,
 *              key, ignoredisk, autopart, cmdline, firstboot, graphical, iscsi,
 *              iscsiname, logging, monitor, multipath, poweroff, halt, services,
 *              shutdown, user, vnc, zfcp, driverdisk, md5_crypt_rootpw")
 *          #prop_desc("string", "arguments", "Arguments of the option")
 *      #struct_end()
 *   #array_end()
 * @xmlrpc.returntype #return_int_success()
 */
public int setAdvancedOptions(User loggedInUser, String ksLabel, List<Map> options) throws FaultException {
    KickstartData ksdata = KickstartFactory.lookupKickstartDataByLabelAndOrgId(ksLabel,
            loggedInUser.getOrg().getId());
    if (ksdata == null) {
        throw new FaultException(-3, "kickstartProfileNotFound",
                "No Kickstart Profile found with label: " + ksLabel);
    }

    List<String> validOptions = Arrays.asList(VALIDOPTIONNAMES);

    Set<String> givenOptions = new HashSet<String>();
    for (Map option : options) {
        givenOptions.add((String) option.get("name"));
    }

    if (!validOptions.containsAll(givenOptions)) {
        throw new FaultException(-5, "invalidKickstartCommandName",
                "Invalid kickstart option present. List of valid options is: " + validOptions);
    }

    Long ksid = ksdata.getId();
    KickstartOptionsCommand cmd = new KickstartOptionsCommand(ksid, loggedInUser);

    //check if all the required options are present
    List<KickstartCommandName> requiredOptions = KickstartFactory.lookupKickstartRequiredOptions();

    List<String> requiredOptionNames = new ArrayList<String>();
    for (KickstartCommandName kcn : requiredOptions) {
        requiredOptionNames.add(kcn.getName());
    }

    if (!givenOptions.containsAll(requiredOptionNames)) {
        throw new FaultException(-6, "requiredOptionMissing",
                "Required option missing. List of required options: " + requiredOptionNames);
    }

    Set<KickstartCommand> customSet = new HashSet<KickstartCommand>();

    for (Iterator itr = cmd.getAvailableOptions().iterator(); itr.hasNext();) {
        Map option = null;
        KickstartCommandName cn = (KickstartCommandName) itr.next();
        if (givenOptions.contains(cn.getName())) {
            for (Map o : options) {
                if (cn.getName().equals(o.get("name"))) {
                    option = o;
                    break;
                }
            }

            KickstartCommand kc = new KickstartCommand();
            kc.setCommandName(cn);
            kc.setKickstartData(cmd.getKickstartData());
            kc.setCreated(new Date());
            kc.setModified(new Date());
            if (cn.getArgs().booleanValue()) {
                // handle password encryption
                if (cn.getName().equals("rootpw")) {
                    String pwarg = (String) option.get("arguments");
                    // password already encrypted
                    if (!md5cryptRootPw(options)) {
                        kc.setArguments(pwarg);
                    }
                    // password changed, encrypt it
                    else {
                        kc.setArguments(MD5Crypt.crypt(pwarg));
                    }
                } else {
                    kc.setArguments((String) option.get("arguments"));
                }
            }
            customSet.add(kc);
        }
    }
    cmd.getKickstartData().setOptions(customSet);
    KickstartFactory.saveKickstartData(ksdata);

    return 1;
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@SuppressWarnings("unchecked")
@Override/*from  ww w  .  j  ava 2 s .  c o  m*/
public RaEndEntitySearchResponse searchForEndEntities(AuthenticationToken authenticationToken,
        RaEndEntitySearchRequest request) {
    final RaEndEntitySearchResponse response = new RaEndEntitySearchResponse();
    final List<Integer> authorizedLocalCaIds = new ArrayList<>(
            caSession.getAuthorizedCaIds(authenticationToken));
    // Only search a subset of the requested CAs if requested
    if (!request.getCaIds().isEmpty()) {
        authorizedLocalCaIds.retainAll(request.getCaIds());
    }
    if (authorizedLocalCaIds.isEmpty()) {
        // Empty response since there were no authorized CAs
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CAs and the search request will be dropped.");
        }
        return response;
    }
    // Check Certificate Profile authorization
    final List<Integer> authorizedCpIds = new ArrayList<>(
            certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0));
    final boolean accessAnyCpAvailable = authorizedCpIds
            .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet());
    if (!request.getCpIds().isEmpty()) {
        authorizedCpIds.retainAll(request.getCpIds());
    }
    if (authorizedCpIds.isEmpty()) {
        // Empty response since there were no authorized Certificate Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CPs and the search request will be dropped.");
        }
        return response;
    }
    // Check End Entity Profile authorization
    final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession
            .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY));
    final boolean accessAnyEepAvailable = authorizedEepIds
            .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet());
    if (!request.getEepIds().isEmpty()) {
        authorizedEepIds.retainAll(request.getEepIds());
    }
    if (authorizedEepIds.isEmpty()) {
        // Empty response since there were no authorized End Entity Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested EEPs and the search request will be dropped.");
        }
        return response;
    }
    final String subjectDnSearchString = request.getSubjectDnSearchString();
    final String subjectAnSearchString = request.getSubjectAnSearchString();
    final String usernameSearchString = request.getUsernameSearchString();
    final StringBuilder sb = new StringBuilder("SELECT a.username FROM UserData a WHERE (a.caId IN (:caId))");
    if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty()
            || !usernameSearchString.isEmpty()) {
        sb.append(" AND (");
        boolean firstAppended = false;
        if (!subjectDnSearchString.isEmpty()) {
            sb.append("a.subjectDN LIKE :subjectDN");
            firstAppended = true;
        }
        if (!subjectAnSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.subjectAltName LIKE :subjectAltName");
        }
        if (!usernameSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.username LIKE :username");
        }
        sb.append(")");
    }

    if (request.isModifiedAfterUsed()) {
        sb.append(" AND (a.timeModified > :modifiedAfter)");
    }
    if (request.isModifiedBeforeUsed()) {
        sb.append(" AND (a.timeModified < :modifiedBefore)");
    }
    if (!request.getStatuses().isEmpty()) {
        sb.append(" AND (a.status IN (:status))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" CP is requested
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))");
    }
    final Query query = entityManager.createQuery(sb.toString());
    query.setParameter("caId", authorizedLocalCaIds);
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        query.setParameter("certificateProfileId", authorizedCpIds);
    }
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        query.setParameter("endEntityProfileId", authorizedEepIds);
    }
    if (log.isDebugEnabled()) {
        log.debug(" CA IDs: " + Arrays.toString(authorizedLocalCaIds.toArray()));
        if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
            log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray()));
        } else {
            log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access.");
        }
        if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
            log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray()));
        } else {
            log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access.");
        }
    }
    if (!subjectDnSearchString.isEmpty()) {
        if (request.isSubjectDnSearchExact()) {
            query.setParameter("subjectDN", subjectDnSearchString);
        } else {
            query.setParameter("subjectDN", "%" + subjectDnSearchString + "%");
        }
    }
    if (!subjectAnSearchString.isEmpty()) {
        if (request.isSubjectAnSearchExact()) {
            query.setParameter("subjectAltName", subjectAnSearchString);
        } else {
            query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%");
        }
    }
    if (!usernameSearchString.isEmpty()) {
        if (request.isUsernameSearchExact()) {
            query.setParameter("username", usernameSearchString);
        } else {
            query.setParameter("username", "%" + usernameSearchString + "%");
        }
    }
    if (request.isModifiedAfterUsed()) {
        query.setParameter("modifiedAfter", request.getModifiedAfter());
    }
    if (request.isModifiedBeforeUsed()) {
        query.setParameter("modifiedBefore", request.getModifiedBefore());
    }
    if (!request.getStatuses().isEmpty()) {
        query.setParameter("status", request.getStatuses());
    }
    final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(),
            request.getMaxResults());
    query.setMaxResults(maxResults);
    /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors:
     * - The hint is ignored
     * - A QueryTimeoutException is thrown
     * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back)
     */
    final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout();
    if (queryTimeout > 0L) {
        query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout));
    }
    final List<String> usernames;
    try {
        usernames = query.getResultList();
        for (final String username : usernames) {
            response.getEndEntities().add(endEntityAccessSession.findUser(username));
        }
        response.setMightHaveMoreResults(usernames.size() == maxResults);
        if (log.isDebugEnabled()) {
            log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 "
                    + usernames.size() + " results. queryTimeout=" + queryTimeout + "ms");
        }
    } catch (QueryTimeoutException e) {
        log.info("Requested search query by " + authenticationToken + " took too long. Query was "
                + e.getQuery().toString() + ". " + e.getMessage());
        response.setMightHaveMoreResults(true);
    } catch (PersistenceException e) {
        log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. "
                + e.getMessage());
        response.setMightHaveMoreResults(true);
    }
    return response;
}

From source file:fragment.web.UsersControllerTest.java

@SuppressWarnings("unchecked")
@Test/*from   w ww. java2s  .co m*/
public void testUsersListShowTenant() {
    asRoot();
    Tenant tenant = getDefaultTenant();
    List<User> expected = userService.list(0, 0, null, null, false, null, tenant.getId().toString(), null);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    String view = controller.listUsersForAccount(controller.getTenant(), true, null, map, session, null, 1, 20,
            "true", mockRequest);
    Assert.assertEquals("users.list_with_admin_menu", view);
    Assert.assertTrue(map.containsKey("users"));
    List<User> found = (List<User>) map.get("users");
    Assert.assertTrue(found.containsAll(expected));
}

From source file:fragment.web.UsersControllerTest.java

@SuppressWarnings("unchecked")
@Test// ww w  . jav a  2s.c  om
public void testUsersListShowForSurrogatedTenant() {
    asRoot();
    Tenant tenant = getDefaultTenant();
    List<User> expected = userService.list(0, 0, null, null, false, null, tenant.getId().toString(), null);
    HttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setAttribute("isSurrogatedTenant", Boolean.TRUE);
    String view = controller.listUsersForAccount(controller.getTenant(), false, tenant.getParam(), map, session,
            null, 1, 20, "true", mockRequest);
    Assert.assertEquals("users.list_with_user_menu", view);
    Assert.assertTrue(map.containsKey("users"));
    List<User> found = (List<User>) map.get("users");
    Assert.assertTrue(found.containsAll(expected));
}

From source file:fragment.web.UsersControllerTest.java

@SuppressWarnings("unchecked")
@Test//  ww w  .  j av  a  2  s  . co  m
public void testUsersList() {
    User user = userDAO.find(3L);
    asUser(user);
    List<User> expected = userService.list(0, 0, null, null, false, null, user.getTenant().getId().toString(),
            null);
    MockHttpServletRequest mockrequest = new MockHttpServletRequest();
    String view = controller.listUsersForAccount(controller.getTenant(), true, null, map, session, null, 1, 20,
            "true", mockrequest);
    Assert.assertEquals("users.nonroot.list_with_user_menu", view);
    Assert.assertTrue(map.containsKey("users"));
    List<User> found = (List<User>) map.get("users");
    Assert.assertTrue(found.containsAll(expected));
    Assert.assertTrue(map.get("page") == Page.ADMIN_ALL_USERS);
}

From source file:fragment.web.UsersControllerTest.java

@SuppressWarnings("unchecked")
@Test//w ww  . j av a  2s. co  m
public void testUsersListWithUserParam() {
    User user = userDAO.find(3L);
    asUser(user);
    List<User> expected = userService.list(0, 0, null, null, false, null, user.getTenant().getId().toString(),
            null);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    String view = controller.listUsersForAccount(controller.getTenant(), true, null, map, session,
            user.getParam(), 1, 20, "true", mockRequest);
    Assert.assertEquals("users.nonroot.list_with_user_menu", view);
    Assert.assertTrue(map.containsKey("users"));
    List<User> found = (List<User>) map.get("users");
    Assert.assertTrue(found.containsAll(expected));
    Assert.assertTrue(map.get("page") == Page.ADMIN_ALL_USERS);
}

From source file:org.openecomp.sdc.be.components.impl.GroupBusinessLogic.java

/**
 * @param groups//  w ww.jav  a  2 s  . c o  m
 * @param component
 * @param getByParam
 *            - the method to fetch the key of the GroupDefinition(from groups) in order to compare to groups in the component
 * @return
 */
private ResponseFormat validateGroupsInComponentByFunc(List<GroupDefinition> groups,
        org.openecomp.sdc.be.model.Component component, Function<GroupDefinition, String> getByParam) {
    ResponseFormat result = null;

    List<GroupDefinition> currentGroups = component.getGroups();

    boolean found = false;
    List<String> updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList());

    List<String> missingGroupNames = updatedGroupsName;

    if (currentGroups != null && false == currentGroups.isEmpty()) {
        List<String> currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList());

        if (currentGroupsName.containsAll(updatedGroupsName)) {
            found = true;
        } else {
            currentGroupsName.removeAll(currentGroupsName);
            missingGroupNames = currentGroupsName;
        }
    }
    if (false == found) {
        String componentTypeForResponse = getComponentTypeForResponse(component);
        String listOfGroups = getAsString(missingGroupNames);
        result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups,
                component.getSystemName(), componentTypeForResponse);
        return result;
    }

    return null;
}

From source file:org.kie.scanner.KieRepositoryScannerTest.java

private void checkUpdateDRLInSameSession(String drl1, String drl2) throws IOException {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");

    InternalKieModule kJar1 = createKieJarFromDrl(ks, releaseId, drl1);

    KieMavenRepository repository = getKieMavenRepository();
    repository.installArtifact(releaseId, kJar1, createKPom(fileManager, releaseId));

    KieContainer kieContainer = ks.newKieContainer(releaseId);
    KieScanner scanner = ks.newKieScanner(kieContainer);

    KieSession ksession = kieContainer.newKieSession("KSession1");

    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);
    ksession.insert("111");
    ksession.fireAllRules();//from  w w  w .  j  a  v a2  s .  c  o  m
    assertEquals(1, list.size());
    assertEquals("XXX:111", list.get(0));
    list.clear();

    InternalKieModule kJar2 = createKieJarFromDrl(ks, releaseId, drl2);
    repository.installArtifact(releaseId, kJar2, createKPom(fileManager, releaseId));

    scanner.scanNow();

    ksession.insert("222");
    ksession.fireAllRules();
    assertEquals(2, list.size());
    assertTrue(list.containsAll(asList("YYY:111", "YYY:222")));

    ks.getRepository().removeKieModule(releaseId);
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@SuppressWarnings("unchecked")
@Override//from   w w w.j  ava2s.  co m
public RaCertificateSearchResponse searchForCertificates(AuthenticationToken authenticationToken,
        RaCertificateSearchRequest request) {
    final RaCertificateSearchResponse response = new RaCertificateSearchResponse();
    final List<Integer> authorizedLocalCaIds = new ArrayList<>(
            caSession.getAuthorizedCaIds(authenticationToken));
    // Only search a subset of the requested CAs if requested
    if (!request.getCaIds().isEmpty()) {
        authorizedLocalCaIds.retainAll(request.getCaIds());
    }
    final List<String> issuerDns = new ArrayList<>();
    for (final int caId : authorizedLocalCaIds) {
        try {
            final String issuerDn = CertTools
                    .stringToBCDNString(StringTools.strip(caSession.getCAInfoInternal(caId).getSubjectDN()));
            issuerDns.add(issuerDn);
        } catch (CADoesntExistsException e) {
            log.warn("CA went missing during search operation. " + e.getMessage());
        }
    }
    if (issuerDns.isEmpty()) {
        // Empty response since there were no authorized CAs
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CAs and the search request will be dropped.");
        }
        return response;
    }
    // Check Certificate Profile authorization
    final List<Integer> authorizedCpIds = new ArrayList<>(
            certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0));
    final boolean accessAnyCpAvailable = authorizedCpIds
            .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet());
    if (!request.getCpIds().isEmpty()) {
        authorizedCpIds.retainAll(request.getCpIds());
    }
    if (authorizedCpIds.isEmpty()) {
        // Empty response since there were no authorized Certificate Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CPs and the search request will be dropped.");
        }
        return response;
    }
    // Check End Entity Profile authorization
    final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession
            .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY));
    final boolean accessAnyEepAvailable = authorizedEepIds
            .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet());
    if (!request.getEepIds().isEmpty()) {
        authorizedEepIds.retainAll(request.getEepIds());
    }
    if (authorizedEepIds.isEmpty()) {
        // Empty response since there were no authorized End Entity Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested EEPs and the search request will be dropped.");
        }
        return response;
    }
    final String subjectDnSearchString = request.getSubjectDnSearchString();
    final String subjectAnSearchString = request.getSubjectAnSearchString();
    final String usernameSearchString = request.getUsernameSearchString();
    final String serialNumberSearchStringFromDec = request.getSerialNumberSearchStringFromDec();
    final String serialNumberSearchStringFromHex = request.getSerialNumberSearchStringFromHex();
    final StringBuilder sb = new StringBuilder(
            "SELECT a.fingerprint FROM CertificateData a WHERE (a.issuerDN IN (:issuerDN))");
    if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty() || !usernameSearchString.isEmpty()
            || !serialNumberSearchStringFromDec.isEmpty() || !serialNumberSearchStringFromHex.isEmpty()) {
        sb.append(" AND (");
        boolean firstAppended = false;
        if (!subjectDnSearchString.isEmpty()) {
            sb.append("a.subjectDN LIKE :subjectDN");
            firstAppended = true;
        }
        if (!subjectAnSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.subjectAltName LIKE :subjectAltName");
        }
        if (!usernameSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.username LIKE :username");
        }
        if (!serialNumberSearchStringFromDec.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.serialNumber LIKE :serialNumberDec");
        }
        if (!serialNumberSearchStringFromHex.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            }
            sb.append("a.serialNumber LIKE :serialNumberHex");
        }
        sb.append(")");
    }
    // NOTE: notBefore is not indexed.. we might want to disallow such search.
    if (request.isIssuedAfterUsed()) {
        sb.append(" AND (a.notBefore > :issuedAfter)");
    }
    if (request.isIssuedBeforeUsed()) {
        sb.append(" AND (a.notBefore < :issuedBefore)");
    }
    if (request.isExpiresAfterUsed()) {
        sb.append(" AND (a.expireDate > :expiresAfter)");
    }
    if (request.isExpiresBeforeUsed()) {
        sb.append(" AND (a.expireDate < :expiresBefore)");
    }
    // NOTE: revocationDate is not indexed.. we might want to disallow such search.
    if (request.isRevokedAfterUsed()) {
        sb.append(" AND (a.revocationDate > :revokedAfter)");
    }
    if (request.isRevokedBeforeUsed()) {
        sb.append(" AND (a.revocationDate < :revokedBefore)");
    }
    if (!request.getStatuses().isEmpty()) {
        sb.append(" AND (a.status IN (:status))");
        if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED)
                || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED))
                && !request.getRevocationReasons().isEmpty()) {
            sb.append(" AND (a.revocationReason IN (:revocationReason))");
        }
    }
    // Don't constrain results to certain certificate profiles if root access is available and "any" CP is requested
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))");
    }
    final Query query = entityManager.createQuery(sb.toString());
    query.setParameter("issuerDN", issuerDns);
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        query.setParameter("certificateProfileId", authorizedCpIds);
    }
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        query.setParameter("endEntityProfileId", authorizedEepIds);
    }
    if (log.isDebugEnabled()) {
        log.debug(" issuerDN: " + Arrays.toString(issuerDns.toArray()));
        if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
            log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray()));
        } else {
            log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access.");
        }
        if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
            log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray()));
        } else {
            log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access.");
        }
    }
    if (!subjectDnSearchString.isEmpty()) {
        if (request.isSubjectDnSearchExact()) {
            query.setParameter("subjectDN", subjectDnSearchString);
        } else {
            query.setParameter("subjectDN", "%" + subjectDnSearchString + "%");
        }
    }
    if (!subjectAnSearchString.isEmpty()) {
        if (request.isSubjectAnSearchExact()) {
            query.setParameter("subjectAltName", subjectAnSearchString);
        } else {
            query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%");
        }
    }
    if (!usernameSearchString.isEmpty()) {
        if (request.isUsernameSearchExact()) {
            query.setParameter("username", usernameSearchString);
        } else {
            query.setParameter("username", "%" + usernameSearchString + "%");
        }
    }
    if (!serialNumberSearchStringFromDec.isEmpty()) {
        query.setParameter("serialNumberDec", serialNumberSearchStringFromDec);
        if (log.isDebugEnabled()) {
            log.debug(" serialNumberDec: " + serialNumberSearchStringFromDec);
        }
    }
    if (!serialNumberSearchStringFromHex.isEmpty()) {
        query.setParameter("serialNumberHex", serialNumberSearchStringFromHex);
        if (log.isDebugEnabled()) {
            log.debug(" serialNumberHex: " + serialNumberSearchStringFromHex);
        }
    }
    if (request.isIssuedAfterUsed()) {
        query.setParameter("issuedAfter", request.getIssuedAfter());
    }
    if (request.isIssuedBeforeUsed()) {
        query.setParameter("issuedBefore", request.getIssuedBefore());
    }
    if (request.isExpiresAfterUsed()) {
        query.setParameter("expiresAfter", request.getExpiresAfter());
    }
    if (request.isExpiresBeforeUsed()) {
        query.setParameter("expiresBefore", request.getExpiresBefore());
    }
    if (request.isRevokedAfterUsed()) {
        query.setParameter("revokedAfter", request.getRevokedAfter());
    }
    if (request.isRevokedBeforeUsed()) {
        query.setParameter("revokedBefore", request.getRevokedBefore());
    }
    if (!request.getStatuses().isEmpty()) {
        query.setParameter("status", request.getStatuses());
        if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED)
                || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED))
                && !request.getRevocationReasons().isEmpty()) {
            query.setParameter("revocationReason", request.getRevocationReasons());
        }
    }
    final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(),
            request.getMaxResults());
    query.setMaxResults(maxResults);
    /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors:
     * - The hint is ignored
     * - A QueryTimeoutException is thrown
     * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back)
     */
    final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout();
    if (queryTimeout > 0L) {
        query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout));
    }
    final List<String> fingerprints;
    try {
        fingerprints = query.getResultList();
        for (final String fingerprint : fingerprints) {
            response.getCdws().add(certificateStoreSession.getCertificateData(fingerprint));
        }
        response.setMightHaveMoreResults(fingerprints.size() == maxResults);
        if (log.isDebugEnabled()) {
            log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 "
                    + fingerprints.size() + " results. queryTimeout=" + queryTimeout + "ms");
        }
    } catch (QueryTimeoutException e) {
        // Query.toString() does not return the SQL query executed just a java object hash. If Hibernate is being used we can get it using:
        // query.unwrap(org.hibernate.Query.class).getQueryString()
        // We don't have access to hibernate when building this class though, all querying should be moved to the ejbca-entity package.
        // See ECA-5341
        String queryString = e.getQuery().toString();
        //            try {
        //                queryString = e.getQuery().unwrap(org.hibernate.Query.class).getQueryString();
        //            } catch (PersistenceException pe) {
        //                log.debug("Query.unwrap(org.hibernate.Query.class) is not supported by JPA provider");
        //            }
        log.info("Requested search query by " + authenticationToken + " took too long. Query was '"
                + queryString + "'. " + e.getMessage());
        response.setMightHaveMoreResults(true);
    } catch (PersistenceException e) {
        log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. "
                + e.getMessage());
        response.setMightHaveMoreResults(true);
    }
    return response;
}