Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

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

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:org.sakaiproject.signup.tool.jsf.organizer.OrganizerSignupMBean.java

/**
 * Synchronise the users in a timeslot with the users in a group.
 * VT customized to allow the user choose the synchronize direction
         /*from  ww w  .  j a  v  a  2  s.  c  o m*/
 * @return url to the same page which will trigger a reload
 */
public String synchroniseGroupMembership() {

    TimeslotWrapper timeslotWrapper = (TimeslotWrapper) timeslotWrapperTable.getRowData();

    //get groupId for timeslot
    String groupId = timeslotWrapper.getGroupId();
    SignupMeeting meeting = null;

    if (StringUtils.isBlank(groupId)) {
        //TODO. 
        //Create the group. Grab the list of attendees in the timeslot and add all at once.
        //Will need to also save the groupId into the timeslot.
        //For now, we just give a message.

        Utilities.addErrorMessage(Utilities.rb.getString("error.no_group_for_timeslot"));
        return ORGANIZER_MEETING_PAGE_URL;
    } else {
        List<String> attendeeUserIds = convertAttendeeWrappersToUuids(timeslotWrapper.getAttendeeWrappers());

        //process to synchronize the time slot attendees to group

        if (timeslottoGroup != null && !timeslottoGroup.trim().isEmpty()
                && !sakaiFacade.addUsersToGroup(attendeeUserIds, currentSiteId(), groupId, timeslottoGroup)) {
            Utilities.addErrorMessage(Utilities.rb.getString("error.group_sync_failed"));
            return ORGANIZER_MEETING_PAGE_URL;
        }

        //retrieve all members in group
        List<String> groupMembers = sakaiFacade.getGroupMembers(currentSiteId(), groupId);

        //process to synchronize from site group members to time slot
        if (timeslottoGroup == null || timeslottoGroup.isEmpty()) {

            //1. first to keep the common members of timeslot and group

            List<String> commonmem = new ArrayList<String>(attendeeUserIds);
            commonmem.retainAll(groupMembers);

            //2. only add the group members not existed in timeslot
            groupMembers.removeAll(attendeeUserIds);

            //3. remove the time slot attendees that existed only in timeslot
            try {
                for (String mem : attendeeUserIds) {
                    if (!commonmem.contains(mem)) {
                        CancelAttendee remove = new CancelAttendee(signupMeetingService, currentUserId(),
                                currentSiteId(), true);
                        SignupAttendee removedAttendee = new SignupAttendee(mem, currentSiteId());
                        meeting = remove.cancelSignup(getMeetingWrapper().getMeeting(),
                                timeslotWrapper.getTimeSlot(), removedAttendee);
                        if (sendEmail) {
                            try {
                                signupMeetingService.sendEmailToParticipantsByOrganizerAction(
                                        remove.getSignupEventTrackingInfo());
                            } catch (Exception e) {
                                logger.error(Utilities.rb.getString("email.exception") + " - " + e.getMessage(),
                                        e);
                                Utilities.addErrorMessage(Utilities.rb.getString("email.exception"));
                            }
                        }
                    }
                }
            } catch (SignupUserActionException ue) {
                Utilities.addErrorMessage(ue.getMessage());
            } catch (Exception e) {
                logger.error(Utilities.rb.getString("error.occurred_try_again") + " - " + e.getMessage());
                Utilities.addErrorMessage(Utilities.rb.getString("error.occurred_try_again"));
            }
        } else {
            //remove all of the existing attendees from this list to remove duplicates
            groupMembers.removeAll(attendeeUserIds);
        }

        //add members and go to return page
        return addAttendeesToTimeslot(currentSiteId(), timeslotWrapper, groupMembers);
    }
}

From source file:netdecoder.NetDecoder.java

