Example usage for com.google.common.collect Iterators getOnlyElement

List of usage examples for com.google.common.collect Iterators getOnlyElement

Introduction

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

Prototype

public static <T> T getOnlyElement(Iterator<T> iterator) 

Source Link

Document

Returns the single element contained in iterator .

Usage

From source file:grakn.core.graql.gremlin.NodesUtil.java

private static void buildDependenciesBetweenNodes(Set<Fragment> allFragments, Map<NodeId, Node> allNodes) {
    // build dependencies between nodes
    // TODO extract this out of the Node objects themselves, if we want to keep at all
    allFragments.forEach(fragment -> {
        if (fragment.end() == null && fragment.dependencies().isEmpty()) {
            // process fragments that have fixed cost
            Node start = allNodes.get(NodeId.of(NodeId.Type.VAR, fragment.start()));
            //fragments that should be done when a node has been visited
            start.getFragmentsWithoutDependency().add(fragment);
        }/*from  w  ww  . ja  va2s.com*/
        if (!fragment.dependencies().isEmpty()) {
            // process fragments that have ordering dependencies

            // it's either neq or value fragment
            Node start = allNodes.get(NodeId.of(NodeId.Type.VAR, fragment.start()));
            Node other = allNodes.get(
                    NodeId.of(NodeId.Type.VAR, Iterators.getOnlyElement(fragment.dependencies().iterator())));

            start.getFragmentsWithDependency().add(fragment);
            other.getDependants().add(fragment);

            // check whether it's value fragment
            if (fragment instanceof ValueFragment) {
                // as value fragment is not symmetric, we need to add it again
                other.getFragmentsWithDependency().add(fragment);
                start.getDependants().add(fragment);
            }
        }
    });
}

From source file:com.google.devtools.build.android.desugar.LambdaClassMaker.java

private Path findOnlyUnprocessed(String pathPrefix) throws IOException {
    // pathPrefix is an internal class name prefix containing '/', but paths obtained on Windows
    // will not contain '/' and searches will fail.  So, construct an absolute path from the given
    // string and use its string representation to find the file we need regardless of host
    // system's file system
    Path rootPathPrefix = rootDirectory.resolve(pathPrefix);
    final String rootPathPrefixStr = rootPathPrefix.toString();

    // TODO(bazel-team): This could be much nicer with lambdas
    try (Stream<Path> paths = Files.list(rootPathPrefix.getParent()).filter(new Predicate<Path>() {
        @Override/*from  www .  java 2  s .co  m*/
        public boolean test(Path path) {
            return path.toString().startsWith(rootPathPrefixStr) && !generatedClasses.containsKey(path);
        }
    })) {
        return Iterators.getOnlyElement(paths.iterator());
    }
}

From source file:com.kurtraschke.wsf.gtfsrealtime.services.TripResolutionService.java

public ActivatedTrip resolve(String departingTerminalId, long departureTime, String arrivingTerminalId) {
    ServiceDate initialServiceDate = new ServiceDate(new Date(departureTime * 1000));
    int maxStopTime = maxStopTime();
    int lookBackDays = (maxStopTime / 86400) + 1;

    AgencyAndId stopId = new AgencyAndId(_agencyId, departingTerminalId);
    AgencyAndId routeId = new AgencyAndId(_agencyId, departingTerminalId + arrivingTerminalId);

    Iterator<ActivatedTrip> activatedTrips = _dao.getAllStopTimes().stream()
            .filter(st -> st.getStop().getId().equals(stopId))
            .filter(st -> st.getTrip().getRoute().getId().equals(routeId)).flatMap(st -> {
                return Stream.iterate(initialServiceDate, ServiceDate::previous).limit(lookBackDays)
                        .filter(sd -> _csd.getServiceIdsForDate(sd).contains(st.getTrip().getServiceId()))
                        .filter(sd -> st.getDepartureTime() == (departureTime
                                - (sd.getAsCalendar(_agencyTimeZone).getTimeInMillis() / 1000)))
                        .map(sd -> new ActivatedTrip(st.getTrip(), sd));
            }).iterator();// ww  w .  j  a  va  2  s.c  o  m

    try {
        if (activatedTrips.hasNext()) {
            return Iterators.getOnlyElement(activatedTrips);
        }
        _log.warn("no trip found for resolve(departId=" + departingTerminalId + ", departureTime="
                + departureTime + ", arrivalId=" + arrivingTerminalId + ")");
        return null;
    } catch (NoSuchElementException | IllegalArgumentException ex) {
        _log.warn("Failed to resolve trip:", ex);
        return null;
    }
}

