Example usage for com.google.common.collect Maps immutableEntry

List of usage examples for com.google.common.collect Maps immutableEntry

Introduction

In this page you can find the example usage for com.google.common.collect Maps immutableEntry.

Prototype

@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value) 

Source Link

Document

Returns an immutable map entry with the specified key and value.

Usage

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Traverse model object graph to determine steps for the proposed operation.
 * @param session the Hibernate session to use for HQL queries
 * @param objects the model objects to process
 * @param include if the given model objects are to be included (instead of just deleted)
 * @param applyRules if the given model objects should have the policy rules applied to them
 * @return the model objects included in the operation, and the deleted objects
 * @throws GraphException if the model objects were not as expected
 *///from  w  ww.  j  av a  2s.  c o m
public Entry<SetMultimap<String, Long>, SetMultimap<String, Long>> planOperation(Session session,
        SetMultimap<String, Long> objects, boolean include, boolean applyRules) throws GraphException {
    if (progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation already planned");
    }
    final Set<CI> targetSet = include ? planning.included : planning.deleted;
    /* note the object instances for processing */
    targetSet.addAll(objectsToCIs(session, objects));
    if (applyRules) {
        /* actually do the planning of the operation */
        planning.toProcess.addAll(targetSet);
        planOperation(session);
    } else {
        /* act as if the target objects have no links and no rules match them */
        for (final CI targetObject : targetSet) {
            planning.blockedBy.put(targetObject, new HashSet<CI>());
        }
    }
    progress.add(Milestone.PLANNED);
    /* report which objects are to be included in the operation or deleted so that it can proceed */
    final SetMultimap<String, Long> included = HashMultimap.create();
    for (final CI includedObject : planning.included) {
        included.put(includedObject.className, includedObject.id);
    }
    final SetMultimap<String, Long> deleted = HashMultimap.create();
    for (final CI deletedObject : planning.deleted) {
        deleted.put(deletedObject.className, deletedObject.id);
    }
    return Maps.immutableEntry(included, deleted);
}

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

private Map.Entry<BlockSampleType, BlockStateObservation> sampleEdgeFromProposal(
        BlockStateObservation parentBlockStateObs, BlockStateObservation proposalEdge, Observation obs,
        EVehiclePhase parentPhase, boolean vehicleNotMoved) {
    Map.Entry<BlockSampleType, BlockStateObservation> newEdge;
    if (proposalEdge != null) {
        if (parentBlockStateObs != null) {
            /*//from  w ww. j  a v a 2s .co m
             * When a state is transitioning we need to consider whether the
             * proposal edge is snapped or not, since that leads to different
             * sampling procedures. Also, we propagate non-snapped states
             * differently.
             */
            final double currentScheduleDev = BlockStateObservation.computeScheduleDeviation(obs,
                    parentBlockStateObs.getBlockState());
            final boolean runChanged = hasRunChanged(parentBlockStateObs, proposalEdge);

            if (proposalEdge.isSnapped()) {
                newEdge = Maps.immutableEntry(BlockSampleType.NOT_SAMPLED, proposalEdge);
            } else if (runChanged) {
                newEdge = Maps.immutableEntry(BlockSampleType.SCHEDULE_STATE_SAMPLE, _blockStateSamplingStrategy
                        .samplePriorScheduleState(proposalEdge.getBlockState().getBlockInstance(), obs));
            } else {
                /*
                 * When our previous journey state was deadhead-before we don't want
                 * to "jump the gun" and expect it to be at the start of the first
                 * trip and moving along, so we wait for a snapped location to appear.
                 */
                if (EVehiclePhase.AT_BASE == parentPhase) {
                    newEdge = Maps.immutableEntry(BlockSampleType.NOT_SAMPLED, parentBlockStateObs);
                } else if (EVehiclePhase.isActiveDuringBlock(parentPhase)) {
                    newEdge = Maps.immutableEntry(BlockSampleType.EDGE_MOVEMENT_SAMPLE,
                            _blockStateSamplingStrategy.sampleTransitionDistanceState(parentBlockStateObs, obs,
                                    vehicleNotMoved, parentPhase));
                } else if (EVehiclePhase.isActiveBeforeBlock(parentPhase)
                        && FastMath.abs(currentScheduleDev) > 0.0) {
                    /*
                     * Continue sampling mid-trip joins for this block...
                     */
                    newEdge = Maps.immutableEntry(BlockSampleType.SCHEDULE_STATE_SAMPLE,
                            _blockStateSamplingStrategy.samplePriorScheduleState(
                                    parentBlockStateObs.getBlockState().getBlockInstance(), obs));
                } else {
                    newEdge = Maps.immutableEntry(BlockSampleType.NOT_SAMPLED, parentBlockStateObs);
                }
            }
        } else {
            if (proposalEdge.isSnapped()) {
                newEdge = Maps.immutableEntry(BlockSampleType.NOT_SAMPLED, proposalEdge);
            } else {
                newEdge = Maps.immutableEntry(BlockSampleType.SCHEDULE_STATE_SAMPLE, _blockStateSamplingStrategy
                        .samplePriorScheduleState(proposalEdge.getBlockState().getBlockInstance(), obs));
            }
        }
    } else {
        newEdge = Maps.immutableEntry(BlockSampleType.NOT_SAMPLED, null);
    }

    return newEdge;
}

