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:org.eclipse.smarthome.core.thing.firmware.FirmwareRegistry.java

/**
 * Returns the latest firmware for the given thing type UID and locale.
 *
 * @param thingTypeUID the thing type UID (must not be null)
 * @param locale the locale to be used (if null then the locale provided by the {@link LocaleProvider} is used)
 *
 * @return the corresponding latest firmware or null if no firmware was found
 *
 * @throws NullPointerException if given thing type UID is null
 *///from  w  ww. ja  va2  s  .  c  om
public Firmware getLatestFirmware(ThingTypeUID thingTypeUID, Locale locale) {
    Locale loc = locale != null ? locale : localeProvider.getLocale();
    return Iterables.getFirst(getFirmwares((thingTypeUID), loc), null);
}

From source file:org.kitesdk.tools.CopyTask.java

public PipelineResult run() throws IOException {
    boolean runInParallel = true;
    if (isLocal(from.getDataset()) || isLocal(to.getDataset())) {
        runInParallel = false;//ww w .jav  a2s .  com
    }

    if (runInParallel) {
        TaskUtil.configure(getConf()).addJarPathForClass(HiveConf.class)
                .addJarForClass(AvroKeyInputFormat.class);

        Pipeline pipeline = new MRPipeline(getClass(), getConf());

        // TODO: add transforms
        PCollection<E> collection = pipeline.read(CrunchDatasets.asSource(from, entityClass));

        if (compact) {
            collection = partition(collection, to.getDataset().getDescriptor(), numWriters);
        }

        pipeline.write(collection, CrunchDatasets.asTarget(to));

        PipelineResult result = pipeline.done();

        StageResult sr = Iterables.getFirst(result.getStageResults(), null);
        if (sr != null && MAP_INPUT_RECORDS != null) {
            this.count = sr.getCounterValue(MAP_INPUT_RECORDS);
        }

        return result;

    } else {
        Pipeline pipeline = MemPipeline.getInstance();

        // TODO: add transforms
        PCollection<E> collection = pipeline.read(CrunchDatasets.asSource(from, entityClass));

        boolean threw = true;
        DatasetWriter<E> writer = null;
        try {
            writer = to.newWriter();

            for (E entity : collection.materialize()) {
                writer.write(entity);
                count += 1;
            }

            threw = false;

        } finally {
            Closeables.close(writer, threw);
        }

        return pipeline.done();
    }
}

From source file:com.google.idea.blaze.base.wizard2.ui.BlazeSelectOptionControl.java

BlazeSelectOptionControl(BlazeNewProjectBuilder builder, Collection<T> options) {
    if (options == null) {
        LOG.error("No options on select screen '" + getTitle() + "'");
    }// w w  w.ja  v a 2  s .  c  o m

    this.userSettings = builder.getUserSettings();

    JPanel canvas = new JPanel(new VerticalLayout(4));

    Dimension minSize = ProjectViewUi.getMinimumSize();
    canvas.setPreferredSize(minSize);

    titleLabel = new JLabel(getTitle());
    canvas.add(titleLabel);
    canvas.add(new JSeparator());

    JPanel content = new JPanel(new VerticalLayout(12));
    content.setBorder(new EmptyBorder(20, 100, 0, 0));
    canvas.add(content);

    ButtonGroup buttonGroup = new ButtonGroup();
    Collection<OptionUiEntry<T>> optionUiEntryList = Lists.newArrayList();
    for (T option : options) {
        JPanel vertical = new JPanel(new VerticalLayout(10));
        JRadioButton radioButton = new JRadioButton();
        radioButton.setText(option.getOptionText());
        vertical.add(radioButton);

        JComponent optionComponent = option.getUiComponent();
        if (optionComponent != null) {
            JPanel horizontal = new JPanel(new HorizontalLayout(0));
            horizontal.setBorder(new EmptyBorder(0, 25, 0, 0));
            horizontal.add(optionComponent);
            vertical.add(horizontal);

            option.optionDeselected();
            radioButton.addItemListener(itemEvent -> {
                if (radioButton.isSelected()) {
                    option.optionSelected();
                } else {
                    option.optionDeselected();
                }
            });
        }

        content.add(vertical);
        buttonGroup.add(radioButton);
        optionUiEntryList.add(new OptionUiEntry<>(option, radioButton));
    }

    OptionUiEntry selected = null;
    String previouslyChosenOption = userSettings.get(getOptionKey(), null);
    if (previouslyChosenOption != null) {
        for (OptionUiEntry<T> entry : optionUiEntryList) {
            if (entry.option.getOptionName().equals(previouslyChosenOption)) {
                selected = entry;
                break;
            }
        }
    }
    if (selected == null) {
        selected = Iterables.getFirst(optionUiEntryList, null);
    }
    if (selected != null) {
        selected.radioButton.setSelected(true);
    }

    this.canvas = canvas;
    this.optionUiEntryList = optionUiEntryList;
}

