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.jclouds.compute.util.ComputeServiceUtils.java

public static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in,
        Map<OsFamily, Map<String, String>> osVersionMap) {
    if (osVersionMap.containsKey(family)) {
        if (osVersionMap.get(family).containsKey(in))
            return osVersionMap.get(family).get(in);
        if (osVersionMap.get(family).containsValue(in))
            return in;
        CONTAINS_SUBSTRING contains = new CONTAINS_SUBSTRING(in.replace('-', '.'));
        try {/*from   w w w  .j  av  a 2s. co  m*/
            String key = Iterables.find(osVersionMap.get(family).keySet(), contains);
            return osVersionMap.get(family).get(key);
        } catch (NoSuchElementException e) {
            try {
                return Iterables.find(osVersionMap.get(family).values(), contains);
            } catch (NoSuchElementException e1) {
            }
        }
    }
    return "";
}

From source file:bear.main.FXConf.java

public void cancelThread(String name) {
    GlobalTaskRunner runContext = global.currentGlobalRunner;

    if (runContext == null) {
        ui.warn(new LogEventToUI("shell", "not running"));
        return;/*w w w  . j ava2 s  .c om*/
    }

    SessionContext $ = Iterables.find(runContext.getSessions(), Predicates2.methodEquals("getName", name));

    $.terminate();
}

From source file:org.opendaylight.controller.sal.connect.netconf.NetconfMapping.java

static RpcResult<CompositeNode> toRpcResult(NetconfMessage message, final QName rpc,
        Optional<SchemaContext> context) {
    CompositeNode rawRpc;/*from w ww.  ja v  a 2  s . c om*/
    if (context.isPresent())
        if (isDataRetrieQNameReply(rpc)) {

            Element xmlData = getDataSubtree(message.getDocument());

            List<org.opendaylight.yangtools.yang.data.api.Node<?>> dataNodes = XmlDocumentUtils
                    .toDomNodes(xmlData, Optional.of(context.get().getDataDefinitions()));

            CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder();
            it.setQName(NETCONF_RPC_REPLY_QNAME);
            it.add(ImmutableCompositeNode.create(NETCONF_DATA_QNAME, dataNodes));

            rawRpc = it.toInstance();
            // sys(xmlData)
        } else {
            RpcDefinition rpcSchema = Iterables.find(context.get().getOperations(),
                    new Predicate<RpcDefinition>() {
                        @Override
                        public boolean apply(final RpcDefinition input) {
                            return rpc == input.getQName();
                        }
                    });
            rawRpc = (CompositeNode) toCompositeNode(message.getDocument());
        }
    else {
        rawRpc = (CompositeNode) toCompositeNode(message.getDocument());
    }
    // rawRpc.
    return Rpcs.getRpcResult(true, rawRpc, Collections.<RpcError>emptySet());
}

From source file:gov.nih.nci.firebird.selenium2.pages.sponsor.protocol.review.ReviewRegistrationTab.java

private WebElement getCompleteReviewButton() {
    return Iterables.find(getDriver().findElements(By.id(COMPLETE_REVIEW_BUTTON_ID)),
            new Predicate<WebElement>() {
                @Override//from   ww w .j  a  v a  2  s  .c o m
                public boolean apply(WebElement button) {
                    return button.isDisplayed();
                }
            });
}

From source file:org.dasein.cloud.jclouds.vcloud.director.VCloudDirector.java

public @Nullable Vm waitForIdle(
        @Nonnull RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx, @Nullable Vm vm) {
    if (vm == null) {
        return null;
    }/*from  ww w  .  ja  v  a  2 s  .c o  m*/
    boolean busy = true;
    final URI vmUri = vm.getHref();
    while (busy) {
        try {
            Thread.sleep(1500L);
        } catch (InterruptedException ignore) {
            /* ignore */ }
        vm = Iterables.find(
                ctx.getApi().getVAppClient().getVApp(vm.getVAppParent().getHref()).getChildren().getVms(),
                new Predicate<Vm>() {
                    @Override
                    public boolean apply(Vm input) {
                        return vmUri.equals(input.getHref());
                    }
                });
        if (vm == null) {
            return null;
        }
        busy = false;
        for (Task task : vm.getTasks()) {
            busy = false;
            if (task == null || task.getStatus() == null) {
                continue;
            }
            if (task.getStatus().equals(Task.Status.QUEUED) || task.getStatus().equals(Task.Status.RUNNING)) {
                busy = true;
            }
        }
    }
    return vm;
}