public int correlationChange(String gene, Map<String, Node> controlNetwork, Map<String, Node> diseaseNetwork) {

    int count = 1;
    if (controlNetwork.containsKey(gene) && diseaseNetwork.containsKey(gene)) {
        Node geneControl = controlNetwork.get(gene);
        Node geneDisease = diseaseNetwork.get(gene);

        List<Edge> edgesControl = geneControl.getEdges();
        List<Edge> edgesDisease = geneDisease.getEdges();

        List<Edge> aux = new ArrayList(edgesControl);
        aux.retainAll(edgesDisease);
        for (Edge e : aux) {
            int iControl = edgesControl.indexOf(e);
            int iDisease = edgesDisease.indexOf(e);
            Double sigControl = Math.signum(edgesControl.get(iControl).getSignScore());
            Double sigDisease = Math.signum(edgesDisease.get(iDisease).getSignScore());
            if (!sigControl.equals(sigDisease)) {
                count++;/*from w  w  w .  j a v  a2s . c  o m*/
                //System.out.println(e + "\t" + edgesControl.get(iControl).getSignScore());
                //System.out.println(e + "\t" + edgesDisease.get(iDisease).getSignScore());
            }
        }
    }
    return count;
}

From source file:com.enonic.vertical.userservices.UserHandlerController.java

protected void handlerLeaveGroup(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems) throws VerticalUserServicesException, RemoteException {
    UserEntity user = securityService.getLoggedInPortalUserAsEntity();
    UserEntity executor = securityService.getRunAsUser();
    if (user == null) {
        String message = "User must be logged in.";
        VerticalUserServicesLogger.warn(this.getClass(), 0, message, null);
        redirectToErrorPage(request, response, formItems, ERR_USER_NOT_LOGGED_IN, null);
        return;/*  w  ww  . j  av  a 2  s.com*/
    }

    String[] requiredParameters = new String[] { "key" };

    List<String> missingParameters = findMissingRequiredParameters(requiredParameters, formItems, true);

    if (!missingParameters.isEmpty()) {
        String message = createMissingParametersMessage("Leave group", missingParameters);

        VerticalUserServicesLogger.warn(this.getClass(), 0, message, null);
        redirectToErrorPage(request, response, formItems, ERR_PARAMETERS_MISSING, null);
        return;
    }

    List<GroupKey> submittedGroupKeysToRemove = getSubmittedGroupKeys(formItems, "key");
    List<GroupKey> existingKeysForUser = getExistingDirectMembershipsForUser(user);
    submittedGroupKeysToRemove.retainAll(existingKeysForUser);

    if (submittedGroupKeysToRemove.size() >= 1) {

        GroupSpecification userGroupForLoggedInUser = new GroupSpecification();
        userGroupForLoggedInUser.setKey(user.getUserGroupKey());

        RemoveMembershipsCommand removeMembershipsCommand = new RemoveMembershipsCommand(
                userGroupForLoggedInUser, executor.getKey());
        removeMembershipsCommand.setUpdateOpenGroupsOnly(true);
        removeMembershipsCommand.setRespondWithException(true);
        for (GroupKey groupKeyToRemove : submittedGroupKeysToRemove) {
            removeMembershipsCommand.addGroupToRemoveFrom(groupKeyToRemove);
        }

        try {
            userStoreService.removeMembershipsFromGroup(removeMembershipsCommand);
            updateUserInSession(session);
        } catch (UserStoreAccessException e) {
            String message = "Not allowed to remove user from group: %t";
            VerticalUserServicesLogger.warn(this.getClass(), 0, message, e);
            redirectToErrorPage(request, response, formItems, ERR_JOIN_GROUP_NOT_ALLOWED, null);
            return;
        } catch (RuntimeException e) {
            VerticalUserServicesLogger.warn(this.getClass(), 0, e.getMessage(), e);
            redirectToErrorPage(request, response, formItems, ERR_JOIN_GROUP_FAILED, null);
            return;
        }
    }

    redirectToPage(request, response, formItems);
}

