Example usage for org.apache.commons.collections4 CollectionUtils isEmpty

List of usage examples for org.apache.commons.collections4 CollectionUtils isEmpty

Introduction

In this page you can find the example usage for org.apache.commons.collections4 CollectionUtils isEmpty.

Prototype

public static boolean isEmpty(final Collection<?> coll) 

Source Link

Document

Null-safe check if the specified collection is empty.

Usage

From source file:com.adguard.android.service.FilterServiceImpl.java

private List<FilterList> checkFilterUpdates(List<FilterList> filters, boolean force) {
    LOG.info("Start checking filters updates for {} outdated filters. Forced={}", filters.size(), force);

    if (CollectionUtils.isEmpty(filters)) {
        LOG.info("Empty filters list, doing nothing");
        return new ArrayList<>();
    }/*from w w  w  .ja va 2s.  co  m*/

    preferencesService.setLastUpdateCheck(new Date().getTime());

    try {
        final List<FilterList> updated = ServiceApiClient.downloadFilterVersions(context, filters);
        if (updated == null) {
            LOG.warn("Cannot download filter updates.");
            return null;
        }

        Map<Integer, FilterList> map = new HashMap<>();
        for (FilterList filter : updated) {
            map.put(filter.getFilterId(), filter);
        }

        for (FilterList current : filters) {
            final int filterId = current.getFilterId();
            if (!map.containsKey(filterId)) {
                current.setLastTimeDownloaded(new Date());
                updateFilter(current);
                continue;
            }

            FilterList update = map.get(filterId);
            if (update.getVersion().compareTo(current.getVersion()) > 0) {
                current.setVersion(update.getVersion().toString());
                current.setLastTimeDownloaded(new Date());
                current.setTimeUpdated(update.getTimeUpdated());
                map.put(filterId, current);

                LOG.info("Updating filter:" + current.getFilterId());
                updateFilter(current);
                LOG.info("Updating rules for filter:" + current.getFilterId());
                updateFilterRules(filterId);
            } else {
                map.remove(filterId);
                current.setLastTimeDownloaded(new Date());
                updateFilter(current);
            }
        }

        LOG.info("Finished checking filters updates.");

        return new ArrayList<>(map.values());
    } catch (IOException e) {
        LOG.error("Error checking filter updates:\r\n", e);
    } catch (Exception e) {
        LOG.error("Error parsing server response:\r\n", e);
    }

    return null;
}

From source file:io.ucoin.ucoinj.elasticsearch.service.CurrencyIndexerService.java

/**
 * Retrieve a currency from its name//from  w w w .  j  a  v  a 2 s.  co  m
 * @param currencyId
 * @return
 */
public Currency getCurrencyById(String currencyId) {

    if (!existsIndex(currencyId)) {
        return null;
    }

    // Prepare request
    SearchRequestBuilder searchRequest = getClient().prepareSearch(INDEX_NAME).setTypes(INDEX_TYPE_SIMPLE)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH);

    // If more than a word, search on terms match
    searchRequest.setQuery(QueryBuilders.matchQuery("_id", currencyId));

    // Execute query
    List<Currency> currencies = null;
    try {
        SearchResponse searchResponse = searchRequest.execute().actionGet();
        currencies = toCurrencies(searchResponse, false);
    } catch (SearchPhaseExecutionException e) {
        // Failed or no item on index
    }

    // No result : return null
    if (CollectionUtils.isEmpty(currencies)) {
        return null;
    }

    // Return the unique result
    return CollectionUtils.extractSingleton(currencies);
}

From source file:monasca.api.infrastructure.persistence.hibernate.AlarmDefinitionSqlRepoImpl.java

