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

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

Introduction

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

Prototype

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

Source Link

Document

Returns the first element in iterable that satisfies the given predicate; use this method only when such an element is known to exist.

Usage

From source file:org.obiba.onyx.quartz.editor.question.CopyQuestionPanel.java

private Question copyQuestion(LocaleProperties localeProperties) {
    Question question = (Question) getDefaultModelObject();

    localePropertiesUtils.load(localeProperties, questionnaireModel.getObject(), question);
    ElementClone<Question> questionCopy = QuestionnaireElementCloner.clone(question,
            new CloneSettings(false, true, false, true, true), localeProperties);
    questionCopy.getElement().setName(name.getModelObject());
    QuestionnaireElementCloner.addProperties(questionCopy, localeProperties);
    questionCopy.getElement().getQuestionCategories().clear();
    for (final Question subQuestion : question.getQuestions()) {
        localePropertiesUtils.load(localeProperties, questionnaireModel.getObject(), subQuestion);
        Question questionFind = Iterables.find(questionCopy.getElement().getQuestions(),
                new Predicate<Question>() {

                    @Override//from  w w w .  ja v  a 2  s  .c om
                    public boolean apply(Question inputQuestion) {
                        return inputQuestion.getName().startsWith("_" + subQuestion.getName() + "_");
                    }

                });
        copyLabels(localeProperties, subQuestion, questionFind);
    }
    switch (categories.getModelObject()) {
    case COPY:
        for (QuestionCategory questionCategory : question.getQuestionCategories()) {
            localePropertiesUtils.load(localeProperties, questionnaireModel.getObject(), questionCategory);
            ElementClone<QuestionCategory> questionCategoryCopy = QuestionnaireElementCloner
                    .clone(questionCategory, new CloneSettings(false, false, true), localeProperties);
            questionCopy.getElement().addQuestionCategory(questionCategoryCopy.getElement());
            QuestionnaireElementCloner.addProperties(questionCategoryCopy, localeProperties);

            for (final OpenAnswerDefinition openAnswer : questionCategory.getCategory()
                    .getOpenAnswerDefinitionsByName().values()) {
                String key = Iterables.find(questionCategoryCopy.getElement().getCategory()
                        .getOpenAnswerDefinitionsByName().keySet(), new Predicate<String>() {

                            @Override
                            public boolean apply(String inputKey) {
                                return inputKey.startsWith("_" + openAnswer.getName() + "_");
                            }

                        });
                OpenAnswerDefinition openAnswerCopy = questionCategoryCopy.getElement().getCategory()
                        .getOpenAnswerDefinitionsByName().get(key);
                copyLabels(localeProperties, openAnswer, openAnswerCopy);
            }
        }
        break;

    case SHARE:
        for (QuestionCategory questionCategory : question.getQuestionCategories()) {
            QuestionCategory questionCategoryCopy = new QuestionCategory();
            questionCategoryCopy.setExportName(questionCategory.getExportName());
            questionCategoryCopy.setCategory(questionCategory.getCategory());
            questionCopy.getElement().addQuestionCategory(questionCategoryCopy);
            copyLabels(localeProperties, questionCategory, questionCategoryCopy);
        }
    }
    return questionCopy.getElement();
}

From source file:terrastore.cluster.ensemble.impl.DefaultEnsembleManager.java

private Node findNode(List<Node> nodes, Member member) {
    try {//  w  ww  .j ava 2  s .co  m
        return Iterables.find(nodes, new NodeFinder(member.getConfiguration().getName()));
    } catch (NoSuchElementException ex) {
        return null;
    }
}

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

public Payment notifyPendingPaymentOfStateChanged(final boolean isApiPayment, final Account account,
        final UUID paymentTransactionId, final boolean isSuccess, final List<String> paymentControlPluginNames,
        final CallContext callContext, final InternalCallContext internalCallContext)
        throws PaymentApiException {
    final PaymentTransactionModelDao paymentTransactionModelDao = paymentDao
            .getPaymentTransaction(paymentTransactionId, internalCallContext);
    final List<PaymentAttemptModelDao> attempts = paymentDao.getPaymentAttemptByTransactionExternalKey(
            paymentTransactionModelDao.getTransactionExternalKey(), internalCallContext);
    final PaymentAttemptModelDao attempt = Iterables.find(attempts, new Predicate<PaymentAttemptModelDao>() {
        @Override// w  w w.  j  a  va  2s .  c  om
        public boolean apply(final PaymentAttemptModelDao input) {
            return input.getTransactionId().equals(paymentTransactionId);
        }
    });

    final Iterable<PluginProperty> pluginProperties;
    try {
        pluginProperties = PluginPropertySerializer.deserialize(attempt.getPluginProperties());
    } catch (final PluginPropertySerializerException e) {
        throw new PaymentApiException(e, ErrorCode.PAYMENT_INTERNAL_ERROR,
                String.format("Unable to deserialize payment attemptId='%s' properties", attempt.getId()));
    }

    return pluginControlledPaymentAutomatonRunner.run(isApiPayment, isSuccess,
            paymentTransactionModelDao.getTransactionType(), ControlOperation.NOTIFICATION_OF_STATE_CHANGE,
            account, attempt.getPaymentMethodId(), paymentTransactionModelDao.getPaymentId(),
            attempt.getPaymentExternalKey(), paymentTransactionId,
            paymentTransactionModelDao.getTransactionExternalKey(), paymentTransactionModelDao.getAmount(),
            paymentTransactionModelDao.getCurrency(), pluginProperties, paymentControlPluginNames, callContext,
            internalCallContext);
}