From source file:org.mitreid.multiparty.service.InMemoryResourceService.java

@Override
public Resource getById(final String rsId) {

    Multimap<String, Resource> filtered = Multimaps.filterValues(resources, new Predicate<Resource>() {

        @Override/*  w  w  w  .  j a v a  2  s  .  c o  m*/
        public boolean apply(Resource input) {
            if (input.getId().equals(rsId)) {
                return true;
            } else {
                return false;
            }
        }
    });

    if (filtered.size() == 1) {
        return Iterators.getOnlyElement(filtered.values().iterator());
    } else {
        return null;
    }

}

From source file:kn.uni.gis.dataimport.util.GeoUtil.java

public NineCutModel spatialRelation(CPolygon a, CPolygon b) {
    return Iterators.getOnlyElement(receiveGeos(
            select(relate(gFromT(a), gFromT(b)), intersects(boundary(gFromT(a)), boundary(gFromT(b)))),
            new GeoFactory<NineCutModel>() {
                @Override// w  ww  .  j  av  a  2 s. c  om
                public NineCutModel createGeo(ResultSet executeQuery) throws SQLException {
                    return NineCutModel.forDE9IM(executeQuery.getString(1), executeQuery.getBoolean(2));
                }
            }).iterator());
}

From source file:org.apache.druid.data.input.impl.StringInputRowParser.java

@Nullable
private InputRow parseMap(@Nullable Map<String, Object> theMap) {
    // If a header is present in the data (and with proper configurations), a null is returned
    if (theMap == null) {
        return null;
    }// ww  w .java 2  s.c o m
    return Iterators.getOnlyElement(mapParser.parseBatch(theMap).iterator());
}

From source file:org.mitreid.multiparty.service.InMemoryResourceService.java

@Override
public SharedResourceSet getSharedResourceSetForResource(final Resource res) {
    Multimap<String, Resource> filtered = Multimaps.filterEntries(resources,
            new Predicate<Entry<String, Resource>>() {

                @Override//from  ww  w.ja  v a 2  s  . co m
                public boolean apply(Entry<String, Resource> input) {
                    if (input.getValue().equals(res)) {
                        return true;
                    } else {
                        return false;
                    }
                }

            });

    String principalName = Iterators.getOnlyElement(filtered.entries().iterator()).getKey();

    return sharedResourceSets.get(principalName);
}

From source file:grakn.core.graql.gremlin.RelationTypeInference.java

private static Map<Variable, Type> getLabelVarTypeMap(TransactionOLTP tx, Set<Fragment> allFragments) {
    Map<Variable, Type> labelVarTypeMap = new HashMap<>();
    allFragments.stream().filter(LabelFragment.class::isInstance).forEach(fragment -> {
        // TODO: labels() should return ONE label instead of a set
        SchemaConcept schemaConcept = tx
                .getSchemaConcept(Iterators.getOnlyElement(((LabelFragment) fragment).labels().iterator()));
        if (schemaConcept != null && !schemaConcept.isRole() && !schemaConcept.isRule()) {
            labelVarTypeMap.put(fragment.start(), schemaConcept.asType());
        }//from  ww w.  ja  va  2 s .c  o m
    });
    return labelVarTypeMap;
}

From source file:grakn.core.graql.gremlin.TraversalPlanner.java

/**
 * Create a plan using Edmonds' algorithm with greedy approach to execute a single conjunction
 *
 * @param query the conjunction query to find a traversal plan
 * @return a semi-optimal traversal plan to execute the given conjunction
 */// w w  w. j  av a  2s.  c om
