Example usage for com.google.common.collect Iterables tryFind

List of usage examples for com.google.common.collect Iterables tryFind

Introduction

In this page you can find the example usage for com.google.common.collect Iterables tryFind.

Prototype

public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:com.google.security.zynamics.binnavi.disassembly.ViewConfiguration.java

@Override
public boolean isTagged(final CTag tag) {
    return Iterables.tryFind(viewTags, new Predicate<CTag>() {
        @Override/*from  w  w  w.  j  av a  2 s  . co m*/
        public boolean apply(final CTag currentTag) {
            return currentTag.getId() == tag.getId();
        }
    }).isPresent();
}

From source file:com.thinkbiganalytics.nifi.rest.model.visitor.NifiVisitableProcessGroup.java

/**
 * Return the connection, if any, matching the incoming source connectionSourceId
 *
 * @param connectionSourceId the unique id for the connection source to find
 * @return a connection matching the incoming connectionSourceId, or Null if not found
 *//* w w  w .j  a  v a 2s.c  o m*/
public ConnectionDTO getConnectionMatchingSourceId(final String connectionSourceId) {
    if (connections != null) {
        return Iterables.tryFind(connections, new Predicate<ConnectionDTO>() {
            @Override
            public boolean apply(ConnectionDTO connection) {
                return connection.getSource() != null
                        && connection.getSource().getId().equals(connectionSourceId);
            }
        }).orNull();
    }
    return null;
}

From source file:org.obm.push.handler.FolderCreateHandler.java

private Optional<BackendId> findBackendId(final FolderCreateRequest folderCreateRequest,
        FolderSnapshot knownSnapshot) {/*from w ww  .java 2 s.  co m*/

    return Iterables.tryFind(knownSnapshot.getFolders(), new Predicate<Folder>() {
        @Override
        public boolean apply(Folder folder) {
            return folder.getCollectionId().equals(folderCreateRequest.getFolderParentId());
        }
    }).transform(new Function<Folder, BackendId>() {
        @Override
        public BackendId apply(Folder folder) {
            return folder.getBackendId();
        }
    });
}

From source file:org.ow2.petals.cloud.manager.core.utils.SSHUtils.java

/**
 * Get client from Node/*from   ww w . ja va 2s  .c  o  m*/
 *
 * @param node
 * @return
 */
public static SSHClient getClient(Node node) throws CloudManagerException {
    String hostname = Iterables.tryFind(node.getPublicIpAddress(), new Predicate<String>() {
        public boolean apply(String input) {
            return input != null;
        }
    }).or(Iterables.tryFind(node.getPrivateIpAddress(), new Predicate<String>() {
        public boolean apply(String input) {
            return input != null;
        }
    })).orNull();
    checkNotNull(hostname, "Can not access to a node using a null IP...");

    // assume that we are using SSH by default
    int port = node.getAccess().getPort();
    if (port <= 0) {
        port = Access.DEFAULT_SSH;
    }

    return SSHUtils.newClient(hostname, port, node.getAccess());
}

From source file:org.apache.brooklyn.entity.nosql.riak.RiakClusterImpl.java