From source file:org.jclouds.ec2.compute.functions.RunningInstanceToNodeMetadata.java

@VisibleForTesting
Hardware getHardwareForInstance(final RunningInstance instance) {
    try {/*w  w w  .ja v a2s. c o m*/
        return Iterables.find(hardware.get(), new Predicate<Hardware>() {

            @Override
            public boolean apply(Hardware input) {
                return input.getId().equals(instance.getInstanceType());
            }

        });
    } catch (NoSuchElementException e) {
        logger.debug("couldn't match instance type %s in: %s", instance.getInstanceType(), hardware.get());
        return null;
    }
}

From source file:brooklyn.networking.sdn.mesos.CalicoModuleImpl.java

/** For Calico we use profiles to group containers in networks and add the required IP address to the eth1 calico interface. */
@Override//from   w w w. ja  va 2 s  .  com
public InetAddress attachNetwork(MesosSlave slave, Entity entity, String containerId, String subnetId) {
    InetAddress address = getNextContainerAddress(subnetId);

    // Run some commands to get information about the container network namespace
    String dockerIpOutput = slave.execCommand(sudo("ip addr show dev docker0 scope global label docker0"));
    String dockerIp = Strings.getFirstWordAfter(dockerIpOutput.replace('/', ' '), "inet");
    String inspect = Strings
            .trimEnd(slave.execCommand(sudo("docker inspect -f '{{.State.Pid}}' " + containerId)));
    String dockerPid = Iterables.find(Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().split(inspect),
            StringPredicates.matchesRegex("^[0-9]+$"));
    Cidr subnetCidr = getSubnetCidr(subnetId);
    String slaveAddressOutput = slave.execCommand(sudo("ip addr show dev eth0 scope global label eth0"));
    String slaveAddress = Strings.getFirstWordAfter(slaveAddressOutput.replace('/', ' '), "inet");

    // Determine whether we are attatching the container to the initial application network
    String applicationId = entity.getApplicationId();
    boolean initial = subnetId.equals(applicationId);

    // Add the container if we have not yet done so
    if (initial) {
        execCalicoCommand(slave,
                String.format("calicoctl container add %s %s", containerId, address.getHostAddress()));

        // Return its endpoint ID
        String getEndpointId = String.format("calicoctl container %s endpoint-id show", containerId);
        String getEndpointIdStdout = execCalicoCommand(slave, getEndpointId);
        Optional<String> endpointId = Iterables.tryFind(
                Splitter.on(CharMatcher.anyOf("\r\n")).split(getEndpointIdStdout),
                StringPredicates.matchesRegex("[0-9a-f]{32}"));
        if (!endpointId.isPresent())
            throw new IllegalStateException("Cannot find endpoint-id: " + getEndpointIdStdout);

        // Add to the application profile
        execCalicoCommand(slave, String.format("calicoctl profile add %s", subnetId));
        execCalicoCommand(slave,
                String.format("calicoctl endpoint %s profile append %s", endpointId.get(), subnetId));
    }

    // Set up the network
    List<String> commands = MutableList.of();
    commands.add(sudo("mkdir -p /var/run/netns"));
    commands.add(BashCommands
            .ok(sudo(String.format("ln -s /proc/%s/ns/net /var/run/netns/%s", dockerPid, dockerPid))));
    if (initial) {
        commands.add(sudo(String.format("ip netns exec %s ip route del default", dockerPid)));
        commands.add(sudo(String.format("ip netns exec %s ip route add default via %s", dockerPid, dockerIp)));
        commands.add(sudo(String.format("ip netns exec %s ip route add %s via %s", dockerPid,
                subnetCidr.toString(), slaveAddress)));
    } else {
        commands.add(sudo(String.format("ip netns exec %s ip addr add %s/%d dev eth1", dockerPid,
                address.getHostAddress(), subnetCidr.getLength())));
    }
    for (String cmd : commands) {
        slave.execCommand(cmd);
    }

    return address;
}

From source file:edu.ucsb.eucalyptus.msgs.BaseMessage.java

/**
 * Get the XML form of the message.// w w w . j a  v  a2s  .c  o  m
 * 
 * @param namespace
 * @return String representation of the object, null if binding fails.
 */
