Example usage for java.util List removeIf

List of usage examples for java.util List removeIf

Introduction

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

Prototype

default boolean removeIf(Predicate<? super E> filter) 

Source Link

Document

Removes all of the elements of this collection that satisfy the given predicate.

Usage

From source file:bwem.map.MapInitializerImpl.java

@Override
public List<WalkPosition> trimOuterMiniTileBorder(final List<WalkPosition> border) {
    border.removeIf(w -> (!getData().getMapData().isValid(w)
            || !getData().getMiniTile(w, CheckMode.NO_CHECK).isWalkable()
            || getData().getTile(w.toTilePosition(), CheckMode.NO_CHECK).getNeutral() != null));
    return border;
}

From source file:org.silverpeas.core.calendar.icalendar.ICal4JExporterTest.java

/**
 * Centralization of verification.<br>
 * <p>//  w  w w  .  ja va  2  s.com
 * The mechanism is the following:<br>
 * <p/>
 * the first parameter represent the list of calendar events to export and the second one is the
 * name of the file that contains the expected result.<br>
 * Each lines starting with '#' character is ignored.<br>
 * If the file content is equal to the result of export, the test is successfully verified.<br>
 * If not, the different lines between the file content and the export result are logged to the
 * console.<br>
 * Only event parts are verified from the contents.
 * </p>
 * @param descriptor
 * @param fileNameOfExpectedResult the name of the file that contains the expected export result.
 */