@Override
@SuppressWarnings("unchecked")
public AlarmDefinition findById(String tenantId, String alarmDefId) {
    logger.trace(ORM_LOG_MARKER, "findById(...) entering...");

    Session session = null;/*from w ww .ja  va  2s  .co m*/
    List<String> okActionIds = null;
    List<String> alarmActionIds = null;
    List<String> undeterminedActionIds = null;

    try {
        session = sessionFactory.openSession();

        final AlarmDefinitionDb alarmDefinitionDb = (AlarmDefinitionDb) session
                .getNamedQuery(AlarmDefinitionDb.Queries.FIND_BY_TENANT_AND_ID_NOT_DELETED)
                .setString("tenant_id", tenantId).setString("id", alarmDefId).uniqueResult();

        if (alarmDefinitionDb == null) {
            throw new EntityNotFoundException("No alarm definition exists for tenantId=%s and id=%s", tenantId,
                    alarmDefId);
        }

        final List<AlarmActionDb> alarmActionList = session
                .getNamedQuery(AlarmActionDb.Queries.FIND_BY_TENANT_ID_AND_ALARMDEFINITION_ID_DISTINCT)
                .setString("tenantId", tenantId).setString("alarmDefId", alarmDefId).list();

        if (!CollectionUtils.isEmpty(alarmActionList)) {

            logger.debug(ORM_LOG_MARKER, "Located {} AlarmActions for AlarmDefinition {}",
                    alarmActionList.size(), alarmDefinitionDb);

            okActionIds = Lists.newArrayList();
            alarmActionIds = Lists.newArrayList();
            undeterminedActionIds = Lists.newArrayList();

            for (final AlarmActionDb alarmAction : alarmActionList) {
                if (alarmAction.isInAlarmState(AlarmState.UNDETERMINED)) {
                    undeterminedActionIds.add(alarmAction.getAlarmActionId().getActionId());
                } else if (alarmAction.isInAlarmState(AlarmState.OK)) {
                    okActionIds.add(alarmAction.getAlarmActionId().getActionId());
                } else if (alarmAction.isInAlarmState(AlarmState.ALARM)) {
                    alarmActionIds.add(alarmAction.getAlarmActionId().getActionId());
                }
            }

        }

        return new AlarmDefinition(alarmDefinitionDb.getId(), alarmDefinitionDb.getName(),
                alarmDefinitionDb.getDescription(), alarmDefinitionDb.getSeverity().name(),
                alarmDefinitionDb.getExpression(), this.splitStringIntoList(alarmDefinitionDb.getMatchBy()),
                alarmDefinitionDb.isActionsEnabled(),
                alarmActionIds == null ? Collections.<String>emptyList() : alarmActionIds,
                okActionIds == null ? Collections.<String>emptyList() : okActionIds,
                undeterminedActionIds == null ? Collections.<String>emptyList() : undeterminedActionIds);

    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:co.rsk.net.discovery.PeerExplorerTest.java

@Test
public void handleFindNodeMessageWithExtraNodes() throws Exception {
    List<String> nodes = new ArrayList<>();
    nodes.add(HOST_1 + ":" + PORT_1);
    nodes.add(HOST_3 + ":" + PORT_3);

    ECKey key1 = ECKey.fromPrivate(Hex.decode(KEY_1)).decompress();
    ECKey key2 = ECKey.fromPrivate(Hex.decode(KEY_2)).decompress();
    ECKey key3 = ECKey.fromPrivate(Hex.decode(KEY_3)).decompress();

    Node node = new Node(key2.getNodeId(), HOST_2, PORT_2);
    NodeDistanceTable distanceTable = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE,
            node);//from  w w  w  .jav  a2  s .  co  m
    PeerExplorer peerExplorer = new PeerExplorer(nodes, node, distanceTable, key2, TIMEOUT, REFRESH);

    Channel internalChannel = Mockito.mock(Channel.class);
    UDPTestChannel channel = new UDPTestChannel(internalChannel, peerExplorer);
    ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    peerExplorer.setUDPChannel(channel);
    Assert.assertTrue(CollectionUtils.isEmpty(peerExplorer.getNodes()));

    //we send the ping first
    peerExplorer.startConversationWithNewNodes();
    List<DiscoveryEvent> sentEvents = channel.getEventsWritten();
    Assert.assertEquals(2, sentEvents.size());
    PongPeerMessage incomingPongMessage1 = PongPeerMessage.create(HOST_1, PORT_1,
            ((PingPeerMessage) sentEvents.get(0).getMessage()).getMessageId(), key1);
    DiscoveryEvent incomingPongEvent1 = new DiscoveryEvent(incomingPongMessage1,
            new InetSocketAddress(HOST_1, PORT_1));
    PongPeerMessage incomingPongMessage2 = PongPeerMessage.create(HOST_3, PORT_3,
            ((PingPeerMessage) sentEvents.get(1).getMessage()).getMessageId(), key3);
    DiscoveryEvent incomingPongEvent2 = new DiscoveryEvent(incomingPongMessage2,
            new InetSocketAddress(HOST_3, PORT_3));

    channel.clearEvents();
    channel.channelRead0(ctx, incomingPongEvent1);
    channel.channelRead0(ctx, incomingPongEvent2);

    List<Node> foundNodes = peerExplorer.getNodes();
    Assert.assertEquals(2, foundNodes.size());
    Assert.assertEquals(NODE_ID_3, Hex.toHexString(foundNodes.get(0).getId()));
    Assert.assertEquals(NODE_ID_1, Hex.toHexString(foundNodes.get(1).getId()));

    String check = UUID.randomUUID().toString();
    FindNodePeerMessage findNodePeerMessage = FindNodePeerMessage.create(key1.getNodeId(), check, key1);
    channel.clearEvents();
    channel.channelRead0(ctx, new DiscoveryEvent(findNodePeerMessage, new InetSocketAddress(HOST_1, PORT_1)));
    sentEvents = channel.getEventsWritten();
    Assert.assertEquals(1, sentEvents.size());
    NeighborsPeerMessage neighborsPeerMessage = (NeighborsPeerMessage) sentEvents.get(0).getMessage();
    Assert.assertEquals(2, neighborsPeerMessage.getNodes().size());
    Assert.assertTrue(cotainsNode(NODE_ID_1, neighborsPeerMessage.getNodes()));
    Assert.assertTrue(cotainsNode(NODE_ID_3, neighborsPeerMessage.getNodes()));
}

From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.warn("Call received to delete all instances");
    Map<String, AutomationDynamicNode> nodes = AutomationContext.getContext().getNodes();
    if (nodes != null && !CollectionUtils.isEmpty(nodes.keySet())) {
        Iterator<String> iterator = nodes.keySet().iterator();
        while (iterator.hasNext()) {
            String instanceId = iterator.next();
            log.warn("Terminating instance: " + instanceId);
            ec2.terminateInstance(instanceId);
            iterator.remove();//from   w  w  w. ja  v a  2 s.  co  m
        }
    } else {
        log.warn("No nodes to terminate.");
    }
}

