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:org.apache.brooklyn.entity.nosql.etcd.EtcdNodeSshDriver.java

@Override
public void leaveCluster(String nodeName) {
    synchronized (getEntity().getClusterMutex()) {
        List<String> listMembersCommands = Lists.newLinkedList();
        listMembersCommands.add("cd " + getRunDir());
        listMembersCommands/*from ww  w .j a v  a  2s  . c  om*/
                .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 });
            ;
            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();
        Iterable<String> found = Iterables.filter(Splitter.on(CharMatcher.anyOf("\r\n")).split(output),
                Predicates.containsPattern("name="));
        Optional<String> node = Iterables.tryFind(found, Predicates.containsPattern(nodeName));
        if (Iterables.size(found) > 1 && node.isPresent()) {
            String nodeId = Strings.getFirstWord(node.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("{}: {} is not part of an etcd cluster", entity, nodeName);
        }
    }
}

From source file:com.eucalyptus.util.dns.NameserverResolver.java

@SuppressWarnings("ConstantConditions")
public static InetAddress maphost(final InetAddress listenerAddress, final InetAddress hostAddress) {
    InetAddress result = hostAddress;
    final Cidr cidr = cidrLookup.apply(listenerAddress);
    if (!cidr.apply(result)) {
        final Host host = Hosts.lookup(hostAddress);
        if (host != null) {
            result = Iterables.tryFind(host.getHostAddresses(), cidr).or(result);
        }/*  w ww . ja  va 2s  .  c  o  m*/
    }
    return result;
}

From source file:com.siemens.sw360.datahandler.common.CommonUtils.java

public static Optional<ModerationRequest> getFirstModerationRequestOfUser(
        List<ModerationRequest> moderationRequestsForDocumentId, final String email) {
    return Iterables.tryFind(moderationRequestsForDocumentId, new Predicate<ModerationRequest>() {
        @Override/*w  w w  .  j a v  a2  s .c om*/
        public boolean apply(ModerationRequest input) {
            return input.getRequestingUser().equals(email);
        }
    });
}

From source file:org.restlet.ext.apispark.internal.introspection.helper.SwaggerAnnotationUtils.java

/**
 * Adds data from the {@link ApiResponse} annotation to the operation.
 * /*ww  w . jav a2s  . c  o  m*/
 * @param apiResponse
 *            The {@link ApiResponse} annotation.
 * @param operation
 *            The {@link Operation} to update.
 * @param representationsUsed
 *            The {@link java.lang.Class} of representation used.
 */
public static void processApiResponse(ApiResponse apiResponse, Operation operation,
        List<Class<?>> representationsUsed) {
    List<Response> responses = operation.getResponses();
    if (responses == null) {
        responses = new ArrayList<>();
        operation.setResponses(responses);
    }
    final int code = apiResponse.code();

    Optional<Response> existingResponse = Iterables.tryFind(responses, new Predicate<Response>() {
        @Override
        public boolean apply(Response response) {
            return response.getCode() == code;
        }
    });
    boolean responseExists = existingResponse.isPresent();
    Response response;
    if (responseExists) {
        response = existingResponse.get();
    } else {
        response = new Response();
        response.setCode(code);
    }

    response.setCode(code);
    response.setName(Status.valueOf(code).getReasonPhrase());
    if (!StringUtils.isNullOrEmpty(apiResponse.message())) {
        response.setDescription(apiResponse.message());
    }
    Class<?> responseClazz = apiResponse.response();
    if (responseClazz != null && responseClazz != Void.TYPE && responseClazz != Void.class) {
        representationsUsed.add(responseClazz);
        PayLoad payLoad = new PayLoad();
        payLoad.setType(Types.convertPrimitiveType(responseClazz));
        response.setOutputPayLoad(payLoad);
    }

    if (!responseExists) {
        responses.add(response);
    }
}

From source file:clocker.mesos.entity.framework.MesosFrameworkImpl.java

public List<String> scanTasks(JsonArray frameworks) {
    String frameworkId = sensors().get(FRAMEWORK_ID);
    Entity mesosCluster = sensors().get(MESOS_CLUSTER);
    LOG.debug("Periodic scanning of framework tasks: frameworkId={}, mesosCluster={}", frameworkId,
            mesosCluster);/*from w  w  w. jav  a  2  s.co m*/

    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject framework = frameworks.get(i).getAsJsonObject();
        if (frameworkId.equals(framework.get("id").getAsString())) {
            JsonArray completed = framework.getAsJsonArray("completed_tasks");
            JsonArray tasks = framework.getAsJsonArray("tasks");
            sensors().set(MESOS_COMPLETED_TASKS, completed.size());
            sensors().set(MESOS_RUNNING_TASKS, tasks.size());

            List<String> taskNames = MutableList.<String>of();
            for (int j = 0; j < tasks.size(); j++) {
                JsonObject json = tasks.get(j).getAsJsonObject();
                String id = json.get("id").getAsString();
                String name = json.get("name").getAsString();
                String state = json.get("state").getAsString();

                Optional<Entity> taskEntity = Iterables.tryFind(sensors().get(FRAMEWORK_TASKS).getMembers(),
                        Predicates.compose(Predicates.equalTo(id),
                                EntityFunctions.attribute(MesosTask.TASK_ID)));
                MesosTask task = null;
                if (taskEntity.isPresent()) {
                    // Only interested in tasks for our own use of Marathon.
                    // Tasks that other people create we'll ignore.
                    task = (MesosTask) taskEntity.get();
                }
                if (task != null) {
                    taskNames.add(name);
                    task.sensors().set(MesosTask.TASK_ID, id);
                    task.sensors().set(MesosTask.TASK_STATE, state);
                }
            }

            Set<String> taskNamesSet = Sets.newHashSet(taskNames);
            for (Entity member : ImmutableList.copyOf(getTaskCluster().getMembers())) {
                final String name = member.sensors().get(MesosTask.TASK_NAME);
                if (name != null) {
                    boolean found = taskNamesSet.contains(name);
                    if (found)
                        continue;
                }

                // Stop and then remove the task as it is no longer running, unless ON_FIRE
                //
                // TODO Aled worries about this: if task has gone, then MarathonTask polling
                // the task's URL will fail, setting the serviceUp to false, setting it 
                // on-fire. What will ever remove the task on a graceful shutdown of a container?
                // Or is that handled elsewhere?
                Lifecycle state = member.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    getTaskCluster().removeMember(member);
                    getTaskCluster().removeChild(member);
                    Entities.unmanage(member);
                } else {
                    ServiceStateLogic.setExpectedState(member, Lifecycle.STOPPING);
                }
            }
            return taskNames;
        }
    }
    // not found
    return null;
}

