Example usage for com.google.common.collect Multimap isEmpty

List of usage examples for com.google.common.collect Multimap isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Multimap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this multimap contains no key-value pairs.

Usage

From source file:com.zyxist.dirtyplayground.core.svc.ServiceComposer.java

public List<StartableService> compose(Set<StartableService> unorderedServices) {
    Multimap<Class<?>, StartableService> servicesReachableFrom = findServiceReachabilityGraph(
            unorderedServices);/*from w w  w  .ja  va 2 s .  c  o  m*/
    Deque<StartableService> toProcess = findRoots(unorderedServices);
    List<StartableService> output = new ArrayList<>(unorderedServices.size());

    while (!toProcess.isEmpty()) {
        StartableService svc = toProcess.poll();
        output.add(svc);

        findProvidedService(svc).ifPresent((provided) -> {
            Iterator<StartableService> reachableServices = servicesReachableFrom.get(provided).iterator();
            while (reachableServices.hasNext()) {
                StartableService reachable = reachableServices.next();
                reachableServices.remove();
                if (!servicesReachableFrom.containsValue(reachable)) {
                    toProcess.add(reachable);
                }
            }
        });
    }
    if (!servicesReachableFrom.isEmpty()) {
        throw new RuntimeException("Cycle detected in services!");
    }
    return output;
}

From source file:org.lealone.cluster.locator.TokenMetaData.java

/**
 * Update token map with a set of token/endpoint pairs in normal state.
 *
 * Prefer this whenever there are multiple pairs to update, as each update (whether a single or multiple)
 * is expensive (lealone-3831)./*  w ww.ja  va  2 s. co m*/
 *
 * @param endpointTokens
 */