From source file:org.hyperic.hq.ui.servlet.MetricDataServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    int sessionId = RequestUtils.getSessionId(request).intValue();
    WebUser user = RequestUtils.getWebUser(request);

    // Load required eid and m attributes.
    AppdefEntityID id;//w  ww .j a  v  a  2  s.  com
    Integer mid;
    try {
        mid = RequestUtils.getIntParameter(request, "metricId");
        id = RequestUtils.getEntityId(request);
    } catch (ParameterNotFoundException e) {
        throw new ServletException("No metric parameter given.");
    }

    // Optional ctype
    AppdefEntityTypeID typeId = null;
    try {
        typeId = RequestUtils.getChildResourceTypeId(request);
    } catch (ParameterNotFoundException e) {
        // Ok
    }

    // Load time range
    Map prefs = user.getMetricRangePreference();
    Long end = (Long) prefs.get(MonitorUtils.END);
    Long begin = (Long) prefs.get(MonitorUtils.BEGIN);

    // The list of resources to generate data for
    List resources = new ArrayList();
    if (typeId != null) {
        try {
            resources.addAll(Bootstrap.getBean(AppdefBoss.class).findChildResources(sessionId, id, typeId,
                    PageControl.PAGE_ALL));
        } catch (Exception e) {
            throw new ServletException("Error finding child resources.", e);
        }
    } else if (id.isGroup()) {
        List entities;
        AppdefGroupValue gval;
        try {
            gval = Bootstrap.getBean(AppdefBoss.class).findGroup(sessionId, id.getId());
            entities = gval.getAppdefGroupEntries();
        } catch (Exception e) {
            throw new ServletException("Error finding group=" + id, e);
        }

        // HHQ-2865: Get list of checked resources to export.
        // The instanceIds request parameter is in javascript array format --> [...]
        String instanceIds = RequestUtils.getStringParameter(request, "instanceIds", "");
        if (instanceIds.length() > 2) {
            try {
                List requestedEntityIds = new ArrayList();
                JSONArray arr = new JSONArray(instanceIds);

                for (int i = 0; i < arr.length(); i++) {
                    requestedEntityIds
                            .add(new AppdefEntityID(gval.getGroupEntType(), Integer.valueOf(arr.getInt(i))));
                }
                // Filter requested resource ids in case of invalid parameters
                if (!requestedEntityIds.isEmpty()) {
                    entities.retainAll(requestedEntityIds);
                }
            } catch (JSONException e) {
                throw new ServletException("Error finding group resources.", e);
            }
        }

        for (Iterator i = entities.iterator(); i.hasNext();) {
            try {
                resources.add(
                        Bootstrap.getBean(AppdefBoss.class).findById(sessionId, (AppdefEntityID) i.next()));
            } catch (Exception e) {
                throw new ServletException("Error finding group members", e);
            }
        }
    } else if (id.isPlatform() || id.isServer() || id.isService()) {
        AppdefResourceValue val;
        try {
            val = Bootstrap.getBean(AppdefBoss.class).findById(sessionId, id);
            resources.add(val);
        } catch (Exception e) {
            throw new ServletException("Error finding id=" + id);
        }

    } else {
        // XXX: Applications?
        throw new ServletException("Unhandled entity=" + id);
    }

    // Load template
    MeasurementTemplate templ;
    try {
        Measurement m = Bootstrap.getBean(MeasurementBoss.class).getMeasurement(sessionId, mid);
        templ = m.getTemplate();
    } catch (Exception e) {
        throw new ServletException("Error looking up measurement.", e);
    }

    List<RowData> rows = new ArrayList<RowData>();
    for (int i = 0; i < resources.size(); i++) {
        AppdefResourceValue rValue = (AppdefResourceValue) resources.get(i);
        try {
            List<HighLowMetricValue> list = null;
            try {
                Measurement m = Bootstrap.getBean(MeasurementBoss.class).findMeasurement(sessionId,
                        templ.getId(), rValue.getEntityId());
                list = Bootstrap.getBean(MeasurementBoss.class).findMeasurementData(sessionId, m,
                        begin.longValue(), end.longValue(), PageControl.PAGE_ALL);
            } catch (MeasurementNotFoundException mnfe) {
                _log.debug(mnfe.getMessage());
                // HHQ-3611: Measurement not found, so set data to an empty list
                list = new ArrayList<HighLowMetricValue>(0);
            }
            List<RowData> hold = new ArrayList<RowData>();
            for (int j = 0; j < list.size(); j++) {
                HighLowMetricValue metric = list.get(j);

                RowData row = new RowData(new Date(metric.getTimestamp()));
                if (rows.indexOf(row) > -1) {
                    row = (RowData) rows.remove(rows.indexOf(row));
                    row.addData(metric.getValue());
                } else {
                    for (int f = 0; f < i; f++) {
                        row.addData(Double.NaN);
                    }
                    row.addData(metric.getValue());
                }
                // Move to hold list
                hold.add(row);
            }

            // Go through the left-overs
            for (int j = 0; j < rows.size(); j++) {
                RowData row = (RowData) rows.get(j);
                row.addData(Double.NaN);
                hold.add(row);
            }
            rows = hold;
        } catch (Exception e) {
            throw new ServletException("Error loading measurement data", e);
        }
    }

    StringBuffer buf = new StringBuffer();

    // Print header
    for (Iterator i = resources.iterator(); i.hasNext();) {
        AppdefResourceValue val = (AppdefResourceValue) i.next();
        buf.append(CSV_DELIM).append(val.getName());
    }

    // Print data, sorted from oldest to newest.
    Collections.sort(rows);

    buf.append("\n");
    for (int i = 0; i < rows.size(); i++) {
        RowData row = rows.get(i);
        buf.append(_df.format(row.getDate()));
        List<Double> data = row.getData();
        for (int j = 0; j < data.size(); j++) {
            Double metricdata = data.get(j);
            buf.append(CSV_DELIM);
            // Comparing to Double.NaN doesn't work
            if (!Double.isNaN(metricdata))
                buf.append(metricdata);
        }
        buf.append("\n");
    }

    try {
        response.setContentType("text/csv");
        response.addHeader("Content-disposition", "attachment; filename=" + templ.getAlias() + ".csv");
        response.getOutputStream().write(buf.toString().getBytes());
    } catch (IOException e) {
        throw new ServletException("Error writing data to the client: ", e);
    }
}