From source file:org.killbill.billing.payment.core.PaymentRefresher.java

private PaymentTransactionInfoPlugin findPaymentTransactionInfoPlugin(
        final PaymentTransactionModelDao paymentTransactionModelDao,
        @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions) {
    if (pluginTransactions == null) {
        return null;
    }//from ww w  .j av a2 s. co  m

    return Iterables.tryFind(pluginTransactions, new Predicate<PaymentTransactionInfoPlugin>() {
        @Override
        public boolean apply(final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin) {
            return paymentTransactionModelDao.getId()
                    .equals(paymentTransactionInfoPlugin.getKbTransactionPaymentId());
        }
    }).orNull();
}

From source file:org.opendaylight.protocol.bgp.openconfig.impl.util.OpenConfigUtil.java

public static AfiSafi toNeighborAfiSafiAddPath(final AfiSafi afiSafi, final BgpTableType tableType,
        final List<AddressFamilies> capabilities) {
    final Optional<AddressFamilies> capability = Iterables.tryFind(capabilities,
            af -> af.getAfi().equals(tableType.getAfi()) && af.getSafi().equals(tableType.getSafi()));
    if (!capability.isPresent()) {
        return afiSafi;
    }/*w w  w .j a  v a 2 s .  c o m*/
    return new AfiSafiBuilder(afiSafi).addAugmentation(
            org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev160614.AfiSafi1.class,
            fromSendReceiveMode(capability.get().getSendReceive())).build();
}

From source file:brooklyn.entity.basic.AbstractGroupImpl.java

/**
 * Returns {@code true} if the group was changed as a result of the call.
 *//*from ww  w .  j  a va2  s  .com*/
@Override
public boolean removeMember(final Entity member) {
    synchronized (members) {
        member.removeGroup((Group) getProxyIfAvailable());
        boolean changed = (member != null && members.remove(member));
        if (changed) {
            log.debug("Group {} lost member {}", this, member);
            // TODO ideally the following are all synched
            setAttribute(GROUP_SIZE, getCurrentSize());
            setAttribute(GROUP_MEMBERS, getMembers());
            if (member.equals(getAttribute(FIRST))) {
                // TODO should we elect a new FIRST ?  as is the *next* will become first.  could we do away with FIRST altogether?
                setAttribute(FIRST, null);
            }
            // emit after the above so listeners can use getMembers() and getCurrentSize()
            emit(MEMBER_REMOVED, member);

            if (Boolean.TRUE.equals(getConfig(MEMBER_DELEGATE_CHILDREN))) {
                Optional<Entity> result = Iterables.tryFind(getChildren(), new Predicate<Entity>() {
                    @Override
                    public boolean apply(Entity input) {
                        return input.getConfig(DelegateEntity.DELEGATE_ENTITY).equals(member);
                    }
                });
                if (result.isPresent()) {
                    Entity child = result.get();
                    removeChild(child);
                    Entities.unmanage(child);
                }
            }

            getManagementSupport().getEntityChangeListener().onMembersChanged();
        }

        return changed;
    }
}

From source file:org.killbill.billing.payment.core.sm.PaymentStateMachineHelper.java

public final State fetchNextState(final String prevStateName, final boolean isSuccess)
        throws MissingEntryException {
    final StateMachine stateMachine = getStateMachineForStateName(prevStateName);
    final Transition transition = Iterables
            .tryFind(ImmutableList.copyOf(stateMachine.getTransitions()), new Predicate<Transition>() {
                @Override//w  w  w .  j  av  a2  s .  c  o m
                public boolean apply(final Transition input) {
                    // This works because there is only one operation defined for a given state machine, which is our model for PaymentStates.xml
                    return input.getInitialState().getName().equals(prevStateName) && input.getOperationResult()
                            .equals(isSuccess ? OperationResult.SUCCESS : OperationResult.FAILURE);
                }
            }).orNull();
    return transition != null ? transition.getFinalState() : null;
}

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

/**
 * Return the connection, if any, matching the incoming destination connectionDestinationId
 *
 * @param connectionDestinationId the unique id for the connection destination to find
 * @return a connection matching the incoming connectionDestinationId, or Null if not found
 *//*  ww  w.j  a  va 2 s .  c om*/
public ConnectionDTO getConnectionMatchingDestinationId(final String connectionDestinationId) {
    if (connections != null) {
        return Iterables.tryFind(connections, new Predicate<ConnectionDTO>() {
            @Override
            public boolean apply(ConnectionDTO connection) {
                return connection.getDestination() != null
                        && connection.getDestination().getId().equals(connectionDestinationId);
            }
        }).orNull();
    }
    return null;
}