From source file:com.android.tools.idea.npw.project.AndroidProjectPaths.java

private void init(@NotNull SourceProvider sourceProvider) {
    mySrcDirectory = Iterables.getFirst(sourceProvider.getJavaDirectories(), null);

    Collection<File> resDirectories = sourceProvider.getResDirectories();
    if (!resDirectories.isEmpty()) {
        myResDirectory = resDirectories.iterator().next();
    }//from w w w . jav  a  2 s .co  m

    Collection<File> aidlDirectories = sourceProvider.getAidlDirectories();
    if (!aidlDirectories.isEmpty()) {
        myAidlDirectory = aidlDirectories.iterator().next();
    }

    myManifestDirectory = sourceProvider.getManifestFile().getParentFile();
}

From source file:org.sosy_lab.cpachecker.cpa.andersen.AndersenTransferRelation.java

@Override
public Collection<AbstractState> getAbstractSuccessorsForEdge(AbstractState pElement, Precision pPrecision,
        CFAEdge pCfaEdge) throws CPATransferException {

    AbstractState successor = null;/* ww  w .j  a v  a2s . co m*/
    AndersenState andersenState = (AndersenState) pElement;

    // check the type of the edge
    switch (pCfaEdge.getEdgeType()) {

    // if edge is a statement edge, e.g. a = b + c
    case StatementEdge:
        CStatementEdge statementEdge = (CStatementEdge) pCfaEdge;
        successor = handleStatement(andersenState, statementEdge.getStatement(), pCfaEdge);
        break;

    // edge is a declaration edge, e.g. int a;
    case DeclarationEdge:
        CDeclarationEdge declarationEdge = (CDeclarationEdge) pCfaEdge;
        successor = handleDeclaration(andersenState, declarationEdge);
        break;

    // this is an assumption, e.g. if (a == b)
    case AssumeEdge:
        successor = andersenState;
        break;

    case BlankEdge:
        successor = andersenState;
        break;
    case MultiEdge:
        successor = andersenState;
        Iterator<CFAEdge> edgeIterator = ((MultiEdge) pCfaEdge).iterator();
        while (pElement != null && edgeIterator.hasNext()) {
            successor = Iterables
                    .getFirst(getAbstractSuccessorsForEdge(successor, pPrecision, edgeIterator.next()), null);
        }
        break;

    case CallToReturnEdge:
    case FunctionCallEdge:
    case ReturnStatementEdge:
    case FunctionReturnEdge:
    default:
        printWarning(pCfaEdge);
    }

    if (successor == null) {
        return Collections.emptySet();
    } else {
        return Collections.singleton(successor);
    }
}

From source file:com.medvision360.medrecord.spi.tck.LocatableStoreTCKTestBase.java

public void testEHRSupport() throws Exception {
    Iterable<HierObjectID> hierObjectIDs;
    EHR EHR = makeEHR();/*  ww  w. j a  v a 2s  .  co  m*/

    try {
        store.list(EHR);
        fail("Should not allow listing non-existent EHR");
    } catch (NotFoundException e) {
    }

    HierObjectID uid = new HierObjectID(makeUUID());
    Locatable orig = makeLocatable(uid);

    Locatable inserted = store.insert(EHR, orig);
    assertEqualish(orig, inserted);

    hierObjectIDs = store.list(EHR);
    assertEquals(1, Iterables.size(hierObjectIDs));
    assertEquals(inserted.getUid(), Iterables.getFirst(hierObjectIDs, null));

    hierObjectIDs = store.list(EHR, "COMPOSITION");
    assertEquals(1, Iterables.size(hierObjectIDs));

    hierObjectIDs = store.list(EHR, "PERSON");
    assertEquals(0, Iterables.size(hierObjectIDs));
}

From source file:com.cloudbees.clickstack.domain.metadata.Metadata.java

/**
 * @param type/* w w  w. ja v  a 2s.c o m*/
 * @return
 * @throws IllegalStateException more than 1 {@link com.cloudbees.clickstack.domain.metadata.Resource} matching given {@type found}
 */
@Nullable
public Resource getResourceByType(@Nullable final String type) throws IllegalStateException {

    Collection<Resource> matchingResources = getResourcesByType(type);

    Preconditions.checkState(matchingResources.size() <= 1, "More than 1 resource with type='%s': %s", type,
            matchingResources);

    return Iterables.getFirst(matchingResources, null);
}

From source file:tiger.TigerDaggerGeneratorProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    messager.printMessage(Kind.NOTE, String.format("%s: process()", TAG));
    if (done) {//from w  w w  . j  av a2s.com
        return false;
    }

    Set<TypeElement> components = new HashSet<>(Collections2
            .transform(env.getElementsAnnotatedWith(Component.class), new Function<Element, TypeElement>() {
                @Override
                public TypeElement apply(Element from) {
                    return (TypeElement) from;
                }
            }));
    verifyComponents(components);

    coreInjectorPackage = getCoreInjectorPackage(
            Preconditions.checkNotNull(Iterables.getFirst(components, null)));

    coreInjectorTree = getCoreInjectorTree(components);
    if (coreInjectorTree.isEmpty()) {
        rootComponentInfo = new ComponentInfo(getScopeForComponent(Iterables.getOnlyElement(components)));
    }
    //    messager.printMessage(Kind.NOTE, String.format("%s components: %s", TAG, components));
    //    messager.printMessage(Kind.NOTE, String.format("%s componentTree: %s", TAG, coreInjectorTree));
    //    messager.printMessage(Kind.NOTE, String.format("%s scopeSizer: %s", TAG, scopeSizer));
    scopeSizer = new TreeScopeSizer(coreInjectorTree, rootComponentInfo);
    //    messager.printMessage(Kind.NOTE, String.format("scopeSizer: %s", scopeSizer));
    scopedModules = HashMultimap.create();
    unscopedModules = new HashSet<>();
    getModulesInComponents(components, scopedModules, unscopedModules);
    for (ComponentInfo componentInfo : scopedModules.keySet()) {
        scopedPassedModules.putAll(componentInfo,
                Utils.getNonNullaryCtorOnes(scopedModules.get(componentInfo)));
    }
    unscopedPassedModules.addAll(Utils.getNonNullaryCtorOnes(unscopedModules));

    Set<TypeElement> allModules = Sets.newHashSet(scopedModules.values());
    allModules.addAll(unscopedModules);
    NewDependencyCollector dependencyCollector = new NewDependencyCollector(processingEnv);
    Collection<NewDependencyInfo> dependencyInfos = dependencyCollector.collect(allModules, components,
            allRecoverableErrors);
    //    messager.printMessage(Kind.NOTE,
    //        String.format("TigerDaggerGeneratorProcessor.process(). all modules: %s", allModules));
    //    messager.printMessage(Kind.NOTE, String.format(
    //        "TigerDaggerGeneratorProcessor.process(). all dependencyInfos: %s", dependencyInfos));

    Set<NewBindingKey> requiredKeys = dependencyCollector.getRequiredKeys(components, dependencyInfos);

    NewScopeCalculator newScopeCalculator = new NewScopeCalculator(scopeSizer, dependencyInfos, requiredKeys,
            processingEnv);
    allRecoverableErrors.addAll(newScopeCalculator.initialize());
    newInjectorGenerator = new NewInjectorGenerator(
            NewDependencyCollector.collectionToMultimap(dependencyInfos), newScopeCalculator, scopedModules,
            unscopedModules, getComponentToScopeMap(components), coreInjectorTree, rootComponentInfo,
            coreInjectorPackage, "Tiger", "Injector", processingEnv);
    newInjectorGenerator.generate();

    generateWrapperComponents(components);

    if (allRecoverableErrors.isEmpty()) {
        done = true;
    } else if (env.processingOver()) {
        for (String error : allRecoverableErrors) {
            messager.printMessage(Kind.ERROR, error);
        }
    }

    return false;
}

From source file:net.nifheim.beelzebu.coins.bukkit.utils.bungee.PluginMessage.java

public void sendToBungeeCord(String channel, String message) {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF(channel);/*  ww  w  .  j av a  2 s  . co m*/
    out.writeUTF(message);
    Player p = Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
    if (p != null) {
        p.sendPluginMessage(Main.getInstance(), "Coins", out.toByteArray());
    }
}

From source file:com.continuuity.weave.internal.kafka.client.KafkaBrokerCache.java

private TopicBroker pickRandomBroker(String topic) {
    Map.Entry<String, InetSocketAddress> entry = Iterables.getFirst(brokers.entrySet(), null);
    if (entry == null) {
        return null;
    }//  w w  w .  ja  v  a  2 s. co  m
    InetSocketAddress address = entry.getValue();
    return new TopicBroker(topic, address, 0);
}