예제 #1
0
 public List<Entry<String, Entity>> scan(
     String start, String end, int max, SortDirection direction, boolean keysOnly) {
   Preconditions.checkNotNull(start);
   Preconditions.checkNotNull(end);
   Preconditions.checkArgument(max > -1);
   if (max == 0) {
     return Lists.newArrayList();
   }
   Query query = new Query(kind);
   query.addFilter(
       "__key__", FilterOperator.GREATER_THAN_OR_EQUAL, KeyFactory.createKey(kind, escape(start)));
   query.addFilter("__key__", FilterOperator.LESS_THAN, KeyFactory.createKey(kind, escape(end)));
   query.addSort("__key__", direction);
   if (keysOnly) {
     query.setKeysOnly();
   }
   PreparedQuery preparedQuery = service.prepare(query);
   List<Entry<String, Entity>> result = Lists.newArrayList();
   for (Entity entity : preparedQuery.asIterable(FetchOptions.Builder.withLimit(max))) {
     if (keysOnly) {
       result.add(Maps.immutableEntry(unescape(entity.getKey().getName()), (Entity) null));
     } else {
       result.add(Maps.immutableEntry(unescape(entity.getKey().getName()), entity));
     }
   }
   return result;
 }
예제 #2
0
  @Override
  public Collection<Resource> getResources(ResourceConsumer consumer) {
    checkNotNull(consumer);

    // NOTE: getting all entries may become performance bottleneck
    // TODO: revisit for better backend data structure
    Stream<DiscreteResource> discreteStream =
        discreteConsumers
            .entrySet()
            .stream()
            .filter(x -> x.getValue().value().equals(consumer))
            .map(Map.Entry::getKey);

    Stream<ContinuousResource> continuousStream =
        continuousConsumers
            .values()
            .stream()
            .flatMap(
                x ->
                    x.value()
                        .allocations()
                        .stream()
                        .map(y -> Maps.immutableEntry(x.value().original(), y)))
            .filter(x -> x.getValue().consumer().equals(consumer))
            .map(x -> x.getKey());

    return Stream.concat(discreteStream, continuousStream).collect(Collectors.toList());
  }
예제 #3
0
  protected Entry<Integer, String> exec(String hostname, String[] command) throws IOException {
    RemoteShell shell = new RemoteShell(hostname, command, options);
    try {
      shell.execute();
    } catch (ExitCodeException e) {
      // capture the stdout of the process as well.
      String output = shell.getOutput();
      // add output for the ExitCodeException.
      ExitCodeException ece =
          new ExitCodeException(
              e.getExitCode(), "stderr: " + e.getMessage() + ", stdout: " + output);
      log.error("Failed to run command", ece);
      return Maps.immutableEntry(e.getExitCode(), output);
    }

    return Maps.immutableEntry(shell.getExitCode(), shell.getOutput());
  }
 private void assertResult(
     Organisaatio parent,
     Organisaatio organisaatio,
     boolean expected,
     Predicate<Entry<Organisaatio, Organisaatio>> validator,
     Predicate<Entry<Organisaatio, Organisaatio>> validator2) {
   Entry<Organisaatio, Organisaatio> parentChild = Maps.immutableEntry(parent, organisaatio);
   Assert.assertEquals(expected, validator.apply(parentChild));
   Assert.assertEquals(expected, validator2.apply(parentChild));
 }
예제 #5
0
파일: Gsons.java 프로젝트: akune/immutables
            @Override
            public Multimap<Character, Map.Entry<String, ValueAttribute>> apply(
                Iterable<ValueAttribute> attributes) {
              ImmutableMultimap.Builder<Character, Map.Entry<String, ValueAttribute>> builder =
                  ImmutableMultimap.builder();

              for (ValueAttribute attribute : attributes) {
                String serializedName = attribute.getMarshaledName();
                builder.put(
                    serializedName.charAt(0), Maps.immutableEntry(serializedName, attribute));

                for (String alternateName : attribute.getAlternateSerializedNames()) {
                  if (!alternateName.isEmpty()) {
                    builder.put(
                        alternateName.charAt(0), Maps.immutableEntry(alternateName, attribute));
                  }
                }
              }

              return builder.build();
            }
