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:li.l1t.common.util.CommandHelper.java

/**
 * Removes irrelevant tab-complete suggestions from given list of suggestions. If given args are empty, or given
 * suggestions are null, or the final element of given args is empty, given suggestions are returned unmodified.
 *
 * @param args        the array of arguments already entered
 * @param suggestions the list of suggestions
 * @return {@code suggestions}, with all elements not starting with the last element of {@code args} removed.
 *//*from w  ww  . j ava2 s.  c om*/
public static List<String> tabCompleteArgs(String[] args, List<String> suggestions) {
    if (suggestions == null || args.length == 0) {
        return suggestions;
    }
    String finalArg = args[args.length - 1];
    suggestions.removeIf(s -> !s.startsWith(finalArg));
    return suggestions;
}

From source file:com.bombardier.plugin.utils.FilePathUtils.java

/**
 * Used to read test cases from a list - line by line.
 * //  w w w. ja v a2s.  co m
 * @param file
 *            the {@link Path} to the file
 * @return An {@link List} containing all test cases.
 * @throws IOException
 * @since 1.0
 */
public static List<String> readTextFileByLines(FilePath file) throws Exception {
    List<String> list = Files.readAllLines(Paths.get(file.absolutize().toURI()), StandardCharsets.UTF_8);
    list.removeIf(new Predicate<String>() {
        @Override
        public boolean test(String arg0) {
            return !StringUtils.isNotBlank(arg0);
        }
    });
    return list;
}

From source file:org.silverpeas.core.calendar.CalendarEventOccurrence.java

/**
 * Gets optionally an event occurrence by its identifier.
 * <p>If the occurrence exists into the persistence, it is returned. Otherwise it is generated.
 * <p>Otherwise and if start date is valid, the occurrence is generated.
 * @param id the identifier of the aimed occurrence.
 * @return an optional calendar event occurrence.
 *//*from ww  w.  j av a  2 s.c o  m*/
public static Optional<CalendarEventOccurrence> getById(final String id) {
    final CalendarEventOccurrenceRepository repository = CalendarEventOccurrenceRepository.get();
    final Mutable<CalendarEventOccurrence> occurrence = Mutable.ofNullable(repository.getById(id));
    if (!occurrence.isPresent()) {
        final Pair<String, Temporal> explodedId = explodeId(id);
        final String eventId = explodedId.getLeft();
        final Temporal startDate = explodedId.getRight();
        final Optional<CalendarEvent> event = Optional.ofNullable(CalendarEvent.getById(eventId));
        event.ifPresent(e -> {
            if (e.isRecurrent()) {
                final LocalDate occStartDate;
                final LocalDate occEndDate;
                if (startDate instanceof LocalDate) {
                    final LocalDate date = (LocalDate) startDate;
                    occStartDate = date.minusDays(1);
                    occEndDate = date.plusDays(1);
                } else {
                    final OffsetDateTime dateTime = (OffsetDateTime) startDate;
                    occStartDate = dateTime.minusDays(1).toLocalDate();
                    occEndDate = dateTime.plusDays(1).toLocalDate();
                }
                final List<CalendarEventOccurrence> occurrences = e.getCalendar()
                        .between(occStartDate, occEndDate).getEventOccurrences();
                occurrences.removeIf(o -> !o.getCalendarEvent().getId().equals(eventId)
                        || (!o.getStartDate().equals(startDate)));
                if (occurrences.size() == 1) {
                    occurrence.set(occurrences.get(0));
                }
            } else {
                occurrence.set(new CalendarEventOccurrence(e, e.getStartDate(), e.getEndDate()));
            }
        });
    }
    return Optional.ofNullable(occurrence.orElse(null));
}

From source file:io.dockstore.webservice.helpers.Helper.java

private static void removeContainersThatCannotBeUpdated(List<Tool> dbTools) {
    // TODO: for now, with no info coming back from Docker Hub, just skip them always
    dbTools.removeIf(container1 -> container1.getRegistry() == Registry.DOCKER_HUB);
    // also skip containers on quay.io but in manual mode
    dbTools.removeIf(container1 -> container1.getMode() == ToolMode.MANUAL_IMAGE_PATH);
}

From source file:io.dockstore.webservice.helpers.Helper.java