protected void onServerPoolMemberChanged(final Entity member) {
    synchronized (mutex) {
        log.trace("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = getAttribute(RIAK_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            // TODO can we discover the nodes by asking the riak cluster, rather than assuming what we add will be in there?
            // TODO and can we do join as part of node starting?

            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }/*from   w  ww  .  j  ava2 s. co m*/
            String riakName = getRiakName(member);
            Preconditions.checkNotNull(riakName);

            // flag a first node to be the first node in the riak cluster.
            Boolean firstNode = getAttribute(IS_FIRST_NODE_SET);
            if (!Boolean.TRUE.equals(firstNode)) {
                sensors().set(IS_FIRST_NODE_SET, Boolean.TRUE);

                nodes.put(member, riakName);
                sensors().set(RIAK_CLUSTER_NODES, nodes);

                ((EntityInternal) member).sensors().set(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);

                log.info("Added initial Riak node {}: {}; {} to new cluster",
                        new Object[] { this, member, getRiakName(member) });
            } else {
                // TODO: be wary of erroneous nodes but are still flagged 'in cluster'
                // add the new node to be part of the riak cluster.
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(), Predicates.and(
                        Predicates.instanceOf(RiakNode.class),
                        EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true)));
                if (anyNodeInCluster.isPresent()) {
                    if (!nodes.containsKey(member)
                            && member.getAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER) == null) {
                        String anyNodeName = anyNodeInCluster.get().getAttribute(RiakNode.RIAK_NODE_NAME);
                        Entities.invokeEffectorWithArgs(this, member, RiakNode.JOIN_RIAK_CLUSTER, anyNodeName)
                                .blockUntilEnded();
                        nodes.put(member, riakName);
                        sensors().set(RIAK_CLUSTER_NODES, nodes);
                        log.info("Added Riak node {}: {}; {} to cluster",
                                new Object[] { this, member, getRiakName(member) });
                    }
                } else {
                    log.error("isFirstNodeSet, but no cluster members found to add {}", member.getId());
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                DependentConfiguration.attributeWhenReady(member, RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER,
                        Predicates.equalTo(false)).blockUntilEnded(Duration.TWO_MINUTES);
                @SuppressWarnings("unchecked")
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(Predicates.instanceOf(RiakNode.class),
                                EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), RiakNode.REMOVE_FROM_CLUSTER,
                            getRiakName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                sensors().set(RIAK_CLUSTER_NODES, nodes);
                log.info("Removed Riak node {}: {}; {} from cluster",
                        new Object[] { this, member, getRiakName(member) });
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, RIAK_CLUSTER_NODES);

        calculateClusterAddresses();
    }
}

From source file:org.jclouds.aliyun.ecs.compute.ECSComputeService.java

private String extractVSwitchId(Set<String> tags) {
    String vSwitchIdTag = Iterables.tryFind(tags, new Predicate<String>() {
        @Override/*from   w  w w .j  a  v a 2s.c o m*/
        public boolean apply(@Nullable String input) {
            return input.startsWith("vsw-");
        }
    }).orNull();
    return vSwitchIdTag;
}

From source file:org.killbill.billing.payment.core.janitor.IncompletePaymentTransactionTask.java

private void tryToProcessNotification(final JanitorNotificationKey notificationKey, final UUID userToken,
        final Long accountRecordId, final long tenantRecordId) throws LockFailedException {
    final InternalTenantContext internalTenantContext = internalCallContextFactory
            .createInternalTenantContext(tenantRecordId, accountRecordId);
    tryToDoJanitorOperationWithAccountLock(new JanitorIterationCallback() {
        @Override//from  w  ww.  j ava 2  s . c o m
        public Void doIteration() {
            // State may have changed since we originally retrieved with no lock
            final PaymentTransactionModelDao rehydratedPaymentTransaction = paymentDao
                    .getPaymentTransaction(notificationKey.getUuidKey(), internalTenantContext);

            final TenantContext tenantContext = internalCallContextFactory
                    .createTenantContext(internalTenantContext);
            final PaymentModelDao payment = paymentDao.getPayment(rehydratedPaymentTransaction.getPaymentId(),
                    internalTenantContext);

            final PaymentTransactionInfoPlugin undefinedPaymentTransaction = new DefaultNoOpPaymentInfoPlugin(
                    payment.getId(), rehydratedPaymentTransaction.getId(),
                    rehydratedPaymentTransaction.getTransactionType(), rehydratedPaymentTransaction.getAmount(),
                    rehydratedPaymentTransaction.getCurrency(), rehydratedPaymentTransaction.getCreatedDate(),
                    rehydratedPaymentTransaction.getCreatedDate(), PaymentPluginStatus.UNDEFINED, null, null);
            PaymentTransactionInfoPlugin paymentTransactionInfoPlugin;
            try {
                final PaymentPluginApi paymentPluginApi = paymentPluginServiceRegistration
                        .getPaymentPluginApi(payment.getPaymentMethodId(), false, internalTenantContext);
                final List<PaymentTransactionInfoPlugin> result = paymentPluginApi.getPaymentInfo(
                        payment.getAccountId(), payment.getId(), ImmutableList.<PluginProperty>of(),
                        tenantContext);
                paymentTransactionInfoPlugin = Iterables
                        .tryFind(result, new Predicate<PaymentTransactionInfoPlugin>() {
                            @Override
                            public boolean apply(final PaymentTransactionInfoPlugin input) {
                                return input.getKbTransactionPaymentId()
                                        .equals(rehydratedPaymentTransaction.getId());
                            }
                        }).or(new Supplier<PaymentTransactionInfoPlugin>() {
                            @Override
                            public PaymentTransactionInfoPlugin get() {
                                return undefinedPaymentTransaction;
                            }
                        });
            } catch (final Exception e) {
                paymentTransactionInfoPlugin = undefinedPaymentTransaction;
            }
            updatePaymentAndTransactionIfNeeded(payment, notificationKey.getAttemptNumber(), userToken,
                    rehydratedPaymentTransaction, paymentTransactionInfoPlugin, internalTenantContext);
            return null;
        }
    }, internalTenantContext);
}