From source file:de.micromata.tpsb.doc.parser.japa.TestCaseVisitor.java

private String extractArgs(ParserContext ctx, List<Expression> list) {
    if (CollectionUtils.isEmpty(list)) {
        return StringUtils.EMPTY;
    }/*www  .ja v a  2s . c om*/
    Expression expr = list.get(0);
    if (!(expr instanceof ClassExpr)) {
        if (list.size() > 1 && list.get(list.size() - 1) instanceof ClassExpr) {
            expr = list.get(list.size() - 1);
        } else {
            return StringUtils.EMPTY;
        }
    }
    ClassExpr clazzExpr = (ClassExpr) expr;
    Type type = clazzExpr.getType();
    String fullQualifiedClassName = ctx.getFullQualifiedNameFromImports(type.toString());
    if (StringUtils.isNotEmpty(fullQualifiedClassName)) {
        return type.toString();
    }
    return ctx.getCurrentClassName();

}

From source file:ddf.camel.component.catalog.framework.FrameworkProducer.java

/**
 * Makes sure that a Metacard or Metacard ID list contains objects of a particular type
 *
 * @param list {@link java.util.List} of Metacard IDs
 * @param cls {@link java.lang.Class} type that the objects inside the list should be
 * @return true if the list is not empty and has valid types inside, else false.
 *//*w ww.  j av a2s . c o m*/
private boolean validateList(List<?> list, Class<?> cls) {
    if (CollectionUtils.isEmpty(list)) {
        LOGGER.debug("No Metacard or Metacard IDs to process");
        return false;
    }

    for (final Object o : list) {
        if (!cls.isInstance(o)) {
            LOGGER.debug("Received a list of non-{} objects", cls.getName());
            return false;
        }
    }

    return true;
}

From source file:com.astamuse.asta4d.web.form.flow.base.BasicFormFlowHandlerTrait.java

/**
 * Assign array value to cascade forms of array type from context by recursively self call.
 * /* w  w  w.  jav a2 s. c  o  m*/
 * @param formCls
 * @param form
 * @param currentContext
 * @param indexes
 * @return
 * @throws Exception
 */