From source file:com.houghtonassociates.bamboo.plugins.view.ViewGerritChainResultsAction.java

public String getJobResultKeyForLogDisplay() {
    if (jobResultKeyForLogDisplay == null && getChainResult().isInProgress()) {
        for (ChainStageResult stageResult : getChainResult().getStageResults()) {
            try {
                jobResultKeyForLogDisplay = Iterables
                        .find(stageResult.getBuildResults(), BambooPredicates.resultsSummaryIsInProgress())
                        .getBuildResultKey();
                return jobResultKeyForLogDisplay;
            } catch (NoSuchElementException e) {
            }/*from   w w w  . j  a  v a  2s.c o  m*/
        }
    }

    return jobResultKeyForLogDisplay;
}

From source file:br.ufpr.inf.gres.pitestincode.integration.pit.PITFacade.java

@Override
public List<Mutant> executeOperators(List<Operator> operators) {
    List<Mutant> mutants = new ArrayList<>();
    if (operators != null && !operators.isEmpty()) {
        PluginServices plugins = PluginServices.makeForContextLoader();

        ReportOptions reportOptions = createDefaultReportOptions();
        reportOptions.setMutators(operators.stream().map(Operator::getName).collect(Collectors.toList()));

        try {/*  w w w  .  j a  v a2 s  .  c  o m*/
            final Program programUnderTest = IntegrationFacade.getProgramUnderTest();
            EntryPointImpl entryPoint = getOrCreateEntryPoint();
            MutationAnalysisUnit unit = entryPoint.generateMutants(new File(trainingDirectory), reportOptions,
                    new SettingsFactory(reportOptions, plugins), new HashMap<>());
            if (unit != null) {
                if (unit instanceof MutationTestUnit) {
                    MutationTestUnit testUnit = (MutationTestUnit) unit;
                    Field field = testUnit.getClass().getDeclaredField("availableMutations");
                    field.setAccessible(true);
                    Collection<MutationDetails> fieldValue = (Collection<MutationDetails>) field.get(testUnit);
                    mutants.addAll(fieldValue.stream().map((mutationDetails) -> {
                        Mutant mutant = new Mutant(mutationDetails.getId().toString(), null, programUnderTest);
                        Operator mappedOperator = ALL_OPERATORS_BY_CLASS.get(mutationDetails.getMutator());
                        Operator operator = Iterables.find(operators,
                                (tempOperator) -> tempOperator.equals(mappedOperator));
                        mutant.getOperators().add(operator);
                        operator.getGeneratedMutants().add(mutant);
                        HashMap<Mutant, MutationDetails> programMutants = generatedMutants
                                .computeIfAbsent(programUnderTest, (t) -> new HashMap<>());
                        programMutants.putIfAbsent(mutant, mutationDetails);
                        return mutant;
                    }).collect(Collectors.toList()));
                    mutationUnits.putIfAbsent(programUnderTest, testUnit);
                } else {
                    throw new IllegalArgumentException("This should not be happening!");
                }
            }
        } catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException
                | IllegalAccessException ex) {
            Logger.getLogger(PITFacade.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return mutants;
}

From source file:org.wso2.carbon.identity.application.authenticator.fido.u2f.U2F.java

/**
 * Finishes a previously started high-level authentication.
 * @param authenticateRequestData the AuthenticateRequestData created by calling startAuthentication
 * @param response                the response from the device/client.
 * @param devices                 the devices currently registered to the user.
 * @param facets                  A list of valid facets to verify against.
 * @return                        The (updated) DeviceRegistration that was authenticated against.
 * @throws U2fException//  w  w w.  j a v  a 2 s.  co  m
 */
public DeviceRegistration finishAuthentication(AuthenticateRequestData authenticateRequestData,
        AuthenticateResponse response, Iterable<? extends DeviceRegistration> devices, Set<String> facets)
        throws U2fException {
    final AuthenticateRequest request = authenticateRequestData.getAuthenticateRequest(response);
    DeviceRegistration device = Iterables.find(devices, new Predicate<DeviceRegistration>() {
        @Override
        public boolean apply(DeviceRegistration input) {
            return Objects.equal(request.getKeyHandle(), input.getKeyHandle());
        }
    });

    finishAuthentication(request, response, device, facets);
    return device;
}

From source file:org.jclouds.aws.ec2.demos.createlamp.MainApp.java

private static RunningInstance findInstanceByKeyName(EC2Client client, final String keyName) {
    // search my account for the instance I just created
    Set<? extends Reservation<? extends RunningInstance>> reservations = client.getInstanceServices()
            .describeInstancesInRegion(null);

    // extract all the instances from all reservations
    Set<RunningInstance> allInstances = Sets.newHashSet();
    for (Reservation<? extends RunningInstance> reservation : reservations) {
        allInstances.addAll(reservation);
    }//from w  w  w. j  a  v  a  2s  . c  o m

    // get the first one that has a keyname matching what I just created
    return Iterables.find(allInstances, new Predicate<RunningInstance>() {

        @Override
        public boolean apply(RunningInstance input) {
            return input.getKeyName().equals(keyName) && input.getInstanceState() != InstanceState.TERMINATED;
        }

    });
}

From source file:org.dasein.cloud.jclouds.vcloud.director.compute.VAppTemplateSupport.java

private @Nonnull MachineImage executeImage(@Nonnull String vmId, @Nonnull String name,
        @Nonnull String description) throws CloudException, InternalException {
    RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx = provider.getCloudClient();

    try {//from w ww.  j  ava  2 s .co  m
        try {
            VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport()
                    .getVirtualMachine(vmId);
            Vm vcloudVm = ctx.getApi().getVmClient().getVm(provider.toHref(ctx, vmId));
            VApp parent = ctx.getApi().getVAppClient().getVApp(vcloudVm.getVAppParent().getHref());

            if (parent.getStatus().equals(Status.POWERED_ON)) {
                provider.waitForTask(ctx.getApi().getVAppClient().powerOff(parent.getHref()));
            }
            UndeployVAppParams params = UndeployVAppParams.builder().undeployPowerAction(PowerAction.POWER_OFF)
                    .build();
            provider.waitForTask(ctx.getApi().getVAppClient().undeploy(parent.getHref(), params));
            HashMap<String, Collection<NetworkConnection.Builder>> oldBuilders = new HashMap<String, Collection<NetworkConnection.Builder>>();
            for (Vm child : parent.getChildren().getVms()) {
                ArrayList<NetworkConnection.Builder> list = new ArrayList<NetworkConnection.Builder>();
                NetworkConnectionSection section = (NetworkConnectionSection) Iterables
                        .find(child.getSections(), Predicates.instanceOf(NetworkConnectionSection.class));
                for (NetworkConnection c : section.getNetworkConnections()) {
                    NetworkConnection.Builder builder = NetworkConnection.builder().fromNetworkConnection(c);
                    list.add(builder);
                }
                oldBuilders.put(provider.toId(ctx, child.getHref()), list);
            }
            /*
             * IPAddress allocation mode nonsense
            for( Vm child : parent.getChildren() ) {
            Builder sectionBuilder = child.getNetworkConnectionSection().toBuilder();
            ArrayList<NetworkConnection> connections = new ArrayList<NetworkConnection>();
                    
            for( NetworkConnection c : child.getNetworkConnectionSection().getConnections() ) {
                NetworkConnection.Builder builder = NetworkConnection.Builder.fromNetworkConnection(c);
                    
                builder.connected(false);
                builder.ipAddressAllocationMode(IpAddressAllocationMode.NONE);
                connections.add(builder.build());
            }
            sectionBuilder.connections(connections);
            provider.waitForTask(ctx.getApi().getVmClient().updateNetworkConnectionOfVm(sectionBuilder.build(), child.getHref()));
            }
            */
            /*
            System.out.println("Powering it back on...");
            provider.waitForTask(ctx.getApi().getVAppClient().deployAndPowerOnVApp(parent.getHref()));
            parent = provider.waitForIdle(ctx, parent);
            System.out.println("Turning it back off...");
            provider.waitForTask(ctx.getApi().getVAppClient().undeployAndSaveStateOfVApp(parent.getHref())); 
            */
            parent = provider.waitForIdle(ctx, parent);
            if (logger.isInfoEnabled()) {
                logger.info("Building template from " + vm);
            }
            VAppTemplate template;
            try {
                CaptureVAppParams capture = CaptureVAppParams.builder().description(description).build();

                template = ctx.getApi().getVdcClient().captureVApp(parent.getHref(), capture);

                if (logger.isDebugEnabled()) {
                    logger.debug("Template=" + template);
                }
                Catalog catalog = findCatalog(ctx);

                if (logger.isInfoEnabled()) {
                    logger.info("Adding " + template + " to catalog " + catalog);
                }
                if (catalog != null) {
                    // note you can also add properties here, if you want
                    Reference ref = Reference.builder().fromEntity(template).build();
                    CatalogItem item = CatalogItem.builder().name(name).description(description).entity(ref)
                            .build();
                    ctx.getApi().getCatalogClient().addCatalogItem(catalog.getHref(), item);
                    if (logger.isInfoEnabled()) {
                        logger.info("Template added to catalog");
                    }
                } else {
                    logger.warn("No catalog exists for this template");
                }
            } finally {
                if (logger.isInfoEnabled()) {
                    logger.info("Turning source VM back on");
                }
                try {
                    parent = provider.waitForIdle(ctx, parent);
                    for (Vm child : parent.getChildren().getVms()) {
                        child = provider.waitForIdle(ctx, child);

                        String id = provider.toId(ctx, child.getHref());
                        Collection<NetworkConnection.Builder> builders = oldBuilders.get(id);
                        Set<NetworkConnection> connections = Sets.newLinkedHashSet();

                        for (NetworkConnection.Builder builder : builders) {
                            builder.isConnected(true);
                            connections.add(builder.build());
                        }
                        NetworkConnectionSection section = VmSupport
                                .getSection(child, NetworkConnectionSection.class).toBuilder()
                                .networkConnections(connections).build();
                        if (logger.isInfoEnabled()) {
                            logger.info("Resetting network connection for " + child);
                        }
                        provider.waitForTask(ctx.getApi().getVmClient()
                                .modifyNetworkConnectionSection(child.getHref(), section));
                    }
                    parent = provider.waitForIdle(ctx, parent);
                    try {
                        logger.info("Powering VM " + parent + " on");
                        DeployVAppParams deploy = DeployVAppParams.builder().powerOn().build();
                        provider.waitForTask(ctx.getApi().getVAppClient().deploy(parent.getHref(), deploy));
                    } catch (Throwable t) {
                        logger.warn("Failed to power on VM " + parent);
                    }
                } catch (Throwable t) {
                    logger.warn("Error upading network connection for source VM: " + t.getMessage());
                    if (logger.isDebugEnabled()) {
                        t.printStackTrace();
                    }
                }
            }
            if (logger.isInfoEnabled()) {
                logger.info("Populating dasein image for new template: " + template);
            }
            return toMachineImage(ctx, provider.getOrg(vm.getProviderOwnerId()),
                    ctx.getApi().getVAppTemplateClient().getVAppTemplate(template.getHref()));
        } catch (RuntimeException e) {
            logger.error("Error creating template from " + vmId + ": " + e.getMessage());
            if (logger.isDebugEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
    } finally {
        ctx.close();
    }
}