类java.util.AbstractMap.SimpleImmutableEntry源码实例Demo

下面列出了怎么用java.util.AbstractMap.SimpleImmutableEntry的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: yangtools   文件: YangFunctionContext.java
private static @Nullable Entry<IdentitySchemaNode, IdentitySchemaNode> commonDerivedFrom(final String functionName,
        final Context context, final List<?> args) throws FunctionCallException {
    if (args == null || args.size() != 1) {
        throw new FunctionCallException(functionName + "() takes two arguments: node-set nodes, string identity");
    }
    if (!(args.get(0) instanceof String)) {
        throw new FunctionCallException("Argument 'identity' of " + functionName
            + "() function should be a String.");
    }

    final NormalizedNodeContext currentNodeContext = verifyContext(context);
    final TypedDataSchemaNode correspondingSchemaNode = getCorrespondingTypedSchemaNode(currentNodeContext);

    final SchemaContext schemaContext = getSchemaContext(currentNodeContext);
    return correspondingSchemaNode.getType() instanceof IdentityrefTypeDefinition
            && currentNodeContext.getNode().getValue() instanceof QName ? new SimpleImmutableEntry<>(
                    getIdentitySchemaNodeFromString((String) args.get(0), schemaContext, correspondingSchemaNode),
                    getIdentitySchemaNodeFromQName((QName) currentNodeContext.getNode().getValue(), schemaContext))
                    : null;
}
 
protected PrefixTree getTree(DateTimeParseContext context) {
    // prepare parse tree
    Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
    final int regionIdsSize = regionIds.size();
    Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
                                        ? cachedPrefixTree : cachedPrefixTreeCI;
    if (cached == null || cached.getKey() != regionIdsSize) {
        synchronized (this) {
            cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
            if (cached == null || cached.getKey() != regionIdsSize) {
                cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
                if (context.isCaseSensitive()) {
                    cachedPrefixTree = cached;
                } else {
                    cachedPrefixTreeCI = cached;
                }
            }
        }
    }
    return cached.getValue();
}
 
源代码3 项目: yangtools   文件: YangToSourcesProcessor.java
private List<Entry<CodeGeneratorArg, BasicCodeGenerator>> instantiateGenerators() throws MojoExecutionException {
    final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators = new ArrayList<>(codeGeneratorArgs.size());
    for (CodeGeneratorArg arg : codeGeneratorArgs) {
        arg.check();

        final BasicCodeGenerator generator;
        try {
            generator = getInstance(arg.getCodeGeneratorClass(), BasicCodeGenerator.class);
        } catch (ReflectiveOperationException e) {
            throw new MojoExecutionException("Failed to instantiate code generator "
                    + arg.getCodeGeneratorClass(), e);
        }

        LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, arg.getCodeGeneratorClass());
        generators.add(new SimpleImmutableEntry<>(arg, generator));
    }

    return generators;
}
 
源代码4 项目: anomaly-detection   文件: FeatureManager.java
private void updateUnprocessedFeatures(
    Optional<double[]> point,
    Deque<Entry<Long, double[]>> shingle,
    AnomalyDetector detector,
    long endTime,
    ActionListener<SinglePointFeatures> listener
) {
    if (point.isPresent()) {
        if (shingle.size() == shingleSize) {
            shingle.remove();
        }
        shingle.add(new SimpleImmutableEntry<>(endTime, point.get()));
        getProcessedFeatures(shingle, detector, endTime, listener);
    } else {
        listener.onResponse(new SinglePointFeatures(Optional.empty(), Optional.empty()));
    }
}
 
源代码5 项目: anomaly-detection   文件: FeatureManager.java
/**
 * Gets time ranges of sampled data points.
 *
 * To reduce workload/latency from search, most data points in the preview time ranges are not from search results.
 * This implementation selects up to maxPreviewSamples evenly spaced points from the entire time range.
 *
 * @return key is a list of sampled time ranges, value is the stride between samples
 */