From source file:brooklyn.entity.nosql.etcd.EtcdNodeSshDriver.java

@Override
public void leaveCluster(String nodeName) {
    List<String> listMembersCommands = Lists.newLinkedList();
    listMembersCommands.add("cd " + getRunDir());
    listMembersCommands.add(String.format("%s --peers %s member list", getEtcdCtlCommand(), getClientUrl()));
    ScriptHelper listMembersScript = newScript("listMembers").body.append(listMembersCommands).gatherOutput();
    int result = listMembersScript.execute();
    if (result != 0) {
        log.warn("{}: The 'member list' command on etcd '{}' failed: {}",
                new Object[] { entity, getClientUrl(), result });
        ;/* w w  w .  j a v  a2 s .  c  o  m*/
        log.debug("{}: STDOUT: {}", entity, listMembersScript.getResultStdout());
        log.debug("{}: STDERR: {}", entity, listMembersScript.getResultStderr());
        return; // Do not throw exception as may not be possible during shutdown
    }
    String output = listMembersScript.getResultStdout();
    Optional<String> found = Iterables.tryFind(Splitter.on(CharMatcher.anyOf("\r\n")).split(output),
            Predicates.containsPattern("name=" + nodeName));
    if (found.isPresent()) {
        String nodeId = Strings.getFirstWord(found.get()).replace(":", "");
        log.debug("{}: Removing etcd node {} with id {} from {}",
                new Object[] { entity, nodeName, nodeId, getClientUrl() });

        List<String> removeMemberCommands = Lists.newLinkedList();
        removeMemberCommands.add("cd " + getRunDir());
        removeMemberCommands.add(
                String.format("%s --peers %s member remove %s", getEtcdCtlCommand(), getClientUrl(), nodeId));
        newScript("removeMember").body.append(removeMemberCommands).failOnNonZeroResultCode().execute();
    } else {
        log.warn("{}: Did not find {} in list of etcd members", entity, nodeName);
    }
}

From source file:biz.ganttproject.impex.csv.GanttCSVExport.java

