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:am.ik.categolj3.api.git.GitStore.java

Pair<Author, Author> getAuthor(Path path) {
    Path p = gitProperties.getBaseDir().toPath().relativize(path);
    try {/* www .  ja  v a2  s . c o m*/
        Iterable<RevCommit> commits = git.log().addPath(p.toString().replace("\\", "/")).call();
        RevCommit updated = Iterables.getFirst(commits, null);
        RevCommit created = Iterables.getLast(commits, updated);
        return new Pair<>(author(created), author(updated));
    } catch (GitAPIException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.googlecode.blaisemath.graph.modules.layout.StaticSpringLayout.java

/**
 * Add leaf nodes that are adjacent to the given positions.
 * @param og the graph/*from   w w  w .  j av  a 2  s  . co  m*/
 * @param pos current positions
 * @param distScale distance between noddes
 * @param <C> graph node type
 */
public static <C> void addLeafNodes(OptimizedGraph<C> og, Map<C, Point2D.Double> pos, double distScale) {
    double nomSz = distScale / 2;
    Set<C> leafs = og.getLeafNodes();
    int n = leafs.size();
    if (n > 0) {
        Rectangle2D bounds = Points.boundingBox(pos.values(), distScale);
        if (bounds == null) {
            // no points exist, so must be all pairs
            double sqSide = nomSz * Math.sqrt(n);
            Rectangle2D pairRegion = new Rectangle2D.Double(-sqSide, -sqSide, 2 * sqSide, 2 * sqSide);
            LinkedHashSet orderedLeafs = orderByAdjacency(leafs, og);
            addPointsToBox(orderedLeafs, pairRegion, pos, nomSz, true);
        } else {
            // add close to their neighboring point
            Set<C> cores = Sets.newHashSet();
            Set<C> pairs = Sets.newHashSet();
            for (C o : leafs) {
                C nbr = og.getNeighborOfLeaf(o);
                if (leafs.contains(nbr)) {
                    pairs.add(o);
                    pairs.add(nbr);
                } else {
                    cores.add(nbr);
                }
            }
            for (C o : cores) {
                Set<C> leaves = og.getLeavesAdjacentTo(o);
                Point2D.Double ctr = pos.get(o);
                double r = nomSz;
                double theta = Math.atan2(ctr.y, ctr.x);
                if (leaves.size() == 1) {
                    pos.put(Iterables.getFirst(leaves, null), new Point2D.Double(
                            ctr.getX() + r * Math.cos(theta), ctr.getY() + r * Math.sin(theta)));
                } else {
                    double th0 = theta - Math.PI / 3;
                    double dth = (2 * Math.PI / 3) / (leaves.size() - 1);
                    for (C l : leaves) {
                        pos.put(l, new Point2D.Double(ctr.getX() + r * Math.cos(th0),
                                ctr.getY() + r * Math.sin(th0)));
                        th0 += dth;
                    }
                }
            }

            // put the pairs to the right side
            double area = n * nomSz * nomSz;
            double ht = Math.min(bounds.getHeight(), 2 * Math.sqrt(area));
            double wid = area / ht;
            Rectangle2D pairRegion = new Rectangle2D.Double(bounds.getMaxX() + .1 * bounds.getWidth(),
                    bounds.getCenterY() - ht / 2, wid, ht);
            LinkedHashSet orderedPairs = orderByAdjacency(pairs, og);
            addPointsToBox(orderedPairs, pairRegion, pos, nomSz, true);
        }
    }
}

From source file:com.google.devtools.build.lib.skyframe.SkyframeLabelVisitor.java

private static Set<Label> getRootCausesOfCycles(Label labelToLoad, Iterable<CycleInfo> cycles) {
    ImmutableSet.Builder<Label> builder = ImmutableSet.builder();
    for (CycleInfo cycleInfo : cycles) {
        // The root cause of a cycle depends on the type of a cycle.

        SkyKey culprit = Iterables.getFirst(cycleInfo.getCycle(), null);
        if (culprit == null) {
            continue;
        }//from www  . ja  v a  2s  .co  m
        if (culprit.functionName().equals(SkyFunctions.TRANSITIVE_TARGET)) {
            // For a cycle between build targets, the root cause is the first element of the cycle.
            builder.add((Label) culprit.argument());
        } else {
            // For other types of cycles (e.g. file symlink cycles), the root cause is the furthest
            // target dependency that itself depended on the cycle.
            Label furthestTarget = labelToLoad;
            for (SkyKey skyKey : cycleInfo.getPathToCycle()) {
                if (skyKey.functionName().equals(SkyFunctions.TRANSITIVE_TARGET)) {
                    furthestTarget = (Label) skyKey.argument();
                } else {
                    break;
                }
            }
            builder.add(furthestTarget);
        }
    }
    return builder.build();
}

From source file:org.apache.beam.runners.spark.translation.SparkGlobalCombineFn.java

/**
 * Implement Spark's combOp function in:
 * <p>//from w w  w  .j  ava  2  s .c om
 * {@link org.apache.spark.api.java.JavaRDD#aggregate}.
 * </p>
 */
Iterable<WindowedValue<AccumT>> combOp(Iterable<WindowedValue<AccumT>> a1, Iterable<WindowedValue<AccumT>> a2) {

    // concatenate accumulators.
    Iterable<WindowedValue<AccumT>> accumulators = Iterables.concat(a1, a2);
    // if empty, return an empty accumulators iterable.
    if (!accumulators.iterator().hasNext()) {
        return Lists.newArrayList();
    }

    // sort accumulators, no need to explode since inputs were exploded.
    Iterable<WindowedValue<AccumT>> sortedAccumulators = sortByWindows(accumulators);

    @SuppressWarnings("unchecked")
    TimestampCombiner timestampCombiner = windowingStrategy.getTimestampCombiner();

    //--- accumulators iterator, by window order.
    final Iterator<WindowedValue<AccumT>> iterator = sortedAccumulators.iterator();

    // get the first accumulator and assign it to the current window's accumulators.
    WindowedValue<AccumT> currentValue = iterator.next();
    BoundedWindow currentWindow = Iterables.getFirst(currentValue.getWindows(), null);
    List<AccumT> currentWindowAccumulators = Lists.newArrayList();
    currentWindowAccumulators.add(currentValue.getValue());

    // keep track of the timestamps assigned by the TimestampCombiner,
    // in createCombiner we already merge the timestamps assigned
    // to individual elements, here we will just merge them.
    List<Instant> windowTimestamps = Lists.newArrayList();
    windowTimestamps.add(currentValue.getTimestamp());

    // accumulate the next windows, or output.
    List<WindowedValue<AccumT>> output = Lists.newArrayList();

    // if merging, merge overlapping windows, e.g. Sessions.
    final boolean merging = !windowingStrategy.getWindowFn().isNonMerging();

    while (iterator.hasNext()) {
        WindowedValue<AccumT> nextValue = iterator.next();
        BoundedWindow nextWindow = Iterables.getOnlyElement(nextValue.getWindows());

        boolean mergingAndIntersecting = merging
                && isIntersecting((IntervalWindow) currentWindow, (IntervalWindow) nextWindow);

        if (mergingAndIntersecting || nextWindow.equals(currentWindow)) {
            if (mergingAndIntersecting) {
                // merge intersecting windows.
                currentWindow = merge((IntervalWindow) currentWindow, (IntervalWindow) nextWindow);
            }
            // add to window accumulators.
            currentWindowAccumulators.add(nextValue.getValue());
            windowTimestamps.add(nextValue.getTimestamp());
        } else {
            // before moving to the next window,
            // add the current accumulation to the output and initialize the accumulation.

            // merge the timestamps of all accumulators to merge.
            Instant mergedTimestamp = timestampCombiner.merge(currentWindow, windowTimestamps);

            // merge accumulators.
            // transforming a KV<K, Iterable<AccumT>> into a KV<K, Iterable<AccumT>>.
            // for the (possibly merged) window.
            Iterable<AccumT> accumsToMerge = Iterables.unmodifiableIterable(currentWindowAccumulators);
            WindowedValue<Iterable<AccumT>> preMergeWindowedValue = WindowedValue.of(accumsToMerge,
                    mergedTimestamp, currentWindow, PaneInfo.NO_FIRING);
            // applying the actual combiner onto the accumulators.
            AccumT accumulated = combineFn.mergeAccumulators(accumsToMerge,
                    ctxtForInput(preMergeWindowedValue));
            WindowedValue<AccumT> postMergeWindowedValue = preMergeWindowedValue.withValue(accumulated);
            // emit the accumulated output.
            output.add(postMergeWindowedValue);

            // re-init accumulator, window and timestamps.
            currentWindowAccumulators.clear();
            currentWindowAccumulators.add(nextValue.getValue());
            currentWindow = nextWindow;
            windowTimestamps.clear();
            windowTimestamps.add(nextValue.getTimestamp());
        }
    }

    // merge the last chunk of accumulators.
    Instant mergedTimestamp = timestampCombiner.merge(currentWindow, windowTimestamps);
    Iterable<AccumT> accumsToMerge = Iterables.unmodifiableIterable(currentWindowAccumulators);
    WindowedValue<Iterable<AccumT>> preMergeWindowedValue = WindowedValue.of(accumsToMerge, mergedTimestamp,
            currentWindow, PaneInfo.NO_FIRING);
    AccumT accumulated = combineFn.mergeAccumulators(accumsToMerge, ctxtForInput(preMergeWindowedValue));
    WindowedValue<AccumT> postMergeWindowedValue = preMergeWindowedValue.withValue(accumulated);
    output.add(postMergeWindowedValue);

    return output;
}

From source file:com.google.gitiles.FakeHttpServletRequest.java

@Override
public String getHeader(String name) {
    return Iterables.getFirst(headers.get(name), null);
}

From source file:org.sonatype.nexus.repository.storage.AssetEntityAdapter.java

Asset findByProperty(final ODatabaseDocumentTx db, final String propName, final Object propValue,
        final Component component) {
    checkNotNull(propName);/*from w w w .  j a  v a 2  s. co  m*/
    checkNotNull(propValue);
    checkNotNull(component);

    Map<String, Object> parameters = ImmutableMap.of("bucket",
            bucketEntityAdapter.recordIdentity(component.bucketId()), "component",
            componentEntityAdapter.recordIdentity(component), "propValue", propValue);
    String query = String.format("select from %s where %s = :bucket and %s = :component and %s = :propValue",
            DB_CLASS, P_BUCKET, P_COMPONENT, propName);
    Iterable<ODocument> docs = db.command(new OCommandSQL(query)).execute(parameters);
    ODocument first = Iterables.getFirst(docs, null);
    return first != null ? readEntity(first) : null;
}

From source file:org.obm.push.mail.ICalendarConverter.java

@VisibleForTesting
String organizer(String organizer, List<Address> fromList) {
    Address from = Iterables.getFirst(fromList, null);
    if (from != null) {
        return Objects.firstNonNull(Strings.emptyToNull(organizer), from.getMail());
    }//from ww w.j  a va2  s.  c o m
    return organizer;
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClient.java

/**
 * Gets FieldMapping detail for a list of indices.
 *
 * @param indices get field mapppings for the provided indices
 * @return mapping of index name to FieldMapping
 *//* w w  w . j a va 2  s.  c  o  m*/
public Map<String, FieldMapping> getMappingByIndex(String[] indices) throws IOException {
    Map<String, FieldMapping> ret = new HashMap<>();
    String indicesCsv = Joiner.on(",").join(indices);
    Response response = lowLevelClient.performRequest("GET", "/" + indicesCsv + "/_mapping");
    if (response.getStatusLine().getStatusCode() == 200) {
        String responseStr = IOUtils.toString(response.getEntity().getContent());
        Map<String, Object> indexToMapping = JSONUtils.INSTANCE.load(responseStr, JSONUtils.MAP_SUPPLIER);
        for (Map.Entry<String, Object> index2Mapping : indexToMapping.entrySet()) {
            String index = index2Mapping.getKey();
            Map<String, Object> mappings = getInnerMap((Map<String, Object>) index2Mapping.getValue(),
                    "mappings");
            if (mappings.size() > 0) {
                Map.Entry<String, Object> docMap = Iterables.getFirst(mappings.entrySet(), null);
                if (docMap != null) {
                    Map<String, Object> fieldPropertiesMap = getInnerMap(
                            (Map<String, Object>) docMap.getValue(), "properties");
                    if (fieldPropertiesMap != null) {
                        FieldMapping mapping = new FieldMapping();
                        for (Map.Entry<String, Object> field2PropsKV : fieldPropertiesMap.entrySet()) {
                            if (field2PropsKV.getValue() != null) {
                                FieldProperties props = new FieldProperties(
                                        (Map<String, Object>) field2PropsKV.getValue());
                                mapping.put(field2PropsKV.getKey(), props);
                            }
                        }
                        ret.put(index, mapping);
                    }
                }
            }
        }
    }
    return ret;
}

From source file:com.google.security.zynamics.binnavi.Database.PostgreSQL.Loaders.PostgreSQLFunctionsLoader.java

/**
 * This function loads a {@link INaviFunction} from the database given the {@link INaviModule}
 * where it is associated to and the {@link IAddress} of the function.
 *
 * @param provider The {@link SQLProvider} to access the database with.
 * @param module The {@link INaviModule} in which the function is located.
 * @param address The {@link IAddress} of the function to load.
 *
 * @return A {@link INaviFunction} if found.
 *
 * @throws CouldntLoadDataException if the function information could not be loaded from the
 *         database.//from  w w  w .  java2s .  c o m
 */
public static INaviFunction loadFunction(final SQLProvider provider, final INaviModule module,
        final IAddress address) throws CouldntLoadDataException {
    checkArguments(provider, module);
    final String query = " SELECT * FROM load_function_information(?,?) ";

    try {
        final PreparedStatement statement = provider.getConnection().getConnection().prepareStatement(query);
        statement.setInt(1, module.getConfiguration().getId());
        statement.setObject(2, address.toBigInteger(), Types.BIGINT);
        final ResultSet resultSet = statement.executeQuery();
        return Iterables.getFirst(parseFunctionInformation(resultSet, provider, module), null);
    } catch (final SQLException exception) {
        throw new CouldntLoadDataException(exception);
    }
}

From source file:org.obm.service.contact.VCFtoContactConverter.java

private <T> T firstValueOrNull(List<T> values) {
    return Iterables.getFirst(values, null);
}