private Entry<List<Entry<Long, Long>>, Integer> getSampleRanges(AnomalyDetector detector, long startMilli, long endMilli) {
    long start = truncateToMinute(startMilli);
    long end = truncateToMinute(endMilli);
    long bucketSize = ((IntervalTimeConfiguration) detector.getDetectionInterval()).toDuration().toMillis();
    int numBuckets = (int) Math.floor((end - start) / (double) bucketSize);
    int numSamples = (int) Math.max(Math.min(numBuckets * previewSampleRate, maxPreviewSamples), 1);
    int stride = (int) Math.max(1, Math.floor((double) numBuckets / numSamples));
    int numStrides = (int) Math.ceil(numBuckets / (double) stride);
    List<Entry<Long, Long>> sampleRanges = Stream
        .iterate(start, i -> i + stride * bucketSize)
        .limit(numStrides)
        .map(time -> new SimpleImmutableEntry<>(time, time + bucketSize))
        .collect(Collectors.toList());
    return new SimpleImmutableEntry<>(sampleRanges, stride);
}
 
源代码6 项目: anomaly-detection   文件: FeatureManager.java
/**
 * Gets search results for the sampled time ranges.
 *
 * @param listener handle search results map: key is time ranges, value is corresponding search results
 * @throws IOException if a user gives wrong query input when defining a detector
 */
void getSamplesForRanges(
    AnomalyDetector detector,
    List<Entry<Long, Long>> sampleRanges,
    ActionListener<Entry<List<Entry<Long, Long>>, double[][]>> listener
) throws IOException {
    searchFeatureDao.getFeatureSamplesForPeriods(detector, sampleRanges, ActionListener.wrap(featureSamples -> {
        List<Entry<Long, Long>> ranges = new ArrayList<>(featureSamples.size());
        List<double[]> samples = new ArrayList<>(featureSamples.size());
        for (int i = 0; i < featureSamples.size(); i++) {
            Entry<Long, Long> currentRange = sampleRanges.get(i);
            featureSamples.get(i).ifPresent(sample -> {
                ranges.add(currentRange);
                samples.add(sample);
            });
        }
        listener.onResponse(new SimpleImmutableEntry<>(ranges, samples.toArray(new double[0][0])));
    }, listener::onFailure));

}
 
源代码7 项目: anomaly-detection   文件: ModelManager.java
/**
 * Partitions a RCF model by forest size.
 *
 * A RCF model is first partitioned into desired size based on heap.
 * If there are more partitions than the number of nodes in the cluster,
 * the model is partitioned by the number of nodes and verified to
 * ensure the size of a partition does not exceed the max size limit based on heap.
 *
 * @param forest RCF configuration, including forest size
 * @param detectorId ID of the detector with no effects on partitioning
 * @return a pair of number of partitions and size of a parition (number of trees)
 * @throws LimitExceededException when there is no sufficient resouce available
 */
public Entry<Integer, Integer> getPartitionedForestSizes(RandomCutForest forest, String detectorId) {
    long totalSize = estimateModelSize(forest);
    long heapSize = jvmService.info().getMem().getHeapMax().getBytes();

    // desired partitioning
    long partitionSize = (long) (Math.min(heapSize * modelDesiredSizePercentage, totalSize));
    int numPartitions = (int) Math.ceil((double) totalSize / (double) partitionSize);
    int forestSize = (int) Math.ceil((double) forest.getNumberOfTrees() / (double) numPartitions);

    int numNodes = nodeFilter.getEligibleDataNodes().length;
    if (numPartitions > numNodes) {
        // partition by cluster size
        partitionSize = (long) Math.ceil((double) totalSize / (double) numNodes);
        long maxPartitionSize = (long) (heapSize * modelMaxSizePercentage);
        // verify against max size limit
        if (partitionSize <= maxPartitionSize) {
            numPartitions = numNodes;
            forestSize = (int) Math.ceil((double) forest.getNumberOfTrees() / (double) numNodes);
        } else {
            throw new LimitExceededException(detectorId, CommonErrorMessages.MEMORY_LIMIT_EXCEEDED_ERR_MSG);
        }
    }

    return new SimpleImmutableEntry<>(numPartitions, forestSize);
}
 