From source file:org.phenotips.export.internal.DataToCellConverter.java

public DataSection patientInfoHeader(Set<String> enabledFields) throws Exception {
    String sectionName = "patientInfo";

    // Must be linked to keep order; in other sections as well
    List<String> fields = new ArrayList<>(
            Arrays.asList("first_name", "last_name", "date_of_birth", "gender", "indication_for_referral"));
    fields.retainAll(enabledFields);
    Set<String> fieldSet = new HashSet<>(fields);
    this.enabledHeaderIdsBySection.put(sectionName, fieldSet);

    DataSection headerSection = new DataSection();
    if (fields.isEmpty()) {
        return null;
    }/*from ww  w.j av  a2  s. com*/

    int hX = 0;
    for (String fieldId : fields) {
        DataCell headerCell = new DataCell(
                this.translationManager.translate("PhenoTips.PatientClass_" + fieldId), hX, 1,
                StyleOption.HEADER);
        headerSection.addCell(headerCell);
        hX++;
    }

    DataCell headerCell = new DataCell(
            this.translationManager.translate("phenotips.export.excel.label.patientInformation"), 0, 0,
            StyleOption.LARGE_HEADER);
    headerCell.addStyle(StyleOption.HEADER);
    headerSection.addCell(headerCell);

    return headerSection;
}