예제 #6
0
 private Entry<String, List<String>> resolveTypes(Entry<String, List<String>> sourceTypes) {
   String typeName = sourceTypes.getKey();
   boolean assumedNotQualified = Ascii.isUpperCase(typeName.charAt(0));
   if (assumedNotQualified) {
     typeName = resolveIfPossible(typeName);
   }
   List<String> typeArguments = Lists.newArrayListWithCapacity(sourceTypes.getValue().size());
   for (String typeArgument : sourceTypes.getValue()) {
     String resolvedTypeArgument =
         SourceTypes.stringify(resolveTypes(SourceTypes.extract(typeArgument)));
     typeArguments.add(resolvedTypeArgument);
   }
   return Maps.immutableEntry(typeName, typeArguments);
 }
예제 #7
0
 ImmutableMap<Service, Long> startupTimes() {
   this.monitor.enter();
   List<Map.Entry<Service, Long>> loadTimes;
   try {
     loadTimes =
         Lists.newArrayListWithCapacity(
             this.states.size()
                 - this.states.count(Service.State.NEW)
                 + this.states.count(Service.State.STARTING));
     for (Map.Entry<Service, Stopwatch> entry : this.startupTimers.entrySet()) {
       Service service = (Service) entry.getKey();
       Stopwatch stopWatch = (Stopwatch) entry.getValue();
       if ((!stopWatch.isRunning())
           && (!this.servicesByState.containsEntry(Service.State.NEW, service))
           && (!(service instanceof ServiceManager.NoOpService))) {
         loadTimes.add(
             Maps.immutableEntry(
                 service, Long.valueOf(stopWatch.elapsed(TimeUnit.MILLISECONDS))));
       }
     }
   } finally {
     this.monitor.leave();
   }
   Collections.sort(
       loadTimes,
       Ordering.natural()
           .onResultOf(
               new Function() {
                 public Long apply(Map.Entry<Service, Long> input) {
                   return (Long) input.getValue();
                 }
               }));
   ImmutableMap.Builder<Service, Long> builder = ImmutableMap.builder();
   for (Map.Entry<Service, Long> entry : loadTimes) {
     builder.put(entry);
   }
   return builder.build();
 }
예제 #8
0
 /** Attests that the map does not contain the given entry. */
 public void doesNotContainEntry(Object key, Object value) {
   if (getSubject().entrySet().contains(Maps.immutableEntry(key, value))) {
     fail("does not contain entry", key, value);
   }
 }
예제 #9
0
 /** Attests that the map contains the given entry. */
 public void containsEntry(Object key, Object value) {
   if (!getSubject().entrySet().contains(Maps.immutableEntry(key, value))) {
     fail("contains entry", key, value);
   }
 }
예제 #10
0
public final class KryoNamespaces {

  public static final KryoNamespace BASIC =
      KryoNamespace.newBuilder()
          .nextId(KryoNamespace.FLOATING_ID)
          .register(byte[].class)
          .register(AtomicBoolean.class)
          .register(AtomicInteger.class)
          .register(AtomicLong.class)
          .register(
              new ImmutableListSerializer(),
              ImmutableList.class,
              ImmutableList.of(1).getClass(),
              ImmutableList.of(1, 2).getClass())
          .register(
              new ImmutableSetSerializer(),
              ImmutableSet.class,
              ImmutableSet.of().getClass(),
              ImmutableSet.of(1).getClass(),
              ImmutableSet.of(1, 2).getClass())
          .register(
              new ImmutableMapSerializer(),
              ImmutableMap.class,
              ImmutableMap.of().getClass(),
              ImmutableMap.of("a", 1).getClass(),
              ImmutableMap.of("R", 2, "D", 2).getClass())
          .register(Collections.unmodifiableSet(Collections.emptySet()).getClass())
          .register(HashMap.class)
          .register(ConcurrentHashMap.class)
          .register(CopyOnWriteArraySet.class)
          .register(ArrayList.class, LinkedList.class, HashSet.class, LinkedHashSet.class)
          .register(Maps.immutableEntry("a", "b").getClass())
          .register(new ArraysAsListSerializer(), Arrays.asList().getClass())
          .register(Collections.singletonList(1).getClass())
          .register(Duration.class)
          .register(Collections.emptySet().getClass())
          .register(Optional.class)
          .register(Collections.emptyList().getClass())
          .register(Collections.singleton(Object.class).getClass())
          .register(int[].class)
          .register(long[].class)
          .register(short[].class)
          .register(double[].class)
          .register(float[].class)
          .register(char[].class)
          .register(String[].class)
          .register(boolean[].class)
          .build("BASIC");