源代码8 项目: anomaly-detection   文件: ADStateManagerTests.java
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    modelManager = mock(ModelManager.class);
    when(modelManager.getPartitionedForestSizes(any(AnomalyDetector.class))).thenReturn(new SimpleImmutableEntry<>(2, 20));
    client = mock(Client.class);
    clientUtil = mock(ClientUtil.class);
    settings = Settings
        .builder()
        .put("opendistro.anomaly_detection.max_retry_for_unresponsive_node", 3)
        .put("opendistro.anomaly_detection.ad_mute_minutes", TimeValue.timeValueMinutes(10))
        .build();
    clock = mock(Clock.class);
    duration = Duration.ofHours(1);
    context = TestHelpers.createThreadPool();
    throttler = new Throttler(clock);

    stateManager = new ADStateManager(client, xContentRegistry(), modelManager, settings, clientUtil, clock, duration);

}
 
源代码9 项目: nexus-public   文件: SearchIndexServiceImpl.java
private void createBulkProcessorsAndExecutors(final int bulkCapacity,
                                              final int concurrentRequests,
                                              final int flushInterval,
                                              final int batchingThreads)
{
  Map<Integer, Entry<BulkProcessor, ExecutorService>> bulkProcessorAndThreadPools = new HashMap<>();
  for (int count = 0; count < batchingThreads; ++count) {
    final BulkIndexUpdateListener updateListener = new BulkIndexUpdateListener();
    updateListeners.add(updateListener);
    bulkProcessorAndThreadPools.put(count, new SimpleImmutableEntry<>(BulkProcessor
        .builder(this.client.get(), updateListener)
        .setBulkActions(bulkCapacity)
        .setBulkSize(new ByteSizeValue(-1)) // turn off automatic flush based on size in bytes
        .setConcurrentRequests(concurrentRequests)
        .setFlushInterval(periodicFlush ? TimeValue.timeValueMillis(flushInterval) : null)
        .build(), createThreadPool(count)));
  }
  this.bulkProcessorToExecutors = unmodifiableMap(bulkProcessorAndThreadPools);
}
 
private List<Entry<Long, Integer>> passEventListToReader(final ListReader<IMonitoringRecord> reader) {
	long currentTimeSeconds;
	int curNumRecords = 0;

	final List<Entry<Long, Integer>> eventList = new ArrayList<>(this.eventTimeOffsetsSeconds.length);

	for (final long eventDelaySeconds : this.eventTimeOffsetsSeconds) {
		curNumRecords++;
		currentTimeSeconds = START_TIME_SECONDS + eventDelaySeconds;
		final Entry<Long, Integer> curEntry = new SimpleImmutableEntry<>(eventDelaySeconds, curNumRecords);
		eventList.add(curEntry);
		final EmptyRecord r = new EmptyRecord();
		r.setLoggingTimestamp(TimeUnit.NANOSECONDS.convert(currentTimeSeconds, TimeUnit.SECONDS));
		this.inputRecords.add(r);
		reader.addObject(r);
	}

	return eventList;
}
 
源代码11 项目: jdk8u60   文件: DateTimeFormatterBuilder.java
protected PrefixTree getTree(DateTimeParseContext context) {
    // prepare parse tree
    Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
    final int regionIdsSize = regionIds.size();
    Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
                                        ? cachedPrefixTree : cachedPrefixTreeCI;
    if (cached == null || cached.getKey() != regionIdsSize) {
        synchronized (this) {
            cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
            if (cached == null || cached.getKey() != regionIdsSize) {
                cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
                if (context.isCaseSensitive()) {
                    cachedPrefixTree = cached;
                } else {
                    cachedPrefixTreeCI = cached;
                }
            }
        }
    }
    return cached.getValue();
}
 