public void updateNormalTokens(Multimap<InetAddress, Token> endpointTokens) {
    if (endpointTokens.isEmpty())
        return;

    lock.writeLock().lock();
    try {
        boolean shouldSortTokens = false;
        for (InetAddress endpoint : endpointTokens.keySet()) {
            Collection<Token> tokens = endpointTokens.get(endpoint);

            assert tokens != null && !tokens.isEmpty();

            bootstrapTokens.removeValue(endpoint);
            tokenToEndpointMap.removeValue(endpoint);
            topology.addEndpoint(endpoint);
            leavingEndpoints.remove(endpoint);
            removeFromMoving(endpoint); // also removing this endpoint from moving

            for (Token token : tokens) {
                InetAddress prev = tokenToEndpointMap.put(token, endpoint);
                if (!endpoint.equals(prev)) {
                    if (prev != null)
                        logger.warn("Token {} changing ownership from {} to {}", token, prev, endpoint);
                    shouldSortTokens = true;
                }
            }
        }

        if (shouldSortTokens)
            sortedTokens = sortTokens();
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.modeshape.graph.query.optimize.RewriteAsRangeCriteria.java

/**
 * {@inheritDoc}//w  w w. j a va  2s  . co m
 * 
 * @see org.modeshape.graph.query.optimize.OptimizerRule#execute(org.modeshape.graph.query.QueryContext,
 *      org.modeshape.graph.query.plan.PlanNode, java.util.LinkedList)
 */
public PlanNode execute(QueryContext context, PlanNode plan, LinkedList<OptimizerRule> ruleStack) {
    // Find all the access nodes ...
    boolean rewritten = false;
    boolean foundNoResults = false;
    for (PlanNode access : plan.findAllAtOrBelow(Type.ACCESS)) {
        // Look for select nodes below an ACCESS node that have a single Comparison constraint,
        // and accumulate them keyed by the dynamic operand ...
        Multimap<DynamicOperand, PlanNode> selectNodeByOperand = ArrayListMultimap.create();
        for (PlanNode select : access.findAllAtOrBelow(Type.SELECT)) {
            Constraint constraint = select.getProperty(Property.SELECT_CRITERIA, Constraint.class);
            // Look for Comparison constraints that use a range operator
            if (constraint instanceof Comparison) {
                Comparison comparison = (Comparison) constraint;
                if (comparison.operator().isRangeOperator()) {
                    selectNodeByOperand.put(comparison.operand1(), select);
                }
            }
        }

        if (!selectNodeByOperand.isEmpty()) {

            // Go through the constraints we've found ...
            for (DynamicOperand operand : selectNodeByOperand.keySet()) {
                Collection<PlanNode> nodes = selectNodeByOperand.get(operand);
                if (nodes.size() <= 1)
                    continue;

                // Extract the constraints from the nodes ...
                List<Comparison> rangeConstraints = new ArrayList<Comparison>(nodes.size());
                List<PlanNode> selectNodes = new ArrayList<PlanNode>(nodes.size());
                Set<SelectorName> selectors = null;
                for (PlanNode select : nodes) {
                    selectNodes.add(select);
                    Comparison constraint = select.getProperty(Property.SELECT_CRITERIA, Comparison.class);
                    rangeConstraints.add(constraint);
                    // Record the selector names (should all be the same) ...
                    if (selectors == null)
                        selectors = select.getSelectors();
                    else
                        assert selectors.equals(select.getSelectors());
                }

                // Attempt to merge the constraints ...
                Constraint merged = rewrite(context, rangeConstraints);
                if (merged == CONFLICTING_CONSTRAINT) {
                    // The ANDed constraints cancel each other out, so this whole access node will return no results ...
                    access.setProperty(Property.ACCESS_NO_RESULTS, Boolean.TRUE);
                    foundNoResults = true;
                    break; // don't do anything else under this access node
                }
                if (merged != null) {
                    // Add a SELECT node for the new merged constraint ...
                    PlanNode newSelect = new PlanNode(Type.SELECT);
                    newSelect.getSelectors().addAll(selectors);
                    newSelect.setProperty(Property.SELECT_CRITERIA, merged);

                    // And insert the SELECT node into the tree (just below the ACCESS, we'll rerun pushdown selects) ...
                    assert access.getChildCount() == 1;
                    access.getFirstChild().insertAsParent(newSelect);
                    rewritten = true;
                }

                // Remove any of the SELECT nodes that were not needed (this can happen if the constraints are not needed) ...
                Iterator<PlanNode> nodeIter = selectNodes.iterator();
                Iterator<Comparison> constraintIter = rangeConstraints.iterator();
                while (nodeIter.hasNext()) {
                    assert constraintIter.hasNext();
                    PlanNode node = nodeIter.next();
                    Comparison comparison = constraintIter.next();
                    if (comparison == null) {
                        // This comparison was rewritten, so remove the PlanNode ...
                        node.extractFromParent();
                        nodeIter.remove();
                    }
                }
                assert !constraintIter.hasNext();
            }
        }
    }

    if (rewritten) {
        // We mucked with the SELECT nodes, adding SELECT node for each rewritten constraint.
        // Rerun the rule that pushes SELECT nodes ...
        ruleStack.addFirst(PushSelectCriteria.INSTANCE);
    }
    if (foundNoResults) {
        ruleStack.addFirst(RemoveEmptyAccessNodes.INSTANCE);
    }

    return plan;
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.model.ErrorAnalyser.java

public Optional<String> computeComment(final List<Bundle> presentBundles, Throwable throwable) {
    if (packageAdmin == null) {
        return absent();
    }/*w  ww. jav a2  s  .  co  m*/

    List<String> problematicPackages = extractProblematicPackage(throwable);
    if (problematicPackages.isEmpty()) {
        return absent();
    }

    Set<String> presentBundlesSymbolicNames = Sets.newHashSet();
    for (Bundle presentBundle : presentBundles) {
        presentBundlesSymbolicNames.add(presentBundle.getName());
    }

    StringBuilder comment = new StringBuilder();
    for (String problematicPackage : problematicPackages) {
        comment.append("The problematic package '").append(problematicPackage)
                .append("' may originate in the following bundles:\n");
        ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(problematicPackage);
        if (ArrayUtils.isEmpty(exportedPackages)) {
            continue;
        }
        Multimap<org.osgi.framework.Bundle, org.osgi.framework.Bundle> exportersToImporters = HashMultimap
                .create();
        for (ExportedPackage exportedPackage : exportedPackages) {
            org.osgi.framework.Bundle exportingBundle = exportedPackage.getExportingBundle();
            if (!isPresent(exportingBundle)) {
                continue;
            }
            for (org.osgi.framework.Bundle importingBundle : exportedPackage.getImportingBundles()) {
                if (!isPresent(importingBundle)) {
                    continue;
                }
                if (presentBundlesSymbolicNames.contains(importingBundle.getSymbolicName())) {
                    exportersToImporters.put(exportingBundle, importingBundle);
                }
            }
        }
        if (exportersToImporters.isEmpty()) {
            continue;
        }

        for (Entry<org.osgi.framework.Bundle, Collection<org.osgi.framework.Bundle>> entry : exportersToImporters
                .asMap().entrySet()) {
            org.osgi.framework.Bundle exporter = entry.getKey();
            Collection<org.osgi.framework.Bundle> importers = entry.getValue();
            comment.append("  ").append(exporter.getSymbolicName()).append(' ').append(exporter.getVersion())
                    .append(", from which the following bundles present on the stack trace import it:\n");
            for (org.osgi.framework.Bundle importer : importers) {
                comment.append("    ").append(importer.getSymbolicName()).append(' ')
                        .append(importer.getVersion()).append('\n');
            }
        }
    }
    return Optional.of(comment.toString());
}

From source file:com.axelor.tools.i18n.I18nExtractor.java

public void extract(final Path base, boolean update, boolean withContext) {

    final Path srcPath = base.resolve("src/main");
    if (!Files.exists(srcPath)) {
        return;/*from  w w  w .java  2  s. c  om*/
    }

    log.info("extracting: {}", "translatable strings...");

    final Multimap<String, String> items = HashMultimap.create();

    final I18nTextVisitor visitor = new I18nTextVisitor(srcPath) {

        @Override
        protected void accept(I18nItem item) {
            if (StringUtils.isBlank(item.text))
                return;
            String location = null;
            if (item.file != null) {
                location = "" + srcPath.relativize(item.file) + ":" + item.line;
            }
            items.put(item.text.trim(), location);
        }
    };

    visitor.walk();

    // don't generate empty templates
    if (items.isEmpty()) {
        return;
    }

    List<String> keys = new ArrayList<>(items.keySet());
    List<String[]> values = new ArrayList<>();

    Collections.sort(keys);

    for (String key : keys) {
        String context = "";
        if (withContext) {
            List<String> locations = new ArrayList<>(items.get(key));
            Collections.sort(locations);
            context = Joiner.on('\n').join(locations).trim();
        }
        String[] line = { key, "", "", context };
        values.add(line);
    }

    try {
        update(base, values, update);
    } catch (IOException e) {
    }
}

From source file:org.brooth.jeta.apt.processors.MetaInjectProcessor.java

private void buildInjectMethod(TypeSpec.Builder builder, RoundContext context, TypeElement masterElement,
        ClassName masterClassName, Boolean staticMeta, ArrayList<Element> unhandledElements) {
    MethodSpec.Builder methodBuilder;/* w w w.  j ava 2  s  . c o m*/
    if (staticMeta) {
        methodBuilder = MethodSpec.methodBuilder("injectStatic").addParameter(metaScopeTypeName, "scope",
                Modifier.FINAL);

    } else {
        methodBuilder = MethodSpec.methodBuilder("inject")
                .addParameter(metaScopeTypeName, "scope", Modifier.FINAL)
                .addParameter(masterClassName, "master", Modifier.FINAL);
    }

    methodBuilder.addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(void.class);
    Multimap<String, StatementSpec> statements = ArrayListMultimap.create();
    for (TypeElement scopeElement : moduleScopes) {
        for (Element element : context.elements()) {
            if (element.getKind() == ElementKind.METHOD) {
                String methodStatement = null;
                if (staticMeta) {
                    if (element.getModifiers().contains(Modifier.STATIC))
                        methodStatement = String.format("%1$s.%2$s",
                                masterElement.getQualifiedName().toString(),
                                element.getSimpleName().toString());
                } else {
                    if (!element.getModifiers().contains(Modifier.STATIC))
                        methodStatement = String.format("master.%1$s", element.getSimpleName().toString());
                }
                if (methodStatement == null)
                    continue;

                ExecutableElement methodElement = (ExecutableElement) element;
                List<? extends VariableElement> paramElements = methodElement.getParameters();
                Multimap<String, StatementSpec> varStatements = HashMultimap.create();
                for (VariableElement paramElement : paramElements) {
                    StatementSpec statement = getResultStatement(scopeElement, paramElement.asType(), "",
                            "getInstance()");
                    if (statement != null) {
                        statement.element = paramElement;
                        varStatements.put(statement.providerScopeStr, statement);
                    }
                }

                if (!varStatements.isEmpty()) {
                    for (String varScope : varStatements.keySet()) {
                        Collection<StatementSpec> scopeVarStatements = varStatements.get(varScope);
                        List<String> paramFormats = new ArrayList<>(paramElements.size());
                        List<Object> paramArgs = new ArrayList<>(paramElements.size());
                        for (final VariableElement paramElement : paramElements) {
                            StatementSpec varStatement = Iterables.find(scopeVarStatements,
                                    new Predicate<StatementSpec>() {
                                        @Override
                                        public boolean apply(StatementSpec input) {
                                            return input.element == paramElement;
                                        }
                                    }, null);

                            if (varStatement != null) {
                                paramFormats.add(varStatement.format);
                                paramArgs.addAll(Arrays.asList(varStatement.args));

                            } else {
                                paramFormats.add("$L");
                                paramArgs.add("null");
                            }
                        }

                        StatementSpec methodStatementSpec = new StatementSpec(varScope,
                                (methodStatement + '(' + Joiner.on(", ").join(paramFormats) + ')'),
                                paramArgs.toArray(new Object[paramArgs.size()]));

                        if (!statements.containsEntry(varScope, methodStatementSpec)) {
                            statements.put(varScope, methodStatementSpec);
                            unhandledElements.remove(element);
                        }
                    }
                }

            } else if (element.getKind() == ElementKind.FIELD) {
                String fieldStatement = null;

                if (staticMeta) {
                    if (element.getModifiers().contains(Modifier.STATIC))
                        fieldStatement = String.format("%1$s.%2$s =\n",
                                masterElement.getQualifiedName().toString(),
                                element.getSimpleName().toString());
                } else {
                    if (!element.getModifiers().contains(Modifier.STATIC))
                        fieldStatement = String.format("master.%1$s = ", element.getSimpleName().toString());
                }
                if (fieldStatement == null)
                    continue;

                StatementSpec statement = getResultStatement(scopeElement, element.asType(), fieldStatement,
                        "getInstance()");
                if (statement != null) {
                    statement.element = element;
                    if (!statements.containsEntry(statement.providerScopeStr, statement)) {
                        statements.put(statement.providerScopeStr, statement);
                        unhandledElements.remove(element);
                    }
                }

            } else {
                throw new ProcessingException("Unhandled injection element type " + element.getKind());
            }
        }
    }

    if (!statements.isEmpty()) {
        List<String> scopes = new ArrayList<>(statements.keySet());
        Collections.sort(scopes, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return isAssignableScope(o1, o2) ? 1 : -1;
            }
        });

        for (String scopeElement : scopes) {
            ClassName scopeClassName = ClassName.bestGuess(scopeElement);
            ClassName scopeMetacodeClassName = ClassName.get(scopeClassName.packageName(),
                    MetacodeUtils.toSimpleMetacodeName(scopeClassName.toString()), "MetaScopeImpl");
            methodBuilder.beginControlFlow("if(scope.isAssignable($T.class))", scopeClassName)
                    .addStatement("final $T s = ($T) scope", scopeMetacodeClassName, scopeMetacodeClassName);

            for (StatementSpec statement : statements.get(scopeElement))
                methodBuilder.addStatement(statement.format, statement.args);

            methodBuilder.endControlFlow();
        }
    }

    builder.addMethod(methodBuilder.build());
}

From source file:org.summer.dsl.model.types.util.TypeArgumentContextProvider.java

protected Map<JvmTypeParameter, JvmTypeReference> normalizedCopy(Multimap<JvmTypeParameter, ResolveInfo> map) {
    if (map.isEmpty())
        return Collections.emptyMap();
    if (map.size() == 1) {
        Map.Entry<JvmTypeParameter, ResolveInfo> singleElement = Iterables.getOnlyElement(map.entries());
        ResolveInfo singleResolveInfo = singleElement.getValue();
        JvmTypeReference reference = wildcardAwareGetReference(singleResolveInfo);
        return Collections.singletonMap(singleElement.getKey(), reference);
    }//from  w w w .j  a v a  2  s .  co m
    Map<JvmTypeParameter, JvmTypeReference> result = createMapWithTweakedToString();
    for (JvmTypeParameter boundParameter : map.keySet()) {
        Collection<ResolveInfo> boundTo = map.get(boundParameter);
        if (boundTo.size() == 1) {
            ResolveInfo singleResolveInfo = Iterables.getOnlyElement(boundTo);
            JvmTypeReference reference = wildcardAwareGetReference(singleResolveInfo);
            result.put(boundParameter, reference);
        } else {
            List<ResolveInfo> boundToList = Lists.newArrayList(boundTo);
            List<JvmTypeReference> uppers = Lists.newArrayListWithCapacity(boundToList.size());
            List<ResolveInfo> lowers = Lists.newArrayListWithCapacity(boundToList.size());
            boolean done = false;
            int lowerIndex = Integer.MAX_VALUE;
            int upperIndex = Integer.MAX_VALUE;
            for (int i = 0; i < boundToList.size(); i++) {
                ResolveInfo info = boundToList.get(i);
                if (info.kind == ResolveInfoKind.EXACT) {
                    result.put(boundParameter, info.reference);
                    done = true;
                    break;
                } else if (info.kind == ResolveInfoKind.UPPER || info.kind == ResolveInfoKind.WC_UPPER) {
                    if (upperIndex == Integer.MAX_VALUE)
                        upperIndex = i;
                    if (!lowers.isEmpty() && upperIndex < lowerIndex) {
                        boolean conformant = true;
                        for (ResolveInfo lower : lowers) {
                            if (!getConformanceComputer().isConformant(info.reference, lower.reference)) {
                                conformant = false;
                                break;
                            }
                        }
                        if (conformant) {
                            uppers.add(info.reference);
                        }
                    } else {
                        uppers.add(info.reference);
                    }
                } else if (info.kind == ResolveInfoKind.LOWER || info.kind == ResolveInfoKind.WC_LOWER) {
                    if (lowerIndex == Integer.MAX_VALUE)
                        lowerIndex = i;
                    lowers.add(info);
                }
            }
            if (!done) {
                JvmTypeReference reference = null;
                if (!uppers.isEmpty() && upperIndex < lowerIndex) {
                    reference = conformanceComputer.getCommonSuperType(uppers);
                    if (uppers.size() == 1 && boundToList.get(upperIndex).kind == ResolveInfoKind.WC_UPPER) {
                        boolean useWildcard = true;
                        for (ResolveInfo lowerResolve : lowers) {
                            if (!conformanceComputer.isConformant(lowerResolve.reference, reference)) {
                                useWildcard = false;
                                break;
                            }
                        }
                        if (useWildcard) {
                            if (reference.eContainer() != null) {
                                JvmDelegateTypeReference delegate = typesFactory
                                        .createJvmDelegateTypeReference();
                                delegate.setDelegate(reference);
                                reference = delegate;
                            }
                            JvmWildcardTypeReference wildCard = typeReferences.wildCard();
                            JvmUpperBound upperBound = typesFactory.createJvmUpperBound();
                            wildCard.getConstraints().add(upperBound);
                            upperBound.setTypeReference(reference);
                            reference = wildCard;
                        }
                    }
                } else if (!lowers.isEmpty()) {
                    boolean lowerWithWildcard = false;
                    ResolveInfo bestResolvedLower = null;
                    for (ResolveInfo resolvedLower : lowers) {
                        lowerWithWildcard |= resolvedLower.kind == ResolveInfoKind.WC_LOWER;
                        if (bestResolvedLower == null) {
                            bestResolvedLower = resolvedLower;
                        } else {
                            TypeConformanceResult conformanceResult = conformanceComputer.isConformant(
                                    bestResolvedLower.reference, resolvedLower.reference,
                                    new TypeConformanceComputationArgument(false, false, true));
                            if (conformanceResult.isConformant() && conformanceResult.getKinds()
                                    .contains(TypeConformanceResult.Kind.SUBTYPE))
                                bestResolvedLower = resolvedLower;
                        }
                    }
                    if (bestResolvedLower != null) {
                        if (lowers.size() == 1 || lowerWithWildcard) {
                            if (bestResolvedLower.kind != ResolveInfoKind.WC_LOWER) {
                                if (!uppers.isEmpty()) {
                                    JvmTypeReference upper = conformanceComputer.getCommonSuperType(uppers);
                                    if (conformanceComputer.isConformant(bestResolvedLower.reference, upper))
                                        reference = upper;
                                    else
                                        reference = wildcardAwareGetReference(bestResolvedLower);
                                } else {
                                    reference = wildcardAwareGetReference(bestResolvedLower);
                                }
                            } else {
                                reference = wildcardAwareGetReference(bestResolvedLower);
                            }
                        } else {
                            reference = bestResolvedLower.reference;
                            if (!uppers.isEmpty()) {
                                JvmTypeReference upper = conformanceComputer.getCommonSuperType(uppers);
                                if (conformanceComputer.isConformant(reference, upper))
                                    reference = upper;
                            }
                        }
                    }
                }
                if (reference != null)
                    result.put(boundParameter, reference);
            }
        }
    }
    Map<JvmTypeParameter, JvmTypeReference> normalizedCopy = normalizedCopy(result);
    return normalizedCopy;
}

From source file:edu.buaa.satla.analysis.core.predicate.PredicatePrecision.java

/**
 * Create a new precision which contains all predicates of this precision
 * and a second one./*from  w w  w  . j  av  a2s.  co m*/
 */
public PredicatePrecision mergeWith(PredicatePrecision prec) {
    // create new set of global predicates
    Collection<AbstractionPredicate> newGlobalPredicates = Lists.newArrayList(getGlobalPredicates());
    newGlobalPredicates.addAll(prec.getGlobalPredicates());
    newGlobalPredicates = ImmutableSet.copyOf(newGlobalPredicates);

    // create new multimap of function-specific predicates
    Multimap<String, AbstractionPredicate> newFunctionPredicates = ArrayListMultimap
            .create(getFunctionPredicates());
    newFunctionPredicates.putAll(prec.getFunctionPredicates());

    if (!newGlobalPredicates.isEmpty()) {
        for (String function : newFunctionPredicates.keySet()) {
            newFunctionPredicates.putAll(function, newGlobalPredicates);
        }
    }
    newFunctionPredicates = ImmutableSetMultimap.copyOf(newFunctionPredicates);

    // create new multimap of location-specific predicates
    Multimap<CFANode, AbstractionPredicate> newLocalPredicates = ArrayListMultimap.create(getLocalPredicates());
    newLocalPredicates.putAll(prec.getLocalPredicates());

    if (!newGlobalPredicates.isEmpty() || !newFunctionPredicates.isEmpty()) {
        for (CFANode loc : newLocalPredicates.keySet()) {
            newLocalPredicates.putAll(loc, newGlobalPredicates);
            newLocalPredicates.putAll(loc, newFunctionPredicates.get(loc.getFunctionName()));
        }
    }

    // create new multimap of location-instance-specific predicates
    Multimap<Pair<CFANode, Integer>, AbstractionPredicate> newLocationInstanceSpecificPredicates = ArrayListMultimap
            .create(getLocationInstancePredicates());
    newLocationInstanceSpecificPredicates.putAll(prec.getLocationInstancePredicates());

    if (!newGlobalPredicates.isEmpty() || !newFunctionPredicates.isEmpty() || !newLocalPredicates.isEmpty()) {
        for (Pair<CFANode, Integer> key : newLocationInstanceSpecificPredicates.keySet()) {
            newLocationInstanceSpecificPredicates.putAll(key, newGlobalPredicates);
            newLocationInstanceSpecificPredicates.putAll(key,
                    newFunctionPredicates.get(key.getFirst().getFunctionName()));
            newLocationInstanceSpecificPredicates.putAll(key, newLocalPredicates.get(key.getFirst()));
        }
    }

    return new PredicatePrecision(newLocationInstanceSpecificPredicates, newLocalPredicates,
            newFunctionPredicates, newGlobalPredicates);
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.BlockStateService.java

private Map<BlockLocationKey, BestBlockStates> computeBlockStatesForObservation(Observation observation) {

    final Map<BlockLocationKey, BestBlockStates> results = Maps.newHashMap();

    Set<String> validRunIds = null;
    if (_requireRunMatchesForNullDSC) {
        validRunIds = Sets.newHashSet(Iterables.concat(observation.getBestFuzzyRunIds(),
                Collections.singleton(observation.getOpAssignedRunId())));
    }/*from w  w  w  . ja  v  a 2s .c o  m*/

    final NycRawLocationRecord record = observation.getRecord();
    final String vehicleAgencyId = record.getVehicleId().getAgencyId();

    final long time = observation.getTime();
    final Date timeFrom = new Date(time - _tripSearchTimeAfterLastStop);
    final Date timeTo = new Date(time + _tripSearchTimeBeforeFirstStop);

    final CoordinateBounds bounds = SphericalGeometryLibrary.bounds(record.getLatitude(), record.getLongitude(),
            _tripSearchRadius);
    final Coordinate obsPoint = new Coordinate(record.getLongitude(), record.getLatitude());
    final Envelope searchEnv = new Envelope(bounds.getMinLon(), bounds.getMaxLon(), bounds.getMinLat(),
            bounds.getMaxLat());

    @SuppressWarnings("unchecked")
    final List<Collection<LocationIndexedLine>> lineMatches = _index.query(searchEnv);
    final Multimap<BlockInstance, Double> instancesToDists = TreeMultimap
            .create(BlockInstanceComparator.INSTANCE, Ordering.natural());

    // lines under the current observed location
    for (final LocationIndexedLine line : Iterables.concat(lineMatches)) {
        final LinearLocation here = line.project(obsPoint);
        final Coordinate pointOnLine = line.extractPoint(here);
        final double dist = pointOnLine.distance(obsPoint);

        // filter out if too far away
        if (dist > _tripSearchRadius)
            continue;

        final Multimap<LocationIndexedLine, TripInfo> linesToTripInfoForVehicleAgencyId = _linesToTripInfoByAgencyId
                .get(vehicleAgencyId);
        if (linesToTripInfoForVehicleAgencyId == null || linesToTripInfoForVehicleAgencyId.isEmpty()) {
            continue;
        }

        // trips that follow the path under the current observed location
        for (final TripInfo tripInfo : linesToTripInfoForVehicleAgencyId.get(line)) {
            final Collection<BlockTripIndex> indices = tripInfo.getIndices();
            final Collection<BlockLayoverIndex> layoverIndices = tripInfo.getLayoverIndices();
            final Collection<FrequencyBlockTripIndex> frequencyIndices = tripInfo.getFrequencyIndices();

            final Coordinate startOfLine = line.extractPoint(line.getStartIndex());
            final double distTraveledOnLine = TurboButton.distance(pointOnLine.y, pointOnLine.x, startOfLine.y,
                    startOfLine.x);

            final double distanceAlongShape = tripInfo.getDistanceFrom() + distTraveledOnLine;

            List<BlockInstance> instances = _blockCalendarService.getActiveBlocksInTimeRange(indices,
                    layoverIndices, frequencyIndices, timeFrom.getTime(), timeTo.getTime());

            for (BlockInstance instance : instances) {
                for (BlockTripEntry blockTrip : instance.getBlock().getTrips()) {
                    /*
                     * XXX: This is still questionable, however,
                     * ScheduledBlockLocationServiceImpl.java appears to do something
                     * similar, where it assumes the block's distance-along can be
                     * related to the shape's (for the particular BlockTripEntry).
                     * (see ScheduledBlockLocationServiceImpl.getLocationAlongShape)
                     * 
                     * Anyway, what we're doing is using the blockTrip's
                     * getDistanceAlongBlock to find out what the distance-along the
                     * block is for the start of the shape, then we're using our
                     * computed distance along shape for the snapped point to find the
                     * total distanceAlongBlock.
                     */
                    final double distanceAlongBlock = blockTrip.getDistanceAlongBlock() + distanceAlongShape;

                    /*
                     * Here we make sure that the DSC and/or run-info matches
                     */
                    if (_requireDSCImpliedRoutes) {
                        if (!observation.getImpliedRouteCollections()
                                .contains(blockTrip.getTrip().getRouteCollection().getId()))
                            continue;
                    }

                    if (_requireRunMatchesForNullDSC) {
                        /*
                         * When there is no valid DSC only allow snapping
                         * to assigned or best fuzzy run.
                         */
                        if (!observation.hasValidDsc()) {
                            if (Sets.intersection(validRunIds,
                                    _runService.getRunIdsForTrip(blockTrip.getTrip())).isEmpty()) {
                                continue;
                            }
                        }
                    }

                    instancesToDists.put(instance, distanceAlongBlock);
                }
            }
        }
    }

    for (final Entry<BlockInstance, Collection<Double>> biEntry : instancesToDists.asMap().entrySet()) {
        final BlockInstance instance = biEntry.getKey();
        final int searchTimeFrom = (int) (timeFrom.getTime() - instance.getServiceDate()) / 1000;
        final int searchTimeTo = (int) (timeTo.getTime() - instance.getServiceDate()) / 1000;

        final Map<Map.Entry<BlockTripEntry, String>, Min<ScheduledBlockLocation>> tripToDists = Maps
                .newHashMap();

        /*
         * TODO could do some really easy improved traversing of these
         * distances...
         */
        for (final Double distanceAlongBlock : biEntry.getValue()) {
            final ScheduledBlockLocation location = _scheduledBlockLocationService
                    .getScheduledBlockLocationFromDistanceAlongBlock(instance.getBlock(), distanceAlongBlock);

            if (location == null)
                continue;

            /*
             * Don't consider opposite direction trips.
             */
            if (movedInOppositeDirection(observation, location))
                continue;

            /*
             * Should be increasing time for increasing distanceAlongBlock...
             */
            final int schedTime = location.getScheduledTime();

            if (schedTime > searchTimeTo)
                break;

            if (schedTime < searchTimeFrom)
                continue;

            final BlockTripEntry activeTrip = location.getActiveTrip();
            final Map.Entry<BlockTripEntry, String> tripDistEntry = Maps.immutableEntry(activeTrip,
                    activeTrip.getTrip().getDirectionId());

            Min<ScheduledBlockLocation> thisMin = tripToDists.get(tripDistEntry);
            if (thisMin == null) {
                thisMin = new Min<ScheduledBlockLocation>();
                tripToDists.put(tripDistEntry, thisMin);
            }

            final double dist = TurboButton.distance(observation.getLocation(), location.getLocation());
            thisMin.add(dist, location);
        }

        for (final Min<ScheduledBlockLocation> thisMin : tripToDists.values()) {
            final ScheduledBlockLocation location = thisMin.getMinElement();
            final BlockTripEntry activeTrip = location.getActiveTrip();
            final String dsc = _destinationSignCodeService
                    .getDestinationSignCodeForTripId(activeTrip.getTrip().getId());
            final RunTripEntry rte = _runService.getRunTripEntryForTripAndTime(activeTrip.getTrip(),
                    location.getScheduledTime());

            final BlockState state = new BlockState(instance, location, rte, dsc);
            final BlockLocationKey key = new BlockLocationKey(instance, 0, Double.POSITIVE_INFINITY);

            BestBlockStates currentStates = results.get(key);
            if (currentStates == null) {
                currentStates = new BestBlockStates(Sets.newHashSet(state));
                results.put(key, currentStates);
            } else {
                currentStates.getAllStates().add(state);
            }
        }
    }

    return results;
}

From source file:com.github.naios.wide.framework.internal.storage.server.builder.SQLScope.java

private void buildUpdates(final StringBuilder builder,
        final Multimap<ServerStorageStructure, SQLUpdateInfo> multimap) {
    final SQLMaker sqlMaker = new SQLMaker(sqlBuilder, sqlBuilder.getUpdateConfig());

    // TODO Group updates by key or updates
    final Multimap<String /*changes*/, ServerStorageStructure> changesPerStructure = HashMultimap.create();

    // Build Changeset (updates without key)
    for (final Entry<ServerStorageStructure, Collection<SQLUpdateInfo>> info : multimap.asMap().entrySet())
        changesPerStructure.put(sqlMaker.createUpdateFields(info.getKey(), info.getValue()), info.getKey());

    for (final Entry<String, Collection<ServerStorageStructure>> change : changesPerStructure.asMap()
            .entrySet()) {/*from w  ww . j  ava2 s. co m*/
        final String tableName = Iterables.get(change.getValue(), 0).getOwner().getTableName();

        final String keyPart = sqlMaker.createKeyPart(change.getValue());

        builder.append(SQLMaker.createUpdateQuery(tableName, change.getKey(), keyPart));
    }

    if (!multimap.isEmpty())
        builder.append(SQLMaker.NEWLINE);
}