/**
 * Refreshes user's containers//from ww  w . j a va2 s. com
 *
 * @param userId
 * @param client
 * @param objectMapper
 * @param userDAO
 * @param toolDAO
 * @param tokenDAO
 * @param tagDAO
 * @param fileDAO
 * @return list of updated containers
 */
@SuppressWarnings("checkstyle:parameternumber")
public static List<Tool> refresh(final Long userId, final HttpClient client, final ObjectMapper objectMapper,
        final UserDAO userDAO, final ToolDAO toolDAO, final TokenDAO tokenDAO, final TagDAO tagDAO,
        final FileDAO fileDAO) {
    List<Tool> dbTools = new ArrayList(getContainers(userId, userDAO));// toolDAO.findByUserId(userId);

    // Get user's quay and git tokens
    List<Token> tokens = tokenDAO.findByUserId(userId);
    Token quayToken = extractToken(tokens, TokenType.QUAY_IO.toString());
    Token githubToken = extractToken(tokens, TokenType.GITHUB_COM.toString());
    Token bitbucketToken = extractToken(tokens, TokenType.BITBUCKET_ORG.toString());

    // with Docker Hub support it is now possible that there is no quayToken
    if (githubToken == null) {
        LOG.info("GIT token not found!");
        throw new CustomWebApplicationException("Git token not found.", HttpStatus.SC_CONFLICT);
    }
    if (bitbucketToken == null) {
        LOG.info("WARNING: BITBUCKET token not found!");
    }
    if (quayToken == null) {
        LOG.info("WARNING: QUAY token not found!");
    }
    ImageRegistryFactory factory = new ImageRegistryFactory(client, objectMapper, quayToken);
    final List<ImageRegistryInterface> allRegistries = factory.getAllRegistries();

    List<String> namespaces = new ArrayList<>();
    // TODO: figure out better approach, for now just smash together stuff from DockerHub and quay.io
    for (ImageRegistryInterface anInterface : allRegistries) {
        namespaces.addAll(anInterface.getNamespaces());
    }
    List<Tool> apiTools = new ArrayList<>();
    for (ImageRegistryInterface anInterface : allRegistries) {
        apiTools.addAll(anInterface.getContainers(namespaces));
    }
    // TODO: when we get proper docker hub support, get this above
    // hack: read relevant containers from database
    User currentUser = userDAO.findById(userId);
    List<Tool> findByMode = toolDAO.findByMode(ToolMode.MANUAL_IMAGE_PATH);
    findByMode.removeIf(test -> !test.getUsers().contains(currentUser));
    apiTools.addAll(findByMode);
    // ends up with docker image path -> quay.io data structure representing builds
    final Map<String, ArrayList<?>> mapOfBuilds = new HashMap<>();
    for (final ImageRegistryInterface anInterface : allRegistries) {
        mapOfBuilds.putAll(anInterface.getBuildMap(apiTools));
    }

    // end up with key = path; value = list of tags
    // final Map<String, List<Tag>> tagMap = getWorkflowVersions(client, allRepos, objectMapper, quayToken, bitbucketToken, githubToken,
    // mapOfBuilds);
    removeContainersThatCannotBeUpdated(dbTools);

    final User dockstoreUser = userDAO.findById(userId);
    // update information on a container by container level
    updateContainers(apiTools, dbTools, dockstoreUser, toolDAO);
    userDAO.clearCache();

    final List<Tool> newDBTools = getContainers(userId, userDAO);
    // update information on a tag by tag level
    final Map<String, List<Tag>> tagMap = getTags(client, newDBTools, objectMapper, quayToken, mapOfBuilds);

    updateTags(newDBTools, client, toolDAO, tagDAO, fileDAO, githubToken, bitbucketToken, tagMap);
    userDAO.clearCache();
    return getContainers(userId, userDAO);
}

From source file:com.ibm.watson.catalyst.jumpqa.splitter.Splitter.java

/**
 * Removes empty strings from a list of strings.
 * //from  w  ww .  j  av  a 2  s  .  c  o m
 * @param strings
 * @return
 */
protected List<String> removeEmpty(List<String> strings) {
    final List<String> result = new ArrayList<String>(strings);
    result.removeIf((s) -> s.equals(""));
    return result;
}