源代码12 项目: jdk8u-jdk   文件: DateTimeFormatterBuilder.java
protected PrefixTree getTree(DateTimeParseContext context) {
    // prepare parse tree
    Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
    final int regionIdsSize = regionIds.size();
    Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
                                        ? cachedPrefixTree : cachedPrefixTreeCI;
    if (cached == null || cached.getKey() != regionIdsSize) {
        synchronized (this) {
            cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
            if (cached == null || cached.getKey() != regionIdsSize) {
                cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
                if (context.isCaseSensitive()) {
                    cachedPrefixTree = cached;
                } else {
                    cachedPrefixTreeCI = cached;
                }
            }
        }
    }
    return cached.getValue();
}
 
public List<RecipeFailure> collectErrors(CloudbreakOrchestratorException exception) {
    Multimap<String, String> nodesWithErrors = getNodesWithErrors(exception);

    if (nodesWithErrors.isEmpty()) {
        throw new CloudbreakServiceException("Failed to collect recipe execution failures. Cause exception contains no information.", exception);
    }

    List<RecipeFailure> failures = nodesWithErrors.asMap().entrySet().stream()
            .flatMap(e -> e.getValue().stream()
                    .map(v -> new SimpleImmutableEntry<>(e.getKey(), v))
                    .map(failure -> new RecipeFailure(failure.getKey(), getRecipePhase(failure.getValue()), getFailedRecipeName(failure.getValue()))))
            .filter(failure -> !failure.getRecipeName().isEmpty() && !failure.getPhase().isEmpty())
            .collect(Collectors.toList());

    return failures;
}
 
源代码14 项目: InflatableDonkey   文件: AssetPool.java
ItemElements<Asset, ByteString>
        assetChunks(List<Voodoo> voodoos, Map<ByteString, Asset> fileSignatureToAsset) {
    Map<Asset, List<ByteString>> map = voodoos.stream()
            .map(Voodoo::fileSignatureToChunkChecksumList)
            .map(Map::entrySet)
            .flatMap(Collection::stream)
            .filter(e -> {
                if (fileSignatureToAsset.containsKey(e.getKey())) {
                    return true;
                }
                logger.warn("-- assetChunks() - unreferenced signature: {}", e.getKey());
                return false;
            })
            .map(e -> new SimpleImmutableEntry<>(fileSignatureToAsset.get(e.getKey()), e.getValue()))
            .collect(toMap(Map.Entry::getKey,
                    Map.Entry::getValue,
                    (u, v) -> {
                        if (!u.equals(v)) {
                            logger.warn("-- assetChunks() - collision: {} {}", u, v);
                        }
                        return u;
                    }));
    return new ItemElements<>(map);
}
 
源代码15 项目: Java8CN   文件: DateTimeFormatterBuilder.java
protected PrefixTree getTree(DateTimeParseContext context) {
    // prepare parse tree
    Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
    final int regionIdsSize = regionIds.size();
    Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
                                        ? cachedPrefixTree : cachedPrefixTreeCI;
    if (cached == null || cached.getKey() != regionIdsSize) {
        synchronized (this) {
            cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
            if (cached == null || cached.getKey() != regionIdsSize) {
                cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
                if (context.isCaseSensitive()) {
                    cachedPrefixTree = cached;
                } else {
                    cachedPrefixTreeCI = cached;
                }
            }
        }
    }
    return cached.getValue();
}
 
源代码16 项目: zuul   文件: Headers.java
/**
 * Removes all header entries that match the given predicate.   Do not access the header list from inside the
 * {@link Predicate#test} body.
 *
 * @return if any elements were removed.
 */
public boolean removeIf(Predicate<? super Map.Entry<HeaderName, String>> filter) {
    requireNonNull(filter, "filter");
    boolean removed = false;
    int w = 0;
    for (int r = 0; r < size(); r++) {
        if (filter.test(new SimpleImmutableEntry<>(new HeaderName(originalName(r), name(r)), value(r)))) {
            removed = true;
        } else {
            originalName(w, originalName(r));
            name(w, name(r));
            value(w, value(r));
            w++;
        }
    }
    truncate(w);
    return removed;
}
 
