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

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

Introduction

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

Prototype

@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:com.dmdirc.ui.core.profiles.CoreProfilesDialogModel.java

@Override
public void removeProfile(final MutableProfile profile) {
    checkNotNull(profile, "Profile cannot be null");
    checkArgument(profiles.containsValue(profile), "profile must exist in list");
    profiles.remove(profile.getName());/*ww w  .j  a  v  a 2  s . com*/
    if (getSelectedProfile().isPresent() && getSelectedProfile().get().equals(profile)) {
        setSelectedProfile(Optional.ofNullable(Iterables.getFirst(profiles.values(), null)));
        setSelectedProfileIdent(Optional.empty());
        setSelectedProfileRealname(Optional.empty());
        setSelectedProfileSelectedHighlight(Optional.empty());
        setSelectedProfileName(Optional.empty());
        setSelectedProfileSelectedNickname(Optional.empty());
        setSelectedProfileHighlights(Optional.empty());
        setSelectedProfileNicknames(Optional.empty());
    }
    listeners.getCallable(ProfilesDialogModelListener.class).profileRemoved(profile);
}

From source file:org.aegis.app.sample.ec2.windows.WindowsInstanceStarter.java

public void run() {
    final String region = arguments.getRegion();

    // Build a template
    Template template = computeService.templateBuilder().locationId(region)
            .imageNameMatches(arguments.getImageNamePattern()).hardwareId(arguments.getInstanceType()).build();
    logger.info("Selected AMI is: %s", template.getImage().toString());
    template.getOptions().inboundPorts(3389);

    // Create the node
    logger.info("Creating node and waiting for it to become available");
    Set<? extends NodeMetadata> nodes = null;
    try {/*from   w  w  w .ja  v a 2s .  co  m*/
        nodes = computeService.createNodesInGroup("basic-ami", 1, template);
    } catch (RunNodesException e) {
        logger.error(e, "Unable to start nodes; aborting");
        return;
    }
    NodeMetadata node = Iterables.getOnlyElement(nodes);

    // Wait for the administrator password
    logger.info("Waiting for administrator password to become available");

    // This predicate will call EC2's API to get the Windows Administrator
    // password, and returns true if there is password data available.
    Predicate<String> passwordReady = new Predicate<String>() {
        @Override
        public boolean apply(@Nullable String s) {
            if (Strings.isNullOrEmpty(s))
                return false;
            PasswordData data = ec2Client.getWindowsServices().getPasswordDataInRegion(region, s);
            if (data == null)
                return false;
            return !Strings.isNullOrEmpty(data.getPasswordData());
        }
    };

    // Now wait, using RetryablePredicate
    final int maxWait = 600;
    final int period = 10;
    final TimeUnit timeUnit = TimeUnit.SECONDS;
    RetryablePredicate<String> passwordReadyRetryable = new RetryablePredicate<String>(passwordReady, maxWait,
            period, timeUnit);
    boolean isPasswordReady = passwordReadyRetryable.apply(node.getProviderId());
    if (!isPasswordReady) {
        logger.error("Password is not ready after %s %s - aborting and shutting down node", maxWait,
                timeUnit.toString());
        computeService.destroyNode(node.getId());
        return;
    }

    // Now we can get the password data, decrypt it, and get a LoginCredentials instance
    PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(
            ec2Client.getWindowsServices().getPasswordDataInRegion(region, node.getProviderId()),
            node.getCredentials().getPrivateKey());
    WindowsLoginCredentialsFromEncryptedData f = context.getUtils().getInjector()
            .getInstance(WindowsLoginCredentialsFromEncryptedData.class);
    LoginCredentials credentials = f.apply(dataAndKey);

    // Send to the log the details you need to log in to the instance with RDP
    String publicIp = Iterables.getFirst(node.getPublicAddresses(), null);
    logger.info("IP address: %s", publicIp);
    logger.info("Login name: %s", credentials.getUser());
    logger.info("Password:   %s", credentials.getPassword());

    // Wait for Enter on the console
    logger.info("Hit Enter to shut down the node.");
    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);
    try {
        in.readLine();
    } catch (IOException e) {
        logger.error(e, "IOException while reading console input");
    }

    // Tidy up
    logger.info("Shutting down");
    computeService.destroyNode(node.getId());
}

From source file:eu.interedition.collatex.nmerge.mvd.Variant.java

/**
 * Generate content by following the paths of the variant
 * in the MVD./*from  www. j  a v a 2  s.c  om*/
 */