  /** KryoNamespace which can serialize ON.lab misc classes. */
  public static final KryoNamespace MISC =
      KryoNamespace.newBuilder()
          .nextId(KryoNamespace.FLOATING_ID)
          .register(new IpPrefixSerializer(), IpPrefix.class)
          .register(new Ip4PrefixSerializer(), Ip4Prefix.class)
          .register(new Ip6PrefixSerializer(), Ip6Prefix.class)
          .register(new IpAddressSerializer(), IpAddress.class)
          .register(new Ip4AddressSerializer(), Ip4Address.class)
          .register(new Ip6AddressSerializer(), Ip6Address.class)
          .register(new MacAddressSerializer(), MacAddress.class)
          .register(Match.class)
          .register(VlanId.class)
          .register(Frequency.class)
          .register(Bandwidth.class)
          .register(Bandwidth.bps(1L).getClass())
          .register(Bandwidth.bps(1.0).getClass())
          .build("MISC");

  /** Kryo registration Id for user custom registration. */
  public static final int BEGIN_USER_CUSTOM_ID = 500;

  // TODO: Populate other classes
  /** KryoNamespace which can serialize API bundle classes. */
  public static final KryoNamespace API =
      KryoNamespace.newBuilder()
          .nextId(KryoNamespace.INITIAL_ID)
          .register(BASIC)
          .nextId(KryoNamespace.INITIAL_ID + 50)
          .register(MISC)
          .nextId(KryoNamespace.INITIAL_ID + 50 + 30)
          .register(
              Instructions.MeterInstruction.class,
              MeterId.class,
              Version.class,
              ControllerNode.State.class,
              ApplicationState.class,
              ApplicationRole.class,
              DefaultApplication.class,
              Permission.class,
              Device.Type.class,
              Port.Type.class,
              ChassisId.class,
              DefaultControllerNode.class,
              DefaultDevice.class,
              DefaultDeviceDescription.class,
              DefaultHost.class,
              DefaultLinkDescription.class,
              Port.class,
              DefaultPortDescription.class,
              Element.class,
              Link.Type.class,
              Link.State.class,
              Timestamp.class,
              Change.class,
              Leader.class,
              Leadership.class,
              LeadershipEvent.class,
              LeadershipEvent.Type.class,
              HostId.class,
              HostDescription.class,
              DefaultHostDescription.class,
              DefaultFlowEntry.class,
              StoredFlowEntry.class,
              DefaultFlowRule.class,
              DefaultPacketRequest.class,
              PacketPriority.class,
              FlowEntry.FlowEntryState.class,
              FlowId.class,
              DefaultTrafficSelector.class,
              PortCriterion.class,
              MetadataCriterion.class,
              EthCriterion.class,
              EthType.class,
              EthTypeCriterion.class,
              VlanIdCriterion.class,
              VlanPcpCriterion.class,
              IPDscpCriterion.class,
              IPEcnCriterion.class,
              IPProtocolCriterion.class,
              IPCriterion.class,
              TpPort.class,
              TcpPortCriterion.class,
              UdpPortCriterion.class,
              SctpPortCriterion.class,
              IcmpTypeCriterion.class,
              IcmpCodeCriterion.class,
              IPv6FlowLabelCriterion.class,
              Icmpv6TypeCriterion.class,
              Icmpv6CodeCriterion.class,
              IPv6NDTargetAddressCriterion.class,
              IPv6NDLinkLayerAddressCriterion.class,
              MplsCriterion.class,
              MplsBosCriterion.class,
              TunnelIdCriterion.class,
              IPv6ExthdrFlagsCriterion.class,
              LambdaCriterion.class,
              OchSignalCriterion.class,
              OchSignalTypeCriterion.class,
              OduSignalIdCriterion.class,
              OduSignalTypeCriterion.class,
              ArpOpCriterion.class,
              ArpHaCriterion.class,
              ArpPaCriterion.class,
              Criterion.class,
              Criterion.Type.class,
              DefaultTrafficTreatment.class,
              Instructions.NoActionInstruction.class,
              Instructions.OutputInstruction.class,
              Instructions.GroupInstruction.class,
              Instructions.TableTypeTransition.class,
              L0ModificationInstruction.class,
              L0ModificationInstruction.L0SubType.class,
              L0ModificationInstruction.ModOchSignalInstruction.class,
              L1ModificationInstruction.class,
              L1ModificationInstruction.L1SubType.class,
              L1ModificationInstruction.ModOduSignalIdInstruction.class,
              L2ModificationInstruction.class,
              L2ModificationInstruction.L2SubType.class,
              L2ModificationInstruction.ModEtherInstruction.class,
              L2ModificationInstruction.PushHeaderInstructions.class,
              L2ModificationInstruction.ModVlanIdInstruction.class,
              L2ModificationInstruction.ModVlanPcpInstruction.class,
              L2ModificationInstruction.PopVlanInstruction.class,
              L2ModificationInstruction.ModMplsLabelInstruction.class,
              L2ModificationInstruction.ModMplsBosInstruction.class,
              L2ModificationInstruction.ModMplsTtlInstruction.class,
              L2ModificationInstruction.ModTunnelIdInstruction.class,
              L3ModificationInstruction.class,
              L3ModificationInstruction.L3SubType.class,
              L3ModificationInstruction.ModIPInstruction.class,
              L3ModificationInstruction.ModIPv6FlowLabelInstruction.class,
              L3ModificationInstruction.ModTtlInstruction.class,
              L4ModificationInstruction.class,
              L4ModificationInstruction.L4SubType.class,
              L4ModificationInstruction.ModTransportPortInstruction.class,
              RoleInfo.class,
              FlowRuleBatchEvent.class,
              FlowRuleBatchEvent.Type.class,
              FlowRuleBatchRequest.class,
              FlowRuleBatchOperation.class,
              FlowRuleEvent.class,
              FlowRuleEvent.Type.class,
              CompletedBatchOperation.class,
              FlowRuleBatchEntry.class,
              FlowRuleBatchEntry.FlowRuleOperation.class,
              IntentId.class,
              IntentState.class,
              // Key.class, is abstract
              Key.of(1L, new DefaultApplicationId(0, "bar")).getClass(), // LongKey.class
              Key.of("foo", new DefaultApplicationId(0, "bar")).getClass(), // StringKey.class
              Intent.class,
              ConnectivityIntent.class,
              PathIntent.class,
              DefaultPath.class,
              DefaultEdgeLink.class,
              HostToHostIntent.class,
              PointToPointIntent.class,
              MultiPointToSinglePointIntent.class,
              SinglePointToMultiPointIntent.class,
              FlowRuleIntent.class,
              LinkCollectionIntent.class,
              OpticalConnectivityIntent.class,
              OpticalPathIntent.class,
              OpticalCircuitIntent.class,
              OpticalOduIntent.class,
              FlowObjectiveIntent.class,
              DiscreteResource.class,
              ContinuousResource.class,
              DiscreteResourceId.class,
              ContinuousResourceId.class,
              ResourceAllocation.class,
              ResourceConsumerId.class,
              // Constraints
              BandwidthConstraint.class,
              LinkTypeConstraint.class,
              LatencyConstraint.class,
              WaypointConstraint.class,
              ObstacleConstraint.class,
              AnnotationConstraint.class,
              BooleanConstraint.class,
              PartialFailureConstraint.class,
              IntentOperation.class,
              FlowRuleExtPayLoad.class,
              DefaultAnnotations.class,
              PortStatistics.class,
              DefaultPortStatistics.class,
              IntentDomainId.class,
              TableStatisticsEntry.class,
              DefaultTableStatisticsEntry.class,
              EncapsulationConstraint.class,
              EncapsulationType.class,
              // Flow Objectives
              DefaultForwardingObjective.class,
              ForwardingObjective.Flag.class,
              DefaultFilteringObjective.class,
              FilteringObjective.Type.class,
              DefaultNextObjective.class,
              NextObjective.Type.class,
              Objective.Operation.class)
          .register(new DefaultApplicationIdSerializer(), DefaultApplicationId.class)
          .register(new UriSerializer(), URI.class)
          .register(new NodeIdSerializer(), NodeId.class)
          .register(new ProviderIdSerializer(), ProviderId.class)
          .register(new DeviceIdSerializer(), DeviceId.class)
          .register(new PortNumberSerializer(), PortNumber.class)
          .register(new DefaultPortSerializer(), DefaultPort.class)
          .register(new LinkKeySerializer(), LinkKey.class)
          .register(new ConnectPointSerializer(), ConnectPoint.class)
          .register(new DefaultLinkSerializer(), DefaultLink.class)
          .register(new MastershipTermSerializer(), MastershipTerm.class)
          .register(new HostLocationSerializer(), HostLocation.class)
          .register(new DefaultOutboundPacketSerializer(), DefaultOutboundPacket.class)
          .register(new AnnotationsSerializer(), DefaultAnnotations.class)
          .register(
              new ExtensionInstructionSerializer(), Instructions.ExtensionInstructionWrapper.class)
          .register(new ExtensionCriterionSerializer(), ExtensionCriterion.class)
          .register(ExtensionSelectorType.class)
          .register(ExtensionTreatmentType.class)
          .register(TransactionId.class)
          .register(MapTransaction.class)
          .register(MapUpdate.class)
          .register(MapUpdate.Type.class)
          .register(Versioned.class)
          .register(MapEvent.class)
          .register(MapEvent.Type.class)
          .register(SetEvent.class)
          .register(SetEvent.Type.class)
          .register(DefaultGroupId.class)
          .register(Annotations.class)
          .register(OmsPort.class)
          .register(OchPort.class)
          .register(OduSignalType.class)
          .register(OchSignalType.class)
          .register(GridType.class)
          .register(ChannelSpacing.class)
          .register(OduCltPort.class)
          .register(CltSignalType.class)
          .register(OchSignal.class)
          .register(OduSignalId.class)
          .register(OduCltPortDescription.class)
          .register(OchPortDescription.class)
          .register(OmsPortDescription.class)
          .register(TributarySlot.class)
          .register(OtuPort.class)
          .register(OtuSignalType.class)
          .register(OtuPortDescription.class)
          .register(
              MplsIntent.class,
              MplsPathIntent.class,
              org.onlab.packet.MplsLabel.class,
              org.onlab.packet.MPLS.class)
          .register(ClosedOpenRange.class)
          .register(DiscreteResourceCodec.class)
          .register(new ImmutableByteSequenceSerializer(), ImmutableByteSequence.class)
          .build("API");

  // not to be instantiated
  private KryoNamespaces() {}
}
예제 #11
0
 private Map.Entry<EventObmId, Event> newEntryWithId(int id) {
   Event event = new Event();
   EventObmId eventId = new EventObmId(id);
   event.setUid(eventId);
   return Maps.immutableEntry(eventId, event);
 }
 /**
  * Remove a resource request and return it.
  *
  * @return The {@link Resource} and {@link Collection} of {@link RuntimeSpecification} or {@code
  *     null} if there is no more request.
  */
 Map.Entry<Resource, ? extends Collection<RuntimeSpecification>> takeRequest() {
   Map.Entry<Resource, Collection<RuntimeSpecification>> next = Iterators.getNext(requests, null);
   return next == null
       ? null
       : Maps.immutableEntry(next.getKey(), ImmutableList.copyOf(next.getValue()));
 }