From source file:com.enonic.cms.web.portal.services.UserServicesProcessor.java

protected void handlerLeaveGroup(HttpServletRequest request, HttpServletResponse response,
        ExtendedMap formItems) throws VerticalUserServicesException, RemoteException {
    UserEntity user = securityService.getLoggedInPortalUserAsEntity();
    if (user == null) {
        String message = "User must be logged in.";
        VerticalUserServicesLogger.warn(message);
        redirectToErrorPage(request, response, formItems, ERR_USER_NOT_LOGGED_IN);
        return;//from   ww  w  . j av  a  2  s  .c om
    }

    String[] requiredParameters = new String[] { "key" };

    List<String> missingParameters = findMissingRequiredParameters(requiredParameters, formItems, true);

    if (!missingParameters.isEmpty()) {
        String message = createMissingParametersMessage("Leave group", missingParameters);

        VerticalUserServicesLogger.warn(message);
        redirectToErrorPage(request, response, formItems, ERR_PARAMETERS_MISSING);
        return;
    }

    List<GroupKey> submittedGroupKeysToRemove = getSubmittedGroupKeys(formItems, "key");
    List<GroupKey> existingKeysForUser = getExistingDirectMembershipsForUser(user);
    submittedGroupKeysToRemove.retainAll(existingKeysForUser);

    if (submittedGroupKeysToRemove.size() >= 1) {

        GroupSpecification userGroupForLoggedInUser = new GroupSpecification();
        userGroupForLoggedInUser.setKey(user.getUserGroupKey());

        RemoveMembershipsCommand removeMembershipsCommand = new RemoveMembershipsCommand(
                userGroupForLoggedInUser, user.getKey());
        removeMembershipsCommand.setUpdateOpenGroupsOnly(true);
        removeMembershipsCommand.setRespondWithException(true);
        for (GroupKey groupKeyToRemove : submittedGroupKeysToRemove) {
            removeMembershipsCommand.addGroupToRemoveFrom(groupKeyToRemove);
        }

        try {
            userStoreService.removeMembershipsFromGroup(removeMembershipsCommand);
            updateUserInSession(ServletRequestAccessor.getSession());
        } catch (UserStoreAccessException e) {
            String message = "Not allowed to remove user from group: %t";
            VerticalUserServicesLogger.warn(message, e);
            redirectToErrorPage(request, response, formItems, ERR_JOIN_GROUP_NOT_ALLOWED);
            return;
        } catch (RuntimeException e) {
            VerticalUserServicesLogger.warn(e.getMessage(), e);
            redirectToErrorPage(request, response, formItems, ERR_JOIN_GROUP_FAILED);
            return;
        }
    }

    redirectToPage(request, response, formItems);
}

From source file:org.phenotips.export.internal.DataToCellConverter.java

public DataSection familyHistoryHeader(Set<String> enabledFields) throws Exception {
    String sectionName = "familyHistory";
    List<String> fields = new ArrayList<>(Arrays.asList("global_mode_of_inheritance", "miscarriages",
            "consanguinity", "family_history", "maternal_ethnicity", "paternal_ethnicity"));
    fields.retainAll(enabledFields);
    Set<String> fieldSet = new HashSet<>(fields);
    this.enabledHeaderIdsBySection.put(sectionName, fieldSet);
    if (fields.isEmpty()) {
        return null;
    }//from w w w.  java2 s  .  c o  m

    DataSection headerSection = new DataSection();

    int bottomY = 1;
    int ethnicityOffset = 0;
    if (fields.contains("maternal_ethnicity") || fields.contains("paternal_ethnicity")) {
        bottomY = 2;
        if (fields.contains("maternal_ethnicity") && fields.contains("paternal_ethnicity")) {
            ethnicityOffset = 2;
        } else {
            ethnicityOffset = 1;
        }
    }
    int x = 0;
    for (String fieldId : fields) {
        DataCell headerCell = new DataCell(
                this.translationManager.translate("phenotips.export.excel.label.familyHistory." + fieldId), x,
                bottomY, StyleOption.HEADER);
        headerSection.addCell(headerCell);
        x++;
    }
    if (ethnicityOffset > 0) {
        DataCell headerCell = new DataCell(
                this.translationManager.translate("phenotips.export.excel.label.familyHistory.ethnicity"),
                x - ethnicityOffset, 1, StyleOption.HEADER);
        headerSection.addCell(headerCell);
    }

    DataCell headerCell = new DataCell(
            this.translationManager.translate("phenotips.export.excel.label.familyHistory"), 0, 0,
            StyleOption.LARGE_HEADER);
    headerCell.addStyle(StyleOption.HEADER);
    headerSection.addCell(headerCell);

    return headerSection;
}