private static List<Fragment> planForConjunction(ConjunctionQuery query, TransactionOLTP tx) {
    // a query plan is an ordered list of fragments
    final List<Fragment> plan = new ArrayList<>();

    // flatten all the possible fragments from the conjunction query (these become edges in the query graph)
    final Set<Fragment> allFragments = query.getEquivalentFragmentSets().stream()
            .flatMap(EquivalentFragmentSet::stream).collect(Collectors.toSet());

    // if role players' types are known, we can infer the types of the relation, adding label & isa fragments
    Set<Fragment> inferredFragments = inferRelationTypes(tx, allFragments);
    allFragments.addAll(inferredFragments);

    // convert fragments into nodes - some fragments create virtual middle nodes to ensure the Janus edge is traversed
    ImmutableMap<NodeId, Node> queryGraphNodes = buildNodesWithDependencies(allFragments);

    // it's possible that some (or all) fragments are disconnected, e.g. $x isa person; $y isa dog;
    Collection<Set<Fragment>> connectedFragmentSets = getConnectedFragmentSets(allFragments);

    // build a query plan for each query subgraph separately
    for (Set<Fragment> connectedFragments : connectedFragmentSets) {
        // one of two cases - either we have a connected graph > 1 node, which is used to compute a MST, OR exactly 1 node
        Arborescence<Node> subgraphArborescence = computeArborescence(connectedFragments, queryGraphNodes, tx);
        if (subgraphArborescence != null) {
            // collect the mapping from directed edge back to fragments -- inverse operation of creating virtual middle nodes
            Map<Node, Map<Node, Fragment>> middleNodeFragmentMapping = virtualMiddleNodeToFragmentMapping(
                    connectedFragments, queryGraphNodes);
            List<Fragment> subplan = GreedyTreeTraversal.greedyTraversal(subgraphArborescence, queryGraphNodes,
                    middleNodeFragmentMapping);
            plan.addAll(subplan);
        } else {
            // find and include all the nodes not touched in the MST in the plan
            Set<Node> unhandledNodes = connectedFragments.stream()
                    .flatMap(fragment -> fragment.getNodes().stream())
                    .map(node -> queryGraphNodes.get(node.getNodeId())).collect(Collectors.toSet());
            if (unhandledNodes.size() != 1) {
                throw GraknServerException
                        .create("Query planner exception - expected one unhandled node, found "
                                + unhandledNodes.size());
            }
            plan.addAll(nodeVisitedDependenciesFragments(Iterators.getOnlyElement(unhandledNodes.iterator()),
                    queryGraphNodes));
        }
    }

    // this shouldn't be necessary, but we keep it just in case of an edge case that we haven't thought of
    List<Fragment> remainingFragments = fragmentsForUnvisitedNodes(queryGraphNodes, queryGraphNodes.values());
    if (remainingFragments.size() > 0) {
        LOG.warn("Expected all fragments to be handled, but found these: " + remainingFragments);
        plan.addAll(remainingFragments);
    }

    LOG.trace("Greedy Plan = {}", plan);
    return plan;
}

From source file:com.google.template.soy.parsepasses.SafetyInfo.java

/**
 * Merges the given SafetyInfo objects into a new SafetyInfo object. A data path is only safe in
 * the merged SafetyInfo if it is safe in all the input SafetyInfos.
 *///from  ww w . j  av  a  2 s  . co  m
public static SafetyInfo merge(Collection<SafetyInfo> safetyInfos) {

    // Special cases.
    if (safetyInfos.size() == 0) {
        return EMPTY_INSTANCE;
    }
    if (safetyInfos.size() == 1) {
        return clone(Iterators.getOnlyElement(safetyInfos.iterator()));
    }

    SafetyInfo mergedInfo = new SafetyInfo();

    // Determine the isSafe value on the mergedInfo.
    boolean mergedIsSafe = true;
    for (SafetyInfo safetyInfo : safetyInfos) {
        if (!safetyInfo.isSafe) {
            mergedIsSafe = false;
            break;
        }
    }
    mergedInfo.isSafe = mergedIsSafe;

    // Determine the merged keys at the current level.
    boolean isStarMergedKey = true;
    Set<String> nonstarMergedKeys = null;
    for (SafetyInfo safetyInfo : safetyInfos) {
        if (safetyInfo.starSubinfo != null) {
            continue; // doesn't subtract from merged keys
        }
        if (isStarMergedKey) {
            isStarMergedKey = false;
            nonstarMergedKeys = Sets.newHashSet(safetyInfo.nonstarSubinfos.keySet());
        } else {
            nonstarMergedKeys = Sets.intersection(nonstarMergedKeys, safetyInfo.nonstarSubinfos.keySet());
        }
    }

    // For each merged key, merge subinfos and put the new merged subinfo.
    if (isStarMergedKey) {
        List<SafetyInfo> subinfosToMerge = Lists.newArrayList();
        for (SafetyInfo safetyInfo : safetyInfos) {
            subinfosToMerge.add(safetyInfo.starSubinfo);
        }
        mergedInfo.starSubinfo = merge(subinfosToMerge);
    } else {
        for (String mergedKey : nonstarMergedKeys) {
            List<SafetyInfo> subinfosToMerge = Lists.newArrayList();
            for (SafetyInfo safetyInfo : safetyInfos) {
                // Important: Must use getSubinfo() and not nonstarSubinfos.get() to retrieve subinfo
                // because some safetyInfos may have '*' key at this level while others have non-'*' key.
                subinfosToMerge.add(safetyInfo.getSubinfo(mergedKey));
            }
            mergedInfo.putSubinfo(mergedKey, merge(subinfosToMerge));
        }
    }

    return mergedInfo;
}