private void findContent() {
    data = Lists.newArrayList();
    int iNode = startIndex;
    Match<T> p = collation.getMatches().get(iNode);
    int i = startOffset;
    int totalLen = 0;
    while (p.length() == 0 || totalLen < this.length) {
        if (p.length() == 0 || i == p.length()) {
            iNode = collation.next(iNode + 1, Iterables.getFirst(versions, null));
            p = collation.getMatches().get(iNode);
            i = 0;
        } else {
            data.addAll(p.getTokens());
            totalLen += p.getTokens().size();
        }
    }
}

From source file:us.physion.ovation.ui.editor.ResourceInfoPanel.java

private void initUi() {
    DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(
            getAvailableContentTypes().toArray(new String[0]));
    contentTypeComboBox.setModel(model);
    contentTypeComboBox.setSelectedItem(getContentType());

    contentTypeComboBox.addItemListener((ItemEvent e) -> {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            String selection = (String) e.getItem();
            setContentType(selection);/*from w  w  w  . j  a  v  a2s. c o  m*/
        }
    });

    final DataContext ctx = Lookup.getDefault().lookup(ConnectionProvider.class).getDefaultContext();

    addSourcesTextField.addActionListener((ActionEvent e) -> {
        addSourceFromText(ctx, addSourcesTextField.getText());
    });

    addSourcesTextField.setEnabled(getMeasurements().size() > 0 || getResources().stream().anyMatch((r) -> {
        return !(r instanceof Measurement);
    }) || getRevisions().stream().anyMatch((r) -> {
        return !(r.getResource() instanceof Measurement);
    }));

    OvationEntity e = Iterables.getFirst(getEntities(OvationEntity.class), null);
    if (e != null) {
        ListeningExecutorService svc = e.getDataContext().getCoordinator().getExecutorService();
        ListenableFuture<List<String>> sourceIds = svc.submit(() -> {
            try {
                //TODO make this async
                List<String> sourceIds1 = getSourceIds(ctx.getTopLevelSources());
                List<String> sortedIds = Lists.newArrayList(sourceIds1);
                Collections.sort(sortedIds);
                AutoCompleteDecorator.decorate(addSourcesTextField, sortedIds, false);
                return sortedIds;
            } catch (Throwable ex) {
                logger.error("Unable to retrieve Sources. Autocomplete for Source IDs disabled.");
                return Lists.newArrayList();
            }
        });
    }

    revisionFileWell
            .setDelegate(new FileWell.AbstractDelegate(Bundle.ResourceInfoPanel_Drop_Files_For_New_Revision()) {

                @Override
                public void filesDropped(File[] files) {
                    if (files.length == 0 || getResources().size() > 1) {
                        return;
                    }

                    for (Resource r : getResources()) {
                        try {
                            File main = null;
                            List<URL> supporting = Lists.newLinkedList();
                            for (File f : files) {
                                if (f.getName().equals(r.getFilename())) {
                                    main = f;
                                } else {
                                    supporting.add(f.toURI().toURL());
                                }

                            }

                            if (main == null) {
                                main = files[0];
                                supporting.remove(0);
                            }

                            r.addRevision(main.toURI().toURL(), ContentTypes.getContentType(main),
                                    main.getName(), supporting);

                        } catch (MalformedURLException ex) {
                            throw new OvationException("Unable to create new revision", ex);
                        } catch (IOException ex) {
                            throw new OvationException("Unable to create new revision", ex);
                        }
                    }
                }
            });

    updateInputs();
}

From source file:org.dcache.gridsite.InMemoryCredentialStore.java

private GSSCredential bestCredentialMatching(DnFqanMatcher predicate) {
    GSSCredential bestCredential = null;
    long bestRemainingLifetime = 0;

    for (Map.Entry<DelegationIdentity, GSSCredential> entry : _storage.entrySet()) {
        try {/*from  w w  w.j  a  v a2  s  . c  om*/
            GSSCredential credential = entry.getValue();
            Iterable<String> fqans = GSSUtils.getFQANsFromGSSCredential(vomsDir, caDir, credential);
            String primaryFqan = Iterables.getFirst(fqans, null);

            if (!predicate.matches(entry.getKey().getDn(), primaryFqan)) {
                continue;
            }

            long remainingLifetime = credential.getRemainingLifetime();

            if (remainingLifetime > bestRemainingLifetime) {
                bestRemainingLifetime = remainingLifetime;
                bestCredential = credential;
            }
        } catch (GSSException | AuthorizationException ignored) {
            // Treat problematic credentials as having expired
        }
    }

    return bestCredential;
}