源代码17 项目: trellis   文件: DBResource.java
/**
 * Fetch data for this resource.
 * @return true if data was found; false otherwise
 */
private boolean fetchData() {
    LOGGER.debug("Fetching data for: {}", identifier);
    final String extraQuery = "SELECT predicate, object FROM extra WHERE resource_id = ?";
    final String query
        = "SELECT id, interaction_model, modified, is_part_of, deleted, acl, "
        + "ldp_membership_resource, ldp_has_member_relation, ldp_is_member_of_relation, "
        + "ldp_inserted_content_relation, binary_location, binary_modified, binary_format "
        + "FROM resource WHERE subject = ?";
    final Optional<ResourceData> rd = jdbi.withHandle(handle -> handle.select(query, identifier.getIRIString())
            .map((rs, ctx) -> new ResourceData(rs)).findFirst());
    if (rd.isPresent()) {
        this.data = rd.get();
        final Map<String, String> extras = new HashMap<>();
        jdbi.useHandle(handle ->
                handle.select(extraQuery, this.data.getId())
                      .map((rs, ctx) -> new SimpleImmutableEntry<>(rs.getString(OBJECT), rs.getString(PREDICATE)))
                      .forEach(entry -> extras.put(entry.getKey(), entry.getValue())));

        this.data.setExtra(extras);
        return true;
    }
    return false;
}
 
源代码18 项目: hbase   文件: TestMasterMetricsWrapper.java
@Test
public void testQuotaSnapshotConversion() {
  MetricsMasterWrapperImpl info = new MetricsMasterWrapperImpl(
      TEST_UTIL.getHBaseCluster().getMaster());
  assertEquals(new SimpleImmutableEntry<Long,Long>(1024L, 2048L),
      info.convertSnapshot(new SpaceQuotaSnapshot(
          SpaceQuotaStatus.notInViolation(), 1024L, 2048L)));
  assertEquals(new SimpleImmutableEntry<Long,Long>(4096L, 2048L),
      info.convertSnapshot(new SpaceQuotaSnapshot(
          new SpaceQuotaStatus(SpaceViolationPolicy.NO_INSERTS), 4096L, 2048L)));
}
 
源代码19 项目: presto   文件: AbstractTestAccumuloRowSerializer.java
protected void deserializeData(AccumuloRowSerializer serializer, byte[] data)
{
    Mutation m = new Mutation("row");
    m.put(b("a"), b("a"), data);
    Key key = new Key(b("row"), b("a"), b("b"), b(), 0, false);
    Value value = new Value(data);
    serializer.setMapping(COLUMN_NAME, "a", "b");
    serializer.deserialize(new SimpleImmutableEntry<>(key, value));
}
 
源代码20 项目: anomaly-detection   文件: FeatureManager.java
/**
 * Gets unprocessed and processed features for the data points in the preview range.
 *
 * To reduce workload on search, the data points within the preview range are interpolated based on
 * sample query results. Unprocessed features are interpolated query results.
 * Processed features are inputs to models, transformed (such as shingle) from unprocessed features.
 *
 * @return unprocessed and procesed features
 */
private Entry<double[][], double[][]> getPreviewFeatures(double[][] samples, int stride) {
    Entry<double[][], double[][]> unprocessedAndProcessed = Optional
        .of(samples)
        .map(m -> transpose(m))
        .map(m -> interpolator.interpolate(m, stride * (samples.length - 1) + 1))
        .map(m -> transpose(m))
        .map(m -> new SimpleImmutableEntry<>(copyOfRange(m, shingleSize - 1, m.length), batchShingle(m, shingleSize)))
        .get();
    return unprocessedAndProcessed;
}
 
源代码21 项目: gemfirexd-oss   文件: CompactCompositeIndexKey.java
/**
 * {@inheritDoc}
 */