From source file:nl.strohalm.cyclos.services.transfertypes.TransferTypeServiceImpl.java

@Override
public List<TransferType> search(final TransferTypeQuery query) {
    // If searching for an operator group permissions, the transfer types are the same as his member's. So we have to actually check by his
    // member's permissions
    final Group group = fetchService.fetch(query.getGroup(),
            RelationshipHelper.nested(OperatorGroup.Relationships.MEMBER, Element.Relationships.GROUP));
    if (group instanceof OperatorGroup) {
        final OperatorGroup operatorGroup = (OperatorGroup) group;
        query.setGroup(operatorGroup.getMember().getGroup());
    }/*ww  w.  ja  v a  2s. c  o m*/

    final TransferTypeQuery finalQuery = (TransferTypeQuery) query.clone();
    finalQuery.setUsePriority(false);
    if (query.isUsePriority()) {
        query.setPriority(true);
        query.setPageForCount();
        final int totalCount = PageHelper.getTotalCount(transferTypeDao.search(query));
        finalQuery.setPriority(totalCount > 0);
    }

    // When fromOwner is a member, ensure disabled accounts (when credit limit is zero) are not used
    if (query.getFromOwner() instanceof Member) {
        final Member member = fetchService.fetch((Member) query.getFromOwner(), RelationshipHelper
                .nested(Element.Relationships.GROUP, MemberGroup.Relationships.ACCOUNT_SETTINGS));
        final List<AccountType> accountTypes = new ArrayList<AccountType>();
        final List<? extends Account> accounts = accountService.getAccounts(member);
        for (final Account account : accounts) {
            boolean hidden = false;
            try {
                final MemberGroupAccountSettings accountSettings = groupService
                        .loadAccountSettings(member.getGroup().getId(), account.getType().getId());
                if (accountSettings.isHideWhenNoCreditLimit()
                        && Math.abs(account.getCreditLimit().floatValue()) < PRECISION_DELTA) {
                    hidden = true;
                }
            } catch (final EntityNotFoundException e) {
                continue;
            }
            if (!hidden) {
                accountTypes.add(account.getType());
            }
        }
        if (CollectionUtils.isNotEmpty(finalQuery.getFromAccountTypes())) {
            // When there were already from account types set, retain them only
            accountTypes.retainAll(finalQuery.getFromAccountTypes());
        }
        // Finally, ensure that only transfer types from visible accounts are used
        finalQuery.setFromAccountTypes(accountTypes);
    }
    return transferTypeDao.search(finalQuery);
}

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

@SuppressWarnings("unchecked")
@Override/*from w w w.j  a v  a  2s. 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:edu.stanford.muse.util.Util.java

public static <E> List<E> listIntersection(Collection<E> list1, Collection<E> list2) {
    if (list1 == null && list2 == null)
        return null;
    if (list1 == null)
        return new ArrayList<>(list2);
    if (list2 == null)
        return new ArrayList<>(list1);
    List<E> cloneList = new ArrayList<E>(list1);
    cloneList.retainAll(list2);
    return cloneList;
}