From source file:org.jooby.pac4j.Auth.java

/**
 * Protect one or more urls with an {@link Authorizer}. For example:
 * <pre>/*from  ww w  . j  av  a  2s  .  com*/
 * {
 *   use(new Auth()
 *     .form("*")
 *     .authorizer("admin", "/admin/**", MyAuthorizer.class)
 *     );
 * }
 * </pre>
 * <p>
 * Previous example will protect any url with form authentication and require and admin role for
 * <code>/admin/</code> or subpath of it.
 * </p>
 *
 * @param name Authorizer name.
 * @param pattern URL pattern to protected.
 * @param authorizer Authorizer to apply.
 */
private void authorizer(final Object authorizer, final String name, final String pattern) {
    requireNonNull(name, "An authorizer's name is required.");
    requireNonNull(pattern, "An authorizer's pattern is required.");
    requireNonNull(authorizer, "An authorizer is required.");
    authorizers.put(pattern, Maps.immutableEntry(name, authorizer));
}

From source file:org.apache.tephra.hbase.txprune.DataJanitorState.java

private Map.Entry<Long, byte[]> getTimeRegion(byte[] key) {
    int offset = REGION_TIME_KEY_PREFIX.length;
    long time = getInvertedTime(Bytes.toLong(key, offset));
    offset += Bytes.SIZEOF_LONG;/*w w w .j  ava  2s. com*/
    byte[] regionName = Bytes.copy(key, offset, key.length - offset);
    return Maps.immutableEntry(time, regionName);
}

From source file:ome.services.graphs.GraphPathBean.java

/**
 * Get what kind of property a specific class property is.
 * @param className the name of a class//ww w  . ja v a2  s.  c  o m
 * @param propertyName the name of a property declared, not just inherited, by that class
 * @return the kind of property it is
 */
public PropertyKind getPropertyKind(String className, String propertyName) {
    return propertyKinds.get(Maps.immutableEntry(className, propertyName));
}

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  ww w.j a  v  a 2 s. c om

    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.hippo.leveldb.impl.VersionSet.java