@Override
public SimpleImmutableEntry<Object, Object> createSnapshot() {
  final Object v = getValidValue();
  if (v != null) {
    // [sumedh] the next link can keep a large region of map alive via the key
    // given out below, but it should be fine since we do not store the index
    // keys for long and are always transient
    return new AbstractMap.SimpleImmutableEntry<Object, Object>(this, v);
  }
  else {
    return null;
  }
}
 
源代码22 项目: anomaly-detection   文件: ADStateManagerTests.java
public void testMaintenancRemove() throws IOException {
    ConcurrentHashMap<String, Entry<AnomalyDetector, Instant>> states = new ConcurrentHashMap<>();
    when(clock.instant()).thenReturn(Instant.MAX);
    states.put("123", new SimpleImmutableEntry<>(TestHelpers.randomAnomalyDetector(TestHelpers.randomUiMetadata(), null), Instant.MIN));
    stateManager.maintenance(states);
    assertEquals(0, states.size());

}
 
源代码23 项目: chart-fx   文件: DefaultRenderColorScheme.java
private static Map<String, List<String>> splitQuery(final String styleString) {
    if ((styleString == null) || styleString.isEmpty()) {
        return Collections.emptyMap();
    }

    return Arrays.stream(styleString.split(";")).map(SELF::splitQueryParameter).collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}
 
源代码24 项目: armeria   文件: GrpcDocStringExtractor.java
private static Map<String, String> parseFile(FileDescriptorProto descriptor) {
    return descriptor.getSourceCodeInfo().getLocationList().stream()
                     .filter(l -> !l.getLeadingComments().isEmpty())
                     .map(l -> {
                         final String fullName = getFullName(descriptor, l.getPathList());
                         if (fullName != null) {
                             return new SimpleImmutableEntry<>(fullName, l.getLeadingComments());
                         } else {
                             return null;
                         }
                     })
                     .filter(Objects::nonNull)
                     .collect(toImmutableMap(Entry::getKey, Entry::getValue));
}
 
源代码25 项目: cava   文件: FileBackedFingerprintRepository.java
private static Entry<String, Bytes> parseLine(String line) throws IOException {
  String[] segments = line.split("\\s+", 2);
  if (segments.length != 2) {
    throw new IOException("Invalid line");
  }
  String identifier = segments[0].toLowerCase();
  String fingerprintString = segments[1].trim().replace(":", "");
  Bytes fingerprint;
  try {
    fingerprint = Bytes.fromHexString(fingerprintString);
  } catch (IllegalArgumentException e) {
    throw new IOException("Invalid fingerprint", e);
  }
  return new SimpleImmutableEntry<>(identifier, fingerprint);
}
 
源代码26 项目: Guice-configuration   文件: VirtualBeanFactory.java
private Entry<String, Object> buildChildEntry(String key, Method m, Map<String, Object> values) {
    if (!isAnnotationTypedPresent(m)) {
        return new SimpleImmutableEntry<>(buildChildEntry(m, key, values));
    }
    return new SimpleImmutableEntry<>(key, values.entrySet().stream()
            .map(e -> buildChildEntry(m, e.getKey(), (Map<String, Object>) e.getValue()))
            .collect(toMap(Entry::getKey, Entry::getValue)));
}
 
源代码27 项目: teku   文件: AbstractCompositeViewWrite.java
@Override
@SuppressWarnings("unchecked")
public ViewRead commitChanges() {
  if (childrenChanges.isEmpty() && childrenRefsChanged.isEmpty()) {
    return backingImmutableView;
  } else {
    IntCache<ChildReadType> cache = backingImmutableView.transferCache();
    List<Entry<Integer, ChildReadType>> changesList =
        Stream.concat(
                childrenChanges.entrySet().stream(),
                childrenRefsChanged.stream()
                    .map(
                        idx ->
                            new SimpleImmutableEntry<>(
                                idx,
                                (ChildReadType)
                                    ((ViewWrite) childrenRefs.get(idx)).commitChanges())))
            .sorted(Entry.comparingByKey())
            .collect(Collectors.toList());
    // pre-fill the read cache with changed values
    changesList.forEach(e -> cache.invalidateWithNewValue(e.getKey(), e.getValue()));
    TreeNode originalBackingTree = backingImmutableView.getBackingNode();
    TreeUpdates changes = changesToNewNodes(changesList, originalBackingTree);
    TreeNode newBackingTree = originalBackingTree.updated(changes);
    return createViewRead(newBackingTree, cache);
  }
}
 
