language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/DefaultCheckpointStatsTracker.java
{ "start": 3202, "end": 32032 }
class ____ { final String metricName; final TaskStatsSummaryExtractor taskStatsSummaryExtractor; final SubtaskMetricExtractor subtaskMetricExtractor; private CheckpointSpanMetric( String metricName, TaskStatsSummaryExtractor taskStatsSummaryExtractor, SubtaskMetricExtractor subtaskMetricExtractor) { this.metricName = metricName; this.taskStatsSummaryExtractor = taskStatsSummaryExtractor; this.subtaskMetricExtractor = subtaskMetricExtractor; } static CheckpointSpanMetric of( String metricName, TaskStatsSummaryExtractor taskStatsSummaryExtractor, SubtaskMetricExtractor subtaskMetricExtractor) { return new CheckpointSpanMetric( metricName, taskStatsSummaryExtractor, subtaskMetricExtractor); } } private static final List<CheckpointSpanMetric> CHECKPOINT_SPAN_METRICS = Arrays.asList( CheckpointSpanMetric.of( "StateSizeBytes", TaskStateStats.TaskStateStatsSummary::getStateSizeStats, SubtaskStateStats::getStateSize), CheckpointSpanMetric.of( "CheckpointedSizeBytes", TaskStateStats.TaskStateStatsSummary::getCheckpointedSize, SubtaskStateStats::getCheckpointedSize), CheckpointSpanMetric.of( "CheckpointStartDelayMs", TaskStateStats.TaskStateStatsSummary::getCheckpointStartDelayStats, SubtaskStateStats::getCheckpointStartDelay), CheckpointSpanMetric.of( "AlignmentDurationMs", TaskStateStats.TaskStateStatsSummary::getAlignmentDurationStats, SubtaskStateStats::getAlignmentDuration), CheckpointSpanMetric.of( "SyncCheckpointDurationMs", TaskStateStats.TaskStateStatsSummary::getSyncCheckpointDurationStats, SubtaskStateStats::getSyncCheckpointDuration), CheckpointSpanMetric.of( "AsyncCheckpointDurationMs", TaskStateStats.TaskStateStatsSummary::getAsyncCheckpointDurationStats, SubtaskStateStats::getAsyncCheckpointDuration), CheckpointSpanMetric.of( "ProcessedDataBytes", TaskStateStats.TaskStateStatsSummary::getProcessedDataStats, SubtaskStateStats::getProcessedData), CheckpointSpanMetric.of( "PersistedDataBytes", TaskStateStats.TaskStateStatsSummary::getPersistedDataStats, SubtaskStateStats::getPersistedData)); private final TraceOptions.CheckpointSpanDetailLevel checkpointSpanDetailLevel; /** * Lock used to update stats and creating snapshots. Updates always happen from a single Thread * at a time and there can be multiple concurrent read accesses to the latest stats snapshot. * * <p>Currently, writes are executed by whatever Thread executes the coordinator actions (which * already happens in locked scope). Reads can come from multiple concurrent Netty event loop * Threads of the web runtime monitor. */ private final ReentrantLock statsReadWriteLock = new ReentrantLock(); /** Checkpoint counts. */ private final CheckpointStatsCounts counts = new CheckpointStatsCounts(); /** A summary of the completed checkpoint stats. */ private final CompletedCheckpointStatsSummary summary = new CompletedCheckpointStatsSummary(); /** History of checkpoints. */ private final CheckpointStatsHistory history; private final JobManagerJobMetricGroup metricGroup; private Optional<JobInitializationMetricsBuilder> jobInitializationMetricsBuilder = Optional.empty(); @Nullable private final CheckpointStatsListener checkpointStatsListener; /** Latest created snapshot. */ private volatile CheckpointStatsSnapshot latestSnapshot; /** * Flag indicating whether a new snapshot needs to be created. This is true if a new checkpoint * was triggered or updated (completed successfully or failed). */ private volatile boolean dirty; /** The latest completed checkpoint. Used by the latest completed checkpoint metrics. */ @Nullable private volatile CompletedCheckpointStats latestCompletedCheckpoint; /** * Creates a new checkpoint stats tracker. * * @param numRememberedCheckpoints Maximum number of checkpoints to remember, including in * progress ones. * @param metricGroup Metric group for exposed metrics */ public DefaultCheckpointStatsTracker( int numRememberedCheckpoints, JobManagerJobMetricGroup metricGroup) { this( numRememberedCheckpoints, metricGroup, TraceOptions.CheckpointSpanDetailLevel.SPAN_PER_CHECKPOINT, null); } /** * Creates a new checkpoint stats tracker. * * @param numRememberedCheckpoints Maximum number of checkpoints to remember, including in * progress ones. * @param metricGroup Metric group for exposed metrics. * @param checkpointStatsListener Listener for monitoring checkpoint-related events. */ public DefaultCheckpointStatsTracker( int numRememberedCheckpoints, JobManagerJobMetricGroup metricGroup, TraceOptions.CheckpointSpanDetailLevel checkpointSpanDetailLevel, @Nullable CheckpointStatsListener checkpointStatsListener) { checkArgument(numRememberedCheckpoints >= 0, "Negative number of remembered checkpoints"); this.history = new CheckpointStatsHistory(numRememberedCheckpoints); this.metricGroup = metricGroup; this.checkpointSpanDetailLevel = checkpointSpanDetailLevel; this.checkpointStatsListener = checkpointStatsListener; // Latest snapshot is empty latestSnapshot = new CheckpointStatsSnapshot( counts.createSnapshot(), summary.createSnapshot(), history.createSnapshot(), null); // Register the metrics registerMetrics(metricGroup); } @Override public CheckpointStatsSnapshot createSnapshot() { CheckpointStatsSnapshot snapshot = latestSnapshot; // Only create a new snapshot if dirty and no update in progress, // because we don't want to block the coordinator. if (dirty && statsReadWriteLock.tryLock()) { try { // Create a new snapshot snapshot = new CheckpointStatsSnapshot( counts.createSnapshot(), summary.createSnapshot(), history.createSnapshot(), jobInitializationMetricsBuilder .flatMap( JobInitializationMetricsBuilder ::buildRestoredCheckpointStats) .orElse(null)); latestSnapshot = snapshot; dirty = false; } finally { statsReadWriteLock.unlock(); } } return snapshot; } // ------------------------------------------------------------------------ // Callbacks // ------------------------------------------------------------------------ @Override public PendingCheckpointStats reportPendingCheckpoint( long checkpointId, long triggerTimestamp, CheckpointProperties props, Map<JobVertexID, Integer> vertexToDop) { PendingCheckpointStats pending = new PendingCheckpointStats(checkpointId, triggerTimestamp, props, vertexToDop); statsReadWriteLock.lock(); try { counts.incrementInProgressCheckpoints(); history.addInProgressCheckpoint(pending); dirty = true; } finally { statsReadWriteLock.unlock(); } return pending; } @Override public void reportRestoredCheckpoint( long checkpointID, CheckpointProperties properties, String externalPath, long stateSize) { statsReadWriteLock.lock(); try { counts.incrementRestoredCheckpoints(); checkState( jobInitializationMetricsBuilder.isPresent(), "JobInitializationMetrics should have been set first, before RestoredCheckpointStats"); jobInitializationMetricsBuilder .get() .setRestoredCheckpointStats(checkpointID, stateSize, properties, externalPath); dirty = true; } finally { statsReadWriteLock.unlock(); } } @Override public void reportCompletedCheckpoint(CompletedCheckpointStats completed) { statsReadWriteLock.lock(); try { latestCompletedCheckpoint = completed; counts.incrementCompletedCheckpoints(); history.replacePendingCheckpointById(completed); summary.updateSummary(completed); dirty = true; logCheckpointStatistics(completed); if (checkpointStatsListener != null) { checkpointStatsListener.onCompletedCheckpoint(); } } finally { statsReadWriteLock.unlock(); } } @Override public void reportFailedCheckpoint(FailedCheckpointStats failed) { statsReadWriteLock.lock(); try { counts.incrementFailedCheckpoints(); history.replacePendingCheckpointById(failed); dirty = true; logCheckpointStatistics(failed); if (checkpointStatsListener != null) { checkpointStatsListener.onFailedCheckpoint(); } } finally { statsReadWriteLock.unlock(); } } private void logCheckpointStatistics(AbstractCheckpointStats checkpointStats) { try { EventBuilder eventBuilder = Events.CheckpointEvent.builder(CheckpointStatsTracker.class) .setObservedTsMillis(checkpointStats.getLatestAckTimestamp()) .setSeverity("INFO"); addCommonCheckpointStatsAttributes(eventBuilder, checkpointStats); metricGroup.addEvent(eventBuilder); SpanBuilder spanBuilder = Span.builder(CheckpointStatsTracker.class, "Checkpoint") .setStartTsMillis(checkpointStats.getTriggerTimestamp()) .setEndTsMillis(checkpointStats.getLatestAckTimestamp()); addCommonCheckpointStatsAttributes(spanBuilder, checkpointStats); // Add max/sum aggregations for breakdown metrics addCheckpointAggregationStats(checkpointStats, spanBuilder); metricGroup.addSpan(spanBuilder); if (LOG.isDebugEnabled()) { StringWriter sw = new StringWriter(); MAPPER.writeValue( sw, CheckpointStatistics.generateCheckpointStatistics(checkpointStats, true)); String jsonDump = sw.toString(); LOG.debug( "CheckpointStatistics (for jobID={}, checkpointId={}) dump = {} ", metricGroup.jobId(), checkpointStats.checkpointId, jsonDump); } } catch (Exception ex) { LOG.warn("Fail to log CheckpointStatistics", ex); } } private AttributeBuilder addCommonCheckpointStatsAttributes( AttributeBuilder attributeBuilder, AbstractCheckpointStats checkpointStats) { attributeBuilder .setAttribute("checkpointId", checkpointStats.getCheckpointId()) .setAttribute("fullSize", checkpointStats.getStateSize()) .setAttribute("checkpointedSize", checkpointStats.getCheckpointedSize()) .setAttribute("metadataSize", checkpointStats.getMetadataSize()) .setAttribute("checkpointStatus", checkpointStats.getStatus().name()) .setAttribute( "isUnaligned", Boolean.toString(checkpointStats.isUnalignedCheckpoint())) .setAttribute( "checkpointType", checkpointStats.getProperties().getCheckpointType().getName()); return attributeBuilder; } private void addCheckpointAggregationStats( AbstractCheckpointStats checkpointStats, SpanBuilder checkpointSpanBuilder) { final List<TaskStateStats> sortedTaskStateStats = new ArrayList<>(checkpointStats.getAllTaskStateStats()); sortedTaskStateStats.sort( (x, y) -> Long.signum( x.getSummaryStats().getCheckpointStartDelayStats().getMinimum() - y.getSummaryStats() .getCheckpointStartDelayStats() .getMinimum())); CHECKPOINT_SPAN_METRICS.stream() .map(metric -> TaskStatsAggregator.aggregate(sortedTaskStateStats, metric)) .forEach( aggregator -> { final String metricName = aggregator.getMetricName(); checkpointSpanBuilder.setAttribute( "max" + metricName, aggregator.getTotalMax()); if (!shouldSkipSumMetricNameInCheckpointSpanForCompatibility( metricName)) { checkpointSpanBuilder.setAttribute( "sum" + metricName, aggregator.getTotalSum()); } if (checkpointSpanDetailLevel == TraceOptions.CheckpointSpanDetailLevel .SPAN_PER_CHECKPOINT_WITH_TASKS) { checkpointSpanBuilder.setAttribute( "perTaskMax" + metricName, Arrays.toString( aggregator.getValuesMax().getInternalArray())); checkpointSpanBuilder.setAttribute( "perTaskSum" + metricName, Arrays.toString( aggregator.getValuesSum().getInternalArray())); } }); if (checkpointSpanDetailLevel == TraceOptions.CheckpointSpanDetailLevel.CHILDREN_SPANS_PER_TASK || checkpointSpanDetailLevel == TraceOptions.CheckpointSpanDetailLevel.CHILDREN_SPANS_PER_SUBTASK) { for (TaskStateStats taskStats : sortedTaskStateStats) { checkpointSpanBuilder.addChild( createTaskSpan( checkpointStats, taskStats, checkpointSpanDetailLevel == TraceOptions.CheckpointSpanDetailLevel .CHILDREN_SPANS_PER_SUBTASK)); } } } private SpanBuilder createTaskSpan( AbstractCheckpointStats checkpointStats, TaskStateStats taskStats, boolean addSubtaskSpans) { // start = trigger ts + minimum delay. long taskStartTs = checkpointStats.getTriggerTimestamp() + taskStats.getSummaryStats().getCheckpointStartDelayStats().getMinimum(); SpanBuilder taskSpanBuilder = Span.builder(CheckpointStatsTracker.class, "Checkpoint_Task") .setStartTsMillis(taskStartTs) .setEndTsMillis(taskStats.getLatestAckTimestamp()) .setAttribute("checkpointId", checkpointStats.getCheckpointId()) .setAttribute("jobVertexId", taskStats.getJobVertexId().toString()); for (CheckpointSpanMetric spanMetric : CHECKPOINT_SPAN_METRICS) { String metricName = spanMetric.metricName; StatsSummary statsSummary = spanMetric.taskStatsSummaryExtractor.extract(taskStats.getSummaryStats()); taskSpanBuilder.setAttribute("max" + metricName, statsSummary.getMaximum()); taskSpanBuilder.setAttribute("sum" + metricName, statsSummary.getSum()); } if (addSubtaskSpans) { addSubtaskSpans(checkpointStats, taskStats, taskSpanBuilder); } return taskSpanBuilder; } private void addSubtaskSpans( AbstractCheckpointStats checkpointStats, TaskStateStats taskStats, SpanBuilder taskSpanBuilder) { for (SubtaskStateStats subtaskStat : taskStats.getSubtaskStats()) { if (subtaskStat == null) { continue; } // start = trigger ts + minimum delay. long subTaskStartTs = checkpointStats.getTriggerTimestamp() + subtaskStat.getCheckpointStartDelay(); SpanBuilder subTaskSpanBuilder = Span.builder(CheckpointStatsTracker.class, "Checkpoint_Subtask") .setStartTsMillis(subTaskStartTs) .setEndTsMillis(subtaskStat.getAckTimestamp()) .setAttribute("checkpointId", checkpointStats.getCheckpointId()) .setAttribute("jobVertexId", taskStats.getJobVertexId().toString()) .setAttribute("subtaskId", subtaskStat.getSubtaskIndex()); for (CheckpointSpanMetric spanMetric : CHECKPOINT_SPAN_METRICS) { String metricName = spanMetric.metricName; long metricValue = spanMetric.subtaskMetricExtractor.extract(subtaskStat); subTaskSpanBuilder.setAttribute(metricName, metricValue); } taskSpanBuilder.addChild(subTaskSpanBuilder); } } private boolean shouldSkipSumMetricNameInCheckpointSpanForCompatibility(String metricName) { // Those two metrics already exists under different names that we want to preserve // (fullSize, checkpointedSize). return metricName.equals("StateSizeBytes") || metricName.equals("CheckpointedSizeBytes"); } @Override public void reportFailedCheckpointsWithoutInProgress() { statsReadWriteLock.lock(); try { counts.incrementFailedCheckpointsWithoutInProgress(); dirty = true; if (checkpointStatsListener != null) { checkpointStatsListener.onFailedCheckpoint(); } } finally { statsReadWriteLock.unlock(); } } @Override public PendingCheckpointStats getPendingCheckpointStats(long checkpointId) { statsReadWriteLock.lock(); try { AbstractCheckpointStats stats = history.getCheckpointById(checkpointId); return stats instanceof PendingCheckpointStats ? (PendingCheckpointStats) stats : null; } finally { statsReadWriteLock.unlock(); } } @Override public void reportIncompleteStats( long checkpointId, ExecutionAttemptID attemptId, CheckpointMetrics metrics) { statsReadWriteLock.lock(); try { AbstractCheckpointStats stats = history.getCheckpointById(checkpointId); if (stats instanceof PendingCheckpointStats) { ((PendingCheckpointStats) stats) .reportSubtaskStats( attemptId.getJobVertexId(), new SubtaskStateStats( attemptId.getSubtaskIndex(), System.currentTimeMillis(), metrics.getBytesPersistedOfThisCheckpoint(), metrics.getTotalBytesPersisted(), metrics.getSyncDurationMillis(), metrics.getAsyncDurationMillis(), metrics.getBytesProcessedDuringAlignment(), metrics.getBytesPersistedDuringAlignment(), metrics.getAlignmentDurationNanos() / 1_000_000, metrics.getCheckpointStartDelayNanos() / 1_000_000, metrics.getUnalignedCheckpoint(), false)); dirty = true; } } finally { statsReadWriteLock.unlock(); } } @Override public void reportInitializationStarted( Set<ExecutionAttemptID> toInitialize, long initializationStartTs) { jobInitializationMetricsBuilder = Optional.of( new JobInitializationMetricsBuilder(toInitialize, initializationStartTs)); } @Override public void reportInitializationMetrics( ExecutionAttemptID executionAttemptId, SubTaskInitializationMetrics initializationMetrics) { statsReadWriteLock.lock(); try { if (!jobInitializationMetricsBuilder.isPresent()) { LOG.warn( "Attempted to report SubTaskInitializationMetrics [{}] without jobInitializationMetricsBuilder present", initializationMetrics); return; } JobInitializationMetricsBuilder builder = jobInitializationMetricsBuilder.get(); builder.reportInitializationMetrics(executionAttemptId, initializationMetrics); if (builder.isComplete()) { traceInitializationMetrics(builder.build()); } } catch (Exception ex) { LOG.warn("Failed to log SubTaskInitializationMetrics [{}]", initializationMetrics, ex); } finally { statsReadWriteLock.unlock(); } } private void traceInitializationMetrics(JobInitializationMetrics jobInitializationMetrics) { SpanBuilder span = Span.builder(CheckpointStatsTracker.class, "JobInitialization") .setStartTsMillis(jobInitializationMetrics.getStartTs()) .setEndTsMillis(jobInitializationMetrics.getEndTs()) .setAttribute( "initializationStatus", jobInitializationMetrics.getStatus().name()); for (JobInitializationMetrics.SumMaxDuration duration : jobInitializationMetrics.getDurationMetrics().values()) { setDurationSpanAttribute(span, duration); } if (jobInitializationMetrics.getCheckpointId() != JobInitializationMetrics.UNSET) { span.setAttribute("checkpointId", jobInitializationMetrics.getCheckpointId()); } if (jobInitializationMetrics.getStateSize() != JobInitializationMetrics.UNSET) { span.setAttribute("fullSize", jobInitializationMetrics.getStateSize()); } metricGroup.addSpan(span); } private void setDurationSpanAttribute( SpanBuilder span, JobInitializationMetrics.SumMaxDuration duration) { span.setAttribute("max" + duration.getName(), duration.getMax()); span.setAttribute("sum" + duration.getName(), duration.getSum()); } // ------------------------------------------------------------------------ // Metrics // ------------------------------------------------------------------------ @VisibleForTesting static final String NUMBER_OF_CHECKPOINTS_METRIC = "totalNumberOfCheckpoints"; @VisibleForTesting static final String NUMBER_OF_IN_PROGRESS_CHECKPOINTS_METRIC = "numberOfInProgressCheckpoints"; @VisibleForTesting static final String NUMBER_OF_COMPLETED_CHECKPOINTS_METRIC = "numberOfCompletedCheckpoints"; @VisibleForTesting static final String NUMBER_OF_FAILED_CHECKPOINTS_METRIC = "numberOfFailedCheckpoints"; @VisibleForTesting static final String LATEST_RESTORED_CHECKPOINT_TIMESTAMP_METRIC = "lastCheckpointRestoreTimestamp"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_SIZE_METRIC = "lastCheckpointSize"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_FULL_SIZE_METRIC = "lastCheckpointFullSize"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_METADATA_SIZE_METRIC = "lastCheckpointMetadataSize"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_DURATION_METRIC = "lastCheckpointDuration"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_PROCESSED_DATA_METRIC = "lastCheckpointProcessedData"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_PERSISTED_DATA_METRIC = "lastCheckpointPersistedData"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_EXTERNAL_PATH_METRIC = "lastCheckpointExternalPath"; @VisibleForTesting static final String LATEST_COMPLETED_CHECKPOINT_ID_METRIC = "lastCompletedCheckpointId"; @VisibleForTesting static final String LATEST_CHECKPOINT_COMPLETED_TIMESTAMP = "lastCheckpointCompletedTimestamp"; /** * Register the exposed metrics. * * @param metricGroup Metric group to use for the metrics. */ private void registerMetrics(MetricGroup metricGroup) { metricGroup.gauge(NUMBER_OF_CHECKPOINTS_METRIC, new CheckpointsCounter()); metricGroup.gauge( NUMBER_OF_IN_PROGRESS_CHECKPOINTS_METRIC, new InProgressCheckpointsCounter()); metricGroup.gauge( NUMBER_OF_COMPLETED_CHECKPOINTS_METRIC, new CompletedCheckpointsCounter()); metricGroup.gauge(NUMBER_OF_FAILED_CHECKPOINTS_METRIC, new FailedCheckpointsCounter()); metricGroup.gauge( LATEST_RESTORED_CHECKPOINT_TIMESTAMP_METRIC, new LatestRestoredCheckpointTimestampGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_SIZE_METRIC, new LatestCompletedCheckpointSizeGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_FULL_SIZE_METRIC, new LatestCompletedCheckpointFullSizeGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_METADATA_SIZE_METRIC, new LatestCompletedCheckpointMetadataSizeGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_DURATION_METRIC, new LatestCompletedCheckpointDurationGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_PROCESSED_DATA_METRIC, new LatestCompletedCheckpointProcessedDataGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_PERSISTED_DATA_METRIC, new LatestCompletedCheckpointPersistedDataGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_EXTERNAL_PATH_METRIC, new LatestCompletedCheckpointExternalPathGauge()); metricGroup.gauge( LATEST_COMPLETED_CHECKPOINT_ID_METRIC, new LatestCompletedCheckpointIdGauge()); metricGroup.gauge( LATEST_CHECKPOINT_COMPLETED_TIMESTAMP, new LatestCheckpointCompletedTimestampGauge()); } private
CheckpointSpanMetric
java
apache__flink
flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/RegistryAvroDeserializationSchema.java
{ "start": 1370, "end": 1945 }
class ____<T> extends AvroDeserializationSchema<T> { private static final long serialVersionUID = -884738268437806062L; /** Provider for schema coder. Used for initializing in each task. */ private final SchemaCoder.SchemaCoderProvider schemaCoderProvider; /** Coder used for reading schema from incoming stream. */ private transient SchemaCoder schemaCoder; /** * Creates Avro deserialization schema that reads schema from input stream using provided {@link * SchemaCoder}. * * @param recordClazz
RegistryAvroDeserializationSchema
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/GenericTypeSerializationTest.java
{ "start": 4881, "end": 5734 }
class ____<B, BB> implements GenericWrapper<B, BB> { private final B first; private final BB second; GenericWrapperImpl(B first, BB second) { this.first = first; this.second = second; } @Override public B first() { return first; } @Override public BB second() { return second; } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) // Invert the type parameter order to make things exciting! public static <C, CC> GenericWrapperImpl<CC, C> fromJson(JsonGenericWrapper<CC, C> val) { return new GenericWrapperImpl<>(val.first(), val.second()); } } @JsonDeserialize @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE) public static final
GenericWrapperImpl
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/handler/predicate/RemoteAddrRoutePredicateFactoryTests.java
{ "start": 4466, "end": 4881 }
class ____ { @Value("${test.uri}") String uri; @Bean public RouteLocator testRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("x_forwarded_for_test", r -> r.path("/xforwardfor") .and() .remoteAddr(XForwardedRemoteAddressResolver.maxTrustedIndex(1), "12.34.56.78") .filters(f -> f.setStatus(200)) .uri(uri)) .build(); } } }
TestConfig
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/GcTimeMonitor.java
{ "start": 4645, "end": 8338 }
interface ____ invoked when GC * time percentage exceeds the specified limit. */ public GcTimeMonitor(long observationWindowMs, long sleepIntervalMs, int maxGcTimePercentage, GcTimeAlertHandler alertHandler) { Preconditions.checkArgument(observationWindowMs > 0); Preconditions.checkArgument( sleepIntervalMs > 0 && sleepIntervalMs < observationWindowMs); Preconditions.checkArgument( maxGcTimePercentage >= 0 && maxGcTimePercentage <= 100); this.observationWindowMs = observationWindowMs; this.sleepIntervalMs = sleepIntervalMs; this.maxGcTimePercentage = maxGcTimePercentage; this.alertHandler = alertHandler; bufSize = (int) (observationWindowMs / sleepIntervalMs + 2); // Prevent the user from accidentally creating an abnormally big buffer, // which will result in slow calculations and likely inaccuracy. Preconditions.checkArgument(bufSize <= 128 * 1024); gcDataBuf = new TsAndData[bufSize]; for (int i = 0; i < bufSize; i++) { gcDataBuf[i] = new TsAndData(); } this.setDaemon(true); this.setName("GcTimeMonitor obsWindow = " + observationWindowMs + ", sleepInterval = " + sleepIntervalMs + ", maxGcTimePerc = " + maxGcTimePercentage); } @Override public void work() { startTime = System.currentTimeMillis(); curData.timestamp = startTime; gcDataBuf[startIdx].setValues(startTime, 0); while (shouldRun) { try { Thread.sleep(sleepIntervalMs); } catch (InterruptedException ie) { return; } calculateGCTimePercentageWithinObservedInterval(); if (alertHandler != null && curData.gcTimePercentage > maxGcTimePercentage) { alertHandler.alert(curData.clone()); } } } public void shutdown() { shouldRun = false; } /** * Returns a copy of the most recent data measured by this monitor. * @return a copy of the most recent data measured by this monitor */ public GcData getLatestGcData() { return curData.clone(); } private void calculateGCTimePercentageWithinObservedInterval() { long prevTotalGcTime = curData.totalGcTime; long totalGcTime = 0; long totalGcCount = 0; for (GarbageCollectorMXBean gcBean : gcBeans) { totalGcTime += gcBean.getCollectionTime(); totalGcCount += gcBean.getCollectionCount(); } long gcTimeWithinSleepInterval = totalGcTime - prevTotalGcTime; long ts = System.currentTimeMillis(); long gcMonitorRunTime = ts - startTime; endIdx = (endIdx + 1) % bufSize; gcDataBuf[endIdx].setValues(ts, gcTimeWithinSleepInterval); // Move startIdx forward until we reach the first buffer entry with // timestamp within the observation window. long startObsWindowTs = ts - observationWindowMs; while (gcDataBuf[startIdx].ts < startObsWindowTs && startIdx != endIdx) { startIdx = (startIdx + 1) % bufSize; } // Calculate total GC time within observationWindowMs. // We should be careful about GC time that passed before the first timestamp // in our observation window. long gcTimeWithinObservationWindow = Math.min( gcDataBuf[startIdx].gcPause, gcDataBuf[startIdx].ts - startObsWindowTs); if (startIdx != endIdx) { for (int i = (startIdx + 1) % bufSize; i != endIdx; i = (i + 1) % bufSize) { gcTimeWithinObservationWindow += gcDataBuf[i].gcPause; } } curData.update(ts, gcMonitorRunTime, totalGcTime, totalGcCount, (int) (gcTimeWithinObservationWindow * 100 / Math.min(observationWindowMs, gcMonitorRunTime))); } /** * The user can provide an instance of a
is
java
apache__camel
components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsTemplate.java
{ "start": 1900, "end": 9915 }
class ____ { private final ConnectionFactory connectionFactory; private final boolean transacted; private final int acknowledgeMode; private DestinationCreationStrategy destinationCreationStrategy; private boolean preserveMessageQos; private boolean explicitQosEnabled; private int deliveryMode = Message.DEFAULT_DELIVERY_MODE; private int priority = Message.DEFAULT_PRIORITY; private long timeToLive = Message.DEFAULT_TIME_TO_LIVE; public SjmsTemplate(ConnectionFactory connectionFactory, boolean transacted, int acknowledgeMode) { ObjectHelper.notNull(connectionFactory, "ConnectionFactory", this); this.connectionFactory = connectionFactory; this.transacted = transacted; this.acknowledgeMode = acknowledgeMode; } public ConnectionFactory getConnectionFactory() { return connectionFactory; } public void setDestinationCreationStrategy(DestinationCreationStrategy destinationCreationStrategy) { this.destinationCreationStrategy = destinationCreationStrategy; } public void setQoSSettings(int deliveryMode, int priority, long timeToLive) { if (deliveryMode != 0) { this.deliveryMode = deliveryMode; this.explicitQosEnabled = true; } if (priority != 0) { this.priority = priority; this.explicitQosEnabled = true; } if (timeToLive > 0) { this.timeToLive = timeToLive; this.explicitQosEnabled = true; } } public void setExplicitQosEnabled(boolean explicitQosEnabled) { this.explicitQosEnabled = explicitQosEnabled; } public void setPreserveMessageQos(boolean preserveMessageQos) { this.preserveMessageQos = preserveMessageQos; } public Object execute(SessionCallback sessionCallback, boolean startConnection) throws Exception { Connection con = null; Session session = null; try { con = createConnection(); if (startConnection) { con.start(); } session = createSession(con); return sessionCallback.doInJms(session); } finally { sessionCallback.onClose(con, session); } } public void execute(Session session, SessionCallback sessionCallback) throws Exception { if (session == null) { execute(sessionCallback, false); } else { try { sessionCallback.doInJms(session); } finally { sessionCallback.onClose(null, session); } } } public void send(Exchange exchange, String destinationName, MessageCreator messageCreator, boolean isTopic) throws Exception { final SessionCallback callback = new SessionCallback() { private volatile Message message; private volatile boolean transacted; @Override public Object doInJms(Session session) throws Exception { this.transacted = isTransactionOrClientAcknowledgeMode(session); if (transacted) { // remember current session if transactional exchange.setProperty(SjmsConstants.JMS_SESSION, session); } Destination dest = destinationCreationStrategy.createDestination(session, destinationName, isTopic); this.message = messageCreator.createMessage(session); MessageProducer producer = session.createProducer(dest); try { send(producer, message); } finally { closeProducer(producer); } return null; } @Override public void onClose(Connection connection, Session session) { try { if (transacted) { // defer closing till end of UoW TransactionOnCompletion toc = new TransactionOnCompletion(session, this.message); if (!exchange.getExchangeExtension().containsOnCompletion(toc)) { exchange.getExchangeExtension().addOnCompletion(toc); } } else { closeSession(session); closeConnection(connection); } } catch (Exception e) { // ignore } } }; execute(callback, false); } public void send(MessageProducer producer, Message message) throws Exception { if (preserveMessageQos) { long ttl = message.getJMSExpiration(); if (ttl != 0) { ttl = ttl - System.currentTimeMillis(); // Message had expired.. so set the ttl as small as possible if (ttl <= 0) { ttl = 1; } } int priority = message.getJMSPriority(); if (priority < 0 || priority > 9) { // use priority from endpoint if not provided on message with a valid range priority = this.priority; } // if a delivery mode was set as a JMS header then we have used a temporary // property to store it - CamelJMSDeliveryMode. Otherwise we could not keep // track whether it was set or not as getJMSDeliveryMode() will default return 1 regardless // if it was set or not, so we can never tell if end user provided it in a header int resolvedDeliveryMode = resolveDeliveryMode(message); producer.send(message, resolvedDeliveryMode, priority, ttl); } else if (explicitQosEnabled) { producer.send(message, deliveryMode, priority, timeToLive); } else { producer.send(message); } } private static int resolveDeliveryMode(Message message) throws JMSException { int resolvedDeliveryMode; if (JmsMessageHelper.hasProperty(message, JmsConstants.JMS_DELIVERY_MODE)) { resolvedDeliveryMode = message.getIntProperty(JmsConstants.JMS_DELIVERY_MODE); // remove the temporary property JmsMessageHelper.removeJmsProperty(message, JmsConstants.JMS_DELIVERY_MODE); } else { // use the existing delivery mode from the message resolvedDeliveryMode = message.getJMSDeliveryMode(); } return resolvedDeliveryMode; } public Message receive(String destinationName, String messageSelector, boolean isTopic, long timeout) throws Exception { Object obj = execute(sc -> { Destination dest = destinationCreationStrategy.createDestination(sc, destinationName, isTopic); MessageConsumer consumer; if (ObjectHelper.isNotEmpty(messageSelector)) { consumer = sc.createConsumer(dest, messageSelector); } else { consumer = sc.createConsumer(dest); } Message message = null; try { if (timeout < 0) { message = consumer.receiveNoWait(); } else if (timeout == 0) { message = consumer.receive(); } else { message = consumer.receive(timeout); } } finally { // success then commit if we need to commitIfNeeded(sc, message); closeConsumer(consumer); } return message; }, true); return (Message) obj; } public Connection createConnection() throws Exception { return connectionFactory.createConnection(); } public Session createSession(Connection connection) throws Exception { return connection.createSession(transacted, acknowledgeMode); } }
SjmsTemplate
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableToMapTest.java
{ "start": 968, "end": 13326 }
class ____ extends RxJavaTest { Subscriber<Object> objectSubscriber; SingleObserver<Object> singleObserver; @Before public void before() { objectSubscriber = TestHelper.mockSubscriber(); singleObserver = TestHelper.mockSingleObserver(); } Function<String, Integer> lengthFunc = new Function<String, Integer>() { @Override public Integer apply(String t1) { return t1.length(); } }; Function<String, String> duplicate = new Function<String, String>() { @Override public String apply(String t1) { return t1 + t1; } }; @Test public void toMapFlowable() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Flowable<Map<Integer, String>> mapped = source.toMap(lengthFunc).toFlowable(); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "a"); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(objectSubscriber); verify(objectSubscriber, never()).onError(any(Throwable.class)); verify(objectSubscriber, times(1)).onNext(expected); verify(objectSubscriber, times(1)).onComplete(); } @Test public void toMapWithValueSelectorFlowable() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Flowable<Map<Integer, String>> mapped = source.toMap(lengthFunc, duplicate).toFlowable(); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "aa"); expected.put(2, "bbbb"); expected.put(3, "cccccc"); expected.put(4, "dddddddd"); mapped.subscribe(objectSubscriber); verify(objectSubscriber, never()).onError(any(Throwable.class)); verify(objectSubscriber, times(1)).onNext(expected); verify(objectSubscriber, times(1)).onComplete(); } @Test public void toMapWithErrorFlowable() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Function<String, Integer> lengthFuncErr = new Function<String, Integer>() { @Override public Integer apply(String t1) { if ("bb".equals(t1)) { throw new RuntimeException("Forced Failure"); } return t1.length(); } }; Flowable<Map<Integer, String>> mapped = source.toMap(lengthFuncErr).toFlowable(); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "a"); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(objectSubscriber); verify(objectSubscriber, never()).onNext(expected); verify(objectSubscriber, never()).onComplete(); verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } @Test public void toMapWithErrorInValueSelectorFlowable() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Function<String, String> duplicateErr = new Function<String, String>() { @Override public String apply(String t1) { if ("bb".equals(t1)) { throw new RuntimeException("Forced failure"); } return t1 + t1; } }; Flowable<Map<Integer, String>> mapped = source.toMap(lengthFunc, duplicateErr).toFlowable(); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "aa"); expected.put(2, "bbbb"); expected.put(3, "cccccc"); expected.put(4, "dddddddd"); mapped.subscribe(objectSubscriber); verify(objectSubscriber, never()).onNext(expected); verify(objectSubscriber, never()).onComplete(); verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } @Test public void toMapWithFactoryFlowable() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Supplier<Map<Integer, String>> mapFactory = new Supplier<Map<Integer, String>>() { @Override public Map<Integer, String> get() { return new LinkedHashMap<Integer, String>() { private static final long serialVersionUID = -3296811238780863394L; @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > 3; } }; } }; Function<String, Integer> lengthFunc = new Function<String, Integer>() { @Override public Integer apply(String t1) { return t1.length(); } }; Flowable<Map<Integer, String>> mapped = source.toMap(lengthFunc, new Function<String, String>() { @Override public String apply(String v) { return v; } }, mapFactory).toFlowable(); Map<Integer, String> expected = new LinkedHashMap<>(); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(objectSubscriber); verify(objectSubscriber, never()).onError(any(Throwable.class)); verify(objectSubscriber, times(1)).onNext(expected); verify(objectSubscriber, times(1)).onComplete(); } @Test public void toMapWithErrorThrowingFactoryFlowable() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Supplier<Map<Integer, String>> mapFactory = new Supplier<Map<Integer, String>>() { @Override public Map<Integer, String> get() { throw new RuntimeException("Forced failure"); } }; Function<String, Integer> lengthFunc = new Function<String, Integer>() { @Override public Integer apply(String t1) { return t1.length(); } }; Flowable<Map<Integer, String>> mapped = source.toMap(lengthFunc, new Function<String, String>() { @Override public String apply(String v) { return v; } }, mapFactory).toFlowable(); Map<Integer, String> expected = new LinkedHashMap<>(); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(objectSubscriber); verify(objectSubscriber, never()).onNext(expected); verify(objectSubscriber, never()).onComplete(); verify(objectSubscriber, times(1)).onError(any(Throwable.class)); } @Test public void toMap() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Single<Map<Integer, String>> mapped = source.toMap(lengthFunc); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "a"); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(singleObserver); verify(singleObserver, never()).onError(any(Throwable.class)); verify(singleObserver, times(1)).onSuccess(expected); } @Test public void toMapWithValueSelector() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Single<Map<Integer, String>> mapped = source.toMap(lengthFunc, duplicate); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "aa"); expected.put(2, "bbbb"); expected.put(3, "cccccc"); expected.put(4, "dddddddd"); mapped.subscribe(singleObserver); verify(singleObserver, never()).onError(any(Throwable.class)); verify(singleObserver, times(1)).onSuccess(expected); } @Test public void toMapWithError() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Function<String, Integer> lengthFuncErr = new Function<String, Integer>() { @Override public Integer apply(String t1) { if ("bb".equals(t1)) { throw new RuntimeException("Forced Failure"); } return t1.length(); } }; Single<Map<Integer, String>> mapped = source.toMap(lengthFuncErr); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "a"); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(singleObserver); verify(singleObserver, never()).onSuccess(expected); verify(singleObserver, times(1)).onError(any(Throwable.class)); } @Test public void toMapWithErrorInValueSelector() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Function<String, String> duplicateErr = new Function<String, String>() { @Override public String apply(String t1) { if ("bb".equals(t1)) { throw new RuntimeException("Forced failure"); } return t1 + t1; } }; Single<Map<Integer, String>> mapped = source.toMap(lengthFunc, duplicateErr); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "aa"); expected.put(2, "bbbb"); expected.put(3, "cccccc"); expected.put(4, "dddddddd"); mapped.subscribe(singleObserver); verify(singleObserver, never()).onSuccess(expected); verify(singleObserver, times(1)).onError(any(Throwable.class)); } @Test public void toMapWithFactory() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Supplier<Map<Integer, String>> mapFactory = new Supplier<Map<Integer, String>>() { @Override public Map<Integer, String> get() { return new LinkedHashMap<Integer, String>() { private static final long serialVersionUID = -3296811238780863394L; @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > 3; } }; } }; Function<String, Integer> lengthFunc = new Function<String, Integer>() { @Override public Integer apply(String t1) { return t1.length(); } }; Single<Map<Integer, String>> mapped = source.toMap(lengthFunc, new Function<String, String>() { @Override public String apply(String v) { return v; } }, mapFactory); Map<Integer, String> expected = new LinkedHashMap<>(); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(singleObserver); verify(singleObserver, never()).onError(any(Throwable.class)); verify(singleObserver, times(1)).onSuccess(expected); } @Test public void toMapWithErrorThrowingFactory() { Flowable<String> source = Flowable.just("a", "bb", "ccc", "dddd"); Supplier<Map<Integer, String>> mapFactory = new Supplier<Map<Integer, String>>() { @Override public Map<Integer, String> get() { throw new RuntimeException("Forced failure"); } }; Function<String, Integer> lengthFunc = new Function<String, Integer>() { @Override public Integer apply(String t1) { return t1.length(); } }; Single<Map<Integer, String>> mapped = source.toMap(lengthFunc, new Function<String, String>() { @Override public String apply(String v) { return v; } }, mapFactory); Map<Integer, String> expected = new LinkedHashMap<>(); expected.put(2, "bb"); expected.put(3, "ccc"); expected.put(4, "dddd"); mapped.subscribe(singleObserver); verify(singleObserver, never()).onSuccess(expected); verify(singleObserver, times(1)).onError(any(Throwable.class)); } }
FlowableToMapTest
java
spring-projects__spring-security
acl/src/main/java/org/springframework/security/acls/model/Sid.java
{ "start": 1050, "end": 1245 }
interface ____ provides a simple way to compare these abstracted security * identities with other security identities and actual security objects. * </p> * * @author Ben Alex */ public
therefore
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/AsyncCheckpointRunnable.java
{ "start": 2985, "end": 18297 }
enum ____ { RUNNING, DISCARDED, COMPLETED } private final AsyncExceptionHandler asyncExceptionHandler; private final Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress; private final CheckpointMetaData checkpointMetaData; private final CheckpointMetricsBuilder checkpointMetrics; private final long asyncConstructionNanos; private final AtomicReference<AsyncCheckpointState> asyncCheckpointState = new AtomicReference<>(AsyncCheckpointState.RUNNING); AsyncCheckpointRunnable( Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress, CheckpointMetaData checkpointMetaData, CheckpointMetricsBuilder checkpointMetrics, long asyncConstructionNanos, String taskName, Consumer<AsyncCheckpointRunnable> unregister, Environment taskEnvironment, AsyncExceptionHandler asyncExceptionHandler, boolean isTaskDeployedAsFinished, boolean isTaskFinished, Supplier<Boolean> isTaskRunning) { this.operatorSnapshotsInProgress = checkNotNull(operatorSnapshotsInProgress); this.checkpointMetaData = checkNotNull(checkpointMetaData); this.checkpointMetrics = checkNotNull(checkpointMetrics); this.asyncConstructionNanos = asyncConstructionNanos; this.taskName = checkNotNull(taskName); this.unregisterConsumer = unregister; this.taskEnvironment = checkNotNull(taskEnvironment); this.asyncExceptionHandler = checkNotNull(asyncExceptionHandler); this.isTaskDeployedAsFinished = isTaskDeployedAsFinished; this.isTaskFinished = isTaskFinished; this.isTaskRunning = isTaskRunning; } @Override public void run() { final long asyncStartNanos = System.nanoTime(); final long asyncStartDelayMillis = (asyncStartNanos - asyncConstructionNanos) / 1_000_000L; LOG.debug( "{} - started executing asynchronous part of checkpoint {}. Asynchronous start delay: {} ms", taskName, checkpointMetaData.getCheckpointId(), asyncStartDelayMillis); FileSystemSafetyNet.initializeSafetyNetForThread(); try { SnapshotsFinalizeResult snapshotsFinalizeResult = isTaskDeployedAsFinished ? finalizedFinishedSnapshots() : finalizeNonFinishedSnapshots(); final long asyncEndNanos = System.nanoTime(); final long asyncDurationMillis = (asyncEndNanos - asyncConstructionNanos) / 1_000_000L; checkpointMetrics.setBytesPersistedDuringAlignment( snapshotsFinalizeResult.bytesPersistedDuringAlignment); checkpointMetrics.setAsyncDurationMillis(asyncDurationMillis); if (asyncCheckpointState.compareAndSet( AsyncCheckpointState.RUNNING, AsyncCheckpointState.COMPLETED)) { reportCompletedSnapshotStates( snapshotsFinalizeResult.jobManagerTaskOperatorSubtaskStates, snapshotsFinalizeResult.localTaskOperatorSubtaskStates, asyncDurationMillis); } else { LOG.debug( "{} - asynchronous part of checkpoint {} could not be completed because it was closed before.", taskName, checkpointMetaData.getCheckpointId()); } finishedFuture.complete(null); } catch (Exception e) { LOG.info( "{} - asynchronous part of checkpoint {} could not be completed.", taskName, checkpointMetaData.getCheckpointId(), e); handleExecutionException(e); finishedFuture.completeExceptionally(e); } finally { unregisterConsumer.accept(this); FileSystemSafetyNet.closeSafetyNetAndGuardedResourcesForThread(); } } private SnapshotsFinalizeResult finalizedFinishedSnapshots() throws Exception { for (Map.Entry<OperatorID, OperatorSnapshotFutures> entry : operatorSnapshotsInProgress.entrySet()) { OperatorSnapshotFutures snapshotInProgress = entry.getValue(); // We should wait for the channels states get completed before continuing, // otherwise the alignment of barriers might have not finished yet. snapshotInProgress.getInputChannelStateFuture().get(); snapshotInProgress.getResultSubpartitionStateFuture().get(); } return new SnapshotsFinalizeResult( TaskStateSnapshot.FINISHED_ON_RESTORE, TaskStateSnapshot.FINISHED_ON_RESTORE, 0L); } private SnapshotsFinalizeResult finalizeNonFinishedSnapshots() throws Exception { TaskStateSnapshot jobManagerTaskOperatorSubtaskStates = new TaskStateSnapshot(operatorSnapshotsInProgress.size(), isTaskFinished); TaskStateSnapshot localTaskOperatorSubtaskStates = new TaskStateSnapshot(operatorSnapshotsInProgress.size(), isTaskFinished); long bytesPersistedDuringAlignment = 0; for (Map.Entry<OperatorID, OperatorSnapshotFutures> entry : operatorSnapshotsInProgress.entrySet()) { OperatorID operatorID = entry.getKey(); OperatorSnapshotFutures snapshotInProgress = entry.getValue(); // finalize the async part of all by executing all snapshot runnables OperatorSnapshotFinalizer finalizedSnapshots = OperatorSnapshotFinalizer.create(snapshotInProgress); jobManagerTaskOperatorSubtaskStates.putSubtaskStateByOperatorID( operatorID, finalizedSnapshots.getJobManagerOwnedState()); localTaskOperatorSubtaskStates.putSubtaskStateByOperatorID( operatorID, finalizedSnapshots.getTaskLocalState()); bytesPersistedDuringAlignment += finalizedSnapshots .getJobManagerOwnedState() .getResultSubpartitionState() .getStateSize(); bytesPersistedDuringAlignment += finalizedSnapshots .getJobManagerOwnedState() .getInputChannelState() .getStateSize(); } return new SnapshotsFinalizeResult( jobManagerTaskOperatorSubtaskStates, localTaskOperatorSubtaskStates, bytesPersistedDuringAlignment); } private void reportCompletedSnapshotStates( TaskStateSnapshot acknowledgedTaskStateSnapshot, TaskStateSnapshot localTaskStateSnapshot, long asyncDurationMillis) { boolean hasAckState = acknowledgedTaskStateSnapshot.hasState(); boolean hasLocalState = localTaskStateSnapshot.hasState(); checkState( hasAckState || !hasLocalState, "Found cached state but no corresponding primary state is reported to the job " + "manager. This indicates a problem."); // we signal stateless tasks by reporting null, so that there are no attempts to assign // empty state // to stateless tasks on restore. This enables simple job modifications that only concern // stateless without the need to assign them uids to match their (always empty) states. taskEnvironment .getTaskStateManager() .reportTaskStateSnapshots( checkpointMetaData, checkpointMetrics .setBytesPersistedOfThisCheckpoint( acknowledgedTaskStateSnapshot.getCheckpointedSize()) .setTotalBytesPersisted( acknowledgedTaskStateSnapshot.getStateSize()) .build(), hasAckState ? acknowledgedTaskStateSnapshot : null, hasLocalState ? localTaskStateSnapshot : null); LOG.debug( "{} - finished asynchronous part of checkpoint {}. Asynchronous duration: {} ms", taskName, checkpointMetaData.getCheckpointId(), asyncDurationMillis); LOG.trace( "{} - reported the following states in snapshot for checkpoint {}: {}.", taskName, checkpointMetaData.getCheckpointId(), acknowledgedTaskStateSnapshot); } private void reportAbortedSnapshotStats(long stateSize, long checkpointedSize) { CheckpointMetrics metrics = checkpointMetrics .setTotalBytesPersisted(stateSize) .setBytesPersistedOfThisCheckpoint(checkpointedSize) .buildIncomplete(); LOG.trace( "{} - report failed checkpoint stats: {} {}", taskName, checkpointMetaData.getCheckpointId(), metrics); taskEnvironment .getTaskStateManager() .reportIncompleteTaskStateSnapshots(checkpointMetaData, metrics); } private void handleExecutionException(Exception e) { boolean didCleanup = false; AsyncCheckpointState currentState = asyncCheckpointState.get(); while (AsyncCheckpointState.DISCARDED != currentState) { if (asyncCheckpointState.compareAndSet(currentState, AsyncCheckpointState.DISCARDED)) { didCleanup = true; try { cleanup(); } catch (Exception cleanupException) { e.addSuppressed(cleanupException); } Exception checkpointException = new Exception( "Could not materialize checkpoint " + checkpointMetaData.getCheckpointId() + " for operator " + taskName + '.', e); if (isTaskRunning.get()) { // We only report the exception for the original cause of fail and cleanup. // Otherwise this followup exception could race the original exception in // failing the task. try { Optional<CheckpointException> underlyingCheckpointException = ExceptionUtils.findThrowable( checkpointException, CheckpointException.class); // If this failure is already a CheckpointException, do not overwrite the // original CheckpointFailureReason CheckpointFailureReason reportedFailureReason = underlyingCheckpointException .map(exception -> exception.getCheckpointFailureReason()) .orElse(CheckpointFailureReason.CHECKPOINT_ASYNC_EXCEPTION); taskEnvironment.declineCheckpoint( checkpointMetaData.getCheckpointId(), new CheckpointException( reportedFailureReason, checkpointException)); } catch (Exception unhandled) { AsynchronousException asyncException = new AsynchronousException(unhandled); asyncExceptionHandler.handleAsyncException( "Failure in asynchronous checkpoint materialization", asyncException); } } else { // We never decline checkpoint after task is not running to avoid unexpected job // failover, which caused by exceeding checkpoint tolerable failure threshold. LOG.info( "Ignore decline of checkpoint {} as task is not running anymore.", checkpointMetaData.getCheckpointId()); } currentState = AsyncCheckpointState.DISCARDED; } else { currentState = asyncCheckpointState.get(); } } if (!didCleanup) { LOG.trace( "Caught followup exception from a failed checkpoint thread. This can be ignored.", e); } } @Override public void close() { if (asyncCheckpointState.compareAndSet( AsyncCheckpointState.RUNNING, AsyncCheckpointState.DISCARDED)) { try { final Tuple2<Long, Long> tuple = cleanup(); reportAbortedSnapshotStats(tuple.f0, tuple.f1); } catch (Exception cleanupException) { LOG.warn( "Could not properly clean up the async checkpoint runnable.", cleanupException); } } else { logFailedCleanupAttempt(); } } long getCheckpointId() { return checkpointMetaData.getCheckpointId(); } public CompletableFuture<Void> getFinishedFuture() { return finishedFuture; } /** * @return discarded full/incremental size (if available). */ private Tuple2<Long, Long> cleanup() throws Exception { LOG.debug( "Cleanup AsyncCheckpointRunnable for checkpoint {} of {}.", checkpointMetaData.getCheckpointId(), taskName); Exception exception = null; // clean up ongoing operator snapshot results and non partitioned state handles long stateSize = 0, checkpointedSize = 0; for (OperatorSnapshotFutures operatorSnapshotResult : operatorSnapshotsInProgress.values()) { if (operatorSnapshotResult != null) { try { Tuple2<Long, Long> tuple2 = operatorSnapshotResult.cancel(); stateSize += tuple2.f0; checkpointedSize += tuple2.f1; } catch (Exception cancelException) { exception = ExceptionUtils.firstOrSuppressed(cancelException, exception); } } } if (null != exception) { throw exception; } return Tuple2.of(stateSize, checkpointedSize); } private void logFailedCleanupAttempt() { LOG.debug( "{} - asynchronous checkpointing operation for checkpoint {} has " + "already been completed. Thus, the state handles are not cleaned up.", taskName, checkpointMetaData.getCheckpointId()); } private static
AsyncCheckpointState
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest85.java
{ "start": 893, "end": 1216 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); assertTrue(provider.checkValid(// "CREATE TABLE lookup (id INT) ENGINE = MEMORY;")); assertEquals(1, provider.getTableStats().size()); } }
MySqlWallTest85
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/fetchAndJoin/Entity1.java
{ "start": 440, "end": 962 }
class ____ { @Id @GeneratedValue private long id; @ManyToOne @JoinColumn(name="entity2_id", nullable = false) private Entity2 entity2; @Column(name = "val") private String value; public long getId() { return id; } public void setId(long id) { this.id = id; } public Entity2 getEntity2() { return entity2; } public void setEntity2(Entity2 entity2) { this.entity2 = entity2; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
Entity1
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/EnumeratedAndGenerics2Test.java
{ "start": 2374, "end": 2574 }
class ____ extends GenericBaseEntity<AnotherTestEnum> { @Id private long id; protected AnotherTestEntity() { } public AnotherTestEntity(long id) { this.id = id; } } }
AnotherTestEntity
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/function/FailableTest.java
{ "start": 70769, "end": 71334 }
interface ____ properly defined to throw any exception using the top level generic types * Object and Throwable. */ @Test void testThrows_FailableBiConsumer_Object_Throwable() { assertThrows(IOException.class, () -> new FailableBiConsumer<Object, Object, Throwable>() { @Override public void accept(final Object object1, final Object object2) throws Throwable { throw new IOException("test"); } }.accept(new Object(), new Object())); } /** * Tests that our failable
is
java
google__dagger
javatests/dagger/internal/codegen/ProductionComponentProcessorTest.java
{ "start": 11915, "end": 12247 }
class ____ {", " @Provides @Nullable C c() {", " return null;", " }", "", " @Provides @Production Executor executor() {", " return MoreExecutors.directExecutor();", " }", " }", "", " @ProducerModule", " static final
CModule
java
spring-projects__spring-security
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/RestClientJwtBearerTokenResponseClientTests.java
{ "start": 14712, "end": 22270 }
class ____ `client_secret_basic`, `client_secret_post`, and `none` by default."); // @formatter:on } @Test public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception { this.server.enqueue(MockResponses.json("access-token-response.json")); ClientRegistration clientRegistration = this.clientRegistration.build(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock(); HttpHeaders headers = new HttpHeaders(); headers.put("custom-header-name", Collections.singletonList("custom-header-value")); given(headersConverter.convert(grantRequest)).willReturn(headers); this.tokenResponseClient.addHeadersConverter(headersConverter); this.tokenResponseClient.getTokenResponse(grantRequest); verify(headersConverter).convert(grantRequest); RecordedRequest recordedRequest = this.server.takeRequest(); assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value"); } @Test public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception { this.server.enqueue(MockResponses.json("access-token-response.json")); ClientRegistration clientRegistration = this.clientRegistration.build(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock(); HttpHeaders headers = new HttpHeaders(); headers.put("custom-header-name", Collections.singletonList("custom-header-value")); given(headersConverter.convert(grantRequest)).willReturn(headers); this.tokenResponseClient.setHeadersConverter(headersConverter); this.tokenResponseClient.getTokenResponse(grantRequest); verify(headersConverter).convert(grantRequest); RecordedRequest recordedRequest = this.server.takeRequest(); assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull(); assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value"); } @Test public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception { this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST); this.server.enqueue(MockResponses.json("access-token-response.json")); ClientRegistration clientRegistration = this.clientRegistration.build(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.GRANT_TYPE, "custom"); parameters.set(OAuth2ParameterNames.ASSERTION, "custom-assertion"); parameters.set(OAuth2ParameterNames.SCOPE, "one two"); // The client_id parameter is omitted for testing purposes this.tokenResponseClient.setParametersConverter((authorizationGrantRequest) -> parameters); this.tokenResponseClient.getTokenResponse(grantRequest); RecordedRequest recordedRequest = this.server.takeRequest(); String formParameters = recordedRequest.getBody().readUtf8(); // @formatter:off assertThat(formParameters).contains( param(OAuth2ParameterNames.GRANT_TYPE, "custom"), param(OAuth2ParameterNames.CLIENT_ID, "client-1"), param(OAuth2ParameterNames.SCOPE, "one two"), param(OAuth2ParameterNames.ASSERTION, "custom-assertion") ); // @formatter:on } @Test public void getTokenResponseWhenParametersConverterSetThenAbleToOverrideDefaultParameters() throws Exception { this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST); this.server.enqueue(MockResponses.json("access-token-response.json")); ClientRegistration clientRegistration = this.clientRegistration.build(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("custom-parameter-name", "custom-parameter-value"); given(parametersConverter.convert(grantRequest)).willReturn(parameters); this.tokenResponseClient.setParametersConverter(parametersConverter); this.tokenResponseClient.getTokenResponse(grantRequest); verify(parametersConverter).convert(grantRequest); RecordedRequest recordedRequest = this.server.takeRequest(); String formParameters = recordedRequest.getBody().readUtf8(); assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value")); } @Test public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception { this.server.enqueue(MockResponses.json("access-token-response.json")); ClientRegistration clientRegistration = this.clientRegistration.build(); Set<String> scopes = clientRegistration.getScopes(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("custom-parameter-name", "custom-parameter-value"); given(parametersConverter.convert(grantRequest)).willReturn(parameters); this.tokenResponseClient.addParametersConverter(parametersConverter); this.tokenResponseClient.getTokenResponse(grantRequest); verify(parametersConverter).convert(grantRequest); RecordedRequest recordedRequest = this.server.takeRequest(); String formParameters = recordedRequest.getBody().readUtf8(); // @formatter:off assertThat(formParameters).contains( param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.JWT_BEARER.getValue()), param(OAuth2ParameterNames.ASSERTION, this.jwtAssertion.getTokenValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value") ); // @formatter:on } @Test public void getTokenResponseWhenParametersCustomizerSetThenCalled() throws Exception { this.server.enqueue(MockResponses.json("access-token-response.json")); ClientRegistration clientRegistration = this.clientRegistration.build(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); Consumer<MultiValueMap<String, String>> parametersCustomizer = mock(); this.tokenResponseClient.setParametersCustomizer(parametersCustomizer); this.tokenResponseClient.getTokenResponse(grantRequest); verify(parametersCustomizer).accept(any()); } @Test public void getTokenResponseWhenRestClientSetThenCalled() { this.server.enqueue(MockResponses.json("access-token-response.json")); RestClient customClient = mock(); given(customClient.post()).willReturn(RestClient.builder().build().post()); this.tokenResponseClient.setRestClient(customClient); ClientRegistration clientRegistration = this.clientRegistration.build(); JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion); this.tokenResponseClient.getTokenResponse(grantRequest); verify(customClient).post(); } private static String param(String parameterName, String parameterValue) { return "%s=%s".formatted(parameterName, URLEncoder.encode(parameterValue, StandardCharsets.UTF_8)); } }
supports
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DJLEndpointBuilderFactory.java
{ "start": 8744, "end": 9819 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final DJLHeaderNameBuilder INSTANCE = new DJLHeaderNameBuilder(); /** * The input data used for prediction. * * The option is a: {@code } type. * * Group: producer * * @return the name of the header {@code DjlInput}. */ public String djlInput() { return "CamelDjlInput"; } /** * The file type of the message body data. It is used when the body is * converted to bytes. * * The option is a: {@code } type. * * Group: producer * * @return the name of the header {@code DjlFileType}. */ public String djlFileType() { return "CamelDjlFileType"; } } static DJLEndpointBuilder endpointBuilder(String componentName, String path) {
DJLHeaderNameBuilder
java
junit-team__junit5
junit-vintage-engine/src/main/java/org/junit/vintage/engine/execution/RunListenerAdapter.java
{ "start": 1355, "end": 7580 }
class ____ extends RunListener { private final TestRun testRun; private final EngineExecutionListener listener; private final TestSourceProvider testSourceProvider; private final Function<Description, String> uniqueIdExtractor; RunListenerAdapter(TestRun testRun, EngineExecutionListener listener, TestSourceProvider testSourceProvider) { this.testRun = testRun; this.listener = listener; this.testSourceProvider = testSourceProvider; this.uniqueIdExtractor = new UniqueIdReader().andThen(new UniqueIdStringifier()); } @Override public void testRunStarted(Description description) { if (description.isSuite() && !testRun.getRunnerTestDescriptor().isIgnored()) { fireExecutionStarted(testRun.getRunnerTestDescriptor(), EventType.REPORTED); } } @Override public void testSuiteStarted(Description description) { RunnerTestDescriptor runnerTestDescriptor = testRun.getRunnerTestDescriptor(); // runnerTestDescriptor is reported in testRunStarted if (!runnerTestDescriptor.getDescription().equals(description)) { testStarted(lookupOrRegisterNextTestDescriptor(description), EventType.REPORTED); } } @Override public void testIgnored(Description description) { TestDescriptor testDescriptor = lookupOrRegisterNextTestDescriptor(description); String reason = determineReasonForIgnoredTest(testDescriptor, description).orElse("<unknown>"); testIgnored(testDescriptor, reason); } @Override public void testStarted(Description description) { testStarted(lookupOrRegisterNextTestDescriptor(description), EventType.REPORTED); } @Override public void testAssumptionFailure(Failure failure) { handleFailure(failure, TestExecutionResult::aborted); } @Override public void testFailure(Failure failure) { handleFailure(failure, TestExecutionResult::failed); } @Override public void testFinished(Description description) { testFinished(lookupOrRegisterCurrentTestDescriptor(description)); } @Override public void testSuiteFinished(Description description) { RunnerTestDescriptor runnerTestDescriptor = testRun.getRunnerTestDescriptor(); // runnerTestDescriptor is reported in testRunFinished if (!runnerTestDescriptor.getDescription().equals(description)) { reportContainerFinished(lookupOrRegisterCurrentTestDescriptor(description)); } } @Override public void testRunFinished(Result result) { testRunFinished(); } void testRunFinished() { reportContainerFinished(testRun.getRunnerTestDescriptor()); } private void reportContainerFinished(TestDescriptor containerTestDescriptor) { if (testRun.isNotSkipped(containerTestDescriptor)) { if (testRun.isNotStarted(containerTestDescriptor)) { fireExecutionStarted(containerTestDescriptor, EventType.SYNTHETIC); } testRun.getInProgressTestDescriptorsWithSyntheticStartEvents().stream() // .filter(this::canFinish) // .forEach(this::fireExecutionFinished); if (testRun.isNotFinished(containerTestDescriptor)) { fireExecutionFinished(containerTestDescriptor); } } } private TestDescriptor lookupOrRegisterNextTestDescriptor(Description description) { return lookupOrRegisterTestDescriptor(description, testRun::lookupNextTestDescriptor); } private TestDescriptor lookupOrRegisterCurrentTestDescriptor(Description description) { return lookupOrRegisterTestDescriptor(description, testRun::lookupCurrentTestDescriptor); } private TestDescriptor lookupOrRegisterTestDescriptor(Description description, Function<Description, Optional<VintageTestDescriptor>> lookup) { return lookup.apply(description).orElseGet(() -> registerDynamicTestDescriptor(description, lookup)); } private VintageTestDescriptor registerDynamicTestDescriptor(Description description, Function<Description, Optional<VintageTestDescriptor>> lookup) { // workaround for dynamic children as used by Spock's Runner TestDescriptor parent = findParent(description, lookup); UniqueId uniqueId = parent.getUniqueId().append(SEGMENT_TYPE_DYNAMIC, uniqueIdExtractor.apply(description)); VintageTestDescriptor dynamicDescriptor = new VintageTestDescriptor(uniqueId, description, testSourceProvider.findTestSource(description)); parent.addChild(dynamicDescriptor); testRun.registerDynamicTest(dynamicDescriptor); dynamicTestRegistered(dynamicDescriptor); return dynamicDescriptor; } private TestDescriptor findParent(Description description, Function<Description, Optional<VintageTestDescriptor>> lookup) { // @formatter:off return Optional.ofNullable(description.getTestClass()) .map(Description::createSuiteDescription) .flatMap(lookup) .orElseGet(testRun::getRunnerTestDescriptor); // @formatter:on } private void handleFailure(Failure failure, Function<Throwable, TestExecutionResult> resultCreator) { handleFailure(failure, resultCreator, lookupOrRegisterCurrentTestDescriptor(failure.getDescription())); } private void handleFailure(Failure failure, Function<Throwable, TestExecutionResult> resultCreator, TestDescriptor testDescriptor) { TestExecutionResult result = resultCreator.apply(failure.getException()); testRun.storeResult(testDescriptor, result); if (testRun.isNotStarted(testDescriptor)) { testStarted(testDescriptor, EventType.SYNTHETIC); } if (testRun.isNotFinished(testDescriptor) && testDescriptor.isContainer() && testRun.hasSyntheticStartEvent(testDescriptor) && testRun.isDescendantOfRunnerTestDescriptor(testDescriptor)) { testFinished(testDescriptor); } } private void testIgnored(TestDescriptor testDescriptor, String reason) { fireExecutionFinishedForInProgressNonAncestorTestDescriptorsWithSyntheticStartEvents(testDescriptor); fireExecutionStartedIncludingUnstartedAncestors(testDescriptor.getParent()); fireExecutionSkipped(testDescriptor, reason); } private Optional<String> determineReasonForIgnoredTest(TestDescriptor testDescriptor, Description description) { Optional<String> reason = getReason(description.getAnnotation(Ignore.class)); if (reason.isPresent()) { return reason; } // Workaround for some runners (e.g. JUnit38ClassRunner) don't include the @Ignore annotation // in the description, so we read it from the test
RunListenerAdapter
java
spring-projects__spring-boot
module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/autoconfigure/actuate/web/mappings/WebFluxMappingsAutoConfiguration.java
{ "start": 2231, "end": 2442 }
class ____ { @Bean DispatcherHandlersMappingDescriptionProvider dispatcherHandlersMappingDescriptionProvider() { return new DispatcherHandlersMappingDescriptionProvider(); } }
WebFluxMappingsAutoConfiguration
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/resource/basic/resource/CollectionDefaultValueResource.java
{ "start": 418, "end": 1501 }
class ____ { @QueryParam("nada") List<String> params; @DefaultValue("foo") @QueryParam("nada") List<String> paramsWithDefaultValue; } @BeanParam MyParams params; @GET @Produces("text/plain") public String get(@QueryParam("nada") List<String> params, @DefaultValue("foo") @QueryParam("nada") List<String> paramsWithDefaultValue) { Assertions.assertNotNull(params); Assertions.assertEquals(0, params.size()); Assertions.assertNotNull(paramsWithDefaultValue); Assertions.assertEquals(1, paramsWithDefaultValue.size()); Assertions.assertEquals("foo", paramsWithDefaultValue.get(0)); Assertions.assertNotNull(this.params.params); Assertions.assertEquals(0, this.params.params.size()); Assertions.assertNotNull(this.params.paramsWithDefaultValue); Assertions.assertEquals(1, this.params.paramsWithDefaultValue.size()); Assertions.assertEquals("foo", this.params.paramsWithDefaultValue.get(0)); return "hello"; } }
MyParams
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java
{ "start": 10681, "end": 11041 }
class ____ { Inner t; } """) .doTest(); } @Test public void negativeNoWildcard() { CompilationTestHelper.newInstance(WildcardImport.class, getClass()) .addSourceLines( "test/Test.java", """ package test; import java.util.Map; public
Test
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/standalone/StandaloneHerder.java
{ "start": 23562, "end": 25639 }
class ____ implements ConfigBackingStore.UpdateListener { @Override public void onConnectorConfigRemove(String connector) { synchronized (StandaloneHerder.this) { configState = configBackingStore.snapshot(); } } @Override public void onConnectorConfigUpdate(String connector) { // TODO: move connector configuration update handling here to be consistent with // the semantics of the config backing store synchronized (StandaloneHerder.this) { configState = configBackingStore.snapshot(); } } @Override public void onTaskConfigUpdate(Collection<ConnectorTaskId> tasks) { synchronized (StandaloneHerder.this) { configState = configBackingStore.snapshot(); } } @Override public void onConnectorTargetStateChange(String connector) { synchronized (StandaloneHerder.this) { configState = configBackingStore.snapshot(); TargetState targetState = configState.targetState(connector); worker.setTargetState(connector, targetState, (error, newState) -> { if (error != null) { log.error("Failed to transition connector {} to target state {}", connector, targetState, error); return; } if (newState == TargetState.STARTED) { requestExecutorService.submit(() -> updateConnectorTasks(connector)); } }); } } @Override public void onSessionKeyUpdate(SessionKey sessionKey) { // no-op } @Override public void onRestartRequest(RestartRequest restartRequest) { // no-op } @Override public void onLoggingLevelUpdate(String namespace, String level) { // no-op } } static
ConfigUpdateListener
java
spring-projects__spring-boot
module/spring-boot-data-jdbc/src/test/java/org/springframework/boot/data/jdbc/autoconfigure/DataJdbcRepositoriesAutoConfigurationTests.java
{ "start": 9880, "end": 10092 }
class ____ { @Bean RelationalManagedTypes customRelationalManagedTypes() { return RelationalManagedTypes.empty(); } } @Configuration(proxyBeanMethods = false) static
RelationalManagedTypesConfiguration
java
google__error-prone
check_api/src/main/java/com/google/errorprone/fixes/IndexedPosition.java
{ "start": 937, "end": 1694 }
class ____ implements DiagnosticPosition { final int startPos; final int endPos; public IndexedPosition(int startPos, int endPos) { checkArgument(startPos >= 0, "Start [%s] should not be less than zero", startPos); checkArgument(startPos <= endPos, "Start [%s] should not be after end [%s]", startPos, endPos); this.startPos = startPos; this.endPos = endPos; } @Override public JCTree getTree() { throw new UnsupportedOperationException(); } @Override public int getStartPosition() { return startPos; } @Override public int getPreferredPosition() { throw new UnsupportedOperationException(); } @Override public int getEndPosition(EndPosTable endPosTable) { return endPos; } }
IndexedPosition
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BadInstanceofTest.java
{ "start": 1693, "end": 1895 }
class ____ { boolean foo(C c) { return c != null; } boolean notFoo(C c) { return c == null; } static
A
java
quarkusio__quarkus
independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/project/create/RecommendStreamsFromScenarioBase.java
{ "start": 219, "end": 4932 }
class ____ extends MultiplePlatformBomsTestBase { protected static final String UPSTREAM_PLATFORM_KEY = "io.upstream.platform"; protected static final String DOWNSTREAM_PLATFORM_KEY = "io.downstream.platform"; @BeforeEach public void setup() throws Exception { TestRegistryClientBuilder registryClientBuilder = TestRegistryClientBuilder.newInstance() //.debug() .baseDir(configDir()); var downstreamRegistry = registryClientBuilder // registry .newRegistry("downstream.registry.test") .recognizedQuarkusVersions("*downstream"); setDownstreamRegistryExtraOptions(downstreamRegistry); downstreamRegistry // platform key .newPlatform(DOWNSTREAM_PLATFORM_KEY) .newStream("2.2") // 2.2.2 release .newRelease("2.2.2.downstream") .quarkusVersion("2.2.2.downstream") .upstreamQuarkusVersion("2.2.2") // default bom including quarkus-core + essential metadata .addCoreMember().release() // platform member .newMember("acme-a-bom") .addExtensionWithMetadata("io.acme", "ext-a", "2.2.2.downstream", Map.of("offering-a-support", List.of("supported"))) .release() .newMember("acme-b-bom") .addExtensionWithMetadata("io.acme", "ext-b", "2.2.2.downstream", Map.of("offering-b-support", List.of("supported"))) .release().stream().platform() .newStream("1.1") // 1.1.1 release .newRelease("1.1.1.downstream") .quarkusVersion("1.1.1.downstream") .upstreamQuarkusVersion("1.1.1") // default bom including quarkus-core + essential metadata .addCoreMember().release() // platform member .newMember("acme-a-bom") .addExtensionWithMetadata("io.acme", "ext-a", "1.1.1.downstream", Map.of("offering-a-support", List.of("supported"))) .release() .newMember("acme-b-bom") .addExtensionWithMetadata("io.acme", "ext-b", "1.1.1.downstream", // on purpose included in offering-a Map.of("offering-a-support", List.of("supported"))); var upstreamRegistry = registryClientBuilder.newRegistry("upstream.registry.test"); setUpstreamRegistryExtraOptions(upstreamRegistry); upstreamRegistry // platform key .newPlatform(UPSTREAM_PLATFORM_KEY) // 3.3 STREAM .newStream("3.3") // 3.3.3 release .newRelease("3.3.3") .quarkusVersion("3.3.3") // default bom including quarkus-core + essential metadata .addCoreMember().release() .newMember("acme-a-bom").addExtension("io.acme", "ext-a", "3.3.3").release() .newMember("acme-b-bom").addExtension("io.acme", "ext-b", "3.3.3").release() .stream().platform() // 2.2 STREAM .newStream("2.2") // 2.2.2 release .newRelease("2.2.2") .quarkusVersion("2.2.2") // default bom including quarkus-core + essential metadata .addCoreMember().release() .newMember("acme-a-bom").addExtension("io.acme", "ext-a", "2.2.2").release() .newMember("acme-b-bom").addExtension("io.acme", "ext-b", "2.2.2").release() .stream().platform() // 1.1 STREAM .newStream("1.1") // 1.1.1 release .newRelease("1.1.1") .quarkusVersion("1.1.1") // default bom including quarkus-core + essential metadata .addCoreMember().release() .newMember("acme-a-bom").addExtension("io.acme", "ext-a", "1.1.1").release() .newMember("acme-b-bom").addExtension("io.acme", "ext-b", "1.1.1"); registryClientBuilder.build(); enableRegistryClient(); } protected void setDownstreamRegistryExtraOptions(TestRegistryClientBuilder.TestRegistryBuilder registry) { } protected void setUpstreamRegistryExtraOptions(TestRegistryClientBuilder.TestRegistryBuilder registry) { } protected String getMainPlatformKey() { return DOWNSTREAM_PLATFORM_KEY; } }
RecommendStreamsFromScenarioBase
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/accept/DefaultApiVersionStrategiesTests.java
{ "start": 1186, "end": 4817 }
class ____ { private static final SemanticApiVersionParser parser = new SemanticApiVersionParser(); @Test void defaultVersionIsParsed() { String version = "1.2.3"; ApiVersionStrategy strategy = apiVersionStrategy(version); assertThat(strategy.getDefaultVersion()).isEqualTo(parser.parseVersion(version)); } @Test void missingRequiredVersion() { assertThatThrownBy(() -> testValidate(null, apiVersionStrategy())) .isInstanceOf(MissingApiVersionException.class) .hasMessage("400 BAD_REQUEST \"API version is required.\""); } @Test void validateSupportedVersion() { String version = "1.2"; DefaultApiVersionStrategy strategy = apiVersionStrategy(); strategy.addSupportedVersion(version); testValidate(version, strategy); } @Test void validateSupportedVersionForDefaultVersion() { String defaultVersion = "1.2"; DefaultApiVersionStrategy strategy = apiVersionStrategy(defaultVersion); testValidate(defaultVersion, strategy); } @Test void validateUnsupportedVersion() { assertThatThrownBy(() -> testValidate("1.2", apiVersionStrategy())) .isInstanceOf(InvalidApiVersionException.class) .hasMessage("400 BAD_REQUEST \"Invalid API version: '1.2.0'.\""); } @Test void validateDetectedVersion() { String version = "1.2"; DefaultApiVersionStrategy strategy = apiVersionStrategy(null, true, null); strategy.addMappedVersion(version); testValidate(version, strategy); } @Test void validateWhenDetectedVersionOff() { String version = "1.2"; DefaultApiVersionStrategy strategy = apiVersionStrategy(); strategy.addMappedVersion(version); assertThatThrownBy(() -> testValidate(version, strategy)).isInstanceOf(InvalidApiVersionException.class); } @Test void validateSupportedWithPredicate() { SemanticApiVersionParser.Version parsedVersion = parser.parseVersion("1.2"); testValidate("1.2", apiVersionStrategy(null, false, version -> version.equals(parsedVersion))); } @Test void validateUnsupportedWithPredicate() { DefaultApiVersionStrategy strategy = apiVersionStrategy(null, false, version -> version.equals("1.2")); assertThatThrownBy(() -> testValidate("1.2", strategy)).isInstanceOf(InvalidApiVersionException.class); } @Test void versionRequiredAndDefaultVersionSet() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultApiVersionStrategy( List.of(request -> request.getParameter("api-version")), new SemanticApiVersionParser(), true, "1.2", true, version -> true, null)) .withMessage("versionRequired cannot be set to true if a defaultVersion is also configured"); } private static DefaultApiVersionStrategy apiVersionStrategy() { return apiVersionStrategy(null, false, null); } private static DefaultApiVersionStrategy apiVersionStrategy(@Nullable String defaultVersion) { return apiVersionStrategy(defaultVersion, false, null); } private static DefaultApiVersionStrategy apiVersionStrategy( @Nullable String defaultVersion, boolean detectSupportedVersions, @Nullable Predicate<Comparable<?>> supportedVersionPredicate) { return new DefaultApiVersionStrategy( List.of(request -> request.getParameter("api-version")), new SemanticApiVersionParser(), null, defaultVersion, detectSupportedVersions, supportedVersionPredicate, null); } private void testValidate(@Nullable String version, DefaultApiVersionStrategy strategy) { MockHttpServletRequest request = new MockHttpServletRequest(); if (version != null) { request.setParameter("api-version", version); } strategy.resolveParseAndValidateVersion(request); } }
DefaultApiVersionStrategiesTests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/errors/UnreleasedInstanceIdException.java
{ "start": 847, "end": 997 }
class ____ extends ApiException { public UnreleasedInstanceIdException(String message) { super(message); } }
UnreleasedInstanceIdException
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java
{ "start": 3783, "end": 9681 }
class ____ extends ContainerManagerImpl { private static final Logger LOG = LoggerFactory.getLogger(DummyContainerManager.class); public DummyContainerManager(Context context, ContainerExecutor exec, DeletionService deletionContext, NodeStatusUpdater nodeStatusUpdater, NodeManagerMetrics metrics, LocalDirsHandlerService dirsHandler) { super(context, exec, deletionContext, nodeStatusUpdater, metrics, dirsHandler); getDispatcher().disableExitOnDispatchException(); } @Override @SuppressWarnings("unchecked") protected ResourceLocalizationService createResourceLocalizationService( ContainerExecutor exec, DeletionService deletionContext, Context context, NodeManagerMetrics metrics) { return new ResourceLocalizationService(getDispatcher(), exec, deletionContext, super.dirsHandler, context, metrics) { @Override public void handle(LocalizationEvent event) { switch (event.getType()) { case INIT_APPLICATION_RESOURCES: Application app = ((ApplicationLocalizationEvent) event).getApplication(); // Simulate event from ApplicationLocalization. dispatcher.getEventHandler().handle(new ApplicationInitedEvent( app.getAppId())); break; case LOCALIZE_CONTAINER_RESOURCES: ContainerLocalizationRequestEvent rsrcReqs = (ContainerLocalizationRequestEvent) event; // simulate localization of all requested resources for (Collection<LocalResourceRequest> rc : rsrcReqs .getRequestedResources().values()) { for (LocalResourceRequest req : rc) { LOG.info("DEBUG: " + req + ":" + rsrcReqs.getContainer().getContainerId()); dispatcher.getEventHandler().handle( new ContainerResourceLocalizedEvent(rsrcReqs.getContainer() .getContainerId(), req, new Path("file:///local" + req.getPath().toUri().getPath()))); } } break; case CLEANUP_CONTAINER_RESOURCES: Container container = ((ContainerLocalizationEvent) event).getContainer(); // TODO: delete the container dir this.dispatcher.getEventHandler().handle( new ContainerEvent(container.getContainerId(), ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP)); break; case DESTROY_APPLICATION_RESOURCES: Application application = ((ApplicationLocalizationEvent) event).getApplication(); // decrement reference counts of all resources associated with this // app this.dispatcher.getEventHandler().handle( new ApplicationEvent(application.getAppId(), ApplicationEventType.APPLICATION_RESOURCES_CLEANEDUP)); break; default: fail("Unexpected event: " + event.getType()); } } }; } @Override protected UserGroupInformation getRemoteUgi() throws YarnException { ApplicationId appId = ApplicationId.newInstance(0, 0); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); UserGroupInformation ugi = UserGroupInformation.createRemoteUser(appAttemptId.toString()); ugi.addTokenIdentifier(new NMTokenIdentifier(appAttemptId, getContext() .getNodeId(), "testuser", getContext().getNMTokenSecretManager().getCurrentKey() .getKeyId())); return ugi; } @Override @SuppressWarnings("unchecked") protected ContainersLauncher createContainersLauncher(Context context, ContainerExecutor exec) { return new ContainersLauncher(context, getDispatcher(), exec, super.dirsHandler, this) { @Override public void handle(ContainersLauncherEvent event) { Container container = event.getContainer(); ContainerId containerId = container.getContainerId(); switch (event.getType()) { case LAUNCH_CONTAINER: getDispatcher().getEventHandler().handle( new ContainerEvent(containerId, ContainerEventType.CONTAINER_LAUNCHED)); break; case CLEANUP_CONTAINER: getDispatcher().getEventHandler().handle( new ContainerExitEvent(containerId, ContainerEventType.CONTAINER_KILLED_ON_REQUEST, 0, "Container exited with exit code 0.")); break; } } }; } @Override protected LogHandler createLogHandler(Configuration conf, Context context, DeletionService deletionService) { return new LogHandler() { @Override public void handle(LogHandlerEvent event) { switch (event.getType()) { case APPLICATION_STARTED: break; case CONTAINER_FINISHED: break; case APPLICATION_FINISHED: break; default: // Ignore } } @Override public Set<ApplicationId> getInvalidTokenApps() { return Collections.emptySet(); } }; } @Override protected void authorizeStartAndResourceIncreaseRequest( NMTokenIdentifier nmTokenIdentifier, ContainerTokenIdentifier containerTokenIdentifier, boolean startRequest) throws YarnException { // do nothing } @Override protected void authorizeGetAndStopContainerRequest(ContainerId containerId, Container container, boolean stopRequest, NMTokenIdentifier identifier, String remoteUser) throws YarnException { // do nothing } @Override public ResourceLocalizationResponse localize( ResourceLocalizationRequest request) throws YarnException, IOException { return null; } }
DummyContainerManager
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/AllocationDecider.java
{ "start": 1001, "end": 1132 }
class ____ allows to make * dynamic cluster- or index-wide shard allocation decisions on a per-node * basis. */ public abstract
that
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/Sinks.java
{ "start": 48146, "end": 55939 }
interface ____<T> extends Scannable { /** * Try to complete the {@link Mono} without a value, generating only an {@link Subscriber#onComplete() onComplete} signal. * The result of the attempt is represented as an {@link EmitResult}, which possibly indicates error cases. * <p> * See the list of failure {@link EmitResult} in {@link #emitEmpty(EmitFailureHandler)} javadoc for an * example of how each of these can be dealt with, to decide if the emit API would be a good enough fit instead. * * @return an {@link EmitResult}, which should be checked to distinguish different possible failures * @see #emitEmpty(Sinks.EmitFailureHandler) * @see Subscriber#onComplete() */ EmitResult tryEmitEmpty(); /** * Try to fail the {@link Mono}, generating only an {@link Subscriber#onError(Throwable) onError} signal. * The result of the attempt is represented as an {@link EmitResult}, which possibly indicates error cases. * <p> * See the list of failure {@link EmitResult} in {@link #emitError(Throwable, EmitFailureHandler)} javadoc for an * example of how each of these can be dealt with, to decide if the emit API would be a good enough fit instead. * * @param error the exception to signal, not null * @return an {@link EmitResult}, which should be checked to distinguish different possible failures * @see #emitError(Throwable, Sinks.EmitFailureHandler) * @see Subscriber#onError(Throwable) */ EmitResult tryEmitError(Throwable error); /** * A simplified attempt at completing via the {@link #tryEmitEmpty()} API, generating an * {@link Subscriber#onComplete() onComplete} signal. * If the result of the attempt is not a {@link EmitResult#isSuccess() success}, implementations SHOULD retry the * {@link #tryEmitEmpty()} call IF the provided {@link EmitFailureHandler} returns {@code true}. * Otherwise, failures are dealt with in a predefined way that might depend on the actual sink implementation * (see below for the vanilla reactor-core behavior). * <p> * Generally, {@link #tryEmitEmpty()} is preferable since it allows a custom handling * of error cases, although this implies checking the returned {@link EmitResult} and correctly * acting on it. This API is intended as a good default for convenience. * <p> * When the {@link EmitResult} is not a success, vanilla reactor-core operators have the following behavior: * <ul> * <li> * {@link EmitResult#FAIL_OVERFLOW}: irrelevant as onComplete is not driven by backpressure. * </li> * <li> * {@link EmitResult#FAIL_ZERO_SUBSCRIBER}: the completion can be ignored since nobody is listening. * Note that most vanilla reactor sinks never trigger this result for onComplete, replaying the * terminal signal to later subscribers instead (to the exception of {@link UnicastSpec#onBackpressureError()}). * </li> * <li> * {@link EmitResult#FAIL_CANCELLED}: the completion can be ignored since nobody is interested. * </li> * <li> * {@link EmitResult#FAIL_TERMINATED}: the extra completion is basically ignored since there was a previous * termination signal, but there is nothing interesting to log. * </li> * <li> * {@link EmitResult#FAIL_NON_SERIALIZED}: throw an {@link EmissionException} mentioning RS spec rule 1.3. * Note that {@link Sinks#unsafe()} never trigger this result. It would be possible for an {@link EmitFailureHandler} * to busy-loop and optimistically wait for the contention to disappear to avoid this case in safe sinks... * </li> * </ul> * <p> * Might throw an unchecked exception as a last resort (eg. in case of a fatal error downstream which cannot * be propagated to any asynchronous handler, a bubbling exception, a {@link EmitResult#FAIL_NON_SERIALIZED} * as described above, ...). * * @param failureHandler the failure handler that allows retrying failed {@link EmitResult}. * @throws EmissionException on non-serialized access * @see #tryEmitEmpty() * @see Subscriber#onComplete() */ void emitEmpty(EmitFailureHandler failureHandler); /** * A simplified attempt at failing the sequence via the {@link #tryEmitError(Throwable)} API, generating an * {@link Subscriber#onError(Throwable) onError} signal. * If the result of the attempt is not a {@link EmitResult#isSuccess() success}, implementations SHOULD retry the * {@link #tryEmitError(Throwable)} call IF the provided {@link EmitFailureHandler} returns {@code true}. * Otherwise, failures are dealt with in a predefined way that might depend on the actual sink implementation * (see below for the vanilla reactor-core behavior). * <p> * Generally, {@link #tryEmitError(Throwable)} is preferable since it allows a custom handling * of error cases, although this implies checking the returned {@link EmitResult} and correctly * acting on it. This API is intended as a good default for convenience. * <p> * When the {@link EmitResult} is not a success, vanilla reactor-core operators have the following behavior: * <ul> * <li> * {@link EmitResult#FAIL_OVERFLOW}: irrelevant as onError is not driven by backpressure. * </li> * <li> * {@link EmitResult#FAIL_ZERO_SUBSCRIBER}: the error is ignored since nobody is listening. Note that most vanilla reactor sinks * never trigger this result for onError, replaying the terminal signal to later subscribers instead * (to the exception of {@link UnicastSpec#onBackpressureError()}). * </li> * <li> * {@link EmitResult#FAIL_CANCELLED}: the error can be ignored since nobody is interested. * </li> * <li> * {@link EmitResult#FAIL_TERMINATED}: the error unexpectedly follows another terminal signal, so it is * dropped via {@link Operators#onErrorDropped(Throwable, Context)}. * </li> * <li> * {@link EmitResult#FAIL_NON_SERIALIZED}: throw an {@link EmissionException} mentioning RS spec rule 1.3. * Note that {@link Sinks#unsafe()} never trigger this result. It would be possible for an {@link EmitFailureHandler} * to busy-loop and optimistically wait for the contention to disappear to avoid this case in safe sinks... * </li> * </ul> * <p> * Might throw an unchecked exception as a last resort (eg. in case of a fatal error downstream which cannot * be propagated to any asynchronous handler, a bubbling exception, a {@link EmitResult#FAIL_NON_SERIALIZED} * as described above, ...). * * @param error the exception to signal, not null * @param failureHandler the failure handler that allows retrying failed {@link EmitResult}. * @throws EmissionException on non-serialized access * @see #tryEmitError(Throwable) * @see Subscriber#onError(Throwable) */ void emitError(Throwable error, EmitFailureHandler failureHandler); /** * Get how many {@link Subscriber Subscribers} are currently subscribed to the sink. * <p> * This is a best effort peek at the sink state, and a subsequent attempt at emitting * to the sink might still return {@link EmitResult#FAIL_ZERO_SUBSCRIBER} where relevant. * Request (and lack thereof) isn't taken into account, all registered subscribers are counted. * * @return the number of active subscribers at the time of invocation */ int currentSubscriberCount(); /** * Return a {@link Mono} view of this sink. Every call returns the same instance. * * @return the {@link Mono} view associated to this {@link Sinks.One} */ Mono<T> asMono(); } /** * A base
Empty
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/ParallelExecutionConfigurationStrategy.java
{ "start": 703, "end": 984 }
interface ____ { /** * Create a configuration for parallel test execution based on the supplied * {@link ConfigurationParameters}. */ ParallelExecutionConfiguration createConfiguration(ConfigurationParameters configurationParameters); }
ParallelExecutionConfigurationStrategy
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java
{ "start": 16602, "end": 16769 }
class ____ { private void doIt() { String s1 = ""; final String s2 = ""; String s3 = "";
Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java
{ "start": 707, "end": 2979 }
class ____ implements TableJoin, PredicateContainer, DomainResultProducer { private final NavigablePath navigablePath; private final TableGroup joinedGroup; private SqlAstJoinType joinType; private Predicate predicate; public TableGroupJoin( NavigablePath navigablePath, SqlAstJoinType joinType, TableGroup joinedGroup) { this( navigablePath, joinType, joinedGroup, null ); } public TableGroupJoin( NavigablePath navigablePath, SqlAstJoinType joinType, TableGroup joinedGroup, Predicate predicate) { assert !joinedGroup.isLateral() || ( joinType == SqlAstJoinType.INNER || joinType == SqlAstJoinType.LEFT || joinType == SqlAstJoinType.CROSS ) : "Lateral is only allowed with inner, left or cross joins"; this.navigablePath = navigablePath; this.joinType = joinType; this.joinedGroup = joinedGroup; this.predicate = predicate; } @Override public SqlAstJoinType getJoinType() { return joinType; } public void setJoinType(SqlAstJoinType joinType) { // SqlTreeCreationLogger.LOGGER.tracef( // "Adjusting join-type for TableGroupJoin(%s) : %s -> %s", // navigablePath, // this.joinType, // joinType // ); this.joinType = joinType; } public TableGroup getJoinedGroup() { return joinedGroup; } @Override public SqlAstNode getJoinedNode() { return joinedGroup; } @Override public Predicate getPredicate() { return predicate; } @Override public void applyPredicate(Predicate predicate) { this.predicate = SqlAstTreeHelper.combinePredicates( this.predicate, predicate ); } @Override public void accept(SqlAstWalker sqlTreeWalker) { sqlTreeWalker.visitTableGroupJoin( this ); } @Override public boolean isInitialized() { return joinedGroup.isInitialized(); } public NavigablePath getNavigablePath() { return navigablePath; } public boolean isImplicit() { return !navigablePath.isAliased(); } @Override public DomainResult createDomainResult( String resultVariable, DomainResultCreationState creationState) { return getJoinedGroup().createDomainResult( resultVariable, creationState ); } @Override public void applySqlSelections(DomainResultCreationState creationState) { getJoinedGroup().applySqlSelections( creationState ); } }
TableGroupJoin
java
google__guava
android/guava/src/com/google/common/graph/AbstractValueGraph.java
{ "start": 1295, "end": 4104 }
class ____<N, V> extends AbstractBaseGraph<N> implements ValueGraph<N, V> { /** Constructor for use by subclasses. */ public AbstractValueGraph() {} @Override public Graph<N> asGraph() { return new AbstractGraph<N>() { @Override public Set<N> nodes() { return AbstractValueGraph.this.nodes(); } @Override public Set<EndpointPair<N>> edges() { return AbstractValueGraph.this.edges(); } @Override public boolean isDirected() { return AbstractValueGraph.this.isDirected(); } @Override public boolean allowsSelfLoops() { return AbstractValueGraph.this.allowsSelfLoops(); } @Override public ElementOrder<N> nodeOrder() { return AbstractValueGraph.this.nodeOrder(); } @Override public ElementOrder<N> incidentEdgeOrder() { return AbstractValueGraph.this.incidentEdgeOrder(); } @Override public Set<N> adjacentNodes(N node) { return AbstractValueGraph.this.adjacentNodes(node); } @Override public Set<N> predecessors(N node) { return AbstractValueGraph.this.predecessors(node); } @Override public Set<N> successors(N node) { return AbstractValueGraph.this.successors(node); } @Override public int degree(N node) { return AbstractValueGraph.this.degree(node); } @Override public int inDegree(N node) { return AbstractValueGraph.this.inDegree(node); } @Override public int outDegree(N node) { return AbstractValueGraph.this.outDegree(node); } }; } @Override public final boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (!(obj instanceof ValueGraph)) { return false; } ValueGraph<?, ?> other = (ValueGraph<?, ?>) obj; return isDirected() == other.isDirected() && nodes().equals(other.nodes()) && edgeValueMap(this).equals(edgeValueMap(other)); } @Override public final int hashCode() { return edgeValueMap(this).hashCode(); } /** Returns a string representation of this graph. */ @Override public String toString() { return "isDirected: " + isDirected() + ", allowsSelfLoops: " + allowsSelfLoops() + ", nodes: " + nodes() + ", edges: " + edgeValueMap(this); } private static <N, V> Map<EndpointPair<N>, V> edgeValueMap(ValueGraph<N, V> graph) { return Maps.asMap( graph.edges(), edge -> // requireNonNull is safe because the endpoint pair comes from the graph. requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null))); } }
AbstractValueGraph
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/client/DefaultConsumerIdsChangeListener.java
{ "start": 1555, "end": 6545 }
class ____ implements ConsumerIdsChangeListener { private static final Logger log = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private final int cacheSize = 8096; private final ScheduledExecutorService scheduledExecutorService = ThreadUtils.newScheduledThreadPool(1, ThreadUtils.newGenericThreadFactory("DefaultConsumerIdsChangeListener", true)); private ConcurrentHashMap<String,List<Channel>> consumerChannelMap = new ConcurrentHashMap<>(cacheSize); private final ConcurrentHashMap<String, NotifyTaskControl> activeGroupNotifyMap = new ConcurrentHashMap<>(); public DefaultConsumerIdsChangeListener(BrokerController brokerController) { this.brokerController = brokerController; scheduledExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(brokerController.getBrokerConfig()) { @Override public void run0() { try { notifyConsumerChange(); } catch (Exception e) { log.error( "DefaultConsumerIdsChangeListen#notifyConsumerChange: unexpected error occurs", e); } } }, 30, 15, TimeUnit.SECONDS); } @Override public void handle(ConsumerGroupEvent event, String group, Object... args) { if (event == null) { return; } switch (event) { case CHANGE: if (args == null || args.length < 1) { return; } List<Channel> channels = (List<Channel>) args[0]; if (channels != null && brokerController.getBrokerConfig().isNotifyConsumerIdsChangedEnable()) { if (this.brokerController.getBrokerConfig().isRealTimeNotifyConsumerChange()) { NotifyTaskControl currentNotifyTaskControl = new NotifyTaskControl(channels); activeGroupNotifyMap.compute(group, (k, oldVal) -> { if (null != oldVal) { oldVal.interrupt(); } return currentNotifyTaskControl; }); boolean isNormalCompletion = true; for (Channel chl : currentNotifyTaskControl.getChannels()) { if (currentNotifyTaskControl.isInterrupted()) { isNormalCompletion = false; break; } this.brokerController.getBroker2Client().notifyConsumerIdsChanged(chl, group); } if (isNormalCompletion) { activeGroupNotifyMap.computeIfPresent(group, (k, val) -> val == currentNotifyTaskControl ? null : val); } } else { consumerChannelMap.put(group, channels); } } break; case UNREGISTER: this.brokerController.getConsumerFilterManager().unRegister(group); break; case REGISTER: if (args == null || args.length < 1) { return; } Collection<SubscriptionData> subscriptionDataList = (Collection<SubscriptionData>) args[0]; this.brokerController.getConsumerFilterManager().register(group, subscriptionDataList); break; case CLIENT_REGISTER: case CLIENT_UNREGISTER: break; default: throw new RuntimeException("Unknown event " + event); } } private void notifyConsumerChange() { if (consumerChannelMap.isEmpty()) { return; } ConcurrentHashMap<String, List<Channel>> processMap = new ConcurrentHashMap<>(consumerChannelMap); consumerChannelMap = new ConcurrentHashMap<>(cacheSize); for (Map.Entry<String, List<Channel>> entry : processMap.entrySet()) { String consumerId = entry.getKey(); List<Channel> channelList = entry.getValue(); try { if (channelList != null && brokerController.getBrokerConfig().isNotifyConsumerIdsChangedEnable()) { for (Channel chl : channelList) { this.brokerController.getBroker2Client().notifyConsumerIdsChanged(chl, consumerId); } } } catch (Exception e) { log.error("Failed to notify consumer when some consumers changed, consumerId to notify: {}", consumerId, e); } } } @Override public void shutdown() { this.scheduledExecutorService.shutdown(); } private static
DefaultConsumerIdsChangeListener
java
grpc__grpc-java
testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java
{ "start": 8144, "end": 9174 }
class ____ extends TagContext { private static final FakeTagContext EMPTY = new FakeTagContext(ImmutableMap.<TagKey, TagValue>of()); private static final TagMetadata METADATA_PROPAGATING = TagMetadata.create(TagTtl.UNLIMITED_PROPAGATION); private final ImmutableMap<TagKey, TagValue> tags; private FakeTagContext(ImmutableMap<TagKey, TagValue> tags) { this.tags = tags; } public ImmutableMap<TagKey, TagValue> getTags() { return tags; } @Override public String toString() { return "[tags=" + tags + "]"; } @Override protected Iterator<Tag> getIterator() { return Iterators.transform( tags.entrySet().iterator(), new Function<Map.Entry<TagKey, TagValue>, Tag>() { @Override public Tag apply(@Nullable Map.Entry<TagKey, TagValue> entry) { return Tag.create(entry.getKey(), entry.getValue(), METADATA_PROPAGATING); } }); } } public static
FakeTagContext
java
apache__spark
sql/core/src/main/java/org/apache/spark/sql/execution/vectorized/Dictionary.java
{ "start": 865, "end": 954 }
interface ____ dictionary in ColumnVector to decode dictionary encoded values. */ public
for
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/file/NestedRootJarResolverTest.java
{ "start": 1067, "end": 2745 }
class ____ extends FileResolverTestBase { @Override protected ClassLoader resourcesLoader(File baseDir) throws Exception { File nestedFiles = Files.createTempFile(TestUtils.MAVEN_TARGET_DIR.toPath(), "", "nestedroot.jar").toFile(); Assert.assertTrue(nestedFiles.delete()); ZipFileResolverTest.getFiles(baseDir, nestedFiles, new Function<OutputStream, ZipOutputStream>() { @Override public ZipOutputStream apply(OutputStream outputStream) { ZipOutputStream zip = new ZipOutputStream(outputStream); try { zip.putNextEntry(new ZipEntry("nested-inf/classes/")); zip.closeEntry(); } catch (IOException e) { throw new AssertionFailedError(); } return zip; } }, name -> new ZipEntry("nested-inf/classes/" + name)); URL webrootURL = nestedFiles.toURI().toURL(); return new ClassLoader(Thread.currentThread().getContextClassLoader()) { @Override public URL getResource(String name) { try { if (name.equals("nested-inf/classes")) { return new URL("jar:" + webrootURL + "!/nested-inf/classes"); } else if (name.startsWith("webroot")) { return new URL("jar:" + webrootURL + "!/nested-inf/classes!/" + name); } else if (name.equals("afile.html") || name.equals("afile with spaces.html") || name.equals("afilewithspaceatend ")) { return new URL("jar:" + webrootURL + "!/nested-inf/classes!/" + name); } } catch (MalformedURLException e) { throw new AssertionError(e); } return super.getResource(name); } }; } }
NestedRootJarResolverTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/CompositeRuntimeFieldTests.java
{ "start": 1231, "end": 21231 }
class ____ extends MapperServiceTestCase { @Override @SuppressWarnings("unchecked") protected <T> T compileScript(Script script, ScriptContext<T> context) { if (context == CompositeFieldScript.CONTEXT) { return (T) (CompositeFieldScript.Factory) (fieldName, params, searchLookup, onScriptError) -> ctx -> new CompositeFieldScript( fieldName, params, searchLookup, OnScriptError.FAIL, ctx ) { @Override public void execute() { if (script.getIdOrCode().equals("split-str-long")) { List<Object> values = extractFromSource("field"); String input = values.get(0).toString(); String[] parts = input.split(" "); emit("str", parts[0]); emit("long", parts[1]); } } }; } if (context == LongFieldScript.CONTEXT) { return (T) (LongFieldScript.Factory) (field, params, lookup, onScriptError) -> ctx -> new LongFieldScript( field, params, lookup, OnScriptError.FAIL, ctx ) { @Override public void execute() { } }; } throw new UnsupportedOperationException("Unknown context " + context.name); } public void testObjectDefinition() throws IOException { MapperService mapperService = createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.startObject("script").field("source", "dummy").endObject(); b.startObject("fields"); b.startObject("long-subfield").field("type", "long").endObject(); b.startObject("str-subfield").field("type", "keyword").endObject(); b.startObject("double-subfield").field("type", "double").endObject(); b.startObject("boolean-subfield").field("type", "boolean").endObject(); b.startObject("ip-subfield").field("type", "ip").endObject(); b.startObject("geopoint-subfield").field("type", "geo_point").endObject(); b.endObject(); b.endObject(); b.endObject(); })); assertNull(mapperService.mappingLookup().getFieldType("obj")); assertNull(mapperService.mappingLookup().getFieldType("long-subfield")); assertNull(mapperService.mappingLookup().getFieldType("str-subfield")); assertNull(mapperService.mappingLookup().getFieldType("double-subfield")); assertNull(mapperService.mappingLookup().getFieldType("boolean-subfield")); assertNull(mapperService.mappingLookup().getFieldType("ip-subfield")); assertNull(mapperService.mappingLookup().getFieldType("geopoint-subfield")); assertNull(mapperService.mappingLookup().getFieldType("obj.any-subfield")); MappedFieldType longSubfield = mapperService.mappingLookup().getFieldType("obj.long-subfield"); assertEquals("obj.long-subfield", longSubfield.name()); assertEquals("long", longSubfield.typeName()); MappedFieldType strSubfield = mapperService.mappingLookup().getFieldType("obj.str-subfield"); assertEquals("obj.str-subfield", strSubfield.name()); assertEquals("keyword", strSubfield.typeName()); MappedFieldType doubleSubfield = mapperService.mappingLookup().getFieldType("obj.double-subfield"); assertEquals("obj.double-subfield", doubleSubfield.name()); assertEquals("double", doubleSubfield.typeName()); MappedFieldType booleanSubfield = mapperService.mappingLookup().getFieldType("obj.boolean-subfield"); assertEquals("obj.boolean-subfield", booleanSubfield.name()); assertEquals("boolean", booleanSubfield.typeName()); MappedFieldType ipSubfield = mapperService.mappingLookup().getFieldType("obj.ip-subfield"); assertEquals("obj.ip-subfield", ipSubfield.name()); assertEquals("ip", ipSubfield.typeName()); MappedFieldType geoPointSubfield = mapperService.mappingLookup().getFieldType("obj.geopoint-subfield"); assertEquals("obj.geopoint-subfield", geoPointSubfield.name()); assertEquals("geo_point", geoPointSubfield.typeName()); RuntimeField rf = mapperService.mappingLookup().getMapping().getRoot().getRuntimeField("obj"); assertEquals("obj", rf.name()); Collection<MappedFieldType> mappedFieldTypes = rf.asMappedFieldTypes().toList(); for (MappedFieldType mappedFieldType : mappedFieldTypes) { if (mappedFieldType.name().equals("obj.long-subfield")) { assertSame(longSubfield, mappedFieldType); } else if (mappedFieldType.name().equals("obj.str-subfield")) { assertSame(strSubfield, mappedFieldType); } else if (mappedFieldType.name().equals("obj.double-subfield")) { assertSame(doubleSubfield, mappedFieldType); } else if (mappedFieldType.name().equals("obj.boolean-subfield")) { assertSame(booleanSubfield, mappedFieldType); } else if (mappedFieldType.name().equals("obj.ip-subfield")) { assertSame(ipSubfield, mappedFieldType); } else if (mappedFieldType.name().equals("obj.geopoint-subfield")) { assertSame(geoPointSubfield, mappedFieldType); } else { fail("unexpected subfield [" + mappedFieldType.name() + "]"); } } } public void testUnsupportedLeafType() { Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.startObject("script").field("source", "dummy").endObject(); b.startObject("fields"); b.startObject("long-subfield").field("type", "unsupported").endObject(); b.endObject(); b.endObject(); b.endObject(); }))); assertThat(e.getMessage(), containsString("")); } public void testToXContent() throws IOException { MapperService mapperService = createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("message"); b.field("type", "composite"); b.field("script", "dummy"); b.startObject("meta").field("test-meta", "value").endObject(); b.startObject("fields").startObject("response").field("type", "long").endObject().endObject(); b.endObject(); b.endObject(); })); assertEquals( """ {"_doc":{"runtime":{"message":{"type":"composite","meta":{"test-meta":"value"},\ "script":{"source":"dummy","lang":"painless"},"fields":{"response":{"type":"long"}}}}}}""", Strings.toString(mapperService.mappingLookup().getMapping()) ); } public void testScriptOnSubFieldThrowsError() { Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(runtimeMapping(b -> { b.startObject("obj"); b.field("type", "composite"); b.field("script", "dummy"); b.startObject("fields"); b.startObject("long").field("type", "long").field("script", "dummy").endObject(); b.endObject(); b.endObject(); }))); assertThat(e.getMessage(), containsString("Cannot use [script] parameter on sub-field [long] of composite field [obj]")); } public void testObjectWithoutScript() { Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(runtimeMapping(b -> { b.startObject("obj"); b.field("type", "composite"); b.startObject("fields"); b.startObject("long").field("type", "long").endObject(); b.endObject(); b.endObject(); }))); assertThat(e.getMessage(), containsString("composite runtime field [obj] must declare a [script]")); } public void testObjectNullScript() { Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(runtimeMapping(b -> { b.startObject("obj"); b.field("type", "composite"); b.nullField("script"); b.startObject("fields"); b.startObject("long").field("type", "long").endObject(); b.endObject(); b.endObject(); }))); assertThat(e.getMessage(), containsString(" [script] on runtime field [obj] of type [composite] must not have a [null] value")); } public void testObjectWithoutFields() { { Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(runtimeMapping(b -> { b.startObject("obj"); b.field("type", "composite"); b.field("script", "dummy"); b.endObject(); }))); assertThat(e.getMessage(), containsString("composite runtime field [obj] must declare its [fields]")); } { Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(runtimeMapping(b -> { b.startObject("obj"); b.field("type", "composite"); b.field("script", "dummy"); b.startObject("fields").endObject(); b.endObject(); }))); assertThat(e.getMessage(), containsString("composite runtime field [obj] must declare its [fields]")); } } public void testMappingUpdate() throws IOException { MapperService mapperService = createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.startObject("script").field("source", "dummy").endObject(); b.startObject("fields"); b.startObject("long-subfield").field("type", "long").endObject(); b.startObject("str-subfield").field("type", "keyword").endObject(); b.endObject(); b.endObject(); b.endObject(); })); XContentBuilder b = XContentBuilder.builder(XContentType.JSON.xContent()); b.startObject(); b.startObject("_doc"); b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.startObject("script").field("source", "dummy2").endObject(); b.startObject("fields"); b.startObject("double-subfield").field("type", "double").endObject(); b.endObject(); b.endObject(); b.endObject(); b.endObject(); b.endObject(); merge(mapperService, b); assertNull(mapperService.mappingLookup().getFieldType("obj.long-subfield")); assertNull(mapperService.mappingLookup().getFieldType("obj.str-subfield")); MappedFieldType doubleSubField = mapperService.mappingLookup().getFieldType("obj.double-subfield"); assertEquals("obj.double-subfield", doubleSubField.name()); assertEquals("double", doubleSubField.typeName()); RuntimeField rf = mapperService.mappingLookup().getMapping().getRoot().getRuntimeField("obj"); assertEquals("obj", rf.name()); Collection<MappedFieldType> mappedFieldTypes = rf.asMappedFieldTypes().toList(); assertEquals(1, mappedFieldTypes.size()); assertSame(doubleSubField, mappedFieldTypes.iterator().next()); assertEquals(""" {"obj":{"type":"composite","script":{"source":"dummy2","lang":"painless"},\ "fields":{"double-subfield":{"type":"double"}}}}""", Strings.toString(rf)); } public void testFieldDefinedTwiceWithSameName() throws IOException { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj.long-subfield").field("type", "long").endObject(); b.startObject("obj"); b.field("type", "composite"); b.startObject("script").field("source", "dummy").endObject(); b.startObject("fields"); b.startObject("long-subfield").field("type", "long").endObject(); b.endObject(); b.endObject(); b.endObject(); }))); assertThat(e.getMessage(), containsString("Found two runtime fields with same name [obj.long-subfield]")); MapperService mapperService = createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj.str-subfield").field("type", "long").endObject(); b.startObject("obj"); b.field("type", "composite"); b.startObject("script").field("source", "dummy").endObject(); b.startObject("fields"); b.startObject("long-subfield").field("type", "long").endObject(); b.endObject(); b.endObject(); b.endObject(); })); XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); builder.startObject(); builder.startObject("_doc"); builder.startObject("runtime"); builder.startObject("obj.long-subfield").field("type", "long").endObject(); builder.endObject(); builder.endObject(); builder.endObject(); IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> merge(mapperService, builder)); assertThat(iae.getMessage(), containsString("Found two runtime fields with same name [obj.long-subfield]")); } public void testParseDocumentSubFieldAccess() throws IOException { MapperService mapperService = createMapperService(topMapping(b -> { b.field("dynamic", false); b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.field("script", "split-str-long"); b.startObject("fields"); b.startObject("str").field("type", "keyword").endObject(); b.startObject("long").field("type", "long").endObject(); b.endObject(); b.endObject(); b.endObject(); })); ParsedDocument doc1 = mapperService.documentMapper().parse(source(b -> b.field("field", "foo 1"))); ParsedDocument doc2 = mapperService.documentMapper().parse(source(b -> b.field("field", "bar 2"))); withLuceneIndex(mapperService, iw -> iw.addDocuments(Arrays.asList(doc1.rootDoc(), doc2.rootDoc())), reader -> { SearchLookup searchLookup = new SearchLookup( mapperService::fieldType, (mft, lookupSupplier, fdo) -> mft.fielddataBuilder( new FieldDataContext("test", null, lookupSupplier, mapperService.mappingLookup()::sourcePaths, fdo) ).build(null, null), SourceProvider.fromLookup(mapperService.mappingLookup(), null, mapperService.getMapperMetrics().sourceFieldMetrics()) ); LeafSearchLookup leafSearchLookup = searchLookup.getLeafSearchLookup(reader.leaves().get(0)); leafSearchLookup.setDocument(0); assertEquals("foo", leafSearchLookup.doc().get("obj.str").get(0)); assertEquals(1L, leafSearchLookup.doc().get("obj.long").get(0)); leafSearchLookup.setDocument(1); assertEquals("bar", leafSearchLookup.doc().get("obj.str").get(0)); assertEquals(2L, leafSearchLookup.doc().get("obj.long").get(0)); }); } public void testParseDocumentDynamicMapping() throws IOException { MapperService mapperService = createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.field("script", "dummy"); b.startObject("fields"); b.startObject("str").field("type", "keyword").endObject(); b.startObject("long").field("type", "long").endObject(); b.endObject(); b.endObject(); b.endObject(); })); ParsedDocument doc1 = mapperService.documentMapper().parse(source(b -> b.field("obj.long", 1L).field("obj.str", "value"))); assertNull(doc1.rootDoc().get("obj.long")); assertNull(doc1.rootDoc().get("obj.str")); assertNull(mapperService.mappingLookup().getMapper("obj.long")); assertNull(mapperService.mappingLookup().getMapper("obj.str")); assertNotNull(mapperService.mappingLookup().getFieldType("obj.long")); assertNotNull(mapperService.mappingLookup().getFieldType("obj.str")); XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); builder.startObject(); builder.startObject("_doc"); builder.startObject("properties"); builder.startObject("obj"); builder.startObject("properties"); builder.startObject("long").field("type", "long").endObject(); builder.endObject(); builder.endObject(); builder.endObject(); builder.endObject(); builder.endObject(); merge(mapperService, builder); ParsedDocument doc2 = mapperService.documentMapper().parse(source(b -> b.field("obj.long", 2L))); assertNotNull(doc2.rootDoc().get("obj.long")); assertNull(doc2.rootDoc().get("obj.str")); assertNotNull(mapperService.mappingLookup().getMapper("obj.long")); assertNull(mapperService.mappingLookup().getMapper("obj.str")); assertNotNull(mapperService.mappingLookup().getFieldType("obj.long")); assertNotNull(mapperService.mappingLookup().getFieldType("obj.str")); } public void testParseDocumentSubfieldsOutsideRuntimeObject() throws IOException { MapperService mapperService = createMapperService(topMapping(b -> { b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.field("script", "dummy"); b.startObject("fields"); b.startObject("long").field("type", "long").endObject(); b.endObject(); b.endObject(); b.endObject(); })); ParsedDocument doc1 = mapperService.documentMapper().parse(source(b -> b.field("obj.long", 1L).field("obj.bool", true))); assertNull(doc1.rootDoc().get("obj.long")); assertNotNull(doc1.rootDoc().get("obj.bool")); assertEquals(""" {"_doc":{"properties":{"obj":{"properties":{"bool":{"type":"boolean"}}}}}}""", Strings.toString(doc1.dynamicMappingsUpdate())); MapperService mapperService2 = createMapperService(topMapping(b -> { b.field("dynamic", "runtime"); b.startObject("runtime"); b.startObject("obj"); b.field("type", "composite"); b.field("script", "dummy"); b.startObject("fields"); b.startObject("long").field("type", "long").endObject(); b.endObject(); b.endObject(); b.endObject(); })); ParsedDocument doc2 = mapperService2.documentMapper().parse(source(b -> b.field("obj.long", 1L).field("obj.bool", true))); assertNull(doc2.rootDoc().get("obj.long")); assertNull(doc2.rootDoc().get("obj.bool")); assertEquals(""" {"_doc":{"dynamic":"runtime","runtime":{"obj.bool":{"type":"boolean"}}}}""", Strings.toString(doc2.dynamicMappingsUpdate())); } }
CompositeRuntimeFieldTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.java
{ "start": 10673, "end": 11035 }
class ____ { private int a; @Override public boolean equals(Object other) { boolean isEqual = other instanceof IntermediateBooleanVariable; if (isEqual) { IntermediateBooleanVariable that = (IntermediateBooleanVariable) other; return that.a == a; } return isEqual; } } private
IntermediateBooleanVariable
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/BackgroundBootstrapTests.java
{ "start": 8116, "end": 9265 }
class ____ { @Bean public TestBean testBean1(ObjectProvider<TestBean> testBean3, ObjectProvider<TestBean> testBean4) { new Thread(testBean3::getObject).start(); new Thread(testBean4::getObject).start(); new Thread(testBean3::getObject).start(); new Thread(testBean4::getObject).start(); try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return new TestBean(); } @Bean public TestBean testBean2(TestBean testBean4) { return new TestBean(testBean4); } @Bean public TestBean testBean3(TestBean testBean4) { return new TestBean(testBean4); } @Bean public FactoryBean<TestBean> testBean4() { try { Thread.sleep(2000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } TestBean testBean = new TestBean(); return new FactoryBean<>() { @Override public TestBean getObject() { return testBean; } @Override public Class<?> getObjectType() { return testBean.getClass(); } }; } } @Configuration(proxyBeanMethods = false) static
UnmanagedThreadsBeanConfig
java
apache__dubbo
dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java
{ "start": 8572, "end": 8602 }
class ____ been reject } }
has
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_5.java
{ "start": 1293, "end": 1504 }
class ____ { @JSONField(ordinal = 1) public int id; @JSONField(unwrapped = true, ordinal = 2) public Map<String, Object> details = new LinkedHashMap<String, Object>(); } }
Health
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/ComponentValidator.java
{ "start": 4786, "end": 6589 }
class ____ implements ClearableCache { private final ModuleValidator moduleValidator; private final ComponentCreatorValidator creatorValidator; private final DependencyRequestValidator dependencyRequestValidator; private final MembersInjectionValidator membersInjectionValidator; private final MethodSignatureFormatter methodSignatureFormatter; private final DependencyRequestFactory dependencyRequestFactory; private final DaggerSuperficialValidation superficialValidation; private final Map<XTypeElement, ValidationReport> reports = new HashMap<>(); @Inject ComponentValidator( ModuleValidator moduleValidator, ComponentCreatorValidator creatorValidator, DependencyRequestValidator dependencyRequestValidator, MembersInjectionValidator membersInjectionValidator, MethodSignatureFormatter methodSignatureFormatter, DependencyRequestFactory dependencyRequestFactory, DaggerSuperficialValidation superficialValidation) { this.moduleValidator = moduleValidator; this.creatorValidator = creatorValidator; this.dependencyRequestValidator = dependencyRequestValidator; this.membersInjectionValidator = membersInjectionValidator; this.methodSignatureFormatter = methodSignatureFormatter; this.dependencyRequestFactory = dependencyRequestFactory; this.superficialValidation = superficialValidation; } @Override public void clearCache() { reports.clear(); } /** Validates the given component. */ public ValidationReport validate(XTypeElement component) { return reentrantComputeIfAbsent(reports, component, this::validateUncached); } private ValidationReport validateUncached(XTypeElement component) { return new ElementValidator(component).validateElement(); } private
ComponentValidator
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 147018, "end": 147207 }
class ____ {}"); JavaFileObject thread = JavaFileObjects.forSourceLines( "foo.bar.Thread", // "package foo.bar;", "", "public
Integer
java
apache__camel
components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcParameterizedQueryGeneratedKeysTest.java
{ "start": 983, "end": 2421 }
class ____ extends AbstractJdbcGeneratedKeysTest { private static final Map<String, Object> VALUE_MAP; static { VALUE_MAP = new HashMap<>(); VALUE_MAP.put("value", "testValue"); } @Test public void testRetrieveGeneratedKeys() { super.testRetrieveGeneratedKeys("insert into tableWithAutoIncr (content) values (:?value)", VALUE_MAP); } @Test public void testRetrieveGeneratedKeysWithStringGeneratedColumns() { super.testRetrieveGeneratedKeysWithStringGeneratedColumns("insert into tableWithAutoIncr (content) values (:?value)", VALUE_MAP); } @Test public void testRetrieveGeneratedKeysWithIntGeneratedColumns() { super.testRetrieveGeneratedKeysWithIntGeneratedColumns("insert into tableWithAutoIncr (content) values (:?value)", VALUE_MAP); } @Test public void testGivenAnInvalidGeneratedColumnsHeaderThenAnExceptionIsThrown() { super.testGivenAnInvalidGeneratedColumnsHeaderThenAnExceptionIsThrown( "insert into tableWithAutoIncr (content) values (:?value)", VALUE_MAP); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:hello").to("jdbc:testdb?useHeadersAsParameters=true&readSize=100"); } }; } }
JdbcParameterizedQueryGeneratedKeysTest
java
apache__camel
components/camel-graphql/src/test/java/org/apache/camel/component/graphql/server/GraphqlServer.java
{ "start": 2270, "end": 4162 }
class ____ implements HttpRequestHandler { private final ObjectMapper objectMapper = new ObjectMapper(); @SuppressWarnings("unchecked") public void handle(ClassicHttpRequest request, ClassicHttpResponse response, HttpContext context) throws HttpException, IOException { HttpEntity entity = request.getEntity(); Header h = request.getHeader("kaboom"); if (h != null) { response.setCode(500); response.setReasonPhrase("Forced error due to kaboom"); return; } String json = EntityUtils.toString(entity); Map<String, Object> map = jsonToMap(json); String query = (String) map.get("query"); String operationName = (String) map.get("operationName"); Map<String, Object> variables = (Map<String, Object>) map.get("variables"); ExecutionInput executionInput = ExecutionInput.newExecutionInput() .query(query) .operationName(operationName) .variables(variables) .build(); ExecutionResult executionResult = graphql.execute(executionInput); Map<String, Object> resultMap = executionResult.toSpecification(); String result = objectMapper.writeValueAsString(resultMap); h = request.getHeader("foo"); if (h != null) { response.setHeader("bar", "response-" + h.getValue()); } response.setHeader("Content-Type", "application/json; charset=UTF-8"); response.setEntity(new StringEntity(result)); } private Map<String, Object> jsonToMap(String json) throws IOException { return objectMapper.readValue(json, new TypeReference<>() { }); } } }
GraphqlHandler
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/aot/generate/GeneratedFilesTests.java
{ "start": 1800, "end": 9019 }
class ____ { private final TestGeneratedFiles generatedFiles = new TestGeneratedFiles(); @Test void addSourceFileWithJavaFileAddsFile() throws Exception { MethodSpec main = MethodSpec.methodBuilder("main") .addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(void.class) .addParameter(String[].class, "args") .addStatement("$T.out.println($S)", System.class, "Hello, World!") .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addMethod(main).build(); JavaFile javaFile = JavaFile.builder("com.example", helloWorld).build(); this.generatedFiles.addSourceFile(javaFile); assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java") .contains("Hello, World!"); } @Test void addSourceFileWithJavaFileInTheDefaultPackageThrowsException() { TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld").build(); JavaFile javaFile = JavaFile.builder("", helloWorld).build(); assertThatIllegalArgumentException().isThrownBy(() -> this.generatedFiles.addSourceFile(javaFile)) .withMessage("Could not add 'HelloWorld', processing classes in the " + "default package is not supported. Did you forget to add a package statement?"); } @Test void addSourceFileWithCharSequenceAddsFile() throws Exception { this.generatedFiles.addSourceFile("com.example.HelloWorld", "{}"); assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}"); } @Test void addSourceFileWithCharSequenceWhenClassNameIsEmptyThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.generatedFiles.addSourceFile("", "{}")) .withMessage("'className' must not be empty"); } @Test void addSourceFileWithCharSequenceWhenClassNameIsInTheDefaultPackageThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.generatedFiles.addSourceFile("HelloWorld", "{}")) .withMessage("Could not add 'HelloWorld', processing classes in the " + "default package is not supported. Did you forget to add a package statement?"); } @Test void addSourceFileWithCharSequenceWhenClassNameIsInvalidThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.generatedFiles .addSourceFile("com/example/HelloWorld.java", "{}")) .withMessage("'className' must be a valid identifier, got 'com/example/HelloWorld.java'"); } @Test void addSourceFileWithConsumedAppendableAddsFile() throws Exception { this.generatedFiles.addSourceFile("com.example.HelloWorld", appendable -> appendable.append("{}")); assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}"); } @Test void addSourceFileWithInputStreamSourceAddsFile() throws Exception { Resource resource = new ByteArrayResource("{}".getBytes(StandardCharsets.UTF_8)); this.generatedFiles.addSourceFile("com.example.HelloWorld", resource); assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}"); } @Test void addResourceFileWithCharSequenceAddsFile() throws Exception { this.generatedFiles.addResourceFile("META-INF/file", "test"); assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test"); } @Test void addResourceFileWithConsumedAppendableAddsFile() throws Exception { this.generatedFiles.addResourceFile("META-INF/file", appendable -> appendable.append("test")); assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test"); } @Test void addResourceFileWithInputStreamSourceAddsFile() throws IOException { Resource resource = new ByteArrayResource( "test".getBytes(StandardCharsets.UTF_8)); this.generatedFiles.addResourceFile("META-INF/file", resource); assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test"); } @Test void addClassFileWithInputStreamSourceAddsFile() throws IOException { Resource resource = new ByteArrayResource( "test".getBytes(StandardCharsets.UTF_8)); this.generatedFiles.addClassFile("com/example/HelloWorld.class", resource); assertThatFileAdded(Kind.CLASS, "com/example/HelloWorld.class").isEqualTo("test"); } @Test void addFileWithCharSequenceAddsFile() throws Exception { this.generatedFiles.addFile(Kind.RESOURCE, "META-INF/file", "test"); assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test"); } @Test void addFileWithConsumedAppendableAddsFile() throws IOException { this.generatedFiles.addFile(Kind.SOURCE, "com/example/HelloWorld.java", appendable -> appendable.append("{}")); assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}"); } @Test void handleFileWhenFileDoesNotExist() throws IOException { this.generatedFiles.setFileHandler(new TestFileHandler()); AtomicBoolean called = new AtomicBoolean(false); this.generatedFiles.handleFile(Kind.RESOURCE, "META-INF/test", handler -> { called.set(true); handler.create(createSource("content")); }); assertThat(called).isTrue(); assertThatFileAdded(Kind.RESOURCE, "META-INF/test").isEqualTo("content").hasOverride(false); } @Test void handleFileWhenFileExistsCanOverride() throws IOException { this.generatedFiles.setFileHandler(new TestFileHandler(createSource("existing"))); AtomicBoolean called = new AtomicBoolean(false); this.generatedFiles.handleFile(Kind.RESOURCE, "META-INF/test", handler -> { called.set(true); handler.override(createSource("overridden")); }); assertThat(called).isTrue(); assertThatFileAdded(Kind.RESOURCE, "META-INF/test").isEqualTo("overridden").hasOverride(true); } @Test void handleFileWhenFileExistsCanOverrideUsingExistingContent() throws IOException { this.generatedFiles.setFileHandler(new TestFileHandler(createSource("existing"))); AtomicBoolean called = new AtomicBoolean(false); this.generatedFiles.handleFile(Kind.RESOURCE, "META-INF/test", handler -> { called.set(true); assertThat(handler.getContent()).isNotNull(); String existing = readSource(handler.getContent()); handler.override(createSource(existing+"-override")); }); assertThat(called).isTrue(); assertThatFileAdded(Kind.RESOURCE, "META-INF/test").isEqualTo("existing-override").hasOverride(true); } @Test void handleFileWhenFileExistsFailedToCreate() { TestFileHandler fileHandler = new TestFileHandler(createSource("existing")); this.generatedFiles.setFileHandler(fileHandler); assertThatIllegalStateException() .isThrownBy(() -> this.generatedFiles.handleFile(Kind.RESOURCE, "META-INF/test", handler -> handler.create(createSource("should fail")))) .withMessage("%s already exists".formatted(fileHandler)); } private static InputStreamSource createSource(String content) { return new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8)); } private static String readSource(InputStreamSource content) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); content.getInputStream().transferTo(out); return out.toString(StandardCharsets.UTF_8); } private GeneratedFileAssert assertThatFileAdded(Kind kind, String path) throws IOException { return this.generatedFiles.assertThatFileAdded(kind, path); } static
GeneratedFilesTests
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/optional/BeanWithOptionals.java
{ "start": 262, "end": 1267 }
class ____ { @Property(name = "string.prop") Optional<String> stringOptional; @Property(name = "integer.prop") OptionalInt optionalInt; @Property(name = "long.prop") OptionalLong optionalLong; @Property(name = "double.prop") OptionalDouble optionalDouble; final OptionalInt optionalIntFromConstructor; final OptionalLong optionalLongFromConstructor; final OptionalDouble optionalDoubleFromConstructor; public BeanWithOptionals(@Property(name = "integer.prop") OptionalInt optionalIntFromConstructor, @Property(name = "long.prop") OptionalLong optionalLongFromConstructor, @Property(name = "double.prop") OptionalDouble optionalDoubleFromConstructor) { this.optionalIntFromConstructor = optionalIntFromConstructor; this.optionalLongFromConstructor = optionalLongFromConstructor; this.optionalDoubleFromConstructor = optionalDoubleFromConstructor; } }
BeanWithOptionals
java
google__truth
core/src/main/java/com/google/common/truth/ExpectFailure.java
{ "start": 9239, "end": 9479 }
interface ____ {@link #expectFailureAbout expectFailureAbout()} to invoke and * capture failures. * * <p>Users should pass a lambda to {@code .expectFailureAbout()} rather than directly implement * this interface. */ public
for
java
spring-projects__spring-boot
module/spring-boot-data-elasticsearch-test/src/dockerTest/java/org/springframework/boot/data/elasticsearch/test/autoconfigure/DataElasticsearchTestReactiveIntegrationTests.java
{ "start": 1584, "end": 2425 }
class ____ { @Container @ServiceConnection static final ElasticsearchContainer elasticsearch = TestImage.container(ElasticsearchContainer.class); @Autowired private ReactiveElasticsearchTemplate elasticsearchTemplate; @Autowired private ExampleReactiveRepository exampleReactiveRepository; @Test void testRepository() { ExampleDocument exampleDocument = new ExampleDocument(); exampleDocument.setText("Look, new @DataElasticsearchTest!"); exampleDocument = this.exampleReactiveRepository.save(exampleDocument).block(Duration.ofSeconds(30)); assertThat(exampleDocument).isNotNull(); assertThat(exampleDocument.getId()).isNotNull(); assertThat(this.elasticsearchTemplate.exists(exampleDocument.getId(), ExampleDocument.class) .block(Duration.ofSeconds(30))).isTrue(); } }
DataElasticsearchTestReactiveIntegrationTests
java
apache__camel
core/camel-base/src/generated/java/org/apache/camel/component/properties/PropertiesComponentConfigurer.java
{ "start": 729, "end": 9282 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("AutoDiscoverPropertiesSources", boolean.class); map.put("CamelContext", org.apache.camel.CamelContext.class); map.put("DefaultFallbackEnabled", boolean.class); map.put("Encoding", java.lang.String.class); map.put("EnvironmentVariableMode", int.class); map.put("IgnoreMissingLocation", boolean.class); map.put("IgnoreMissingProperty", boolean.class); map.put("InitialProperties", java.util.Properties.class); map.put("LocalProperties", java.util.Properties.class); map.put("Location", java.lang.String.class); map.put("Locations", java.util.List.class); map.put("NestedPlaceholder", boolean.class); map.put("OverrideProperties", java.util.Properties.class); map.put("PropertiesFunctionResolver", org.apache.camel.component.properties.PropertiesFunctionResolver.class); map.put("PropertiesParser", org.apache.camel.component.properties.PropertiesParser.class); map.put("SystemPropertiesMode", int.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.properties.PropertiesComponent target = (org.apache.camel.component.properties.PropertiesComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autodiscoverpropertiessources": case "autoDiscoverPropertiesSources": target.setAutoDiscoverPropertiesSources(property(camelContext, boolean.class, value)); return true; case "camelcontext": case "camelContext": target.setCamelContext(property(camelContext, org.apache.camel.CamelContext.class, value)); return true; case "defaultfallbackenabled": case "defaultFallbackEnabled": target.setDefaultFallbackEnabled(property(camelContext, boolean.class, value)); return true; case "encoding": target.setEncoding(property(camelContext, java.lang.String.class, value)); return true; case "environmentvariablemode": case "environmentVariableMode": target.setEnvironmentVariableMode(property(camelContext, int.class, value)); return true; case "ignoremissinglocation": case "ignoreMissingLocation": target.setIgnoreMissingLocation(property(camelContext, boolean.class, value)); return true; case "ignoremissingproperty": case "ignoreMissingProperty": target.setIgnoreMissingProperty(property(camelContext, boolean.class, value)); return true; case "initialproperties": case "initialProperties": target.setInitialProperties(property(camelContext, java.util.Properties.class, value)); return true; case "localproperties": case "localProperties": target.setLocalProperties(property(camelContext, java.util.Properties.class, value)); return true; case "location": target.setLocation(property(camelContext, java.lang.String.class, value)); return true; case "locations": target.setLocations(property(camelContext, java.util.List.class, value)); return true; case "nestedplaceholder": case "nestedPlaceholder": target.setNestedPlaceholder(property(camelContext, boolean.class, value)); return true; case "overrideproperties": case "overrideProperties": target.setOverrideProperties(property(camelContext, java.util.Properties.class, value)); return true; case "propertiesfunctionresolver": case "propertiesFunctionResolver": target.setPropertiesFunctionResolver(property(camelContext, org.apache.camel.component.properties.PropertiesFunctionResolver.class, value)); return true; case "propertiesparser": case "propertiesParser": target.setPropertiesParser(property(camelContext, org.apache.camel.component.properties.PropertiesParser.class, value)); return true; case "systempropertiesmode": case "systemPropertiesMode": target.setSystemPropertiesMode(property(camelContext, int.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "autodiscoverpropertiessources": case "autoDiscoverPropertiesSources": return boolean.class; case "camelcontext": case "camelContext": return org.apache.camel.CamelContext.class; case "defaultfallbackenabled": case "defaultFallbackEnabled": return boolean.class; case "encoding": return java.lang.String.class; case "environmentvariablemode": case "environmentVariableMode": return int.class; case "ignoremissinglocation": case "ignoreMissingLocation": return boolean.class; case "ignoremissingproperty": case "ignoreMissingProperty": return boolean.class; case "initialproperties": case "initialProperties": return java.util.Properties.class; case "localproperties": case "localProperties": return java.util.Properties.class; case "location": return java.lang.String.class; case "locations": return java.util.List.class; case "nestedplaceholder": case "nestedPlaceholder": return boolean.class; case "overrideproperties": case "overrideProperties": return java.util.Properties.class; case "propertiesfunctionresolver": case "propertiesFunctionResolver": return org.apache.camel.component.properties.PropertiesFunctionResolver.class; case "propertiesparser": case "propertiesParser": return org.apache.camel.component.properties.PropertiesParser.class; case "systempropertiesmode": case "systemPropertiesMode": return int.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.properties.PropertiesComponent target = (org.apache.camel.component.properties.PropertiesComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autodiscoverpropertiessources": case "autoDiscoverPropertiesSources": return target.isAutoDiscoverPropertiesSources(); case "camelcontext": case "camelContext": return target.getCamelContext(); case "defaultfallbackenabled": case "defaultFallbackEnabled": return target.isDefaultFallbackEnabled(); case "encoding": return target.getEncoding(); case "environmentvariablemode": case "environmentVariableMode": return target.getEnvironmentVariableMode(); case "ignoremissinglocation": case "ignoreMissingLocation": return target.isIgnoreMissingLocation(); case "ignoremissingproperty": case "ignoreMissingProperty": return target.isIgnoreMissingProperty(); case "initialproperties": case "initialProperties": return target.getInitialProperties(); case "localproperties": case "localProperties": return target.getLocalProperties(); case "location": return target.getLocation(); case "locations": return target.getLocations(); case "nestedplaceholder": case "nestedPlaceholder": return target.isNestedPlaceholder(); case "overrideproperties": case "overrideProperties": return target.getOverrideProperties(); case "propertiesfunctionresolver": case "propertiesFunctionResolver": return target.getPropertiesFunctionResolver(); case "propertiesparser": case "propertiesParser": return target.getPropertiesParser(); case "systempropertiesmode": case "systemPropertiesMode": return target.getSystemPropertiesMode(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "locations": return org.apache.camel.component.properties.PropertiesLocation.class; default: return null; } } }
PropertiesComponentConfigurer
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/client/BasicConnectorContextTest.java
{ "start": 840, "end": 3314 }
class ____ { @RegisterExtension public static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot(root -> { root.addClasses(ServerEndpoint.class); }); @TestHTTPResource("/end") URI uri; static final CountDownLatch MESSAGE_LATCH = new CountDownLatch(2); static final Set<String> THREADS = ConcurrentHashMap.newKeySet(); static final Set<String> MESSAGES = ConcurrentHashMap.newKeySet(); static final CountDownLatch CLOSED_LATCH = new CountDownLatch(2); @Test void testClient() throws InterruptedException { BasicWebSocketConnector connector = BasicWebSocketConnector.create(); connector .executionModel(BasicWebSocketConnector.ExecutionModel.NON_BLOCKING) .onTextMessage((c, m) -> { String thread = Thread.currentThread().getName(); THREADS.add(thread); MESSAGE_LATCH.countDown(); MESSAGES.add(m); }) .onClose((c, cr) -> { CLOSED_LATCH.countDown(); }) .customizeOptions(((connectOptions, clientOptions) -> { connectOptions.addHeader("Foo", "Eric"); })) .baseUri(uri); WebSocketClientConnection conn1 = connector.connectAndAwait(); WebSocketClientConnection conn2 = connector.connectAndAwait(); assertTrue(MESSAGE_LATCH.await(10, TimeUnit.SECONDS)); if (Runtime.getRuntime().availableProcessors() > 1) { // Each client should be executed on a dedicated event loop thread assertEquals(2, THREADS.size()); } else { // Single core - the event pool is shared // Due to some CI weirdness it might happen that the system incorrectly reports single core // Therefore, the assert checks if the number of threads used is >= 1 assertTrue(THREADS.size() >= 1); } conn1.closeAndAwait(); conn2.closeAndAwait(); assertTrue(ServerEndpoint.CLOSED_LATCH.await(5, TimeUnit.SECONDS)); assertTrue(CLOSED_LATCH.await(5, TimeUnit.SECONDS)); assertTrue(MESSAGES.stream().allMatch("Hello Eric!"::equals), () -> "Expected messages equal to 'Hello Eric!', but got " + MESSAGES); } @WebSocket(path = "/end") public static
BasicConnectorContextTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/period/PeriodAssert_isNegative_Test.java
{ "start": 1086, "end": 2118 }
class ____ { @Test void should_pass_if_period_is_negative() { // GIVEN Period period = Period.ofMonths(-10); // WHEN/THEN then(period).isNegative(); } @Test void should_fail_when_period_is_null() { // GIVEN Period period = null; // WHEN final AssertionError code = expectAssertionError(() -> assertThat(period).isNegative()); // THEN then(code).hasMessage(actualIsNull()); } @Test void should_fail_if_period_is_positive() { // GIVEN Period period = Period.ofMonths(10); // WHEN final AssertionError code = expectAssertionError(() -> assertThat(period).isNegative()); // THEN then(code).hasMessage(shouldBeNegative(period).create()); } @Test void should_fail_if_period_is_zero() { // GIVEN Period period = Period.ofMonths(0); // WHEN final AssertionError code = expectAssertionError(() -> assertThat(period).isNegative()); // THEN then(code).hasMessage(shouldBeNegative(period).create()); } }
PeriodAssert_isNegative_Test
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonLockTest.java
{ "start": 874, "end": 1948 }
class ____ extends Thread { private CountDownLatch latch; private RedissonClient redisson; public LockWithoutBoolean(String name, CountDownLatch latch, RedissonClient redisson) { super(name); this.latch = latch; this.redisson = redisson; } public void run() { RLock lock = redisson.getLock("lock"); lock.lock(10, TimeUnit.MINUTES); System.out.println(Thread.currentThread().getName() + " gets lock. and interrupt: " + Thread.currentThread().isInterrupted()); try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { latch.countDown(); Thread.currentThread().interrupt(); } finally { try { lock.unlock(); } finally { latch.countDown(); } } System.out.println(Thread.currentThread().getName() + " ends."); } } public static
LockWithoutBoolean
java
apache__flink
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/workflow/EmbeddedSchedulerRelatedITCase.java
{ "start": 16792, "end": 16918 }
class ____ implements CreateRefreshWorkflow {} /** Just used for test. */ private static
UnsupportedCreateRefreshWorkflow
java
micronaut-projects__micronaut-core
http-server/src/test/groovy/io/micronaut/http/server/exceptions/UnsupportedMediaExceptionTest.java
{ "start": 260, "end": 811 }
class ____ { @Test void statusIsUnsupportedMediaType() { UnsupportedMediaException ex = new UnsupportedMediaException(MediaType.TEXT_HTML, List.of(MediaType.APPLICATION_JSON)); assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ex.getStatus()); assertEquals("text/html", ex.getContentType()); assertEquals(List.of("application/json"), ex.getAcceptableContentTypes()); assertEquals("Content Type [text/html] not allowed. Allowed types: [application/json]", ex.getMessage()); } }
UnsupportedMediaExceptionTest
java
elastic__elasticsearch
test/test-clusters/src/main/java/org/elasticsearch/test/cluster/util/ProcessUtils.java
{ "start": 1113, "end": 6623 }
class ____ { private static final Logger LOGGER = LogManager.getLogger(ProcessUtils.class); private static final Logger PROCESS_LOGGER = LogManager.getLogger("process-output"); private static final Duration PROCESS_DESTROY_TIMEOUT = Duration.ofSeconds(20); private ProcessUtils() {} public static Process exec(Path workingDir, Path executable, Map<String, String> environment, boolean inheritIO, String... args) { return exec(null, workingDir, executable, environment, inheritIO, args); } public static Process exec( String input, Path workingDir, Path executable, Map<String, String> environment, boolean inheritIO, String... args ) { Process process; if (Files.exists(executable) == false) { throw new IllegalArgumentException("Can't run executable: `" + executable + "` does not exist."); } ProcessBuilder processBuilder = new ProcessBuilder(); List<String> command = new ArrayList<>(); command.addAll( OS.conditional( c -> c.onWindows(() -> List.of("cmd", "/c", workingDir.relativize(executable).toString())) .onUnix(() -> List.of(workingDir.relativize(executable).toString())) ) ); command.addAll(Arrays.asList(args)); processBuilder.command(command); processBuilder.directory(workingDir.toFile()); processBuilder.environment().clear(); processBuilder.environment().putAll(environment); try { process = processBuilder.start(); startLoggingThread( process.getInputStream(), inheritIO ? System.out::println : PROCESS_LOGGER::info, executable.getFileName().toString() ); startLoggingThread( process.getErrorStream(), inheritIO ? System.err::println : PROCESS_LOGGER::error, executable.getFileName().toString() ); if (input != null) { try (BufferedWriter writer = process.outputWriter()) { writer.write(input); } } } catch (IOException e) { throw new UncheckedIOException("Error executing process: " + executable.getFileName(), e); } return process; } public static void stopHandle(ProcessHandle processHandle, boolean forcibly) { // No-op if the process has already exited by itself. if (processHandle.isAlive() == false) { return; } // Stop all children last - if the ML processes are killed before the ES JVM then // they'll be recorded as having failed and won't restart when the cluster restarts. // ES could actually be a child when there's some wrapper process like on Windows, // and in that case the ML processes will be grandchildren of the wrapper. List<ProcessHandle> children = processHandle.children().toList(); try { LOGGER.info("Terminating Elasticsearch process {}: {}", forcibly ? " forcibly " : "gracefully", processHandle.info()); if (forcibly) { processHandle.destroyForcibly(); } else { processHandle.destroy(); waitForProcessToExit(processHandle); if (processHandle.isAlive() == false) { return; } LOGGER.info( "Process did not terminate after {}, stopping it forcefully: {}", PROCESS_DESTROY_TIMEOUT, processHandle.info() ); processHandle.destroyForcibly(); } waitForProcessToExit(processHandle); if (processHandle.isAlive()) { throw new RuntimeException("Failed to terminate terminate elasticsearch process."); } } finally { children.forEach(each -> stopHandle(each, forcibly)); } } public static void waitForExit(ProcessHandle processHandle) { // No-op if the process has already exited by itself. if (processHandle.isAlive() == false) { return; } waitForProcessToExit(processHandle); } private static void waitForProcessToExit(ProcessHandle processHandle) { try { Retry.retryUntilTrue(PROCESS_DESTROY_TIMEOUT, Duration.ofSeconds(1), () -> { processHandle.destroy(); return processHandle.isAlive() == false; }); } catch (ExecutionException e) { LOGGER.info("Failure while waiting for process to exit: {}", processHandle.info(), e); } catch (TimeoutException e) { LOGGER.info("Timed out waiting for process to exit: {}", processHandle.info(), e); } } private static void startLoggingThread(InputStream is, Consumer<String> logAppender, String name) { new Thread(() -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line; while ((line = reader.readLine()) != null) { logAppender.accept(line); } } catch (IOException e) { throw new UncheckedIOException("Error reading output from process.", e); } }, name + "-log-forwarder").start(); } }
ProcessUtils
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/metrics/MetricsTrackingListState.java
{ "start": 1479, "end": 8048 }
class ____<K, N, T> extends AbstractMetricsTrackState< K, N, List<T>, InternalListState<K, N, T>, MetricsTrackingListState.ListStateMetrics> implements InternalListState<K, N, T> { private TypeSerializer<T> elementSerializer; MetricsTrackingListState( String stateName, InternalListState<K, N, T> original, KeyedStateBackend<K> keyedStateBackend, LatencyTrackingStateConfig latencyTrackingStateConfig, SizeTrackingStateConfig sizeTrackingStateConfig) { super( original, keyedStateBackend, latencyTrackingStateConfig.isEnabled() ? new ListStateMetrics( stateName, latencyTrackingStateConfig.getMetricGroup(), latencyTrackingStateConfig.getSampleInterval(), latencyTrackingStateConfig.getHistorySize(), latencyTrackingStateConfig.isStateNameAsVariable()) : null, sizeTrackingStateConfig.isEnabled() ? new ListStateMetrics( stateName, sizeTrackingStateConfig.getMetricGroup(), sizeTrackingStateConfig.getSampleInterval(), sizeTrackingStateConfig.getHistorySize(), sizeTrackingStateConfig.isStateNameAsVariable()) : null); if (valueSerializer != null) { this.elementSerializer = ((ListSerializer<T>) this.valueSerializer).getElementSerializer().duplicate(); } } @Override public Iterable<T> get() throws Exception { Iterable<T> result; if (latencyTrackingStateMetric != null && latencyTrackingStateMetric.trackMetricsOnGet()) { result = trackLatencyWithException( () -> original.get(), ListStateMetrics.LIST_STATE_GET_LATENCY); } else { result = original.get(); } if (sizeTrackingStateMetric != null && sizeTrackingStateMetric.trackMetricsOnGet()) { sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_GET_KEY_SIZE, super.sizeOfKey()); sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_GET_VALUE_SIZE, sizeOfValueList(result)); } return result; } @Override public void add(T value) throws Exception { if (sizeTrackingStateMetric != null && sizeTrackingStateMetric.trackMetricsOnAdd()) { sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_ADD_KEY_SIZE, super.sizeOfKey()); sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_ADD_VALUE_SIZE, sizeOfValueList(Collections.singletonList(value))); } if (latencyTrackingStateMetric != null && latencyTrackingStateMetric.trackMetricsOnAdd()) { trackLatencyWithException( () -> original.add(value), ListStateMetrics.LIST_STATE_ADD_LATENCY); } else { original.add(value); } } @Override public List<T> getInternal() throws Exception { return original.getInternal(); } @Override public void updateInternal(List<T> valueToStore) throws Exception { original.updateInternal(valueToStore); } @Override public void update(List<T> values) throws Exception { if (sizeTrackingStateMetric != null && sizeTrackingStateMetric.trackMetricsOnUpdate()) { sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_UPDATE_KEY_SIZE, super.sizeOfKey()); sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_UPDATE_VALUE_SIZE, sizeOfValueList(values)); } if (latencyTrackingStateMetric != null && latencyTrackingStateMetric.trackMetricsOnUpdate()) { trackLatencyWithException( () -> original.update(values), ListStateMetrics.LIST_STATE_UPDATE_LATENCY); } else { original.update(values); } } @Override public void addAll(List<T> values) throws Exception { if (sizeTrackingStateMetric != null && sizeTrackingStateMetric.trackMetricsOnAddAll()) { sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_ADD_ALL_KEY_SIZE, super.sizeOfKey()); sizeTrackingStateMetric.updateMetrics( ListStateMetrics.LIST_STATE_ADD_ALL_VALUE_SIZE, sizeOfValueList(values)); } if (latencyTrackingStateMetric != null && latencyTrackingStateMetric.trackMetricsOnAddAll()) { trackLatencyWithException( () -> original.addAll(values), ListStateMetrics.LIST_STATE_ADD_ALL_LATENCY); } else { original.addAll(values); } } @Override public void mergeNamespaces(N target, Collection<N> sources) throws Exception { if (latencyTrackingStateMetric != null && latencyTrackingStateMetric.trackMetricsOnMergeNamespace()) { trackLatencyWithException( () -> original.mergeNamespaces(target, sources), ListStateMetrics.LIST_STATE_MERGE_NAMESPACES_LATENCY); } else { original.mergeNamespaces(target, sources); } } private long sizeOfValueList(Iterable<T> valueList) throws IOException { if (elementSerializer == null || valueList == null) { return 0; } long totalSize = 0; for (T value : valueList) { if (value == null) { continue; } if (elementSerializer.getLength() == -1) { try { elementSerializer.serialize(value, outputSerializer); totalSize += outputSerializer.length(); } finally { outputSerializer.clear(); } } else { totalSize += elementSerializer.getLength(); } } return totalSize; } static
MetricsTrackingListState
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/tests/KeyTester.java
{ "start": 4465, "end": 4640 }
class ____ { private final Key key; private final String hash; KeyAndHash(Key key, String hash) { this.key = key; this.hash = hash; } } }
KeyAndHash
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/shard/GlobalCheckpointListenersTests.java
{ "start": 2275, "end": 2363 }
class ____ extends ESTestCase { @FunctionalInterface
GlobalCheckpointListenersTests
java
apache__camel
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/queue/HazelcastQueueConsumer.java
{ "start": 2677, "end": 4384 }
class ____ implements Runnable { CamelItemListener camelItemListener; public QueueConsumerTask(CamelItemListener camelItemListener) { this.camelItemListener = camelItemListener; } @Override public void run() { IQueue<Object> queue = hazelcastInstance.getQueue(cacheName); if (config.getQueueConsumerMode() == HazelcastQueueConsumerMode.LISTEN) { queue.addItemListener(camelItemListener, true); } if (config.getQueueConsumerMode() == HazelcastQueueConsumerMode.POLL) { while (isRunAllowed()) { try { final Object body = queue.poll(config.getPollingTimeout(), TimeUnit.MILLISECONDS); // CAMEL-16035 - If the polling timeout is exceeded with nothing to poll from the queue, the queue.poll() method return NULL if (body != null) { Exchange exchange = createExchange(false); exchange.getIn().setBody(body); try { processor.process(exchange); } catch (Exception e) { getExceptionHandler().handleException("Error during processing", exchange, e); } finally { releaseExchange(exchange, false); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } } }
QueueConsumerTask
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EqualsIncompatibleTypeTest.java
{ "start": 12292, "end": 12324 }
interface ____<X, Y> {} final
Bar
java
junit-team__junit5
junit-platform-launcher/src/main/java/org/junit/platform/launcher/ExcludeMethodFilter.java
{ "start": 872, "end": 918 }
class ____ be excluded. * * @since 1.12 */
will
java
spring-projects__spring-boot
module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/testcontainers/OracleFreeR2dbcContainerConnectionDetailsFactory.java
{ "start": 1987, "end": 2407 }
class ____ extends ContainerConnectionDetails<OracleContainer> implements R2dbcConnectionDetails { private R2dbcDatabaseContainerConnectionDetails(ContainerConnectionSource<OracleContainer> source) { super(source); } @Override public ConnectionFactoryOptions getConnectionFactoryOptions() { return OracleR2DBCDatabaseContainer.getOptions(getContainer()); } } }
R2dbcDatabaseContainerConnectionDetails
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/main/java/io/github/resilience4j/ratelimiter/monitoring/endpoint/RateLimiterEventsEndpoint.java
{ "start": 1430, "end": 3569 }
class ____ { private final EventConsumerRegistry<RateLimiterEvent> eventsConsumerRegistry; public RateLimiterEventsEndpoint( EventConsumerRegistry<RateLimiterEvent> eventsConsumerRegistry) { this.eventsConsumerRegistry = eventsConsumerRegistry; } @ReadOperation public RateLimiterEventsEndpointResponse getAllRateLimiterEvents() { return new RateLimiterEventsEndpointResponse(eventsConsumerRegistry.getAllEventConsumer().stream() .flatMap(CircularEventConsumer::getBufferedEventsStream) .sorted(Comparator.comparing(RateLimiterEvent::getCreationTime)) .map(RateLimiterEventDTO::createRateLimiterEventDTO) .collect(Collectors.toList())); } @ReadOperation public RateLimiterEventsEndpointResponse getEventsFilteredByRateLimiterName( @Selector String name) { return new RateLimiterEventsEndpointResponse(getRateLimiterEvents(name).stream() .map(RateLimiterEventDTO::createRateLimiterEventDTO) .collect(Collectors.toList())); } @ReadOperation public RateLimiterEventsEndpointResponse getEventsFilteredByRateLimiterNameAndEventType( @Selector String name, @Selector String eventType) { RateLimiterEvent.Type targetType = RateLimiterEvent.Type.valueOf(eventType.toUpperCase()); return new RateLimiterEventsEndpointResponse(getRateLimiterEvents(name).stream() .filter(event -> event.getEventType() == targetType) .map(RateLimiterEventDTO::createRateLimiterEventDTO) .collect(Collectors.toList())); } private List<RateLimiterEvent> getRateLimiterEvents(String name) { CircularEventConsumer<RateLimiterEvent> eventConsumer = eventsConsumerRegistry .getEventConsumer(name); if (eventConsumer != null) { return eventConsumer.getBufferedEventsStream() .filter(event -> event.getRateLimiterName().equals(name)) .collect(Collectors.toList()); } else { return Collections.emptyList(); } } }
RateLimiterEventsEndpoint
java
apache__hadoop
hadoop-tools/hadoop-resourceestimator/src/main/java/org/apache/hadoop/resourceestimator/translator/impl/LogParserUtil.java
{ "start": 1506, "end": 3582 }
class ____ { private static final Logger LOGGER = LoggerFactory.getLogger(LogParserUtil.class); private LogParser logParser; private DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); /** * Set the {@link LogParser} to use. * * @param logParser the {@link LogParser} to use. */ public void setLogParser(final LogParser logParser) { this.logParser = logParser; } /** * Set date format for the {@link LogParser}. * * @param datePattern the date pattern in the log. */ public void setDateFormat(final String datePattern) { this.format = new SimpleDateFormat(datePattern); } /** * Converts String date to unix timestamp. Note that we assume the time in the * logs has the same time zone with the machine which runs the * {@link RmSingleLineParser}. * * @param date The String date. * @return Unix time stamp. * @throws ParseException if data conversion from String to unix timestamp * fails. */ public long stringToUnixTimestamp(final String date) throws ParseException { return format.parse(date).getTime(); } /** * Parse the log file/directory. * * @param logFile the file/directory of the log. * @throws SkylineStoreException if fails to addHistory to * {@link SkylineStore}. * @throws IOException if fails to parse the log. * @throws ResourceEstimatorException if the {@link LogParser} * is not initialized. */ public final void parseLog(final String logFile) throws SkylineStoreException, IOException, ResourceEstimatorException { if (logParser == null) { throw new ResourceEstimatorException("The log parser is not initialized," + " please try again after initializing."); } InputStream inputStream = null; try { inputStream = new FileInputStream(logFile); logParser.parseStream(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } } }
LogParserUtil
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListCircuitBreaker.java
{ "start": 9663, "end": 10221 }
class ____ implements Cloneable { String pid; String name; String age; long uptime; String component; String id; String routeId; String state; int bufferedCalls; int successfulCalls; int failedCalls; long notPermittedCalls; double failureRate; Row copy() { try { return (Row) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } } }
Row
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/PercentilesAggregationBuilder.java
{ "start": 1459, "end": 6075 }
class ____ extends AbstractPercentilesAggregationBuilder<PercentilesAggregationBuilder> { public static final String NAME = Percentiles.TYPE_NAME; public static final ValuesSourceRegistry.RegistryKey<PercentilesAggregatorSupplier> REGISTRY_KEY = new ValuesSourceRegistry.RegistryKey<>(NAME, PercentilesAggregatorSupplier.class); private static final double[] DEFAULT_PERCENTS = new double[] { 1, 5, 25, 50, 75, 95, 99 }; private static final ParseField PERCENTS_FIELD = new ParseField("percents"); public static final ConstructingObjectParser<PercentilesAggregationBuilder, String> PARSER = AbstractPercentilesAggregationBuilder .createParser(PercentilesAggregationBuilder.NAME, (name, values, percentileConfig) -> { if (values == null) { values = DEFAULT_PERCENTS; // this is needed because Percentiles has a default, while Ranks does not } else { values = validatePercentiles(values, name); } return new PercentilesAggregationBuilder(name, values, percentileConfig); }, PercentilesConfig.TDigest::new, PERCENTS_FIELD); public static void registerAggregators(ValuesSourceRegistry.Builder builder) { PercentilesAggregatorFactory.registerAggregators(builder); } public PercentilesAggregationBuilder(StreamInput in) throws IOException { super(PERCENTS_FIELD, in); } public PercentilesAggregationBuilder(String name) { this(name, DEFAULT_PERCENTS, null); } public PercentilesAggregationBuilder(String name, double[] values, PercentilesConfig percentilesConfig) { super(name, values, percentilesConfig, PERCENTS_FIELD); } protected PercentilesAggregationBuilder( PercentilesAggregationBuilder clone, AggregatorFactories.Builder factoriesBuilder, Map<String, Object> metadata ) { super(clone, factoriesBuilder, metadata); } @Override protected AggregationBuilder shallowCopy(AggregatorFactories.Builder factoriesBuilder, Map<String, Object> metadata) { return new PercentilesAggregationBuilder(this, factoriesBuilder, metadata); } @Override protected ValuesSourceType defaultValueSourceType() { return CoreValuesSourceType.NUMERIC; } /** * Set the values to compute percentiles from. */ public PercentilesAggregationBuilder percentiles(double... percents) { this.values = validatePercentiles(percents, name); return this; } private static double[] validatePercentiles(double[] percents, String aggName) { if (percents == null) { throw new IllegalArgumentException("[percents] must not be null: [" + aggName + "]"); } if (percents.length == 0) { throw new IllegalArgumentException("[percents] must not be empty: [" + aggName + "]"); } double[] sortedPercents = Arrays.copyOf(percents, percents.length); double previousPercent = -1.0; Arrays.sort(sortedPercents); for (double percent : sortedPercents) { if (percent < 0.0 || percent > 100.0) { throw new IllegalArgumentException("percent must be in [0,100], got [" + percent + "]: [" + aggName + "]"); } if (percent == previousPercent) { throw new IllegalArgumentException("percent [" + percent + "] has been specified twice: [" + aggName + "]"); } previousPercent = percent; } return sortedPercents; } /** * Get the values to compute percentiles from. */ public double[] percentiles() { return values; } @Override protected ValuesSourceAggregatorFactory innerBuild( AggregationContext context, ValuesSourceConfig config, AggregatorFactory parent, AggregatorFactories.Builder subFactoriesBuilder ) throws IOException { PercentilesAggregatorSupplier aggregatorSupplier = context.getValuesSourceRegistry().getAggregator(REGISTRY_KEY, config); return new PercentilesAggregatorFactory( name, config, values, configOrDefault(), keyed, context, parent, subFactoriesBuilder, metadata, aggregatorSupplier ); } @Override public String getType() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.zero(); } }
PercentilesAggregationBuilder
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/records/ContainerStartData.java
{ "start": 1451, "end": 2766 }
class ____ { @Public @Unstable public static ContainerStartData newInstance(ContainerId containerId, Resource allocatedResource, NodeId assignedNode, Priority priority, long startTime) { ContainerStartData containerSD = Records.newRecord(ContainerStartData.class); containerSD.setContainerId(containerId); containerSD.setAllocatedResource(allocatedResource); containerSD.setAssignedNode(assignedNode); containerSD.setPriority(priority); containerSD.setStartTime(startTime); return containerSD; } @Public @Unstable public abstract ContainerId getContainerId(); @Public @Unstable public abstract void setContainerId(ContainerId containerId); @Public @Unstable public abstract Resource getAllocatedResource(); @Public @Unstable public abstract void setAllocatedResource(Resource resource); @Public @Unstable public abstract NodeId getAssignedNode(); @Public @Unstable public abstract void setAssignedNode(NodeId nodeId); @Public @Unstable public abstract Priority getPriority(); @Public @Unstable public abstract void setPriority(Priority priority); @Public @Unstable public abstract long getStartTime(); @Public @Unstable public abstract void setStartTime(long startTime); }
ContainerStartData
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/leaderelection/TestingLeaderBase.java
{ "start": 1213, "end": 3587 }
class ____ { // The queues will be offered by subclasses protected final BlockingQueue<LeaderInformation> leaderEventQueue = new LinkedBlockingQueue<>(); private final BlockingQueue<Throwable> errorQueue = new LinkedBlockingQueue<>(); private boolean isLeader = false; private Throwable error; public void waitForLeader() throws Exception { throwExceptionIfNotNull(); CommonTestUtils.waitUntilCondition( () -> { final LeaderInformation leader = leaderEventQueue.take(); return !leader.isEmpty(); }); isLeader = true; } public void waitForRevokeLeader() throws Exception { throwExceptionIfNotNull(); CommonTestUtils.waitUntilCondition( () -> { final LeaderInformation leader = leaderEventQueue.take(); return leader.isEmpty(); }); isLeader = false; } public void waitForError() throws Exception { error = errorQueue.take(); } public void clearError() { error = null; } public void handleError(Throwable ex) { errorQueue.offer(ex); } /** * Please use {@link #waitForError} before get the error. * * @return the error has been handled. */ @Nullable public Throwable getError() { return error == null ? errorQueue.poll() : error; } /** * Method for exposing errors that were caught during the test execution and need to be exposed * within the test. * * @throws AssertionError with the actual unhandled error as the cause if such an error was * caught during the test code execution. */ public void throwErrorIfPresent() { final String assertionErrorMessage = "An unhandled error was caught during test execution."; if (error != null) { throw new AssertionError(assertionErrorMessage, error); } if (!errorQueue.isEmpty()) { throw new AssertionError(assertionErrorMessage, errorQueue.poll()); } } public boolean isLeader() { return isLeader; } private void throwExceptionIfNotNull() throws Exception { if (error != null) { ExceptionUtils.rethrowException(error); } } }
TestingLeaderBase
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java
{ "start": 1285, "end": 5290 }
class ____ { private AbstractRegistryFactory registryFactory; @BeforeEach public void setup() { registryFactory = new AbstractRegistryFactory() { @Override protected Registry createRegistry(final URL url) { return new Registry() { public URL getUrl() { return url; } @Override public boolean isAvailable() { return false; } @Override public void destroy() {} @Override public void register(URL url) {} @Override public void unregister(URL url) {} @Override public void subscribe(URL url, NotifyListener listener) {} @Override public void unsubscribe(URL url, NotifyListener listener) {} @Override public List<URL> lookup(URL url) { return null; } }; } }; registryFactory.setApplicationModel(ApplicationModel.defaultModel()); } @AfterEach public void teardown() { ApplicationModel.defaultModel().destroy(); } @Test void testRegistryFactoryCache() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233"); Registry registry1 = registryFactory.getRegistry(url); Registry registry2 = registryFactory.getRegistry(url); Assertions.assertEquals(registry1, registry2); } /** * Registration center address `dubbo` does not resolve */ // @Test public void testRegistryFactoryIpCache() { Registry registry1 = registryFactory.getRegistry( URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233")); Registry registry2 = registryFactory.getRegistry( URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233")); Assertions.assertEquals(registry1, registry2); } @Test void testRegistryFactoryGroupCache() { Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa")); Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb")); Assertions.assertNotSame(registry1, registry2); } @Test void testDestroyAllRegistries() { Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":8888?group=xxx")); Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":9999?group=yyy")); Registry registry3 = new AbstractRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2020?group=yyy")) { @Override public boolean isAvailable() { return true; } }; RegistryManager registryManager = ApplicationModel.defaultModel().getBeanFactory().getBean(RegistryManager.class); Collection<Registry> registries = registryManager.getRegistries(); Assertions.assertTrue(registries.contains(registry1)); Assertions.assertTrue(registries.contains(registry2)); registry3.destroy(); registries = registryManager.getRegistries(); Assertions.assertFalse(registries.contains(registry3)); registryManager.destroyAll(); registries = registryManager.getRegistries(); Assertions.assertFalse(registries.contains(registry1)); Assertions.assertFalse(registries.contains(registry2)); } }
AbstractRegistryFactoryTest
java
apache__camel
dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/RouteBuilder.java
{ "start": 914, "end": 4470 }
class ____ { private Map<String, String> annotations; private Boolean enabled; private String host; private String tlsCACertificate; private String tlsCACertificateSecret; private String tlsCertificate; private String tlsCertificateSecret; private String tlsDestinationCACertificate; private String tlsDestinationCACertificateSecret; private Route.TlsInsecureEdgeTerminationPolicy tlsInsecureEdgeTerminationPolicy; private String tlsKey; private String tlsKeySecret; private Route.TlsTermination tlsTermination; private RouteBuilder() { } public static RouteBuilder route() { return new RouteBuilder(); } public RouteBuilder withAnnotations(Map<String, String> annotations) { this.annotations = annotations; return this; } public RouteBuilder withEnabled(Boolean enabled) { this.enabled = enabled; return this; } public RouteBuilder withHost(String host) { this.host = host; return this; } public RouteBuilder withTlsCACertificate(String tlsCACertificate) { this.tlsCACertificate = tlsCACertificate; return this; } public RouteBuilder withTlsCACertificateSecret(String tlsCACertificateSecret) { this.tlsCACertificateSecret = tlsCACertificateSecret; return this; } public RouteBuilder withTlsCertificate(String tlsCertificate) { this.tlsCertificate = tlsCertificate; return this; } public RouteBuilder withTlsCertificateSecret(String tlsCertificateSecret) { this.tlsCertificateSecret = tlsCertificateSecret; return this; } public RouteBuilder withTlsDestinationCACertificate(String tlsDestinationCACertificate) { this.tlsDestinationCACertificate = tlsDestinationCACertificate; return this; } public RouteBuilder withTlsDestinationCACertificateSecret(String tlsDestinationCACertificateSecret) { this.tlsDestinationCACertificateSecret = tlsDestinationCACertificateSecret; return this; } public RouteBuilder withTlsInsecureEdgeTerminationPolicy( Route.TlsInsecureEdgeTerminationPolicy tlsInsecureEdgeTerminationPolicy) { this.tlsInsecureEdgeTerminationPolicy = tlsInsecureEdgeTerminationPolicy; return this; } public RouteBuilder withTlsKey(String tlsKey) { this.tlsKey = tlsKey; return this; } public RouteBuilder withTlsKeySecret(String tlsKeySecret) { this.tlsKeySecret = tlsKeySecret; return this; } public RouteBuilder withTlsTermination(Route.TlsTermination tlsTermination) { this.tlsTermination = tlsTermination; return this; } public Route build() { Route route = new Route(); route.setAnnotations(annotations); route.setEnabled(enabled); route.setHost(host); route.setTlsCACertificate(tlsCACertificate); route.setTlsCACertificateSecret(tlsCACertificateSecret); route.setTlsCertificate(tlsCertificate); route.setTlsCertificateSecret(tlsCertificateSecret); route.setTlsDestinationCACertificate(tlsDestinationCACertificate); route.setTlsDestinationCACertificateSecret(tlsDestinationCACertificateSecret); route.setTlsInsecureEdgeTerminationPolicy(tlsInsecureEdgeTerminationPolicy); route.setTlsKey(tlsKey); route.setTlsKeySecret(tlsKeySecret); route.setTlsTermination(tlsTermination); return route; } }
RouteBuilder
java
netty__netty
transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java
{ "start": 29976, "end": 36285 }
class ____ extends AbstractEpollUnsafe { // Overridden here just to be able to access this method from AbstractEpollStreamChannel @Override protected Executor prepareToClose() { return super.prepareToClose(); } private void handleReadException(ChannelPipeline pipeline, ByteBuf byteBuf, Throwable cause, boolean allDataRead, EpollRecvByteAllocatorHandle allocHandle) { if (byteBuf != null) { if (byteBuf.isReadable()) { readPending = false; pipeline.fireChannelRead(byteBuf); } else { byteBuf.release(); } } allocHandle.readComplete(); pipeline.fireChannelReadComplete(); pipeline.fireExceptionCaught(cause); // If oom will close the read event, release connection. // See https://github.com/netty/netty/issues/10434 if (allDataRead || cause instanceof OutOfMemoryError || cause instanceof LeakPresenceDetector.AllocationProhibitedException || cause instanceof IOException) { shutdownInput(true); } } @Override EpollRecvByteAllocatorHandle newEpollHandle(RecvByteBufAllocator.ExtendedHandle handle) { return new EpollRecvByteAllocatorStreamingHandle(handle); } @Override void epollInReady() { final ChannelConfig config = config(); if (shouldBreakEpollInReady(config)) { clearEpollIn0(); return; } final EpollRecvByteAllocatorHandle allocHandle = recvBufAllocHandle(); final ChannelPipeline pipeline = pipeline(); final ByteBufAllocator allocator = config.getAllocator(); allocHandle.reset(config); ByteBuf byteBuf = null; boolean allDataRead = false; Queue<SpliceInTask> sQueue = null; try { do { if (sQueue != null || (sQueue = spliceQueue) != null) { SpliceInTask spliceTask = sQueue.peek(); if (spliceTask != null) { boolean spliceInResult = spliceTask.spliceIn(allocHandle); if (allocHandle.isReceivedRdHup()) { shutdownInput(false); } if (spliceInResult) { // We need to check if it is still active as if not we removed all SpliceTasks in // doClose(...) if (isActive()) { sQueue.remove(); } continue; } else { break; } } } // we use a direct buffer here as the native implementations only be able // to handle direct buffers. byteBuf = allocHandle.allocate(allocator); allocHandle.lastBytesRead(doReadBytes(byteBuf)); if (allocHandle.lastBytesRead() <= 0) { // nothing was read, release the buffer. byteBuf.release(); byteBuf = null; allDataRead = allocHandle.lastBytesRead() < 0; if (allDataRead) { // There is nothing left to read as we received an EOF. readPending = false; } break; } allocHandle.incMessagesRead(1); readPending = false; pipeline.fireChannelRead(byteBuf); byteBuf = null; if (shouldBreakEpollInReady(config)) { // We need to do this for two reasons: // // - If the input was shutdown in between (which may be the case when the user did it in the // fireChannelRead(...) method we should not try to read again to not produce any // miss-leading exceptions. // // - If the user closes the channel we need to ensure we not try to read from it again as // the filedescriptor may be re-used already by the OS if the system is handling a lot of // concurrent connections and so needs a lot of filedescriptors. If not do this we risk // reading data from a filedescriptor that belongs to another socket then the socket that // was "wrapped" by this Channel implementation. break; } } while (allocHandle.continueReading()); allocHandle.readComplete(); pipeline.fireChannelReadComplete(); if (allDataRead) { shutdownInput(true); } } catch (Throwable t) { handleReadException(pipeline, byteBuf, t, allDataRead, allocHandle); } finally { if (sQueue == null) { if (shouldStopReading(config)) { clearEpollIn(); } } else { if (!config.isAutoRead()) { clearEpollIn(); } } } } } private void addToSpliceQueue(final SpliceInTask task) { Queue<SpliceInTask> sQueue = spliceQueue; if (sQueue == null) { synchronized (this) { sQueue = spliceQueue; if (sQueue == null) { spliceQueue = sQueue = PlatformDependent.newMpscQueue(); } } } sQueue.add(task); } protected abstract
EpollStreamUnsafe
java
quarkusio__quarkus
extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/binder/vertx/VertxMeterBinderUndertowServletFilter.java
{ "start": 515, "end": 1104 }
class ____ extends HttpFilter { @Inject RoutingContext routingContext; @Override protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(req, res); } finally { // Fallback. Only set if not already set by something smarter HttpRequestMetric metric = HttpRequestMetric.getRequestMetric(routingContext); metric.setTemplatePath(req.getServletPath()); } } }
VertxMeterBinderUndertowServletFilter
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/groupwindow/operator/WindowOperator.java
{ "start": 22651, "end": 23313 }
class ____ extends WindowContext implements MergingWindowProcessFunction.MergingContext<K, W> { @Override public BiConsumerWithException<W, Collection<W>, Throwable> getWindowStateMergingConsumer() { return new MergingWindowProcessFunction.DefaultAccMergingConsumer<>( this, windowAggregator); } } /** * {@code TriggerContext} is a utility for handling {@code Trigger} invocations. It can be * reused by setting the {@code key} and {@code window} fields. No internal state must be kept * in the {@code TriggerContext} */ private
MergingWindowContext
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/cluster/PrevalidateShardPathIT.java
{ "start": 1906, "end": 6156 }
class ____ extends ESIntegTestCase { public void testCheckShards() throws Exception { internalCluster().startMasterOnlyNode(); String node1 = internalCluster().startDataOnlyNode(); String node2 = internalCluster().startDataOnlyNode(); String indexName = "index1"; int index1shards = randomIntBetween(1, 5); createIndex("index1", Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, index1shards).build()); ensureGreen(indexName); var shardIds = clusterService().state() .routingTable() .allShards(indexName) .stream() .map(ShardRouting::shardId) .collect(Collectors.toSet()); String node1Id = getNodeId(node1); String node2Id = getNodeId(node2); Set<ShardId> shardIdsToCheck = new HashSet<>(shardIds); boolean includeUnknownShardId = randomBoolean(); if (includeUnknownShardId) { shardIdsToCheck.add(new ShardId(randomAlphaOfLength(10), UUIDs.randomBase64UUID(), randomIntBetween(0, 10))); } PrevalidateShardPathRequest req = new PrevalidateShardPathRequest(shardIdsToCheck, node1Id, node2Id); PrevalidateShardPathResponse resp = client().execute(TransportPrevalidateShardPathAction.TYPE, req).get(); var nodeResponses = resp.getNodes(); assertThat(nodeResponses.size(), equalTo(2)); assertThat(nodeResponses.stream().map(r -> r.getNode().getId()).collect(Collectors.toSet()), equalTo(Set.of(node1Id, node2Id))); assertTrue(resp.failures().isEmpty()); for (NodePrevalidateShardPathResponse nodeResponse : nodeResponses) { assertThat(nodeResponse.getShardIds(), equalTo(shardIds)); } // Check that after relocation the source node doesn't have the shard path internalCluster().startDataOnlyNode(); ensureStableCluster(4); logger.info("--> relocating shards from the node {}", node2); updateIndexSettings(Settings.builder().put("index.routing.allocation.exclude._name", node2), indexName); ensureGreen(indexName); logger.info("--> green after relocation"); assertBusy(() -> { try { // The excluded node should eventually delete the shards assertNoShards(shardIdsToCheck, node2Id); } catch (AssertionError e) { // Removal of shards which are no longer allocated to the node is attempted on every cluster state change in IndicesStore. // If for whatever reason the removal is not successful (e.g. not enough nodes reported that the shards are active) or it // temporarily failed to clean up the shard folder, we need to trigger another cluster state change for this removal to // finally succeed. logger.info("--> Triggering an extra cluster state update: {}", e.getMessage()); updateIndexSettings( Settings.builder().put("index.routing.allocation.exclude.name", "non-existent" + randomAlphaOfLength(5)), indexName ); throw e; } }, 30, TimeUnit.SECONDS); } private void assertNoShards(Set<ShardId> shards, String nodeId) throws Exception { assertBusy(() -> { PrevalidateShardPathRequest req = new PrevalidateShardPathRequest(shards, nodeId); PrevalidateShardPathResponse resp = client().execute(TransportPrevalidateShardPathAction.TYPE, req).get(); assertThat(resp.getNodes().size(), equalTo(1)); assertThat(resp.getNodes().get(0).getNode().getId(), equalTo(nodeId)); assertTrue("There should be no failures in the response", resp.failures().isEmpty()); Set<ShardId> node2ShardIds = resp.getNodes().get(0).getShardIds(); assertThat( Strings.format( "Relocation source node [%s] should have no shards after the relocation, but still got %s", nodeId, node2ShardIds ), node2ShardIds, is(empty()) ); }); } }
PrevalidateShardPathIT
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng5530MojoExecutionScopeTest.java
{ "start": 920, "end": 4209 }
class ____ extends AbstractMavenIntegrationTestCase { @Test public void testCopyfiles() throws Exception { File testDir = extractResources("/mng-5530-mojo-execution-scope"); File pluginDir = new File(testDir, "plugin"); File projectDir = new File(testDir, "basic"); Verifier verifier; // install the test plugin verifier = newVerifier(pluginDir.getAbsolutePath()); verifier.addCliArgument("install"); verifier.execute(); verifier.verifyErrorFreeLog(); // build the test project verifier = newVerifier(projectDir.getAbsolutePath()); verifier.addCliArgument("package"); verifier.execute(); verifier.verifyErrorFreeLog(); // verifier.verifyFilePresent( "target/execution-failure.txt" ); verifier.verifyFilePresent("target/execution-success.txt"); verifier.verifyFilePresent("target/execution-before.txt"); } @Test public void testCopyfilesMultithreaded() throws Exception { File testDir = extractResources("/mng-5530-mojo-execution-scope"); File pluginDir = new File(testDir, "plugin"); File projectDir = new File(testDir, "basic"); Verifier verifier; // install the test plugin verifier = newVerifier(pluginDir.getAbsolutePath()); verifier.addCliArgument("install"); verifier.execute(); verifier.verifyErrorFreeLog(); // build the test project verifier = newVerifier(projectDir.getAbsolutePath()); verifier.addCliArgument("--builder"); verifier.addCliArgument("multithreaded"); verifier.addCliArgument("-T"); verifier.addCliArgument("1"); verifier.addCliArgument("package"); verifier.execute(); verifier.verifyErrorFreeLog(); // verifier.verifyFilePresent( "target/execution-failure.txt" ); verifier.verifyFilePresent("target/execution-success.txt"); verifier.verifyFilePresent("target/execution-before.txt"); } @Test public void testExtension() throws Exception { File testDir = extractResources("/mng-5530-mojo-execution-scope"); File extensionDir = new File(testDir, "extension"); File pluginDir = new File(testDir, "extension-plugin"); File projectDir = new File(testDir, "extension-project"); Verifier verifier; // install the test extension verifier = newVerifier(extensionDir.getAbsolutePath()); verifier.addCliArgument("install"); verifier.execute(); verifier.verifyErrorFreeLog(); // install the test plugin verifier = newVerifier(pluginDir.getAbsolutePath()); verifier.addCliArgument("install"); verifier.execute(); verifier.verifyErrorFreeLog(); // build the test project verifier = newVerifier(projectDir.getAbsolutePath()); verifier.addCliArgument("-Dmaven.ext.class.path=" + new File(extensionDir, "target/classes").getAbsolutePath()); verifier.setForkJvm(true); // verifier does not support custom realms in embedded mode verifier.addCliArgument("package"); verifier.execute(); verifier.verifyErrorFreeLog(); } }
MavenITmng5530MojoExecutionScopeTest
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/ClassUtils.java
{ "start": 22437, "end": 22732 }
class ____ by {@code className} using the {@code classLoader}. This implementation supports the * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", and * "{@code [Ljava.util.Map$Entry;}". * <p> * The provided
represented
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UngroupedOverloadsTest.java
{ "start": 5717, "end": 7414 }
class ____ { private int foo; // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, String z, int y) { System.out.println(String.format("z: %s, x: %d, y: %d", z, x, y)); } public UngroupedOverloadsPositiveCasesInterleaved(int foo) { this.foo = foo; } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x) { bar(foo, x); } // BUG: Diagnostic contains: ungrouped overloads of 'baz' public void baz(String x) { baz(x, FOO); } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, int y) { bar(y, FOO, x); } public static final String FOO = "foo"; // BUG: Diagnostic contains: ungrouped overloads of 'baz' public void baz(String x, String y) { bar(foo, x + y, foo); } public void foo(int x) {} public void foo() { foo(foo); } }\ """) .doTest(); } @Test public void ungroupedOverloadsPositiveCasesCovering() { compilationHelper .addSourceLines( "UngroupedOverloadsPositiveCasesCovering.java", """ package com.google.errorprone.bugpatterns.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public
UngroupedOverloadsPositiveCasesInterleaved
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java
{ "start": 78594, "end": 81305 }
interface ____ provides access. * to application and request URI information. * @param delegation Represents delegation token used for authentication. * @param username User parameter. * @param doAsUser DoAs parameter for proxy user. * @param op Http DELETE operation parameter. * @param recursive Recursive parameter. * @param snapshotName The snapshot name parameter for createSnapshot * and deleteSnapshot operation. * @return Represents an HTTP response. */ @DELETE @Path("{" + UriFsPathParam.NAME + ":.*}") @Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8) public Response delete( @Context final UserGroupInformation ugi, @Context final UriInfo uriInfo, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT) final DeleteOpParam op, @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT) final RecursiveParam recursive, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName ) throws IOException, InterruptedException { final UriFsPathParam path = new UriFsPathParam(uriInfo.getPath()); init(ugi, delegation, username, doAsUser, path, op, recursive, snapshotName); return doAs(ugi, () -> delete(ugi, delegation, username, doAsUser, path.getAbsolutePath(), op, recursive, snapshotName)); } protected Response delete( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final DeleteOpParam op, final RecursiveParam recursive, final SnapshotNameParam snapshotName ) throws IOException { final ClientProtocol cp = getRpcClientProtocol(); switch(op.getValue()) { case DELETE: { final boolean b = cp.delete(fullpath, recursive.getValue()); final String js = JsonUtil.toJsonString("boolean", b); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case DELETESNAPSHOT: { validateOpParams(op, snapshotName); cp.deleteSnapshot(fullpath, snapshotName.getValue()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } default: throw new UnsupportedOperationException(op + " is not supported"); } } }
that
java
elastic__elasticsearch
x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/SamlMetadataResponse.java
{ "start": 465, "end": 911 }
class ____ extends ActionResponse { private final String xmlString; public SamlMetadataResponse(String xmlString) { this.xmlString = Objects.requireNonNull(xmlString, "Metadata XML string must be provided"); } public String getXmlString() { return xmlString; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(xmlString); } }
SamlMetadataResponse
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/mailbox/MailboxExecutorImpl.java
{ "start": 1576, "end": 4372 }
class ____ implements MailboxExecutor { /** The mailbox that manages the submitted runnable objects. */ @Nonnull private final TaskMailbox mailbox; private final int priority; private final StreamTaskActionExecutor actionExecutor; private final MailboxProcessor mailboxProcessor; public MailboxExecutorImpl( @Nonnull TaskMailbox mailbox, int priority, StreamTaskActionExecutor actionExecutor) { this(mailbox, priority, actionExecutor, null); } public MailboxExecutorImpl( @Nonnull TaskMailbox mailbox, int priority, StreamTaskActionExecutor actionExecutor, MailboxProcessor mailboxProcessor) { this.mailbox = mailbox; this.priority = priority; this.actionExecutor = Preconditions.checkNotNull(actionExecutor); this.mailboxProcessor = mailboxProcessor; } public boolean isIdle() { return !mailboxProcessor.isDefaultActionAvailable() && !mailbox.hasMail() && mailbox.getState().isAcceptingMails(); } @Override public void execute( MailOptions mailOptions, final ThrowingRunnable<? extends Exception> command, final String descriptionFormat, final Object... descriptionArgs) { try { mailbox.put( new Mail( mailOptions, command, priority, actionExecutor, descriptionFormat, descriptionArgs)); } catch (MailboxClosedException mbex) { throw new RejectedExecutionException(mbex); } } @Override public void yield() throws InterruptedException { Mail mail = mailbox.take(priority); try { mail.run(); } catch (Exception ex) { throw WrappingRuntimeException.wrapIfNecessary(ex); } } @Override public boolean tryYield() { Optional<Mail> optionalMail = mailbox.tryTake(priority); if (optionalMail.isPresent()) { try { optionalMail.get().run(); } catch (Exception ex) { throw WrappingRuntimeException.wrapIfNecessary(ex); } return true; } else { return false; } } @Override public boolean shouldInterrupt() { // TODO: FLINK-35051 we shouldn't interrupt for every mail, but only for the time sensitive // ones, for example related to checkpointing. return mailbox.hasMail(); } @VisibleForTesting public int getPriority() { return priority; } }
MailboxExecutorImpl
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/query/CombinedFieldsQueryBuilder.java
{ "start": 15124, "end": 19089 }
class ____ extends QueryBuilder { private final List<FieldAndBoost> fields; private final SearchExecutionContext context; CombinedFieldsBuilder( List<FieldAndBoost> fields, Analyzer analyzer, boolean autoGenerateSynonymsPhraseQuery, SearchExecutionContext context ) { super(analyzer); this.fields = fields; setAutoGenerateMultiTermSynonymsPhraseQuery(autoGenerateSynonymsPhraseQuery); this.context = context; } @Override protected Query createFieldQuery(TokenStream source, BooleanClause.Occur operator, String field, boolean quoted, int phraseSlop) { if (source.hasAttribute(DisableGraphAttribute.class)) { /* * A {@link TokenFilter} in this {@link TokenStream} disabled the graph analysis to avoid * paths explosion. See {@link org.elasticsearch.index.analysis.ShingleTokenFilterFactory} for details. */ setEnableGraphQueries(false); } try { return super.createFieldQuery(source, operator, field, quoted, phraseSlop); } finally { setEnableGraphQueries(true); } } @Override public Query createPhraseQuery(String field, String queryText, int phraseSlop) { throw new IllegalArgumentException("[combined_fields] queries don't support phrases"); } @Override protected Query newSynonymQuery(String field, TermAndBoost[] terms) { CombinedFieldQuery.Builder query = new CombinedFieldQuery.Builder(); for (TermAndBoost termAndBoost : terms) { assert termAndBoost.boost() == BoostAttribute.DEFAULT_BOOST; BytesRef bytes = termAndBoost.term(); query.addTerm(bytes); } for (FieldAndBoost fieldAndBoost : fields) { MappedFieldType fieldType = fieldAndBoost.fieldType; float fieldBoost = fieldAndBoost.boost; query.addField(fieldType.name(), fieldBoost); } return query.build(); } @Override protected Query newTermQuery(Term term, float boost) { TermAndBoost termAndBoost = new TermAndBoost(term.bytes(), boost); return newSynonymQuery(term.field(), new TermAndBoost[] { termAndBoost }); } @Override protected Query analyzePhrase(String field, TokenStream stream, int slop) throws IOException { BooleanQuery.Builder builder = new BooleanQuery.Builder(); for (FieldAndBoost fieldAndBoost : fields) { Query query = fieldAndBoost.fieldType.phraseQuery(stream, slop, enablePositionIncrements, context); if (fieldAndBoost.boost != 1f) { query = new BoostQuery(query, fieldAndBoost.boost); } builder.add(query, BooleanClause.Occur.SHOULD); } return builder.build(); } } @Override protected int doHashCode() { return Objects.hash(value, fieldsAndBoosts, operator, minimumShouldMatch, zeroTermsQuery, autoGenerateSynonymsPhraseQuery); } @Override protected boolean doEquals(CombinedFieldsQueryBuilder other) { return Objects.equals(value, other.value) && Objects.equals(fieldsAndBoosts, other.fieldsAndBoosts) && Objects.equals(operator, other.operator) && Objects.equals(minimumShouldMatch, other.minimumShouldMatch) && Objects.equals(zeroTermsQuery, other.zeroTermsQuery) && Objects.equals(autoGenerateSynonymsPhraseQuery, other.autoGenerateSynonymsPhraseQuery); } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.zero(); } }
CombinedFieldsBuilder
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/MyLoggingSentEventNotifer.java
{ "start": 1078, "end": 1532 }
class ____ extends EventNotifierSupport { private static final Logger LOG = LoggerFactory.getLogger(MyLoggingSentEventNotifer.class); @Override public void notify(CamelEvent event) { // react only when its the sent event if (event instanceof ExchangeSentEvent sent) { LOG.info("Took {} millis to send to: {}", sent.getTimeTaken(), sent.getEndpoint()); } } } // END SNIPPET: e1
MyLoggingSentEventNotifer
java
elastic__elasticsearch
libs/entitlement/asm-provider/src/test/java/org/elasticsearch/entitlement/instrumentation/impl/InstrumentationServiceImplTests.java
{ "start": 23332, "end": 23666 }
class ____ the method to instrument", "check$org_example_TestClass$instanceMethod", Type.getType(Class.class) ); } public void testParseCheckerMethodSignatureInstanceMethodIncorrectArgumentTypes2() { assertParseCheckerMethodSignatureThrows( "a second argument of the
containing
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/collection/erroneous/ErroneousCollectionMappingTest.java
{ "start": 827, "end": 8208 }
class ____ { @ProcessorTest @IssueKey("6") @WithClasses({ ErroneousCollectionToNonCollectionMapper.class, Source.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionToNonCollectionMapper.class, kind = Kind.ERROR, line = 15, message = "Can't generate mapping method from iterable type from java stdlib to non-iterable type."), @Diagnostic(type = ErroneousCollectionToNonCollectionMapper.class, kind = Kind.ERROR, line = 17, message = "Can't generate mapping method from non-iterable type to iterable type from java stdlib."), @Diagnostic(type = ErroneousCollectionToNonCollectionMapper.class, kind = Kind.ERROR, line = 19, message = "Can't generate mapping method from non-iterable type to iterable type from java stdlib.") } ) public void shouldFailToGenerateImplementationBetweenCollectionAndNonCollectionWithResultTypeFromJava() { } @ProcessorTest @IssueKey("729") @WithClasses({ ErroneousCollectionToPrimitivePropertyMapper.class, Source.class, Target.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionToPrimitivePropertyMapper.class, kind = Kind.ERROR, line = 13, message = "Can't map property \"List<String> strings\" to \"int strings\". " + "Consider to declare/implement a mapping method: \"int map(List<String> value)\".") } ) public void shouldFailToGenerateImplementationBetweenCollectionAndPrimitive() { } @ProcessorTest @IssueKey("417") @WithClasses({ EmptyItererableMappingMapper.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = EmptyItererableMappingMapper.class, kind = Kind.ERROR, line = 22, message = "'nullValueMappingStrategy','dateformat', 'qualifiedBy' and 'elementTargetType' are " + "undefined in @IterableMapping, define at least one of them.") } ) public void shouldFailOnEmptyIterableAnnotation() { } @ProcessorTest @IssueKey("417") @WithClasses({ EmptyMapMappingMapper.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = EmptyMapMappingMapper.class, kind = Kind.ERROR, line = 22, message = "'nullValueMappingStrategy', 'keyDateFormat', 'keyQualifiedBy', 'keyTargetType', " + "'valueDateFormat', 'valueQualfiedBy' and 'valueTargetType' are all undefined in @MapMapping, " + "define at least one of them.") } ) public void shouldFailOnEmptyMapAnnotation() { } @ProcessorTest @IssueKey("459") @WithClasses({ ErroneousCollectionNoElementMappingFound.class, NoProperties.class, WithProperties.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionNoElementMappingFound.class, kind = Kind.ERROR, line = 25, message = "No target bean properties found: can't map Collection element " + "\"WithProperties withProperties\" to \"NoProperties noProperties\". " + "Consider to declare/implement a mapping method: \"NoProperties map(WithProperties value)\".") } ) public void shouldFailOnNoElementMappingFound() { } @ProcessorTest @IssueKey("993") @WithClasses({ ErroneousCollectionNoElementMappingFoundDisabledAuto.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionNoElementMappingFoundDisabledAuto.class, kind = Kind.ERROR, line = 19, message = "Can't map collection element \"AttributedString\" to \"String \". " + "Consider to declare/implement a mapping method: \"String map(AttributedString value)\".") } ) public void shouldFailOnNoElementMappingFoundWithDisabledAuto() { } @ProcessorTest @IssueKey("459") @WithClasses({ ErroneousCollectionNoKeyMappingFound.class, NoProperties.class, WithProperties.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionNoKeyMappingFound.class, kind = Kind.ERROR, line = 25, message = "No target bean properties found: can't map Map key \"WithProperties withProperties\" to " + "\"NoProperties noProperties\". " + "Consider to declare/implement a mapping method: \"NoProperties map(WithProperties value)\".") } ) public void shouldFailOnNoKeyMappingFound() { } @ProcessorTest @IssueKey("993") @WithClasses({ ErroneousCollectionNoKeyMappingFoundDisabledAuto.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionNoKeyMappingFoundDisabledAuto.class, kind = Kind.ERROR, line = 19, message = "Can't map map key \"AttributedString\" to \"String \". Consider to " + "declare/implement a mapping method: \"String map(AttributedString value)\".") } ) public void shouldFailOnNoKeyMappingFoundWithDisabledAuto() { } @ProcessorTest @IssueKey("459") @WithClasses({ ErroneousCollectionNoValueMappingFound.class, NoProperties.class, WithProperties.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionNoValueMappingFound.class, kind = Kind.ERROR, line = 25, message = "No target bean properties found: can't map Map value \"WithProperties withProperties\" " + "to \"NoProperties noProperties\". " + "Consider to declare/implement a mapping method: \"NoProperties map(WithProperties value)\".") } ) public void shouldFailOnNoValueMappingFound() { } @ProcessorTest @IssueKey("993") @WithClasses({ ErroneousCollectionNoValueMappingFoundDisabledAuto.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousCollectionNoValueMappingFoundDisabledAuto.class, kind = Kind.ERROR, line = 19, message = "Can't map map value \"AttributedString\" to \"String \". " + "Consider to declare/implement a mapping method: \"String map(AttributedString value)\".") } ) public void shouldFailOnNoValueMappingFoundWithDisabledAuto() { } }
ErroneousCollectionMappingTest
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/databricks/DataBricks.java
{ "start": 133, "end": 233 }
class ____ { public static final SQLDialect DIALECT = SQLDialect.of(DbType.databricks); }
DataBricks
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/Generated.java
{ "start": 1131, "end": 1995 }
interface ____ { /** * The value element MUST have the name of the code generator. The * name is the fully qualified name of the code generator. * * @return The name of the code generator */ String[] value(); /** * Date when the source was generated. The date element must follow the ISO * 8601 standard. For example the date element would have the following * value 2017-07-04T12:08:56.235-0700 which represents 2017-07-04 12:08:56 * local time in the U.S. Pacific Time zone. * * @return The date the source was generated */ String date() default ""; /** * A placeholder for any comments that the code generator may want to * include in the generated code. * * @return Comments that the code generated included */ String comments() default ""; }
Generated
java
apache__camel
components/camel-microprofile/camel-microprofile-fault-tolerance/src/main/java/org/apache/camel/component/microprofile/faulttolerance/FaultToleranceProcessorFactory.java
{ "start": 1164, "end": 1570 }
class ____ extends TypedProcessorFactory<CircuitBreakerDefinition> { public FaultToleranceProcessorFactory() { super(CircuitBreakerDefinition.class); } @Override public Processor doCreateProcessor(Route route, CircuitBreakerDefinition definition) throws Exception { return new FaultToleranceReifier(route, definition).createProcessor(); } }
FaultToleranceProcessorFactory
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpProxyRouteTest.java
{ "start": 1236, "end": 4437 }
class ____ extends BaseJettyTest { private static final Logger LOG = LoggerFactory.getLogger(HttpProxyRouteTest.class); private final int size = 10; @Test public void testHttpProxy() { LOG.info("Sending {} messages to a http endpoint which is proxied/bridged", size); StopWatch watch = new StopWatch(); for (int i = 0; i < size; i++) { String out = template.requestBody("http://localhost:{{port}}?foo=" + i, null, String.class); assertEquals("Bye " + i, out); } LOG.info("Time taken: {}", TimeUtils.printDuration(watch.taken(), true)); } @Test public void testHttpProxyWithDifferentPath() { String out = template.requestBody("http://localhost:{{port}}/proxy", null, String.class); assertEquals("/otherEndpoint", out); out = template.requestBody("http://localhost:{{port}}/proxy/path", null, String.class); assertEquals("/otherEndpoint/path", out); } @Test public void testHttpProxyHostHeader() { String out = template.requestBody("http://localhost:{{port}}/proxyServer", null, String.class); assertEquals("localhost:" + getPort2(), out, "Get a wrong host header"); } @Test public void testHttpProxyFormHeader() { String out = template.requestBodyAndHeader("http://localhost:{{port}}/form", "username=abc&pass=password", Exchange.CONTENT_TYPE, "application/x-www-form-urlencoded", String.class); assertEquals("username=abc&pass=password", out, "Get a wrong response message"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("jetty://http://localhost:{{port}}") .to("http://localhost:{{port}}/bye?throwExceptionOnFailure=false&bridgeEndpoint=true"); from("jetty://http://localhost:{{port}}/proxy?matchOnUriPrefix=true") .to("http://localhost:{{port}}/otherEndpoint?throwExceptionOnFailure=false&bridgeEndpoint=true"); from("jetty://http://localhost:{{port}}/bye").transform(header("foo").prepend("Bye ")); from("jetty://http://localhost:{{port}}/otherEndpoint?matchOnUriPrefix=true") .transform(header(Exchange.HTTP_URI)); from("jetty://http://localhost:{{port}}/proxyServer").to("http://localhost:{{port2}}/host?bridgeEndpoint=true"); from("jetty://http://localhost:{{port2}}/host").transform(header("host")); // check the from request from("jetty://http://localhost:{{port}}/form?bridgeEndpoint=true").process(new Processor() { @Override public void process(Exchange exchange) { // just take out the message body and send it back Message in = exchange.getIn(); String request = in.getBody(String.class); exchange.getMessage().setBody(request); } }); } }; } }
HttpProxyRouteTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-session-data-redis/src/main/java/smoketest/session/redis/SampleSessionRedisApplication.java
{ "start": 811, "end": 960 }
class ____ { public static void main(String[] args) { SpringApplication.run(SampleSessionRedisApplication.class); } }
SampleSessionRedisApplication
java
elastic__elasticsearch
modules/lang-expression/src/main/java/org/elasticsearch/script/expression/ExpressionScriptEngine.java
{ "start": 2283, "end": 23584 }
class ____ implements ScriptEngine { public static final String NAME = "expression"; private static Map<ScriptContext<?>, Function<Expression, Object>> contexts = Map.of( BucketAggregationScript.CONTEXT, ExpressionScriptEngine::newBucketAggregationScriptFactory, BucketAggregationSelectorScript.CONTEXT, (Expression expr) -> { BucketAggregationScript.Factory factory = newBucketAggregationScriptFactory(expr); BucketAggregationSelectorScript.Factory wrappedFactory = parameters -> new BucketAggregationSelectorScript(parameters) { @Override public boolean execute() { return factory.newInstance(getParams()).execute().doubleValue() == 1.0; } }; return wrappedFactory; }, FilterScript.CONTEXT, (Expression expr) -> new FilterScript.Factory() { @Override public boolean isResultDeterministic() { return true; } @Override public FilterScript.LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup) { return newFilterScript(expr, lookup, params); } }, ScoreScript.CONTEXT, (Expression expr) -> new ScoreScript.Factory() { @Override public ScoreScript.LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup) { return newScoreScript(expr, lookup, params); } @Override public boolean isResultDeterministic() { return true; } }, TermsSetQueryScript.CONTEXT, (Expression expr) -> (TermsSetQueryScript.Factory) (p, lookup) -> newTermsSetQueryScript(expr, lookup, p), AggregationScript.CONTEXT, (Expression expr) -> new AggregationScript.Factory() { @Override public AggregationScript.LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup) { return newAggregationScript(expr, lookup, params); } @Override public boolean isResultDeterministic() { return true; } }, NumberSortScript.CONTEXT, (Expression expr) -> new NumberSortScript.Factory() { @Override public NumberSortScript.LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup) { return newSortScript(expr, lookup, params); } @Override public boolean isResultDeterministic() { return true; } }, FieldScript.CONTEXT, (Expression expr) -> new FieldScript.Factory() { @Override public FieldScript.LeafFactory newFactory(Map<String, Object> params, SearchLookup lookup) { return newFieldScript(expr, lookup, params); } @Override public boolean isResultDeterministic() { return true; } }, DoubleValuesScript.CONTEXT, (Expression expr) -> new ExpressionDoubleValuesScript(expr) { @Override public boolean isResultDeterministic() { return true; } } ); @Override public String getType() { return NAME; } @Override public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params) { SpecialPermission.check(); Expression expr; try { // NOTE: validation is delayed to allow runtime vars, and we don't have access to per index stuff here expr = JavascriptCompiler.compile(scriptSource, JavascriptCompiler.DEFAULT_FUNCTIONS); } catch (ParseException e) { throw convertToScriptException("compile error", scriptSource, scriptSource, e); } if (contexts.containsKey(context) == false) { throw new IllegalArgumentException("expression engine does not know how to handle script context [" + context.name + "]"); } return context.factoryClazz.cast(contexts.get(context).apply(expr)); } @Override public Set<ScriptContext<?>> getSupportedContexts() { return contexts.keySet(); } private static BucketAggregationScript.Factory newBucketAggregationScriptFactory(Expression expr) { return parameters -> { ReplaceableConstDoubleValues[] functionValuesArray = new ReplaceableConstDoubleValues[expr.variables.length]; Map<String, ReplaceableConstDoubleValues> functionValuesMap = new HashMap<>(); for (int i = 0; i < expr.variables.length; ++i) { functionValuesArray[i] = new ReplaceableConstDoubleValues(); functionValuesMap.put(expr.variables[i], functionValuesArray[i]); } return new BucketAggregationScript(parameters) { @Override public Double execute() { getParams().forEach((name, value) -> { ReplaceableConstDoubleValues placeholder = functionValuesMap.get(name); if (placeholder == null) { throw new IllegalArgumentException( "Error using " + expr + ". " + "The variable [" + name + "] does not exist in the executable expressions script." ); } else if (value instanceof Number == false) { throw new IllegalArgumentException( "Error using " + expr + ". " + "Executable expressions scripts can only process numbers." + " The variable [" + name + "] is not a number." ); } else { placeholder.setValue(((Number) value).doubleValue()); } }); try { return expr.evaluate(functionValuesArray); } catch (IOException e) { throw new UncheckedIOException(e); } } }; }; } private static NumberSortScript.LeafFactory newSortScript(Expression expr, SearchLookup lookup, @Nullable Map<String, Object> vars) { // NOTE: if we need to do anything complicated with bindings in the future, we can just extend Bindings, // instead of complicating SimpleBindings (which should stay simple) SimpleBindings bindings = new SimpleBindings(); boolean needsScores = false; for (String variable : expr.variables) { try { if (variable.equals("_score")) { bindings.add("_score", DoubleValuesSource.SCORES); needsScores = true; } else if (vars != null && vars.containsKey(variable)) { bindFromParams(vars, bindings, variable); } else { // delegate valuesource creation based on field's type // there are three types of "fields" to expressions, and each one has a different "api" of variables and methods. final DoubleValuesSource valueSource = getDocValueSource(variable, lookup); needsScores |= valueSource.needsScores(); bindings.add(variable, valueSource); } } catch (Exception e) { // we defer "binding" of variables until here: give context for that variable throw convertToScriptException("link error", expr.sourceText, variable, e); } } return new ExpressionNumberSortScript(expr, bindings, needsScores); } private static TermsSetQueryScript.LeafFactory newTermsSetQueryScript( Expression expr, SearchLookup lookup, @Nullable Map<String, Object> vars ) { // NOTE: if we need to do anything complicated with bindings in the future, we can just extend Bindings, // instead of complicating SimpleBindings (which should stay simple) SimpleBindings bindings = new SimpleBindings(); for (String variable : expr.variables) { try { if (vars != null && vars.containsKey(variable)) { bindFromParams(vars, bindings, variable); } else { // delegate valuesource creation based on field's type // there are three types of "fields" to expressions, and each one has a different "api" of variables and methods. bindings.add(variable, getDocValueSource(variable, lookup)); } } catch (Exception e) { // we defer "binding" of variables until here: give context for that variable throw convertToScriptException("link error", expr.sourceText, variable, e); } } return new ExpressionTermSetQueryScript(expr, bindings); } private static AggregationScript.LeafFactory newAggregationScript( Expression expr, SearchLookup lookup, @Nullable Map<String, Object> vars ) { // NOTE: if we need to do anything complicated with bindings in the future, we can just extend Bindings, // instead of complicating SimpleBindings (which should stay simple) SimpleBindings bindings = new SimpleBindings(); boolean needsScores = false; ReplaceableConstDoubleValueSource specialValue = null; for (String variable : expr.variables) { try { if (variable.equals("_score")) { bindings.add("_score", DoubleValuesSource.SCORES); needsScores = true; } else if (variable.equals("_value")) { specialValue = new ReplaceableConstDoubleValueSource(); bindings.add("_value", specialValue); // noop: _value is special for aggregations, and is handled in ExpressionScriptBindings // TODO: if some uses it in a scoring expression, they will get a nasty failure when evaluating...need a // way to know this is for aggregations and so _value is ok to have... } else if (vars != null && vars.containsKey(variable)) { bindFromParams(vars, bindings, variable); } else { // delegate valuesource creation based on field's type // there are three types of "fields" to expressions, and each one has a different "api" of variables and methods. final DoubleValuesSource valueSource = getDocValueSource(variable, lookup); needsScores |= valueSource.needsScores(); bindings.add(variable, valueSource); } } catch (Exception e) { // we defer "binding" of variables until here: give context for that variable throw convertToScriptException("link error", expr.sourceText, variable, e); } } return new ExpressionAggregationScript(expr, bindings, needsScores, specialValue); } private static FieldScript.LeafFactory newFieldScript(Expression expr, SearchLookup lookup, @Nullable Map<String, Object> vars) { SimpleBindings bindings = new SimpleBindings(); for (String variable : expr.variables) { try { if (vars != null && vars.containsKey(variable)) { bindFromParams(vars, bindings, variable); } else { bindings.add(variable, getDocValueSource(variable, lookup)); } } catch (Exception e) { throw convertToScriptException("link error", expr.sourceText, variable, e); } } return new ExpressionFieldScript(expr, bindings); } /** * This is a hack for filter scripts, which must return booleans instead of doubles as expression do. * See https://github.com/elastic/elasticsearch/issues/26429. */ private static FilterScript.LeafFactory newFilterScript(Expression expr, SearchLookup lookup, @Nullable Map<String, Object> vars) { ScoreScript.LeafFactory searchLeafFactory = newScoreScript(expr, lookup, vars); return docReader -> { ScoreScript script = searchLeafFactory.newInstance(docReader); return new FilterScript(vars, lookup, docReader) { @Override public boolean execute() { return script.execute(null) != 0.0; } @Override public void setDocument(int docid) { script.setDocument(docid); } }; }; } private static ScoreScript.LeafFactory newScoreScript(Expression expr, SearchLookup lookup, @Nullable Map<String, Object> vars) { // NOTE: if we need to do anything complicated with bindings in the future, we can just extend Bindings, // instead of complicating SimpleBindings (which should stay simple) SimpleBindings bindings = new SimpleBindings(); boolean needsScores = false; for (String variable : expr.variables) { try { if (variable.equals("_score")) { bindings.add("_score", DoubleValuesSource.SCORES); needsScores = true; } else if (variable.equals("_value")) { bindings.add("_value", DoubleValuesSource.constant(0)); // noop: _value is special for aggregations, and is handled in ExpressionScriptBindings // TODO: if some uses it in a scoring expression, they will get a nasty failure when evaluating...need a // way to know this is for aggregations and so _value is ok to have... } else if (vars != null && vars.containsKey(variable)) { bindFromParams(vars, bindings, variable); } else { // delegate valuesource creation based on field's type // there are three types of "fields" to expressions, and each one has a different "api" of variables and methods. final DoubleValuesSource valueSource = getDocValueSource(variable, lookup); needsScores |= valueSource.needsScores(); bindings.add(variable, valueSource); } } catch (Exception e) { // we defer "binding" of variables until here: give context for that variable throw convertToScriptException("link error", expr.sourceText, variable, e); } } return new ExpressionScoreScript(expr, bindings, needsScores); } /** * converts a ParseException at compile-time or link-time to a ScriptException */ private static ScriptException convertToScriptException(String message, String source, String portion, Throwable cause) { List<String> stack = new ArrayList<>(); stack.add(portion); StringBuilder pointer = new StringBuilder(); if (cause instanceof ParseException) { int offset = ((ParseException) cause).getErrorOffset(); for (int i = 0; i < offset; i++) { pointer.append(' '); } } pointer.append("^---- HERE"); stack.add(pointer.toString()); throw new ScriptException(message, cause, stack, source, NAME); } private static DoubleValuesSource getDocValueSource(String variable, SearchLookup lookup) throws ParseException { VariableContext[] parts = VariableContext.parse(variable); if (parts[0].text.equals("doc") == false) { throw new ParseException("Unknown variable [" + parts[0].text + "]", 0); } if (parts.length < 2 || parts[1].type != VariableContext.Type.STR_INDEX) { throw new ParseException("Variable 'doc' must be used with a specific field like: doc['myfield']", 3); } // .value is the default for doc['field'], its optional. String variablename = "value"; String methodname = null; if (parts.length == 3) { if (parts[2].type == VariableContext.Type.METHOD) { methodname = parts[2].text; } else if (parts[2].type == VariableContext.Type.MEMBER) { variablename = parts[2].text; } else { throw new IllegalArgumentException( "Only member variables or member methods may be accessed on a field when not accessing the field directly" ); } } // true if the variable is of type doc['field'].date.xxx boolean dateAccessor = false; if (parts.length > 3) { // access to the .date "object" within the field if (parts.length == 4 && ("date".equals(parts[2].text) || "getDate".equals(parts[2].text))) { if (parts[3].type == VariableContext.Type.METHOD) { methodname = parts[3].text; dateAccessor = true; } else if (parts[3].type == VariableContext.Type.MEMBER) { variablename = parts[3].text; dateAccessor = true; } } if (dateAccessor == false) { throw new IllegalArgumentException( "Variable [" + variable + "] does not follow an allowed format of either doc['field'] or doc['field'].method()" ); } } String fieldname = parts[1].text; MappedFieldType fieldType = lookup.fieldType(fieldname); if (fieldType == null) { throw new ParseException("Field [" + fieldname + "] does not exist in mappings", 5); } IndexFieldData<?> fieldData = lookup.getForField(fieldType, MappedFieldType.FielddataOperation.SEARCH); final DoubleValuesSource valueSource; if (fieldType instanceof GeoPointFieldType) { // geo if (methodname == null) { valueSource = GeoField.getVariable(fieldData, fieldname, variablename); } else { valueSource = GeoField.getMethod(fieldData, fieldname, methodname); } } else if (fieldType instanceof DateFieldMapper.DateFieldType) { if (dateAccessor) { // date object if (methodname == null) { valueSource = DateObject.getVariable(fieldData, fieldname, variablename); } else { valueSource = DateObject.getMethod(fieldData, fieldname, methodname); } } else { // date field itself if (methodname == null) { valueSource = DateField.getVariable(fieldData, fieldname, variablename); } else { valueSource = DateField.getMethod(fieldData, fieldname, methodname); } } } else if (fieldData instanceof IndexNumericFieldData) { // number if (methodname == null) { valueSource = NumericField.getVariable(fieldData, fieldname, variablename); } else { valueSource = NumericField.getMethod(fieldData, fieldname, methodname); } } else { throw new ParseException("Field [" + fieldname + "] must be numeric, date, or geopoint", 5); } return valueSource; } // TODO: document and/or error if params contains _score? // NOTE: by checking for the variable in params first, it allows masking document fields with a global constant, // but if we were to reverse it, we could provide a way to supply dynamic defaults for documents missing the field? private static void bindFromParams(@Nullable final Map<String, Object> params, final SimpleBindings bindings, final String variable) throws ParseException { // NOTE: by checking for the variable in vars first, it allows masking document fields with a global constant, // but if we were to reverse it, we could provide a way to supply dynamic defaults for documents missing the field? Object value = params.get(variable); if (value instanceof Number) { bindings.add(variable, DoubleValuesSource.constant(((Number) value).doubleValue())); } else { throw new ParseException("Parameter [" + variable + "] must be a numeric type", 0); } } }
ExpressionScriptEngine
java
resilience4j__resilience4j
resilience4j-framework-common/src/main/java/io/github/resilience4j/common/circuitbreaker/configuration/CommonCircuitBreakerConfigurationProperties.java
{ "start": 1661, "end": 13499 }
class ____ extends CommonProperties { private static final String DEFAULT = "default"; private Map<String, InstanceProperties> instances = new HashMap<>(); private Map<String, InstanceProperties> configs = new HashMap<>(); public Optional<InstanceProperties> findCircuitBreakerProperties(String name) { InstanceProperties instanceProperties = instances.get(name); if (instanceProperties == null) { instanceProperties = configs.get(DEFAULT); } else if (configs.get(DEFAULT) != null) { ConfigUtils.mergePropertiesIfAny(instanceProperties, configs.get(DEFAULT)); } return Optional.ofNullable(instanceProperties); } public CircuitBreakerConfig createCircuitBreakerConfig(String instanceName, @Nullable InstanceProperties instanceProperties, CompositeCustomizer<CircuitBreakerConfigCustomizer> customizer) { CircuitBreakerConfig baseConfig = null; if (instanceProperties != null && StringUtils.isNotEmpty(instanceProperties.getBaseConfig())) { baseConfig = createBaseConfig(instanceName, instanceProperties, customizer); } else if (configs.get(instanceName) != null) { baseConfig = createDirectConfig(instanceName, instanceProperties, customizer); } else if (configs.get(DEFAULT) != null) { baseConfig = createDefaultConfig(instanceProperties, customizer); } return buildConfig(baseConfig != null ? from(baseConfig) : custom(), instanceProperties, customizer, instanceName); } private CircuitBreakerConfig createBaseConfig(String instanceName, InstanceProperties instanceProperties, CompositeCustomizer<CircuitBreakerConfigCustomizer> customizer) { String baseConfigName = instanceProperties.getBaseConfig(); if (instanceName.equals(baseConfigName)) { throw new IllegalStateException("Circular reference detected in instance config: " + instanceName); } InstanceProperties baseProperties = configs.get(baseConfigName); if (baseProperties == null) { throw new ConfigurationNotFoundException(baseConfigName); } ConfigUtils.mergePropertiesIfAny(instanceProperties, baseProperties); return createCircuitBreakerConfig(baseConfigName, baseProperties, customizer); } private CircuitBreakerConfig createDirectConfig(String instanceName, @Nullable InstanceProperties instanceProperties, CompositeCustomizer<CircuitBreakerConfigCustomizer> customizer) { if (instanceProperties != null) { ConfigUtils.mergePropertiesIfAny(instanceProperties, configs.get(instanceName)); } return buildConfig(custom(), configs.get(instanceName), customizer, instanceName); } private CircuitBreakerConfig createDefaultConfig( @Nullable InstanceProperties instanceProperties, CompositeCustomizer<CircuitBreakerConfigCustomizer> customizer) { if (instanceProperties != null) { ConfigUtils.mergePropertiesIfAny(instanceProperties, configs.get(DEFAULT)); } return createCircuitBreakerConfig(DEFAULT, configs.get(DEFAULT), customizer); } private CircuitBreakerConfig buildConfig(Builder builder, @Nullable InstanceProperties properties, CompositeCustomizer<CircuitBreakerConfigCustomizer> compositeCircuitBreakerCustomizer, String instanceName) { if (properties != null) { if (properties.enableExponentialBackoff != null && properties.enableExponentialBackoff && properties.enableRandomizedWait != null && properties.enableRandomizedWait) { throw new IllegalStateException( "you can not enable Exponential backoff policy and randomized delay at the same time , please enable only one of them"); } configureCircuitBreakerOpenStateIntervalFunction(properties, builder); if (properties.getFailureRateThreshold() != null) { builder.failureRateThreshold(properties.getFailureRateThreshold()); } if (properties.getWritableStackTraceEnabled() != null) { builder.writableStackTraceEnabled(properties.getWritableStackTraceEnabled()); } if (properties.getSlowCallRateThreshold() != null) { builder.slowCallRateThreshold(properties.getSlowCallRateThreshold()); } if (properties.getSlowCallDurationThreshold() != null) { builder.slowCallDurationThreshold(properties.getSlowCallDurationThreshold()); } if (properties.getMaxWaitDurationInHalfOpenState() != null) { builder.maxWaitDurationInHalfOpenState(properties.getMaxWaitDurationInHalfOpenState()); } if (properties.getTransitionToStateAfterWaitDuration() != null) { builder.transitionToStateAfterWaitDuration(properties.getTransitionToStateAfterWaitDuration()); } if (properties.getSlidingWindowSize() != null) { builder.slidingWindowSize(properties.getSlidingWindowSize()); } if (properties.getMinimumNumberOfCalls() != null) { builder.minimumNumberOfCalls(properties.getMinimumNumberOfCalls()); } if (properties.getSlidingWindowType() != null) { builder.slidingWindowType(properties.getSlidingWindowType()); } if (properties.getPermittedNumberOfCallsInHalfOpenState() != null) { builder.permittedNumberOfCallsInHalfOpenState( properties.getPermittedNumberOfCallsInHalfOpenState()); } if (properties.recordExceptions != null) { builder.recordExceptions(properties.recordExceptions); // if instance config has set recordExceptions, then base config's recordExceptionPredicate is useless. builder.recordException(null); } if (properties.recordFailurePredicate != null) { buildRecordFailurePredicate(properties, builder); } if (properties.recordResultPredicate != null) { buildRecordResultPredicate(properties, builder); } if (properties.ignoreExceptions != null) { builder.ignoreExceptions(properties.ignoreExceptions); builder.ignoreException(null); } if (properties.ignoreExceptionPredicate != null) { buildIgnoreExceptionPredicate(properties, builder); } if (properties.automaticTransitionFromOpenToHalfOpenEnabled != null) { builder.automaticTransitionFromOpenToHalfOpenEnabled( properties.automaticTransitionFromOpenToHalfOpenEnabled); } if(properties.getInitialState() != null){ builder.initialState(properties.getInitialState()); } } compositeCircuitBreakerCustomizer.getCustomizer(instanceName).ifPresent( circuitBreakerConfigCustomizer -> circuitBreakerConfigCustomizer.customize(builder)); return builder.build(); } /** * decide which circuit breaker delay policy for open state will be configured based into the * configured properties * * @param properties the backend circuit breaker properties * @param builder the circuit breaker config builder */ private void configureCircuitBreakerOpenStateIntervalFunction(InstanceProperties properties, CircuitBreakerConfig.Builder builder) { Duration waitDurationInOpenState = properties.getWaitDurationInOpenState(); if (waitDurationInOpenState != null && waitDurationInOpenState.toMillis() > 0) { if (properties.getEnableExponentialBackoff() != null && properties.getEnableExponentialBackoff()) { configureEnableExponentialBackoff(properties, builder); } else if (properties.getEnableRandomizedWait() != null && properties.getEnableRandomizedWait()) { configureEnableRandomizedWait(properties, builder); } else { builder.waitDurationInOpenState(waitDurationInOpenState); } } } private void configureEnableExponentialBackoff(InstanceProperties properties, Builder builder) { Duration maxWaitDuration = properties.getExponentialMaxWaitDurationInOpenState(); Double backoffMultiplier = properties.getExponentialBackoffMultiplier(); Duration waitDuration = properties.getWaitDurationInOpenState(); if (maxWaitDuration != null && backoffMultiplier != null) { builder.waitIntervalFunctionInOpenState( IntervalFunction.ofExponentialBackoff(waitDuration, backoffMultiplier, maxWaitDuration)); } else if (backoffMultiplier != null) { builder.waitIntervalFunctionInOpenState( IntervalFunction.ofExponentialBackoff(waitDuration, backoffMultiplier)); } else { builder.waitIntervalFunctionInOpenState( IntervalFunction.ofExponentialBackoff(waitDuration)); } } private void configureEnableRandomizedWait(InstanceProperties properties, Builder builder) { Duration waitDuration = properties.getWaitDurationInOpenState(); if (properties.getRandomizedWaitFactor() != null) { builder.waitIntervalFunctionInOpenState( IntervalFunction.ofRandomized(waitDuration, properties.getRandomizedWaitFactor())); } else { builder.waitIntervalFunctionInOpenState( IntervalFunction.ofRandomized(waitDuration)); } } private void buildRecordFailurePredicate(InstanceProperties properties, Builder builder) { if (properties.getRecordFailurePredicate() != null) { Predicate<Throwable> predicate = ClassUtils.instantiatePredicateClass(properties.getRecordFailurePredicate()); if (predicate != null) { builder.recordException(predicate); } } } private void buildRecordResultPredicate(InstanceProperties properties, Builder builder) { if (properties.getRecordResultPredicate() != null) { Predicate<Object> predicate = ClassUtils.instantiatePredicateClass(properties.getRecordResultPredicate()); if (predicate != null) { builder.recordResult(predicate); } } } private void buildIgnoreExceptionPredicate(InstanceProperties properties, Builder builder) { if (properties.getIgnoreExceptionPredicate() != null) { Predicate<Throwable> predicate = ClassUtils.instantiatePredicateClass(properties.getIgnoreExceptionPredicate()); if (predicate != null) { builder.ignoreException(predicate); } } } @Nullable public InstanceProperties getBackendProperties(String backend) { return instances.get(backend); } public Map<String, InstanceProperties> getInstances() { return instances; } /** * For backwards compatibility when setting backends in configuration properties. */ public Map<String, InstanceProperties> getBackends() { return instances; } public Map<String, InstanceProperties> getConfigs() { return configs; } /** * Class storing property values for configuring {@link io.github.resilience4j.circuitbreaker.CircuitBreaker} * instances. */ public static
CommonCircuitBreakerConfigurationProperties
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/AbstractFluxConcatMapTest.java
{ "start": 1273, "end": 29471 }
class ____ extends FluxOperatorTest<String, String> { abstract int testBasePrefetchValue(); @Override protected final Scenario<String, String> defaultScenarioOptions(Scenario<String, String> defaultOptions) { return defaultOptions.shouldHitDropNextHookAfterTerminate(false) .shouldHitDropErrorHookAfterTerminate(false) .prefetch(testBasePrefetchValue() == 0 ? -1 : testBasePrefetchValue()) .producerError(new RuntimeException("AbstractFluxConcatMapTest")); } @Override protected List<Scenario<String, String>> scenarios_operatorSuccess() { return Arrays.asList( scenario(f -> f.concatMap(Flux::just, testBasePrefetchValue())), scenario(f -> f.concatMap(d -> Flux.just(d).hide(), testBasePrefetchValue())), scenario(f -> f.concatMap(d -> Flux.empty(), testBasePrefetchValue())) .receiverEmpty(), scenario(f -> f.concatMapDelayError(Flux::just, testBasePrefetchValue())), scenario(f -> f.concatMapDelayError(d -> Flux.just(d).hide(), testBasePrefetchValue())), scenario(f -> f.concatMapDelayError(d -> Flux.empty(), testBasePrefetchValue())) .receiverEmpty(), //scenarios with fromCallable(() -> null) scenario(f -> f.concatMap(d -> Mono.fromCallable(() -> null), testBasePrefetchValue())) .receiverEmpty(), scenario(f -> f.concatMapDelayError(d -> Mono.fromCallable(() -> null), testBasePrefetchValue())) .shouldHitDropErrorHookAfterTerminate(true) .receiverEmpty() ); } @Override protected List<Scenario<String, String>> scenarios_errorFromUpstreamFailure() { return Arrays.asList( scenario(f -> f.concatMap(Flux::just, testBasePrefetchValue())), scenario(f -> f.concatMapDelayError(Flux::just, testBasePrefetchValue())) .shouldHitDropErrorHookAfterTerminate(true) ); } @Override protected List<Scenario<String, String>> scenarios_operatorError() { return Arrays.asList( scenario(f -> f.concatMap(d -> { throw exception(); }, testBasePrefetchValue())), scenario(f -> f.concatMap(d -> null, testBasePrefetchValue())), scenario(f -> f.concatMapDelayError(d -> { throw exception(); }, testBasePrefetchValue())) .shouldHitDropErrorHookAfterTerminate(true), scenario(f -> f.concatMapDelayError(d -> null, testBasePrefetchValue())) .shouldHitDropErrorHookAfterTerminate(true) ); } @Test public void normal() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 2) .concatMap(v -> Flux.range(v, 2), testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1, 2, 2, 3) .assertNoError() .assertComplete(); } @Test public void normal2() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 2) .hide() .concatMap(v -> Flux.range(v, 2), testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1, 2, 2, 3) .assertNoError() .assertComplete(); } @Test public void normalBoundary() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 2) .concatMapDelayError(v -> Flux.range(v, 2), testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1, 2, 2, 3) .assertNoError() .assertComplete(); } @Test public void normalBoundary2() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 2) .hide() .concatMapDelayError(v -> Flux.range(v, 2), testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1, 2, 2, 3) .assertNoError() .assertComplete(); } @Test public void normalLongRun() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 1000) .concatMap(v -> Flux.range(v, 1000), testBasePrefetchValue()) .subscribe(ts); ts.assertValueCount(1_000_000) .assertNoError() .assertComplete(); } @Test public void normalLongRunJust() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 1000_000) .concatMap(v -> Flux.just(v), testBasePrefetchValue()) .subscribe(ts); ts.assertValueCount(1_000_000) .assertNoError() .assertComplete(); } @Test public void normalLongRun2() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 1000) .hide() .concatMap(v -> Flux.range(v, 1000), testBasePrefetchValue()) .subscribe(ts); ts.assertValueCount(1_000_000) .assertNoError() .assertComplete(); } @Test public void normalLongRunBoundary() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 1000) .concatMapDelayError(v -> Flux.range(v, 1000), testBasePrefetchValue()) .subscribe(ts); ts.assertValueCount(1_000_000) .assertNoError() .assertComplete(); } @Test public void normalLongRunJustBoundary() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 1000_000) .concatMapDelayError(v -> Flux.just(v), testBasePrefetchValue()) .subscribe(ts); ts.assertValueCount(1_000_000) .assertNoError() .assertComplete(); } @Test public void normalLongRunBoundary2() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 1000) .hide() .concatMapDelayError(v -> Flux.range(v, 1000), testBasePrefetchValue()) .subscribe(ts); ts.assertValueCount(1_000_000) .assertNoError() .assertComplete(); } //see https://github.com/reactor/reactor-core/issues/1302 @Test public void boundaryFusion() { Flux.range(1, 10000) .publishOn(Schedulers.single()) .map(t -> Thread.currentThread().getName().contains("single-") ? "single" : ("BAD-" + t + Thread.currentThread().getName())) .concatMap(Flux::just, testBasePrefetchValue()) .publishOn(Schedulers.boundedElastic()) .distinct() .as(StepVerifier::create) .expectFusion() .expectNext("single") .expectComplete() .verify(Duration.ofSeconds(5)); } //see https://github.com/reactor/reactor-core/issues/1302 @Test public void boundaryFusionDelayError() { Flux.range(1, 10000) .publishOn(Schedulers.single()) .map(t -> Thread.currentThread().getName().contains("single-") ? "single" : ("BAD-" + t + Thread.currentThread().getName())) .concatMapDelayError(Flux::just, testBasePrefetchValue()) .publishOn(Schedulers.boundedElastic()) .distinct() .as(StepVerifier::create) .expectFusion() .expectNext("single") .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void singleSubscriberOnlyBoundary() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().concatMapDelayError(v -> v == 1 ? source1.asFlux() : source2.asFlux(), testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); source.emitNext(1, FAIL_FAST); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isPositive(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); source1.emitNext(1, FAIL_FAST); source2.emitNext(10, FAIL_FAST); source1.emitComplete(FAIL_FAST); source.emitNext(2, FAIL_FAST); source.emitComplete(FAIL_FAST); source2.emitNext(2, FAIL_FAST); source2.emitComplete(FAIL_FAST); ts.assertValues(1, 2) .assertNoError() .assertComplete(); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isZero(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); } @Test public void mainErrorsImmediate() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().concatMap(v -> v == 1 ? source1.asFlux() : source2.asFlux(), testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); source.emitNext(1, FAIL_FAST); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isPositive(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); source1.emitNext(1, FAIL_FAST); source.emitError(new RuntimeException("forced failure"), FAIL_FAST); ts.assertValues(1) .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isZero(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); } @Test public void mainErrorsBoundary() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().concatMapDelayError(v -> v == 1 ? source1.asFlux() : source2.asFlux(), testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); source.emitNext(1, FAIL_FAST); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isPositive(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); source1.emitNext(1, FAIL_FAST); source.emitError(new RuntimeException("forced failure"), FAIL_FAST); ts.assertValues(1) .assertNoError() .assertNotComplete(); source1.emitNext(2, FAIL_FAST); source1.emitComplete(FAIL_FAST); ts.assertValues(1, 2) .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isZero(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); } @Test public void innerErrorsImmediate() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().concatMap(v -> v == 1 ? source1.asFlux() : source2.asFlux(), testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); source.emitNext(1, FAIL_FAST); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isPositive(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); source1.emitNext(1, FAIL_FAST); source1.emitError(new RuntimeException("forced failure"), FAIL_FAST); ts.assertValues(1) .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isZero(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); } @Test public void syncFusionMapToNull() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 2) .map(v -> v == 2 ? null : v) .concatMap(Flux::just, testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void syncFusionMapToNullFilter() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 2) .map(v -> v == 2 ? null : v) .filter(v -> true) .concatMap(Flux::just, testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void asyncFusionMapToNull() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> up = Sinks.many().unicast().onBackpressureBuffer(Queues.<Integer>get(2).get()); up.emitNext(1, FAIL_FAST); up.emitNext(2, FAIL_FAST); up.emitComplete(FAIL_FAST); up.asFlux() .map(v -> v == 2 ? null : v) .concatMap(Flux::just, testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void asyncFusionMapToNullFilter() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> up = Sinks.many().unicast().onBackpressureBuffer(Queues.<Integer>get(2).get()); up.emitNext(1, FAIL_FAST); up.emitNext(2, FAIL_FAST); up.emitComplete(FAIL_FAST); up.asFlux() .map(v -> v == 2 ? null : v) .filter(v -> true) .concatMap(Flux::just, testBasePrefetchValue()) .subscribe(ts); ts.assertValues(1) .assertError(NullPointerException.class) .assertNotComplete(); } @Test public void scalarAndRangeBackpressured() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); @SuppressWarnings("unchecked") Publisher<Integer>[] sources = new Publisher[]{Flux.just(1), Flux.range(2, 3)}; Flux.range(0, 2) .concatMap(v -> sources[v], testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError(); ts.request(5); ts.assertValues(1, 2, 3, 4) .assertComplete() .assertNoError(); } @Test public void publisherOfPublisherDelayError2() { StepVerifier.create(Flux.just(Flux.just(1, 2) .concatWith(Flux.error(new Exception("test"))), Flux.just(3, 4)) .concatMap(f -> f, testBasePrefetchValue())) .expectNext(1, 2) .verifyErrorMessage("test"); } //see https://github.com/reactor/reactor-core/issues/936 @Test public void concatDelayErrorWithFluxError() { StepVerifier.create( Flux.concatDelayError( Flux.just( Flux.just(1, 2), Flux.error(new Exception("test")), Flux.just(3, 4)), testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } //see https://github.com/reactor/reactor-core/issues/936 @Test public void concatDelayErrorWithMonoError() { Flux<CorePublisher<Integer>> sources = Flux.just( Flux.just(1, 2), Mono.error(new Exception("test")), Flux.just(3, 4) ); StepVerifier.create(Flux.concatDelayError(sources, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } @Test public void errorModeContinueNullPublisher() { Flux<Integer> test = Flux .just(1, 2) .hide() .<Integer>concatMap(f -> null, testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectComplete() .verifyThenAssertThat() .hasDropped(1, 2) .hasDroppedErrors(2); } @Test public void errorModeContinueInternalError() { Flux<Integer> test = Flux .just(1, 2) .hide() .concatMap(f -> { if(f == 1){ return Mono.error(new NullPointerException()); } else { return Mono.just(f); } }, testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(2) .expectComplete() .verifyThenAssertThat() .hasDropped(1) .hasDroppedErrors(1); } @Test public void errorModeContinueInternalErrorHidden() { Flux<Integer> test = Flux .just(1, 2) .hide() .concatMap(f -> { if(f == 1){ return Mono.<Integer>error(new NullPointerException()).hide(); } else { return Mono.just(f); } }, testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(2) .expectComplete() .verifyThenAssertThat() .hasNotDroppedElements() .hasDroppedErrors(1); } @Test public void errorModeContinueWithCallable() { Flux<Integer> test = Flux .just(1, 2) .hide() .concatMap(f -> Mono.<Integer>fromRunnable(() -> { if(f == 1) { throw new ArithmeticException("boom"); } }), testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectComplete() .verifyThenAssertThat() .hasDropped(1) .hasDroppedErrors(1); } @Test public void errorModeContinueDelayErrors() { Flux<Integer> test = Flux .just(1, 2) .hide() .concatMapDelayError(f -> { if(f == 1){ return Mono.<Integer>error(new NullPointerException()).hide(); } else { return Mono.just(f); } }, testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(2) .expectComplete() .verifyThenAssertThat() // When inner is not a Callable error value is not available. .hasNotDroppedElements() .hasDroppedErrors(1); } @Test public void errorModeContinueDelayErrorsWithCallable() { Flux<Integer> test = Flux .just(1, 2) .hide() .concatMapDelayError(f -> { if(f == 1){ return Mono.<Integer>error(new NullPointerException()); } else { return Mono.just(f); } }, testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(2) .expectComplete() .verifyThenAssertThat() .hasDropped(1) .hasDroppedErrors(1); } @Test public void errorModeContinueInternalErrorStopStrategy() { Flux<Integer> test = Flux .just(0, 1) .hide() .concatMap(f -> Flux.range(f, 1).map(i -> 1/i).onErrorStop(), testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(1) .expectComplete() .verifyThenAssertThat() .hasNotDroppedElements() .hasDroppedErrors(1); } @Test public void errorModeContinueInternalErrorStopStrategyAsync() { Flux<Integer> test = Flux .just(0, 1) .hide() .concatMap(f -> Flux.range(f, 1).publishOn(Schedulers.parallel()).map(i -> 1 / i).onErrorStop(), testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(1) .expectComplete() .verifyThenAssertThat() .hasNotDroppedElements() .hasDroppedErrors(1); } @Test public void errorModeContinueInternalErrorMono() { Flux<Integer> test = Flux .just(0, 1) .hide() .concatMap(f -> Mono.just(f).map(i -> 1/i), testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(1) .expectComplete() .verifyThenAssertThat() .hasDropped(0) .hasDroppedErrors(1); } @Test public void errorModeContinueInternalErrorMonoAsync() { Flux<Integer> test = Flux .just(0, 1) .hide() .concatMap(f -> Mono.just(f).publishOn(Schedulers.parallel()).map(i -> 1/i), testBasePrefetchValue()) .onErrorContinue(OnNextFailureStrategyTest::drop); StepVerifier.create(test) .expectNoFusionSupport() .expectNext(1) .expectComplete() .verifyThenAssertThat() .hasDropped(0) .hasDroppedErrors(1); } @Test public void discardOnDrainMapperError() { StepVerifier.create(Flux.just(1, 2, 3) .concatMap(i -> { throw new IllegalStateException("boom"); }, testBasePrefetchValue())) .expectErrorMessage("boom") .verifyThenAssertThat() .hasDiscardedExactly(1); } @Test public void discardDelayedOnDrainMapperError() { StepVerifier.create(Flux.just(1, 2, 3) .concatMapDelayError(i -> { throw new IllegalStateException("boom"); }, testBasePrefetchValue())) .expectErrorMessage("boom") .verifyThenAssertThat() .hasDiscardedExactly(1, 2, 3); } @Test public void discardDelayedInnerOnDrainMapperError() { StepVerifier.create(Flux.just(1, 2, 3) .concatMapDelayError( i -> { if (i == 2) { throw new IllegalStateException("boom"); } return Mono.just(i); }, false, testBasePrefetchValue() )) .expectNext(1) .expectErrorMessage("boom") .verifyThenAssertThat() .hasDiscardedExactly(2); } @Test public void publisherOfPublisherDelayEnd() { StepVerifier.create(Flux.concatDelayError(Flux.just(Flux.just(1, 2), Flux.just(3, 4)), false, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyComplete(); } @Test public void publisherOfPublisherDelayEnd2() { StepVerifier.create(Flux.concatDelayError(Flux.just(Flux.just(1, 2), Flux.just(3, 4)), true, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyComplete(); } @Test public void publisherOfPublisherDelayEndNot3() { StepVerifier.create(Flux.just(Flux.just(1, 2) .concatWith(Flux.error(new Exception("test"))), Flux.just(3, 4)) .concatMapDelayError(f -> f, false, testBasePrefetchValue())) .expectNext(1, 2) .verifyErrorMessage("test"); } @Test public void publisherOfPublisherDelayEndError() { StepVerifier.create(Flux.concatDelayError(Flux.just(Flux.just(1, 2) .concatWith(Flux.error(new Exception( "test"))), Flux.just(3, 4)), false, testBasePrefetchValue())) .expectNext(1, 2) .verifyErrorMessage("test"); } @Test public void publisherOfPublisherDelayEndError2() { StepVerifier.create(Flux.concatDelayError(Flux.just(Flux.just(1, 2) .concatWith(Flux.error(new Exception( "test"))), Flux.just(3, 4)), true, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } @Test public void publisherOfPublisherDelayEnd3() { StepVerifier.create(Flux.just(Flux.just(1, 2) .concatWith(Flux.error(new Exception("test"))), Flux.just(3, 4)) .concatMapDelayError(f -> f, true, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } @Test public void innerErrorsBoundary() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort(); //gh-1101: default changed from BOUNDARY to END source.asFlux().concatMapDelayError(v -> v == 1 ? source1.asFlux() : source2.asFlux(), false, testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); source.emitNext(1, FAIL_FAST); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isPositive(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); source1.emitNext(1, FAIL_FAST); source1.emitError(new RuntimeException("forced failure"), FAIL_FAST); ts.assertValues(1) .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isZero(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); } @Test public void innerErrorsEnd() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Sinks.Many<Integer> source = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort(); source.asFlux().concatMapDelayError(v -> v == 1 ? source1.asFlux() : source2.asFlux(), true, testBasePrefetchValue()) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); source.emitNext(1, FAIL_FAST); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isPositive(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); source1.emitNext(1, FAIL_FAST); source1.emitError(new RuntimeException("forced failure"), FAIL_FAST); source.emitNext(2, FAIL_FAST); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isPositive(); source2.emitNext(2, FAIL_FAST); source2.emitComplete(FAIL_FAST); source.emitComplete(FAIL_FAST); ts.assertValues(1, 2) .assertError(RuntimeException.class) .assertErrorMessage("forced failure") .assertNotComplete(); assertThat(source1.currentSubscriberCount()).as("source1 has subscriber").isZero(); assertThat(source2.currentSubscriberCount()).as("source2 has subscriber").isZero(); } @Test public void publisherOfPublisherDelay() { StepVerifier.create(Flux.concatDelayError(Flux.just(Flux.just(1, 2), Flux.just(3, 4)), testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyComplete(); } @Test public void publisherOfPublisherDelayError() { StepVerifier.create(Flux.concatDelayError(Flux.just(Flux.just(1, 2).concatWith(Flux.error(new Exception("test"))), Flux.just(3, 4)), testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } //see https://github.com/reactor/reactor-core/issues/936 @Test public void concatMapDelayErrorWithFluxError() { StepVerifier.create( Flux.just( Flux.just(1, 2), Flux.<Integer>error(new Exception("test")), Flux.just(3, 4)) .concatMapDelayError(f -> f, true, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } //see https://github.com/reactor/reactor-core/issues/936 @Test public void concatMapDelayErrorWithMonoError() { StepVerifier.create( Flux.just( Flux.just(1, 2), Mono.<Integer>error(new Exception("test")), Flux.just(3, 4)) .concatMapDelayError(f -> f, true, testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyErrorMessage("test"); } @Test public void publisherOfPublisher() { StepVerifier.create(Flux.concat(Flux.just(Flux.just(1, 2), Flux.just(3, 4)), testBasePrefetchValue())) .expectNext(1, 2, 3, 4) .verifyComplete(); } }
AbstractFluxConcatMapTest
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 1288728, "end": 1294047 }
class ____ extends YamlDeserializerBase<XPathExpression> { public XPathExpressionDeserializer() { super(XPathExpression.class); } @Override protected XPathExpression newInstance() { return new XPathExpression(); } @Override protected XPathExpression newInstance(String value) { return new XPathExpression(value); } @Override protected boolean setProperty(XPathExpression target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "documentType": { String val = asText(node); target.setDocumentTypeName(val); break; } case "expression": { String val = asText(node); target.setExpression(val); break; } case "factoryRef": { String val = asText(node); target.setFactoryRef(val); break; } case "id": { String val = asText(node); target.setId(val); break; } case "logNamespaces": { String val = asText(node); target.setLogNamespaces(val); break; } case "namespace": { java.util.List<org.apache.camel.model.PropertyDefinition> val = asFlatList(node, org.apache.camel.model.PropertyDefinition.class); target.setNamespace(val); break; } case "objectModel": { String val = asText(node); target.setObjectModel(val); break; } case "preCompile": { String val = asText(node); target.setPreCompile(val); break; } case "resultQName": { String val = asText(node); target.setResultQName(val); break; } case "resultType": { String val = asText(node); target.setResultTypeName(val); break; } case "saxon": { String val = asText(node); target.setSaxon(val); break; } case "source": { String val = asText(node); target.setSource(val); break; } case "threadSafety": { String val = asText(node); target.setThreadSafety(val); break; } case "trim": { String val = asText(node); target.setTrim(val); break; } default: { ExpressionDefinition ed = target.getExpressionType(); if (ed != null) { throw new org.apache.camel.dsl.yaml.common.exception.DuplicateFieldException(node, propertyName, "as an expression"); } ed = ExpressionDeserializers.constructExpressionType(propertyKey, node); if (ed != null) { target.setExpressionType(ed); } else { return false; } } } return true; } } @YamlType( nodes = "xquery", inline = true, types = org.apache.camel.model.language.XQueryExpression.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "XQuery", description = "Evaluates an XQuery expressions against an XML payload.", deprecated = false, properties = { @YamlProperty(name = "configurationRef", type = "string", description = "Reference to a saxon configuration instance in the registry to use for xquery (requires camel-saxon). This may be needed to add custom functions to a saxon configuration, so these custom functions can be used in xquery expressions.", displayName = "Configuration Ref"), @YamlProperty(name = "expression", type = "string", required = true, description = "The expression value in your chosen language syntax", displayName = "Expression"), @YamlProperty(name = "id", type = "string", description = "Sets the id of this node", displayName = "Id"), @YamlProperty(name = "namespace", type = "array:org.apache.camel.model.PropertyDefinition", description = "Injects the XML Namespaces of prefix - uri mappings", displayName = "Namespace"), @YamlProperty(name = "resultType", type = "string", description = "Sets the
XPathExpressionDeserializer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java
{ "start": 30951, "end": 31396 }
class ____ { @LazyInit int a = 42; } """) .doTest(); } @Test public void lazyInitMutable() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.ThreadSafe; import com.google.errorprone.annotations.concurrent.LazyInit; import java.util.List; @ThreadSafe
Test
java
quarkusio__quarkus
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/graal/QuartzSubstitutions.java
{ "start": 700, "end": 863 }
class ____ { @Substitute protected RemotableQuartzScheduler getRemoteScheduler() { return null; } } final
Target_org_quartz_impl_RemoteScheduler
java
apache__spark
common/kvstore/src/main/java/org/apache/spark/util/kvstore/LevelDB.java
{ "start": 2393, "end": 12983 }
class ____ * will often have a long, redundant prefix (think "org.apache.spark."). */ private final ConcurrentMap<String, byte[]> typeAliases; private final ConcurrentMap<Class<?>, LevelDBTypeInfo> types; /** * Trying to close a JNI LevelDB handle with a closed DB causes JVM crashes. This is used to * ensure that all iterators are correctly closed before LevelDB is closed. Use weak references * to ensure that the iterator can be GCed, when it is only referenced here. */ private final ConcurrentLinkedQueue<Reference<LevelDBIterator<?>>> iteratorTracker; public LevelDB(File path) throws Exception { this(path, new KVStoreSerializer()); } public LevelDB(File path, KVStoreSerializer serializer) throws Exception { this.serializer = serializer; this.types = new ConcurrentHashMap<>(); Options options = new Options(); options.createIfMissing(true); this._db = new AtomicReference<>(JniDBFactory.factory.open(path, options)); byte[] versionData = db().get(STORE_VERSION_KEY); if (versionData != null) { long version = serializer.deserializeLong(versionData); if (version != STORE_VERSION) { close(); throw new UnsupportedStoreVersionException(); } } else { db().put(STORE_VERSION_KEY, serializer.serialize(STORE_VERSION)); } Map<String, byte[]> aliases; try { aliases = get(TYPE_ALIASES_KEY, TypeAliases.class).aliases; } catch (NoSuchElementException e) { aliases = new HashMap<>(); } typeAliases = new ConcurrentHashMap<>(aliases); iteratorTracker = new ConcurrentLinkedQueue<>(); } @Override public <T> T getMetadata(Class<T> klass) throws Exception { try { return get(METADATA_KEY, klass); } catch (NoSuchElementException nsee) { return null; } } @Override public void setMetadata(Object value) throws Exception { if (value != null) { put(METADATA_KEY, value); } else { db().delete(METADATA_KEY); } } <T> T get(byte[] key, Class<T> klass) throws Exception { byte[] data = db().get(key); if (data == null) { throw new NoSuchElementException(new String(key, UTF_8)); } return serializer.deserialize(data, klass); } private void put(byte[] key, Object value) throws Exception { JavaUtils.checkArgument(value != null, "Null values are not allowed."); db().put(key, serializer.serialize(value)); } @Override public <T> T read(Class<T> klass, Object naturalKey) throws Exception { JavaUtils.checkArgument(naturalKey != null, "Null keys are not allowed."); byte[] key = getTypeInfo(klass).naturalIndex().start(null, naturalKey); return get(key, klass); } @Override public void write(Object value) throws Exception { JavaUtils.checkArgument(value != null, "Null values are not allowed."); LevelDBTypeInfo ti = getTypeInfo(value.getClass()); try (WriteBatch batch = db().createWriteBatch()) { byte[] data = serializer.serialize(value); synchronized (ti) { updateBatch(batch, value, data, value.getClass(), ti.naturalIndex(), ti.indices()); db().write(batch); } } } public void writeAll(List<?> values) throws Exception { JavaUtils.checkArgument(values != null && !values.isEmpty(), "Non-empty values required."); // Group by class, in case there are values from different classes in the values // Typical usecase is for this to be a single class. // A NullPointerException will be thrown if values contain null object. for (Map.Entry<? extends Class<?>, ? extends List<?>> entry : values.stream().collect(Collectors.groupingBy(Object::getClass)).entrySet()) { final Iterator<?> valueIter = entry.getValue().iterator(); final Iterator<byte[]> serializedValueIter; // Deserialize outside synchronized block List<byte[]> list = new ArrayList<>(entry.getValue().size()); for (Object value : entry.getValue()) { list.add(serializer.serialize(value)); } serializedValueIter = list.iterator(); final Class<?> klass = entry.getKey(); final LevelDBTypeInfo ti = getTypeInfo(klass); synchronized (ti) { final LevelDBTypeInfo.Index naturalIndex = ti.naturalIndex(); final Collection<LevelDBTypeInfo.Index> indices = ti.indices(); try (WriteBatch batch = db().createWriteBatch()) { while (valueIter.hasNext()) { assert serializedValueIter.hasNext(); updateBatch(batch, valueIter.next(), serializedValueIter.next(), klass, naturalIndex, indices); } db().write(batch); } } } } private void updateBatch( WriteBatch batch, Object value, byte[] data, Class<?> klass, LevelDBTypeInfo.Index naturalIndex, Collection<LevelDBTypeInfo.Index> indices) throws Exception { Object existing; try { existing = get(naturalIndex.entityKey(null, value), klass); } catch (NoSuchElementException e) { existing = null; } PrefixCache cache = new PrefixCache(value); byte[] naturalKey = naturalIndex.toKey(naturalIndex.getValue(value)); for (LevelDBTypeInfo.Index idx : indices) { byte[] prefix = cache.getPrefix(idx); idx.add(batch, value, existing, data, naturalKey, prefix); } } @Override public void delete(Class<?> type, Object naturalKey) throws Exception { JavaUtils.checkArgument(naturalKey != null, "Null keys are not allowed."); try (WriteBatch batch = db().createWriteBatch()) { LevelDBTypeInfo ti = getTypeInfo(type); byte[] key = ti.naturalIndex().start(null, naturalKey); synchronized (ti) { byte[] data = db().get(key); if (data != null) { Object existing = serializer.deserialize(data, type); PrefixCache cache = new PrefixCache(existing); byte[] keyBytes = ti.naturalIndex().toKey(ti.naturalIndex().getValue(existing)); for (LevelDBTypeInfo.Index idx : ti.indices()) { idx.remove(batch, existing, keyBytes, cache.getPrefix(idx)); } db().write(batch); } } } catch (NoSuchElementException nse) { // Ignore. } } @Override public <T> KVStoreView<T> view(Class<T> type) throws Exception { return new KVStoreView<T>() { @Override public Iterator<T> iterator() { try { LevelDBIterator<T> it = new LevelDBIterator<>(type, LevelDB.this, this); iteratorTracker.add(new WeakReference<>(it)); return it; } catch (Exception e) { if (e instanceof RuntimeException re) throw re; throw new RuntimeException(e); } } }; } @Override public <T> boolean removeAllByIndexValues( Class<T> klass, String index, Collection<?> indexValues) throws Exception { LevelDBTypeInfo.Index naturalIndex = getTypeInfo(klass).naturalIndex(); boolean removed = false; KVStoreView<T> view = view(klass).index(index); for (Object indexValue : indexValues) { try (KVStoreIterator<T> iterator = view.first(indexValue).last(indexValue).closeableIterator()) { while (iterator.hasNext()) { T value = iterator.next(); Object itemKey = naturalIndex.getValue(value); delete(klass, itemKey); removed = true; } } } return removed; } @Override public long count(Class<?> type) throws Exception { LevelDBTypeInfo.Index idx = getTypeInfo(type).naturalIndex(); return idx.getCount(idx.end(null)); } @Override public long count(Class<?> type, String index, Object indexedValue) throws Exception { LevelDBTypeInfo.Index idx = getTypeInfo(type).index(index); return idx.getCount(idx.end(null, indexedValue)); } @Override public void close() throws IOException { synchronized (this._db) { DB _db = this._db.getAndSet(null); if (_db == null) { return; } try { if (iteratorTracker != null) { for (Reference<LevelDBIterator<?>> ref: iteratorTracker) { LevelDBIterator<?> it = ref.get(); if (it != null) { it.close(); } } } _db.close(); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e.getMessage(), e); } } } /** * Closes the given iterator if the DB is still open. Trying to close a JNI LevelDB handle * with a closed DB can cause JVM crashes, so this ensures that situation does not happen. */ void closeIterator(DBIterator it) throws IOException { notifyIteratorClosed(it); synchronized (this._db) { DB _db = this._db.get(); if (_db != null) { it.close(); } } } /** * Remove iterator from iterator tracker. `LevelDBIterator` calls it to notify * iterator is closed. */ void notifyIteratorClosed(DBIterator dbIterator) { iteratorTracker.removeIf(ref -> { LevelDBIterator<?> it = ref.get(); return it != null && dbIterator.equals(it.internalIterator()); }); } /** Returns metadata about indices for the given type. */ LevelDBTypeInfo getTypeInfo(Class<?> type) throws Exception { LevelDBTypeInfo ti = types.get(type); if (ti == null) { LevelDBTypeInfo tmp = new LevelDBTypeInfo(this, type, getTypeAlias(type)); ti = types.putIfAbsent(type, tmp); if (ti == null) { ti = tmp; } } return ti; } /** * Try to avoid use-after close since that has the tendency of crashing the JVM. This doesn't * prevent methods that retrieved the instance from using it after close, but hopefully will * catch most cases; otherwise, we'll need some kind of locking. */ DB db() { DB _db = this._db.get(); if (_db == null) { throw new IllegalStateException("DB is closed."); } return _db; } private byte[] getTypeAlias(Class<?> klass) throws Exception { byte[] alias = typeAliases.get(klass.getName()); if (alias == null) { synchronized (typeAliases) { byte[] tmp = String.valueOf(typeAliases.size()).getBytes(UTF_8); alias = typeAliases.putIfAbsent(klass.getName(), tmp); if (alias == null) { alias = tmp; put(TYPE_ALIASES_KEY, new TypeAliases(typeAliases)); } } } return alias; } /** Needs to be public for Jackson. */ public static
names
java
quarkusio__quarkus
extensions/tls-registry/runtime/src/main/java/io/quarkus/tls/runtime/keystores/ExpiryTrustOptions.java
{ "start": 1034, "end": 3741 }
class ____ implements TrustOptions { private final TrustOptions delegate; private final TrustStoreConfig.CertificateExpiryPolicy policy; private static final Logger LOGGER = Logger.getLogger(ExpiryTrustOptions.class); public ExpiryTrustOptions(TrustOptions delegate, TrustStoreConfig.CertificateExpiryPolicy certificateExpiryPolicy) { this.delegate = delegate; this.policy = certificateExpiryPolicy; } public TrustOptions unwrap() { return delegate; } @Override public TrustOptions copy() { return this; } @Override public TrustManagerFactory getTrustManagerFactory(Vertx vertx) throws Exception { var tmf = delegate.getTrustManagerFactory(vertx); return new TrustManagerFactory(new TrustManagerFactorySpi() { @Override protected void engineInit(KeyStore ks) throws KeyStoreException { tmf.init(ks); } @Override protected void engineInit(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException { tmf.init(spec); } @Override protected TrustManager[] engineGetTrustManagers() { var managers = tmf.getTrustManagers(); return getWrappedTrustManagers(managers); } }, tmf.getProvider(), tmf.getAlgorithm()) { // Empty - we use this pattern to have access to the protected constructor }; } @Override public Function<String, TrustManager[]> trustManagerMapper(Vertx vertx) { return Unchecked.function(new UncheckedFunction<String, TrustManager[]>() { @Override public TrustManager[] apply(String s) throws Exception { TrustManager[] tms = delegate.trustManagerMapper(vertx).apply(s); return ExpiryTrustOptions.this.getWrappedTrustManagers(tms); } }); } private TrustManager[] getWrappedTrustManagers(TrustManager[] tms) { // If we do not find any trust managers (for example in the SNI case, where we do not have a trust manager for // a given name), return `null` and not an empty array. if (tms == null) { return null; } var wrapped = new TrustManager[tms.length]; for (int i = 0; i < tms.length; i++) { var manager = tms[i]; if (!(manager instanceof X509TrustManager)) { wrapped[i] = manager; } else { wrapped[i] = new ExpiryAwareX509TrustManager((X509TrustManager) manager); } } return wrapped; } private
ExpiryTrustOptions