java.util.AbstractMap.SimpleImmutableEntry Java Examples

The following examples show how to use java.util.AbstractMap.SimpleImmutableEntry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DateTimeFormatterBuilder.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #2
Source File: RecipeExecutionFailureCollector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: DateTimeFormatterBuilder.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #4
Source File: ADStateManagerTests.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example #5
Source File: ModelManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #6
Source File: AssetPool.java    From InflatableDonkey with MIT License 6 votes vote down vote up
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);
}
 
Example #7
Source File: FeatureManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * 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));

}
 
Example #8
Source File: FeatureManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: FeatureManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
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()));
    }
}
 
Example #10
Source File: YangToSourcesProcessor.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: Headers.java    From zuul with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: DBResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: DateTimeFormatterBuilder.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #14
Source File: DateTimeFormatterBuilder.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #15
Source File: AbstractTestRealtimeRecordDelayFilter.java    From kieker with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: SearchIndexServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #17
Source File: YangFunctionContext.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #18
Source File: AbstractCompositeViewWrite.java    From teku with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #19
Source File: FileBackedFingerprintRepository.java    From cava with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #20
Source File: VirtualBeanFactory.java    From Guice-configuration with Apache License 2.0 5 votes vote down vote up
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)));
}
 
Example #21
Source File: AbstractTestAccumuloRowSerializer.java    From presto with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #22
Source File: CompactCompositeIndexKey.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@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;
  }
}
 
Example #23
Source File: hs.java    From letv with Apache License 2.0 5 votes vote down vote up
public Collection<Entry<K, V>> b() {
    Collection arrayList = new ArrayList();
    for (Entry entry : this.a.entrySet()) {
        for (Object simpleImmutableEntry : (List) entry.getValue()) {
            arrayList.add(new SimpleImmutableEntry(entry.getKey(), simpleImmutableEntry));
        }
    }
    return arrayList;
}
 
Example #24
Source File: SingleRepositoryAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected static Entry<File, File[]> getActionRoots (VCSContext context) {
    Set<File> repositories = GitUtils.getRepositoryRoots(context);
    if (repositories.isEmpty()) {
        LOG.log(Level.FINE, "No repository in the given context: {0}", context.getRootFiles()); //NOI18N
        return null;
    }
    SimpleImmutableEntry<File, File[]> actionRoots = GitUtils.getActionRoots(context);
    if (actionRoots != null) {
        File repository = actionRoots.getKey();
        if (repositories.size() > 1) {
            LOG.log(Level.FINE, "Multiple repositories in the given context: {0}, selected {1}", new Object[] { context.getRootFiles(), repository }); //NOI18N
        }
    }
    return actionRoots;
}
 
Example #25
Source File: InfinispanAsyncMapImpl.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
@Override
public ReadStream<Entry<K, V>> entryStream() {
  return new CloseableIteratorCollectionStream<>(vertx.getOrCreateContext(), cache::entrySet, cacheEntry -> {
    K key = DataConverter.fromCachedObject(cacheEntry.getKey());
    V value = DataConverter.fromCachedObject(cacheEntry.getValue());
    return new SimpleImmutableEntry<>(key, value);
  });
}
 
Example #26
Source File: CodeVisitor.java    From es6draft with MIT License 5 votes vote down vote up
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();
    }
}
 
Example #27
Source File: ListFormatPrototype.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * CreatePartsFromList (listFormat, list)
 * 
 * @param listFormat
 *            the ListFormat object
 * @param list
 *            the list argument
 * @return the list parts
 */
private static List<Map.Entry<String, String>> CreatePartsFromList(ListFormatObject listFormat, List<String> list) {
    if (list.size() == 0) {
        return Collections.emptyList();
    }

    String pattern = listFormat.getListFormatter().getPatternForNumItems(list.size());
    SimpleFormatter formatter = SimpleFormatter.compile(pattern);
    int[] offsets = new int[list.size()];
    String result = formatter.formatAndAppend(new StringBuilder(), offsets, list.toArray(new String[0])).toString();

    ArrayList<Map.Entry<String, String>> parts = new ArrayList<>();
    int lastOffset = 0;
    for (int i = 0; i < offsets.length; i++) {
        int offset = offsets[i];
        if (offset != lastOffset) {
            parts.add(new SimpleImmutableEntry<>("literal", result.substring(lastOffset, offset)));
        }
        String element = list.get(i);
        parts.add(new SimpleImmutableEntry<>("element", element));
        lastOffset = offset + element.length();
    }
    if (lastOffset != result.length()) {
        parts.add(new SimpleImmutableEntry<>("literal", result.substring(lastOffset)));
    }

    return parts;
}
 
Example #28
Source File: DefaultMessageMapperFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, MessageMapper> instantiateMappers(final Stream<Map.Entry<String, MappingContext>> definitions) {
    return definitions
            .map(e -> {
                final String alias = e.getKey();
                final MessageMapper messageMapper =
                        mapperOf(alias, e.getValue()).map(WrappingMessageMapper::wrap).orElse(null);
                return new SimpleImmutableEntry<>(alias, messageMapper);
            })
            .filter(e -> null != e.getValue())
            .collect(Collectors.toMap(SimpleImmutableEntry::getKey, SimpleImmutableEntry::getValue));
}
 
Example #29
Source File: SimpleMovingAverage.java    From hazelcast-jet-demos with Apache License 2.0 5 votes vote down vote up
/**
 * <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;
	}
}
 
Example #30
Source File: AnnotatedBeanFactoryRegistry.java    From armeria with Apache License 2.0 5 votes vote down vote up
@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;
}