源代码28 项目: es6draft   文件: CodeVisitor.java
private void labelReturn(Jump label, ArrayList<Map.Entry<LabelKind, String>> labels, LabelKind kind, String name) {
    if (label.isTarget()) {
        labels.add(new SimpleImmutableEntry<>(kind, name));

        mark(label);
        iconst(labels.size());
        _return();
    }
}
 
源代码29 项目: hazelcast-jet-demos   文件: SimpleMovingAverage.java
/**
 * <p>Accumulate input in a ringbuffer, implemented
 * using an array.
 * </p>
 * <p>As the array is filling, no output is produced
 * but we return "{@code true}" so Jet knows all is
 * good with input processing.
 * </p>
 * <p>Once the array is full, for each number of input
 * we place in the appropriate part of the array,
 * calculate the average and try to output. Potentially
 * the output queue is full. It's not guaranteed that
 * there is room for our output to be accepted, so cater
    * for this.
 * </p>
 */
@Override
protected boolean tryProcess(int ordinal, Object item) {
	
	@SuppressWarnings("unchecked")
	Price price = ((Entry<String, Price>) item).getValue();
	
	// Store the value
	this.rates[this.current] = price.getRate();

	// Determine the next slot
	int next;
	if (this.current == (this.rates.length - 1)) {
		next = 0;
	} else {
		next = this.current + 1;
	}
	
	// Try to output an average, if we have enough stored input
	if (this.rates[next]==null) {
		this.current = next;
		return true;
	} else {
		Price average = new Price();
		average.setLocalDate(price.getLocalDate());
		average.setRate(this.calculateAverage());
		
		Entry<String,Price> result
			= new SimpleImmutableEntry<>(this.key, average);
		
		// If we can output, advance the next write location
		boolean emit = super.tryEmit(result);
		if (emit) {
			this.current = next;
		}
		return emit;
	}
}
 
源代码30 项目: armeria   文件: AnnotatedBeanFactoryRegistry.java
@Nullable
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> Entry<Constructor<T>, List<AnnotatedValueResolver>> findConstructor(
        BeanFactoryId beanFactoryId, List<RequestObjectResolver> objectResolvers) {

    Entry<Constructor<T>, List<AnnotatedValueResolver>> candidate = null;

    final Set<Constructor> constructors = getConstructors(beanFactoryId.type);
    for (final Constructor<T> constructor : constructors) {
        // A default constructor can be a candidate only if there has been no candidate yet.
        if (constructor.getParameterCount() == 0 && candidate == null) {
            candidate = new SimpleImmutableEntry<>(constructor, ImmutableList.of());
            continue;
        }

        try {
            final List<RequestConverter> converters =
                    AnnotationUtil.findDeclared(constructor, RequestConverter.class);
            final List<AnnotatedValueResolver> resolvers =
                    AnnotatedValueResolver.ofBeanConstructorOrMethod(
                            constructor, beanFactoryId.pathParams,
                            addToFirstIfExists(objectResolvers, converters));
            if (!resolvers.isEmpty()) {
                // Can overwrite only if the current candidate is a default constructor.
                if (candidate == null || candidate.getValue().isEmpty()) {
                    candidate = new SimpleImmutableEntry<>(constructor, resolvers);
                } else {
                    throw new IllegalArgumentException(
                            "too many annotated constructors in " + beanFactoryId.type.getSimpleName() +
                            " (expected: 0 or 1)");
                }
            }
        } catch (NoAnnotatedParameterException ignored) {
            // There's no annotated parameters in the constructor.
        }
    }
    return candidate;
}
 
 类所在包
 类方法
 同包方法