@SuppressWarnings({ "unchecked", "Duplicates" })
private void exportAndVerifyResult(final ExportDescriptor descriptor, List<CalendarEvent> calendarEvents,
        String fileNameOfExpectedResult) throws ExportException {
    try {

        ByteArrayOutputStream emptyExportResult = new ByteArrayOutputStream();
        iCalendarExporter.exports(
                ExportDescriptor.withOutputStream(emptyExportResult).withParameter(CALENDAR, calendar),
                Stream::<CalendarEvent>empty);

        List<String> empty = IOUtils.readLines(new StringReader(emptyExportResult.toString()));
        empty.remove(empty.size() - 1);

        iCalendarExporter.exports(descriptor, calendarEvents::stream);

        StringReader current = new StringReader(descriptor.getOutputStream().toString());
        StringReader expected = new StringReader(getFileContent(fileNameOfExpectedResult));

        final List<String> currentContentLines = IOUtils.readLines(current);
        currentContentLines.remove(currentContentLines.size() - 1);
        Iterator<String> it = currentContentLines.iterator();
        while (it.hasNext() && !empty.isEmpty()) {
            String currentLine = it.next();
            String expectedLine = empty.remove(0);
            assertThat(expectedLine, is(currentLine));
            it.remove();
        }

        // Line to ignore from expected result extracted from a file.
        final List<String> expectedContentLines = IOUtils.readLines(expected);
        expectedContentLines.removeIf(currentExpectedLine -> currentExpectedLine.startsWith("#"));

        String currentContent = StringUtil.join(currentContentLines, "\n");
        String expectedContent = StringUtil.join(expectedContentLines, "\n");

        // Removing DTSTAMP
        currentContent = currentContent.replaceAll("DTSTAMP.+\n",
                "DTSTAMP:VALUE IS NOT VERIFIED BUT IS MANDATORY\n");

        assertThat(currentContent, is(expectedContent));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.fao.geonet.api.users.UsersApi.java

@ApiOperation(value = "Get users", notes = "", nickname = "getUsers")
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)//from www . j a  v  a2 s  .c o  m
@PreAuthorize("isAuthenticated()")
@ResponseBody
public List<User> getUsers(@ApiIgnore HttpSession httpSession) throws Exception {
    UserSession session = ApiUtils.getUserSession(httpSession);
    Profile profile = session.getProfile();

    UserRepository userRepository = ApplicationContextHolder.get().getBean(UserRepository.class);

    if (profile == Profile.Administrator) {
        return userRepository.findAll(SortUtils.createSort(User_.name));
    } else if (profile != Profile.UserAdmin) {
        return userRepository.findAll(UserSpecs.hasUserId(session.getUserIdAsInt()));
    } else if (profile == Profile.UserAdmin) {
        int userId = session.getUserIdAsInt();
        final List<Integer> userGroupIds = getGroupIds(userId);

        List<User> allUsers = userRepository.findAll(SortUtils.createSort(User_.name));

        // Filter users which are not in current user admin groups
        allUsers.removeIf(u -> !userGroupIds.containsAll(getGroupIds(u.getId()))
                || u.getProfile().equals(Profile.Administrator));
        //              TODO-API: Check why there was this check on profiles ?
        //                    if (!profileSet.contains(profile))
        //                        alToRemove.add(elRec);

        return allUsers;
    }

    return null;
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private Path getContentFilePath(URI uri) throws StorageException {
    Path contentIdDir = getContentItemDir(uri);
    List<Path> contentFiles;
    if (Files.exists(contentIdDir)) {
        try {/*  w w  w  .ja  v  a 2s.  co m*/
            contentFiles = listPaths(contentIdDir);
        } catch (IOException e) {
            throw new StorageException(e);
        }

        contentFiles.removeIf(Files::isDirectory);

        if (contentFiles.size() != 1) {
            throw new StorageException(
                    "Content ID: " + uri.getSchemeSpecificPart() + " storage folder is corrupted.");
        }

        //there should only be one file
        return contentFiles.get(0);
    }
    return null;
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Loads a list of jar files and automatically resolves any dependency issues.
 *
 * @param files The jar files to load./*  w ww. j  a v a2  s.  c  om*/
 */
public static void loadExternalModules(List<File> files) {
    List<File> independents = new ArrayList<>();
    List<File> dependents = new ArrayList<>();

    files.forEach((file) -> {
        try {
            if (getModuleRequires(file).length > 0) {
                dependents.add(file);
            } else {
                independents.add(file);
            }
        } catch (IOException e) {
            Discord4J.LOGGER.error(LogMarkers.MODULES, "Discord4J Internal Exception");
        }
    });

    independents.forEach(ModuleLoader::loadExternalModules);

    List<File> noLongerDependents = dependents.stream().filter(jarFile -> { // loads all dependents whose requirements have been met already
        try {
            String[] moduleRequires = getModuleRequires(jarFile);
            List<Class> classes = new ArrayList<>();
            for (String clazz : moduleRequires) {
                classes.add(Class.forName(clazz));
            }
            return classes.size() == moduleRequires.length;
        } catch (Exception e) {
            return false;
        }
    }).collect(Collectors.toList());
    dependents.removeAll(noLongerDependents);
    noLongerDependents.forEach(ModuleLoader::loadExternalModules);

    final int retryAttempts = dependents.size();
    for (int i = 0; i < retryAttempts; i++) {
        dependents.removeIf((file -> { // Filters out all usable files
            boolean loaded = false;
            try {
                String[] required = getModuleRequires(file);
                for (String clazz : required) {
                    try {
                        Class.forName(clazz);
                        loaded = true;
                    } catch (ClassNotFoundException ignored) {
                    }

                    if (!loaded)
                        loaded = findFileForClass(files, clazz) != null;

                    if (!loaded)
                        break;
                }
            } catch (IOException ignored) {
            }

            if (loaded)
                loadExternalModules(file);

            return loaded;
        }));

        if (dependents.isEmpty())
            break;
    }

    if (dependents.size() > 0)
        Discord4J.LOGGER.warn(LogMarkers.MODULES, "Unable to load {} modules!", dependents.size());
}

From source file:org.apache.metron.elasticsearch.dao.ElasticsearchMetaAlertDao.java

protected boolean removeAlertsFromMetaAlert(Document metaAlert, Collection<String> alertGuids) {
    List<Map<String, Object>> currentAlerts = (List<Map<String, Object>>) metaAlert.getDocument()
            .get(ALERT_FIELD);//from w w  w  .j a  v a 2  s  . c  o  m
    int previousSize = currentAlerts.size();
    // Only remove an alert if it is in the meta alert
    currentAlerts.removeIf(currentAlert -> alertGuids.contains((String) currentAlert.get(GUID)));
    return currentAlerts.size() != previousSize;
}

From source file:org.silverpeas.core.webapi.calendar.CalendarWebManager.java

/**
 * Gets all event occurrences associated to users and contained a the time window specified
 * by the start and end date times.<br>
 * Attendees which have answered negatively about their presence are not taken into account.
 * The occurrences are sorted from the lowest to the highest date and mapped by user identifiers.
 * @param currentUserAndComponentInstanceId the current user and the current component instance
 * ids from which the service is requested.
 * @param startDate the start date of time window.
 * @param endDate the end date of time window.
 * @param users the users to filter on./* w  w w .  jav a2 s  .c  o  m*/
 * @return a list of entities of calendar event occurrences mapped by user identifiers.
 */
protected Map<String, List<CalendarEventOccurrence>> getAllEventOccurrencesByUserIds(
        final Pair<List<String>, User> currentUserAndComponentInstanceId, LocalDate startDate,
        LocalDate endDate, Collection<User> users) {
    // Retrieving the occurrences from personal calendars
    final List<Calendar> personalCalendars = new ArrayList<>();
    users.forEach(u -> personalCalendars.addAll(getCalendarsHandledBy(
            PersonalComponentInstance.from(u, PersonalComponent.getByName("userCalendar").get()).getId())));
    final List<CalendarEventOccurrence> entities = personalCalendars.isEmpty() ? emptyList()
            : Calendar.getTimeWindowBetween(startDate, endDate).filter(f -> f.onCalendar(personalCalendars))
                    .getEventOccurrences();
    entities.addAll(Calendar.getTimeWindowBetween(startDate, endDate).filter(f -> f.onParticipants(users))
            .getEventOccurrences());
    // Getting the occurrences by users
    Map<String, List<CalendarEventOccurrence>> result = new CalendarEventInternalParticipationView(users)
            .apply(entities.stream().distinct().collect(Collectors.toList()));
    final String currentUserId = currentUserAndComponentInstanceId.getRight().getId();
    if (result.containsKey(currentUserId)) {
        List<CalendarEventOccurrence> currentUserOccurrences = result.get(currentUserId);
        // Remove occurrence associated to given user when he is the creator
        currentUserOccurrences.removeIf(calendarEventOccurrence -> {
            CalendarEvent event = calendarEventOccurrence.getCalendarEvent();
            return currentUserAndComponentInstanceId.getLeft()
                    .contains(event.getCalendar().getComponentInstanceId())
                    && event.getCreator().getId().equals(currentUserId);
        });
    } else {
        result.put(currentUserId, emptyList());
    }
    return result;
}

From source file:org.silverpeas.core.webapi.calendar.CalendarResource.java

/**
 * Gets the JSON representation of a list of calendar event occurrence of an aimed event.
 * If it doesn't exist, a 404 HTTP code is returned.
 * @param calendarId the identifier of calendar the event must belong with
 * @param eventId the identifier of event the returned occurrences must be linked with
 * @return the response to the HTTP GET request with the JSON representation of the asked
 * occurrences.//from www .ja  v  a2s.  c om
 * @see WebProcess#execute()
 */
@GET
@Path("{calendarId}/" + CalendarResourceURIs.CALENDAR_EVENT_URI_PART + "/{eventId}/"
        + CalendarResourceURIs.CALENDAR_EVENT_OCCURRENCE_URI_PART)
@Produces(MediaType.APPLICATION_JSON)
public List<CalendarEventOccurrenceEntity> getEventOccurrencesOf(@PathParam("calendarId") String calendarId,
        @PathParam("eventId") String eventId) {
    final Calendar calendar = Calendar.getById(calendarId);
    final CalendarEvent event = CalendarEvent.getById(eventId);
    assertDataConsistency(calendar.getComponentInstanceId(), calendar, event);
    CalendarEventOccurrenceRequestParameters params = RequestParameterDecoder.decode(getHttpRequest(),
            CalendarEventOccurrenceRequestParameters.class);
    final LocalDate occStartDate = params.getStartDateOfWindowTime().toLocalDate();
    final LocalDate occEndDate = params.getEndDateOfWindowTime().toLocalDate();
    return process(() -> {
        List<CalendarEventOccurrence> occurrences = getCalendarWebManager().getEventOccurrencesOf(occStartDate,
                occEndDate, singletonList(calendar));
        occurrences.removeIf(occurrence -> !occurrence.getCalendarEvent().getId().equals(eventId));
        return asOccurrenceWebEntities(occurrences);
    }).execute();
}

From source file:pl.datamatica.traccar.api.providers.DeviceProvider.java

public void updateDeviceShare(long id, List<Long> userIds) throws ProviderException {
    checkUserSharePermission();/*from   ww w  .  j  av  a  2  s.co  m*/

    Device d = get(Device.class, id, this::isVisible);
    if (requestUser.hasPermission(UserPermission.ALL_USERS)) {
        d.getUsers().clear();
    } else {
        d.getUsers().removeAll(requestUser.getAllManagedUsers());
        d.getUsers().remove(requestUser);
    }
    if (userIds.isEmpty()) {
        return;
    }

    Set<Long> ids = new HashSet<>(userIds);
    List<User> users;
    if (requestUser.hasPermission(UserPermission.ALL_USERS)) {
        TypedQuery<User> tq = em.createQuery("from User u where u.id in :ids", User.class);
        tq.setParameter("ids", userIds);
        users = tq.getResultList();
    } else {
        users = new ArrayList<>(requestUser.getManagedUsers());
        users.add(requestUser);
        users.removeIf(u -> !ids.contains(u.getId()));
    }
    d.getUsers().addAll(users);

    users.stream().filter(u -> !u.hadAnyDevice()).forEach(u -> u.setHadAnyDevice(true));
}

From source file:org.silverpeas.core.webapi.calendar.CalendarWebManager.java

/**
 * Gets the next event occurrences from now.
 * @param componentIds identifiers of aimed component instance.
 * @param calendarIdsToExclude identifier of calendars which linked occurrences must be excluded
 * from the result./*ww  w .j a  v a2  s . c  o m*/
 * @param usersToInclude identifiers of users which linked occurrences must be included into the
 * result
 * @param calendarIdsToInclude identifier of calendars which linked occurrences must be included
 * into the result.
 * @param zoneId the identifier of the zone.
 * @param limit the maximum occurrences the result must have (must be lower than 500)
 * @return a list of {@link CalendarEventOccurrence}.
 */
public Stream<CalendarEventOccurrence> getNextEventOccurrences(final List<String> componentIds,
        final Set<String> calendarIdsToExclude, final Set<User> usersToInclude,
        final Set<String> calendarIdsToInclude, final ZoneId zoneId, final Integer limit) {
    final User currentRequester = User.getCurrentRequester();
    // load calendars
    final List<Calendar> calendars = componentIds.stream().flatMap(i -> getCalendarsHandledBy(i).stream())
            .distinct().collect(Collectors.toList());
    // includes/excludes
    calendarIdsToInclude.removeAll(calendarIdsToExclude);
    calendars.removeIf(c -> calendarIdsToExclude.contains(c.getId()));
    if (!calendarIdsToInclude.isEmpty()) {
        calendars.forEach(c -> calendarIdsToInclude.remove(c.getId()));
        calendarIdsToInclude.forEach(i -> {
            Calendar calendarToInclude = Calendar.getById(i);
            if (calendarToInclude.canBeAccessedBy(currentRequester)) {
                calendars.add(calendarToInclude);
            }
        });
    }
    // loading occurrences
    final int nbOccLimit = (limit != null && limit > 0 && limit <= 500) ? limit : DEFAULT_NB_MAX_NEXT_OCC;
    final LocalDate startDate = zoneId != null ? LocalDateTime.now(zoneId).toLocalDate() : LocalDate.now();
    final Set<CalendarEventOccurrence> occurrences = new HashSet<>();
    for (int nbMonthsToAdd : getNextEventTimeWindows()) {
        occurrences.clear();
        LocalDate endDate = startDate.plusMonths(nbMonthsToAdd);
        occurrences.addAll(getEventOccurrencesOf(startDate, endDate, calendars));
        if (!usersToInclude.isEmpty()) {
            getAllEventOccurrencesByUserIds(Pair.of(componentIds, currentRequester), startDate, endDate,
                    usersToInclude).forEach((u, o) -> occurrences.addAll(o));
        }
        if (occurrences.size() >= nbOccLimit) {
            break;
        }
    }
    return occurrences.stream().sorted(COMPARATOR_BY_DATE_ASC).limit(nbOccLimit);
}