From source file:org.eclipse.xtext.xtext.SuperCallScope.java

@Override
public IEObjectDescription getSingleElement(EObject object) {
    return Iterables.getFirst(getElements(object), null);
}

From source file:com.android.tools.idea.wizard.AddAndroidActivityPath.java

/**
 * Finds and returns the main src directory for the given project or null if one cannot be found.
 *///from   w ww  .  j a v a 2  s . c o m
@Nullable
public static File findSrcDirectory(@NotNull SourceProvider sourceProvider) {
    return Iterables.getFirst(sourceProvider.getJavaDirectories(), null);
}

From source file:org.diqube.plan.planner.RemoteColumnManager.java

@Override
public List<RExecutionPlanStep> build() {
    // columnValuesProvidingStep is ignored.
    for (Entry<String, List<RExecutionPlanStep>> remoteEntry : functionRemoteSteps.entrySet()) {
        PlannerColumnInfo colInfo = columnInfo.get(remoteEntry.getKey());
        RExecutionPlanStep inputStep = Iterables.getFirst(remoteEntry.getValue(), null);
        for (String prevColumnName : colInfo.getDependsOnColumns())
            wireOutputOfColumnIfAvailable(prevColumnName, inputStep);
    }/*w ww  .  j  a  va  2s. c o  m*/

    List<RExecutionPlanStep> allSteps = functionRemoteSteps.values().stream().flatMap(lst -> lst.stream())
            .collect(Collectors.toList());
    return allSteps;
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {/*from  w ww  .  j  a v  a 2s . co  m*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:org.alloy.metal.xml.merge.MergePoint.java

private List<Node> merge(MergeHandler handler, List<Node> exhaustedNodes, Object sourceLoc, Object patchLoc)
        throws XPathExpressionException, TransformerException {
    if (sourceLoc == null) {
        sourceLoc = this.sourceDoc;
    }// w w  w  .jav  a2s.  c o m

    if (patchLoc == null) {
        patchLoc = this.patchDoc;
    }

    String[] xPaths = handler.getXPath().split(" ");

    MutableList<Node> sourceNodes = _Lists.list();
    MutableList<Node> patchNodes = _Lists.list();

    for (String xPathVal : xPaths) {
        sourceNodes.addAll(this.getNodes(xPathVal, sourceLoc));
        patchNodes.addAll(this.getNodes(xPathVal, patchLoc));
    }

    MutableList<Pair<Node, Node>> matchedNodes = _Lists.list();
    MutableList<Node> unmatchedPatchNodes = _Lists.list();

    for (Node sourceNode : sourceNodes) {
        Optional<Node> matchingNode = patchNodes.filter(this.filter(sourceNode, handler.getMatcherType()))
                .single();

        if (matchingNode.isPresent()) {
            log.debug("Match found: " + matchingNode + " for source node " + sourceNode);
            matchedNodes.add(_Tuple.of(sourceNode, matchingNode.get()));
        }
    }

    for (Node patchNode : patchNodes) {
        boolean matchFound = false;
        for (Pair<Node, Node> matchedNode : matchedNodes) {
            if (patchNode == matchedNode.getSecond()) {
                matchFound = true;
                break;
            }
        }

        if (!matchFound) {
            unmatchedPatchNodes.add(patchNode);
        }
    }

    for (Pair<Node, Node> matchedNode : matchedNodes) {
        if (handler.getChildren().isEmpty()) {
            this.merge(this.getDefaultMergeHandler(), exhaustedNodes, matchedNode.getFirst(),
                    matchedNode.getSecond());
        } else {
            for (MergeHandler childHandler : handler.getChildren()) {
                this.merge(childHandler, exhaustedNodes, matchedNode.getFirst(), matchedNode.getSecond());
            }
        }

        exhaustedNodes.add(matchedNode.getSecond());
        handler.merge(matchedNode.getFirst(), matchedNode.getSecond());
    }

    if (!sourceNodes.isEmpty()) {
        Node parent = Iterables.getFirst(sourceNodes, null).getParentNode();

        for (Node unmatchedPatchNode : unmatchedPatchNodes) {
            if (!exhaustedNodes.contains(unmatchedPatchNode)) {
                exhaustedNodes.add(unmatchedPatchNode);
                parent.appendChild(_XPath.cloneAndImport(unmatchedPatchNode, _XPath.getDocument(parent)));
            }
        }
    }

    return Lists.newArrayList();
}