public String toString(String namespace) {
    ByteArrayOutputStream temp = new ByteArrayOutputStream();
    Class targetClass = Iterables.find(Classes.classAncestors(this), new Predicate<Class>() {
        @Override
        public boolean apply(Class arg0) {
            return !arg0.isAnonymousClass();
        }
    });
    try {
        IBindingFactory bindingFactory = BindingDirectory.getFactory(namespace, targetClass);
        IMarshallingContext mctx = bindingFactory.createMarshallingContext();
        mctx.setIndent(2);
        mctx.marshalDocument(this, "UTF-8", null, temp);
    } catch (JiBXException e) {
        Logger.getLogger(BaseMessage.class).debug(e, e);
    } catch (Exception e) {
        Logger.getLogger(BaseMessage.class).error(e, e);
    }
    return temp.toString();
}

From source file:org.jclouds.azurecompute.compute.AzureComputeServiceAdapter.java

@Override
public OSImage getImage(final String id) {
    final String[] idParts = OSImageToImage.fromGeoName(id);
    final OSImage image = Iterables.find(api.getOSImageApi().list(), new Predicate<OSImage>() {
        @Override// www .j a  v  a2s.c o  m
        public boolean apply(final OSImage input) {
            return idParts[0].equals(input.name());
        }
    });

    return image == null ? null
            : idParts[1] == null ? image
                    : OSImage.create(id, idParts[1], image.affinityGroup(), image.label(), image.description(),
                            image.imageFamily(), image.category(), image.os(), image.publisherName(),
                            image.mediaLink(), image.logicalSizeInGB(), image.eula());
}

From source file:fr.xebia.vcloud.AbstractVcloud.java

/**
 * Configure each VM ://from  w  ww.j  a  v a 2 s  .  c o  m
 * <ul>
 * <li>Set root password</li>
 * <li>Set bootstrap script</li>
 * <li>Start VMs</li>
 * </ul>
 * Warning : The Database server must be up and running while Tomcat server start. If not,
 * Petclinic app will be down.
 *
 * @param vapp the vApp
 * @throws com.vmware.vcloud.sdk.VCloudException
 *
 * @throws java.io.IOException
 * @throws java.util.concurrent.TimeoutException
 *
 */
protected void configureAndStartVMs(Vapp vapp) throws VCloudException, IOException, TimeoutException {
    // Refresh vApp
    vapp = Vapp.getVappByReference(vcloudClient, vapp.getReference());
    List<VM> vms = vapp.getChildrenVms();
    VM vmMySQL = Iterables.find(vms, new VmPredicate(VM_MYSQL));
    VM vmApache = Iterables.find(vms, new VmPredicate(VM_APACHE_RP));
    VM vmTomcat1 = Iterables.find(vms, new VmPredicate(VM_TOMCAT_1));
    VM vmTomcat2 = Iterables.find(vms, new VmPredicate(VM_TOMCAT_2));

    configureVmMySQL(vmMySQL);
    // Start MySQL VM now to be sure database server it is up and running while
    // Tomcat VMs start. If not, Petclinic app will be down
    startVM(vmMySQL);

    // Get MySQL IP
    String ipMysql = Iterables.getOnlyElement(vmMySQL.getNetworkConnections()).getIpAddress();
    configureVmTomcat(vmTomcat1, ipMysql);
    configureVmTomcat(vmTomcat2, ipMysql);

    // Get Tomcat IPs
    String ipTomcat1 = Iterables.getOnlyElement(vmTomcat1.getNetworkConnections()).getIpAddress();
    String ipTomcat2 = Iterables.getOnlyElement(vmTomcat2.getNetworkConnections()).getIpAddress();
    configureVmApache(vmApache, ipTomcat1, ipTomcat2);

    // Start Tomcat and Apache VM
    startVM(vmTomcat1);
    startVM(vmTomcat2);
    startVM(vmApache);

    String ipApache = Iterables.getOnlyElement(vmApache.getNetworkConnections()).getIpAddress();
    LOGGER.info("Petclinic app available :  http://" + ipApache + "/xebia-petclinic");
}

From source file:org.jclouds.vfs.provider.blobstore.BlobStoreFileObject.java

private void getContainer(String name) {
    metadata = Iterables.find(getBlobStore().list(), new Predicate<StorageMetadata>() {
        @Override//from  www .ja  va 2  s  . com
        public boolean apply(StorageMetadata input) {
            return input.getType() == StorageType.CONTAINER && input.getName().equals(container);
        }
    });
    logger.info(String.format("<< container: %s/%s", container, name));
}

From source file:com.proofpoint.cloudmanagement.service.JCloudsInstanceConnector.java

@Override
public com.proofpoint.cloudmanagement.service.Location getLocation(final String location) {
    Location jcloudsLocation = Iterables.find(computeService.listAssignableLocations(),
            new Predicate<Location>() {
                @Override// ww w . ja  v  a  2s.  c  om
                public boolean apply(@Nullable Location input) {
                    return input.getId().equals(location);
                }
            });

    return new com.proofpoint.cloudmanagement.service.Location(jcloudsLocation.getId(),
            jcloudsLocation.getDescription(), this.getSizes(jcloudsLocation.getId()));
}