From source file:org.openlmis.converter.FileObjectTypeConverter.java

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    String by = getBy(mapping.getType());

    String parent = configuration.getDirectory();
    String inputFileName = new File(parent, mapping.getEntityName()).getAbsolutePath();
    List<Map<String, String>> csvs = reader.readFromFile(new File(inputFileName));

    csvs.removeIf(map -> !value.equals(map.get(by)));

    if (!csvs.isEmpty()) {
        Map<String, String> csv = csvs.get(0);

        String mappingFileName = inputFileName.replace(".csv", "_mapping.csv");
        List<Mapping> mappings = mappingConverter.getMappingForFile(new File(mappingFileName));

        String json = converter.convert(csv, mappings).toString();

        try (JsonReader jsonReader = Json.createReader(new StringReader(json))) {
            JsonObject jsonObject = jsonReader.readObject();
            builder.add(mapping.getTo(), jsonObject);
        }/*from  w  w w.j  av a 2  s  . com*/
    } else {
        logger.warn("The CSV file contained reference to {} {} from input file {}, " + "but it does not exist.",
                by, value, mapping.getEntityName());
    }
}

From source file:org.openlmis.converter.FileArrayTypeConverter.java

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    List<String> codes = getArrayValues(value);
    String by = getBy(mapping.getType());

    String parent = configuration.getDirectory();
    String inputFileName = new File(parent, mapping.getEntityName()).getAbsolutePath();
    List<Map<String, String>> csvs = reader.readFromFile(new File(inputFileName));
    csvs.removeIf(map -> !codes.contains(map.get(by)));

    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();

    if (!csvs.isEmpty()) {
        String mappingFileName = inputFileName.replace(".csv", "_mapping.csv");
        List<Mapping> mappings = mappingConverter.getMappingForFile(new File(mappingFileName));

        for (Map<String, String> csv : csvs) {
            String json = converter.convert(csv, mappings).toString();

            try (JsonReader jsonReader = Json.createReader(new StringReader(json))) {
                arrayBuilder.add(jsonReader.readObject());
            }//  w w w  .  ja  v  a 2 s. c o m
        }
    }

    builder.add(mapping.getTo(), arrayBuilder);
}

From source file:org.apache.geode.cache.lucene.LuceneSearchWithRollingUpgradeDUnit.java

@Parameterized.Parameters
public static Collection<String> data() {
    List<String> result = VersionManager.getInstance().getVersionsWithoutCurrent();
    // Lucene Compatibility checks start with Apache Geode v1.2.0
    // Removing the versions older than v1.2.0
    result.removeIf(s -> Integer.parseInt(s) < 120);
    if (result.size() < 1) {
        throw new RuntimeException("No older versions of Geode were found to test against");
    } else {//from w  ww  . j a  v  a  2 s .com
        System.out.println("running against these versions: " + result);
    }
    return result;
}

From source file:org.primeframework.mvc.control.form.LocaleSelect.java

/**
 * Adds the countries Map and then calls super.
 *//*from  w w  w  .j  a v  a2s  . c o m*/
@Override
protected Map<String, Object> makeParameters() {
    LinkedHashMap<String, String> locales = new LinkedHashMap<>();
    String preferred = (String) attributes.get("preferredLocales");
    if (preferred != null) {
        String[] parts = preferred.split(",");
        for (String part : parts) {
            Locale locale = LocaleUtils.toLocale(part);
            locales.put(locale.toString(), locale.getDisplayName(locale));
        }
    }

    boolean includeCountries = attributes.containsKey("includeCountries")
            ? (Boolean) attributes.get("includeCountries")
            : true;
    List<Locale> allLocales = new ArrayList<>();
    Collections.addAll(allLocales, Locale.getAvailableLocales());
    allLocales.removeIf((locale) -> locale.getLanguage().isEmpty() || locale.hasExtensions()
            || !locale.getScript().isEmpty() || !locale.getVariant().isEmpty()
            || (!includeCountries && !locale.getCountry().isEmpty()));
    allLocales.sort((one, two) -> one.getDisplayName(locale).compareTo(two.getDisplayName(locale)));

    for (Locale locale : allLocales) {
        if (!locales.containsKey(locale.getCountry())) {
            locales.put(locale.toString(), locale.getDisplayName(this.locale));
        }
    }

    attributes.put("items", locales);

    return super.makeParameters();
}