private void writeTasks(SpreadsheetWriter writer) throws IOException {
    List<CustomPropertyDefinition> customFields = writeTaskHeaders(writer);
    for (Task task : myTaskManager.getTasks()) {
        for (Map.Entry<String, BooleanOption> entry : myCsvOptions.getTaskOptions().entrySet()) {
            if (!entry.getValue().isChecked()) {
                continue;
            }//from w w  w .jav a2  s . c  om
            TaskDefaultColumn defaultColumn = TaskDefaultColumn.find(entry.getKey());
            if (defaultColumn == null) {
                if ("webLink".equals(entry.getKey())) {
                    writer.print(getWebLink((GanttTask) task));
                    continue;
                }
                if ("notes".equals(entry.getKey())) {
                    writer.print(task.getNotes());
                    continue;
                }
            } else {
                switch (defaultColumn) {
                case ID:
                    writer.print(String.valueOf(task.getTaskID()));
                    break;
                case NAME:
                    writer.print(getName(task));
                    break;
                case BEGIN_DATE:
                    writer.print(task.getStart().toString());
                    break;
                case END_DATE:
                    writer.print(task.getDisplayEnd().toString());
                    break;
                case DURATION:
                    writer.print(String.valueOf(task.getDuration().getLength()));
                    break;
                case COMPLETION:
                    writer.print(String.valueOf(task.getCompletionPercentage()));
                    break;
                case OUTLINE_NUMBER:
                    List<Integer> outlinePath = task.getManager().getTaskHierarchy().getOutlinePath(task);
                    writer.print(Joiner.on('.').join(outlinePath));
                    break;
                case COORDINATOR:
                    ResourceAssignment coordinator = Iterables
                            .tryFind(Arrays.asList(task.getAssignments()), COORDINATOR_PREDICATE).orNull();
                    writer.print(coordinator == null ? "" : coordinator.getResource().getName());
                    break;
                case PREDECESSORS:
                    writer.print(TaskProperties.formatPredecessors(task, ";", true));
                    break;
                case RESOURCES:
                    writer.print(getAssignments(task));
                    break;
                case COST:
                    writer.print(task.getCost().getValue().toPlainString());
                    break;
                case INFO:
                case PRIORITY:
                case TYPE:
                    break;
                }
            }
        }
        writeCustomPropertyValues(writer, customFields, task.getCustomValues().getCustomProperties());
    }
}

From source file:org.killbill.billing.util.security.shiro.dao.DefaultUserDao.java

@Override
public void updateUserRoles(final String username, final List<String> roles, final String updatedBy)
        throws SecurityApiException {
    inTransactionWithExceptionHandling(new TransactionCallback<Void>() {
        @Override/*  w ww.  ja  va  2s .c o  m*/
        public Void inTransaction(final Handle handle, final TransactionStatus status) throws Exception {
            final DateTime updatedDate = clock.getUTCNow();
            final UsersSqlDao usersSqlDao = handle.attach(UsersSqlDao.class);
            final UserModelDao userModelDao = usersSqlDao.getByUsername(username);
            if (userModelDao == null) {
                throw new SecurityApiException(ErrorCode.SECURITY_INVALID_USER, username);
            }

            // Remove stale entries
            final UserRolesSqlDao userRolesSqlDao = handle.attach(UserRolesSqlDao.class);
            final List<UserRolesModelDao> existingRoles = userRolesSqlDao.getByUsername(username);
            for (final UserRolesModelDao curRole : existingRoles) {
                if (Iterables.tryFind(roles, new Predicate<String>() {
                    @Override
                    public boolean apply(final String input) {
                        return input.equals(curRole.getRoleName());
                    }
                }).orNull() == null) {
                    userRolesSqlDao.invalidate(username, curRole.getRoleName(), updatedDate.toDate(),
                            updatedBy);
                }
            }

            // Add new entries
            for (final String curNewRole : roles) {
                if (Iterables.tryFind(existingRoles, new Predicate<UserRolesModelDao>() {
                    @Override
                    public boolean apply(final UserRolesModelDao input) {
                        return input.getRoleName().equals(curNewRole);
                    }
                }).orNull() == null) {
                    userRolesSqlDao.create(new UserRolesModelDao(username, curNewRole, updatedDate, updatedBy));
                }
            }
            return null;
        }
    });
}