private Compaction setupOtherInputs(int level, List<FileMetaData> levelInputs) {
    Entry<InternalKey, InternalKey> range = getRange(levelInputs);
    InternalKey smallest = range.getKey();
    InternalKey largest = range.getValue();

    List<FileMetaData> levelUpInputs = getOverlappingInputs(level + 1, smallest, largest);

    // Get entire range covered by compaction
    range = getRange(levelInputs, levelUpInputs);
    InternalKey allStart = range.getKey();
    InternalKey allLimit = range.getValue();

    // See if we can grow the number of inputs in "level" without
    // changing the number of "level+1" files we pick up.
    if (!levelUpInputs.isEmpty()) {

        List<FileMetaData> expanded0 = getOverlappingInputs(level, allStart, allLimit);

        if (expanded0.size() > levelInputs.size()) {
            range = getRange(expanded0);
            InternalKey newStart = range.getKey();
            InternalKey newLimit = range.getValue();

            List<FileMetaData> expanded1 = getOverlappingInputs(level + 1, newStart, newLimit);
            if (expanded1.size() == levelUpInputs.size()) {
                //              Log(options_->info_log,
                //                  "Expanding@%d %d+%d to %d+%d\n",
                //                  level,
                //                  int(c->inputs_[0].size()),
                //                  int(c->inputs_[1].size()),
                //                  int(expanded0.size()),
                //                  int(expanded1.size()));
                smallest = newStart;//  ww  w.  j  a v a  2 s .c om
                largest = newLimit;
                levelInputs = expanded0;
                levelUpInputs = expanded1;

                range = getRange(levelInputs, levelUpInputs);
                allStart = range.getKey();
                allLimit = range.getValue();

            }
        }
    }

    // Compute the set of grandparent files that overlap this compaction
    // (parent == level+1; grandparent == level+2)
    List<FileMetaData> grandparents = null;
    if (level + 2 < NUM_LEVELS) {
        grandparents = getOverlappingInputs(level + 2, allStart, allLimit);
    }

    //        if (false) {
    //            Log(options_ - > info_log, "Compacting %d '%s' .. '%s'",
    //                    level,
    //                    EscapeString(smallest.Encode()).c_str(),
    //                    EscapeString(largest.Encode()).c_str());
    //        }

    Compaction compaction = new Compaction(current, level, levelInputs, levelUpInputs, grandparents)
            .setKeyRange(Maps.immutableEntry(smallest, largest));

    // Update the place where we will do the next compaction for this level.
    // We update this immediately instead of waiting for the VersionEdit
    // to be applied so that if the compaction fails, we will try a different
    // key range next time.
    compactPointers.put(level, largest);
    compaction.getEdit().setCompactPointer(level, largest);

    return compaction;
}

From source file:ome.services.graphs.GraphPathBean.java

/**
 * Find if the given property can be accessed.
 * @param className the name of a class//from  w w  w  .  j  a  va2s  .  c  o m
 * @param propertyName the name of a property declared, not just inherited, by that class
 * @return if the property can be accessed
 */
public boolean isPropertyAccessible(String className, String propertyName) {
    return accessibleProperties.contains(Maps.immutableEntry(className, propertyName));
}

From source file:org.renyan.leveldb.impl.VersionSet.java

private Entry<InternalKey, InternalKey> getRange(List<FileMetaData>... inputLists) {
    InternalKey smallest = null;/*from  w w w .  j  ava  2s  .  c  om*/
    InternalKey largest = null;
    for (List<FileMetaData> inputList : inputLists) {
        for (FileMetaData fileMetaData : inputList) {
            if (smallest == null) {
                smallest = fileMetaData.getSmallest();
                largest = fileMetaData.getLargest();
            } else {
                if (internalKeyComparator.compare(fileMetaData.getSmallest(), smallest) < 0) {
                    smallest = fileMetaData.getSmallest();
                }
                if (internalKeyComparator.compare(fileMetaData.getLargest(), largest) > 0) {
                    largest = fileMetaData.getLargest();
                }
            }
        }
    }
    return Maps.immutableEntry(smallest, largest);
}

From source file:org.apache.hadoop.hdfs.notifier.NamespaceNotifierClient.java

public ConnectionManager(List<String> hosts, List<Integer> ports, NamespaceNotifierClient notifierClient) {
    serverId = null;/*from   w ww.j  a  v a2 s .  c o  m*/
    id = -1;
    tracker = new ServerTracker();
    this.notifierClient = notifierClient;
    this.listeningPort = notifierClient.listeningPort;

    servers = new ArrayList<Map.Entry<String, Integer>>();
    for (int i = 0; i < hosts.size(); i++) {
        String host = hosts.get(i);
        int port = ports.get(ports.size() == 0 ? 0 : i);
        servers.add(Maps.immutableEntry(host, port));
    }

    // So clients try have different priority for servers, avoiding
    // all the clients connecting to one server.
    Collections.shuffle(servers, notifierClient.generator);
}