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__dubbo | dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java | {
"start": 2654,
"end": 7561
} | class ____ extends CombMetricsCollector<RegistryEvent> {
private Boolean collectEnabled = null;
private final ApplicationModel applicationModel;
private final RegistryStatComposite internalStat;
public RegistryMetricsCollector(ApplicationModel applicationModel) {
super(new BaseStatComposite(applicationModel) {
@Override
protected void init(ApplicationStatComposite applicationStatComposite) {
super.init(applicationStatComposite);
applicationStatComposite.init(RegistryMetricsConstants.APP_LEVEL_KEYS);
}
@Override
protected void init(ServiceStatComposite serviceStatComposite) {
super.init(serviceStatComposite);
serviceStatComposite.initWrapper(RegistryMetricsConstants.SERVICE_LEVEL_KEYS);
}
@Override
protected void init(RtStatComposite rtStatComposite) {
super.init(rtStatComposite);
rtStatComposite.init(
OP_TYPE_REGISTER,
OP_TYPE_SUBSCRIBE,
OP_TYPE_NOTIFY,
OP_TYPE_REGISTER_SERVICE,
OP_TYPE_SUBSCRIBE_SERVICE);
}
});
super.setEventMulticaster(new RegistrySubDispatcher(this));
internalStat = new RegistryStatComposite(applicationModel);
this.applicationModel = applicationModel;
}
public void setCollectEnabled(Boolean collectEnabled) {
if (collectEnabled != null) {
this.collectEnabled = collectEnabled;
}
}
@Override
public boolean isCollectEnabled() {
if (collectEnabled == null) {
ConfigManager configManager = applicationModel.getApplicationConfigManager();
configManager.getMetrics().ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getEnableRegistry()));
}
return Optional.ofNullable(collectEnabled).orElse(false);
}
@Override
public List<MetricSample> collect() {
List<MetricSample> list = new ArrayList<>();
if (!isCollectEnabled()) {
return list;
}
list.addAll(super.export(MetricsCategory.REGISTRY));
list.addAll(internalStat.export(MetricsCategory.REGISTRY));
return list;
}
public void incrMetricsNum(MetricsKey metricsKey, List<String> registryClusterNames) {
registryClusterNames.forEach(name -> internalStat.incrMetricsNum(metricsKey, name));
}
public void incrRegisterFinishNum(
MetricsKey metricsKey, String registryOpType, List<String> registryClusterNames, Long responseTime) {
registryClusterNames.forEach(name -> {
ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel);
applicationMetric.setExtraInfo(
Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name));
internalStat.incrMetricsNum(metricsKey, name);
getStats().getRtStatComposite().calcServiceKeyRt(registryOpType, responseTime, applicationMetric);
});
}
public void incrServiceRegisterNum(
MetricsKeyWrapper wrapper, String serviceKey, List<String> registryClusterNames, int size) {
registryClusterNames.forEach(name -> stats.incrementServiceKey(
wrapper,
serviceKey,
Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name),
size));
}
public void incrServiceRegisterFinishNum(
MetricsKeyWrapper wrapper,
String serviceKey,
List<String> registryClusterNames,
int size,
Long responseTime) {
registryClusterNames.forEach(name -> {
Map<String, String> extraInfo =
Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name);
ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(applicationModel, serviceKey);
serviceKeyMetric.setExtraInfo(extraInfo);
stats.incrementServiceKey(wrapper, serviceKey, extraInfo, size);
getStats().getRtStatComposite().calcServiceKeyRt(wrapper.getType(), responseTime, serviceKeyMetric);
});
}
public void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num, Map<String, String> attachments) {
this.stats.setServiceKey(metricsKey, serviceKey, num, attachments);
}
@Override
public boolean calSamplesChanged() {
// Should ensure that all the stat's samplesChanged have been compareAndSet, and cannot flip the `or` logic
boolean changed = stats.calSamplesChanged();
changed = internalStat.calSamplesChanged() || changed;
return changed;
}
}
| RegistryMetricsCollector |
java | apache__camel | components/camel-csv/src/test/java/org/apache/camel/dataformat/csv/CsvMarshalHeaderWithCustomMarshallFactoryTest.java | {
"start": 4155,
"end": 6177
} | class ____ extends CsvMarshaller {
private final Lock lock = new ReentrantLock();
private final CSVPrinter printer;
private SinglePrinterCsvMarshaller(CSVFormat format) {
super(format);
printer = createPrinter(format);
}
private static CSVPrinter createPrinter(CSVFormat format) {
try {
// Headers and header comments are written out in the constructor already.
return format.print(new StringBuilder());
} catch (IOException e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
@Override
@SuppressWarnings("unchecked")
public void marshal(Exchange exchange, Object object, OutputStream outputStream) throws IOException {
lock.lock();
try {
if (object instanceof Map) {
Map map = (Map) object;
printer.printRecord(getMapRecordValues(map));
} else {
Iterator<Map<String, String>> it = (Iterator<Map<String, String>>) ObjectHelper.createIterator(object);
while (it.hasNext()) {
printer.printRecord(getMapRecordValues(it.next()));
}
}
// Access the 'Appendable'
StringBuilder stringBuilder = (StringBuilder) printer.getOut();
outputStream.write(stringBuilder.toString().getBytes());
// Reset the 'Appendable' for the next exchange.
stringBuilder.setLength(0);
} finally {
lock.unlock();
}
}
@Override
protected Iterable<?> getMapRecordValues(Map<?, ?> map) {
List<String> result = new ArrayList<>(map.size());
for (Object o : map.values()) {
result.add((String) o);
}
return result;
}
}
}
| SinglePrinterCsvMarshaller |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryMethodInvocationMatcherTest.java | {
"start": 1451,
"end": 1918
} | class ____ {
private static final Matcher<ExpressionTree> TO_STRING =
methodInvocation(instanceMethod().anyClass().named("toString"));
}
""")
.addOutputLines(
"Test.java",
"""
import static com.google.errorprone.matchers.Matchers.*;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
public | Test |
java | apache__kafka | clients/src/test/java/org/apache/kafka/test/MockMetricsReporter.java | {
"start": 1096,
"end": 1851
} | class ____ implements MetricsReporter {
public static final AtomicInteger INIT_COUNT = new AtomicInteger(0);
public static final AtomicInteger CLOSE_COUNT = new AtomicInteger(0);
public String clientId;
public MockMetricsReporter() {
}
@Override
public void init(List<KafkaMetric> metrics) {
INIT_COUNT.incrementAndGet();
}
@Override
public void metricChange(KafkaMetric metric) {}
@Override
public void metricRemoval(KafkaMetric metric) {}
@Override
public void close() {
CLOSE_COUNT.incrementAndGet();
}
@Override
public void configure(Map<String, ?> configs) {
clientId = (String) configs.get(CommonClientConfigs.CLIENT_ID_CONFIG);
}
} | MockMetricsReporter |
java | spring-projects__spring-boot | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java | {
"start": 7534,
"end": 7922
} | class ____<K, T> {
private final Map<K, T> content;
private @Nullable T defaultItem;
private MetadataHolder() {
this.content = new HashMap<>();
}
Map<K, T> getContent() {
return this.content;
}
@Nullable T getDefaultItem() {
return this.defaultItem;
}
void setDefaultItem(@Nullable T defaultItem) {
this.defaultItem = defaultItem;
}
}
}
| MetadataHolder |
java | apache__kafka | trogdor/src/main/java/org/apache/kafka/trogdor/workload/Histogram.java | {
"start": 1027,
"end": 2412
} | class ____ {
private final int[] counts;
public Histogram(int maxValue) {
this.counts = new int[maxValue + 1];
}
/**
* Add a new value to the histogram.
*
* Note that the value will be clipped to the maximum value available in the Histogram instance.
* So if the histogram has 100 buckets, inserting 101 will increment the last bucket.
*/
public void add(int value) {
if (value < 0) {
throw new RuntimeException("invalid negative value.");
}
if (value >= counts.length) {
value = counts.length - 1;
}
synchronized (this) {
int curCount = counts[value];
if (curCount < Integer.MAX_VALUE) {
counts[value] = counts[value] + 1;
}
}
}
/**
* Add a new value to the histogram.
*
* Note that the value will be clipped to the maximum value available in the Histogram instance.
* This method is provided for convenience, but handles the same numeric range as the method which
* takes an int.
*/
public void add(long value) {
if (value > Integer.MAX_VALUE) {
add(Integer.MAX_VALUE);
} else if (value < Integer.MIN_VALUE) {
add(Integer.MIN_VALUE);
} else {
add((int) value);
}
}
public static | Histogram |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableConcatMap.java | {
"start": 14681,
"end": 16141
} | class ____<R> extends AtomicReference<Disposable> implements Observer<R> {
private static final long serialVersionUID = 2620149119579502636L;
final Observer<? super R> downstream;
final ConcatMapDelayErrorObserver<?, R> parent;
DelayErrorInnerObserver(Observer<? super R> actual, ConcatMapDelayErrorObserver<?, R> parent) {
this.downstream = actual;
this.parent = parent;
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.replace(this, d);
}
@Override
public void onNext(R value) {
downstream.onNext(value);
}
@Override
public void onError(Throwable e) {
ConcatMapDelayErrorObserver<?, R> p = parent;
if (p.errors.tryAddThrowableOrReport(e)) {
if (!p.tillTheEnd) {
p.upstream.dispose();
}
p.active = false;
p.drain();
}
}
@Override
public void onComplete() {
ConcatMapDelayErrorObserver<?, R> p = parent;
p.active = false;
p.drain();
}
void dispose() {
DisposableHelper.dispose(this);
}
}
}
}
| DelayErrorInnerObserver |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java | {
"start": 4491,
"end": 4683
} | class ____
* {@link SpringExtensionConfig#useTestClassScopedExtensionContext()
* @SpringExtensionConfig(useTestClassScopedExtensionContext = true)}.
*
* <p><strong>NOTE:</strong> This | with |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/gwt/CustomFieldSerializerTest.java | {
"start": 5630,
"end": 6462
} | interface ____ {
Builder string(String x);
Builder strings(ImmutableList<String> x);
ValueTypeWithBuilder build();
}
}
@Test
public void testCustomFieldSerializerWithBuilder() throws SerializationException {
AutoValue_CustomFieldSerializerTest_ValueTypeWithBuilder instance =
(AutoValue_CustomFieldSerializerTest_ValueTypeWithBuilder)
ValueTypeWithBuilder.builder().string("s").strings(ImmutableList.of("a", "b")).build();
AutoValue_CustomFieldSerializerTest_ValueTypeWithBuilder_CustomFieldSerializer.serialize(
streamWriter, instance);
mock.verify(
() -> {
streamWriter.writeString("s");
streamWriter.writeObject(ImmutableList.of("a", "b"));
});
}
@AutoValue
@GwtCompatible(serializable = true)
abstract static | Builder |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1700/Issue1772.java | {
"start": 716,
"end": 764
} | class ____ {
public Date time;
}
}
| Model |
java | square__retrofit | retrofit-mock/src/main/java/retrofit2/mock/MockRetrofitIOException.java | {
"start": 661,
"end": 815
} | class ____ extends IOException {
MockRetrofitIOException() {
super("Failure triggered by MockRetrofit's NetworkBehavior");
}
}
| MockRetrofitIOException |
java | grpc__grpc-java | core/src/test/java/io/grpc/internal/RetryingNameResolverTest.java | {
"start": 1468,
"end": 4410
} | class ____ {
@Rule
public final MockitoRule mocks = MockitoJUnit.rule();
@Mock
private NameResolver mockNameResolver;
@Mock
private Listener2 mockListener;
@Mock
private RetryScheduler mockRetryScheduler;
@Captor
private ArgumentCaptor<Listener2> listenerCaptor;
private final SynchronizationContext syncContext = new SynchronizationContext(
mock(UncaughtExceptionHandler.class));
private RetryingNameResolver retryingNameResolver;
@Before
public void setup() {
retryingNameResolver = new RetryingNameResolver(mockNameResolver, mockRetryScheduler,
syncContext);
}
@Test
public void startAndShutdown() {
retryingNameResolver.start(mockListener);
retryingNameResolver.shutdown();
}
@Test
public void onResult_success() {
when(mockListener.onResult2(isA(ResolutionResult.class))).thenReturn(Status.OK);
retryingNameResolver.start(mockListener);
verify(mockNameResolver).start(listenerCaptor.capture());
listenerCaptor.getValue().onResult(ResolutionResult.newBuilder().build());
verify(mockRetryScheduler).reset();
}
@Test
public void onResult2_sucesss() {
when(mockListener.onResult2(isA(ResolutionResult.class))).thenReturn(Status.OK);
retryingNameResolver.start(mockListener);
verify(mockNameResolver).start(listenerCaptor.capture());
assertThat(listenerCaptor.getValue().onResult2(ResolutionResult.newBuilder().build()))
.isEqualTo(Status.OK);
verify(mockRetryScheduler).reset();
}
// Make sure that a retry gets scheduled when the resolution results are rejected.
@Test
public void onResult_failure() {
when(mockListener.onResult2(isA(ResolutionResult.class))).thenReturn(Status.UNAVAILABLE);
retryingNameResolver.start(mockListener);
verify(mockNameResolver).start(listenerCaptor.capture());
listenerCaptor.getValue().onResult(ResolutionResult.newBuilder().build());
verify(mockRetryScheduler).schedule(isA(Runnable.class));
}
// Make sure that a retry gets scheduled when the resolution results are rejected.
@Test
public void onResult2_failure() {
when(mockListener.onResult2(isA(ResolutionResult.class))).thenReturn(Status.UNAVAILABLE);
retryingNameResolver.start(mockListener);
verify(mockNameResolver).start(listenerCaptor.capture());
assertThat(listenerCaptor.getValue().onResult2(ResolutionResult.newBuilder().build()))
.isEqualTo(Status.UNAVAILABLE);
verify(mockRetryScheduler).schedule(isA(Runnable.class));
}
// A retry should get scheduled when name resolution fails.
@Test
public void onError() {
retryingNameResolver.start(mockListener);
verify(mockNameResolver).start(listenerCaptor.capture());
listenerCaptor.getValue().onError(Status.DEADLINE_EXCEEDED);
verify(mockListener).onError(Status.DEADLINE_EXCEEDED);
verify(mockRetryScheduler).schedule(isA(Runnable.class));
}
}
| RetryingNameResolverTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/injection/guice/spi/Elements.java | {
"start": 1770,
"end": 2370
} | class ____ {
/**
* Records the elements executed by {@code modules}.
*/
public static List<Element> getElements(Module... modules) {
return getElements(Arrays.asList(modules));
}
/**
* Records the elements executed by {@code modules}.
*/
public static List<Element> getElements(Iterable<? extends Module> modules) {
RecordingBinder binder = new RecordingBinder();
for (Module module : modules) {
binder.install(module);
}
return Collections.unmodifiableList(binder.elements);
}
private static | Elements |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/autoquote/SpecialCharactersTest.java | {
"start": 459,
"end": 595
} | class ____ {
@Test void test(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory();
}
@Entity static | SpecialCharactersTest |
java | apache__spark | common/network-shuffle/src/test/java/org/apache/spark/network/shuffle/OneForOneBlockPusherSuite.java | {
"start": 1828,
"end": 7478
} | class ____ {
@Test
public void testPushOne() {
LinkedHashMap<String, ManagedBuffer> blocks = new LinkedHashMap<>();
blocks.put("shufflePush_0_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[1])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id", 0, 0, 0, 0, 0, 0)));
verify(listener).onBlockPushSuccess(eq("shufflePush_0_0_0_0"), any());
}
@Test
public void testPushThree() {
LinkedHashMap<String, ManagedBuffer> blocks = new LinkedHashMap<>();
blocks.put("shufflePush_0_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[12])));
blocks.put("shufflePush_0_0_1_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[23])));
blocks.put("shufflePush_0_0_2_0",
new NettyManagedBuffer(Unpooled.wrappedBuffer(new byte[23])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id",0, 0, 0, 0, 0, 0),
new PushBlockStream("app-id", 0, 0, 0, 1, 0, 1),
new PushBlockStream("app-id", 0, 0, 0, 2, 0, 2)));
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_0_0"), any());
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_1_0"), any());
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_2_0"), any());
}
@Test
public void testServerFailures() {
LinkedHashMap<String, ManagedBuffer> blocks = new LinkedHashMap<>();
blocks.put("shufflePush_0_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[12])));
blocks.put("shufflePush_0_0_1_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[0])));
blocks.put("shufflePush_0_0_2_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[0])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id", 0, 0, 0, 0, 0, 0),
new PushBlockStream("app-id", 0, 0, 0, 1, 0, 1),
new PushBlockStream("app-id", 0, 0, 0, 2, 0, 2)));
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_0_0"), any());
verify(listener, times(1)).onBlockPushFailure(eq("shufflePush_0_0_1_0"), any());
verify(listener, times(1)).onBlockPushFailure(eq("shufflePush_0_0_2_0"), any());
}
@Test
public void testHandlingRetriableFailures() {
LinkedHashMap<String, ManagedBuffer> blocks = new LinkedHashMap<>();
blocks.put("shufflePush_0_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[12])));
blocks.put("shufflePush_0_0_1_0", null);
blocks.put("shufflePush_0_0_2_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[0])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id", 0, 0, 0, 0, 0, 0),
new PushBlockStream("app-id", 0, 0, 0, 1, 0, 1),
new PushBlockStream("app-id", 0, 0, 0, 2, 0, 2)));
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_0_0"), any());
verify(listener, times(0)).onBlockPushSuccess(not(eq("shufflePush_0_0_0_0")), any());
verify(listener, times(0)).onBlockPushFailure(eq("shufflePush_0_0_0_0"), any());
verify(listener, times(1)).onBlockPushFailure(eq("shufflePush_0_0_1_0"), any());
verify(listener, times(2)).onBlockPushFailure(eq("shufflePush_0_0_2_0"), any());
}
/**
* Begins a push on the given set of blocks by mocking the response from server side.
* If a block is an empty byte, a server side retriable exception will be thrown.
* If a block is null, a non-retriable exception will be thrown.
*/
private static BlockPushingListener pushBlocks(
LinkedHashMap<String, ManagedBuffer> blocks,
String[] blockIds,
Iterable<BlockTransferMessage> expectMessages) {
TransportClient client = mock(TransportClient.class);
BlockPushingListener listener = mock(BlockPushingListener.class);
OneForOneBlockPusher pusher =
new OneForOneBlockPusher(client, "app-id", 0, blockIds, listener, blocks);
Iterator<Map.Entry<String, ManagedBuffer>> blockIterator = blocks.entrySet().iterator();
Iterator<BlockTransferMessage> msgIterator = expectMessages.iterator();
doAnswer(invocation -> {
ByteBuffer header = ((ManagedBuffer) invocation.getArguments()[0]).nioByteBuffer();
BlockTransferMessage message = BlockTransferMessage.Decoder.fromByteBuffer(header);
RpcResponseCallback callback = (RpcResponseCallback) invocation.getArguments()[2];
Map.Entry<String, ManagedBuffer> entry = blockIterator.next();
String blockId = entry.getKey();
ManagedBuffer block = entry.getValue();
if (block != null && block.nioByteBuffer().capacity() > 0) {
callback.onSuccess(new BlockPushReturnCode(ReturnCode.SUCCESS.id(), "").toByteBuffer());
} else if (block != null) {
callback.onSuccess(new BlockPushReturnCode(
ReturnCode.BLOCK_APPEND_COLLISION_DETECTED.id(), blockId).toByteBuffer());
} else {
callback.onFailure(new BlockPushNonFatalFailure(
ReturnCode.TOO_LATE_BLOCK_PUSH, ""));
}
assertEquals(msgIterator.next(), message);
return null;
}).when(client).uploadStream(any(ManagedBuffer.class), any(), any(RpcResponseCallback.class));
pusher.start();
return listener;
}
}
| OneForOneBlockPusherSuite |
java | resilience4j__resilience4j | resilience4j-framework-common/src/main/java/io/github/resilience4j/common/circuitbreaker/configuration/CommonCircuitBreakerConfigurationProperties.java | {
"start": 13499,
"end": 32263
} | class ____ {
@Nullable
private Duration waitDurationInOpenState;
@Nullable
private Duration slowCallDurationThreshold;
@Nullable
private Duration maxWaitDurationInHalfOpenState;
@Nullable
private State transitionToStateAfterWaitDuration;
@Nullable
private Float failureRateThreshold;
@Nullable
private Float slowCallRateThreshold;
@Nullable
private SlidingWindowType slidingWindowType;
@Nullable
private Integer slidingWindowSize;
@Nullable
private Integer minimumNumberOfCalls;
@Nullable
private Integer permittedNumberOfCallsInHalfOpenState;
@Nullable
private Boolean automaticTransitionFromOpenToHalfOpenEnabled;
@Nullable
private State initialState;
@Nullable
private Boolean writableStackTraceEnabled;
@Nullable
private Boolean allowHealthIndicatorToFail;
@Nullable
private Integer eventConsumerBufferSize;
@Nullable
private Boolean registerHealthIndicator;
@Nullable
private Class<Predicate<Throwable>> recordFailurePredicate;
@Nullable
private Class<? extends Throwable>[] recordExceptions;
@Nullable
private Class<Predicate<Object>> recordResultPredicate;
@Nullable
private Class<Predicate<Throwable>> ignoreExceptionPredicate;
@Nullable
private Class<? extends Throwable>[] ignoreExceptions;
@Nullable
private String baseConfig;
/**
* flag to enable Exponential backoff policy or not for retry policy delay
*/
@Nullable
private Boolean enableExponentialBackoff;
/**
* exponential backoff multiplier value
*/
private Double exponentialBackoffMultiplier;
/**
* exponential max interval value
*/
private Duration exponentialMaxWaitDurationInOpenState;
/**
* flag to enable randomized delay policy or not for retry policy delay
*/
@Nullable
private Boolean enableRandomizedWait;
/**
* randomized delay factor value
*/
private Double randomizedWaitFactor;
@Nullable
private Boolean ignoreClassBindingExceptions;
/**
* Returns the failure rate threshold for the circuit breaker as percentage.
*
* @return the failure rate threshold
*/
@Nullable
public Float getFailureRateThreshold() {
return failureRateThreshold;
}
/**
* Sets the failure rate threshold for the circuit breaker as percentage.
*
* @param failureRateThreshold the failure rate threshold
*/
public InstanceProperties setFailureRateThreshold(Float failureRateThreshold) {
Objects.requireNonNull(failureRateThreshold);
if (failureRateThreshold < 1 || failureRateThreshold > 100) {
throw new IllegalArgumentException(
"failureRateThreshold must be between 1 and 100.");
}
this.failureRateThreshold = failureRateThreshold;
return this;
}
/**
* Returns the wait duration the CircuitBreaker will stay open, before it switches to half
* closed.
*
* @return the wait duration
*/
@Nullable
public Duration getWaitDurationInOpenState() {
return waitDurationInOpenState;
}
/**
* Sets the wait duration the CircuitBreaker should stay open, before it switches to half
* closed.
*
* @param waitDurationInOpenStateMillis the wait duration
*/
public InstanceProperties setWaitDurationInOpenState(
Duration waitDurationInOpenStateMillis) {
Objects.requireNonNull(waitDurationInOpenStateMillis);
if (waitDurationInOpenStateMillis.toMillis() < 1) {
throw new IllegalArgumentException(
"waitDurationInOpenStateMillis must be greater than or equal to 1 millis.");
}
this.waitDurationInOpenState = waitDurationInOpenStateMillis;
return this;
}
/**
* Returns if we should automatically transition to half open after the timer has run out.
*
* @return setAutomaticTransitionFromOpenToHalfOpenEnabled if we should automatically go to
* half open or not
*/
public Boolean getAutomaticTransitionFromOpenToHalfOpenEnabled() {
return this.automaticTransitionFromOpenToHalfOpenEnabled;
}
/**
* Sets if we should automatically transition to half open after the timer has run out.
*
* @param automaticTransitionFromOpenToHalfOpenEnabled The flag for automatic transition to
* half open after the timer has run
* out.
*/
public InstanceProperties setAutomaticTransitionFromOpenToHalfOpenEnabled(
Boolean automaticTransitionFromOpenToHalfOpenEnabled) {
this.automaticTransitionFromOpenToHalfOpenEnabled = automaticTransitionFromOpenToHalfOpenEnabled;
return this;
}
/**
* Returns state by which Circuit breaker was initialized
*
* @return initialState
*/
@Nullable
public State getInitialState(){
return this.initialState;
}
/**
* Sets initial state of Circuit Breaker
*
* @param state inital state of Circuit breaker, Will set initializion using this state
*/
public InstanceProperties setInitialState(State state){
this.initialState = state;
return this;
}
/**
* Returns if we should enable writable stack traces or not.
*
* @return writableStackTraceEnabled if we should enable writable stack traces or not.
*/
@Nullable
public Boolean getWritableStackTraceEnabled() {
return this.writableStackTraceEnabled;
}
/**
* Sets if we should enable writable stack traces or not.
*
* @param writableStackTraceEnabled The flag to enable writable stack traces.
*/
public InstanceProperties setWritableStackTraceEnabled(Boolean writableStackTraceEnabled) {
this.writableStackTraceEnabled = writableStackTraceEnabled;
return this;
}
@Nullable
public Integer getEventConsumerBufferSize() {
return eventConsumerBufferSize;
}
public InstanceProperties setEventConsumerBufferSize(Integer eventConsumerBufferSize) {
Objects.requireNonNull(eventConsumerBufferSize);
if (eventConsumerBufferSize < 1) {
throw new IllegalArgumentException(
"eventConsumerBufferSize must be greater than or equal to 1.");
}
this.eventConsumerBufferSize = eventConsumerBufferSize;
return this;
}
/**
* @return the flag that controls if health indicators are allowed to go into a failed
* (DOWN) status.
* @see #setAllowHealthIndicatorToFail(Boolean)
*/
@Nullable
public Boolean getAllowHealthIndicatorToFail() {
return allowHealthIndicatorToFail;
}
/**
* When set to true, it allows the health indicator to go to a failed (DOWN) status. By
* default, health indicators for circuit breakers will never go into an unhealthy state.
*
* @param allowHealthIndicatorToFail flag to control if the health indicator is allowed to
* fail
* @return the InstanceProperties
*/
public InstanceProperties setAllowHealthIndicatorToFail(
Boolean allowHealthIndicatorToFail) {
this.allowHealthIndicatorToFail = allowHealthIndicatorToFail;
return this;
}
@Nullable
public Boolean getRegisterHealthIndicator() {
return registerHealthIndicator;
}
public InstanceProperties setRegisterHealthIndicator(Boolean registerHealthIndicator) {
this.registerHealthIndicator = registerHealthIndicator;
return this;
}
@Nullable
public Class<Predicate<Throwable>> getRecordFailurePredicate() {
return recordFailurePredicate;
}
public InstanceProperties setRecordFailurePredicate(
Class<Predicate<Throwable>> recordFailurePredicate) {
this.recordFailurePredicate = recordFailurePredicate;
return this;
}
@Nullable
public Class<Predicate<Object>> getRecordResultPredicate() {
return recordResultPredicate;
}
public InstanceProperties setRecordResultPredicate(
Class<Predicate<Object>> recordResultPredicate) {
this.recordResultPredicate = recordResultPredicate;
return this;
}
@Nullable
public Class<? extends Throwable>[] getRecordExceptions() {
return recordExceptions;
}
public InstanceProperties setRecordExceptions(
Class<? extends Throwable>[] recordExceptions) {
this.recordExceptions = recordExceptions;
return this;
}
@Nullable
public Class<Predicate<Throwable>> getIgnoreExceptionPredicate() {
return ignoreExceptionPredicate;
}
public InstanceProperties setIgnoreExceptionPredicate(
Class<Predicate<Throwable>> ignoreExceptionPredicate) {
this.ignoreExceptionPredicate = ignoreExceptionPredicate;
return this;
}
@Nullable
public Class<? extends Throwable>[] getIgnoreExceptions() {
return ignoreExceptions;
}
public InstanceProperties setIgnoreExceptions(
Class<? extends Throwable>[] ignoreExceptions) {
this.ignoreExceptions = ignoreExceptions;
return this;
}
/**
* Gets the shared configuration name. If this is set, the configuration builder will use
* the shared configuration backend over this one.
*
* @return The shared configuration name.
*/
@Nullable
public String getBaseConfig() {
return baseConfig;
}
/**
* Sets the shared configuration name. If this is set, the configuration builder will use
* the shared configuration backend over this one.
*
* @param baseConfig The shared configuration name.
*/
public InstanceProperties setBaseConfig(String baseConfig) {
this.baseConfig = baseConfig;
return this;
}
@Nullable
public Integer getPermittedNumberOfCallsInHalfOpenState() {
return permittedNumberOfCallsInHalfOpenState;
}
public InstanceProperties setPermittedNumberOfCallsInHalfOpenState(
Integer permittedNumberOfCallsInHalfOpenState) {
Objects.requireNonNull(permittedNumberOfCallsInHalfOpenState);
if (permittedNumberOfCallsInHalfOpenState < 1) {
throw new IllegalArgumentException(
"permittedNumberOfCallsInHalfOpenState must be greater than or equal to 1.");
}
this.permittedNumberOfCallsInHalfOpenState = permittedNumberOfCallsInHalfOpenState;
return this;
}
@Nullable
public Integer getMinimumNumberOfCalls() {
return minimumNumberOfCalls;
}
public InstanceProperties setMinimumNumberOfCalls(Integer minimumNumberOfCalls) {
Objects.requireNonNull(minimumNumberOfCalls);
if (minimumNumberOfCalls < 1) {
throw new IllegalArgumentException(
"minimumNumberOfCalls must be greater than or equal to 1.");
}
this.minimumNumberOfCalls = minimumNumberOfCalls;
return this;
}
@Nullable
public Integer getSlidingWindowSize() {
return slidingWindowSize;
}
public InstanceProperties setSlidingWindowSize(Integer slidingWindowSize) {
Objects.requireNonNull(slidingWindowSize);
if (slidingWindowSize < 1) {
throw new IllegalArgumentException(
"slidingWindowSize must be greater than or equal to 1.");
}
this.slidingWindowSize = slidingWindowSize;
return this;
}
@Nullable
public Float getSlowCallRateThreshold() {
return slowCallRateThreshold;
}
public InstanceProperties setSlowCallRateThreshold(Float slowCallRateThreshold) {
Objects.requireNonNull(slowCallRateThreshold);
if (slowCallRateThreshold < 1 || slowCallRateThreshold > 100) {
throw new IllegalArgumentException(
"slowCallRateThreshold must be between 1 and 100.");
}
this.slowCallRateThreshold = slowCallRateThreshold;
return this;
}
@Nullable
public Duration getSlowCallDurationThreshold() {
return slowCallDurationThreshold;
}
@Nullable
public Duration getMaxWaitDurationInHalfOpenState() {
return maxWaitDurationInHalfOpenState;
}
@Nullable
public State getTransitionToStateAfterWaitDuration() {
return transitionToStateAfterWaitDuration;
}
public InstanceProperties setSlowCallDurationThreshold(Duration slowCallDurationThreshold) {
Objects.requireNonNull(slowCallDurationThreshold);
if (slowCallDurationThreshold.toNanos() < 1) {
throw new IllegalArgumentException(
"slowCallDurationThreshold must be greater than or equal to 1 nanos.");
}
this.slowCallDurationThreshold = slowCallDurationThreshold;
return this;
}
public InstanceProperties setMaxWaitDurationInHalfOpenState(Duration maxWaitDurationInHalfOpenState) {
Objects.requireNonNull(maxWaitDurationInHalfOpenState);
if (maxWaitDurationInHalfOpenState.toMillis() < 0) {
throw new IllegalArgumentException(
"maxWaitDurationInHalfOpenState must be greater than or equal to 0 ms.");
}
this.maxWaitDurationInHalfOpenState = maxWaitDurationInHalfOpenState;
return this;
}
public void setTransitionToStateAfterWaitDuration(State transitionToStateAfterWaitDuration) {
Objects.requireNonNull(transitionToStateAfterWaitDuration);
if (transitionToStateAfterWaitDuration != State.OPEN && transitionToStateAfterWaitDuration != State.CLOSED) {
throw new IllegalArgumentException("transitionToStateAfterWaitDuration must be either OPEN or CLOSED");
}
this.transitionToStateAfterWaitDuration = transitionToStateAfterWaitDuration;
}
@Nullable
public SlidingWindowType getSlidingWindowType() {
return slidingWindowType;
}
public InstanceProperties setSlidingWindowType(SlidingWindowType slidingWindowType) {
this.slidingWindowType = slidingWindowType;
return this;
}
public Boolean getEnableExponentialBackoff() {
return enableExponentialBackoff;
}
public InstanceProperties setEnableExponentialBackoff(Boolean enableExponentialBackoff) {
this.enableExponentialBackoff = enableExponentialBackoff;
return this;
}
@Nullable
public Double getExponentialBackoffMultiplier() {
return exponentialBackoffMultiplier;
}
public InstanceProperties setExponentialBackoffMultiplier(
Double exponentialBackoffMultiplier) {
if (exponentialBackoffMultiplier <= 0) {
throw new IllegalArgumentException(
"Illegal argument exponentialBackoffMultiplier: " + exponentialBackoffMultiplier + " is less or equal 0");
}
this.exponentialBackoffMultiplier = exponentialBackoffMultiplier;
return this;
}
@Nullable
public Duration getExponentialMaxWaitDurationInOpenState() {
return exponentialMaxWaitDurationInOpenState;
}
public InstanceProperties setExponentialMaxWaitDurationInOpenState(
Duration exponentialMaxWaitDurationInOpenState) {
if (exponentialMaxWaitDurationInOpenState.toMillis() < 1) {
throw new IllegalArgumentException(
"Illegal argument interval: " + exponentialMaxWaitDurationInOpenState + " is less than 1 millisecond");
}
this.exponentialMaxWaitDurationInOpenState = exponentialMaxWaitDurationInOpenState;
return this;
}
@Nullable
public Boolean getEnableRandomizedWait() {
return enableRandomizedWait;
}
public InstanceProperties setEnableRandomizedWait(Boolean enableRandomizedWait) {
this.enableRandomizedWait = enableRandomizedWait;
return this;
}
@Nullable
public Double getRandomizedWaitFactor() {
return randomizedWaitFactor;
}
public InstanceProperties setRandomizedWaitFactor(Double randomizedWaitFactor) {
if (randomizedWaitFactor < 0 || randomizedWaitFactor >= 1) {
throw new IllegalArgumentException(
"Illegal argument randomizedWaitFactor: " + randomizedWaitFactor + " is not in range [0..1)");
}
this.randomizedWaitFactor = randomizedWaitFactor;
return this;
}
@Nullable
public Boolean getIgnoreClassBindingExceptions() {
return ignoreClassBindingExceptions;
}
public InstanceProperties setIgnoreClassBindingExceptions(Boolean ignoreClassBindingExceptions) {
this.ignoreClassBindingExceptions = ignoreClassBindingExceptions;
return this;
}
}
}
| InstanceProperties |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/internals/AbstractReadWriteDecorator.java | {
"start": 5446,
"end": 5778
} | class ____<K, V>
extends KeyValueStoreReadWriteDecorator<K, ValueAndTimestamp<V>>
implements TimestampedKeyValueStore<K, V> {
TimestampedKeyValueStoreReadWriteDecorator(final TimestampedKeyValueStore<K, V> inner) {
super(inner);
}
}
static | TimestampedKeyValueStoreReadWriteDecorator |
java | alibaba__nacos | ai/src/test/java/com/alibaba/nacos/ai/config/McpConfigurationTest.java | {
"start": 956,
"end": 1279
} | class ____ {
@Mock
ControllerMethodsCache methodsCache;
@Test
void testInit() {
McpConfiguration mcpConfiguration = new McpConfiguration(methodsCache);
mcpConfiguration.init();
verify(methodsCache).initClassMethod("com.alibaba.nacos.ai.controller");
}
} | McpConfigurationTest |
java | spring-projects__spring-boot | module/spring-boot-mongodb/src/test/java/org/springframework/boot/mongodb/autoconfigure/MongoReactiveAutoConfigurationTests.java | {
"start": 1911,
"end": 11049
} | class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class, SslAutoConfiguration.class));
@Test
void clientExists() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoClient.class));
}
@Test
void settingsAdded() {
this.contextRunner.withPropertyValues("spring.mongodb.host:localhost")
.withUserConfiguration(SettingsConfig.class)
.run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS))
.isEqualTo(300));
}
@Test
void settingsAddedButNoHost() {
this.contextRunner.withPropertyValues("spring.mongodb.uri:mongodb://localhost/test")
.withUserConfiguration(SettingsConfig.class)
.run((context) -> assertThat(getSettings(context).getReadPreference()).isEqualTo(ReadPreference.nearest()));
}
@Test
void settingsSslConfig() {
this.contextRunner.withPropertyValues("spring.mongodb.uri:mongodb://localhost/test")
.withUserConfiguration(SslSettingsConfig.class)
.run((context) -> {
assertThat(context).hasSingleBean(MongoClient.class);
MongoClientSettings settings = getSettings(context);
assertThat(settings.getApplicationName()).isEqualTo("test-config");
assertThat(settings.getTransportSettings()).isSameAs(context.getBean("myTransportSettings"));
});
}
@Test
void configuresSslWhenEnabled() {
this.contextRunner.withPropertyValues("spring.mongodb.ssl.enabled=true").run((context) -> {
SslSettings sslSettings = getSettings(context).getSslSettings();
assertThat(sslSettings.isEnabled()).isTrue();
assertThat(sslSettings.getContext()).isNotNull();
});
}
@Test
@WithPackageResources("test.jks")
void configuresSslWithBundle() {
this.contextRunner
.withPropertyValues("spring.mongodb.ssl.bundle=test-bundle",
"spring.ssl.bundle.jks.test-bundle.keystore.location=classpath:test.jks",
"spring.ssl.bundle.jks.test-bundle.keystore.password=secret",
"spring.ssl.bundle.jks.test-bundle.key.password=password")
.run((context) -> {
SslSettings sslSettings = getSettings(context).getSslSettings();
assertThat(sslSettings.isEnabled()).isTrue();
assertThat(sslSettings.getContext()).isNotNull();
});
}
@Test
void configuresWithoutSslWhenDisabledWithBundle() {
this.contextRunner
.withPropertyValues("spring.mongodb.ssl.enabled=false", "spring.mongodb.ssl.bundle=test-bundle")
.run((context) -> {
SslSettings sslSettings = getSettings(context).getSslSettings();
assertThat(sslSettings.isEnabled()).isFalse();
});
}
@Test
void doesNotConfigureCredentialsWithoutUsername() {
this.contextRunner
.withPropertyValues("spring.mongodb.password=secret", "spring.mongodb.authentication-database=authdb")
.run((context) -> assertThat(getSettings(context).getCredential()).isNull());
}
@Test
void configuresCredentialsFromPropertiesWithDefaultDatabase() {
this.contextRunner.withPropertyValues("spring.mongodb.username=user", "spring.mongodb.password=secret")
.run((context) -> {
MongoCredential credential = getSettings(context).getCredential();
assertThat(credential).isNotNull();
assertThat(credential.getUserName()).isEqualTo("user");
assertThat(credential.getPassword()).isEqualTo("secret".toCharArray());
assertThat(credential.getSource()).isEqualTo("test");
});
}
@Test
void configuresCredentialsFromPropertiesWithDatabase() {
this.contextRunner
.withPropertyValues("spring.mongodb.username=user", "spring.mongodb.password=secret",
"spring.mongodb.database=mydb")
.run((context) -> {
MongoCredential credential = getSettings(context).getCredential();
assertThat(credential).isNotNull();
assertThat(credential.getUserName()).isEqualTo("user");
assertThat(credential.getPassword()).isEqualTo("secret".toCharArray());
assertThat(credential.getSource()).isEqualTo("mydb");
});
}
@Test
void configuresCredentialsFromPropertiesWithAuthDatabase() {
this.contextRunner
.withPropertyValues("spring.mongodb.username=user", "spring.mongodb.password=secret",
"spring.mongodb.database=mydb", "spring.mongodb.authentication-database=authdb")
.run((context) -> {
MongoCredential credential = getSettings(context).getCredential();
assertThat(credential).isNotNull();
assertThat(credential.getUserName()).isEqualTo("user");
assertThat(credential.getPassword()).isEqualTo("secret".toCharArray());
assertThat(credential.getSource()).isEqualTo("authdb");
});
}
@Test
void doesNotConfigureCredentialsWithoutUsernameInUri() {
this.contextRunner.withPropertyValues("spring.mongodb.uri=mongodb://localhost/mydb?authSource=authdb")
.run((context) -> assertThat(getSettings(context).getCredential()).isNull());
}
@Test
void configuresCredentialsFromUriPropertyWithDefaultDatabase() {
this.contextRunner.withPropertyValues("spring.mongodb.uri=mongodb://user:secret@localhost/").run((context) -> {
MongoCredential credential = getSettings(context).getCredential();
assertThat(credential).isNotNull();
assertThat(credential.getUserName()).isEqualTo("user");
assertThat(credential.getPassword()).isEqualTo("secret".toCharArray());
assertThat(credential.getSource()).isEqualTo("admin");
});
}
@Test
void configuresCredentialsFromUriPropertyWithDatabase() {
this.contextRunner
.withPropertyValues("spring.mongodb.uri=mongodb://user:secret@localhost/mydb",
"spring.mongodb.database=notused", "spring.mongodb.authentication-database=notused")
.run((context) -> {
MongoCredential credential = getSettings(context).getCredential();
assertThat(credential).isNotNull();
assertThat(credential.getUserName()).isEqualTo("user");
assertThat(credential.getPassword()).isEqualTo("secret".toCharArray());
assertThat(credential.getSource()).isEqualTo("mydb");
});
}
@Test
void configuresCredentialsFromUriPropertyWithAuthDatabase() {
this.contextRunner
.withPropertyValues("spring.mongodb.uri=mongodb://user:secret@localhost/mydb?authSource=authdb",
"spring.mongodb.database=notused", "spring.mongodb.authentication-database=notused")
.run((context) -> {
MongoCredential credential = getSettings(context).getCredential();
assertThat(credential).isNotNull();
assertThat(credential.getUserName()).isEqualTo("user");
assertThat(credential.getPassword()).isEqualTo("secret".toCharArray());
assertThat(credential.getSource()).isEqualTo("authdb");
});
}
@Test
void nettyTransportSettingsAreConfiguredAutomatically() {
AtomicReference<EventLoopGroup> eventLoopGroupReference = new AtomicReference<>();
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(MongoClient.class);
TransportSettings transportSettings = getSettings(context).getTransportSettings();
assertThat(transportSettings).isInstanceOf(NettyTransportSettings.class);
EventLoopGroup eventLoopGroup = ((NettyTransportSettings) transportSettings).getEventLoopGroup();
assertThat(eventLoopGroup).isNotNull();
assertThat(eventLoopGroup.isShutdown()).isFalse();
eventLoopGroupReference.set(eventLoopGroup);
});
EventLoopGroup eventLoopGroup = eventLoopGroupReference.get();
assertThat(eventLoopGroup).isNotNull();
assertThat(eventLoopGroup.isShutdown()).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void customizerWithTransportSettingsOverridesAutoConfig() {
this.contextRunner.withPropertyValues("spring.mongodb.uri:mongodb://localhost/test?appname=auto-config")
.withUserConfiguration(SimpleTransportSettingsCustomizerConfig.class)
.run((context) -> {
assertThat(context).hasSingleBean(MongoClient.class);
MongoClientSettings settings = getSettings(context);
assertThat(settings.getApplicationName()).isEqualTo("custom-transport-settings");
assertThat(settings.getTransportSettings())
.isSameAs(SimpleTransportSettingsCustomizerConfig.transportSettings);
});
}
@Test
void definesPropertiesBasedConnectionDetailsByDefault() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(PropertiesMongoConnectionDetails.class));
}
@Test
void shouldUseCustomConnectionDetailsWhenDefined() {
this.contextRunner.withBean(MongoConnectionDetails.class, () -> new MongoConnectionDetails() {
@Override
public ConnectionString getConnectionString() {
return new ConnectionString("mongodb://localhost");
}
})
.run((context) -> assertThat(context).hasSingleBean(MongoConnectionDetails.class)
.doesNotHaveBean(PropertiesMongoConnectionDetails.class));
}
@Test
void uuidRepresentationDefaultsAreAligned() {
this.contextRunner.run((context) -> assertThat(getSettings(context).getUuidRepresentation())
.isEqualTo(new MongoProperties().getRepresentation().getUuid()));
}
private MongoClientSettings getSettings(ApplicationContext context) {
MongoClientImpl client = (MongoClientImpl) context.getBean(MongoClient.class);
return client.getSettings();
}
@Configuration(proxyBeanMethods = false)
static | MongoReactiveAutoConfigurationTests |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/UpdateNodeResourceRequestPBImpl.java | {
"start": 1730,
"end": 6225
} | class ____ extends UpdateNodeResourceRequest {
UpdateNodeResourceRequestProto proto = UpdateNodeResourceRequestProto.getDefaultInstance();
UpdateNodeResourceRequestProto.Builder builder = null;
boolean viaProto = false;
Map<NodeId, ResourceOption> nodeResourceMap = null;
public UpdateNodeResourceRequestPBImpl() {
builder = UpdateNodeResourceRequestProto.newBuilder();
}
public UpdateNodeResourceRequestPBImpl(UpdateNodeResourceRequestProto proto) {
this.proto = proto;
viaProto = true;
}
@Override
public Map<NodeId, ResourceOption> getNodeResourceMap() {
initNodeResourceMap();
return this.nodeResourceMap;
}
@Override
public void setNodeResourceMap(Map<NodeId, ResourceOption> nodeResourceMap) {
if (nodeResourceMap == null) {
return;
}
initNodeResourceMap();
this.nodeResourceMap.clear();
this.nodeResourceMap.putAll(nodeResourceMap);
}
@Override
public String getSubClusterId() {
UpdateNodeResourceRequestProtoOrBuilder p = viaProto ? proto : builder;
return (p.hasSubClusterId()) ? p.getSubClusterId() : null;
}
@Override
public void setSubClusterId(String subClusterId) {
maybeInitBuilder();
if (subClusterId == null) {
builder.clearSubClusterId();
return;
}
builder.setSubClusterId(subClusterId);
}
public UpdateNodeResourceRequestProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
private void mergeLocalToBuilder() {
if (this.nodeResourceMap != null) {
addNodeResourceMap();
}
}
private void mergeLocalToProto() {
if (viaProto)
maybeInitBuilder();
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void initNodeResourceMap() {
if (this.nodeResourceMap != null) {
return;
}
UpdateNodeResourceRequestProtoOrBuilder p = viaProto ? proto : builder;
List<NodeResourceMapProto> list = p.getNodeResourceMapList();
this.nodeResourceMap = new HashMap<NodeId, ResourceOption>(list
.size());
for (NodeResourceMapProto nodeResourceProto : list) {
this.nodeResourceMap.put(convertFromProtoFormat(nodeResourceProto.getNodeId()),
convertFromProtoFormat(nodeResourceProto.getResourceOption()));
}
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = UpdateNodeResourceRequestProto.newBuilder(proto);
}
viaProto = false;
}
private NodeIdProto convertToProtoFormat(NodeId nodeId) {
return ((NodeIdPBImpl)nodeId).getProto();
}
private NodeId convertFromProtoFormat(NodeIdProto proto) {
return new NodeIdPBImpl(proto);
}
private ResourceOptionPBImpl convertFromProtoFormat(ResourceOptionProto c) {
return new ResourceOptionPBImpl(c);
}
private ResourceOptionProto convertToProtoFormat(ResourceOption c) {
return ((ResourceOptionPBImpl)c).getProto();
}
private void addNodeResourceMap() {
maybeInitBuilder();
builder.clearNodeResourceMap();
if (nodeResourceMap == null) {
return;
}
Iterable<? extends NodeResourceMapProto> values
= new Iterable<NodeResourceMapProto>() {
@Override
public Iterator<NodeResourceMapProto> iterator() {
return new Iterator<NodeResourceMapProto>() {
Iterator<NodeId> nodeIterator = nodeResourceMap
.keySet().iterator();
@Override
public boolean hasNext() {
return nodeIterator.hasNext();
}
@Override
public NodeResourceMapProto next() {
NodeId nodeId = nodeIterator.next();
return NodeResourceMapProto.newBuilder().setNodeId(
convertToProtoFormat(nodeId)).setResourceOption(
convertToProtoFormat(nodeResourceMap.get(nodeId))).build();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
this.builder.addAllNodeResourceMap(values);
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
}
| UpdateNodeResourceRequestPBImpl |
java | quarkusio__quarkus | independent-projects/qute/core/src/main/java/io/quarkus/qute/TemplateInstanceBase.java | {
"start": 354,
"end": 3061
} | class ____ implements TemplateInstance {
private static final Logger LOG = Logger.getLogger(TemplateInstanceBase.class);
static final String DATA_MAP_KEY = "io.quarkus.qute.dataMap";
static final Map<String, Object> EMPTY_DATA_MAP = Collections.singletonMap(DATA_MAP_KEY, true);
protected Object data;
protected DataMap dataMap;
protected final Map<String, Object> attributes;
protected List<Runnable> renderedActions;
public TemplateInstanceBase() {
this.attributes = new HashMap<>();
}
@Override
public TemplateInstance data(Object data) {
this.data = data;
dataMap = null;
return this;
}
@Override
public TemplateInstance data(String key, Object data) {
this.data = null;
if (dataMap == null) {
dataMap = new DataMap();
}
dataMap.put(Objects.requireNonNull(key), data);
return this;
}
@Override
public TemplateInstance computedData(String key, Function<String, Object> function) {
this.data = null;
if (dataMap == null) {
dataMap = new DataMap();
}
dataMap.computed(Objects.requireNonNull(key), Objects.requireNonNull(function));
return this;
}
@Override
public TemplateInstance setAttribute(String key, Object value) {
attributes.put(key, value);
return this;
}
@Override
public Object getAttribute(String key) {
return attributes.get(key);
}
@Override
public TemplateInstance onRendered(Runnable action) {
if (renderedActions == null) {
renderedActions = new ArrayList<>();
}
renderedActions.add(action);
return this;
}
@Override
public long getTimeout() {
return attributes.isEmpty() ? engine().getTimeout() : getTimeoutAttributeValue();
}
private long getTimeoutAttributeValue() {
Object t = getAttribute(TemplateInstance.TIMEOUT);
if (t != null) {
if (t instanceof Long) {
return ((Long) t).longValue();
} else {
try {
return Long.parseLong(t.toString());
} catch (NumberFormatException e) {
LOG.warnf("Invalid timeout value set for " + toString() + ": " + t);
}
}
}
return engine().getTimeout();
}
protected Object data() {
if (data != null) {
return data;
}
if (dataMap != null) {
return dataMap;
}
return EMPTY_DATA_MAP;
}
protected abstract Engine engine();
public static | TemplateInstanceBase |
java | quarkusio__quarkus | extensions/vertx/latebound-mdc-provider/src/main/java/io/quarkus/vertx/mdc/provider/LateBoundMDCProvider.java | {
"start": 634,
"end": 5041
} | class ____ implements MDCProvider {
private static volatile MDCProvider delegate;
private final InheritableThreadLocal<Map<String, Object>> threadLocalMap = new InheritableThreadLocal<>() {
@Override
protected Map<String, Object> childValue(Map<String, Object> parentValue) {
if (parentValue == null) {
return null;
}
return new HashMap<>(parentValue);
}
};
/**
* Set the actual {@link MDCProvider} to use as the delegate.
*
* @param delegate Properly constructed {@link MDCProvider}.
*/
public synchronized static void setMDCProviderDelegate(MDCProvider delegate) {
LateBoundMDCProvider.delegate = delegate;
}
@Override
public String get(String key) {
if (delegate == null) {
Object value = getLocal(key);
return value != null ? value.toString() : null;
}
return delegate.get(key);
}
@Override
public Object getObject(String key) {
if (delegate == null) {
return getLocal(key);
}
return delegate.getObject(key);
}
@Override
public String put(String key, String value) {
if (delegate == null) {
Object oldValue = putLocal(key, value);
return oldValue != null ? oldValue.toString() : null;
}
return delegate.put(key, value);
}
@Override
public Object putObject(String key, Object value) {
if (delegate == null) {
return putLocal(key, value);
}
return delegate.putObject(key, value);
}
@Override
public String remove(String key) {
if (delegate == null) {
Object oldValue = removeLocal(key);
return oldValue != null ? oldValue.toString() : null;
}
return delegate.remove(key);
}
@Override
public Object removeObject(String key) {
if (delegate == null) {
return removeLocal(key);
}
return delegate.removeObject(key);
}
@Override
public Map<String, String> copy() {
if (delegate == null) {
final HashMap<String, String> result = new HashMap<>();
Map<String, Object> currentMap = threadLocalMap.get();
if (currentMap != null) {
for (Map.Entry<String, Object> entry : currentMap.entrySet()) {
result.put(entry.getKey(), entry.getValue().toString());
}
}
return result;
}
return delegate.copy();
}
@Override
public Map<String, Object> copyObject() {
if (delegate == null) {
Map<String, Object> currentMap = threadLocalMap.get();
if (currentMap != null) {
return new HashMap<>(currentMap);
} else {
return Collections.emptyMap();
}
}
return delegate.copyObject();
}
@Override
public boolean isEmpty() {
if (delegate == null) {
Map<String, Object> currentMap = threadLocalMap.get();
return currentMap == null || currentMap.isEmpty();
} else {
return delegate.isEmpty();
}
}
@Override
public void clear() {
if (delegate == null) {
Map<String, Object> map = threadLocalMap.get();
if (map != null) {
map.clear();
threadLocalMap.remove();
}
} else {
delegate.clear();
}
}
private Object putLocal(String key, Object value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
Map<String, Object> map = threadLocalMap.get();
if (map == null) {
map = new HashMap<>();
threadLocalMap.set(map);
}
return map.put(key, value);
}
private Object getLocal(String key) {
Objects.requireNonNull(key);
Map<String, Object> map = threadLocalMap.get();
if (map != null) {
return map.get(key);
}
return null;
}
private Object removeLocal(String key) {
Objects.requireNonNull(key);
Map<String, Object> map = threadLocalMap.get();
if (map != null) {
return map.remove(key);
}
return null;
}
}
| LateBoundMDCProvider |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/file/tfile/RandomDistribution.java | {
"start": 1037,
"end": 1152
} | class ____ {
/**
* Interface for discrete (integer) random distributions.
*/
public static | RandomDistribution |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/typeutils/RowDataSerializerTest.java | {
"start": 2975,
"end": 8012
} | class ____ extends SerializerTestInstance<RowData> {
private final RowDataSerializer serializer;
private final RowData[] testData;
RowDataSerializerTest(RowDataSerializer serializer, RowData[] testData) {
super(
new DeeplyEqualsChecker()
.withCustomCheck(
(o1, o2) -> o1 instanceof RowData && o2 instanceof RowData,
(o1, o2, checker) ->
deepEqualsRowData(
(RowData) o1,
(RowData) o2,
(RowDataSerializer) serializer.duplicate(),
(RowDataSerializer) serializer.duplicate())),
serializer,
RowData.class,
-1,
testData);
this.serializer = serializer;
this.testData = testData;
}
// ----------------------------------------------------------------------------------------------
private static BinaryArrayData createArray(int... ints) {
BinaryArrayData array = new BinaryArrayData();
BinaryArrayWriter writer = new BinaryArrayWriter(array, ints.length, 4);
for (int i = 0; i < ints.length; i++) {
writer.writeInt(i, ints[i]);
}
writer.complete();
return array;
}
private static BinaryMapData createMap(int[] keys, int[] values) {
return BinaryMapData.valueOf(createArray(keys), createArray(values));
}
private static GenericRowData createRow(Object f0, Object f1, Object f2, Object f3, Object f4) {
GenericRowData row = new GenericRowData(5);
row.setField(0, f0);
row.setField(1, f1);
row.setField(2, f2);
row.setField(3, f3);
row.setField(4, f4);
return row;
}
private static boolean deepEqualsRowData(
RowData should,
RowData is,
RowDataSerializer serializer1,
RowDataSerializer serializer2) {
return deepEqualsRowData(should, is, serializer1, serializer2, false);
}
private static boolean deepEqualsRowData(
RowData should,
RowData is,
RowDataSerializer serializer1,
RowDataSerializer serializer2,
boolean checkClass) {
if (should.getArity() != is.getArity()) {
return false;
}
if (checkClass && (should.getClass() != is.getClass() || !should.equals(is))) {
return false;
}
BinaryRowData row1 = serializer1.toBinaryRow(should);
BinaryRowData row2 = serializer2.toBinaryRow(is);
return Objects.equals(row1, row2);
}
private void checkDeepEquals(RowData should, RowData is, boolean checkClass) {
boolean equals =
deepEqualsRowData(
should,
is,
(RowDataSerializer) serializer.duplicate(),
(RowDataSerializer) serializer.duplicate(),
checkClass);
assertThat(equals).isTrue();
}
@Test
protected void testCopy() {
for (RowData row : testData) {
checkDeepEquals(row, serializer.copy(row), true);
}
for (RowData row : testData) {
checkDeepEquals(row, serializer.copy(row, new GenericRowData(row.getArity())), true);
}
for (RowData row : testData) {
checkDeepEquals(
row,
serializer.copy(
serializer.toBinaryRow(row), new GenericRowData(row.getArity())),
false);
}
for (RowData row : testData) {
checkDeepEquals(row, serializer.copy(serializer.toBinaryRow(row)), false);
}
for (RowData row : testData) {
checkDeepEquals(
row,
serializer.copy(serializer.toBinaryRow(row), new BinaryRowData(row.getArity())),
false);
}
}
@Test
void testWrongCopy() {
assertThatThrownBy(() -> serializer.copy(new GenericRowData(serializer.getArity() + 1)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testWrongCopyReuse() {
for (RowData row : testData) {
assertThatThrownBy(
() ->
checkDeepEquals(
row,
serializer.copy(
row, new GenericRowData(row.getArity() + 1)),
false))
.isInstanceOf(IllegalArgumentException.class);
}
}
/** Class used for concurrent testing with KryoSerializer. */
private static | RowDataSerializerTest |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/JSONPath.java | {
"start": 30105,
"end": 71792
} | class ____ {
private final String path;
private int pos;
private char ch;
private int level;
private boolean hasRefSegment;
private static final String strArrayRegex = "\'\\s*,\\s*\'";
private static final Pattern strArrayPatternx = Pattern.compile(strArrayRegex);
public JSONPathParser(String path){
this.path = path;
next();
}
void next() {
ch = path.charAt(pos++);
}
char getNextChar() {
return path.charAt(pos);
}
boolean isEOF() {
return pos >= path.length();
}
Segment readSegement() {
if (level == 0 && path.length() == 1) {
if (isDigitFirst(ch)) {
int index = ch - '0';
return new ArrayAccessSegment(index);
} else if ((ch >= 'a' && ch <= 'z') || ((ch >= 'A' && ch <= 'Z'))) {
return new PropertySegment(Character.toString(ch), false);
}
}
while (!isEOF()) {
skipWhitespace();
if (ch == '$') {
next();
skipWhitespace();
if (ch == '?') {
return new FilterSegment(
(Filter) parseArrayAccessFilter(false));
}
continue;
}
if (ch == '.' || ch == '/') {
int c0 = ch;
boolean deep = false;
next();
if (c0 == '.' && ch == '.') {
next();
deep = true;
if (path.length() > pos + 3
&& ch == '['
&& path.charAt(pos) == '*'
&& path.charAt(pos + 1) == ']'
&& path.charAt(pos + 2) == '.') {
next();
next();
next();
next();
}
}
if (ch == '*' || (deep && ch == '[')) {
boolean objectOnly = ch == '[';
if (!isEOF()) {
next();
}
if (deep) {
if (objectOnly) {
return WildCardSegment.instance_deep_objectOnly;
} else {
return WildCardSegment.instance_deep;
}
} else {
return WildCardSegment.instance;
}
}
if (isDigitFirst(ch)) {
return parseArrayAccess(false);
}
String propertyName = readName();
if (ch == '(') {
next();
if (ch == ')') {
if (!isEOF()) {
next();
}
if ("size".equals(propertyName) || "length".equals(propertyName)) {
return SizeSegment.instance;
} else if ("max".equals(propertyName)) {
return MaxSegment.instance;
} else if ("min".equals(propertyName)) {
return MinSegment.instance;
} else if ("keySet".equals(propertyName)) {
return KeySetSegment.instance;
} else if ("type".equals(propertyName)) {
return TypeSegment.instance;
} else if ("floor".equals(propertyName)) {
return FloorSegment.instance;
}
throw new JSONPathException("not support jsonpath : " + path);
}
throw new JSONPathException("not support jsonpath : " + path);
}
return new PropertySegment(propertyName, deep);
}
if (ch == '[') {
return parseArrayAccess(true);
}
if (level == 0) {
String propertyName = readName();
return new PropertySegment(propertyName, false);
}
if (ch == '?') {
return new FilterSegment(
(Filter) parseArrayAccessFilter(false));
}
throw new JSONPathException("not support jsonpath : " + path);
}
return null;
}
public final void skipWhitespace() {
for (;;) {
if (ch <= ' ' && (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\b')) {
next();
continue;
} else {
break;
}
}
}
Segment parseArrayAccess(boolean acceptBracket) {
Object object = parseArrayAccessFilter(acceptBracket);
if (object instanceof Segment) {
return ((Segment) object);
}
return new FilterSegment((Filter) object);
}
Object parseArrayAccessFilter(boolean acceptBracket) {
if (acceptBracket) {
accept('[');
}
boolean predicateFlag = false;
int lparanCount = 0;
if (ch == '?') {
next();
accept('(');
lparanCount++;
while (ch == '(') {
next();
lparanCount++;
}
predicateFlag = true;
}
skipWhitespace();
if (predicateFlag
|| IOUtils.firstIdentifier(ch)
|| Character.isJavaIdentifierStart(ch)
|| ch == '\\'
|| ch == '@') {
boolean self = false;
if (ch == '@') {
next();
accept('.');
self = true;
}
String propertyName = readName();
skipWhitespace();
if (predicateFlag && ch == ')') {
next();
Filter filter = new NotNullSegement(propertyName, false);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
if (acceptBracket) {
accept(']');
}
return filter;
}
if (acceptBracket && ch == ']') {
if (isEOF()) {
if (propertyName.equals("last")) {
return new MultiIndexSegment(new int[]{-1});
}
}
next();
Filter filter = new NotNullSegement(propertyName, false);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
boolean function = false;
skipWhitespace();
if (ch == '(') {
next();
accept(')');
skipWhitespace();
function = true;
}
Operator op = readOp();
skipWhitespace();
if (op == Operator.BETWEEN || op == Operator.NOT_BETWEEN) {
final boolean not = (op == Operator.NOT_BETWEEN);
Object startValue = readValue();
String name = readName();
if (!"and".equalsIgnoreCase(name)) {
throw new JSONPathException(path);
}
Object endValue = readValue();
if (startValue == null || endValue == null) {
throw new JSONPathException(path);
}
if (isInt(startValue.getClass()) && isInt(endValue.getClass())) {
Filter filter = new IntBetweenSegement(propertyName
, function
, TypeUtils.longExtractValue((Number) startValue)
, TypeUtils.longExtractValue((Number) endValue)
, not);
return filter;
}
throw new JSONPathException(path);
}
if (op == Operator.IN || op == Operator.NOT_IN) {
final boolean not = (op == Operator.NOT_IN);
accept('(');
List<Object> valueList = new JSONArray();
{
Object value = readValue();
valueList.add(value);
for (;;) {
skipWhitespace();
if (ch != ',') {
break;
}
next();
value = readValue();
valueList.add(value);
}
}
boolean isInt = true;
boolean isIntObj = true;
boolean isString = true;
for (Object item : valueList) {
if (item == null) {
if (isInt) {
isInt = false;
}
continue;
}
Class<?> clazz = item.getClass();
if (isInt && !(clazz == Byte.class || clazz == Short.class || clazz == Integer.class
|| clazz == Long.class)) {
isInt = false;
isIntObj = false;
}
if (isString && clazz != String.class) {
isString = false;
}
}
if (valueList.size() == 1 && valueList.get(0) == null) {
Filter filter;
if (not) {
filter = new NotNullSegement(propertyName, function);
} else {
filter = new NullSegement(propertyName, function);
}
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
if (isInt) {
if (valueList.size() == 1) {
long value = TypeUtils.longExtractValue((Number) valueList.get(0));
Operator intOp = not ? Operator.NE : Operator.EQ;
Filter filter = new IntOpSegement(propertyName, function, value, intOp);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
long[] values = new long[valueList.size()];
for (int i = 0; i < values.length; ++i) {
values[i] = TypeUtils.longExtractValue((Number) valueList.get(i));
}
Filter filter = new IntInSegement(propertyName, function, values, not);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
if (isString) {
if (valueList.size() == 1) {
String value = (String) valueList.get(0);
Operator intOp = not ? Operator.NE : Operator.EQ;
Filter filter = new StringOpSegement(propertyName, function, value, intOp);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
String[] values = new String[valueList.size()];
valueList.toArray(values);
Filter filter = new StringInSegement(propertyName, function, values, not);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
if (isIntObj) {
Long[] values = new Long[valueList.size()];
for (int i = 0; i < values.length; ++i) {
Number item = (Number) valueList.get(i);
if (item != null) {
values[i] = TypeUtils.longExtractValue(item);
}
}
Filter filter = new IntObjInSegement(propertyName, function, values, not);
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
accept(')');
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
throw new UnsupportedOperationException();
}
if (ch == '\'' || ch == '"') {
String strValue = readString();
Filter filter = null;
if (op == Operator.RLIKE) {
filter = new RlikeSegement(propertyName, function, strValue, false);
} else if (op == Operator.NOT_RLIKE) {
filter = new RlikeSegement(propertyName, function, strValue, true);
} else if (op == Operator.LIKE || op == Operator.NOT_LIKE) {
while (strValue.indexOf("%%") != -1) {
strValue = strValue.replaceAll("%%", "%");
}
final boolean not = (op == Operator.NOT_LIKE);
int p0 = strValue.indexOf('%');
if (p0 == -1) {
if (op == Operator.LIKE) {
op = Operator.EQ;
} else {
op = Operator.NE;
}
filter = new StringOpSegement(propertyName, function, strValue, op);
} else {
String[] items = strValue.split("%");
String startsWithValue = null;
String endsWithValue = null;
String[] containsValues = null;
if (p0 == 0) {
if (strValue.charAt(strValue.length() - 1) == '%') {
containsValues = new String[items.length - 1];
System.arraycopy(items, 1, containsValues, 0, containsValues.length);
} else {
endsWithValue = items[items.length - 1];
if (items.length > 2) {
containsValues = new String[items.length - 2];
System.arraycopy(items, 1, containsValues, 0, containsValues.length);
}
}
} else if (strValue.charAt(strValue.length() - 1) == '%') {
if (items.length == 1) {
startsWithValue = items[0];
} else {
containsValues = items;
}
} else {
if (items.length == 1) {
startsWithValue = items[0];
} else if (items.length == 2) {
startsWithValue = items[0];
endsWithValue = items[1];
} else {
startsWithValue = items[0];
endsWithValue = items[items.length - 1];
containsValues = new String[items.length - 2];
System.arraycopy(items, 1, containsValues, 0, containsValues.length);
}
}
filter = new MatchSegement(propertyName, function, startsWithValue, endsWithValue,
containsValues, not);
}
} else {
filter = new StringOpSegement(propertyName, function, strValue, op);
}
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
if (isDigitFirst(ch)) {
long value = readLongValue();
double doubleValue = 0D;
if (ch == '.') {
doubleValue = readDoubleValue(value);
}
Filter filter;
if (doubleValue == 0) {
filter = new IntOpSegement(propertyName, function, value, op);
} else {
filter = new DoubleOpSegement(propertyName, function, doubleValue, op);
}
while (ch == ' ') {
next();
}
if (lparanCount > 1 && ch == ')') {
next();
lparanCount--;
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
if (predicateFlag) {
lparanCount--;
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
} else if (ch == '$') {
Segment segment = readSegement();
RefOpSegement filter = new RefOpSegement(propertyName, function, segment, op);
hasRefSegment = true;
while (ch == ' ') {
next();
}
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
} else if (ch == '/') {
int flags = 0;
StringBuilder regBuf = new StringBuilder();
for (;;) {
next();
if (ch == '/') {
next();
if (ch == 'i') {
next();
flags |= Pattern.CASE_INSENSITIVE;
}
break;
}
if (ch == '\\') {
next();
regBuf.append(ch);
} else {
regBuf.append(ch);
}
}
Pattern pattern = Pattern.compile(regBuf.toString(), flags);
RegMatchSegement filter = new RegMatchSegement(propertyName, function, pattern, op);
if (predicateFlag) {
accept(')');
}
if (acceptBracket) {
accept(']');
}
return filter;
}
if (ch == 'n') {
String name = readName();
if ("null".equals(name)) {
Filter filter = null;
if (op == Operator.EQ) {
filter = new NullSegement(propertyName, function);
} else if (op == Operator.NE) {
filter = new NotNullSegement(propertyName, function);
}
if (filter != null) {
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
}
if (predicateFlag) {
accept(')');
}
accept(']');
if (filter != null) {
return filter;
}
throw new UnsupportedOperationException();
}
} else if (ch == 't') {
String name = readName();
if ("true".equals(name)) {
Filter filter = null;
if (op == Operator.EQ) {
filter = new ValueSegment(propertyName, function, Boolean.TRUE, true);
} else if (op == Operator.NE) {
filter = new ValueSegment(propertyName, function, Boolean.TRUE, false);
}
if (filter != null) {
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
}
if (predicateFlag) {
accept(')');
}
accept(']');
if (filter != null) {
return filter;
}
throw new UnsupportedOperationException();
}
} else if (ch == 'f') {
String name = readName();
if ("false".equals(name)) {
Filter filter = null;
if (op == Operator.EQ) {
filter = new ValueSegment(propertyName, function, Boolean.FALSE, true);
} else if (op == Operator.NE) {
filter = new ValueSegment(propertyName, function, Boolean.FALSE, false);
}
if (filter != null) {
while (ch == ' ') {
next();
}
if (ch == '&' || ch == '|') {
filter = filterRest(filter);
}
}
if (predicateFlag) {
accept(')');
}
accept(']');
if (filter != null) {
return filter;
}
throw new UnsupportedOperationException();
}
}
throw new UnsupportedOperationException();
// accept(')');
}
int start = pos - 1;
char startCh = ch;
while (ch != ']' && ch != '/' && !isEOF()) {
if (ch == '.' //
&& (!predicateFlag) //
&& !predicateFlag
&& startCh != '\''
) {
break;
}
if (ch == '\\') {
next();
}
next();
}
int end;
if (acceptBracket) {
end = pos - 1;
} else {
if (ch == '/' || ch == '.') {
end = pos - 1;
} else {
end = pos;
}
}
String text = path.substring(start, end);
if (text.indexOf('\\') != 0) {
StringBuilder buf = new StringBuilder(text.length());
for (int i = 0; i < text.length(); ++i) {
char ch = text.charAt(i);
if (ch == '\\' && i < text.length() - 1) {
char c2 = text.charAt(i + 1);
if (c2 == '@' || ch == '\\' || ch == '\"') {
buf.append(c2);
i++;
continue;
}
}
buf.append(ch);
}
text = buf.toString();
}
if (text.indexOf("\\.") != -1) {
String propName;
if (startCh == '\'' && text.length() > 2 && text.charAt(text.length() - 1) == startCh) {
propName = text.substring(1, text.length() - 1);
} else {
propName = text.replaceAll("\\\\\\.", "\\.");
if (propName.indexOf("\\-") != -1) {
propName = propName.replaceAll("\\\\-", "-");
}
}
if (predicateFlag) {
accept(')');
}
return new PropertySegment(propName, false);
}
Segment segment = buildArraySegement(text);
if (acceptBracket && !isEOF()) {
accept(']');
}
return segment;
}
Filter filterRest(Filter filter) {
boolean and = ch == '&';
if ((ch == '&' && getNextChar() == '&') || (ch == '|' && getNextChar() == '|')) {
next();
next();
boolean paren = false;
if (ch == '(') {
paren = true;
next();
}
while (ch == ' ') {
next();
}
Filter right = (Filter) parseArrayAccessFilter(false);
filter = new FilterGroup(filter, right, and);
if (paren && ch == ')') {
next();
}
}
return filter;
}
protected long readLongValue() {
int beginIndex = pos - 1;
if (ch == '+' || ch == '-') {
next();
}
while (ch >= '0' && ch <= '9') {
next();
}
int endIndex = pos - 1;
String text = path.substring(beginIndex, endIndex);
long value = Long.parseLong(text);
return value;
}
protected double readDoubleValue(long longValue) {
int beginIndex = pos - 1;
next();
while (ch >= '0' && ch <= '9') {
next();
}
int endIndex = pos - 1;
String text = path.substring(beginIndex, endIndex);
double value = Double.parseDouble(text);
value += longValue;
return value;
}
protected Object readValue() {
skipWhitespace();
if (isDigitFirst(ch)) {
return readLongValue();
}
if (ch == '"' || ch == '\'') {
return readString();
}
if (ch == 'n') {
String name = readName();
if ("null".equals(name)) {
return null;
} else {
throw new JSONPathException(path);
}
}
throw new UnsupportedOperationException();
}
static boolean isDigitFirst(char ch) {
return ch == '-' || ch == '+' || (ch >= '0' && ch <= '9');
}
protected Operator readOp() {
Operator op = null;
if (ch == '=') {
next();
if (ch == '~') {
next();
op = Operator.REG_MATCH;
} else if (ch == '=') {
next();
op = Operator.EQ;
} else {
op = Operator.EQ;
}
} else if (ch == '!') {
next();
accept('=');
op = Operator.NE;
} else if (ch == '<') {
next();
if (ch == '=') {
next();
op = Operator.LE;
} else {
op = Operator.LT;
}
} else if (ch == '>') {
next();
if (ch == '=') {
next();
op = Operator.GE;
} else {
op = Operator.GT;
}
}
if (op == null) {
String name = readName();
if ("not".equalsIgnoreCase(name)) {
skipWhitespace();
name = readName();
if ("like".equalsIgnoreCase(name)) {
op = Operator.NOT_LIKE;
} else if ("rlike".equalsIgnoreCase(name)) {
op = Operator.NOT_RLIKE;
} else if ("in".equalsIgnoreCase(name)) {
op = Operator.NOT_IN;
} else if ("between".equalsIgnoreCase(name)) {
op = Operator.NOT_BETWEEN;
} else {
throw new UnsupportedOperationException();
}
} else if ("nin".equalsIgnoreCase(name)) {
op = Operator.NOT_IN;
} else {
if ("like".equalsIgnoreCase(name)) {
op = Operator.LIKE;
} else if ("rlike".equalsIgnoreCase(name)) {
op = Operator.RLIKE;
} else if ("in".equalsIgnoreCase(name)) {
op = Operator.IN;
} else if ("between".equalsIgnoreCase(name)) {
op = Operator.BETWEEN;
} else {
throw new UnsupportedOperationException();
}
}
}
return op;
}
String readName() {
skipWhitespace();
if (ch != '\\' && !Character.isJavaIdentifierStart(ch)) {
throw new JSONPathException("illeal jsonpath syntax. " + path);
}
StringBuilder buf = new StringBuilder();
while (!isEOF()) {
if (ch == '\\') {
next();
buf.append(ch);
if (isEOF()) {
return buf.toString();
}
next();
continue;
}
boolean identifierFlag = Character.isJavaIdentifierPart(ch);
if (!identifierFlag) {
break;
}
buf.append(ch);
next();
}
if (isEOF() && Character.isJavaIdentifierPart(ch)) {
buf.append(ch);
}
return buf.toString();
}
String readString() {
char quoate = ch;
next();
int beginIndex = pos - 1;
while (ch != quoate && !isEOF()) {
next();
}
String strValue = path.substring(beginIndex, isEOF() ? pos : pos - 1);
accept(quoate);
return strValue;
}
void accept(char expect) {
if (ch == ' ') {
next();
}
if (ch != expect) {
throw new JSONPathException("expect '" + expect + ", but '" + ch + "'");
}
if (!isEOF()) {
next();
}
}
public Segment[] explain() {
if (path == null || path.length() == 0) {
throw new IllegalArgumentException();
}
Segment[] segments = new Segment[8];
for (;;) {
Segment segment = readSegement();
if (segment == null) {
break;
}
if (segment instanceof PropertySegment) {
PropertySegment propertySegment = (PropertySegment) segment;
if ((!propertySegment.deep) && propertySegment.propertyName.equals("*")) {
continue;
}
}
if (level == segments.length) {
Segment[] t = new Segment[level * 3 / 2];
System.arraycopy(segments, 0, t, 0, level);
segments = t;
}
segments[level++] = segment;
}
if (level == segments.length) {
return segments;
}
Segment[] result = new Segment[level];
System.arraycopy(segments, 0, result, 0, level);
return result;
}
Segment buildArraySegement(String indexText) {
final int indexTextLen = indexText.length();
final char firstChar = indexText.charAt(0);
final char lastChar = indexText.charAt(indexTextLen - 1);
int commaIndex = indexText.indexOf(',');
if (indexText.length() > 2 && firstChar == '\'' && lastChar == '\'') {
String propertyName = indexText.substring(1, indexTextLen - 1);
if (commaIndex == -1 || !strArrayPatternx.matcher(indexText).find()) {
return new PropertySegment(propertyName, false);
}
String[] propertyNames = propertyName.split(strArrayRegex);
return new MultiPropertySegment(propertyNames);
}
int colonIndex = indexText.indexOf(':');
if (commaIndex == -1 && colonIndex == -1) {
if (TypeUtils.isNumber(indexText)) {
try {
int index = Integer.parseInt(indexText);
return new ArrayAccessSegment(index);
}catch (NumberFormatException ex){
return new PropertySegment(indexText, false); // fix ISSUE-1208
}
} else {
if (indexText.charAt(0) == '"' && indexText.charAt(indexText.length() - 1) == '"') {
indexText = indexText.substring(1, indexText.length() - 1);
}
return new PropertySegment(indexText, false);
}
}
if (commaIndex != -1) {
String[] indexesText = indexText.split(",");
int[] indexes = new int[indexesText.length];
for (int i = 0; i < indexesText.length; ++i) {
indexes[i] = Integer.parseInt(indexesText[i]);
}
return new MultiIndexSegment(indexes);
}
if (colonIndex != -1) {
String[] indexesText = indexText.split(":");
int[] indexes = new int[indexesText.length];
for (int i = 0; i < indexesText.length; ++i) {
String str = indexesText[i];
if (str.length() == 0) {
if (i == 0) {
indexes[i] = 0;
} else {
throw new UnsupportedOperationException();
}
} else {
indexes[i] = Integer.parseInt(str);
}
}
int start = indexes[0];
int end;
if (indexes.length > 1) {
end = indexes[1];
} else {
end = -1;
}
int step;
if (indexes.length == 3) {
step = indexes[2];
} else {
step = 1;
}
if (end >= 0 && end < start) {
throw new UnsupportedOperationException("end must greater than or equals start. start " + start
+ ", end " + end);
}
if (step <= 0) {
throw new UnsupportedOperationException("step must greater than zero : " + step);
}
return new RangeSegment(start, end, step);
}
throw new UnsupportedOperationException();
}
}
| JSONPathParser |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ExtendsAutoValueTest.java | {
"start": 1603,
"end": 1910
} | class ____ extends SuperClass {}
""")
.doTest();
}
@Test
public void extendsAutoValue_goodAutoValueExtendsSuperclass() {
helper
.addSourceLines(
"TestClass.java",
"""
import com.google.auto.value.AutoValue;
public | TestClass |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/builder/xml/XPathHeaderNameTest.java | {
"start": 1098,
"end": 3518
} | class ____ extends ContextTestSupport {
@Test
public void testChoiceWithHeaderNamePremium() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:premium");
mock.expectedBodiesReceived("<response>OK</response>");
mock.expectedHeaderReceived("invoiceDetails",
"<invoice orderType='premium'><person><name>Alan</name></person></invoice>");
template.sendBodyAndHeader("direct:in", "<response>OK</response>", "invoiceDetails",
"<invoice orderType='premium'><person><name>Alan</name></person></invoice>");
mock.assertIsSatisfied();
}
@Test
public void testChoiceWithHeaderNameStandard() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:standard");
mock.expectedBodiesReceived("<response>OK</response>");
mock.expectedHeaderReceived("invoiceDetails",
"<invoice orderType='standard'><person><name>Alan</name></person></invoice>");
template.sendBodyAndHeader("direct:in", "<response>OK</response>", "invoiceDetails",
"<invoice orderType='standard'><person><name>Alan</name></person></invoice>");
mock.assertIsSatisfied();
}
@Test
public void testChoiceWithHeaderNameUnknown() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:unknown");
mock.expectedBodiesReceived("<response>OK</response>");
mock.expectedHeaderReceived("invoiceDetails", "<invoice />");
template.sendBodyAndHeader("direct:in", "<response>OK</response>", "invoiceDetails", "<invoice />");
mock.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
var premium = expression().xpath().expression("/invoice/@orderType = 'premium'").source("header:invoiceDetails")
.end();
var standard = expression().xpath().expression("/invoice/@orderType = 'standard'")
.source("header:invoiceDetails").end();
from("direct:in").choice().when(premium)
.to("mock:premium")
.when(standard)
.to("mock:standard")
.otherwise()
.to("mock:unknown").end();
}
};
}
}
| XPathHeaderNameTest |
java | quarkusio__quarkus | extensions/hal/deployment/src/main/java/io/quarkus/hal/deployment/HalProcessor.java | {
"start": 748,
"end": 1807
} | class ____ {
@BuildStep
ReflectiveClassBuildItem registerReflection() {
return ReflectiveClassBuildItem.builder(HalLink.class).reason(getClass().getName()).methods().fields().build();
}
@BuildStep
JacksonModuleBuildItem registerJacksonSerializers() {
return new JacksonModuleBuildItem.Builder("hal-wrappers")
.addSerializer(HalEntityWrapperJacksonSerializer.class.getName(), HalEntityWrapper.class.getName())
.addSerializer(HalCollectionWrapperJacksonSerializer.class.getName(), HalCollectionWrapper.class.getName())
.addSerializer(HalLinkJacksonSerializer.class.getName(), HalLink.class.getName())
.build();
}
@BuildStep
JsonbSerializerBuildItem registerJsonbSerializers() {
return new JsonbSerializerBuildItem(Arrays.asList(
HalEntityWrapperJsonbSerializer.class.getName(),
HalCollectionWrapperJsonbSerializer.class.getName(),
HalLinkJsonbSerializer.class.getName()));
}
}
| HalProcessor |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/json/async/AsyncConcurrencyTest.java | {
"start": 1193,
"end": 5917
} | class ____ implements AutoCloseable {
private int stage = 0;
private AsyncReaderWrapper parser;
private boolean errored = false;
public boolean process() throws Exception {
// short-cut through if this instance has already failed
if (errored) {
return false;
}
try {
switch (stage++) {
case 0:
parser = createParser();
break;
case 1:
_assert(JsonToken.START_ARRAY);
break;
case 2:
_assert(TEXT1);
break;
case 3:
_assert(TEXT2);
break;
case 4:
_assert(TEXT3);
break;
case 5:
_assert(TEXT4);
break;
case 6:
_assert(JsonToken.END_ARRAY);
break;
default:
/*
if (parser.nextToken() != null) {
throw new IOException("Unexpected token at "+stage+"; expected `null`, got "+parser.currentToken());
}
*/
close();
return true;
}
} catch (Exception e) {
errored = true;
throw e;
}
return false;
}
private void _assert(String exp) throws IOException {
_assert(JsonToken.VALUE_STRING);
String str = parser.currentText();
if (!exp.equals(str)) {
throw new IOException("Unexpected VALUE_STRING: expected '"+exp+"', got '"+str+"'");
}
}
private void _assert(JsonToken exp) throws IOException {
JsonToken t = parser.nextToken();
if (t != exp) {
throw new IOException("Unexpected token at "+stage+"; expected "+exp+", got "+t);
}
}
@Override
public void close() throws Exception {
if (parser != null) {
parser.close();
parser = null;
stage = 0;
}
}
}
// [jackson-core#476]
@Test
void concurrentAsync() throws Exception
{
final int MAX_ROUNDS = 30;
for (int i = 0; i < MAX_ROUNDS; ++i) {
_testConcurrentAsyncOnce(i, MAX_ROUNDS);
}
}
void _testConcurrentAsyncOnce(final int round, final int maxRounds) throws Exception
{
final int numThreads = 3;
final ExecutorService executor = Executors.newFixedThreadPool(numThreads);
final AtomicInteger errorCount = new AtomicInteger(0);
final AtomicInteger completedCount = new AtomicInteger(0);
final AtomicReference<String> errorRef = new AtomicReference<>();
// First, add a few shared work units
final ArrayBlockingQueue<WorkUnit> q = new ArrayBlockingQueue<>(20);
for (int i = 0; i < 7; ++i) {
q.add(new WorkUnit());
}
// then invoke swarm of workers on it...
final int REP_COUNT = 99000;
ArrayList<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < REP_COUNT; i++) {
Callable<Void> c = () -> {
WorkUnit w = q.take();
try {
if (w.process()) {
completedCount.incrementAndGet();
}
} catch (Throwable t) {
if (errorCount.getAndIncrement() == 0) {
errorRef.set(t.toString());
}
} finally {
q.add(w);
}
return null;
};
futures.add(executor.submit(c));
}
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
int count = errorCount.get();
if (count > 0) {
fail("Expected no problems (round "+round+"/"+maxRounds
+"); got "+count+", first with: "+errorRef.get());
}
final int EXP_COMPL = ((REP_COUNT + 7) / 8);
int compl = completedCount.get();
if (compl < (EXP_COMPL-10) || compl > EXP_COMPL) {
fail("Expected about "+EXP_COMPL+" completed rounds, got: "+compl);
}
while (!q.isEmpty()) {
q.take().close();
}
}
protected AsyncReaderWrapper createParser() throws IOException {
return asyncForBytes(JSON_F, 100, JSON_DOC, 0);
}
}
| WorkUnit |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java | {
"start": 1643,
"end": 3944
} | class ____ {
@Test
void configurationPropertiesClass() {
new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> {
new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class)
.withParent(parent)
.run((child) -> {
ConfigurationPropertiesReportEndpoint endpoint = child
.getBean(ConfigurationPropertiesReportEndpoint.class);
ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties();
assertThat(applicationProperties.getContexts()).containsOnlyKeys(child.getId(), parent.getId());
ContextConfigurationPropertiesDescriptor childContext = applicationProperties.getContexts()
.get(child.getId());
assertThat(childContext).isNotNull();
assertThat(childContext.getBeans().keySet()).containsExactly("someProperties");
ContextConfigurationPropertiesDescriptor parentContext = applicationProperties.getContexts()
.get(parent.getId());
assertThat(parentContext).isNotNull();
assertThat((parentContext.getBeans().keySet())).containsExactly("testProperties");
});
});
}
@Test
void configurationPropertiesBeanMethod() {
new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> {
new ApplicationContextRunner().withUserConfiguration(BeanMethodConfigurationProperties.class)
.withParent(parent)
.run((child) -> {
ConfigurationPropertiesReportEndpoint endpoint = child
.getBean(ConfigurationPropertiesReportEndpoint.class);
ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties();
ContextConfigurationPropertiesDescriptor childContext = applicationProperties.getContexts()
.get(child.getId());
assertThat(childContext).isNotNull();
assertThat(childContext.getBeans().keySet()).containsExactlyInAnyOrder("otherProperties");
ContextConfigurationPropertiesDescriptor parentContext = applicationProperties.getContexts()
.get(parent.getId());
assertThat(parentContext).isNotNull();
assertThat((parentContext.getBeans().keySet())).containsExactly("testProperties");
});
});
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static | ConfigurationPropertiesReportEndpointParentTests |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/collection_in_constructor/Mapper.java | {
"start": 745,
"end": 1163
} | interface ____ {
Store getAStore(Integer id);
List<Store> getStores();
Store2 getAStore2(Integer id);
Store3 getAStore3(Integer id);
Store4 getAStore4(Integer id);
Store5 getAStore5(Integer id);
Store6 getAStore6(Integer id);
Store7 getAStore7(Integer id);
Store8 getAStore8(Integer id);
Container getAContainer();
List<Container1> getContainers();
List<Store10> getStores10();
}
| Mapper |
java | apache__camel | components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/vm/AbstractVmTestSupport.java | {
"start": 1155,
"end": 1983
} | class ____ extends CamelTestSupport {
protected CamelContext context2;
protected ProducerTemplate template2;
@Override
public void doPostSetup() throws Exception {
context2 = new DefaultCamelContext();
template2 = context2.createProducerTemplate();
ServiceHelper.startService(template2);
context2.start();
// add routes after CamelContext has been started
RouteBuilder routeBuilder = createRouteBuilderForSecondContext();
if (routeBuilder != null) {
context2.addRoutes(routeBuilder);
}
}
@Override
public void doPostTearDown() {
ServiceHelper.stopService(template2);
context2.stop();
}
protected RouteBuilder createRouteBuilderForSecondContext() {
return null;
}
}
| AbstractVmTestSupport |
java | apache__kafka | storage/src/test/java/org/apache/kafka/server/log/remote/metadata/storage/TopicBasedRemoteLogMetadataManagerConfigTest.java | {
"start": 2569,
"end": 11026
} | class ____ {
private static final String BOOTSTRAP_SERVERS = "localhost:2222";
@Test
public void testValidConfig() {
Map<String, Object> commonClientConfig = new HashMap<>();
commonClientConfig.put(CommonClientConfigs.RETRIES_CONFIG, 10);
commonClientConfig.put(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG, 1000L);
commonClientConfig.put(CommonClientConfigs.METADATA_MAX_AGE_CONFIG, 60000L);
Map<String, Object> producerConfig = new HashMap<>();
producerConfig.put(ProducerConfig.ACKS_CONFIG, "all");
Map<String, Object> consumerConfig = new HashMap<>();
consumerConfig.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
Map<String, Object> props = createValidConfigProps(commonClientConfig, producerConfig, consumerConfig);
// Check for topic properties
TopicBasedRemoteLogMetadataManagerConfig rlmmConfig = new TopicBasedRemoteLogMetadataManagerConfig(props);
assertEquals(props.get(REMOTE_LOG_METADATA_TOPIC_PARTITIONS_PROP), rlmmConfig.metadataTopicPartitionsCount());
// Check for common client configs.
assertEquals(BOOTSTRAP_SERVERS, rlmmConfig.commonProperties().get(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG));
assertEquals(BOOTSTRAP_SERVERS, rlmmConfig.producerProperties().get(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG));
assertEquals(BOOTSTRAP_SERVERS, rlmmConfig.consumerProperties().get(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG));
for (Map.Entry<String, Object> entry : commonClientConfig.entrySet()) {
assertEquals(entry.getValue(), rlmmConfig.commonProperties().get(entry.getKey()));
assertEquals(entry.getValue(), rlmmConfig.producerProperties().get(entry.getKey()));
assertEquals(entry.getValue(), rlmmConfig.consumerProperties().get(entry.getKey()));
}
// Check for producer configs.
for (Map.Entry<String, Object> entry : producerConfig.entrySet()) {
assertEquals(entry.getValue(), rlmmConfig.producerProperties().get(entry.getKey()));
}
// Check for consumer configs.
for (Map.Entry<String, Object> entry : consumerConfig.entrySet()) {
assertEquals(entry.getValue(), rlmmConfig.consumerProperties().get(entry.getKey()));
}
}
@Test
public void testCommonProducerConsumerOverridesConfig() {
Map.Entry<String, Long> overrideEntry =
new AbstractMap.SimpleImmutableEntry<>(CommonClientConfigs.METADATA_MAX_AGE_CONFIG, 60000L);
Map<String, Object> commonClientConfig = new HashMap<>();
commonClientConfig.put(CommonClientConfigs.RETRIES_CONFIG, 10);
commonClientConfig.put(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG, 1000L);
Long overrideCommonPropValue = overrideEntry.getValue();
commonClientConfig.put(overrideEntry.getKey(), overrideCommonPropValue);
Map<String, Object> producerConfig = new HashMap<>();
producerConfig.put(ProducerConfig.ACKS_CONFIG, -1);
Long overriddenProducerPropValue = overrideEntry.getValue() * 2;
producerConfig.put(overrideEntry.getKey(), overriddenProducerPropValue);
Map<String, Object> consumerConfig = new HashMap<>();
consumerConfig.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
Long overriddenConsumerPropValue = overrideEntry.getValue() * 3;
consumerConfig.put(overrideEntry.getKey(), overriddenConsumerPropValue);
Map<String, Object> props = createValidConfigProps(commonClientConfig, producerConfig, consumerConfig);
TopicBasedRemoteLogMetadataManagerConfig rlmmConfig = new TopicBasedRemoteLogMetadataManagerConfig(props);
assertEquals(overrideCommonPropValue, rlmmConfig.commonProperties().get(overrideEntry.getKey()));
assertEquals(overriddenProducerPropValue, rlmmConfig.producerProperties().get(overrideEntry.getKey()));
assertEquals(overriddenConsumerPropValue, rlmmConfig.consumerProperties().get(overrideEntry.getKey()));
}
@Test
void verifyToStringRedactsSensitiveConfigurations() {
Map<String, Object> commonClientConfig = new HashMap<>();
commonClientConfig.put(CommonClientConfigs.RETRIES_CONFIG, 10);
commonClientConfig.put(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG, 1000L);
commonClientConfig.put(CommonClientConfigs.METADATA_MAX_AGE_CONFIG, 60000L);
addPasswordTypeConfigurationProperties(commonClientConfig);
Map<String, Object> producerConfig = new HashMap<>();
producerConfig.put(ProducerConfig.ACKS_CONFIG, "all");
addPasswordTypeConfigurationProperties(producerConfig);
Map<String, Object> consumerConfig = new HashMap<>();
consumerConfig.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
addPasswordTypeConfigurationProperties(consumerConfig);
Map<String, Object> props = createValidConfigProps(commonClientConfig, producerConfig, consumerConfig);
// Check for topic properties
TopicBasedRemoteLogMetadataManagerConfig rlmmConfig = new TopicBasedRemoteLogMetadataManagerConfig(props);
String configString = rlmmConfig.toString();
assertMaskedSensitiveConfigurations(configString);
//verify not redacted properties present
assertTrue(configString.contains("retries=10"));
assertTrue(configString.contains("acks=\"all\""));
assertTrue(configString.contains("enable.auto.commit=false"));
}
private Map<String, Object> createValidConfigProps(Map<String, Object> commonClientConfig,
Map<String, Object> producerConfig,
Map<String, Object> consumerConfig) {
Map<String, Object> props = new HashMap<>();
props.put(REMOTE_LOG_METADATA_COMMON_CLIENT_PREFIX + CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
props.put(BROKER_ID, 1);
props.put(LOG_DIR, TestUtils.tempDirectory().getAbsolutePath());
props.put(REMOTE_LOG_METADATA_TOPIC_REPLICATION_FACTOR_PROP, (short) 3);
props.put(REMOTE_LOG_METADATA_TOPIC_PARTITIONS_PROP, 10);
props.put(REMOTE_LOG_METADATA_TOPIC_RETENTION_MS_PROP, 60 * 60 * 1000L);
// common client configs
for (Map.Entry<String, Object> entry : commonClientConfig.entrySet()) {
props.put(REMOTE_LOG_METADATA_COMMON_CLIENT_PREFIX + entry.getKey(), entry.getValue());
}
// producer configs
for (Map.Entry<String, Object> entry : producerConfig.entrySet()) {
props.put(REMOTE_LOG_METADATA_PRODUCER_PREFIX + entry.getKey(), entry.getValue());
}
//consumer configs
for (Map.Entry<String, Object> entry : consumerConfig.entrySet()) {
props.put(REMOTE_LOG_METADATA_CONSUMER_PREFIX + entry.getKey(), entry.getValue());
}
return props;
}
/**
* Sample properties marked with {@link org.apache.kafka.common.config.ConfigDef.Type#PASSWORD} in the configuration.
*/
private void addPasswordTypeConfigurationProperties(Map<String, Object> config) {
config.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "keystorePassword");
config.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "keyPassword");
config.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, "keystoreKey");
config.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, "keystoreCertificate");
config.put(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, "truststoreCertificate");
config.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "truststorePassword");
config.put(SaslConfigs.SASL_JAAS_CONFIG, "saslJaas");
}
private void assertMaskedSensitiveConfigurations(String configString) {
String[] sensitiveConfigKeys = {
SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG,
SslConfigs.SSL_KEY_PASSWORD_CONFIG,
SslConfigs.SSL_KEYSTORE_KEY_CONFIG,
SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG,
SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG,
SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG,
SaslConfigs.SASL_JAAS_CONFIG
};
Arrays.stream(sensitiveConfigKeys)
.forEach(config -> assertTrue(configString.contains(config + "=(redacted)")));
}
} | TopicBasedRemoteLogMetadataManagerConfigTest |
java | lettuce-io__lettuce-core | src/main/templates/io/lettuce/core/api/RedisSentinelCommands.java | {
"start": 1272,
"end": 7578
} | interface ____<K, V> {
/**
* Return the ip and port number of the master with that name.
*
* @param key the key.
* @return SocketAddress.
*/
SocketAddress getMasterAddrByName(K key);
/**
* Enumerates all the monitored masters and their states.
*
* @return Map<K, V>>.
*/
List<Map<K, V>> masters();
/**
* Show the state and info of the specified master.
*
* @param key the key.
* @return Map<K, V>.
*/
Map<K, V> master(K key);
/**
* Provides a list of replicas for the master with the specified name.
*
* @param key the key.
* @return List<Map<K, V>>.
* @deprecated since 6.2, use #replicas(Object) instead.
*/
@Deprecated
List<Map<K, V>> slaves(K key);
/**
* This command will reset all the masters with matching name.
*
* @param key the key.
* @return Long.
*/
Long reset(K key);
/**
* Provides a list of replicas for the master with the specified name.
*
* @param key the key.
* @return List<Map<K, V>>.
* @since 6.2
*/
List<Map<K, V>> replicas(K key);
/**
* Perform a failover.
*
* @param key the master id.
* @return String.
*/
String failover(K key);
/**
* This command tells the Sentinel to start monitoring a new master with the specified name, ip, port, and quorum.
*
* @param key the key.
* @param ip the IP address.
* @param port the port.
* @param quorum the quorum count.
* @return String.
*/
String monitor(K key, String ip, int port, int quorum);
/**
* Multiple option / value pairs can be specified (or none at all).
*
* @param key the key.
* @param option the option.
* @param value the value.
* @return String simple-string-reply {@code OK} if {@code SET} was executed correctly.
*/
String set(K key, String option, V value);
/**
* remove the specified master.
*
* @param key the key.
* @return String.
*/
String remove(K key);
/**
* Get the current connection name.
*
* @return K bulk-string-reply The connection name, or a null bulk reply if no name is set.
*/
K clientGetname();
/**
* Set the current connection name.
*
* @param name the client name.
* @return simple-string-reply {@code OK} if the connection name was successfully set.
*/
String clientSetname(K name);
/**
* Assign various info attributes to the current connection.
*
* @param key the key.
* @param value the value.
* @return simple-string-reply {@code OK} if the connection name was successfully set.
* @since 6.3
*/
String clientSetinfo(String key, String value);
/**
* Kill the connection of a client identified by ip:port.
*
* @param addr ip:port.
* @return String simple-string-reply {@code OK} if the connection exists and has been closed.
*/
String clientKill(String addr);
/**
* Kill connections of clients which are filtered by {@code killArgs}.
*
* @param killArgs args for the kill operation.
* @return Long integer-reply number of killed connections.
*/
Long clientKill(KillArgs killArgs);
/**
* Stop processing commands from clients for some time.
*
* @param timeout the timeout value in milliseconds.
* @return String simple-string-reply The command returns OK or an error if the timeout is invalid.
*/
String clientPause(long timeout);
/**
* Get the list of client connections.
*
* @return String bulk-string-reply a unique string, formatted as follows: One client connection per line (separated by LF),
* each line is composed of a succession of property=value fields separated by a space character.
*/
String clientList();
/**
* Get the list of client connections which are filtered by {@code clientListArgs}.
*
* @return String bulk-string-reply a unique string, formatted as follows: One client connection per line (separated by LF),
* each line is composed of a succession of property=value fields separated by a space character.
* @since 6.3
*/
String clientList(ClientListArgs clientListArgs);
/**
* Get the list of the current client connection.
*
* @return String bulk-string-reply a unique string, formatted as a succession of property=value fields separated by a space
* character.
* @since 6.3
*/
String clientInfo();
/**
* Get information and statistics about the server.
*
* @return String bulk-string-reply as a collection of text lines.
*/
String info();
/**
* Get information and statistics about the server.
*
* @param section the section type: string.
* @return String bulk-string-reply as a collection of text lines.
*/
String info(String section);
/**
* Ping the server.
*
* @return String simple-string-reply.
*/
String ping();
/**
* Dispatch a command to the Redis Server. Please note the command output type must fit to the command response.
*
* @param type the command, must not be {@code null}.
* @param output the command output, must not be {@code null}.
* @param <T> response type.
* @return the command response.
* @since 6.0.2
*/
<T> T dispatch(ProtocolKeyword type, CommandOutput<K, V, T> output);
/**
* Dispatch a command to the Redis Server. Please note the command output type must fit to the command response.
*
* @param type the command, must not be {@code null}.
* @param output the command output, must not be {@code null}.
* @param args the command arguments, must not be {@code null}.
* @param <T> response type.
* @return the command response.
* @since 6.0.2
*/
<T> T dispatch(ProtocolKeyword type, CommandOutput<K, V, T> output, CommandArgs<K, V> args);
/**
*
* @return the underlying connection.
*/
StatefulRedisSentinelConnection<K, V> getStatefulConnection();
}
| RedisSentinelCommands |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/internal/rbac/engine/GrpcAuthorizationEngine.java | {
"start": 16208,
"end": 16522
} | class ____ implements Matcher {
public static AlwaysTrueMatcher INSTANCE =
new AutoValue_GrpcAuthorizationEngine_AlwaysTrueMatcher();
@Override
public boolean matches(EvaluateArgs args) {
return true;
}
}
/** Negate matcher.*/
@AutoValue
public abstract static | AlwaysTrueMatcher |
java | apache__camel | dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/SourceDirDevConsole.java | {
"start": 1789,
"end": 8657
} | class ____ extends AbstractDevConsole {
/**
* Whether to show the source in the output
*/
public static final String SOURCE = "source";
public SourceDirDevConsole() {
super("camel-jbang", "source-dir", "Source Directory", "Information about Camel JBang source files");
}
@Override
protected String doCallText(Map<String, Object> options) {
String path = (String) options.get(Exchange.HTTP_PATH);
String subPath = path != null ? StringHelper.after(path, "/") : null;
String source = (String) options.get(SOURCE);
final StringBuilder sb = new StringBuilder();
RouteOnDemandReloadStrategy reload = getCamelContext().hasService(RouteOnDemandReloadStrategy.class);
if (reload != null) {
sb.append(String.format("Directory: %s%n", reload.getFolder()));
// list files in this directory
Path dir = Paths.get(reload.getFolder());
if (Files.exists(dir) && Files.isDirectory(dir)) {
try (Stream<Path> streams = Files.list(dir)) {
List<Path> files = streams.collect(Collectors.toList());
if (!files.isEmpty()) {
sb.append("Files:\n");
// sort files by name (ignore case)
files.sort((o1, o2) -> o1.getFileName().toString().compareToIgnoreCase(o2.getFileName().toString()));
for (Path f : files) {
String fileName = f.getFileName().toString();
boolean skip = fileName.startsWith(".") || Files.isHidden(f);
if (skip) {
continue;
}
boolean match = subPath == null || fileName.startsWith(subPath) || fileName.endsWith(subPath)
|| PatternHelper.matchPattern(fileName, subPath);
if (match) {
long size = Files.size(f);
long ts = Files.getLastModifiedTime(f).toMillis();
String age = ts > 0 ? TimeUtils.printSince(ts) : "n/a";
sb.append(String.format(" %s (size: %d age: %s)%n", fileName, size, age));
if ("true".equals(source)) {
StringBuilder code = new StringBuilder();
try (Reader fileReader = Files.newBufferedReader(f, StandardCharsets.UTF_8);
LineNumberReader reader = new LineNumberReader(fileReader)) {
int i = 0;
String t;
do {
t = reader.readLine();
if (t != null) {
i++;
code.append(String.format("\n #%s %s", i, t));
}
} while (t != null);
} catch (Exception e) {
// ignore
}
if (!code.isEmpty()) {
sb.append(" ").append("-".repeat(40));
sb.append(code);
sb.append("\n\n");
}
}
}
}
}
} catch (Exception e) {
// ignore
}
}
}
return sb.toString();
}
@Override
protected Map<String, Object> doCallJson(Map<String, Object> options) {
String path = (String) options.get(Exchange.HTTP_PATH);
String subPath = path != null ? StringHelper.after(path, "/") : null;
String source = (String) options.get(SOURCE);
JsonObject root = new JsonObject();
RouteOnDemandReloadStrategy reload = getCamelContext().hasService(RouteOnDemandReloadStrategy.class);
if (reload != null) {
root.put("dir", reload.getFolder());
// list files in this directory
Path dir = Paths.get(reload.getFolder());
if (Files.exists(dir) && Files.isDirectory(dir)) {
try (Stream<Path> streams = Files.list(dir)) {
List<Path> files = streams.collect(Collectors.toList());
if (!files.isEmpty()) {
// sort files by name (ignore case)
files.sort((o1, o2) -> o1.getFileName().toString().compareToIgnoreCase(o2.getFileName().toString()));
JsonArray arr = new JsonArray();
root.put("files", arr);
for (Path f : files) {
String fileName = f.getFileName().toString();
boolean skip = fileName.startsWith(".") || Files.isHidden(f);
if (skip) {
continue;
}
boolean match = subPath == null || fileName.startsWith(subPath) || fileName.endsWith(subPath)
|| PatternHelper.matchPattern(fileName, subPath);
if (match) {
JsonObject jo = new JsonObject();
jo.put("name", fileName);
jo.put("size", Files.size(f));
jo.put("lastModified", Files.getLastModifiedTime(f).toMillis());
if ("true".equals(source)) {
try (Reader fileReader = Files.newBufferedReader(f, StandardCharsets.UTF_8)) {
List<JsonObject> code = ConsoleHelper.loadSourceAsJson(fileReader, null);
if (code != null) {
jo.put("code", code);
}
} catch (Exception e) {
// ignore
}
}
arr.add(jo);
}
}
}
} catch (Exception e) {
// ignore
}
}
}
return root;
}
}
| SourceDirDevConsole |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java | {
"start": 6933,
"end": 6991
} | interface ____ extends Greetable {
}
private static | Person |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/RepeatedPermissionsAllowedTest.java | {
"start": 635,
"end": 3301
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(TestIdentityProvider.class, TestIdentityController.class, HelloResource.class)
.addAsResource(
new StringAsset(
"quarkus.log.category.\"io.quarkus.vertx.http.runtime.QuarkusErrorHandler\".level=OFF"
+ System.lineSeparator()),
"application.properties"));
@BeforeAll
public static void setupUsers() {
TestIdentityController.resetRoles()
.add("user", "user", new StringPermission("read"))
.add("admin", "admin", new StringPermission("read"), new StringPermission("write"));
}
@Test
public void testRepeatedPermissionsAllowedOnClass() {
// anonymous user
RestAssured.given()
.body("{%$$#!#@") // assures checks are eager
.post("/hello")
.then()
.statusCode(401);
// authenticated user, insufficient rights
RestAssured.given()
.auth().preemptive().basic("user", "user")
.body("{%$$#!#@") // assures checks are eager
.post("/hello")
.then()
.statusCode(403);
// authorized user, invalid payload
RestAssured.given()
.auth().preemptive().basic("admin", "admin")
.body("{%$$#!#@") // assures checks are eager
.post("/hello")
.then()
.statusCode(500);
}
@Test
public void testRepeatedPermissionsAllowedOnInterface() {
// anonymous user
RestAssured.given()
.body("{%$$#!#@") // assures checks are eager
.post("/hello-interface")
.then()
.statusCode(401);
// authenticated user, insufficient rights
RestAssured.given()
.auth().preemptive().basic("user", "user")
.body("{%$$#!#@") // assures checks are eager
.post("/hello-interface")
.then()
.statusCode(403);
// authorized user, invalid payload
RestAssured.given()
.auth().preemptive().basic("admin", "admin")
.body("{%$$#!#@") // assures checks are eager
.post("/hello-interface")
.then()
.statusCode(500);
}
@Path("/hello")
public static | RepeatedPermissionsAllowedTest |
java | google__dagger | hilt-compiler/main/java/dagger/hilt/processor/internal/ComponentNames.java | {
"start": 737,
"end": 847
} | class ____ getting the generated component name.
*
* <p>This should not be used externally.
*/
public final | for |
java | quarkusio__quarkus | integration-tests/test-extension/extension/runtime/src/main/java/io/quarkus/extest/runtime/config/StaticInitConfigBuilder.java | {
"start": 206,
"end": 605
} | class ____ implements ConfigBuilder {
public static AtomicInteger counter = new AtomicInteger(0);
public StaticInitConfigBuilder() {
counter.incrementAndGet();
}
@Override
public SmallRyeConfigBuilder configBuilder(final SmallRyeConfigBuilder builder) {
builder.withDefaultValue("skip.build.sources", "true");
return builder;
}
}
| StaticInitConfigBuilder |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/classes/ClassAssert_hasOnlyPublicFields_Test.java | {
"start": 905,
"end": 1257
} | class ____ extends ClassAssertBaseTest {
@Override
protected ClassAssert invoke_api_method() {
return assertions.hasOnlyPublicFields("field");
}
@Override
protected void verify_internal_effects() {
verify(classes).assertHasOnlyPublicFields(getInfo(assertions), getActual(assertions), "field");
}
}
| ClassAssert_hasOnlyPublicFields_Test |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/Options.java | {
"start": 374,
"end": 1990
} | class ____ implements Key {
private final ArrayMap<Option<?>, Object> values = new CachedHashCodeArrayMap<>();
public void putAll(@NonNull Options other) {
values.putAll((SimpleArrayMap<Option<?>, Object>) other.values);
}
@NonNull
public <T> Options set(@NonNull Option<T> option, @NonNull T value) {
values.put(option, value);
return this;
}
// TODO(b/234614365): Expand usage of this method in BaseRequestOptions so that it's usable for
// other options.
public Options remove(@NonNull Option<?> option) {
values.remove(option);
return this;
}
@Nullable
@SuppressWarnings("unchecked")
public <T> T get(@NonNull Option<T> option) {
return values.containsKey(option) ? (T) values.get(option) : option.getDefaultValue();
}
@Override
public boolean equals(Object o) {
if (o instanceof Options) {
Options other = (Options) o;
return values.equals(other.values);
}
return false;
}
@Override
public int hashCode() {
return values.hashCode();
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
for (int i = 0; i < values.size(); i++) {
Option<?> key = values.keyAt(i);
Object value = values.valueAt(i);
updateDiskCacheKey(key, value, messageDigest);
}
}
@Override
public String toString() {
return "Options{" + "values=" + values + '}';
}
@SuppressWarnings("unchecked")
private static <T> void updateDiskCacheKey(
@NonNull Option<T> option, @NonNull Object value, @NonNull MessageDigest md) {
option.update((T) value, md);
}
}
| Options |
java | quarkusio__quarkus | integration-tests/container-image/maven-invoker-way/src/it/container-native-main/src/test/java/org/acme/HelloWorldMainTest.java | {
"start": 297,
"end": 868
} | class ____ {
@Test
@Launch("World")
public void testLaunchCommand(LaunchResult result) {
Assertions.assertTrue(result.getOutput().contains("Hello World"));
}
@Test
@Launch(value = {}, exitCode = 1)
public void testLaunchCommandFailed() {
}
@Test
public void testManualLaunch(QuarkusMainLauncher launcher) {
LaunchResult result = launcher.launch("Everyone");
Assertions.assertEquals(0, result.exitCode());
Assertions.assertTrue(result.getOutput().contains("Hello Everyone"));
}
} | HelloWorldMainTest |
java | quarkusio__quarkus | extensions/cache/deployment/src/test/java/io/quarkus/cache/test/deployment/UnknownCacheTypeTest.java | {
"start": 439,
"end": 983
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(new StringAsset("quarkus.cache.type=i_am_an_unknown_cache_type"), "application.properties")
.addClass(CachedService.class))
.setExpectedException(DeploymentException.class);
@Test
public void shouldNotBeInvoked() {
fail("This method should not be invoked");
}
@ApplicationScoped
static | UnknownCacheTypeTest |
java | apache__hadoop | hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/client/types/Endpoint.java | {
"start": 1946,
"end": 7211
} | class ____ implements Cloneable {
/**
* API implemented at the end of the binding
*/
public String api;
/**
* Type of address. The standard types are defined in
* {@link AddressTypes}
*/
public String addressType;
/**
* Protocol type. Some standard types are defined in
* {@link ProtocolTypes}
*/
public String protocolType;
/**
* a list of address tuples —tuples whose format depends on the address type
*/
public List<Map<String, String>> addresses;
/**
* Create an empty instance.
*/
public Endpoint() {
}
/**
* Create an endpoint from another endpoint.
* This is a deep clone with a new list of addresses.
* @param that the endpoint to copy from
*/
public Endpoint(Endpoint that) {
this.api = that.api;
this.addressType = that.addressType;
this.protocolType = that.protocolType;
this.addresses = newAddresses(that.addresses.size());
for (Map<String, String> address : that.addresses) {
Map<String, String> addr2 = new HashMap<String, String>(address.size());
addr2.putAll(address);
addresses.add(addr2);
}
}
/**
* Build an endpoint with a list of addresses
* @param api API name
* @param addressType address type
* @param protocolType protocol type
* @param addrs addresses
*/
public Endpoint(String api,
String addressType,
String protocolType,
List<Map<String, String>> addrs) {
this.api = api;
this.addressType = addressType;
this.protocolType = protocolType;
this.addresses = newAddresses(0);
if (addrs != null) {
addresses.addAll(addrs);
}
}
/**
* Build an endpoint with an empty address list
* @param api API name
* @param addressType address type
* @param protocolType protocol type
*/
public Endpoint(String api,
String addressType,
String protocolType) {
this.api = api;
this.addressType = addressType;
this.protocolType = protocolType;
this.addresses = newAddresses(0);
}
/**
* Build an endpoint with a single address entry.
* <p>
* This constructor is superfluous given the varags constructor is equivalent
* for a single element argument. However, type-erasure in java generics
* causes javac to warn about unchecked generic array creation. This
* constructor, which represents the common "one address" case, does
* not generate compile-time warnings.
* @param api API name
* @param addressType address type
* @param protocolType protocol type
* @param addr address. May be null —in which case it is not added
*/
public Endpoint(String api,
String addressType,
String protocolType,
Map<String, String> addr) {
this(api, addressType, protocolType);
if (addr != null) {
addresses.add(addr);
}
}
/**
* Build an endpoint with a list of addresses
* @param api API name
* @param addressType address type
* @param protocolType protocol type
* @param addrs addresses. Null elements will be skipped
*/
public Endpoint(String api,
String addressType,
String protocolType,
Map<String, String>...addrs) {
this(api, addressType, protocolType);
for (Map<String, String> addr : addrs) {
if (addr!=null) {
addresses.add(addr);
}
}
}
/**
* Create a new address structure of the requested size
* @param size size to create
* @return the new list
*/
private List<Map<String, String>> newAddresses(int size) {
return new ArrayList<Map<String, String>>(size);
}
/**
* Build an endpoint from a list of URIs; each URI
* is ASCII-encoded and added to the list of addresses.
* @param api API name
* @param protocolType protocol type
* @param uris URIs to convert to a list of tup;les
*/
public Endpoint(String api,
String protocolType,
URI... uris) {
this.api = api;
this.addressType = AddressTypes.ADDRESS_URI;
this.protocolType = protocolType;
List<Map<String, String>> addrs = newAddresses(uris.length);
for (URI uri : uris) {
addrs.add(RegistryTypeUtils.uri(uri.toString()));
}
this.addresses = addrs;
}
@Override
public String toString() {
return marshalToString.toString(this);
}
/**
* Validate the record by checking for null fields and other invalid
* conditions
* @throws NullPointerException if a field is null when it
* MUST be set.
* @throws RuntimeException on invalid entries
*/
public void validate() {
Preconditions.checkNotNull(api, "null API field");
Preconditions.checkNotNull(addressType, "null addressType field");
Preconditions.checkNotNull(protocolType, "null protocolType field");
Preconditions.checkNotNull(addresses, "null addresses field");
for (Map<String, String> address : addresses) {
Preconditions.checkNotNull(address, "null element in address");
}
}
/**
* Shallow clone: the lists of addresses are shared
* @return a cloned instance
* @throws CloneNotSupportedException
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Static instance of service record marshalling
*/
private static | Endpoint |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java | {
"start": 4565,
"end": 5118
} | class ____ implements Test {
// BUG: Diagnostic contains: should be final or annotated
public Object[] xs = {};
public Class<? extends Annotation> annotationType() {
return null;
}
}
""")
.doTest();
}
@Test
public void customAnnotationsSubtype() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.errorprone.annotations.ThreadSafe;
@ThreadSafe
@ | MyTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ResourceTypeInfoPBImpl.java | {
"start": 1395,
"end": 1495
} | class ____ represents different resource types
* supported in YARN.
*/
@Private
@Unstable
public | which |
java | dropwizard__dropwizard | dropwizard-health/src/main/java/io/dropwizard/health/response/HealthResponseProvider.java | {
"start": 141,
"end": 271
} | interface ____ {
@NonNull
HealthResponse healthResponse(Map<String, Collection<String>> queryParams);
}
| HealthResponseProvider |
java | apache__thrift | lib/java/src/main/java/org/apache/thrift/protocol/TSimpleJSONProtocol.java | {
"start": 2127,
"end": 2333
} | class ____ {
protected void write() throws TException {}
/** Returns whether the current value is a key in a map */
protected boolean isMapKey() {
return false;
}
}
protected | Context |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/base/DecorableTSFactory.java | {
"start": 798,
"end": 7759
} | class ____<F extends TokenStreamFactory,
T extends TSFBuilder<F,T>>
extends TSFBuilder<F,T>
{
/**
* Optional helper object that may decorate input sources, to do
* additional processing on input during parsing.
*/
protected InputDecorator _inputDecorator;
/**
* Optional helper object that may decorate output object, to do
* additional processing on output during content generation.
*/
protected OutputDecorator _outputDecorator;
protected List<JsonGeneratorDecorator> _generatorDecorators;
// // // Construction
protected DecorableTSFBuilder(StreamReadConstraints src,
StreamWriteConstraints swc, ErrorReportConfiguration erc,
int formatPF, int formatGF) {
super(src, swc, erc, formatPF, formatGF);
_inputDecorator = null;
_outputDecorator = null;
_generatorDecorators = null;
}
protected DecorableTSFBuilder(DecorableTSFactory base)
{
super(base);
_inputDecorator = base.getInputDecorator();
_outputDecorator = base.getOutputDecorator();
_generatorDecorators = base.getGeneratorDecorators();
}
// // // Accessors
public InputDecorator inputDecorator() { return _inputDecorator; }
public OutputDecorator outputDecorator() { return _outputDecorator; }
public List<JsonGeneratorDecorator> generatorDecorators() { return _generatorDecorators; }
// // // Decorators
public T inputDecorator(InputDecorator dec) {
_inputDecorator = dec;
return _this();
}
public T outputDecorator(OutputDecorator dec) {
_outputDecorator = dec;
return _this();
}
public T addDecorator(JsonGeneratorDecorator dec) {
if (_generatorDecorators == null) {
_generatorDecorators = new ArrayList<>();
}
_generatorDecorators.add(dec);
return _this();
}
}
/*
/**********************************************************************
/* Configuration
/**********************************************************************
*/
/**
* Optional helper object that may decorate input sources, to do
* additional processing on input during parsing.
*/
protected final InputDecorator _inputDecorator;
/**
* Optional helper object that may decorate output object, to do
* additional processing on output during content generation.
*/
protected final OutputDecorator _outputDecorator;
protected List<JsonGeneratorDecorator> _generatorDecorators;
/*
/**********************************************************************
/* Construction
/**********************************************************************
*/
protected DecorableTSFactory(StreamReadConstraints src, StreamWriteConstraints swc,
ErrorReportConfiguration erc,
int formatPF, int formatGF) {
super(src, swc, erc, formatPF, formatGF);
_inputDecorator = null;
_outputDecorator = null;
_generatorDecorators = null;
}
/**
* Constructor used by builders for instantiation.
*
* @param baseBuilder Builder with configurations to use
*
* @since 3.0
*/
protected DecorableTSFactory(DecorableTSFBuilder<?,?> baseBuilder)
{
super(baseBuilder);
_inputDecorator = baseBuilder.inputDecorator();
_outputDecorator = baseBuilder.outputDecorator();
_generatorDecorators = _copy(baseBuilder.generatorDecorators());
}
// Copy constructor.
protected DecorableTSFactory(DecorableTSFactory src) {
super(src);
_inputDecorator = src.getInputDecorator();
_outputDecorator = src.getOutputDecorator();
_generatorDecorators = _copy(src._generatorDecorators);
}
protected static <T> List<T> _copy(List<T> src) {
if (src == null) {
return src;
}
return new ArrayList<T>(src);
}
/*
/**********************************************************************
/* Configuration, decorators
/**********************************************************************
*/
public OutputDecorator getOutputDecorator() {
return _outputDecorator;
}
public InputDecorator getInputDecorator() {
return _inputDecorator;
}
public List<JsonGeneratorDecorator> getGeneratorDecorators() {
return _copy(_generatorDecorators);
}
/*
/**********************************************************************
/* Decorators, input
/**********************************************************************
*/
protected InputStream _decorate(IOContext ioCtxt, InputStream in) throws JacksonException
{
if (_inputDecorator != null) {
InputStream in2 = _inputDecorator.decorate(ioCtxt, in);
if (in2 != null) {
return in2;
}
}
return in;
}
protected Reader _decorate(IOContext ioCtxt, Reader in) throws JacksonException
{
if (_inputDecorator != null) {
Reader in2 = _inputDecorator.decorate(ioCtxt, in);
if (in2 != null) {
return in2;
}
}
return in;
}
protected DataInput _decorate(IOContext ioCtxt, DataInput in) throws JacksonException
{
if (_inputDecorator != null) {
DataInput in2 = _inputDecorator.decorate(ioCtxt, in);
if (in2 != null) {
return in2;
}
}
return in;
}
/*
/**********************************************************************
/* Decorators, output
/**********************************************************************
*/
protected OutputStream _decorate(IOContext ioCtxt, OutputStream out) throws JacksonException
{
if (_outputDecorator != null) {
OutputStream out2 = _outputDecorator.decorate(ioCtxt, out);
if (out2 != null) {
return out2;
}
}
return out;
}
protected Writer _decorate(IOContext ioCtxt, Writer out) throws JacksonException
{
if (_outputDecorator != null) {
Writer out2 = _outputDecorator.decorate(ioCtxt, out);
if (out2 != null) {
return out2;
}
}
return out;
}
protected JsonGenerator _decorate(JsonGenerator result) {
if (_generatorDecorators != null) {
for(JsonGeneratorDecorator decorator : _generatorDecorators) {
result = decorator.decorate(this, result);
}
}
return result;
}
}
| DecorableTSFBuilder |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayHashCodePositiveCases2.java | {
"start": 781,
"end": 3562
} | class ____ {
private Object[] objArray = {1, 2, 3};
private String[] stringArray = {"1", "2", "3"};
private int[] intArray = {1, 2, 3};
private byte[] byteArray = {1, 2, 3};
private int[][] multidimensionalIntArray = {{1, 2, 3}, {4, 5, 6}};
private String[][] multidimensionalStringArray = {{"1", "2", "3"}, {"4", "5", "6"}};
public void javaUtilObjectsHashCode() {
int hashCode;
// BUG: Diagnostic contains: Arrays.hashCode(objArray)
hashCode = Objects.hashCode(objArray);
// BUG: Diagnostic contains: Arrays.hashCode(stringArray)
hashCode = Objects.hashCode(stringArray);
// BUG: Diagnostic contains: Arrays.hashCode(intArray)
hashCode = Objects.hashCode(intArray);
// BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalIntArray)
hashCode = Objects.hashCode(multidimensionalIntArray);
// BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalStringArray)
hashCode = Objects.hashCode(multidimensionalStringArray);
}
public void javaUtilObjectsHash() {
int hashCode;
// BUG: Diagnostic contains: Arrays.hashCode(intArray)
hashCode = Objects.hash(intArray);
// BUG: Diagnostic contains: Arrays.hashCode(byteArray)
hashCode = Objects.hash(byteArray);
// BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalIntArray)
hashCode = Objects.hash(multidimensionalIntArray);
// BUG: Diagnostic contains: Arrays.deepHashCode(multidimensionalStringArray)
hashCode = Objects.hash(multidimensionalStringArray);
}
public void varargsHashCodeOnMoreThanOneArg() {
int hashCode;
// BUG: Diagnostic contains: Objects.hash(Arrays.hashCode(objArray), Arrays.hashCode(intArray))
hashCode = Objects.hash(objArray, intArray);
// BUG: Diagnostic contains: Objects.hash(Arrays.hashCode(stringArray),
// Arrays.hashCode(byteArray))
hashCode = Objects.hash(stringArray, byteArray);
Object obj1 = new Object();
Object obj2 = new Object();
// BUG: Diagnostic contains: Objects.hash(obj1, obj2, Arrays.hashCode(intArray))
hashCode = Objects.hash(obj1, obj2, intArray);
// BUG: Diagnostic contains: Objects.hash(obj1, Arrays.hashCode(intArray), obj2)
hashCode = Objects.hash(obj1, intArray, obj2);
// BUG: Diagnostic contains: Objects.hash(Arrays.hashCode(intArray), obj1, obj2)
hashCode = Objects.hash(intArray, obj1, obj2);
// BUG: Diagnostic contains: Objects.hash(obj1, obj2,
// Arrays.deepHashCode(multidimensionalIntArray))
hashCode = Objects.hash(obj1, obj2, multidimensionalIntArray);
// BUG: Diagnostic contains: Objects.hash(obj1, obj2,
// Arrays.deepHashCode(multidimensionalStringArray))
hashCode = Objects.hash(obj1, obj2, multidimensionalStringArray);
}
}
| ArrayHashCodePositiveCases2 |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/ThreadInfoSampleServiceTest.java | {
"start": 8631,
"end": 8960
} | class ____ implements SampleableTask {
private final ExecutionAttemptID executionId = ExecutionAttemptID.randomId();
public Thread getExecutingThread() {
return new Thread();
}
public ExecutionAttemptID getExecutionId() {
return executionId;
}
}
}
| NotRunningTask |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GoogleCloudFunctionsEndpointBuilderFactory.java | {
"start": 1432,
"end": 1585
} | interface ____ {
/**
* Builder for endpoint for the Google Cloud Functions component.
*/
public | GoogleCloudFunctionsEndpointBuilderFactory |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/UserWeights.java | {
"start": 1487,
"end": 3474
} | class ____ {
public static final float DEFAULT_WEIGHT = 1.0F;
/**
* Key: Username,
* Value: Weight as float.
*/
private final Map<String, Float> data = new HashMap<>();
private UserWeights() {}
public static UserWeights createEmpty() {
return new UserWeights();
}
public static UserWeights createByConfig(
CapacitySchedulerConfiguration conf,
ConfigurationProperties configurationProperties,
QueuePath queuePath) {
String queuePathPlusPrefix = getQueuePrefix(queuePath) + USER_SETTINGS;
Map<String, String> props = configurationProperties
.getPropertiesWithPrefix(queuePathPlusPrefix);
UserWeights userWeights = new UserWeights();
for (Map.Entry<String, String> item: props.entrySet()) {
Matcher m = USER_WEIGHT_PATTERN.matcher(item.getKey());
if (m.find()) {
String userName = item.getKey().replaceFirst("\\." + USER_WEIGHT, "");
if (!userName.isEmpty()) {
String value = conf.substituteCommonVariables(item.getValue());
userWeights.data.put(userName, new Float(value));
}
}
}
return userWeights;
}
public float getByUser(String userName) {
Float weight = data.get(userName);
if (weight == null) {
return DEFAULT_WEIGHT;
}
return weight;
}
public void validateForLeafQueue(float queueUserLimit, String queuePath) throws IOException {
for (Map.Entry<String, Float> e : data.entrySet()) {
String userName = e.getKey();
float weight = e.getValue();
if (weight < 0.0F || weight > (100.0F / queueUserLimit)) {
throw new IOException("Weight (" + weight + ") for user \"" + userName
+ "\" must be between 0 and" + " 100 / " + queueUserLimit + " (= " +
100.0f / queueUserLimit + ", the number of concurrent active users in "
+ queuePath + ")");
}
}
}
public void addFrom(UserWeights addFrom) {
data.putAll(addFrom.data);
}
}
| UserWeights |
java | quarkusio__quarkus | extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/FixedLocaleJavaType.java | {
"start": 414,
"end": 1295
} | class ____ extends LocaleJavaType {
public FixedLocaleJavaType() {
super();
}
@Override
public JdbcType getRecommendedJdbcType(JdbcTypeIndicators indicators) {
return indicators.getJdbcType(SqlTypes.VARCHAR);
}
@SuppressWarnings("unchecked")
@Override
public <X> X unwrap(Locale value, Class<X> type, WrapperOptions options) {
if (value == null) {
return null;
}
if (Locale.class.isAssignableFrom(type)) {
return (X) value;
}
return super.unwrap(value, type, options);
}
@Override
public <X> Locale wrap(X value, WrapperOptions options) {
if (value == null) {
return null;
}
if (value instanceof Locale) {
return (Locale) value;
}
return super.wrap(value, options);
}
}
| FixedLocaleJavaType |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/SinkTestPrograms.java | {
"start": 1173,
"end": 4924
} | class ____ {
public static final TableTestProgram INSERT_RETRACT_WITHOUT_PK =
TableTestProgram.of(
"insert-retract-without-pk",
"The sink accepts retract input. Retract is directly passed through.")
.setupTableSource(
SourceTestStep.newBuilder("source_t")
.addSchema("name STRING", "score INT")
.addOption("changelog-mode", "I")
.producedValues(
Row.ofKind(RowKind.INSERT, "Alice", 3),
Row.ofKind(RowKind.INSERT, "Bob", 5),
Row.ofKind(RowKind.INSERT, "Bob", 6),
Row.ofKind(RowKind.INSERT, "Charly", 33))
.build())
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema("name STRING", "score BIGINT")
.addOption("sink-changelog-mode-enforced", "I,UB,UA,D")
.consumedValues(
"+I[Alice, 3]",
"+I[Bob, 5]",
"-U[Bob, 5]",
"+U[Bob, 11]",
"+I[Charly, 33]")
.build())
.runSql(
"INSERT INTO sink_t SELECT name, SUM(score) FROM source_t GROUP BY name")
.build();
public static final TableTestProgram INSERT_RETRACT_WITH_PK =
TableTestProgram.of(
"insert-retract-with-pk",
"The sink accepts retract input. Although upsert keys (name) and primary keys (UPPER(name))"
+ "don't match, the retract changelog is passed through.")
.setupTableSource(
SourceTestStep.newBuilder("source_t")
.addSchema("name STRING", "score INT")
.addOption("changelog-mode", "I")
.producedValues(
Row.ofKind(RowKind.INSERT, "Alice", 3),
Row.ofKind(RowKind.INSERT, "Bob", 5),
Row.ofKind(RowKind.INSERT, "Bob", 6),
Row.ofKind(RowKind.INSERT, "Charly", 33))
.build())
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
"name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
.addOption("sink-changelog-mode-enforced", "I,UB,UA,D")
.consumedValues(
"+I[ALICE, 3]",
"+I[BOB, 5]",
"-U[BOB, 5]",
"+U[BOB, 11]",
"+I[CHARLY, 33]")
.build())
.runSql(
"INSERT INTO sink_t SELECT UPPER(name), SUM(score) FROM source_t GROUP BY name")
.build();
}
| SinkTestPrograms |
java | apache__camel | components/camel-cxf/camel-cxf-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/simplebinding/testbean/CustomerList.java | {
"start": 995,
"end": 1234
} | class ____ {
private List<Customer> customers;
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
| CustomerList |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/instance/cacheget/InstanceWithCachingTest.java | {
"start": 1478,
"end": 1797
} | class ____ {
static final AtomicBoolean DESTROYED = new AtomicBoolean(false);
String id;
@PostConstruct
void init() {
this.id = UUID.randomUUID().toString();
}
@PreDestroy
void destroy() {
DESTROYED.set(true);
}
}
}
| Washcloth |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/AbstractPreemptableResourceCalculator.java | {
"start": 3289,
"end": 18795
} | class ____ {
private Resource numerator;
private Resource denominator;
NormalizationTuple(Resource numer, Resource denom) {
this.numerator = numer;
this.denominator = denom;
}
long getNumeratorValue(int i) {
return numerator.getResourceInformation(i).getValue();
}
long getDenominatorValue(int i) {
String nUnits = numerator.getResourceInformation(i).getUnits();
ResourceInformation dResourceInformation = denominator
.getResourceInformation(i);
return UnitsConversionUtil.convert(
dResourceInformation.getUnits(), nUnits, dResourceInformation.getValue());
}
float getNormalizedValue(int i) {
long nValue = getNumeratorValue(i);
long dValue = getDenominatorValue(i);
return dValue == 0 ? 0.0f : (float) nValue / dValue;
}
}
/**
* PreemptableResourceCalculator constructor.
*
* @param preemptionContext context
* @param isReservedPreemptionCandidatesSelector
* this will be set by different implementation of candidate
* selectors, please refer to TempQueuePerPartition#offer for
* details.
* @param allowQueuesBalanceAfterAllQueuesSatisfied
* Should resources be preempted from an over-served queue when the
* requesting queues are all at or over their guarantees?
* An example is, there're 10 queues under root, guaranteed resource
* of them are all 10%.
* Assume there're two queues are using resources, queueA uses 10%
* queueB uses 90%. For all queues are guaranteed, but it's not fair
* for queueA.
* We wanna make this behavior can be configured. By default it is
* not allowed.
*
*/
public AbstractPreemptableResourceCalculator(
CapacitySchedulerPreemptionContext preemptionContext,
boolean isReservedPreemptionCandidatesSelector,
boolean allowQueuesBalanceAfterAllQueuesSatisfied) {
context = preemptionContext;
rc = preemptionContext.getResourceCalculator();
this.isReservedPreemptionCandidatesSelector =
isReservedPreemptionCandidatesSelector;
this.allowQueuesBalanceAfterAllQueuesSatisfied =
allowQueuesBalanceAfterAllQueuesSatisfied;
stepFactor = Resource.newInstance(0, 0);
for (ResourceInformation ri : stepFactor.getResources()) {
ri.setValue(1);
}
}
/**
* Given a set of queues compute the fix-point distribution of unassigned
* resources among them. As pending request of a queue are exhausted, the
* queue is removed from the set and remaining capacity redistributed among
* remaining queues. The distribution is weighted based on guaranteed
* capacity, unless asked to ignoreGuarantee, in which case resources are
* distributed uniformly.
*
* @param totGuarant
* total guaranteed resource
* @param qAlloc
* List of child queues
* @param unassigned
* Unassigned resource per queue
* @param ignoreGuarantee
* ignore guarantee per queue.
*/
protected void computeFixpointAllocation(Resource totGuarant,
Collection<TempQueuePerPartition> qAlloc, Resource unassigned,
boolean ignoreGuarantee) {
// Prior to assigning the unused resources, process each queue as follows:
// If current > guaranteed, idealAssigned = guaranteed + untouchable extra
// Else idealAssigned = current;
// Subtract idealAssigned resources from unassigned.
// If the queue has all of its needs met (that is, if
// idealAssigned >= current + pending), remove it from consideration.
// Sort queues from most under-guaranteed to most over-guaranteed.
TQComparator tqComparator = new TQComparator(rc, totGuarant);
PriorityQueue<TempQueuePerPartition> orderedByNeed = new PriorityQueue<>(10,
tqComparator);
for (Iterator<TempQueuePerPartition> i = qAlloc.iterator(); i.hasNext(); ) {
TempQueuePerPartition q = i.next();
Resource used = q.getUsed();
Resource initIdealAssigned;
if (Resources.greaterThan(rc, totGuarant, used, q.getGuaranteed())) {
initIdealAssigned = Resources.add(
Resources.componentwiseMin(q.getGuaranteed(), q.getUsed()),
q.untouchableExtra);
} else{
initIdealAssigned = Resources.clone(used);
}
// perform initial assignment
initIdealAssignment(totGuarant, q, initIdealAssigned);
Resources.subtractFrom(unassigned, q.idealAssigned);
// If idealAssigned < (allocated + used + pending), q needs more
// resources, so
// add it to the list of underserved queues, ordered by need.
Resource curPlusPend = Resources.add(q.getUsed(), q.pending);
if (Resources.lessThan(rc, totGuarant, q.idealAssigned, curPlusPend)) {
orderedByNeed.add(q);
}
}
// assign all cluster resources until no more demand, or no resources are
// left
while (!orderedByNeed.isEmpty() && Resources.greaterThan(rc, totGuarant,
unassigned, Resources.none())) {
// we compute normalizedGuarantees capacity based on currently active
// queues
resetCapacity(orderedByNeed, ignoreGuarantee);
// For each underserved queue (or set of queues if multiple are equally
// underserved), offer its share of the unassigned resources based on its
// normalized guarantee. After the offer, if the queue is not satisfied,
// place it back in the ordered list of queues, recalculating its place
// in the order of most under-guaranteed to most over-guaranteed. In this
// way, the most underserved queue(s) are always given resources first.
Collection<TempQueuePerPartition> underserved = getMostUnderservedQueues(
orderedByNeed, tqComparator);
// This value will be used in every round to calculate ideal allocation.
// So make a copy to avoid it changed during calculation.
Resource dupUnassignedForTheRound = Resources.clone(unassigned);
for (Iterator<TempQueuePerPartition> i = underserved.iterator(); i
.hasNext();) {
if (!rc.isAnyMajorResourceAboveZero(unassigned)) {
break;
}
TempQueuePerPartition sub = i.next();
// How much resource we offer to the queue (to increase its ideal_alloc
Resource wQavail = Resources.multiplyAndNormalizeUp(rc,
dupUnassignedForTheRound,
sub.normalizedGuarantee, this.stepFactor);
// Make sure it is not beyond unassigned
wQavail = Resources.componentwiseMin(wQavail, unassigned);
Resource wQidle = sub.offer(wQavail, rc, totGuarant,
isReservedPreemptionCandidatesSelector,
allowQueuesBalanceAfterAllQueuesSatisfied);
Resource wQdone = Resources.subtract(wQavail, wQidle);
if (Resources.greaterThan(rc, totGuarant, wQdone, Resources.none())) {
// The queue is still asking for more. Put it back in the priority
// queue, recalculating its order based on need.
orderedByNeed.add(sub);
}
Resources.subtractFrom(unassigned, wQdone);
// Make sure unassigned is always larger than 0
unassigned = Resources.componentwiseMax(unassigned, Resources.none());
}
}
// Sometimes its possible that, all queues are properly served. So intra
// queue preemption will not try for any preemption. How ever there are
// chances that within a queue, there are some imbalances. Hence make sure
// all queues are added to list.
while (!orderedByNeed.isEmpty()) {
TempQueuePerPartition q1 = orderedByNeed.remove();
context.addPartitionToUnderServedQueues(q1.queueName, q1.partition);
}
}
/**
* This method is visible to allow sub-classes to override the initialization
* behavior.
*
* @param totGuarant total resources (useful for {@code ResourceCalculator}
* operations)
* @param q the {@code TempQueuePerPartition} being initialized
* @param initIdealAssigned the proposed initialization value.
*/
protected void initIdealAssignment(Resource totGuarant,
TempQueuePerPartition q, Resource initIdealAssigned) {
q.idealAssigned = initIdealAssigned;
}
/**
* Computes a normalizedGuaranteed capacity based on active queues.
*
* @param queues
* the list of queues to consider
* @param ignoreGuar
* ignore guarantee.
*/
private void resetCapacity(Collection<TempQueuePerPartition> queues,
boolean ignoreGuar) {
Resource activeCap = Resource.newInstance(0, 0);
float activeTotalAbsCap = 0.0f;
int maxLength = ResourceUtils.getNumberOfCountableResourceTypes();
if (ignoreGuar) {
for (int i = 0; i < maxLength; i++) {
for (TempQueuePerPartition q : queues) {
computeNormGuarEvenly(q, queues.size(), i);
}
}
} else {
for (TempQueuePerPartition q : queues) {
Resources.addTo(activeCap, q.getGuaranteed());
activeTotalAbsCap += q.getAbsCapacity();
}
// loop through all resource types and normalize guaranteed capacity for all queues
for (int i = 0; i < maxLength; i++) {
boolean useAbsCapBasedNorm = false;
// if the sum of absolute capacity of all queues involved is 0,
// we should normalize evenly
boolean useEvenlyDistNorm = activeTotalAbsCap == 0;
// loop through all the queues once to determine the
// right normalization strategy for current processing resource type
for (TempQueuePerPartition q : queues) {
NormalizationTuple normTuple = new NormalizationTuple(
q.getGuaranteed(), activeCap);
long queueGuaranValue = normTuple.getNumeratorValue(i);
long totalActiveGuaranValue = normTuple.getDenominatorValue(i);
if (queueGuaranValue == 0 && q.getAbsCapacity() != 0 && totalActiveGuaranValue != 0) {
// when the rounded value of a resource type is 0 but its absolute capacity is not 0,
// we should consider taking the normalized guarantee based on absolute capacity
useAbsCapBasedNorm = true;
break;
}
if (totalActiveGuaranValue == 0) {
// If totalActiveGuaranValue from activeCap is zero, that means the guaranteed capacity
// of this resource dimension for all active queues is tiny (close to 0).
// For example, if a queue has 1% of minCapacity on a cluster with a totalVcores of 48,
// then the idealAssigned Vcores for this queue is (48 * 0.01)=0.48 which then
// get rounded/casted into 0 (double -> long)
// In this scenario where the denominator is 0, we can just spread resources across
// all tiny queues evenly since their absoluteCapacity are roughly the same
useEvenlyDistNorm = true;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Queue normalization strategy: " +
"absoluteCapacityBasedNormalization(" + useAbsCapBasedNorm +
"), evenlyDistributedNormalization(" + useEvenlyDistNorm +
"), defaultNormalization(" + !(useAbsCapBasedNorm || useEvenlyDistNorm) + ")");
}
// loop through all the queues again to apply normalization strategy
for (TempQueuePerPartition q : queues) {
if (useAbsCapBasedNorm) {
computeNormGuarFromAbsCapacity(q, activeTotalAbsCap, i);
} else if (useEvenlyDistNorm) {
computeNormGuarEvenly(q, queues.size(), i);
} else {
computeDefaultNormGuar(q, activeCap, i);
}
}
}
}
}
/**
* Computes the normalized guaranteed capacity based on the weight of a queue's abs capacity.
*
* Example:
* There are two active queues: queueA & queueB, and
* their configured absolute minimum capacity is 1% and 3% respectively.
*
* Then their normalized guaranteed capacity are:
* normalized_guar_queueA = 0.01 / (0.01 + 0.03) = 0.25
* normalized_guar_queueB = 0.03 / (0.01 + 0.03) = 0.75
*
* @param q
* the queue to consider
* @param activeTotalAbsCap
* the sum of absolute capacity of all active queues
* @param resourceTypeIdx
* index of the processing resource type
*/
private static void computeNormGuarFromAbsCapacity(TempQueuePerPartition q,
float activeTotalAbsCap,
int resourceTypeIdx) {
if (activeTotalAbsCap != 0) {
q.normalizedGuarantee[resourceTypeIdx] = q.getAbsCapacity() / activeTotalAbsCap;
}
}
/**
* Computes the normalized guaranteed capacity evenly based on num of active queues.
*
* @param q
* the queue to consider
* @param numOfActiveQueues
* number of active queues
* @param resourceTypeIdx
* index of the processing resource type
*/
private static void computeNormGuarEvenly(TempQueuePerPartition q,
int numOfActiveQueues,
int resourceTypeIdx) {
q.normalizedGuarantee[resourceTypeIdx] = 1.0f / numOfActiveQueues;
}
/**
* The default way to compute a queue's normalized guaranteed capacity.
*
* For each resource type, divide a queue's configured guaranteed amount (MBs/Vcores) by
* the total amount of guaranteed resource of all active queues
*
* @param q
* the queue to consider
* @param activeCap
* total guaranteed resources of all active queues
* @param resourceTypeIdx
* index of the processing resource type
*/
private static void computeDefaultNormGuar(TempQueuePerPartition q,
Resource activeCap,
int resourceTypeIdx) {
NormalizationTuple normTuple = new NormalizationTuple(q.getGuaranteed(), activeCap);
q.normalizedGuarantee[resourceTypeIdx] = normTuple.getNormalizedValue(resourceTypeIdx);
}
// Take the most underserved TempQueue (the one on the head). Collect and
// return the list of all queues that have the same idealAssigned
// percentage of guaranteed.
private Collection<TempQueuePerPartition> getMostUnderservedQueues(
PriorityQueue<TempQueuePerPartition> orderedByNeed,
TQComparator tqComparator) {
ArrayList<TempQueuePerPartition> underserved = new ArrayList<>();
while (!orderedByNeed.isEmpty()) {
TempQueuePerPartition q1 = orderedByNeed.remove();
underserved.add(q1);
// Add underserved queues in order for later uses
context.addPartitionToUnderServedQueues(q1.queueName, q1.partition);
TempQueuePerPartition q2 = orderedByNeed.peek();
// q1's pct of guaranteed won't be larger than q2's. If it's less, then
// return what has already been collected. Otherwise, q1's pct of
// guaranteed == that of q2, so add q2 to underserved list during the
// next pass.
if (q2 == null || tqComparator.compare(q1, q2) < 0) {
if (null != q2) {
context.addPartitionToUnderServedQueues(q2.queueName, q2.partition);
}
return underserved;
}
}
return underserved;
}
} | NormalizationTuple |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_22.java | {
"start": 931,
"end": 2012
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "select CONSTRAINT constraint from t where id = 1 order by constraint desc";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statemen = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
statemen.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(2, visitor.getColumns().size());
assertEquals(1, visitor.getConditions().size());
assertEquals(1, visitor.getOrderByColumns().size());
}
}
| MySqlSelectTest_22 |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configuration/AuthenticationPrincipalArgumentResolverTests.java | {
"start": 4036,
"end": 4150
} | class ____ {
public String extract(User u) {
return "extracted-" + u.getUsername();
}
}
}
| UsernameExtractor |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/file/FileAssert_hasFileName_Test.java | {
"start": 785,
"end": 1158
} | class ____ extends FileAssertBaseTest {
private final String expected = "expected.name";
@Override
protected FileAssert invoke_api_method() {
return assertions.hasFileName(expected);
}
@Override
protected void verify_internal_effects() {
verify(files).assertHasName(getInfo(assertions), getActual(assertions), expected);
}
}
| FileAssert_hasFileName_Test |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/fs/LocatedFileStatus.java | {
"start": 1118,
"end": 1434
} | class ____ communicates the block information (including locations) when that
* information is readily (or cheaply) available. That way users can avoid an additional call to
* {@link FileSystem#getFileBlockLocations(FileStatus, long, long)}, which is an additional RPC call
* for each file.
*/
@Public
public | eagerly |
java | apache__thrift | lib/java/src/main/java/org/apache/thrift/transport/TFileTransport.java | {
"start": 3680,
"end": 16783
} | enum ____ {
NOWAIT(0, 0),
WAIT_FOREVER(500, -1);
/** Time in milliseconds to sleep before next read If 0, no sleep */
public final int timeout_;
/** Number of retries before giving up if 0, no retries if -1, retry forever */
public final int retries_;
/**
* ctor for policy
*
* @param timeout sleep time for this particular policy
* @param retries number of retries
*/
TailPolicy(int timeout, int retries) {
timeout_ = timeout;
retries_ = retries;
}
}
/** Current tailing policy */
TailPolicy currentPolicy_ = TailPolicy.NOWAIT;
/** Underlying file being read */
protected TSeekableFile inputFile_ = null;
/** Underlying outputStream */
protected OutputStream outputStream_ = null;
/** Event currently read in */
Event currentEvent_ = null;
/** InputStream currently being used for reading */
InputStream inputStream_ = null;
/** current Chunk state */
ChunkState cs = null;
/** is read only? */
private boolean readOnly_ = false;
/**
* Get File Tailing Policy
*
* @return current read policy
*/
public TailPolicy getTailPolicy() {
return (currentPolicy_);
}
/**
* Set file Tailing Policy
*
* @param policy New policy to set
* @return Old policy
*/
public TailPolicy setTailPolicy(TailPolicy policy) {
TailPolicy old = currentPolicy_;
currentPolicy_ = policy;
return (old);
}
/**
* Initialize read input stream
*
* @return input stream to read from file
*/
private InputStream createInputStream() throws TTransportException {
InputStream is;
try {
if (inputStream_ != null) {
((TruncableBufferedInputStream) inputStream_).trunc();
is = inputStream_;
} else {
is = new TruncableBufferedInputStream(inputFile_.getInputStream());
}
} catch (IOException iox) {
throw new TTransportException(iox.getMessage(), iox);
}
return (is);
}
/**
* Read (potentially tailing) an input stream
*
* @param is InputStream to read from
* @param buf Buffer to read into
* @param off Offset in buffer to read into
* @param len Number of bytes to read
* @param tp policy to use if we hit EOF
* @return number of bytes read
*/
private int tailRead(InputStream is, byte[] buf, int off, int len, TailPolicy tp)
throws TTransportException {
int orig_len = len;
try {
int retries = 0;
while (len > 0) {
int cnt = is.read(buf, off, len);
if (cnt > 0) {
off += cnt;
len -= cnt;
retries = 0;
cs.skip(cnt); // remember that we read so many bytes
} else if (cnt == -1) {
// EOF
retries++;
if ((tp.retries_ != -1) && tp.retries_ < retries) return (orig_len - len);
if (tp.timeout_ > 0) {
try {
Thread.sleep(tp.timeout_);
} catch (InterruptedException e) {
}
}
} else {
// either non-zero or -1 is what the contract says!
throw new TTransportException("Unexpected return from InputStream.read = " + cnt);
}
}
} catch (IOException iox) {
throw new TTransportException(iox.getMessage(), iox);
}
return (orig_len - len);
}
/**
* Event is corrupted. Do recovery
*
* @return true if recovery could be performed and we can read more data false is returned only
* when nothing more can be read
*/
private boolean performRecovery() throws TTransportException {
int numChunks = getNumChunks();
int curChunk = cs.getChunkNum();
if (curChunk >= (numChunks - 1)) {
return false;
}
seekToChunk(curChunk + 1);
return true;
}
/**
* Read event from underlying file
*
* @return true if event could be read, false otherwise (on EOF)
*/
private boolean readEvent() throws TTransportException {
byte[] ebytes = new byte[4];
int esize;
int nread;
int nrequested;
retry:
do {
// corner case. read to end of chunk
nrequested = cs.getRemaining();
if (nrequested < 4) {
nread = tailRead(inputStream_, ebytes, 0, nrequested, currentPolicy_);
if (nread != nrequested) {
return (false);
}
}
// assuming serialized on little endian machine
nread = tailRead(inputStream_, ebytes, 0, 4, currentPolicy_);
if (nread != 4) {
return (false);
}
esize = 0;
for (int i = 3; i >= 0; i--) {
int val = (0x000000ff & (int) ebytes[i]);
esize |= (val << (i * 8));
}
// check if event is corrupted and do recovery as required
if (esize > cs.getRemaining()) {
throw new TTransportException("FileTransport error: bad event size");
/*
if(performRecovery()) {
esize=0;
} else {
return false;
}
*/
}
} while (esize == 0);
// reset existing event or get a larger one
if (currentEvent_.getSize() < esize) currentEvent_ = new Event(new byte[esize]);
// populate the event
byte[] buf = currentEvent_.getBuf();
nread = tailRead(inputStream_, buf, 0, esize, currentPolicy_);
if (nread != esize) {
return (false);
}
currentEvent_.setAvailable(esize);
return (true);
}
/**
* open if both input/output open unless readonly
*
* @return true
*/
public boolean isOpen() {
return ((inputStream_ != null) && (readOnly_ || (outputStream_ != null)));
}
/**
* Diverging from the cpp model and sticking to the TSocket model Files are not opened in ctor -
* but in explicit open call
*/
public void open() throws TTransportException {
if (isOpen()) throw new TTransportException(TTransportException.ALREADY_OPEN);
try {
inputStream_ = createInputStream();
cs = new ChunkState();
currentEvent_ = new Event(new byte[256]);
if (!readOnly_) outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream());
} catch (IOException iox) {
throw new TTransportException(TTransportException.NOT_OPEN, iox);
}
}
/** Closes the transport. */
public void close() {
if (inputFile_ != null) {
try {
inputFile_.close();
} catch (IOException iox) {
LOGGER.warn("WARNING: Error closing input file: " + iox.getMessage());
}
inputFile_ = null;
}
if (outputStream_ != null) {
try {
outputStream_.close();
} catch (IOException iox) {
LOGGER.warn("WARNING: Error closing output stream: " + iox.getMessage());
}
outputStream_ = null;
}
}
/**
* File Transport ctor
*
* @param path File path to read and write from
* @param readOnly Whether this is a read-only transport
* @throws IOException if there is an error accessing the file.
*/
public TFileTransport(final String path, boolean readOnly) throws IOException {
inputFile_ = new TStandardFile(path);
readOnly_ = readOnly;
}
/**
* File Transport ctor
*
* @param inputFile open TSeekableFile to read/write from
* @param readOnly Whether this is a read-only transport
*/
public TFileTransport(TSeekableFile inputFile, boolean readOnly) {
inputFile_ = inputFile;
readOnly_ = readOnly;
}
/**
* Cloned from TTransport.java:readAll(). Only difference is throwing an EOF exception where one
* is detected.
*/
public int readAll(byte[] buf, int off, int len) throws TTransportException {
int got = 0;
int ret = 0;
while (got < len) {
ret = read(buf, off + got, len - got);
if (ret < 0) {
throw new TTransportException("Error in reading from file");
}
if (ret == 0) {
throw new TTransportException(TTransportException.END_OF_FILE, "End of File reached");
}
got += ret;
}
return got;
}
/**
* Reads up to len bytes into buffer buf, starting at offset off.
*
* @param buf Array to read into
* @param off Index to start reading at
* @param len Maximum number of bytes to read
* @return The number of bytes actually read
* @throws TTransportException if there was an error reading data
*/
public int read(byte[] buf, int off, int len) throws TTransportException {
if (!isOpen())
throw new TTransportException(TTransportException.NOT_OPEN, "Must open before reading");
if (currentEvent_.getRemaining() == 0 && !readEvent()) {
return 0;
}
return currentEvent_.emit(buf, off, len);
}
public int getNumChunks() throws TTransportException {
if (!isOpen())
throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getNumChunks");
try {
long len = inputFile_.length();
if (len == 0) return 0;
else return (((int) (len / cs.getChunkSize())) + 1);
} catch (IOException iox) {
throw new TTransportException(iox.getMessage(), iox);
}
}
public int getCurChunk() throws TTransportException {
if (!isOpen())
throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getCurChunk");
return (cs.getChunkNum());
}
public void seekToChunk(int chunk) throws TTransportException {
if (!isOpen())
throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking");
int numChunks = getNumChunks();
// file is empty, seeking to chunk is pointless
if (numChunks == 0) {
return;
}
// negative indicates reverse seek (from the end)
if (chunk < 0) {
chunk += numChunks;
}
// too large a value for reverse seek, just seek to beginning
if (chunk < 0) {
chunk = 0;
}
long eofOffset = 0;
boolean seekToEnd = (chunk >= numChunks);
if (seekToEnd) {
chunk = chunk - 1;
try {
eofOffset = inputFile_.length();
} catch (IOException iox) {
throw new TTransportException(iox.getMessage(), iox);
}
}
if (chunk * cs.getChunkSize() != cs.getOffset()) {
try {
inputFile_.seek((long) chunk * cs.getChunkSize());
} catch (IOException iox) {
throw new TTransportException("Seek to chunk " + chunk + " " + iox.getMessage(), iox);
}
cs.seek((long) chunk * cs.getChunkSize());
currentEvent_.setAvailable(0);
inputStream_ = createInputStream();
}
if (seekToEnd) {
// waiting forever here - otherwise we can hit EOF and end up
// having consumed partial data from the data stream.
TailPolicy old = setTailPolicy(TailPolicy.WAIT_FOREVER);
while (cs.getOffset() < eofOffset) {
readEvent();
}
currentEvent_.setAvailable(0);
setTailPolicy(old);
}
}
public void seekToEnd() throws TTransportException {
if (!isOpen())
throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking");
seekToChunk(getNumChunks());
}
/**
* Writes up to len bytes from the buffer.
*
* @param buf The output data buffer
* @param off The offset to start writing from
* @param len The number of bytes to write
* @throws TTransportException if there was an error writing data
*/
public void write(byte[] buf, int off, int len) throws TTransportException {
throw new TTransportException("Not Supported");
}
/**
* Flush any pending data out of a transport buffer.
*
* @throws TTransportException if there was an error writing out data.
*/
public void flush() throws TTransportException {
throw new TTransportException("Not Supported");
}
@Override
public TConfiguration getConfiguration() {
return null;
}
@Override
public void updateKnownMessageSize(long size) throws TTransportException {}
@Override
public void checkReadBytesAvailable(long numBytes) throws TTransportException {}
/** test program */
public static void main(String[] args) throws Exception {
int num_chunks = 10;
if ((args.length < 1)
|| args[0].equals("--help")
|| args[0].equals("-h")
|| args[0].equals("-?")) {
printUsage();
}
if (args.length > 1) {
try {
num_chunks = Integer.parseInt(args[1]);
} catch (Exception e) {
LOGGER.error("Cannot parse " + args[1]);
printUsage();
}
}
TFileTransport t = new TFileTransport(args[0], true);
t.open();
LOGGER.info("NumChunks=" + t.getNumChunks());
Random r = new Random();
for (int j = 0; j < num_chunks; j++) {
byte[] buf = new byte[4096];
int cnum = r.nextInt(t.getNumChunks() - 1);
LOGGER.info("Reading chunk " + cnum);
t.seekToChunk(cnum);
for (int i = 0; i < 4096; i++) {
t.read(buf, 0, 4096);
}
}
}
private static void printUsage() {
LOGGER.error("Usage: TFileTransport <filename> [num_chunks]");
LOGGER.error(" (Opens and reads num_chunks chunks from file randomly)");
System.exit(1);
}
}
| TailPolicy |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/rest/action/RestWatchServiceAction.java | {
"start": 1445,
"end": 2099
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, "/_watcher/_stop"));
}
@Override
public String getName() {
return "watcher_stop_service";
}
@Override
public RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) {
final var request = new WatcherServiceRequest(RestUtils.getMasterNodeTimeout(restRequest)).stop();
return channel -> client.execute(WatcherServiceAction.INSTANCE, request, new RestToXContentListener<>(channel));
}
}
}
| StopRestHandler |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/typeutils/WindowKeySerializerTest.java | {
"start": 1253,
"end": 2340
} | class ____ extends SerializerTestBase<WindowKey> {
@Override
protected TypeSerializer<WindowKey> createSerializer() {
return new WindowKeySerializer((AbstractRowDataSerializer) new BinaryRowDataSerializer(2));
}
@Override
protected int getLength() {
return -1;
}
@Override
protected Class<WindowKey> getTypeClass() {
return WindowKey.class;
}
@Override
protected WindowKey[] getTestData() {
return new WindowKey[] {
new WindowKey(1000L, createRow("11", 1)),
new WindowKey(-2000L, createRow("12", 2)),
new WindowKey(Long.MAX_VALUE, createRow("132", 3)),
new WindowKey(Long.MIN_VALUE, createRow("55", 4)),
};
}
private static BinaryRowData createRow(String f0, int f1) {
BinaryRowData row = new BinaryRowData(2);
BinaryRowWriter writer = new BinaryRowWriter(row);
writer.writeString(0, StringData.fromString(f0));
writer.writeInt(1, f1);
writer.complete();
return row;
}
}
| WindowKeySerializerTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_63_alias.java | {
"start": 1086,
"end": 6729
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = " SELECT totalNumber, concat(\"\",? , round(memberNumber, 0) , \"\") AS totalDisplay FROM (\n" +
"SELECT count(1) AS totalNumber, sum(memberNumber) AS memberNumber FROM(\n" +
"SELECT mmd.office_id AS departID,st.no AS staffNO,st.name AS staffName,count(mmd.id) memberNumber FROM ms_member_def mmd\n" +
"LEFT JOIN sys_user st ON mmd.salesman_id=st.id AND st.del_flag='0'\n" +
"WHERE mmd.create_date BETWEEN (?) AND DATE_ADD((?),INTERVAL '23:59:59' HOUR_SECOND) AND mmd.del_flag='0'\n" +
"AND ('' IN (?) OR st.no IN (?))\n" +
"AND ('' IN (?) OR mmd.office_id IN (?))\n" +
"GROUP BY mmd.office_id,st.no\n" +
") gg\n" +
")temp";
System.out.println(sql);
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcConstants.MYSQL, SQLParserFeature.OptimizedForParameterized);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL);
stmt.accept(visitor);
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("SELECT totalNumber\n" +
"\t, concat('', ?, round(memberNumber, 0), '') AS totalDisplay\n" +
"FROM (\n" +
"\tSELECT count(1) AS totalNumber, sum(memberNumber) AS memberNumber\n" +
"\tFROM (\n" +
"\t\tSELECT mmd.office_id AS departID, st.no AS staffNO, st.name AS staffName, count(mmd.id) AS memberNumber\n" +
"\t\tFROM ms_member_def mmd\n" +
"\t\t\tLEFT JOIN sys_user st\n" +
"\t\t\tON mmd.salesman_id = st.id\n" +
"\t\t\t\tAND st.del_flag = '0'\n" +
"\t\tWHERE mmd.create_date BETWEEN ? AND DATE_ADD(?, INTERVAL '23:59:59' HOUR_SECOND)\n" +
"\t\t\tAND mmd.del_flag = '0'\n" +
"\t\t\tAND ('' IN (?)\n" +
"\t\t\t\tOR st.no IN (?))\n" +
"\t\t\tAND ('' IN (?)\n" +
"\t\t\t\tOR mmd.office_id IN (?))\n" +
"\t\tGROUP BY mmd.office_id, st.no\n" +
"\t) gg\n" +
") temp", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("select totalNumber\n" +
"\t, concat('', ?, round(memberNumber, 0), '') as totalDisplay\n" +
"from (\n" +
"\tselect count(1) as totalNumber, sum(memberNumber) as memberNumber\n" +
"\tfrom (\n" +
"\t\tselect mmd.office_id as departID, st.no as staffNO, st.name as staffName, count(mmd.id) as memberNumber\n" +
"\t\tfrom ms_member_def mmd\n" +
"\t\t\tleft join sys_user st\n" +
"\t\t\ton mmd.salesman_id = st.id\n" +
"\t\t\t\tand st.del_flag = '0'\n" +
"\t\twhere mmd.create_date between ? and DATE_ADD(?, interval '23:59:59' hour_second)\n" +
"\t\t\tand mmd.del_flag = '0'\n" +
"\t\t\tand ('' in (?)\n" +
"\t\t\t\tor st.no in (?))\n" +
"\t\t\tand ('' in (?)\n" +
"\t\t\t\tor mmd.office_id in (?))\n" +
"\t\tgroup by mmd.office_id, st.no\n" +
"\t) gg\n" +
") temp", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, new SQLUtils.FormatOption(true, true, true));
assertEquals("SELECT totalNumber\n" +
"\t, concat(?, ?, round(memberNumber, ?), ?) AS totalDisplay\n" +
"FROM (\n" +
"\tSELECT count(1) AS totalNumber, sum(memberNumber) AS memberNumber\n" +
"\tFROM (\n" +
"\t\tSELECT mmd.office_id AS departID, st.no AS staffNO, st.name AS staffName, count(mmd.id) AS memberNumber\n" +
"\t\tFROM ms_member_def mmd\n" +
"\t\t\tLEFT JOIN sys_user st\n" +
"\t\t\tON mmd.salesman_id = st.id\n" +
"\t\t\t\tAND st.del_flag = ?\n" +
"\t\tWHERE mmd.create_date BETWEEN ? AND DATE_ADD(?, INTERVAL ? HOUR_SECOND)\n" +
"\t\t\tAND mmd.del_flag = ?\n" +
"\t\t\tAND (? IN (?)\n" +
"\t\t\t\tOR st.no IN (?))\n" +
"\t\t\tAND (? IN (?)\n" +
"\t\t\t\tOR mmd.office_id IN (?))\n" +
"\t\tGROUP BY mmd.office_id, st.no\n" +
"\t) gg\n" +
") temp", //
output);
}
}
}
| MySqlSelectTest_63_alias |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/protocol/CommandArgs.java | {
"start": 12450,
"end": 12842
} | class ____ {
static final ProtocolKeywordArgument cache[];
static {
CommandKeyword[] values = CommandKeyword.values();
cache = new ProtocolKeywordArgument[values.length];
for (int i = 0; i < cache.length; i++) {
cache[i] = new ProtocolKeywordArgument(values[i]);
}
}
}
static | CommandKeywordCache |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/EntityUseSingleTableOptimizationTest.java | {
"start": 1304,
"end": 11107
} | class ____ {
@Test
public void testEqTypeRestriction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where type(t) = House", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE='House'",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testEqSuperTypeRestriction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "select 1 from Thing t where type(t) = Building", Integer.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"1 " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE='Building'",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testEqTypeRestrictionSelectId(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "select t.id from Thing t where type(t) = House", Long.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE='House'",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testNotEqTypeRestriction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where type(t) <> House", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE<>'House'",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testInTypeRestriction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where type(t) in (House, Car)", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE in ('House','Car')",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testInTypeCommonSuperTypeRestriction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where type(t) in (House, Skyscraper)", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE in ('House','Skyscraper')",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testNotInTypeRestriction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where type(t) not in (House, Car)", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE not in ('House','Car')",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testTreatPath(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where treat(t as House).familyName is not null", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.familyName is not null",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testTreatPathSharedColumn(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where treat(t as Skyscraper).doors is not null", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"case when t1_0.DTYPE='Skyscraper' then t1_0.doors end is not null",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testTreatPathInDisjunction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where treat(t as House).familyName is not null or t.id > 0", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.familyName is not null or t1_0.id>0",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testTypeRestrictionInDisjunction(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "from Thing t where type(t) = House or t.id > 0", Thing.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"t1_0.id," +
"t1_0.DTYPE," +
"t1_0.seats," +
"t1_0.nr," +
"t1_0.doors," +
"t1_0.familyName," +
"t1_0.architectName," +
"t1_0.name " +
"from Thing t1_0 " +
"where " +
"t1_0.DTYPE='House' or t1_0.id>0",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Test
public void testQueryChildUseParent(SessionFactoryScope scope) {
SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector();
scope.inTransaction(
entityManager -> {
sqlStatementInterceptor.clear();
entityManager.createSelectionQuery( "select t.nr from Skyscraper t", Integer.class )
.getResultList();
sqlStatementInterceptor.assertExecutedCount( 1 );
assertEquals(
"select " +
"s1_0.nr " +
"from Thing s1_0 " +
"where s1_0.DTYPE='Skyscraper'",
sqlStatementInterceptor.getSqlQueries().get( 0 )
);
}
);
}
@Entity(name = "Thing")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public static abstract | EntityUseSingleTableOptimizationTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/delegate/MutationDelegateJoinedInheritanceTest.java | {
"start": 7948,
"end": 8585
} | class ____ {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long id;
@Generated( event = EventType.INSERT )
@ColumnDefault( "'default_name'" )
private String name;
@UpdateTimestamp( source = SourceType.DB )
private Date updateDate;
@SuppressWarnings( "FieldCanBeLocal" )
private String data;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Date getUpdateDate() {
return updateDate;
}
public void setData(String data) {
this.data = data;
}
}
@Entity( name = "ChildEntity" )
@SuppressWarnings( "unused" )
public static | BaseEntity |
java | apache__camel | components/camel-reactor/src/main/java/org/apache/camel/component/reactor/engine/ReactorCamelProcessor.java | {
"start": 1733,
"end": 5610
} | class ____ implements Closeable {
private final String name;
private final EmitterProcessor<Exchange> publisher;
private final AtomicReference<FluxSink<Exchange>> camelSink;
private final ReactorStreamsService service;
private final Lock lock = new ReentrantLock();
private ReactiveStreamsProducer camelProducer;
ReactorCamelProcessor(ReactorStreamsService service, String name) {
this.service = service;
this.name = name;
this.camelProducer = null;
this.camelSink = new AtomicReference<>();
// TODO: The perfect emitter processor would have no buffer (0 sized)
// The chain caches one more item than expected.
// This implementation has (almost) full control over backpressure, but it's too chatty.
// There's a ticket to improve chattiness of the reactive-streams internal impl.
this.publisher = EmitterProcessor.create(1, false);
}
@Override
public void close() throws IOException {
}
Publisher<Exchange> getPublisher() {
return publisher;
}
void attach(ReactiveStreamsProducer producer) {
lock.lock();
try {
Objects.requireNonNull(producer, "producer cannot be null, use the detach method");
if (this.camelProducer != null) {
throw new IllegalStateException("A producer is already attached to the stream '" + name + "'");
}
if (this.camelProducer != producer) { // this condition is always true
detach();
ReactiveStreamsBackpressureStrategy strategy = producer.getEndpoint().getBackpressureStrategy();
Flux<Exchange> flux = Flux.create(camelSink::set, FluxSink.OverflowStrategy.IGNORE);
if (ObjectHelper.equal(strategy, ReactiveStreamsBackpressureStrategy.OLDEST)) {
// signal item emitted for non-dropped items only
flux = flux.onBackpressureDrop(this::onBackPressure).handle(this::onItemEmitted);
} else if (ObjectHelper.equal(strategy, ReactiveStreamsBackpressureStrategy.LATEST)) {
// Since there is no callback for dropped elements on backpressure "latest", item emission is signaled before dropping
// No exception is reported back to the exchanges
flux = flux.handle(this::onItemEmitted).onBackpressureLatest();
} else {
// Default strategy is BUFFER
flux = flux.onBackpressureBuffer(Queues.SMALL_BUFFER_SIZE, this::onBackPressure)
.handle(this::onItemEmitted);
}
flux.subscribe(this.publisher);
camelProducer = producer;
}
} finally {
lock.unlock();
}
}
void detach() {
lock.lock();
try {
this.camelProducer = null;
this.camelSink.set(null);
} finally {
lock.unlock();
}
}
void send(Exchange exchange) {
if (service.isRunAllowed()) {
FluxSink<Exchange> sink = ObjectHelper.notNull(camelSink.get(), "FluxSink");
sink.next(exchange);
}
}
// **************************************
// Helpers
// **************************************
private void onItemEmitted(Exchange exchange, SynchronousSink<Exchange> sink) {
if (service.isRunAllowed()) {
sink.next(exchange);
ReactiveStreamsHelper.invokeDispatchCallback(exchange);
}
}
private void onBackPressure(Exchange exchange) {
ReactiveStreamsHelper.invokeDispatchCallback(
exchange,
new ReactiveStreamsDiscardedException("Discarded by back pressure strategy", exchange, name));
}
}
| ReactorCamelProcessor |
java | google__dagger | dagger-producers/main/java/dagger/producers/monitoring/internal/Monitors.java | {
"start": 3807,
"end": 4695
} | class ____ extends ProductionComponentMonitor.Factory {
private final ProductionComponentMonitor.Factory delegate;
Factory(ProductionComponentMonitor.Factory delegate) {
this.delegate = delegate;
}
@Override
public ProductionComponentMonitor create(Object component) {
try {
ProductionComponentMonitor monitor = delegate.create(component);
return monitor == null
? ProductionComponentMonitor.noOp()
: new NonThrowingProductionComponentMonitor(monitor);
} catch (RuntimeException e) {
logCreateException(e, delegate, component);
return ProductionComponentMonitor.noOp();
}
}
}
}
/**
* A producer monitor that delegates to a single monitor, and catches and logs all exceptions
* that the delegate throws.
*/
private static final | Factory |
java | spring-projects__spring-boot | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/launch/PropertiesLauncher.java | {
"start": 3061,
"end": 11477
} | class ____ extends Launcher {
/**
* Properties key for main class. As a manifest entry can also be specified as
* {@code Start-Class}.
*/
public static final String MAIN = "loader.main";
/**
* Properties key for classpath entries (directories possibly containing jars or
* jars). Multiple entries can be specified using a comma-separated list. {@code
* BOOT-INF/classes,BOOT-INF/lib} in the application archive are always used.
*/
public static final String PATH = "loader.path";
/**
* Properties key for home directory. This is the location of external configuration
* if not on classpath, and also the base path for any relative paths in the
* {@link #PATH loader path}. Defaults to current working directory (
* <code>${user.dir}</code>).
*/
public static final String HOME = "loader.home";
/**
* Properties key for default command line arguments. These arguments (if present) are
* prepended to the main method arguments before launching.
*/
public static final String ARGS = "loader.args";
/**
* Properties key for name of external configuration file (excluding suffix). Defaults
* to "application". Ignored if {@link #CONFIG_LOCATION loader config location} is
* provided instead.
*/
public static final String CONFIG_NAME = "loader.config.name";
/**
* Properties key for config file location (including optional classpath:, file: or
* URL prefix).
*/
public static final String CONFIG_LOCATION = "loader.config.location";
/**
* Properties key for boolean flag (default false) which, if set, will cause the
* external configuration properties to be copied to System properties (assuming that
* is allowed by Java security).
*/
public static final String SET_SYSTEM_PROPERTIES = "loader.system";
private static final URL[] NO_URLS = new URL[0];
private static final Pattern WORD_SEPARATOR = Pattern.compile("\\W+");
private static final String NESTED_ARCHIVE_SEPARATOR = "!" + File.separator;
private static final String JAR_FILE_PREFIX = "jar:file:";
private static final DebugLogger debug = DebugLogger.get(PropertiesLauncher.class);
private final Archive archive;
private final File homeDirectory;
private final List<String> paths;
private final Properties properties = new Properties();
public PropertiesLauncher() throws Exception {
this(Archive.create(Launcher.class));
}
PropertiesLauncher(Archive archive) throws Exception {
this.archive = archive;
this.homeDirectory = getHomeDirectory();
initializeProperties();
this.paths = getPaths();
this.classPathIndex = getClassPathIndex(this.archive);
}
protected File getHomeDirectory() throws Exception {
return new File(getPropertyWithDefault(HOME, "${user.dir}"));
}
private void initializeProperties() throws Exception {
List<String> configs = new ArrayList<>();
if (getProperty(CONFIG_LOCATION) != null) {
configs.add(getProperty(CONFIG_LOCATION));
}
else {
String[] names = getPropertyWithDefault(CONFIG_NAME, "loader").split(",");
for (String name : names) {
String propertiesFile = name + ".properties";
configs.add("file:" + this.homeDirectory + "/" + propertiesFile);
configs.add("classpath:" + propertiesFile);
configs.add("classpath:BOOT-INF/classes/" + propertiesFile);
}
}
for (String config : configs) {
try (InputStream resource = getResource(config)) {
if (resource == null) {
debug.log("Not found: %s", config);
continue;
}
debug.log("Found: %s", config);
loadResource(resource);
return; // Load the first one we find
}
}
}
private InputStream getResource(String config) throws Exception {
if (config.startsWith("classpath:")) {
return getClasspathResource(config.substring("classpath:".length()));
}
config = handleUrl(config);
if (isUrl(config)) {
return getURLResource(config);
}
return getFileResource(config);
}
private InputStream getClasspathResource(String config) {
config = stripLeadingSlashes(config);
config = "/" + config;
debug.log("Trying classpath: %s", config);
return getClass().getResourceAsStream(config);
}
private String handleUrl(String path) {
if (path.startsWith("jar:file:") || path.startsWith("file:")) {
path = URLDecoder.decode(path, StandardCharsets.UTF_8);
if (path.startsWith("file:")) {
path = path.substring("file:".length());
if (path.startsWith("//")) {
path = path.substring(2);
}
}
}
return path;
}
private boolean isUrl(String config) {
return config.contains("://");
}
private InputStream getURLResource(String config) throws Exception {
URL url = new URL(config);
if (exists(url)) {
URLConnection connection = url.openConnection();
try {
return connection.getInputStream();
}
catch (IOException ex) {
disconnect(connection);
throw ex;
}
}
return null;
}
private boolean exists(URL url) throws IOException {
URLConnection connection = url.openConnection();
try {
connection.setUseCaches(connection.getClass().getSimpleName().startsWith("JNLP"));
if (connection instanceof HttpURLConnection httpConnection) {
httpConnection.setRequestMethod("HEAD");
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return true;
}
if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
return (connection.getContentLength() >= 0);
}
finally {
disconnect(connection);
}
}
private void disconnect(URLConnection connection) {
if (connection instanceof HttpURLConnection httpConnection) {
httpConnection.disconnect();
}
}
private InputStream getFileResource(String config) throws Exception {
File file = new File(config);
debug.log("Trying file: %s", config);
return (!file.canRead()) ? null : new FileInputStream(file);
}
private void loadResource(InputStream resource) throws Exception {
this.properties.load(resource);
resolvePropertyPlaceholders();
if ("true".equalsIgnoreCase(getProperty(SET_SYSTEM_PROPERTIES))) {
addToSystemProperties();
}
}
private void resolvePropertyPlaceholders() {
for (String name : this.properties.stringPropertyNames()) {
String value = this.properties.getProperty(name);
String resolved = SystemPropertyUtils.resolvePlaceholders(this.properties, value);
if (resolved != null) {
this.properties.put(name, resolved);
}
}
}
private void addToSystemProperties() {
debug.log("Adding resolved properties to System properties");
for (String name : this.properties.stringPropertyNames()) {
String value = this.properties.getProperty(name);
System.setProperty(name, value);
}
}
private List<String> getPaths() throws Exception {
String path = getProperty(PATH);
List<String> paths = (path != null) ? parsePathsProperty(path) : Collections.emptyList();
debug.log("Nested archive paths: %s", this.paths);
return paths;
}
private List<String> parsePathsProperty(String commaSeparatedPaths) {
List<String> paths = new ArrayList<>();
for (String path : commaSeparatedPaths.split(",")) {
path = cleanupPath(path);
// "" means the user wants root of archive but not current directory
path = (path.isEmpty()) ? "/" : path;
paths.add(path);
}
if (paths.isEmpty()) {
paths.add("lib");
}
return paths;
}
private String cleanupPath(String path) {
path = path.trim();
// No need for current dir path
if (path.startsWith("./")) {
path = path.substring(2);
}
if (isArchive(path)) {
return path;
}
if (path.endsWith("/*")) {
return path.substring(0, path.length() - 1);
}
// It's a directory
return (!path.endsWith("/") && !path.equals(".")) ? path + "/" : path;
}
@Override
protected ClassLoader createClassLoader(Collection<URL> urls) throws Exception {
String loaderClassName = getProperty("loader.classLoader");
if (this.classPathIndex != null) {
urls = new ArrayList<>(urls);
urls.addAll(this.classPathIndex.getUrls());
}
if (loaderClassName == null) {
return super.createClassLoader(urls);
}
ClassLoader parent = getClass().getClassLoader();
ClassLoader classLoader = new LaunchedClassLoader(false, urls.toArray(new URL[0]), parent);
debug.log("Classpath for custom loader: %s", urls);
classLoader = wrapWithCustomClassLoader(classLoader, loaderClassName);
debug.log("Using custom | PropertiesLauncher |
java | quarkusio__quarkus | extensions/avro/runtime/src/main/java/io/quarkus/avro/runtime/graal/AvroSubstitutions.java | {
"start": 2371,
"end": 3286
} | class ____ {
@Substitute
public static <V, R> Function<V, R> getConstructorAsFunction(Class<V> parameterClass, Class<R> clazz) {
// Cannot use the method handle approach as it uses ProtectionDomain which got removed.
try {
Constructor<R> constructor = clazz.getConstructor(parameterClass);
return new Function<V, R>() {
@Override
public R apply(V v) {
try {
return constructor.newInstance(v);
} catch (Exception e) {
throw new IllegalStateException("Unable to create new instance for " + clazz, e);
}
}
};
} catch (Throwable t) {
// if something goes wrong, do not provide a Function instance
return null;
}
}
}
| Target_org_apache_avro_reflect_ReflectionUtil |
java | spring-projects__spring-boot | module/spring-boot-webflux/src/test/java/org/springframework/boot/webflux/autoconfigure/WebFluxAutoConfigurationTests.java | {
"start": 47546,
"end": 47806
} | class ____ implements WebFluxConfigurer {
private final Validator validator = mock(Validator.class);
@Override
public Validator getValidator() {
return this.validator;
}
}
@Configuration(proxyBeanMethods = false)
static | ValidatorWebFluxConfigurer |
java | google__dagger | java/dagger/hilt/android/plugin/main/src/test/data/spi-plugin/src/main/java/spi/TestPlugin.java | {
"start": 913,
"end": 1360
} | class ____ implements BindingGraphPlugin {
@Override
public void visitGraph(BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) {
ComponentNode componentNode = bindingGraph.rootComponentNode();
if (componentNode.isRealComponent()) {
diagnosticReporter.reportComponent(
Diagnostic.Kind.ERROR,
componentNode,
"Found component: " + componentNode.componentPath()
);
}
}
} | TestPlugin |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/testdata/input/BinaryTemplateExample.java | {
"start": 786,
"end": 1298
} | class ____ {
public void example(int x, int y) {
// positive examples
System.out.println((0xFF + 5) / 2);
System.out.println((x + y) / 2 + 20);
System.err.println((y + new Random().nextInt()) / 2);
// negative examples
System.out.println((x + y /* signed division */) / 2 + 20);
System.out.println(x + y / 2);
System.out.println((x - y) / 2);
System.out.println((x * y) / 2);
System.out.println((x + y) / 3);
System.out.println((x + 5L) / 2);
}
}
| BinaryTemplateExample |
java | apache__camel | components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/producer/KubernetesCronJobProducerTest.java | {
"start": 2283,
"end": 11232
} | class ____ extends KubernetesTestSupport {
KubernetesMockServer server;
NamespacedKubernetesClient client;
@BindToRegistry("kubernetesClient")
public KubernetesClient getClient() {
return client;
}
@Test
void listTest() {
server.expect().withPath("/apis/batch/v1/cronjobs")
.andReturn(200, new CronJobListBuilder().addNewItem().and().addNewItem().and().addNewItem().and().build())
.once();
server.expect().withPath("/apis/batch/v1/namespaces/test/cronjobs")
.andReturn(200, new CronJobListBuilder().addNewItem().and().addNewItem().and().build())
.always();
List<?> result = template.requestBody("direct:list", "", List.class);
assertEquals(3, result.size());
Exchange ex = template.request("direct:list",
exchange -> exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test"));
assertEquals(2, ex.getMessage().getBody(List.class).size());
}
@Test
void listByLabelsTest() throws Exception {
Map<String, String> labels = Map.of(
"key1", "value1",
"key2", "value2");
String urlEncodedLabels = toUrlEncoded(labels.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(",")));
server.expect()
.withPath("/apis/batch/v1/cronjobs?labelSelector=" + urlEncodedLabels)
.andReturn(200, new CronJobListBuilder().addNewItem().and().addNewItem().and().addNewItem().and().build())
.always();
server.expect()
.withPath("/apis/batch/v1/namespaces/test/cronjobs?labelSelector=" + urlEncodedLabels)
.andReturn(200, new CronJobListBuilder().addNewItem().and().addNewItem().and().build())
.always();
Exchange ex = template.request("direct:listByLabels",
exchange -> exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_LABELS, labels));
List<?> result = ex.getMessage().getBody(List.class);
assertEquals(3, result.size());
ex = template.request("direct:listByLabels", exchange -> {
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_LABELS, labels);
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test");
});
assertEquals(2, ex.getMessage().getBody(List.class).size());
}
@Test
void getJobTest() {
CronJob sc1 = new CronJobBuilder().withNewMetadata().withName("sc1").withNamespace("test").and().build();
server.expect().withPath("/apis/batch/v1/namespaces/test/cronjobs/sc1").andReturn(200, sc1).once();
Exchange ex = template.request("direct:get", exchange -> {
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_NAME, "sc1");
});
CronJob result = ex.getMessage().getBody(CronJob.class);
assertNotNull(result);
}
@Test
void createJobTest() {
Map<String, String> labels = Map.of("my.label.key", "my.label.value");
CronJobSpec spec = new CronJobSpecBuilder().build();
CronJob j1 = new CronJobBuilder().withNewMetadata().withName("j1").withNamespace("test").withLabels(labels).and()
.withSpec(spec).build();
server.expect().post().withPath("/apis/batch/v1/namespaces/test/cronjobs").andReturn(200, j1).once();
Exchange ex = template.request("direct:create", exchange -> {
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_LABELS, labels);
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_NAME, "j1");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_SPEC, spec);
});
CronJob result = ex.getMessage().getBody(CronJob.class);
assertEquals("test", result.getMetadata().getNamespace());
assertEquals("j1", result.getMetadata().getName());
assertEquals(labels, result.getMetadata().getLabels());
}
@Test
void createJobWithAnnotationsTest() {
Map<String, String> labels = Map.of("my.label.key", "my.label.value");
Map<String, String> annotations = Map.of("my.annotation.key", "my.annotation.value");
CronJobSpec spec = new CronJobSpecBuilder().build();
CronJob j1 = new CronJobBuilder().withNewMetadata().withName("j1").withNamespace("test").withLabels(labels)
.withAnnotations(annotations).and()
.withSpec(spec).build();
server.expect().post().withPath("/apis/batch/v1/namespaces/test/cronjobs").andReturn(200, j1).once();
Exchange ex = template.request("direct:create", exchange -> {
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_LABELS, labels);
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_ANNOTATIONS, annotations);
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_NAME, "j1");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_SPEC, spec);
});
CronJob result = ex.getMessage().getBody(CronJob.class);
assertEquals("test", result.getMetadata().getNamespace());
assertEquals("j1", result.getMetadata().getName());
assertEquals(labels, result.getMetadata().getLabels());
assertEquals(annotations, result.getMetadata().getAnnotations());
}
@Test
void updateJobTest() {
Map<String, String> labels = Map.of("my.label.key", "my.label.value");
CronJobSpec spec = new CronJobSpecBuilder().withJobTemplate(new JobTemplateSpecBuilder().build()).build();
CronJob j1 = new CronJobBuilder().withNewMetadata().withName("j1").withNamespace("test").withLabels(labels).and()
.withSpec(spec).build();
server.expect().get().withPath("/apis/batch/v1/namespaces/test/cronjobs/j1")
.andReturn(200, new JobBuilder().withNewMetadata().withName("j1").withNamespace("test").endMetadata()
.withSpec(new JobSpecBuilder()
.withTemplate(new PodTemplateSpecBuilder().withMetadata(new ObjectMeta()).build()).build())
.build())
.times(2);
server.expect().put().withPath("/apis/batch/v1/namespaces/test/cronjobs/j1").andReturn(200, j1).once();
Exchange ex = template.request("direct:update", exchange -> {
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_LABELS, labels);
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_NAME, "j1");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_SPEC, spec);
});
CronJob result = ex.getMessage().getBody(CronJob.class);
assertEquals("test", result.getMetadata().getNamespace());
assertEquals("j1", result.getMetadata().getName());
assertEquals(labels, result.getMetadata().getLabels());
}
@Test
void deleteJobTest() {
CronJob j1 = new CronJobBuilder().withNewMetadata().withName("j1").withNamespace("test").and().build();
server.expect().delete().withPath("/apis/batch/v1/namespaces/test/cronjobs/j1").andReturn(200, j1)
.once();
Exchange ex = template.request("direct:delete", exchange -> {
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test");
exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CRON_JOB_NAME, "j1");
});
assertNotNull(ex.getMessage());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// the kubernetes-client is autowired on the component
from("direct:list").to("kubernetes-cronjob:foo?operation=listCronJob");
from("direct:listByLabels").to("kubernetes-cronjob:foo?operation=listCronJobByLabels");
from("direct:get").to("kubernetes-cronjob:foo?operation=getCronJob");
from("direct:create").to("kubernetes-cronjob:foo?operation=createCronJob");
from("direct:update").to("kubernetes-cronjob:foo?operation=updateCronJob");
from("direct:delete").to("kubernetes-cronjob:foo?operation=deleteCronJob");
}
};
}
}
| KubernetesCronJobProducerTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TruthContainsExactlyElementsInUsageTest.java | {
"start": 3373,
"end": 3969
} | class ____ {
void test() {
List<Integer> list = ImmutableList.of(1, 2, 3);
assertThat(list).containsExactlyElementsIn(ImmutableList.copyOf(list));
}
}
""")
.doTest();
}
@Test
public void negativeTruthContainsExactlyElementsInUsageWithHashSet() {
compilationHelper
.addSourceLines(
"ExampleClassTest.java",
"""
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
public | ExampleClassTest |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webmvc/src/test/java/org/springframework/cloud/gateway/server/mvc/filter/WeightRequestPredicateIntegrationTests.java | {
"start": 2572,
"end": 3561
} | class ____ {
@Autowired
RestTestClient testClient;
@Autowired
private WeightCalculatorFilter filter;
private static Supplier<Double> getRandom(double value) {
Supplier<Double> random = mock(Supplier.class);
when(random.get()).thenReturn(value);
return random;
}
@Test
public void highWeight() {
filter.setRandomSupplier(getRandom(0.9));
testClient.get()
.uri("/get")
.header(HttpHeaders.HOST, "www.weight-high.org")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueEquals("X-Route", "weight_high_test");
}
@Test
public void lowWeight() {
filter.setRandomSupplier(getRandom(0.1));
testClient.get()
.uri("/get")
.header(HttpHeaders.HOST, "www.weight-low.org")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueEquals("X-Route", "weight_low_test");
}
@EnableAutoConfiguration
@SpringBootConfiguration
@Import(PermitAllSecurityConfiguration.class)
public static | WeightRequestPredicateIntegrationTests |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java | {
"start": 2716,
"end": 130119
} | class ____ extends SimpleHttpTest {
protected HttpTest(HttpConfig config) {
super(config);
}
@Test
public void testCloseMulti() throws Exception {
int num = 4;
waitFor(num);
HttpServer[] servers = new HttpServer[num];
for (int i = 0;i < num;i++) {
int val = i;
servers[i] = createHttpServer().requestHandler(req -> {
req.response().end("Server " + val);
});
startServer(testAddress, servers[i]);
}
List<HttpClientConnection> connections = Collections.synchronizedList(new ArrayList<>());
for (int i = 0;i < num;i++) {
client.connect(new HttpConnectOptions().setServer(testAddress))
.onComplete(onSuccess(connections::add));
}
waitUntil(() -> connections.size() == 4);
Set<String> actual = new HashSet<>();
Set<String> expected = new HashSet<>();
for (int i = 0;i < num;i++) {
Buffer body = awaitFuture(connections.get(i)
.request(requestOptions)
.compose(req -> req.send()
.compose(HttpClientResponse::body)
));
expected.add("Server " + i);
actual.add(body.toString());
}
assertEquals(expected, actual);
awaitFuture(servers[3].close());
int successes = 0;
int failures = 0;
for (int i = 0;i < num;i++) {
Future<Buffer> fut = connections.get(i)
.request(requestOptions)
.compose(req -> req.send()
.compose(HttpClientResponse::body)
);
try {
awaitFuture(fut);
successes++;
} catch (Exception e) {
failures++;
}
}
assertEquals(3, successes);
assertEquals(1, failures);
}
@Test
public void testClientRequestArguments() throws Exception {
server.requestHandler(req -> {
fail();
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(req -> {
assertNullPointerException(() -> req.putHeader((String) null, "someValue"));
assertNullPointerException(() -> req.putHeader((CharSequence) null, "someValue"));
assertNullPointerException(() -> req.putHeader("someKey", (Iterable<String>) null));
assertNullPointerException(() -> req.write((Buffer) null));
assertNullPointerException(() -> req.write((String) null));
assertNullPointerException(() -> req.write(null, "UTF-8"));
assertNullPointerException(() -> req.write("someString", (String) null));
assertNullPointerException(() -> req.end((Buffer) null));
assertNullPointerException(() -> req.end((String) null));
assertNullPointerException(() -> req.end(null, "UTF-8"));
assertNullPointerException(() -> req.end("someString", (String) null));
assertIllegalArgumentException(() -> req.idleTimeout(0));
testComplete();
}));
await();
}
@Test
public void testLowerCaseHeaders() throws Exception {
server.requestHandler(req -> {
assertEquals("foo", req.headers().get("Foo"));
assertEquals("foo", req.headers().get("foo"));
assertEquals("foo", req.headers().get("fOO"));
assertTrue(req.headers().contains("Foo"));
assertTrue(req.headers().contains("foo"));
assertTrue(req.headers().contains("fOO"));
req.response().putHeader("Quux", "quux");
assertEquals("quux", req.response().headers().get("Quux"));
assertEquals("quux", req.response().headers().get("quux"));
assertEquals("quux", req.response().headers().get("qUUX"));
assertTrue(req.response().headers().contains("Quux"));
assertTrue(req.response().headers().contains("quux"));
assertTrue(req.response().headers().contains("qUUX"));
req.response().end();
});
startServer(testAddress);
client
.request(requestOptions)
.onComplete(onSuccess(req -> {
req.putHeader("Foo", "foo");
assertEquals("foo", req.headers().get("Foo"));
assertEquals("foo", req.headers().get("foo"));
assertEquals("foo", req.headers().get("fOO"));
assertTrue(req.headers().contains("Foo"));
assertTrue(req.headers().contains("foo"));
assertTrue(req.headers().contains("fOO"));
req
.send()
.onComplete(onSuccess(resp -> {
assertEquals("quux", resp.headers().get("Quux"));
assertEquals("quux", resp.headers().get("quux"));
assertEquals("quux", resp.headers().get("qUUX"));
assertTrue(resp.headers().contains("Quux"));
assertTrue(resp.headers().contains("quux"));
assertTrue(resp.headers().contains("qUUX"));
testComplete();
}));
}));
await();
}
@Test
public void testServerActualPortWhenSet() throws Exception {
assumeTrue(testAddress.isInetSocket());
server.close();
server
.requestHandler(request -> {
request.response().end("hello");
});
startServer(testAddress);
assertEquals(server.actualPort(), config.port());
HttpClient client = createHttpClient();
client
.request(new RequestOptions(requestOptions).setPort(server.actualPort()))
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(resp.statusCode(), 200);
return resp.body();
}))
.onComplete(onSuccess(body -> {
assertEquals(body.toString("UTF-8"), "hello");
testComplete();
}));
await();
}
@Test
public void testServerActualPortWhenZero() throws Exception {
assumeTrue(testAddress.isInetSocket());
server.close();
server = createHttpServer();
server
.requestHandler(request -> {
request.response().end("hello");
});
server.listen(0).await();
assertTrue(server.actualPort() != 0);
HttpClient client = createHttpClient();
client
.request(new RequestOptions(requestOptions).setPort(server.actualPort()))
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(resp.statusCode(), 200);
return resp.body();
}))
.onComplete(onSuccess(body -> {
assertEquals(body.toString("UTF-8"), "hello");
testComplete();
}));
await();
}
@Test
public void testServerActualPortWhenZeroPassedInListen() throws Exception {
assumeTrue(testAddress.isInetSocket());
server.close();
server = createHttpServer();
server
.requestHandler(request -> {
request.response().end("hello");
});
startServer();
assertTrue(server.actualPort() != 0);
client.close();
client = createHttpClient();
client.request(new RequestOptions(requestOptions).setPort(server.actualPort()))
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(resp.statusCode(), 200);
return resp.body();
}))
.onComplete(onSuccess(body -> {
assertEquals(body.toString("UTF-8"), "hello");
testComplete();
}));
await();
}
@Test
public void testClientRequestOptionsSocketAddressOnly() throws Exception {
assumeTrue(testAddress.isInetSocket());
Integer port = requestOptions.getPort();
String host = requestOptions.getHost();
server
.requestHandler(request -> {
assertEquals(host, request.authority().host());
assertEquals((int)port, request.authority().port());
request.response().end();
});
startServer(testAddress);
SocketAddress server = SocketAddress.inetSocketAddress(port, host);
client.request(new RequestOptions().setServer(server)).compose(req -> req.send().compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.body();
})).onComplete(onSuccess(body -> {
testComplete();
}));
await();
}
/*
@Test
public void testRequestNPE() {
String uri = "/some-uri?foo=bar";
TestUtils.assertNullPointerException(() -> client.request(null, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri));
TestUtils.assertNullPointerException(() -> client.request( null, 8080, "localhost", "/somepath"));
TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, null, "/somepath"));
TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, "localhost", null));
}
*/
@Test
public void testInvalidAbsoluteURI() {
try {
client.request(new RequestOptions().setAbsoluteURI("ijdijwidjqwoijd192d192192ej12d"));
fail("Should throw exception");
} catch (VertxException e) {
//OK
}
}
@Test
public void testPutHeadersOnRequest() throws Exception {
server.requestHandler(req -> {
assertEquals("bar", req.headers().get("foo"));
assertEquals("bar", req.getHeader("foo"));
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.putHeader("foo", "bar")
.send()
.map(HttpClientResponse::statusCode))
.onComplete(onSuccess(sc -> {
assertEquals(200, (int) sc);
testComplete();
}));
await();
}
@Test
public void testPutHeaderReplacesPreviousHeaders() throws Exception {
server.requestHandler(req ->
req.response()
.putHeader("Location", "http://example1.org")
.putHeader("location", "http://example2.org")
.send());
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.map(resp -> resp.headers().get("LocatioN")))
.onComplete(onSuccess(header -> {
assertEquals("http://example2.org", header);
testComplete();
}));
await();
}
@Test
public void testSimpleGET() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.GET, resp -> testComplete());
}
@Test
public void testSimplePUT() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PUT, resp -> testComplete());
}
@Test
public void testSimplePOST() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.POST, resp -> testComplete());
}
@Test
public void testSimpleDELETE() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.DELETE, resp -> testComplete());
}
@Test
public void testSimpleHEAD() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.HEAD, resp -> testComplete());
}
@Test
public void testSimpleTRACE() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.TRACE, resp -> testComplete());
}
@Test
public void testSimpleCONNECT() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.CONNECT, resp -> testComplete());
}
@Test
public void testSimpleOPTIONS() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.OPTIONS, resp -> testComplete());
}
@Test
public void testSimplePATCH() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PATCH, resp -> testComplete());
}
@Test
public void testSimpleGETAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete());
}
@Test
public void testEmptyPathGETAbsolute() throws Exception {
String uri = "";
testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete());
}
@Test
public void testNoPathButQueryGETAbsolute() throws Exception {
String uri = "?foo=bar";
testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete());
}
@Test
public void testSimplePUTAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PUT, true, resp -> testComplete());
}
@Test
public void testSimplePOSTAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.POST, true, resp -> testComplete());
}
@Test
public void testSimpleDELETEAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.DELETE, true, resp -> testComplete());
}
@Test
public void testSimpleHEADAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.HEAD, true, resp -> testComplete());
}
@Test
public void testSimpleTRACEAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.TRACE, true, resp -> testComplete());
}
@Test
public void testSimpleCONNECTAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.CONNECT, true, resp -> testComplete());
}
@Test
public void testSimpleOPTIONSAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.OPTIONS, true, resp -> testComplete());
}
@Test
public void testSimplePATCHAbsolute() throws Exception {
String uri = "/some-uri?foo=bar";
testSimpleRequest(uri, HttpMethod.PATCH, true, resp -> testComplete());
}
private void testSimpleRequest(String uri, HttpMethod method, Handler<HttpClientResponse> handler) throws Exception {
testSimpleRequest(uri, method, false, handler);
}
private void testSimpleRequest(String uri, HttpMethod method, boolean absolute, Handler<HttpClientResponse> handler) throws Exception {
boolean ssl = this instanceof Http2Test;
RequestOptions options;
if (absolute) {
options = new RequestOptions(requestOptions).setServer(testAddress).setMethod(method).setAbsoluteURI((ssl ? "https://" : "http://") + config.host() + ":" + config.port() + uri);
} else {
options = new RequestOptions(requestOptions).setMethod(method).setURI(uri);
}
testSimpleRequest(uri, method, options, absolute, handler);
}
private void testSimpleRequest(String uri, HttpMethod method, RequestOptions requestOptions, boolean absolute, Handler<HttpClientResponse> handler) throws Exception {
int index = uri.indexOf('?');
String query;
String path;
if (index == -1) {
path = uri;
query = null;
} else {
path = uri.substring(0, index);
query = uri.substring(index + 1);
}
String resource = absolute && path.isEmpty() ? "/" + path : path;
server.requestHandler(req -> {
String expectedPath = req.method() == HttpMethod.CONNECT && req.version() == HttpVersion.HTTP_2 ? null : resource;
String expectedQuery = req.method() == HttpMethod.CONNECT && req.version() == HttpVersion.HTTP_2 ? null : query;
assertEquals(expectedPath, req.path());
assertEquals(method, req.method());
assertEquals(expectedQuery, req.query());
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(onSuccess(handler::handle));
await();
}
@Test
public void testServerChaining() throws Exception {
server.requestHandler(req -> {
assertTrue(req.response().setChunked(true) == req.response());
testComplete();
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(HttpClientRequest::send));
await();
}
@Test
public void testResponseEndHandlers1() throws Exception {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
server.requestHandler(req -> {
req.response().putHeader("removedheader", "foo");
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
req.response().headers().remove("removedheader");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(0, req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.map(resp -> {
assertEquals(200, resp.statusCode());
assertEquals("wibble", resp.headers().get("extraheader"));
assertNull(resp.headers().get("removedheader"));
return null;
}))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testResponseEndHandlers2() throws Exception {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
String content = "blah";
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(content.length(), req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().end(content);
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
assertEquals("wibble", resp.headers().get("extraheader"));
return resp.body();
}))
.onComplete(onSuccess(body -> {
assertEquals(Buffer.buffer(content), body);
complete();
}));
await();
}
@Test
public void testResponseEndHandlersChunkedResponse() throws Exception {
waitFor(2);
AtomicInteger cnt = new AtomicInteger();
String chunk = "blah";
int numChunks = 6;
StringBuilder content = new StringBuilder(chunk.length() * numChunks);
IntStream.range(0, numChunks).forEach(i -> content.append(chunk));
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
});
req.response().bodyEndHandler(v -> {
assertEquals(content.length(), req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().setChunked(true);
// note that we have a -1 here because the last chunk is written via end(chunk)
IntStream.range(0, numChunks - 1).forEach(x -> req.response().write(chunk));
// End with a chunk to ensure size is correctly calculated
req.response().end(chunk);
});
startServer(testAddress);
client.request(requestOptions).compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
assertEquals("wibble", resp.headers().get("extraheader"));
return resp.body();
})).onComplete(onSuccess(body -> {
assertEquals(Buffer.buffer(content.toString()), body);
complete();
}));
await();
}
@Test
public void testResponseEndHandlersSendFile() throws Exception {
waitFor(4);
AtomicInteger cnt = new AtomicInteger();
String content = "iqdioqwdqwiojqwijdwqd";
File toSend = setupFile("somefile.txt", content);
server.requestHandler(req -> {
req.response().headersEndHandler(v -> {
// Insert another header
req.response().putHeader("extraheader", "wibble");
assertEquals(0, cnt.getAndIncrement());
complete();
});
req.response().bodyEndHandler(v -> {
assertEquals(content.length(), req.response().bytesWritten());
assertEquals(1, cnt.getAndIncrement());
complete();
});
req.response().endHandler(v -> complete());
req.response().sendFile(toSend.getAbsolutePath());
});
startServer(testAddress);
client.request(requestOptions).compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
assertEquals("wibble", resp.headers().get("extraheader"));
return resp.body();
})).onComplete(onSuccess(body -> {
assertEquals(Buffer.buffer(content), body);
complete();
}));
await();
}
@Test
public void testAbsoluteURI() throws Exception {
String uri = "http://" + config.host() + ":" + config.port() + "/this/is/a/path/foo.html";
testURIAndPath(uri, uri, "/this/is/a/path/foo.html");
}
@Test
public void testRelativeURI() throws Exception {
String uri = "/this/is/a/path/foo.html";
testURIAndPath(uri, uri, uri);
}
@Test
public void testAbsoluteURIWithHttpSchemaInQuery() throws Exception {
String uri = "http://" + config.host() + ":" + config.port() + "/correct/path?url=http://localhost:8008/wrong/path";
testURIAndPath(uri, uri, "/correct/path");
}
@Test
public void testRelativeURIWithHttpSchemaInQuery() throws Exception {
String uri = "/correct/path?url=http://localhost:8008/wrong/path";
testURIAndPath(uri, uri, "/correct/path");
}
@Test
public void testAbsoluteURIEmptyPath() throws Exception {
String uri = "http://" + config.host() + ":" + config.port() + "/";
testURIAndPath(uri, uri, "/");
}
@Test
public void testEmptyURI() throws Exception {
testURIAndPath("", "/", "/");
}
@Test
public void testParams() throws Exception {
server.requestHandler(req -> {
MultiMap params1 = req.params(true);
MultiMap params2 = req.params(true);
assertSame(params1, params2); // got the cached value
MultiMap params3 = req.params(false);
assertNotSame(params1, params3); // cache refreshed
MultiMap params4 = req.params(false);
assertSame(params3, params4); // got the cached value
assertEquals(params1.get("a"), "1;b=2");
assertEquals(params3.get("a"), "1");
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI("/?a=1;b=2&c=3"))
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end();
}))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
private void testURIAndPath(String uri, String expectedUri, String expectedPath) throws Exception {
server.requestHandler(req -> {
assertEquals(expectedUri, req.uri());
assertEquals(expectedPath, req.path());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI(uri))
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end();
}))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testParamUmlauteDecoding() throws Exception {
testParamDecoding("\u00e4\u00fc\u00f6");
}
@Test
public void testParamPlusDecoding() throws Exception {
testParamDecoding("+");
}
@Test
public void testParamPercentDecoding() throws Exception {
testParamDecoding("%");
}
@Test
public void testParamSpaceDecoding() throws Exception {
testParamDecoding(" ");
}
@Test
public void testParamNormalDecoding() throws Exception {
testParamDecoding("hello");
}
@Test
public void testParamAltogetherDecoding() throws Exception {
testParamDecoding("\u00e4\u00fc\u00f6+% hello");
}
private void testParamDecoding(String value) throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
MultiMap formAttributes = req.formAttributes();
assertEquals(value, formAttributes.get("param"));
});
req.response().end();
});
Buffer body = Buffer.buffer("param=" + URLEncoder.encode(value,"UTF-8"));
startServer(testAddress);
client
.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.compose(req -> req
.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length()))
.putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED)
.send(body).compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end();
}))
.onComplete(onSuccess(resp -> testComplete()));
await();
}
@Test
public void testParamsAmpersand() throws Exception {
testParams('&');
}
@Test
public void testParamsSemiColon() throws Exception {
testParams(';');
}
private void testParams(char delim) throws Exception {
MultiMap params = TestUtils.randomMultiMap(10);
String query = generateQueryString(params, delim);
server.requestHandler(req -> {
assertEquals(query, req.query());
assertEquals(params.size(), req.params().size());
for (Map.Entry<String, String> entry : req.params()) {
assertEquals(entry.getValue(), params.get(entry.getKey()));
}
req.response().end();
});
startServer(testAddress);
sendAndAwait(new RequestOptions(requestOptions).setURI("some-uri/?" + query));
}
@Test
public void testNoParams() throws Exception {
server.requestHandler(req -> {
assertNull(req.query());
assertTrue(req.params().isEmpty());
req.response().end();
});
startServer(testAddress);
sendAndAwait(requestOptions);
}
@Test
public void testOverrideParamsCharset() throws Exception {
server.requestHandler(req -> {
String val = req.getParam("param");
assertEquals("\u20AC", val); // Euro sign
req.setParamsCharset(StandardCharsets.ISO_8859_1.name());
val = req.getParam("param");
assertEquals("\u00E2\u0082\u00AC", val);
req.response().end();
});
startServer(testAddress);
sendAndAwait(new RequestOptions(requestOptions).setURI("/?param=%E2%82%AC"));
}
@Test
public void testGetParamDefaultValue() throws Exception {
String paramName1 = "foo";
String paramName1Value = "bar";
String paramName2 = "notPresentParam";
String paramName2DefaultValue = "defaultValue";
String reqUri = DEFAULT_TEST_URI + "/?" + paramName1 + "=" + paramName1Value;
server.requestHandler(req -> {
assertTrue(req.params().contains(paramName1));
assertEquals(paramName1Value, req.getParam(paramName1, paramName2DefaultValue));
assertFalse(req.params().contains(paramName2));
assertEquals(paramName2DefaultValue, req.getParam(paramName2, paramName2DefaultValue));
req.response().end();
});
startServer(testAddress);
sendAndAwait(new RequestOptions(requestOptions).setURI(reqUri));
}
@Test
public void testMissingContentTypeMultipartRequest() throws Exception {
testInvalidMultipartRequest(null, HttpMethod.POST);
}
@Test
public void testInvalidContentTypeMultipartRequest() throws Exception {
testInvalidMultipartRequest("application/json", HttpMethod.POST);
}
@Test
public void testInvalidMethodMultipartRequest() throws Exception {
testInvalidMultipartRequest("multipart/form-data", HttpMethod.GET);
}
private void testInvalidMultipartRequest(String contentType, HttpMethod method) throws Exception {
server.requestHandler(req -> {
try {
req.setExpectMultipart(true);
fail();
} catch (IllegalStateException ignore) {
req.response().end();
}
});
startServer(testAddress);
sendAndAwait(requestOptions, req -> {
if (contentType != null) {
req.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
});
}
@Test
public void testDefaultRequestHeaders() throws Exception {
server.requestHandler(req -> {
if (req.version() == HttpVersion.HTTP_1_1) {
assertEquals(1, req.headers().size());
assertEquals(config.host() + ":" + config.port(), req.headers().get("host"));
} else {
assertEquals(0, req.headers().size());
}
req.response().end();
});
startServer(testAddress);
sendAndAwait(requestOptions);
}
private void sendAndAwait(RequestOptions request) {
sendAndAwait(request, req -> {});
}
private void sendAndAwait(RequestOptions request, Handler<HttpClientRequest> handler) {
client.request(request)
.compose(req -> {
handler.handle(req);
return req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end();
});
})
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testRequestHeadersWithCharSequence() throws Exception {
HashMap<CharSequence, String> expectedHeaders = new HashMap<>();
expectedHeaders.put(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");
expectedHeaders.put(HttpHeaderNames.CONTENT_ENCODING, "gzip");
expectedHeaders.put(HttpHeaderNames.USER_AGENT, "Mozilla/5.0");
server.requestHandler(req -> {
MultiMap headers = req.headers();
headers.remove("host");
assertEquals(expectedHeaders.size(), headers.size());
expectedHeaders.forEach((k, v) -> assertEquals(v, headers.get(k)));
expectedHeaders.forEach((k, v) -> assertEquals(v, req.getHeader(k)));
req.response().end();
});
startServer(testAddress);
sendAndAwait(requestOptions, req -> {
expectedHeaders.forEach((k, v) -> req.headers().set(k, v));
});
}
@Test
public void testRequestHeadersPutAll() throws Exception {
testRequestHeaders(false);
}
@Test
public void testRequestHeadersIndividually() throws Exception {
testRequestHeaders(true);
}
private void testRequestHeaders(boolean individually) throws Exception {
MultiMap expectedHeaders = randomMultiMap(10);
server.requestHandler(req -> {
MultiMap headers = req.headers();
headers.remove("host");
assertEquals(expectedHeaders.size(), expectedHeaders.size());
for (Map.Entry<String, String> entry : expectedHeaders) {
assertEquals(entry.getValue(), req.headers().get(entry.getKey()));
assertEquals(entry.getValue(), req.getHeader(entry.getKey()));
}
req.response().end();
});
startServer(testAddress);
sendAndAwait(requestOptions, req -> {
if (individually) {
for (Map.Entry<String, String> header : expectedHeaders) {
req.headers().add(header.getKey(), header.getValue());
}
} else {
req.headers().setAll(expectedHeaders);
}
});
}
@Test
public void testResponseHeadersPutAll() throws Exception {
testResponseHeaders(false);
}
@Test
public void testResponseHeadersIndividually() throws Exception {
testResponseHeaders(true);
}
private void testResponseHeaders(boolean individually) throws Exception {
MultiMap headers = randomMultiMap(10);
server.requestHandler(req -> {
if (individually) {
for (Map.Entry<String, String> header : headers) {
req.response().headers().add(header.getKey(), header.getValue());
}
} else {
req.response().headers().setAll(headers);
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.compose(resp -> resp.end().map(resp.headers())))
.onComplete(onSuccess(respHeaders -> {
assertTrue(headers.size() < respHeaders.size());
for (Map.Entry<String, String> entry : headers) {
assertEquals(entry.getValue(), respHeaders.get(entry.getKey()));
}
testComplete();
}));
await();
}
@Test
public void testResponseHeadersWithCharSequence() throws Exception {
HashMap<CharSequence, String> headers = new HashMap<>();
headers.put(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");
headers.put(HttpHeaderNames.CONTENT_ENCODING, "gzip");
headers.put(HttpHeaderNames.USER_AGENT, "Mozilla/5.0");
server.requestHandler(req -> {
headers.forEach((k, v) -> req.response().headers().add(k, v));
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.compose(resp -> resp.end().map(resp.headers())))
.onComplete(onSuccess(respHeaders -> {
assertTrue(headers.size() < respHeaders.size());
headers.forEach((k, v) -> assertEquals(v, respHeaders.get(k)));
testComplete();
}));
await();
}
@Test
public void testResponseMultipleSetCookieInHeader() throws Exception {
testResponseMultipleSetCookie(true, false);
}
@Test
public void testResponseMultipleSetCookieInTrailer() throws Exception {
testResponseMultipleSetCookie(false, true);
}
@Test
public void testResponseMultipleSetCookieInHeaderAndTrailer() throws Exception {
testResponseMultipleSetCookie(true, true);
}
private void testResponseMultipleSetCookie(boolean inHeader, boolean inTrailer) throws Exception {
List<String> cookies = new ArrayList<>();
server.requestHandler(req -> {
if (inHeader) {
List<String> headers = new ArrayList<>();
headers.add("h1=h1v1");
headers.add("h2=h2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT");
cookies.addAll(headers);
req.response().headers().set("Set-Cookie", headers);
}
if (inTrailer) {
req.response().setChunked(true);
List<String> trailers = new ArrayList<>();
trailers.add("t1=t1v1");
trailers.add("t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT");
cookies.addAll(trailers);
req.response().trailers().set("Set-Cookie", trailers);
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions).compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end().map(v -> resp.cookies());
}))
.onComplete(onSuccess(respCookies -> {
assertEquals(cookies.size(), respCookies.size());
for (int i = 0; i < cookies.size(); ++i) {
assertEquals(cookies.get(i), respCookies.get(i));
}
testComplete();
}));
await();
}
@Test
public void testUseRequestAfterComplete() throws Exception {
server.requestHandler(v -> {});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(req -> {
req.end();
Buffer buff = Buffer.buffer();
assertIllegalStateExceptionAsync(() -> req.end());
assertIllegalStateException(() -> req.continueHandler(v -> {}));
assertIllegalStateException(() -> req.drainHandler(v -> {}));
assertIllegalStateExceptionAsync(() -> req.end("foo"));
assertIllegalStateExceptionAsync(() -> req.end(buff));
assertIllegalStateExceptionAsync(() -> req.end("foo", "UTF-8"));
assertIllegalStateException(() -> req.writeHead());
assertIllegalStateException(() -> req.setChunked(false));
assertIllegalStateException(() -> req.setWriteQueueMaxSize(123));
assertIllegalStateExceptionAsync(() -> req.write(buff));
assertIllegalStateExceptionAsync(() -> req.write("foo"));
assertIllegalStateExceptionAsync(() -> req.write("foo", "UTF-8"));
assertIllegalStateExceptionAsync(() -> req.write(buff));
assertIllegalStateException(() -> req.writeQueueFull());
testComplete();
}));
await();
}
@Test
public void testRequestBodyBufferAtEnd() throws Exception {
Buffer body = TestUtils.randomBuffer(1000);
server.requestHandler(req -> req.bodyHandler(buffer -> {
assertEquals(body, buffer);
req.response().end();
}));
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.compose(req -> req
.send(body)
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end();
}))
.onComplete(onSuccess(req -> testComplete()));
await();
}
@Test
public void testRequestBodyStringDefaultEncodingAtEnd() throws Exception {
testRequestBodyStringAtEnd(null);
}
@Test
public void testRequestBodyStringUTF8AtEnd() throws Exception {
testRequestBodyStringAtEnd("UTF-8");
}
@Test
public void testRequestBodyStringUTF16AtEnd() throws Exception {
testRequestBodyStringAtEnd("UTF-16");
}
private void testRequestBodyStringAtEnd(String encoding) throws Exception {
String body = TestUtils.randomUnicodeString(1000);
Buffer bodyBuff;
if (encoding == null) {
bodyBuff = Buffer.buffer(body);
} else {
bodyBuff = Buffer.buffer(body, encoding);
}
server.requestHandler(req -> {
req.bodyHandler(buffer -> {
assertEquals(bodyBuff, buffer);
testComplete();
});
});
startServer(testAddress);
client
.request(requestOptions)
.compose(req -> {
if (encoding == null) {
return req.end(body);
} else {
return req.end(body, encoding);
}
});
await();
}
@Test
public void testRequestBodyWriteChunked() throws Exception {
testRequestBodyWrite(true);
}
@Test
public void testRequestBodyWriteNonChunked() throws Exception {
testRequestBodyWrite(false);
}
private void testRequestBodyWrite(boolean chunked) throws Exception {
Buffer body = Buffer.buffer();
server.requestHandler(req -> {
req.bodyHandler(buffer -> {
assertEquals(body, buffer);
req.response().end();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.compose(req -> {
int numWrites = 10;
int chunkSize = 100;
if (chunked) {
req.setChunked(true);
} else {
req.headers().set("Content-Length", String.valueOf(numWrites * chunkSize));
}
for (int i = 0; i < numWrites; i++) {
Buffer b = TestUtils.randomBuffer(chunkSize);
body.appendBuffer(b);
req.write(b);
}
req.end();
return req.response().compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end();
});
}).onComplete(onSuccess(req -> {
testComplete();
}));
await();
}
@Test
public void testRequestBodyWriteStringChunkedDefaultEncoding() throws Exception {
testRequestBodyWriteString(true, null);
}
@Test
public void testRequestBodyWriteStringChunkedUTF8() throws Exception {
testRequestBodyWriteString(true, "UTF-8");
}
@Test
public void testRequestBodyWriteStringChunkedUTF16() throws Exception {
testRequestBodyWriteString(true, "UTF-16");
}
@Test
public void testRequestBodyWriteStringNonChunkedDefaultEncoding() throws Exception {
testRequestBodyWriteString(false, null);
}
@Test
public void testRequestBodyWriteStringNonChunkedUTF8() throws Exception {
testRequestBodyWriteString(false, "UTF-8");
}
@Test
public void testRequestBodyWriteStringNonChunkedUTF16() throws Exception {
testRequestBodyWriteString(false, "UTF-16");
}
private void testRequestBodyWriteString(boolean chunked, String encoding) throws Exception {
String body = TestUtils.randomUnicodeString(1000);
Buffer bodyBuff;
if (encoding == null) {
bodyBuff = Buffer.buffer(body);
} else {
bodyBuff = Buffer.buffer(body, encoding);
}
server.requestHandler(req -> {
req.bodyHandler(buff -> {
assertEquals(bodyBuff, buff);
testComplete();
});
});
startServer(testAddress);
client
.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.onComplete(onSuccess(req -> {
if (chunked) {
req.setChunked(true);
} else {
req.headers().set("Content-Length", String.valueOf(bodyBuff.length()));
}
if (encoding == null) {
req.write(body);
} else {
req.write(body, encoding);
}
req.end();
}));
await();
}
@Test
public void testRequestWrite() throws Exception {
int times = 3;
Buffer chunk = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.bodyHandler(buff -> {
Buffer expected = Buffer.buffer();
for (int i = 0;i < times;i++) {
expected.appendBuffer(chunk);
}
assertEquals(expected, buff);
testComplete();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.onComplete(onSuccess(req -> {
req.setChunked(true);
int padding = 5;
for (int i = 0;i < times;i++) {
Buffer paddedChunk = TestUtils.leftPad(padding, chunk);
req.write(paddedChunk);
}
req.end();
}));
await();
}
@Repeat(times = 10)
@Test
public void testClientExceptionHandlerCalledWhenServerTerminatesConnection() throws Exception {
int numReqs = 1;
server.requestHandler(request -> {
request.connection().close();
});
startServer(testAddress);
// Exception handler should be called for any requests in the pipeline if connection is closed
for (int i = 0; i < numReqs; i++) {
try {
client.request(requestOptions)
.compose(HttpClientRequest::send)
.await();
fail();
} catch (Exception expected) {
}
}
}
@Test
public void testClientExceptionHandlerCalledWhenServerTerminatesConnectionAfterPartialResponse() throws Exception {
AtomicReference<HttpConnection> connection = new AtomicReference<>();
server.requestHandler(request -> {
//Write partial response then close connection before completing it
connection.set(request.connection());
HttpServerResponse resp = request.response().setChunked(true);
resp.write("foo");
});
startServer(testAddress);
// Exception handler should be called for any requests in the pipeline if connection is closed
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
resp.exceptionHandler(atMostOnce(t -> {
testComplete();
}));
connection.get().close();
}));
}));
await();
}
@Test
public void testContextExceptionHandlerCalledWhenExceptionOnDataHandler() throws Exception {
client.close();
server.requestHandler(request -> {
request.response().end("foo");
});
startServer(testAddress);
// Exception handler should be called for any exceptions in the data handler
Context ctx = vertx.getOrCreateContext();
ctx.runOnContext(v -> {
RuntimeException cause = new RuntimeException("should be caught");
ctx.exceptionHandler(err -> {
if (err == cause) {
testComplete();
}
});
client = createHttpClient();
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
resp.handler(data -> {
throw cause;
});
}));
}));
});
await();
}
@Test
public void testClientExceptionHandlerCalledWhenExceptionOnBodyHandler() throws Exception {
client.close();
server.requestHandler(request -> {
request.response().end("foo");
});
startServer(testAddress);
client = createHttpClient();
// Exception handler should be called for any exceptions in the data handler
Context ctx = vertx.getOrCreateContext();
RuntimeException cause = new RuntimeException("should be caught");
ctx.runOnContext(v -> {
ctx.exceptionHandler(err -> {
if (err == cause) {
testComplete();
}
});
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
resp.bodyHandler(data -> {
throw cause;
});
}));
}));
});
await();
}
@Test
public void testNoExceptionHandlerCalledWhenResponseEnded() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
req.exceptionHandler(this::fail);
resp.exceptionHandler(err -> {
fail(err);
});
resp.end();
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(req -> {
req
.exceptionHandler(t -> {
fail("Should not be called");
})
.send().onComplete(onSuccess(resp -> {
resp.endHandler(v -> {
vertx.setTimer(100, tid -> testComplete());
});
resp.exceptionHandler(t -> {
fail("Should not be called");
});
}));
}));
await();
}
@Test
public void testServerExceptionHandlerOnClose() throws Exception {
waitFor(4);
AtomicInteger requestCount = new AtomicInteger();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
AtomicInteger requestExceptionHandlerCount = new AtomicInteger();
req.exceptionHandler(err -> {
if (err instanceof HttpClosedException) {
assertEquals(1, requestExceptionHandlerCount.incrementAndGet());
complete();
}
});
AtomicInteger responseExceptionHandlerCount = new AtomicInteger();
resp.exceptionHandler(err -> {
if (err instanceof HttpClosedException) {
assertEquals(1, responseExceptionHandlerCount.incrementAndGet());
complete();
}
});
resp.endHandler(v -> {
fail();
});
resp.closeHandler(v -> {
complete();
});
AtomicInteger closeHandlerCount = new AtomicInteger();
req.connection().closeHandler(v -> {
assertEquals(1, closeHandlerCount.incrementAndGet());
complete();
});
requestCount.incrementAndGet();
});
startServer(testAddress);
HttpClientRequest request = client.request(new RequestOptions(requestOptions).setMethod(PUT)).await();
request.setChunked(true);
request.writeHead();
assertWaitUntil(() -> requestCount.get() > 0);
HttpConnection connection = request.connection();
connection.close();
await();
}
@Test
public void testClientRequestExceptionHandlerCalledWhenConnectionClosed() throws Exception {
server.requestHandler(req -> {
req.handler(buff -> {
req.connection().close();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.onComplete(onSuccess(req -> {
req.setChunked(true);
req.exceptionHandler(err -> {
testComplete();
});
req.write("chunk");
}));
await();
}
@Test
public void testClientResponseExceptionHandlerCalledWhenConnectionClosed() throws Exception {
AtomicReference<HttpConnection> conn = new AtomicReference<>();
server.requestHandler(req -> {
conn.set(req.connection());
req.response().setChunked(true).write("chunk");
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
resp.handler(buff -> {
conn.get().close();
});
resp.exceptionHandler(atMostOnce(err -> {
testComplete();
}));
}));
}));
await();
}
@Test
public void testClientRequestExceptionHandlerCalledWhenRequestEnded() throws Exception {
waitFor(2);
server.requestHandler(req -> {
req.connection().close();
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(req -> {
req
.exceptionHandler(this::fail)
.send().onComplete(onFailure(err -> {
complete();
}));
try {
req.exceptionHandler(err -> fail());
fail();
} catch (Exception e) {
complete();
}
}));
await();
}
@Test
public void testDefaultStatus() throws Exception {
testStatusCode(-1, null);
}
@Test
public void testDefaultOther() throws Exception {
// Doesn't really matter which one we choose
testStatusCode(405, null);
}
@Test
public void testOverrideStatusMessage() throws Exception {
testStatusCode(404, "some message");
}
@Test
public void testOverrideDefaultStatusMessage() throws Exception {
testStatusCode(-1, "some other message");
}
private void testStatusCode(int code, String statusMessage) throws Exception {
server.requestHandler(req -> {
if (code != -1) {
req.response().setStatusCode(code);
}
if (statusMessage != null) {
req.response().setStatusMessage(statusMessage);
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions).compose(req -> req
.send()
.compose(resp -> {
int theCode;
if (code == -1) {
// Default code - 200
assertEquals(200, resp.statusCode());
theCode = 200;
} else {
theCode = code;
}
if (statusMessage != null && resp.version() == HttpVersion.HTTP_1_1) {
assertEquals(statusMessage, resp.statusMessage());
} else {
assertEquals(HttpResponseStatus.valueOf(theCode).reasonPhrase(), resp.statusMessage());
}
return resp.end();
})).onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testResponseTrailersPutAll() throws Exception {
testResponseTrailers(false);
}
@Test
public void testResponseTrailersPutIndividually() throws Exception {
testResponseTrailers(true);
}
private void testResponseTrailers(boolean individually) throws Exception {
MultiMap trailers = randomMultiMap(10);
server.requestHandler(req -> {
req.response().setChunked(true);
if (individually) {
for (Map.Entry<String, String> header : trailers) {
req.response().trailers().add(header.getKey(), header.getValue());
}
} else {
req.response().trailers().setAll(trailers);
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end().map(v -> resp.trailers());
}))
.onComplete(onSuccess(respTrailers -> {
assertEquals(trailers.size(), respTrailers.size());
for (Map.Entry<String, String> entry : trailers) {
assertEquals(entry.getValue(), respTrailers.get(entry.getKey()));
}
testComplete();
}));
await();
}
@Test
public void testResponseNoTrailers() throws Exception {
server.requestHandler(req -> {
req.response().setChunked(true);
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.compose(resp -> {
assertEquals(200, resp.statusCode());
return resp.end().map(v -> resp.trailers());
})).onComplete(onSuccess(trailers -> {
assertTrue(trailers.isEmpty());
testComplete();
}));
await();
}
@Test
public void testUseAfterServerResponseHeadSent() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.putHeader(HttpHeaders.CONTENT_LENGTH, "" + 128);
resp.write("01234567");
assertTrue(resp.headWritten());
assertIllegalStateException(() -> resp.setChunked(false));
assertIllegalStateException(() -> resp.setStatusCode(200));
assertIllegalStateException(() -> resp.setStatusMessage("OK"));
assertIllegalStateException(() -> resp.putHeader("foo", "bar"));
assertIllegalStateException(() -> resp.addCookie(Cookie.cookie("the_cookie", "wibble")));
assertIllegalStateException(() -> resp.removeCookie("the_cookie"));
testComplete();
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(HttpClientRequest::send));
await();
}
@Test
public void testUseAfterServerResponseSent() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
assertFalse(resp.ended());
resp.end();
assertTrue(resp.ended());
Buffer buff = Buffer.buffer();
assertIllegalStateException(() -> resp.drainHandler(v -> {}));
assertIllegalStateException(() -> resp.exceptionHandler(v -> {}));
assertIllegalStateException(() -> resp.setChunked(false));
assertIllegalStateException(() -> resp.setWriteQueueMaxSize(123));
assertIllegalStateException(() -> resp.writeQueueFull());
assertIllegalStateException(() -> resp.putHeader("foo", "bar"));
assertIllegalStateException(() -> resp.sendFile("a/a.txt"));
assertIllegalStateException(() -> resp.end());
assertIllegalStateException(() -> resp.end("foo"));
assertIllegalStateException(() -> resp.end(buff));
assertIllegalStateException(() -> resp.end("foo", "UTF-8"));
assertIllegalStateException(() -> resp.write(buff));
assertIllegalStateException(() -> resp.write("foo"));
assertIllegalStateException(() -> resp.write("foo", "UTF-8"));
assertIllegalStateException(() -> resp.write(buff));
assertIllegalStateException(() -> resp.sendFile("a/a.txt"));
assertIllegalStateException(() -> resp.end());
assertIllegalStateException(() -> resp.end("foo"));
assertIllegalStateException(() -> resp.end(buff));
assertIllegalStateException(() -> resp.end("foo", "UTF-8"));
assertIllegalStateException(() -> resp.write(buff));
assertIllegalStateException(() -> resp.write("foo"));
assertIllegalStateException(() -> resp.write("foo", "UTF-8"));
assertIllegalStateException(() -> resp.write(buff));
testComplete();
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(HttpClientRequest::send));
await();
}
@Test
public void testSetInvalidStatusMessage() throws Exception {
server.requestHandler(req -> {
try {
req.response().setStatusMessage("hello\nworld");
assertEquals(HttpVersion.HTTP_2, req.version());
} catch (IllegalArgumentException ignore) {
assertEquals(HttpVersion.HTTP_1_1, req.version());
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::end)
).onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testResponseBodyBufferAtEnd() throws Exception {
Buffer body = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.response().end(body);
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::body)
.expecting(that(buff -> assertEquals(body, buff))))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testResponseBodyWriteChunked() throws Exception {
testResponseBodyWrite(true);
}
@Test
public void testResponseBodyWriteNonChunked() throws Exception {
testResponseBodyWrite(false);
}
private void testResponseBodyWrite(boolean chunked) throws Exception {
Buffer body = Buffer.buffer();
int numWrites = 10;
int chunkSize = 100;
server.requestHandler(req -> {
assertFalse(req.response().headWritten());
if (chunked) {
req.response().setChunked(true);
} else {
req.response().headers().set("Content-Length", String.valueOf(numWrites * chunkSize));
}
assertFalse(req.response().headWritten());
for (int i = 0; i < numWrites; i++) {
Buffer b = TestUtils.randomBuffer(chunkSize);
body.appendBuffer(b);
req.response().write(b);
assertTrue(req.response().headWritten());
}
req.response().end();
assertTrue(req.response().headWritten());
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::body)
.expecting(that(buff -> assertEquals(body, buff))))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testResponseBodyWriteStringChunkedDefaultEncoding() throws Exception {
testResponseBodyWriteString(true, null);
}
@Test
public void testResponseBodyWriteStringChunkedUTF8() throws Exception {
testResponseBodyWriteString(true, "UTF-8");
}
@Test
public void testResponseBodyWriteStringChunkedUTF16() throws Exception {
testResponseBodyWriteString(true, "UTF-16");
}
@Test
public void testResponseBodyWriteStringNonChunkedDefaultEncoding() throws Exception {
testResponseBodyWriteString(false, null);
}
@Test
public void testResponseBodyWriteStringNonChunkedUTF8() throws Exception {
testResponseBodyWriteString(false, "UTF-8");
}
@Test
public void testResponseBodyWriteStringNonChunkedUTF16() throws Exception {
testResponseBodyWriteString(false, "UTF-16");
}
private void testResponseBodyWriteString(boolean chunked, String encoding) throws Exception {
String body = TestUtils.randomUnicodeString(1000);
Buffer bodyBuff;
if (encoding == null) {
bodyBuff = Buffer.buffer(body);
} else {
bodyBuff = Buffer.buffer(body, encoding);
}
server.requestHandler(req -> {
if (chunked) {
req.response().setChunked(true);
} else {
req.response().headers().set("Content-Length", String.valueOf(bodyBuff.length()));
}
if (encoding == null) {
req.response().write(body);
} else {
req.response().write(body, encoding);
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::body)
.expecting(that(buff -> assertEquals(body, encoding == null ? buff.toString() : buff.toString(encoding)))))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testResponseWrite() throws Exception {
Buffer body = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.response().setChunked(true);
req.response().write(body);
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::body)
.expecting(that(buff -> assertEquals(body, buff))))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void test100ContinueHandledAutomatically() throws Exception {
Buffer toSend = TestUtils.randomBuffer(1000);
server.close();
server = config.forServer().setHandle100ContinueAutomatically(true).create(vertx);
server.requestHandler(req -> {
req.bodyHandler(data -> {
assertEquals(toSend, data);
req.response().end();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT)).onComplete(onSuccess(req -> {
req
.response()
.onComplete(onSuccess(resp -> resp.endHandler(v -> testComplete())));
req.headers().set("Expect", "100-continue");
req.setChunked(true);
req.continueHandler(v -> {
req.write(toSend);
req.end();
});
req.writeHead();
}));
await();
}
@Test
public void test100ContinueHandledManually() throws Exception {
Buffer toSend = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
assertEquals("100-continue", req.getHeader("expect"));
req.response().writeContinue();
req.bodyHandler(data -> {
assertEquals(toSend, data);
req.response().end();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT)).onComplete(onSuccess(req -> {
req
.response().onComplete(onSuccess(resp -> {
resp.endHandler(v -> testComplete());
}));
req.headers().set("Expect", "100-continue");
req.setChunked(true);
req.continueHandler(v -> {
req.write(toSend);
req.end();
});
req.writeHead();
}));
await();
}
@Test
public void test100ContinueRejectedManually() throws Exception {
server.requestHandler(req -> {
req.response().setStatusCode(405).end();
req.bodyHandler(data -> {
fail("body should not be received");
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT)).onComplete(onSuccess(req -> {
req
.response().onComplete(onSuccess(resp -> {
assertEquals(405, resp.statusCode());
testComplete();
}));
req.headers().set("Expect", "100-continue");
req.setChunked(true);
req.continueHandler(v -> {
fail("should not be called");
});
req.writeHead();
}));
await();
}
@Test
public void test100ContinueTimeout() throws Exception {
waitFor(2);
server.requestHandler(req -> {
req.response().writeContinue();
});
client.close();
client = config.forClient().setIdleTimeout(Duration.ofSeconds(1)).create(vertx);
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.onComplete(onSuccess(req -> {
req
.putHeader("Expect", "100-continue")
.continueHandler(v -> complete())
.send()
.onComplete(onFailure(err -> complete()));
}));
await();
}
@Test
public void test103EarlyHints() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
req.pause();
resp.writeEarlyHints(Http1xHeaders.httpHeaders().add("wibble", "wibble-103-value"))
.onComplete(onSuccess(result -> {
req.resume();
resp.putHeader("wibble", "wibble-200-value");
req.bodyHandler(body -> {
assertEquals("request-body", body.toString());
resp.end("response-body");
});
}));
});
AtomicBoolean earlyHintsHandled = new AtomicBoolean();
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.onComplete(onSuccess(req -> {
req
.earlyHintsHandler(earlyHintsHeaders -> {
assertEquals("wibble-103-value", earlyHintsHeaders.get("wibble"));
earlyHintsHandled.set(true);
})
.send("request-body")
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals("wibble-200-value", resp.headers().get("wibble"));
resp.endHandler(v -> {
assertEquals("Early hints handle check", true, earlyHintsHandled.get());
testComplete();
}).bodyHandler(body -> assertEquals(body, Buffer.buffer("response-body")));
}));
}));
await();
}
@Test
public void testClientDrainHandler() throws Exception {
pausingServer(resumeFuture -> {
client.request(requestOptions).onComplete(onSuccess(req -> {
req.setChunked(true);
assertFalse(req.writeQueueFull());
req.setWriteQueueMaxSize(1000);
Buffer buff = TestUtils.randomBuffer(10000);
vertx.setPeriodic(1, id -> {
req.write(buff);
if (req.writeQueueFull()) {
vertx.cancelTimer(id);
req.drainHandler(v -> {
assertFalse(req.writeQueueFull());
testComplete();
});
// Tell the server to resume
resumeFuture.complete();
}
});
}));
});
await();
}
private void pausingServer(Consumer<Promise<Void>> consumer) throws Exception {
Promise<Void> resumeFuture = Promise.promise();
server.requestHandler(req -> {
req.response().setChunked(true);
req.pause();
Context ctx = vertx.getOrCreateContext();
resumeFuture.future().onComplete(v1 -> {
ctx.runOnContext(v2 -> {
req.resume();
});
});
req.handler(buff -> {
req.response().write(buff);
});
});
startServer(testAddress);
consumer.accept(resumeFuture);
}
@Test
public void testServerDrainHandler() throws Exception {
drainingServer(resumeFuture -> {
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> {
resp.pause();
resumeFuture.onComplete(ar -> resp.resume());
}));
});
await();
}
private void drainingServer(Consumer<Future<Void>> consumer) throws Exception {
Promise<Void> resumeFuture = Promise.promise();
server.requestHandler(req -> {
req.response().setChunked(true);
assertFalse(req.response().writeQueueFull());
req.response().setWriteQueueMaxSize(1000);
Buffer buff = TestUtils.randomBuffer(10000);
//Send data until the buffer is full
vertx.setPeriodic(1, id -> {
req.response().write(buff);
if (req.response().writeQueueFull()) {
vertx.cancelTimer(id);
req.response().drainHandler(v -> {
assertFalse(req.response().writeQueueFull());
testComplete();
});
// Tell the client to resume
resumeFuture.complete();
}
});
});
startServer(testAddress);
consumer.accept(resumeFuture.future());
}
@Test
public void testConnectInvalidPort() {
client.request(HttpMethod.GET, 9998, config.host(), DEFAULT_TEST_URI).onComplete(onFailure(err -> complete()));
await();
}
@Test
public void testConnectInvalidHost() {
client.request(HttpMethod.GET, 9998, "255.255.255.255", DEFAULT_TEST_URI).onComplete(onFailure(resp -> complete()));
await();
}
@Test
public void testSetHandlersAfterListening() throws Exception {
server.requestHandler(v -> {});
startServer(testAddress);
assertIllegalStateException(() -> server.requestHandler(v -> {}));
assertIllegalStateException(() -> server.webSocketHandler(v -> {}));
}
@Test
public void testListenNoHandlers() {
assertIllegalStateException(() -> server.listen().await());
}
@Test
public void testListenTwice() throws Exception {
server.requestHandler(v -> {});
startServer(testAddress);
assertIllegalStateException(() -> server.listen().await());
}
@Test
public void testHeadCanSetContentLength() throws Exception {
server.requestHandler(req -> {
assertEquals(HttpMethod.HEAD, req.method());
// Head never contains a body but it can contain a Content-Length header
// Since headers from HEAD must correspond EXACTLY with corresponding headers for GET
req.response().headers().set("Content-Length", String.valueOf(41));
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.HEAD))
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(resp -> resp.end().map(resp.headers().get("Content-Length"))))
.onComplete(onSuccess(contentLength -> {
assertEquals("41", contentLength);
testComplete();
}));
await();
}
@Test
public void testHeadDoesNotSetAutomaticallySetContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.HEAD, 200, HttpHeaders.headers());
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testHeadAllowsContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.HEAD, 200, HttpHeaders.set("content-length", "34"));
assertEquals("34", respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testHeadRemovesTransferEncodingHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.HEAD, 200, HttpHeaders.set("transfer-encoding", "chunked"));
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testNoContentRemovesContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 204, HttpHeaders.set("content-length", "34"));
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testNoContentRemovesTransferEncodingHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 204, HttpHeaders.set("transfer-encoding", "chunked"));
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testResetContentSetsContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 205, HttpHeaders.headers());
assertEquals("0", respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testResetContentRemovesTransferEncodingHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 205, HttpHeaders.set("transfer-encoding", "chunked"));
assertEquals("0", respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testNotModifiedDoesNotSetAutomaticallySetContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 304, HttpHeaders.headers());
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testNotModifiedAllowsContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 304, HttpHeaders.set("content-length", "34"));
assertEquals("34", respHeaders.get("Content-Length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void testNotModifiedRemovesTransferEncodingHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 304, HttpHeaders.set("transfer-encoding", "chunked"));
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void test1xxRemovesContentLengthHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 102, HttpHeaders.set("content-length", "34"));
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
@Test
public void test1xxRemovesTransferEncodingHeader() throws Exception {
MultiMap respHeaders = checkEmptyHttpResponse(HttpMethod.GET, 102, HttpHeaders.set("transfer-encoding", "chunked"));
assertNull(respHeaders.get("content-length"));
assertNull(respHeaders.get("transfer-encoding"));
}
protected MultiMap checkEmptyHttpResponse(HttpMethod method, int sc, MultiMap reqHeaders) throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setStatusCode(sc);
reqHeaders.remove("transfer-encoding");
resp.headers().addAll(reqHeaders);
resp.end();
});
startServer(testAddress);
try {
Future<MultiMap> result = client
.request(new RequestOptions(requestOptions).setMethod(method)).compose(req ->
req
.setFollowRedirects(false)
.send()
.compose(resp ->
resp.body().compose(body -> {
if (body.length() > 0) {
return Future.failedFuture(new Exception());
} else {
return Future.succeededFuture(resp.headers());
}
})
));
return result.await(20, TimeUnit.SECONDS);
} finally {
client.close();
}
}
@Test
public void testHeadHasNoContentLengthByDefault() throws Exception {
server.requestHandler(req -> {
assertEquals(HttpMethod.HEAD, req.method());
// By default HEAD does not have a content-length header
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.HEAD))
.compose(req -> req
.send()
.expecting(that(resp -> assertNull(resp.headers().get(HttpHeaders.CONTENT_LENGTH))))
.compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testHeadButCanSetContentLength() throws Exception {
server.requestHandler(req -> {
assertEquals(HttpMethod.HEAD, req.method());
// By default HEAD does not have a content-length header but it can contain a content-length header
// if explicitly set
req.response().putHeader(HttpHeaders.CONTENT_LENGTH, "41").end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.HEAD))
.compose(req -> req
.send()
.expecting(that(resp -> assertEquals("41", resp.headers().get(HttpHeaders.CONTENT_LENGTH))))
.compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> testComplete()));
await();
}
@Test
public void testRemoteAddress() throws Exception {
server.requestHandler(req -> {
if (testAddress.isInetSocket()) {
assertEquals("127.0.0.1", req.remoteAddress().host());
} else {
// Returns null for domain sockets
}
req.response().end();
});
startServer(testAddress);
client.request(requestOptions)
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::body))
.onComplete(onSuccess(req -> {
testComplete();
}));
await();
}
@Test
public void testGetAbsoluteURI() throws Exception {
server.requestHandler(req -> {
assertEquals(req.scheme() + "://" + config.host() + ":" + config.port() + "/foo/bar", req.absoluteURI());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI("/foo/bar"))
.compose(req -> req.send().compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testGetAbsoluteURIWithParam() throws Exception {
server.requestHandler(req -> {
assertEquals(req.scheme() + "://" + config.host() + ":" + config.port() + "/foo/bar?a=1", req.absoluteURI());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI("/foo/bar?a=1"))
.compose(req -> req.send().compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testGetAbsoluteURIWithUnsafeParam() throws Exception {
server.requestHandler(req -> {
assertEquals(req.scheme() + "://" + config.host() + ":" + config.port() + "/foo/bar?a={1}", req.absoluteURI());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI("/foo/bar?a={1}"))
.compose(req -> req.send().compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testGetAbsoluteURIWithOptionsServerLevel() throws Exception {
server.requestHandler(req -> {
assertEquals(OPTIONS, req.method());
assertNull(req.absoluteURI());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI("*").setMethod(OPTIONS))
.compose(req -> req.send().compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testGetAbsoluteURIWithAbsoluteRequestUri() throws Exception {
server.requestHandler(req -> {
assertEquals("http://www.w3.org/pub/WWW/TheProject.html", req.absoluteURI());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setURI("http://www.w3.org/pub/WWW/TheProject.html"))
.compose(req -> req.send().compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> {
testComplete();
}));
await();
}
@Test
public void testListenInvalidPort() throws Exception {
server.close();
ServerSocket occupied = null;
try{
/* Ask to be given a usable port, then use it exclusively so Vert.x can't use the port number */
occupied = new ServerSocket(0);
occupied.setReuseAddress(false);
server = createHttpServer(new HttpServerOptions().setPort(occupied.getLocalPort()));
server.requestHandler(v -> {}).listen().onComplete(onFailure(server -> testComplete()));
await();
}finally {
if( occupied != null ) {
occupied.close();
}
}
}
@Test
public void testListenInvalidHost() {
server.close();
server = createHttpServer(new HttpServerOptions().setPort(config.port()).setHost("iqwjdoqiwjdoiqwdiojwd"));
server.requestHandler(v -> {});
server.listen().onComplete(onFailure(s -> testComplete()));
await();
}
@Test
public void testPauseResumeClientResponseWontCallEndHandlePrematurely() throws Exception {
Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(8192));
server.requestHandler(req -> {
req.response().end(expected);
});
startServer(testAddress);
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
resp.bodyHandler(body -> {
assertEquals(expected, body);
testComplete();
});
// Check that pause resume won't call the end handler prematurely
resp.pause();
resp.resume();
}));
}));
await();
}
@Test
public void testPauseClientResponse() throws Exception {
int numWrites = 10;
int numBytes = 100;
server.requestHandler(req -> {
req.response().setChunked(true);
// Send back a big response in several chunks
for (int i = 0; i < numWrites; i++) {
req.response().write(TestUtils.randomBuffer(numBytes));
}
req.response().end();
});
startServer(testAddress);
AtomicBoolean paused = new AtomicBoolean();
Buffer totBuff = Buffer.buffer();
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
resp.pause();
paused.set(true);
resp.handler(chunk -> {
if (paused.get()) {
fail("Shouldn't receive chunks when paused");
} else {
totBuff.appendBuffer(chunk);
}
});
resp.endHandler(v -> {
if (paused.get()) {
fail("Shouldn't receive chunks when paused");
} else {
assertEquals(numWrites * numBytes, totBuff.length());
testComplete();
}
});
vertx.setTimer(500, id -> {
paused.set(false);
resp.resume();
});
}));
}));
await();
}
@Test
public void testDeliverPausedBufferWhenResume() throws Exception {
testDeliverPausedBufferWhenResume(block -> vertx.setTimer(10, id -> block.run()));
}
@Test
public void testDeliverPausedBufferWhenResumeOnOtherThread() throws Exception {
ExecutorService exec = Executors.newSingleThreadExecutor();
try {
testDeliverPausedBufferWhenResume(block -> exec.execute(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
fail(e);
Thread.currentThread().interrupt();
}
block.run();
}));
} finally {
exec.shutdown();
}
}
private void testDeliverPausedBufferWhenResume(Consumer<Runnable> scheduler) throws Exception {
Buffer data = TestUtils.randomBuffer(2048);
int num = 10;
waitFor(num);
List<CompletableFuture<Void>> resumes = Collections.synchronizedList(new ArrayList<>());
for (int i = 0;i < num;i++) {
resumes.add(new CompletableFuture<>());
}
server.requestHandler(req -> {
int idx = Integer.parseInt(req.path().substring(1));
HttpServerResponse resp = req.response();
resumes.get(idx).thenAccept(v -> {
resp.end();
});
resp.setChunked(true).write(data);
});
startServer(testAddress);
client.close();
client = config.forClient().create(vertx, new PoolOptions().setHttp1MaxSize(1));
for (int i = 0;i < num;i++) {
int idx = i;
client.request(new RequestOptions(requestOptions).setURI("/" + i)).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
Buffer body = Buffer.buffer();
Thread t = Thread.currentThread();
resp.handler(buff -> {
assertSame(t, Thread.currentThread());
resumes.get(idx).complete(null);
body.appendBuffer(buff);
});
resp.endHandler(v -> {
// assertEquals(data, body);
complete();
});
resp.pause();
scheduler.accept(resp::resume);
}));
}));
}
await();
}
@Test
public void testClearPausedBuffersWhenResponseEnds() throws Exception {
Buffer data = TestUtils.randomBuffer(20);
int num = 10;
waitFor(num);
server.requestHandler(req -> {
req.response().end(data);
});
startServer(testAddress);
client.close();
client = config.forClient().create(vertx, new PoolOptions().setHttp1MaxSize(1));
for (int i = 0;i < num;i++) {
client.request(requestOptions)
.compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(resp -> Future.future(promise -> {
resp.bodyHandler(buff -> {
assertEquals(data, buff);
promise.complete();
});
resp.pause();
vertx.setTimer(10, id -> {
resp.resume();
});
}))).onComplete(onSuccess(v -> complete()));
}
await();
}
@Test
public void testPausedHttpServerRequest() throws Exception {
CompletableFuture<Void> resumeCF = new CompletableFuture<>();
Buffer expected = Buffer.buffer();
server.requestHandler(req -> {
req.pause();
AtomicBoolean paused = new AtomicBoolean(true);
Buffer body = Buffer.buffer();
req.handler(buff -> {
assertFalse(paused.get());
body.appendBuffer(buff);
});
resumeCF.thenAccept(v -> {
paused.set(false);
req.resume();
});
req.endHandler(v -> {
assertEquals(expected, body);
req.response().end();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT))
.onComplete(onSuccess(req -> {
req
.setChunked(true)
.response().onComplete(onSuccess(resp -> {
resp.endHandler(v -> {
testComplete();
});
}));
while (!req.writeQueueFull()) {
Buffer buff = Buffer.buffer(TestUtils.randomAlphaString(1024));
expected.appendBuffer(buff);
req.write(buff);
}
resumeCF.complete(null);
req.end();
}));
await();
}
@Test
public void testHttpServerRequestPausedDuringLastChunk1() throws Exception {
testHttpServerRequestPausedDuringLastChunk(false);
}
@Test
public void testHttpServerRequestPausedDuringLastChunk2() throws Exception {
testHttpServerRequestPausedDuringLastChunk(true);
}
private void testHttpServerRequestPausedDuringLastChunk(boolean fetching) throws Exception {
server.requestHandler(req -> {
AtomicBoolean ended = new AtomicBoolean();
AtomicBoolean paused = new AtomicBoolean();
req.handler(buff -> {
assertEquals("small", buff.toString());
req.pause();
paused.set(true);
vertx.setTimer(20, id -> {
assertFalse(ended.get());
paused.set(false);
if (fetching) {
req.fetch(1);
} else {
req.resume();
}
});
});
req.endHandler(v -> {
assertFalse(paused.get());
ended.set(true);
req.response().end();
});
});
startServer(testAddress);
client.close();
client = createHttpClient(new PoolOptions().setHttp1MaxSize(1));
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.PUT)).onComplete(onSuccess(req -> {
req
.send(Buffer.buffer("small")).onComplete(onSuccess(resp -> {
complete();
}));
}));
await();
}
@Test
public void testHttpClientResponsePausedDuringLastChunk1() throws Exception {
testHttpClientResponsePausedDuringLastChunk(false);
}
@Test
public void testHttpClientResponsePausedDuringLastChunk2() throws Exception {
testHttpClientResponsePausedDuringLastChunk(true);
}
private void testHttpClientResponsePausedDuringLastChunk(boolean fetching) throws Exception {
server.requestHandler(req -> {
req.response().end("small");
});
startServer(testAddress);
client.close();
client = createHttpClient(new PoolOptions().setHttp1MaxSize(1));
client.request(requestOptions).onComplete(onSuccess(req -> {
req.send().onComplete(onSuccess(resp -> {
AtomicBoolean ended = new AtomicBoolean();
AtomicBoolean paused = new AtomicBoolean();
resp.handler(buff -> {
assertEquals("small", buff.toString());
resp.pause();
paused.set(true);
vertx.setTimer(20, id -> {
assertFalse(ended.get());
paused.set(false);
if (fetching) {
resp.fetch(1);
} else {
resp.resume();
}
});
});
resp.endHandler(v -> {
assertFalse(paused.get());
ended.set(true);
complete();
});
}));
}));
await();
}
@Test
public void testHostHeaderOverridePossible() throws Exception {
server.requestHandler(req -> {
assertEquals("localhost", req.authority().host());
assertEquals(4444, req.authority().port());
req.response().end();
});
startServer(testAddress);
client.request(new RequestOptions().setServer(testAddress).setHost("localhost").setPort(4444))
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> testComplete()));
await();
}
@Test
public void testResponseBodyWriteFixedString() throws Exception {
String body = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
Buffer bodyBuff = Buffer.buffer(body);
server.requestHandler(req -> {
req.response().setChunked(true);
req.response().write(body);
req.response().end();
});
startServer(testAddress);
client.request(requestOptions).compose(req -> req
.send()
.expecting(HttpResponseExpectation.SC_OK)
.compose(HttpClientResponse::body))
.onComplete(onSuccess(buff -> {
assertEquals(bodyBuff, buff);
testComplete();
}));
await();
}
@Test
public void testClientMultiThreaded() throws Exception {
int numThreads = 10;
Thread[] threads = new Thread[numThreads];
CountDownLatch latch = new CountDownLatch(numThreads);
server.requestHandler(req -> {
req.response().putHeader("count", req.headers().get("count"));
req.response().end();
});
startServer(testAddress);
for (int i = 0; i < numThreads; i++) {
int index = i;
threads[i] = new Thread() {
public void run() {
client.request(requestOptions)
.compose(req -> req.putHeader("count", String.valueOf(index)).send())
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(String.valueOf(index), resp.headers().get("count"));
latch.countDown();
}));
}
};
threads[i].start();
}
awaitLatch(latch);
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
}
@Test
public void testWorkerServer() throws Exception {
int numReq = 5; // 5 == the HTTP/1 pool max size
waitFor(numReq);
AtomicBoolean owner = new AtomicBoolean();
CountDownLatch latch = new CountDownLatch(1);
AtomicInteger connCount = new AtomicInteger();
vertx.deployVerticle(() -> new AbstractVerticle() {
@Override
public void start(Promise<Void> startPromise) {
createHttpServer()
.requestHandler(req -> {
Context current = Vertx.currentContext();
assertTrue(current.isWorkerContext());
assertSameEventLoop(context, current);
try {
assertTrue(owner.compareAndSet(false, true));
Thread.sleep(200);
} catch (Exception e) {
fail(e);
} finally {
owner.set(false);
}
req.response().end("pong");
}).connectionHandler(conn -> {
Context current = Vertx.currentContext();
// Not great but works for now
if (server instanceof HttpServerImpl) {
assertTrue(Context.isOnEventLoopThread());
assertTrue(current.isEventLoopContext());
assertNotSame(context, current);
}
connCount.incrementAndGet(); // No complete here as we may have 1 or 5 connections depending on the protocol
}).listen(testAddress)
.<Void>mapEmpty()
.onComplete(startPromise);
}
}, new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER))
.onComplete(onSuccess(id -> latch.countDown()));
awaitLatch(latch);
for (int i = 0;i < numReq;i++) {
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(
onSuccess(resp -> {
complete();
}));
}
await();
assertTrue(connCount.get() > 0);
}
@Test
public void testInWorker() throws Exception {
vertx.deployVerticle(new AbstractVerticle() {
@Override
public void start() throws Exception {
assertTrue(Vertx.currentContext().isWorkerContext());
assertTrue(Context.isOnWorkerThread());
HttpServer server = createHttpServer();
server.requestHandler(req -> {
assertTrue(Vertx.currentContext().isWorkerContext());
assertTrue(Context.isOnWorkerThread());
Buffer buf = Buffer.buffer();
req.handler(buf::appendBuffer);
req.endHandler(v -> {
assertEquals("hello", buf.toString());
req.response().end("bye");
});
}).listen(testAddress).onComplete(onSuccess(s -> {
assertTrue(Vertx.currentContext().isWorkerContext());
assertTrue(Context.isOnWorkerThread());
client.close();
client = createHttpClient();
client.request(new RequestOptions(requestOptions).setMethod(PUT)).onComplete(onSuccess(req -> {
req.send(Buffer.buffer("hello"))
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertTrue(Vertx.currentContext().isWorkerContext());
assertTrue(Context.isOnWorkerThread());
resp.handler(buf -> {
assertEquals("bye", buf.toString());
resp.endHandler(v -> {
testComplete();
});
});
}));
}));
}));
}
}, new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER));
await();
}
@Test
public void testClientReadStreamInWorker() throws Exception {
int numReq = 16;
waitFor(numReq);
Buffer body = Buffer.buffer(randomAlphaString(512 * 1024));
vertx.deployVerticle(new AbstractVerticle() {
@Override
public void start(Promise<Void> startPromise) {
HttpServer server = createHttpServer();
server.requestHandler(req -> {
req.response().end(body);
}).listen(testAddress)
.<Void>mapEmpty()
.onComplete(startPromise);
}
})
.await(20, TimeUnit.SECONDS);
vertx.deployVerticle(new AbstractVerticle() {
HttpClient client;
@Override
public void start(Promise<Void> startPromise) {
client = createHttpClient(new PoolOptions().setHttp1MaxSize(1));
for (int i = 0; i < numReq; i++) {
client.request(requestOptions)
.compose(req -> req
.send()
.compose(resp -> {
resp.pause();
vertx.setTimer(250, id -> {
resp.resume();
});
return resp.end();
}))
.onComplete(onSuccess(v -> complete()));
}
}
}, new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER));
await();
}
@Repeat(times = 16)
@Test
public void testServerReadStreamInWorker() throws Exception {
int numReq = 1;
waitFor(numReq);
Buffer body = Buffer.buffer(randomAlphaString(512 * 1024));
vertx.deployVerticle(new AbstractVerticle() {
@Override
public void start(Promise<Void> startPromise) {
HttpServer server = createHttpServer();
server.requestHandler(req -> {
req.end().onComplete(onSuccess(v -> {
req.response().end();
}));
req.pause();
vertx.setTimer(10, id -> {
req.resume();
});
}).listen(testAddress)
.<Void>mapEmpty()
.onComplete(startPromise);
}
}, new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER))
.await(20, TimeUnit.SECONDS);
vertx.deployVerticle(new AbstractVerticle() {
HttpClient client;
@Override
public void start(Promise<Void> startPromise) {
client = createHttpClient(new PoolOptions().setHttp1MaxSize(1));
for (int i = 0; i < numReq; i++) {
client.request(requestOptions).
compose(req -> req
.send(body)
.compose(HttpClientResponse::end))
.onComplete(onSuccess(v -> complete()));
}
}
});
await();
}
@Test
public void testMultipleServerClose() {
this.server = createHttpServer();
// We assume the endHandler and the close completion handler are invoked in the same context task
ThreadLocal stack = new ThreadLocal();
stack.set(true);
server.close().onComplete(ar1 -> {
assertNull(stack.get());
assertTrue(Vertx.currentContext().isEventLoopContext());
server.close().onComplete(ar2 -> {
server.close().onComplete(ar3 -> {
testComplete();
});
});
});
await();
}
@Test
public void testRequestEnded() throws Exception {
server.requestHandler(req -> {
assertFalse(req.isEnded());
req.endHandler(v -> {
assertTrue(req.isEnded());
try {
req.endHandler(v2 -> {});
fail("Shouldn't be able to set end handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.setExpectMultipart(true);
fail("Shouldn't be able to set expect multipart");
} catch (IllegalStateException e) {
// OK
}
try {
req.bodyHandler(v2 -> {
});
fail("Shouldn't be able to set body handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.handler(v2 -> {
});
fail("Shouldn't be able to set handler");
} catch (IllegalStateException e) {
// OK
}
req.response().setStatusCode(200).end();
});
});
startServer(testAddress);
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
await();
}
@Test
public void testRequestEndedNoEndHandler() throws Exception {
server.requestHandler(req -> {
assertFalse(req.isEnded());
req.response().setStatusCode(200).end();
vertx.setTimer(500, v -> {
assertTrue(req.isEnded());
try {
req.endHandler(v2 -> {
});
fail("Shouldn't be able to set end handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.setExpectMultipart(true);
fail("Shouldn't be able to set expect multipart");
} catch (IllegalStateException e) {
// OK
}
try {
req.bodyHandler(v2 -> {
});
fail("Shouldn't be able to set body handler");
} catch (IllegalStateException e) {
// OK
}
try {
req.handler(v2 -> {
});
fail("Shouldn't be able to set handler");
} catch (IllegalStateException e) {
// OK
}
testComplete();
});
});
startServer(testAddress);
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
}));
await();
}
@Test
public void testAbsoluteURIServer() throws Exception {
server.requestHandler(req -> {
String absURI = req.absoluteURI();
assertEquals(req.scheme() + "://" + config.host() + ":" + config.port() + "/path", absURI);
req.response().end();
});
startServer(testAddress);
String path = "/path";
client.request(new RequestOptions(requestOptions).setURI(path))
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
await();
}
@Test
public void testDumpManyRequestsOnQueue() throws Exception {
int sendRequests = 10000;
AtomicInteger receivedRequests = new AtomicInteger();
client.close();
client = config.forClient().create(vertx);
server.requestHandler(r-> {
r.response().end();
if (receivedRequests.incrementAndGet() == sendRequests) {
testComplete();
}
});
startServer(testAddress);
IntStream.range(0, sendRequests)
.forEach(x -> client.request(requestOptions).compose(HttpClientRequest::send));
await();
}
@Test
public void testOtherMethodRequest() throws Exception {
server.requestHandler(r -> {
assertEquals("COPY", r.method().name());
r.response().end();
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.valueOf("COPY")))
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> testComplete()));
await();
}
@Test
public void testClientGlobalConnectionHandler() throws Exception {
waitFor(2);
server.requestHandler(req -> {
req.response().end();
});
startServer(testAddress);
ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
client.close();
client = httpClientBuilder()
.withConnectHandler(conn -> {
assertSame(ctx.nettyEventLoop(), ((ContextInternal)Vertx.currentContext()).nettyEventLoop());
complete();
})
.build();
ctx.runOnContext(v -> {
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(resp -> complete());
});
await();
}
@Test
public void testServerConnectionHandler() throws Exception {
AtomicInteger status = new AtomicInteger();
AtomicReference<HttpConnection> connRef = new AtomicReference<>();
Context serverCtx = vertx.getOrCreateContext();
server.connectionHandler(conn -> {
assertSameEventLoop(serverCtx, Vertx.currentContext());
assertEquals(0, status.getAndIncrement());
assertNull(connRef.getAndSet(conn));
});
server.requestHandler(req -> {
assertEquals(1, status.getAndIncrement());
assertSame(connRef.get(), req.connection());
req.response().end();
});
startServer(testAddress, serverCtx, server);
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(resp -> testComplete());
await();
}
@Test
public void testServerConnectionHandlerClose() throws Exception {
waitFor(2);
Context serverCtx = vertx.getOrCreateContext();
server.connectionHandler(conn -> {
conn.close();
conn.closeHandler(v -> complete());
});
server.requestHandler(req -> {
});
startServer(testAddress, serverCtx, server);
client.close();
client = httpClientBuilder()
.withConnectHandler(conn -> {
conn.closeHandler(v -> {
complete();
});
})
.build();
client.request(requestOptions).compose(HttpClientRequest::send);
await();
}
@Test
public void testClientConnectionClose() throws Exception {
// Test client connection close + server close handler
Promise<Void> latch = Promise.promise();
server.requestHandler(req -> {
AtomicInteger len = new AtomicInteger();
req.handler(buff -> {
if (len.addAndGet(buff.length()) == 1024) {
latch.complete();
}
});
req.connection().closeHandler(v -> {
testComplete();
});
});
startServer(testAddress);
client.request(new RequestOptions(requestOptions).setMethod(HttpMethod.POST)).onComplete(onSuccess(req -> {
req
.setChunked(true)
.write(TestUtils.randomBuffer(1024));
latch.future().onComplete(onSuccess(v -> {
req.connection().close();
}));
}));
await();
}
@Test
public void testServerConnectionClose() throws Exception {
// Test server connection close + client close handler
waitFor(2);
server.requestHandler(req -> {
req.connection().close();
});
startServer(testAddress);
client.close();
client = httpClientBuilder()
.withConnectHandler(conn -> {
conn.closeHandler(v -> {
complete();
});
})
.build();
client.request(requestOptions)
.compose(HttpClientRequest::send)
.onComplete(onFailure(req -> complete()));
await();
}
@Test
public void testNoLogging() throws Exception {
TestLoggerFactory factory = testLogging();
assertFalse(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger"));
}
@Test
public void testServerLogging() throws Exception {
server.close();
server = config.forServer().setLogActivity(true).create(vertx);
TestLoggerFactory factory = testLogging();
if (this instanceof Http1xTest) {
assertTrue(factory.hasName("io.netty.handler.logging.LoggingHandler"));
} else {
assertTrue(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger"));
}
}
@Test
public void testClientLogging() throws Exception {
client.close();
client = config.forClient().setLogActivity(true).create(vertx);
TestLoggerFactory factory = testLogging();
if (this instanceof Http1xTest) {
assertTrue(factory.hasName("io.netty.handler.logging.LoggingHandler"));
} else {
assertTrue(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger"));
}
}
@Test
public void testClientLocalAddress() throws Exception {
String expectedAddress = TestUtils.loopbackAddress();
client.close();
client = config.forClient().setLocalAddress(expectedAddress).create(vertx);
server.requestHandler(req -> {
assertEquals(expectedAddress, req.remoteAddress().host());
req.response().end();
});
startServer(testAddress);
client.request(HttpMethod.GET, config.port(), config.host(), "/somepath")
.compose(HttpClientRequest::send)
.onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
await();
}
@Test
public void testFollowRedirectGetOn301() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 301, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectPostOn301() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 301, 301, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectPutOn301() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 301, 301, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectGetOn302() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 302, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectPostOn302() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 302, 302, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectPutOn302() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 302, 302, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectGetOn303() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 303, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectPostOn303() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 303, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectPutOn303() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 303, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectNotOn304() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 304, 304, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectGetOn307() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 307, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectPostOn307() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.POST, 307, 307, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectPutOn307() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.PUT, 307, 307, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectWithRelativeLocation() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 301, 200, 2, "/another", "http://" + config.host() + ":" + config.port() + "/another");
}
@Test
public void testFollowRedirectGetOn308() throws Exception {
testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 308, 200, 2, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/redirected");
}
@Test
public void testFollowRedirectPostOn308() throws Exception {
testFollowRedirect(HttpMethod.POST, HttpMethod.POST, 308, 308, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
@Test
public void testFollowRedirectPutOn308() throws Exception {
testFollowRedirect(HttpMethod.PUT, HttpMethod.PUT, 308, 308, 1, "http://" + config.host() + ":" + config.port() + "/redirected", "http://" + config.host() + ":" + config.port() + "/somepath");
}
private void testFollowRedirect(
HttpMethod method,
HttpMethod expectedMethod,
int statusCode,
int expectedStatus,
int expectedRequests,
String location,
String expectedURI) throws Exception {
AtomicInteger numRequests = new AtomicInteger();
Buffer expectedBody = Buffer.buffer(TestUtils.randomAlphaString(256));
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
if (numRequests.getAndIncrement() == 0) {
resp.setStatusCode(statusCode);
String s;
if (req.connection().isSsl() && location.startsWith("http://")) {
s = "https://" + location.substring("http://".length());
} else {
s = location;
}
if (s != null) {
resp.putHeader(HttpHeaders.LOCATION, s);
}
resp.end();
} else {
String t;
if (req.connection().isSsl() && expectedURI.startsWith("http://")) {
t = "https://" + expectedURI.substring("http://".length());
} else {
t = expectedURI;
}
assertEquals(t, req.absoluteURI());
assertEquals("foo_value", req.getHeader("foo"));
assertEquals(expectedMethod, req.method());
resp.end(expectedBody);
}
});
startServer(testAddress);
client.request(
new RequestOptions(requestOptions)
.setServer(null)
.setMethod(method)
.setURI("/somepath")
)
.compose(req -> req
.putHeader("foo", "foo_value")
.setFollowRedirects(true)
.send()
.compose(resp -> {
String t;
if (req.connection().isSsl() && expectedURI.startsWith("http://")) {
t = "https://" + expectedURI.substring("http://".length());
} else {
t = expectedURI;
}
assertEquals(resp.request().absoluteURI(), t);
assertEquals(expectedRequests, numRequests.get());
assertEquals(expectedStatus, resp.statusCode());
return resp.body().compose(body -> {
if (resp.statusCode() == 200) {
assertEquals(expectedBody, body);
} else {
assertEquals(Buffer.buffer(), body);
}
return Future.succeededFuture();
});
})
).onSuccess(v -> testComplete());
await();
}
@Test
public void testFollowRedirectWithBody() throws Exception {
testFollowRedirectWithBody(Function.identity());
}
@Test
public void testFollowRedirectWithPaddedBody() throws Exception {
testFollowRedirectWithBody(buff -> TestUtils.leftPad(1, buff));
}
private void testFollowRedirectWithBody(Function<Buffer, Buffer> translator) throws Exception {
Buffer expected = TestUtils.randomBuffer(2048);
AtomicBoolean redirected = new AtomicBoolean();
server.requestHandler(req -> {
if (redirected.compareAndSet(false, true)) {
assertEquals(HttpMethod.PUT, req.method());
req.bodyHandler(body -> {
assertEquals(body, expected);
String scheme = req.connection().isSsl() ? "https" : "http";
req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://" + config.host() + ":" + config.port() + "/whatever").end();
});
} else {
assertEquals(HttpMethod.GET, req.method());
assertNull(req.getHeader(HttpHeaders.CONTENT_LENGTH));
req.response().end();
}
});
startServer(testAddress);
client.request(new RequestOptions()
.setMethod(HttpMethod.PUT)
.setHost(config.host())
.setPort(config.port())
)
.onComplete(onSuccess(req -> {
req.setFollowRedirects(true);
req.send(translator.apply(expected)).onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
}));
await();
}
@Test
public void testFollowRedirectHappensAfterResponseIsReceived() throws Exception {
AtomicBoolean redirected = new AtomicBoolean();
AtomicBoolean sent = new AtomicBoolean();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
if (redirected.compareAndSet(false, true)) {
String scheme = req.connection().isSsl() ? "https" : "http";
resp
.setStatusCode(303)
.putHeader(HttpHeaders.CONTENT_LENGTH, "11")
.putHeader(HttpHeaders.LOCATION, scheme + "://" + config.host() + ":" + config.port() + "/whatever")
.write("hello ");
vertx.setTimer(500, id -> {
sent.set(true);
resp.end("world");
});
} else {
assertTrue(sent.get());
resp.end();
}
});
startServer(testAddress);
client.request(new RequestOptions()
.setMethod(HttpMethod.PUT)
.setHost(config.host())
.setPort(config.port())
)
.onComplete(onSuccess(req -> {
req.setFollowRedirects(true);
req.send().onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
}));
await();
}
@Test
public void testFollowRedirectWithChunkedBody() throws Exception {
Buffer buff1 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer buff2 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer expected = Buffer.buffer().appendBuffer(buff1).appendBuffer(buff2);
AtomicBoolean redirected = new AtomicBoolean();
Promise<Void> latch = Promise.promise();
server.requestHandler(req -> {
boolean redirect = redirected.compareAndSet(false, true);
if (redirect) {
latch.complete();
}
if (redirect) {
assertEquals(HttpMethod.PUT, req.method());
req.bodyHandler(body -> {
assertEquals(body, expected);
String scheme = req.connection().isSsl() ? "https" : "http";
req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://" + config.host() + ":" + config.port() + "/whatever").end();
});
} else {
assertEquals(HttpMethod.GET, req.method());
req.response().end();
}
});
startServer(testAddress);
client.request(new RequestOptions()
.setMethod(HttpMethod.PUT)
.setHost(config.host())
.setPort(config.port())
.setURI(DEFAULT_TEST_URI)
)
.onComplete(onSuccess(req -> {
req.setFollowRedirects(true);
req.setChunked(true);
req.write(buff1);
latch.future().onSuccess(v -> {
req.end(buff2);
});
req.response().onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
}));
await();
}
@Test
public void testFollowRedirectWithRequestNotEnded() throws Exception {
testFollowRedirectWithRequestNotEnded(false);
}
@Test
public void testFollowRedirectWithRequestNotEndedFailing() throws Exception {
testFollowRedirectWithRequestNotEnded(true);
}
private void testFollowRedirectWithRequestNotEnded(boolean expectFail) throws Exception {
Buffer buff1 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer buff2 = Buffer.buffer(TestUtils.randomAlphaString(2048));
Buffer expected = Buffer.buffer().appendBuffer(buff1).appendBuffer(buff2);
AtomicBoolean redirected = new AtomicBoolean();
Promise<Void> latch = Promise.promise();
server.requestHandler(req -> {
boolean redirect = redirected.compareAndSet(false, true);
if (redirect) {
Buffer body = Buffer.buffer();
req.handler(buff -> {
if (body.length() == 0) {
HttpServerResponse resp = req.response();
String scheme = req.connection().isSsl() ? "https" : "http";
resp.setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://" + config.host() + ":" + config.port() + "/whatever");
if (expectFail) {
resp
.setChunked(true)
.write("whatever")
.onComplete(onSuccess(v -> req.response().reset()));
} else {
resp.end();
}
latch.complete();
}
body.appendBuffer(buff);
});
req.endHandler(v -> {
assertEquals(expected, body);
});
} else {
req.response().end();
}
});
startServer(testAddress);
AtomicBoolean called = new AtomicBoolean();
client.request(new RequestOptions(requestOptions)
.setMethod(HttpMethod.PUT)).onComplete(onSuccess(req -> {
req.response().onComplete(ar -> {
assertEquals(expectFail, ar.failed());
if (ar.succeeded()) {
HttpClientResponse resp = ar.result();
assertEquals(200, resp.statusCode());
testComplete();
} else {
if (called.compareAndSet(false, true)) {
testComplete();
}
}
});
latch.future().onComplete(onSuccess(v -> {
// Wait so we end the request while having received the server response (but we can't be notified)
if (!expectFail) {
vertx.setTimer(500, id -> {
req.end(buff2);
});
}
}));
req
.setFollowRedirects(true)
.setChunked(true)
.write(buff1);
}));
await();
}
@Test
public void testFollowRedirectwriteHeadThenBody() throws Exception {
Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(2048));
AtomicBoolean redirected = new AtomicBoolean();
server.requestHandler(req -> {
if (redirected.compareAndSet(false, true)) {
assertEquals(HttpMethod.PUT, req.method());
req.bodyHandler(body -> {
assertEquals(body, expected);
req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, "/whatever").end();
});
} else {
assertEquals(HttpMethod.GET, req.method());
req.response().end();
}
});
startServer(testAddress);
client.request(new RequestOptions()
.setMethod(HttpMethod.PUT)
.setHost(config.host())
.setPort(config.port())
.setURI("/somepath")
).onComplete(onSuccess(req -> {
req
.setFollowRedirects(true)
.putHeader("Content-Length", "" + expected.length())
.response().onComplete(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}));
req.writeHead().onComplete(onSuccess(v -> {
req.end(expected);
}));
}));
await();
}
@Test
public void testFollowRedirectLimit() throws Exception {
assumeTrue(testAddress.isInetSocket());
AtomicInteger numberOfRequests = new AtomicInteger();
server.requestHandler(req -> {
int val = numberOfRequests.incrementAndGet();
if (val > 17) {
fail();
} else {
String scheme = req.connection().isSsl() ? "https" : "http";
req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://" + config.host() + ":" + config.port() + "/otherpath").end();
}
});
startServer(testAddress);
client.request(requestOptions)
.onComplete(onSuccess(req -> {
req.setFollowRedirects(true);
req.send().onComplete(onSuccess(resp -> {
assertEquals(17, numberOfRequests.get());
assertEquals(301, resp.statusCode());
assertEquals("/otherpath", resp.request().path());
testComplete();
}));
}));
await();
}
@Test
public void testFollowRedirectPropagatesTimeout() throws Exception {
assumeTrue(testAddress.isInetSocket());
AtomicInteger redirections = new AtomicInteger();
server.requestHandler(req -> {
switch (redirections.getAndIncrement()) {
case 0:
String scheme = req.connection().isSsl() ? "https" : "http";
req.response().setStatusCode(307).putHeader(HttpHeaders.LOCATION, scheme + "://" + config.host() + ":" + config.port() + "/whatever").end();
break;
}
});
startServer(testAddress);
AtomicBoolean done = new AtomicBoolean();
client.request(new RequestOptions(requestOptions)
.setIdleTimeout(500)).onComplete(onSuccess(req -> {
req
.setFollowRedirects(true)
.send()
.onComplete(onFailure(t -> {
if (done.compareAndSet(false, true)) {
assertEquals(2, redirections.get());
testComplete();
}
}));
}));
await();
}
@Test
public void testFollowRedirectHost() throws Exception {
waitFor(2);
int port = config.port() + 1;
AtomicInteger redirects = new AtomicInteger();
server.requestHandler(req -> {
redirects.incrementAndGet();
req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, req.scheme() + "://localhost:" + (server.actualPort() + 1) + "/whatever").end();
});
startServer(testAddress);
HttpServer server2 = createHttpServer();
server2.requestHandler(req -> {
assertEquals(1, redirects.get());
assertEquals(req.scheme() + "://localhost:" + port + "/whatever", req.absoluteURI());
req.response().end();
complete();
});
startServer(SocketAddress.inetSocketAddress(port, testAddress.host()), server2);
client.request(requestOptions)
.compose(req -> req
.setFollowRedirects(true)
// .setAuthority("localhost:" + options.getPort())
.send()
)
.onComplete(onSuccess(resp -> {
String scheme = resp.request().connection().isSsl() ? "https" : "http";
assertEquals(scheme + "://localhost:" + port + "/whatever", resp.request().absoluteURI());
complete();
}));
await();
}
@Test
public void testFollowRedirectWithCustomHandler() throws Exception {
waitFor(2);
int basePort = config.port();
SocketAddress redirectedServerAddress = SocketAddress.inetSocketAddress(basePort + 1, testAddress.host());
AtomicInteger redirects = new AtomicInteger();
server.requestHandler(req -> {
redirects.incrementAndGet();
req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, req.scheme() + "://localhost:" + (server.actualPort() + 1) + "/whatever").end();
});
startServer(testAddress);
HttpServer redirectedServer = createHttpServer();
redirectedServer.requestHandler(req -> {
assertEquals(1, redirects.get());
assertEquals(req.scheme() + "://localhost:" + redirectedServerAddress.port() + "/custom", req.absoluteURI());
req.response().end();
complete();
});
startServer(redirectedServerAddress, redirectedServer);
Context ctx = vertx.getOrCreateContext();
client.close();
client = httpClientBuilder()
.withRedirectHandler(resp -> {
assertEquals(ctx, Vertx.currentContext());
Promise<RequestOptions> fut = Promise.promise();
vertx.setTimer(25, id -> {
fut.complete(new RequestOptions().setAbsoluteURI((resp.request().connection().isSsl() ? "https" : "http") + "://localhost:" + redirectedServerAddress.port() + "/custom"));
});
return fut.future();
})
.build();
ctx.runOnContext(v -> {
client.request(new RequestOptions()
.setHost(config.host())
.setPort(config.port())).onComplete(onSuccess(req -> {
req.setFollowRedirects(true);
req.putHeader("foo", "foo_value");
req
.send()
.onComplete(onSuccess(resp -> {
assertEquals((req.connection().isSsl() ? "https" : "http") + "://localhost:" + redirectedServerAddress.port() + "/custom", resp.request().absoluteURI());
complete();
}));
}));
});
await();
}
@Test
public void testDefaultRedirectHandler() throws Exception {
testFoo("http://example.com", "http://example.com");
testFoo("http://example.com/somepath", "http://example.com/somepath");
testFoo("http://example.com:8000", "http://example.com:8000");
testFoo("http://example.com:8000/somepath", "http://example.com:8000/somepath");
testFoo("https://example.com", "https://example.com");
testFoo("https://example.com/somepath", "https://example.com/somepath");
testFoo("https://example.com:8000", "https://example.com:8000");
testFoo("https://example.com:8000/somepath", "https://example.com:8000/somepath");
testFoo("whatever://example.com", null);
testFoo("http://", null);
testFoo("http://:" + config.host() + ":" + config.port() + "/somepath", null);
}
private void testFoo(String location, String expectedAbsoluteURI) throws Exception {
int status = 301;
MultiMap headers = HttpHeaders.headers().add(HttpHeaders.LOCATION.toString(), location);
HttpMethod method = HttpMethod.GET;
String baseURI = "https://" + config.host() + ":" + config.port();
| HttpTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/connector/sink2/SinkWriter.java | {
"start": 1123,
"end": 2158
} | interface ____<InputT> extends AutoCloseable {
/**
* Adds an element to the writer.
*
* @param element The input record
* @param context The additional information about the input record
* @throws IOException if fail to add an element.
*/
void write(InputT element, Context context) throws IOException, InterruptedException;
/**
* Called on checkpoint or end of input so that the writer to flush all pending data for
* at-least-once.
*/
void flush(boolean endOfInput) throws IOException, InterruptedException;
/**
* Adds a watermark to the writer.
*
* <p>This method is intended for advanced sinks that propagate watermarks.
*
* @param watermark The watermark.
* @throws IOException if fail to add a watermark.
*/
default void writeWatermark(Watermark watermark) throws IOException, InterruptedException {}
/** Context that {@link #write} can use for getting additional data about an input record. */
@Public
| SinkWriter |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/MultisetTestSuiteBuilder.java | {
"start": 9998,
"end": 10730
} | class ____<E> implements TestMultisetGenerator<E> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedMultisetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Multiset<E> create(Object... elements) {
return (Multiset<E>) SerializableTester.reserialize(gen.create(elements));
}
@Override
public E[] createArray(int length) {
return gen.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return gen.order(insertionOrder);
}
}
}
| ReserializedMultisetGenerator |
java | spring-projects__spring-boot | module/spring-boot-mongodb/src/main/java/org/springframework/boot/mongodb/testcontainers/AbstractMongoContainerConnectionDetailsFactory.java | {
"start": 2398,
"end": 3076
} | class ____<T extends GenericContainer<T>>
extends ContainerConnectionDetails<T> implements MongoConnectionDetails {
private final Function<T, String> connectionStringFunction;
private MongoContainerConnectionDetails(ContainerConnectionSource<T> source,
Function<T, String> connectionStringFunction) {
super(source);
this.connectionStringFunction = connectionStringFunction;
}
@Override
public ConnectionString getConnectionString() {
return new ConnectionString(this.connectionStringFunction.apply(getContainer()));
}
@Override
public @Nullable SslBundle getSslBundle() {
return super.getSslBundle();
}
}
}
| MongoContainerConnectionDetails |
java | spring-projects__spring-security | config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/AnonymousAuthenticationITests.java | {
"start": 3875,
"end": 4668
} | class ____ {
@Bean
ServerController controller() {
return new ServerController();
}
@Bean
RSocketMessageHandler messageHandler() {
return new RSocketMessageHandler();
}
@Bean
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> anonymous = (authentication,
exchange) -> authentication.map(trustResolver::isAnonymous).map(AuthorizationDecision::new);
rsocket.authorizePayload((authorize) -> authorize.anyExchange().access(anonymous));
rsocket.anonymous((anonymousAuthentication) -> anonymousAuthentication.disable());
return rsocket.build();
}
}
@Controller
static | Config |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/MulticastStreamCachingTest.java | {
"start": 1282,
"end": 3396
} | class ____ extends ContextTestSupport {
protected Endpoint startEndpoint;
protected MockEndpoint x;
protected MockEndpoint y;
protected MockEndpoint z;
@Test
public void testSendingAMessageUsingMulticastConvertsToReReadable() throws Exception {
x.expectedBodiesReceived("<input/>+output");
y.expectedBodiesReceived("<input/>+output");
z.expectedBodiesReceived("<input/>+output");
template.send("direct:a", new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(new StreamSource(new StringReader("<input/>")));
in.setHeader("foo", "bar");
}
});
assertMockEndpointsSatisfied();
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
x = getMockEndpoint("mock:x");
y = getMockEndpoint("mock:y");
z = getMockEndpoint("mock:z");
}
@Override
protected RouteBuilder createRouteBuilder() {
final Processor processor = new Processor() {
public void process(Exchange exchange) {
// lets transform the IN message
Message in = exchange.getIn();
String body = in.getBody(String.class);
in.setBody(body + "+output");
}
};
return new RouteBuilder() {
public void configure() {
// enable stream caching
context.setStreamCaching(true);
errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).maximumRedeliveries(3));
// stream caching should fix re-readability issues when
// multicasting messages
from("direct:a").multicast().to("direct:x", "direct:y", "direct:z");
from("direct:x").process(processor).to("mock:x");
from("direct:y").process(processor).to("mock:y");
from("direct:z").process(processor).to("mock:z");
}
};
}
}
| MulticastStreamCachingTest |
java | google__dagger | javatests/dagger/hilt/android/ActivityInjectedSavedStateViewModelTest.java | {
"start": 3156,
"end": 3301
} | class ____
extends Hilt_ActivityInjectedSavedStateViewModelTest_TestActivityWithSuperActivity {}
public static | TestActivityWithSuperActivity |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/ReflectionUtil.java | {
"start": 353,
"end": 977
} | class ____ declares the field
* @param fieldName name of the field
* @return value of the field
*/
public static Object readField(Object object, Class<?> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
return field.get(object);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new IllegalArgumentException("Cannot read '" + fieldName + "' field from " + object + " of class " + clazz);
}
}
}
| that |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/authentication/ott/DefaultGenerateOneTimeTokenRequestResolver.java | {
"start": 1187,
"end": 1937
} | class ____ implements GenerateOneTimeTokenRequestResolver {
private static final Duration DEFAULT_EXPIRES_IN = Duration.ofMinutes(5);
private Duration expiresIn = DEFAULT_EXPIRES_IN;
@Override
public @Nullable GenerateOneTimeTokenRequest resolve(HttpServletRequest request) {
String username = request.getParameter("username");
if (!StringUtils.hasText(username)) {
return null;
}
return new GenerateOneTimeTokenRequest(username, this.expiresIn);
}
/**
* Sets one-time token expiration time
* @param expiresIn one-time token expiration time
*/
public void setExpiresIn(Duration expiresIn) {
Assert.notNull(expiresIn, "expiresIn cannot be null");
this.expiresIn = expiresIn;
}
}
| DefaultGenerateOneTimeTokenRequestResolver |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/CamelCommandBaseTest.java | {
"start": 965,
"end": 1140
} | class ____ {
protected StringPrinter printer;
@BeforeEach
public void setup() throws Exception {
printer = new StringPrinter();
}
}
| CamelCommandBaseTest |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/ArrayAggFunctionTest.java | {
"start": 14837,
"end": 15690
} | class ____<T> extends ArrayAggFunctionTestBase<T> {
protected abstract T getValue(String v);
@Override
protected List<List<T>> getInputValueSets() {
return Arrays.asList(
Arrays.asList(getValue("1"), null, getValue("-99"), getValue("3"), null),
Arrays.asList(null, null, null, null),
Arrays.asList(null, getValue("10"), null, getValue("3")));
}
@Override
protected List<ArrayData> getExpectedResults() {
return Arrays.asList(
new GenericArrayData(
new Object[] {getValue("1"), getValue("-99"), getValue("3")}),
null,
new GenericArrayData(new Object[] {getValue("10"), getValue("3")}));
}
}
}
| NumberArrayAggFunctionTestBase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/SecureRandomHolder.java | {
"start": 574,
"end": 729
} | class ____ is atomic - this is a lazy & safe singleton to be used by this package
public static final SecureRandom INSTANCE = new SecureRandom();
}
| loading |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/CookieTest.java | {
"start": 530,
"end": 1453
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar.addClasses(Resource.class));
@TestHTTPResource
URI baseUri;
@Test
void testCookie() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class);
assertThat(client.sendCookie("bar")).isEqualTo("bar");
}
@Test
void testNullCookie() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class);
assertThat(client.sendCookie(null)).isNull();
}
@Test
void testCookiesWithSubresource() {
Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class);
assertThat(client.cookieSub("bar", "bar2").send("bar3", "bar4")).isEqualTo("bar:bar2:bar3:bar4");
}
@Path("/")
@ApplicationScoped
public static | CookieTest |
java | google__gson | gson/src/test/java/com/google/gson/common/TestTypes.java | {
"start": 2015,
"end": 2230
} | class ____ {
public static final String FIELD_KEY = "base";
public final Base[] base;
public ClassWithBaseArrayField(Base[] base) {
this.base = base;
}
}
public static | ClassWithBaseArrayField |
java | elastic__elasticsearch | modules/apm/src/main/java/org/elasticsearch/telemetry/apm/APM.java | {
"start": 2610,
"end": 4882
} | class ____ extends Plugin implements NetworkPlugin, TelemetryPlugin {
private static final Logger logger = LogManager.getLogger(APM.class);
private final SetOnce<APMTelemetryProvider> telemetryProvider = new SetOnce<>();
private final Settings settings;
public APM(Settings settings) {
this.settings = settings;
}
@Override
public TelemetryProvider getTelemetryProvider(Settings settings) {
final APMTelemetryProvider apmTelemetryProvider = new APMTelemetryProvider(settings);
telemetryProvider.set(apmTelemetryProvider);
return apmTelemetryProvider;
}
@Override
public Collection<?> createComponents(PluginServices services) {
final APMTracer apmTracer = telemetryProvider.get().getTracer();
final APMMeterService apmMeter = telemetryProvider.get().getMeterService();
apmTracer.setClusterName(services.clusterService().getClusterName().value());
apmTracer.setNodeName(services.clusterService().getNodeName());
final APMAgentSettings apmAgentSettings = new APMAgentSettings();
apmAgentSettings.initAgentSystemProperties(settings);
apmAgentSettings.addClusterSettingsListeners(services.clusterService(), telemetryProvider.get());
logger.info("Sending apm metrics is {}", APMAgentSettings.TELEMETRY_METRICS_ENABLED_SETTING.get(settings) ? "enabled" : "disabled");
logger.info("Sending apm tracing is {}", APMAgentSettings.TELEMETRY_TRACING_ENABLED_SETTING.get(settings) ? "enabled" : "disabled");
return List.of(apmTracer, apmMeter);
}
@Override
public List<Setting<?>> getSettings() {
return List.of(
// APM general
APMAgentSettings.APM_AGENT_SETTINGS,
APMAgentSettings.TELEMETRY_SECRET_TOKEN_SETTING,
APMAgentSettings.TELEMETRY_API_KEY_SETTING,
// Metrics
APMAgentSettings.TELEMETRY_METRICS_ENABLED_SETTING,
// Tracing
APMAgentSettings.TELEMETRY_TRACING_ENABLED_SETTING,
APMAgentSettings.TELEMETRY_TRACING_NAMES_INCLUDE_SETTING,
APMAgentSettings.TELEMETRY_TRACING_NAMES_EXCLUDE_SETTING,
APMAgentSettings.TELEMETRY_TRACING_SANITIZE_FIELD_NAMES
);
}
}
| APM |
java | apache__hadoop | hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseFromSource.java | {
"start": 932,
"end": 1250
} | class ____
extends TestDistCpSyncReverseBase {
/*
* Initialize the source path to /target.
* @see org.apache.hadoop.tools.TestDistCpSyncReverseBase#initSourcePath()
*/
@Override
void initSourcePath() {
setSource(new Path("/source"));
setSrcNotSameAsTgt(true);
}
}
| TestDistCpSyncReverseFromSource |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/ClassTemplateInvocationTests.java | {
"start": 65060,
"end": 65292
} | class ____ {
@Test
void test(CustomCloseableResource resource) {
assertNotNull(resource);
assertFalse(CustomCloseableResource.closed, "should not be closed yet");
}
}
private static | ClassTemplateWithPreparationsTestCase |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/acl/AclOperation.java | {
"start": 1547,
"end": 4357
} | enum ____ {
/**
* Represents any AclOperation which this client cannot understand, perhaps because this
* client is too old.
*/
UNKNOWN((byte) 0),
/**
* In a filter, matches any AclOperation.
*/
ANY((byte) 1),
/**
* ALL operation.
*/
ALL((byte) 2),
/**
* READ operation.
*/
READ((byte) 3),
/**
* WRITE operation.
*/
WRITE((byte) 4),
/**
* CREATE operation.
*/
CREATE((byte) 5),
/**
* DELETE operation.
*/
DELETE((byte) 6),
/**
* ALTER operation.
*/
ALTER((byte) 7),
/**
* DESCRIBE operation.
*/
DESCRIBE((byte) 8),
/**
* CLUSTER_ACTION operation.
*/
CLUSTER_ACTION((byte) 9),
/**
* DESCRIBE_CONFIGS operation.
*/
DESCRIBE_CONFIGS((byte) 10),
/**
* ALTER_CONFIGS operation.
*/
ALTER_CONFIGS((byte) 11),
/**
* IDEMPOTENT_WRITE operation.
*/
IDEMPOTENT_WRITE((byte) 12),
/**
* CREATE_TOKENS operation.
*/
CREATE_TOKENS((byte) 13),
/**
* DESCRIBE_TOKENS operation.
*/
DESCRIBE_TOKENS((byte) 14),
/**
* TWO_PHASE_COMMIT operation.
*/
TWO_PHASE_COMMIT((byte) 15);
// Note: we cannot have more than 30 ACL operations without modifying the format used
// to describe ACL operations in MetadataResponse.
private static final HashMap<Byte, AclOperation> CODE_TO_VALUE = new HashMap<>();
static {
for (AclOperation operation : AclOperation.values()) {
CODE_TO_VALUE.put(operation.code, operation);
}
}
/**
* Parse the given string as an ACL operation.
*
* @param str The string to parse.
*
* @return The AclOperation, or UNKNOWN if the string could not be matched.
*/
public static AclOperation fromString(String str) throws IllegalArgumentException {
try {
return AclOperation.valueOf(str.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return UNKNOWN;
}
}
/**
* Return the AclOperation with the provided code or `AclOperation.UNKNOWN` if one cannot be found.
*/
public static AclOperation fromCode(byte code) {
AclOperation operation = CODE_TO_VALUE.get(code);
if (operation == null) {
return UNKNOWN;
}
return operation;
}
private final byte code;
AclOperation(byte code) {
this.code = code;
}
/**
* Return the code of this operation.
*/
public byte code() {
return code;
}
/**
* Return true if this operation is UNKNOWN.
*/
public boolean isUnknown() {
return this == UNKNOWN;
}
}
| AclOperation |
java | elastic__elasticsearch | libs/native/src/main/java/org/elasticsearch/nativeaccess/PosixNativeAccess.java | {
"start": 862,
"end": 9699
} | class ____ extends AbstractNativeAccess {
public static final int MCL_CURRENT = 1;
public static final int ENOMEM = 12;
public static final int O_RDONLY = 0;
public static final int O_WRONLY = 1;
protected final PosixCLibrary libc;
protected final VectorSimilarityFunctions vectorDistance;
protected final PosixConstants constants;
protected final ProcessLimits processLimits;
PosixNativeAccess(String name, NativeLibraryProvider libraryProvider, PosixConstants constants) {
super(name, libraryProvider);
this.libc = libraryProvider.getLibrary(PosixCLibrary.class);
this.vectorDistance = vectorSimilarityFunctionsOrNull(libraryProvider);
this.constants = constants;
this.processLimits = new ProcessLimits(
getMaxThreads(),
getRLimit(constants.RLIMIT_AS(), "max size virtual memory"),
getRLimit(constants.RLIMIT_FSIZE(), "max file size")
);
}
/**
* Return the maximum number of threads this process may start, or {@link ProcessLimits#UNKNOWN}.
*/
protected abstract long getMaxThreads();
/**
* Return the current rlimit for the given resource.
* If getrlimit fails, returns {@link ProcessLimits#UNKNOWN}.
* If the rlimit is unlimited, returns {@link ProcessLimits#UNLIMITED}.
* */
protected long getRLimit(int resource, String description) {
var rlimit = libc.newRLimit();
if (libc.getrlimit(resource, rlimit) == 0) {
long value = rlimit.rlim_cur();
return value == constants.RLIMIT_INFINITY() ? ProcessLimits.UNLIMITED : value;
} else {
logger.warn("unable to retrieve " + description + " [" + libc.strerror(libc.errno()) + "]");
return ProcessLimits.UNKNOWN;
}
}
static VectorSimilarityFunctions vectorSimilarityFunctionsOrNull(NativeLibraryProvider libraryProvider) {
if (isNativeVectorLibSupported()) {
var lib = libraryProvider.getLibrary(VectorLibrary.class).getVectorSimilarityFunctions();
logger.info("Using native vector library; to disable start with -D" + ENABLE_JDK_VECTOR_LIBRARY + "=false");
return lib;
}
return null;
}
@Override
public boolean definitelyRunningAsRoot() {
return libc.geteuid() == 0;
}
@Override
public ProcessLimits getProcessLimits() {
return processLimits;
}
@Override
public void tryLockMemory() {
int result = libc.mlockall(MCL_CURRENT);
if (result == 0) {
isMemoryLocked = true;
return;
}
// mlockall failed for some reason
int errno = libc.errno();
String errMsg = libc.strerror(errno);
logger.warn("Unable to lock JVM Memory: error={}, reason={}", errno, errMsg);
logger.warn("This can result in part of the JVM being swapped out.");
if (errno == ENOMEM) {
boolean rlimitSuccess = false;
long softLimit = 0;
long hardLimit = 0;
// we only know RLIMIT_MEMLOCK for these two at the moment.
var rlimit = libc.newRLimit();
if (libc.getrlimit(constants.RLIMIT_MEMLOCK(), rlimit) == 0) {
rlimitSuccess = true;
softLimit = rlimit.rlim_cur();
hardLimit = rlimit.rlim_max();
} else {
logger.warn("Unable to retrieve resource limits: {}", libc.strerror(libc.errno()));
}
if (rlimitSuccess) {
logger.warn(
"Increase RLIMIT_MEMLOCK, soft limit: {}, hard limit: {}",
rlimitToString(softLimit),
rlimitToString(hardLimit)
);
logMemoryLimitInstructions();
} else {
logger.warn("Increase RLIMIT_MEMLOCK (ulimit).");
}
}
}
protected abstract void logMemoryLimitInstructions();
@Override
public OptionalLong allocatedSizeInBytes(Path path) {
assert Files.isRegularFile(path) : path;
var stats = libc.newStat64(constants.statStructSize(), constants.statStructSizeOffset(), constants.statStructBlocksOffset());
int fd = libc.open(path.toAbsolutePath().toString(), O_RDONLY);
if (fd == -1) {
logger.warn("Could not open file [" + path + "] to get allocated size: " + libc.strerror(libc.errno()));
return OptionalLong.empty();
}
if (libc.fstat64(fd, stats) != 0) {
logger.warn("Could not get stats for file [" + path + "] to get allocated size: " + libc.strerror(libc.errno()));
return OptionalLong.empty();
}
if (libc.close(fd) != 0) {
logger.warn("Failed to close file [" + path + "] after getting stats: " + libc.strerror(libc.errno()));
}
return OptionalLong.of(stats.st_blocks() * 512);
}
@SuppressForbidden(reason = "Using mkdirs")
@Override
public void tryPreallocate(Path file, long newSize) {
var absolutePath = file.toAbsolutePath();
var directory = absolutePath.getParent();
directory.toFile().mkdirs();
// get fd and current size, then pass to OS variant
// We pass down O_CREAT, so open will create the file if it does not exist.
// From the open man page (https://www.man7.org/linux/man-pages/man2/open.2.html):
// - The mode parameter is needed when specifying O_CREAT
// - The effective mode is modified by the process's umask: in the absence of a default ACL, the mode of the created file is
// (mode & ~umask).
// We choose to pass down 0666 (r/w permission for user/group/others) to mimic what the JDK does for its open operations;
// see for example the fileOpen implementation in libjava:
// https://github.com/openjdk/jdk/blob/98562166e4a4c8921709014423c6cbc993aa0d97/src/java.base/unix/native/libjava/io_util_md.c#L105
int fd = libc.open(absolutePath.toString(), O_WRONLY | constants.O_CREAT(), 0666);
if (fd == -1) {
logger.warn("Could not open file [" + file + "] to preallocate size: " + libc.strerror(libc.errno()));
return;
}
var stats = libc.newStat64(constants.statStructSize(), constants.statStructSizeOffset(), constants.statStructBlocksOffset());
if (libc.fstat64(fd, stats) != 0) {
logger.warn("Could not get stats for file [" + file + "] to preallocate size: " + libc.strerror(libc.errno()));
} else {
if (nativePreallocate(fd, stats.st_size(), newSize)) {
logger.debug("pre-allocated file [{}] to {} bytes", file, newSize);
} // OS specific preallocate logs its own errors
}
if (libc.close(fd) != 0) {
logger.warn("Could not close file [" + file + "] after trying to preallocate size: " + libc.strerror(libc.errno()));
}
}
protected abstract boolean nativePreallocate(int fd, long currentSize, long newSize);
@Override
public Optional<VectorSimilarityFunctions> getVectorSimilarityFunctions() {
return Optional.ofNullable(vectorDistance);
}
String rlimitToString(long value) {
if (value == constants.RLIMIT_INFINITY()) {
return "unlimited";
} else {
return Long.toUnsignedString(value);
}
}
static boolean isNativeVectorLibSupported() {
return Runtime.version().feature() >= 21 && (isMacOrLinuxAarch64() || isLinuxAmd64()) && checkEnableSystemProperty();
}
/**
* Returns true iff the architecture is x64 (amd64) and the OS Linux (the OS we currently support for the native lib).
*/
static boolean isLinuxAmd64() {
String name = System.getProperty("os.name");
return (name.startsWith("Linux")) && System.getProperty("os.arch").equals("amd64");
}
/** Returns true iff the OS is Mac or Linux, and the architecture is aarch64. */
static boolean isMacOrLinuxAarch64() {
String name = System.getProperty("os.name");
return (name.startsWith("Mac") || name.startsWith("Linux")) && System.getProperty("os.arch").equals("aarch64");
}
/** -Dorg.elasticsearch.nativeaccess.enableVectorLibrary=false to disable.*/
static final String ENABLE_JDK_VECTOR_LIBRARY = "org.elasticsearch.nativeaccess.enableVectorLibrary";
@SuppressForbidden(
reason = "TODO Deprecate any lenient usage of Boolean#parseBoolean https://github.com/elastic/elasticsearch/issues/128993"
)
static boolean checkEnableSystemProperty() {
return Optional.ofNullable(System.getProperty(ENABLE_JDK_VECTOR_LIBRARY)).map(Boolean::valueOf).orElse(Boolean.TRUE);
}
}
| PosixNativeAccess |
java | apache__hadoop | hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KeyAuthorizationKeyProvider.java | {
"start": 2626,
"end": 12762
} | interface ____ {
/**
* This is called by the KeyProvider to check if the given user is
* authorized to perform the specified operation on the given acl name.
* @param aclName name of the key ACL
* @param ugi User's UserGroupInformation
* @param opType Operation Type
* @return true if user has access to the aclName and opType else false
*/
public boolean hasAccessToKey(String aclName, UserGroupInformation ugi,
KeyOpType opType);
/**
*
* @param aclName ACL name
* @param opType Operation Type
* @return true if AclName exists else false
*/
public boolean isACLPresent(String aclName, KeyOpType opType);
}
private final KeyProviderCryptoExtension provider;
private final KeyACLs acls;
private Lock readLock;
private Lock writeLock;
/**
* The constructor takes a {@link KeyProviderCryptoExtension} and an
* implementation of <code>KeyACLs</code>. All calls are delegated to the
* provider keyProvider after authorization check (if required)
* @param keyProvider the key provider
* @param acls the Key ACLs
*/
public KeyAuthorizationKeyProvider(KeyProviderCryptoExtension keyProvider,
KeyACLs acls) {
super(keyProvider, null);
this.provider = keyProvider;
this.acls = acls;
ReadWriteLock lock = new ReentrantReadWriteLock(true);
readLock = lock.readLock();
writeLock = lock.writeLock();
}
// This method first checks if "key.acl.name" attribute is present as an
// attribute in the provider Options. If yes, use the aclName for any
// subsequent access checks, else use the keyName as the aclName and set it
// as the value of the "key.acl.name" in the key's metadata.
private void authorizeCreateKey(String keyName, Options options,
UserGroupInformation ugi) throws IOException{
Preconditions.checkNotNull(ugi, "UserGroupInformation cannot be null");
Map<String, String> attributes = options.getAttributes();
String aclName = attributes.get(KEY_ACL_NAME);
boolean success = false;
if (Strings.isNullOrEmpty(aclName)) {
if (acls.isACLPresent(keyName, KeyOpType.MANAGEMENT)) {
options.setAttributes(ImmutableMap.<String, String> builder()
.putAll(attributes).put(KEY_ACL_NAME, keyName).build());
success =
acls.hasAccessToKey(keyName, ugi, KeyOpType.MANAGEMENT)
|| acls.hasAccessToKey(keyName, ugi, KeyOpType.ALL);
} else {
success = false;
}
} else {
success = acls.isACLPresent(aclName, KeyOpType.MANAGEMENT) &&
(acls.hasAccessToKey(aclName, ugi, KeyOpType.MANAGEMENT)
|| acls.hasAccessToKey(aclName, ugi, KeyOpType.ALL));
}
if (!success)
throw new AuthorizationException(String.format("User [%s] is not"
+ " authorized to create key !!", ugi.getShortUserName()));
}
private void checkAccess(String aclName, UserGroupInformation ugi,
KeyOpType opType) throws AuthorizationException {
Preconditions.checkNotNull(aclName, "Key ACL name cannot be null");
Preconditions.checkNotNull(ugi, "UserGroupInformation cannot be null");
if (acls.isACLPresent(aclName, opType) &&
(acls.hasAccessToKey(aclName, ugi, opType)
|| acls.hasAccessToKey(aclName, ugi, KeyOpType.ALL))) {
return;
} else {
throw new AuthorizationException(String.format("User [%s] is not"
+ " authorized to perform [%s] on key with ACL name [%s]!!",
ugi.getShortUserName(), opType, aclName));
}
}
@Override
public KeyVersion createKey(String name, Options options)
throws NoSuchAlgorithmException, IOException {
writeLock.lock();
try {
authorizeCreateKey(name, options, getUser());
return provider.createKey(name, options);
} finally {
writeLock.unlock();
}
}
@Override
public KeyVersion createKey(String name, byte[] material, Options options)
throws IOException {
writeLock.lock();
try {
authorizeCreateKey(name, options, getUser());
return provider.createKey(name, material, options);
} finally {
writeLock.unlock();
}
}
@Override
public KeyVersion rollNewVersion(String name)
throws NoSuchAlgorithmException, IOException {
writeLock.lock();
try {
doAccessCheck(name, KeyOpType.MANAGEMENT);
return provider.rollNewVersion(name);
} finally {
writeLock.unlock();
}
}
@Override
public void deleteKey(String name) throws IOException {
writeLock.lock();
try {
doAccessCheck(name, KeyOpType.MANAGEMENT);
provider.deleteKey(name);
} finally {
writeLock.unlock();
}
}
@Override
public KeyVersion rollNewVersion(String name, byte[] material)
throws IOException {
writeLock.lock();
try {
doAccessCheck(name, KeyOpType.MANAGEMENT);
return provider.rollNewVersion(name, material);
} finally {
writeLock.unlock();
}
}
@Override
public void invalidateCache(String name) throws IOException {
writeLock.lock();
try {
doAccessCheck(name, KeyOpType.MANAGEMENT);
provider.invalidateCache(name);
} finally {
writeLock.unlock();
}
}
@Override
public void warmUpEncryptedKeys(String... names) throws IOException {
readLock.lock();
try {
for (String name : names) {
doAccessCheck(name, KeyOpType.GENERATE_EEK);
}
provider.warmUpEncryptedKeys(names);
} finally {
readLock.unlock();
}
}
@Override
public EncryptedKeyVersion generateEncryptedKey(String encryptionKeyName)
throws IOException, GeneralSecurityException {
readLock.lock();
try {
doAccessCheck(encryptionKeyName, KeyOpType.GENERATE_EEK);
return provider.generateEncryptedKey(encryptionKeyName);
} finally {
readLock.unlock();
}
}
private void verifyKeyVersionBelongsToKey(EncryptedKeyVersion ekv)
throws IOException {
String kn = ekv.getEncryptionKeyName();
String kvn = ekv.getEncryptionKeyVersionName();
KeyVersion kv = provider.getKeyVersion(kvn);
if (kv == null) {
throw new IllegalArgumentException(String.format(
"'%s' not found", kvn));
}
if (!kv.getName().equals(kn)) {
throw new IllegalArgumentException(String.format(
"KeyVersion '%s' does not belong to the key '%s'", kvn, kn));
}
}
@Override
public KeyVersion decryptEncryptedKey(EncryptedKeyVersion encryptedKeyVersion)
throws IOException, GeneralSecurityException {
readLock.lock();
try {
verifyKeyVersionBelongsToKey(encryptedKeyVersion);
doAccessCheck(
encryptedKeyVersion.getEncryptionKeyName(), KeyOpType.DECRYPT_EEK);
return provider.decryptEncryptedKey(encryptedKeyVersion);
} finally {
readLock.unlock();
}
}
@Override
public EncryptedKeyVersion reencryptEncryptedKey(EncryptedKeyVersion ekv)
throws IOException, GeneralSecurityException {
readLock.lock();
try {
verifyKeyVersionBelongsToKey(ekv);
doAccessCheck(ekv.getEncryptionKeyName(), KeyOpType.GENERATE_EEK);
return provider.reencryptEncryptedKey(ekv);
} finally {
readLock.unlock();
}
}
@Override
public void reencryptEncryptedKeys(List<EncryptedKeyVersion> ekvs)
throws IOException, GeneralSecurityException {
if (ekvs.isEmpty()) {
return;
}
readLock.lock();
try {
for (EncryptedKeyVersion ekv : ekvs) {
verifyKeyVersionBelongsToKey(ekv);
}
final String keyName = ekvs.get(0).getEncryptionKeyName();
doAccessCheck(keyName, KeyOpType.GENERATE_EEK);
provider.reencryptEncryptedKeys(ekvs);
} finally {
readLock.unlock();
}
}
@Override
public KeyVersion getKeyVersion(String versionName) throws IOException {
readLock.lock();
try {
KeyVersion keyVersion = provider.getKeyVersion(versionName);
if (keyVersion != null) {
doAccessCheck(keyVersion.getName(), KeyOpType.READ);
}
return keyVersion;
} finally {
readLock.unlock();
}
}
@Override
public List<String> getKeys() throws IOException {
return provider.getKeys();
}
@Override
public List<KeyVersion> getKeyVersions(String name) throws IOException {
readLock.lock();
try {
doAccessCheck(name, KeyOpType.READ);
return provider.getKeyVersions(name);
} finally {
readLock.unlock();
}
}
@Override
public Metadata getMetadata(String name) throws IOException {
readLock.lock();
try {
doAccessCheck(name, KeyOpType.READ);
return provider.getMetadata(name);
} finally {
readLock.unlock();
}
}
@Override
public Metadata[] getKeysMetadata(String... names) throws IOException {
readLock.lock();
try {
for (String name : names) {
doAccessCheck(name, KeyOpType.READ);
}
return provider.getKeysMetadata(names);
} finally {
readLock.unlock();
}
}
@Override
public KeyVersion getCurrentKey(String name) throws IOException {
readLock.lock();
try {
doAccessCheck(name, KeyOpType.READ);
return provider.getCurrentKey(name);
} finally {
readLock.unlock();
}
}
@Override
public void flush() throws IOException {
provider.flush();
}
@Override
public boolean isTransient() {
return provider.isTransient();
}
private void doAccessCheck(String keyName, KeyOpType opType) throws
IOException {
Metadata metadata = provider.getMetadata(keyName);
if (metadata != null) {
String aclName = metadata.getAttributes().get(KEY_ACL_NAME);
checkAccess((aclName == null) ? keyName : aclName, getUser(), opType);
}
}
private UserGroupInformation getUser() throws IOException {
return UserGroupInformation.getCurrentUser();
}
@Override
protected KeyProvider getKeyProvider() {
return this;
}
@Override
public String toString() {
return this.getClass().getName()+": "+provider.toString();
}
}
| KeyACLs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.