default T assignArrayValueFromContext(Class formCls, T form, Context currentContext, int[] indexes)
        throws Exception {
    List<AnnotatedPropertyInfo> list = AnnotatedPropertyUtil.retrieveProperties(formCls);
    for (final AnnotatedPropertyInfo field : list) {
        CascadeFormField cff = field.getAnnotation(CascadeFormField.class);
        if (cff != null) {
            if (field.getType().isArray()) {// a cascade form for array
                if (field.retrieveValue(form) != null) {
                    continue;
                }
                if (StringUtils.isEmpty(cff.arrayLengthField())) {
                    continue;
                }

                List<AnnotatedPropertyInfo> arrayLengthFieldList = AnnotatedPropertyUtil
                        .retrievePropertyByName(formCls, cff.arrayLengthField());
                if (CollectionUtils.isEmpty(arrayLengthFieldList)) {
                    throw new NullPointerException(
                            "specified array length field [" + cff.arrayLengthField() + "] was not found");
                }
                // we only need one
                AnnotatedPropertyInfo arrayLengthField = arrayLengthFieldList.get(0);

                Integer len = (Integer) arrayLengthField.retrieveValue(form);
                if (len == null) {
                    // throw new NullPointerException("specified array length field [" + cff.arrayLengthField() + "] is null");
                    len = 0;
                }

                final Object[] array = (Object[]) Array.newInstance(field.getType().getComponentType(), len);
                for (int i = 0; i < len; i++) {
                    final int seq = i;
                    final int[] newIndex = ArrayUtils.add(indexes, seq);
                    Context.with(new DelatedContext(currentContext) {
                        protected String convertKey(String scope, String key) {
                            if (scope.equals(WebApplicationContext.SCOPE_QUERYPARAM)) {
                                return rewriteArrayIndexPlaceHolder(key, newIndex);
                            } else {
                                return key;
                            }
                        }
                    }, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Object subform = field.getType().getComponentType().newInstance();
                                InjectUtil.injectToInstance(subform);
                                Array.set(array, seq, subform);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });// end runnable and context.with

                    assignArrayValueFromContext(field.getType().getComponentType(), (T) array[seq],
                            currentContext, newIndex);
                } // end for loop

                field.assignValue(form, array);
            } else {
                // a cascade form for not array
                assignArrayValueFromContext(field.getType(), (T) field.retrieveValue(form), currentContext,
                        indexes);
            }
        }
    }
    return form;
}

From source file:com.epam.catgenome.manager.protein.ProteinSequenceManager.java

private List<List<ImmutablePair<Gene, List<Sequence>>>> combineData(final Map<Gene, List<List<Sequence>>> data,
        final Comparator<Gene> comparator) {
    List<List<ImmutablePair<Gene, List<Sequence>>>> source = data.entrySet().stream()
            .sorted((e1, e2) -> comparator.compare(e1.getKey(), e2.getKey())).map(e -> e.getValue().stream()
                    .map(s -> new ImmutablePair<>(e.getKey(), s)).collect(Collectors.toList()))
            .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(source)) {
        return Collections.emptyList();
    }/*from ww w  .jav  a 2 s  .c  o m*/
    List<List<ImmutablePair<Gene, List<Sequence>>>> start = new ArrayList<>();
    for (ImmutablePair<Gene, List<Sequence>> p : source.remove(0)) {
        List<ImmutablePair<Gene, List<Sequence>>> ll = new ArrayList<>();
        ll.add(p);
        start.add(ll);
    }
    return recursiveCombine(start, source);
}

From source file:com.epam.catgenome.manager.protein.ProteinSequenceReconstructionManager.java

private void readMrna(final List<Gene> genes, final Map<Gene, List<Gene>> map) {
    if (CollectionUtils.isEmpty(genes) || map == null) {
        return;//w w  w.  jav  a 2 s  .  co m
    }
    List<Gene> distinctGenes = genes.stream().distinct().collect(Collectors.toList());
    for (Gene gene : distinctGenes) {
        if (TRANSCRIPTS_NAMES.contains(gene.getFeature().toLowerCase()) && gene.getItems() != null) {
            List<Gene> cds = gene.getItems().stream()
                    .filter(item -> CDS_NAMES.contains(item.getFeature().toLowerCase())).distinct()
                    .collect(Collectors.toList());
            map.put(gene, cds);
        }
    }
}