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
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/RowIdTest.java
|
{
"start": 674,
"end": 1287
}
|
class ____ {
@Test
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Product product = new Product();
product.setId(1L);
product.setName("Mobile phone");
product.setNumber("123-456-7890");
entityManager.persist(product);
});
scope.inTransaction( entityManager -> {
//tag::identifiers-rowid-example[]
Product product = entityManager.find(Product.class, 1L);
product.setName("Smart phone");
//end::identifiers-rowid-example[]
});
}
//tag::identifiers-rowid-mapping[]
@Entity(name = "Product")
@RowId("ROWID")
public static
|
RowIdTest
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/runtime/src/main/java/io/quarkus/websockets/next/HttpUpgradeCheck.java
|
{
"start": 997,
"end": 1840
}
|
interface ____ {
/**
* This method inspects HTTP Upgrade context and either allows or denies upgrade to a WebSocket connection.
* <p>
* Use {@link VertxContextSupport#executeBlocking(java.util.concurrent.Callable)} in order to execute some blocking code in
* the check.
*
* @param context {@link HttpUpgradeContext}
* @return check result; must never be null
*/
Uni<CheckResult> perform(HttpUpgradeContext context);
/**
* Determines WebSocket endpoints this check is applied to.
*
* @param endpointId WebSocket endpoint id, @see {@link WebSocket#endpointId()} for more information
* @return true if this check should be applied on a WebSocket endpoint with given id
*/
default boolean appliesTo(String endpointId) {
return true;
}
|
HttpUpgradeCheck
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/StdDevDoubleAggregator.java
|
{
"start": 1028,
"end": 2347
}
|
class ____ {
public static VarianceStates.SingleState initSingle(boolean stdDev) {
return new VarianceStates.SingleState(stdDev);
}
public static void combine(VarianceStates.SingleState state, double value) {
state.add(value);
}
public static void combineIntermediate(VarianceStates.SingleState state, double mean, double m2, long count) {
state.combine(mean, m2, count);
}
public static Block evaluateFinal(VarianceStates.SingleState state, DriverContext driverContext) {
return state.evaluateFinal(driverContext);
}
public static VarianceStates.GroupingState initGrouping(BigArrays bigArrays, boolean stdDev) {
return new VarianceStates.GroupingState(bigArrays, stdDev);
}
public static void combine(VarianceStates.GroupingState current, int groupId, double value) {
current.add(groupId, value);
}
public static void combineIntermediate(VarianceStates.GroupingState state, int groupId, double mean, double m2, long count) {
state.combine(groupId, mean, m2, count);
}
public static Block evaluateFinal(VarianceStates.GroupingState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) {
return state.evaluateFinal(selected, ctx.driverContext());
}
}
|
StdDevDoubleAggregator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
|
{
"start": 77558,
"end": 77612
}
|
class ____ {
@Anno(a = 1)
|
Test
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/MulticastParallelTimeout2Test.java
|
{
"start": 1372,
"end": 3622
}
|
class ____ extends ContextTestSupport {
private final Phaser phaser = new Phaser(3);
@BeforeEach
void sendEarly() {
Assumptions.assumeTrue(context.isStarted(), "The test cannot be run because the context is not started");
template.sendBody("direct:start", "Hello");
}
@Test
public void testMulticastParallelTimeout() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
// B will timeout so we only get A and/or C
mock.message(0).body().not(body().contains("B"));
getMockEndpoint("mock:A").expectedMessageCount(1);
getMockEndpoint("mock:B").expectedMessageCount(0);
getMockEndpoint("mock:C").expectedMessageCount(1);
phaser.awaitAdvanceInterruptibly(0, 5000, TimeUnit.SECONDS);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// START SNIPPET: e1
from("direct:start").multicast(new AggregationStrategy() {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body = oldExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body + newExchange.getIn().getBody(String.class));
return oldExchange;
}
}).parallelProcessing().timeout(250).to("direct:a", "direct:b", "direct:c")
// use end to indicate end of multicast route
.end().to("mock:result");
from("direct:a").process(e -> phaser.arriveAndAwaitAdvance()).to("mock:A").setBody(constant("A"));
from("direct:b").process(e -> phaser.arriveAndAwaitAdvance()).delay(1000).to("mock:B").setBody(constant("B"));
from("direct:c").process(e -> phaser.arriveAndAwaitAdvance()).to("mock:C").setBody(constant("C"));
// END SNIPPET: e1
}
};
}
}
|
MulticastParallelTimeout2Test
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/records/RecordsWithJsonIncludeAndIgnorals4629Test.java
|
{
"start": 497,
"end": 1653
}
|
class ____
extends DatabindTestUtil
{
record Id2Name(
int id,
String name
) { }
record RecordWithInclude4629(
@JsonIncludeProperties("id") Id2Name child
) { }
record RecordWIthIgnore4629(
@JsonIgnoreProperties("name") Id2Name child
) { }
private final ObjectMapper MAPPER = newJsonMapper();
@Test
void testJsonInclude4629()
throws Exception
{
RecordWithInclude4629 expected = new RecordWithInclude4629(new Id2Name(123, null));
String input = "{\"child\":{\"id\":123,\"name\":\"Bob\"}}";
RecordWithInclude4629 actual = MAPPER.readValue(input, RecordWithInclude4629.class);
assertEquals(expected, actual);
}
@Test
void testJsonIgnore4629()
throws Exception
{
RecordWIthIgnore4629 expected = new RecordWIthIgnore4629(new Id2Name(123, null));
String input = "{\"child\":{\"id\":123,\"name\":\"Bob\"}}";
RecordWIthIgnore4629 actual = MAPPER.readValue(input, RecordWIthIgnore4629.class);
assertEquals(expected, actual);
}
}
|
RecordsWithJsonIncludeAndIgnorals4629Test
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/serializer/enum_/EnumOrdinalTest.java
|
{
"start": 690,
"end": 737
}
|
enum ____ {
Big, Medium, Small
}
}
|
Type
|
java
|
micronaut-projects__micronaut-core
|
core/src/main/java/io/micronaut/core/io/service/SoftServiceLoader.java
|
{
"start": 11171,
"end": 12476
}
|
class ____<S> implements ServiceDefinition<S> {
private final String name;
private final Supplier<S> value;
private StaticDefinition(String name, Supplier<S> value) {
this.name = name;
this.value = value;
}
public static <S> StaticDefinition<S> of(String name, Class<S> value) {
return new StaticDefinition<>(name, () -> doCreate(value));
}
public static <S> StaticDefinition<S> of(String name, Supplier<S> value) {
return new StaticDefinition<>(name, value);
}
@Override
public boolean isPresent() {
return true;
}
@Override
public String getName() {
return name;
}
@Override
public S load() {
return value.get();
}
@SuppressWarnings({"unchecked"})
private static <S> S doCreate(Class<S> clazz) {
try {
return (S) LOOKUP.findConstructor(clazz, VOID_TYPE).invoke();
} catch (Throwable e) {
throw new ServiceLoadingException(e);
}
}
}
/**
* Service collector for loading services of the given type.
*
* @param <S> The service type
*/
public
|
StaticDefinition
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/output/GeoCoordinatesValueListOutput.java
|
{
"start": 430,
"end": 2033
}
|
class ____<K, V> extends CommandOutput<K, V, List<Value<GeoCoordinates>>>
implements StreamingOutput<Value<GeoCoordinates>> {
boolean hasX;
private Double x;
private boolean initialized;
private Subscriber<Value<GeoCoordinates>> subscriber;
public GeoCoordinatesValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
if (bytes == null) {
subscriber.onNext(output, Value.empty());
return;
}
double value = parseDouble(decodeString(bytes));
set(value);
}
@Override
public void set(double number) {
if (!hasX) {
x = number;
hasX = true;
return;
}
subscriber.onNext(output, Value.fromNullable(new GeoCoordinates(x, number)));
x = null;
hasX = false;
}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(count / 2);
initialized = true;
}
if (count == -1) {
subscriber.onNext(output, Value.empty());
}
}
@Override
public void setSubscriber(Subscriber<Value<GeoCoordinates>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<Value<GeoCoordinates>> getSubscriber() {
return subscriber;
}
}
|
GeoCoordinatesValueListOutput
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/DependentId.java
|
{
"start": 281,
"end": 560
}
|
class ____ implements Serializable {
String name;
long empPK; // corresponds to PK type of Employee
public DependentId() {
}
public DependentId(long empPK, String name) {
this.empPK = empPK;
this.name = name;
}
public String getName() {
return name;
}
}
|
DependentId
|
java
|
alibaba__nacos
|
api/src/test/java/com/alibaba/nacos/api/ai/model/mcp/registry/OfficialMetaTest.java
|
{
"start": 1011,
"end": 2304
}
|
class ____ extends BasicRequestTest {
@Test
void testSerialize() throws JsonProcessingException {
OfficialMeta officialMeta = new OfficialMeta();
officialMeta.setPublishedAt("2022-01-01T00:00:00Z");
officialMeta.setUpdatedAt("2022-01-02T00:00:00Z");
officialMeta.setIsLatest(true);
String json = mapper.writeValueAsString(officialMeta);
assertNotNull(json);
assertTrue(json.contains("\"publishedAt\":\"2022-01-01T00:00:00Z\""));
assertTrue(json.contains("\"updatedAt\":\"2022-01-02T00:00:00Z\""));
assertTrue(json.contains("\"isLatest\":true"));
}
@Test
void testDeserialize() throws JsonProcessingException {
String json = "{\"serverId\":\"server1\",\"versionId\":\"version1\","
+ "\"publishedAt\":\"2022-01-01T00:00:00Z\",\"updatedAt\":\"2022-01-02T00:00:00Z\","
+ "\"isLatest\":true}";
OfficialMeta officialMeta = mapper.readValue(json, OfficialMeta.class);
assertNotNull(officialMeta);
assertEquals("2022-01-01T00:00:00Z", officialMeta.getPublishedAt());
assertEquals("2022-01-02T00:00:00Z", officialMeta.getUpdatedAt());
assertEquals(true, officialMeta.getIsLatest());
}
}
|
OfficialMetaTest
|
java
|
netty__netty
|
codec-base/src/main/java/io/netty/handler/codec/CodecOutputList.java
|
{
"start": 1721,
"end": 1844
}
|
interface ____ {
void recycle(CodecOutputList codecOutputList);
}
private static final
|
CodecOutputListRecycler
|
java
|
apache__camel
|
components/camel-mapstruct/src/main/java/org/apache/camel/component/mapstruct/DefaultMapStructFinder.java
|
{
"start": 1414,
"end": 4678
}
|
class ____ extends ServiceSupport implements MapStructMapperFinder, CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(DefaultMapStructFinder.class);
private CamelContext camelContext;
private String mapperPackageName;
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public String getMapperPackageName() {
return mapperPackageName;
}
@Override
public int discoverMappings(Class<?> clazz) {
final AtomicInteger answer = new AtomicInteger();
try {
// is there a generated mapper
final Object mapper = Mappers.getMapper(clazz);
if (mapper != null) {
ReflectionHelper.doWithMethods(mapper.getClass(), mc -> {
// must be public
if (!Modifier.isPublic(mc.getModifiers())) {
return;
}
// must not be a default method
if (mc.isDefault()) {
return;
}
// must have a single parameter
int parameterCount = mc.getParameterCount();
if (parameterCount != 1) {
return;
}
Class<?> from = mc.getParameterTypes()[0];
// must return a non-primitive value
Class<?> to = mc.getReturnType();
if (to.isPrimitive()) {
return;
}
// okay register this method as a Camel type converter
camelContext.getTypeConverterRegistry()
.addTypeConverter(to, from, new SimpleTypeConverter(
false, (type, exchange, value) -> ObjectHelper.invokeMethod(mc, mapper, value)));
LOG.debug("Added MapStruct type converter: {} -> {}", from, to);
answer.incrementAndGet();
});
}
} catch (Exception e) {
LOG.debug("Mapper class: {} is not a MapStruct Mapper. Skipping this class.", clazz);
}
return answer.get();
}
public void setMapperPackageName(String mapperPackageName) {
this.mapperPackageName = mapperPackageName;
}
@Override
protected void doInit() throws Exception {
if (mapperPackageName != null) {
String[] names = mapperPackageName.split(",");
ExtendedCamelContext ecc = camelContext.getCamelContextExtension();
var set = PluginHelper.getPackageScanClassResolver(ecc)
.findByFilter(f -> f.getName().endsWith("Mapper"), names);
if (!set.isEmpty()) {
int converters = 0;
for (Class<?> clazz : set) {
converters += discoverMappings(clazz);
}
LOG.info("Discovered {} MapStruct type converters from classpath scanning: {}", converters, mapperPackageName);
}
}
}
}
|
DefaultMapStructFinder
|
java
|
apache__thrift
|
lib/java/src/main/java/org/apache/thrift/scheme/SchemeFactory.java
|
{
"start": 846,
"end": 912
}
|
interface ____ {
<S extends IScheme> S getScheme();
}
|
SchemeFactory
|
java
|
quarkusio__quarkus
|
extensions/cache/runtime/src/main/java/io/quarkus/cache/CacheManager.java
|
{
"start": 532,
"end": 1020
}
|
class ____ {
*
* private final CacheManager cacheManager;
*
* public CachedService(CacheManager cacheManager) {
* this.cacheManager = cacheManager;
* }
* String getExpensiveValue(Object key) {
* Cache cache = cacheManager.getCache("my-cache");
* {@code Uni<String>} cacheValue = cache.get(key, () -> expensiveService.getValue(key));
* return cacheValue.await().indefinitely();
* }
* }
* </pre>
* </p>
*/
public
|
CachedService
|
java
|
apache__commons-lang
|
src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java
|
{
"start": 3500,
"end": 3648
}
|
interface ____ {
void event1(PropertyChangeEvent e);
void event2(PropertyChangeEvent e);
}
public static
|
MultipleEventListener
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KafkaEndpointBuilderFactory.java
|
{
"start": 80867,
"end": 92786
}
|
interface ____
extends
EndpointConsumerBuilder {
default KafkaEndpointConsumerBuilder basic() {
return (KafkaEndpointConsumerBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Controls how to read messages written transactionally. If set to
* read_committed, consumer.poll() will only return transactional
* messages which have been committed. If set to read_uncommitted (the
* default), consumer.poll() will return all messages, even
* transactional messages which have been aborted. Non-transactional
* messages will be returned unconditionally in either mode. Messages
* will always be returned in offset order. Hence, in read_committed
* mode, consumer.poll() will only return messages up to the last stable
* offset (LSO), which is the one less than the offset of the first open
* transaction. In particular, any messages appearing after messages
* belonging to ongoing transactions will be withheld until the relevant
* transaction has been completed. As a result, read_committed consumers
* will not be able to read up to the high watermark when there are in
* flight transactions. Further, when in read_committed the seekToEnd
* method will return the LSO.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: read_uncommitted
* Group: consumer (advanced)
*
* @param isolationLevel the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder isolationLevel(String isolationLevel) {
doSetProperty("isolationLevel", isolationLevel);
return this;
}
/**
* Factory to use for creating KafkaManualCommit instances. This allows
* to plugin a custom factory to create custom KafkaManualCommit
* instances in case special logic is needed when doing manual commits
* that deviates from the default implementation that comes out of the
* box.
*
* The option is a:
* <code>org.apache.camel.component.kafka.consumer.KafkaManualCommitFactory</code> type.
*
* Group: consumer (advanced)
*
* @param kafkaManualCommitFactory the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder kafkaManualCommitFactory(org.apache.camel.component.kafka.consumer.KafkaManualCommitFactory kafkaManualCommitFactory) {
doSetProperty("kafkaManualCommitFactory", kafkaManualCommitFactory);
return this;
}
/**
* Factory to use for creating KafkaManualCommit instances. This allows
* to plugin a custom factory to create custom KafkaManualCommit
* instances in case special logic is needed when doing manual commits
* that deviates from the default implementation that comes out of the
* box.
*
* The option will be converted to a
* <code>org.apache.camel.component.kafka.consumer.KafkaManualCommitFactory</code> type.
*
* Group: consumer (advanced)
*
* @param kafkaManualCommitFactory the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder kafkaManualCommitFactory(String kafkaManualCommitFactory) {
doSetProperty("kafkaManualCommitFactory", kafkaManualCommitFactory);
return this;
}
/**
* Factory to use for creating
* org.apache.kafka.clients.consumer.KafkaConsumer and
* org.apache.kafka.clients.producer.KafkaProducer instances. This
* allows to configure a custom factory to create instances with logic
* that extends the vanilla Kafka clients.
*
* The option is a:
* <code>org.apache.camel.component.kafka.KafkaClientFactory</code>
* type.
*
* Group: advanced
*
* @param kafkaClientFactory the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder kafkaClientFactory(org.apache.camel.component.kafka.KafkaClientFactory kafkaClientFactory) {
doSetProperty("kafkaClientFactory", kafkaClientFactory);
return this;
}
/**
* Factory to use for creating
* org.apache.kafka.clients.consumer.KafkaConsumer and
* org.apache.kafka.clients.producer.KafkaProducer instances. This
* allows to configure a custom factory to create instances with logic
* that extends the vanilla Kafka clients.
*
* The option will be converted to a
* <code>org.apache.camel.component.kafka.KafkaClientFactory</code>
* type.
*
* Group: advanced
*
* @param kafkaClientFactory the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder kafkaClientFactory(String kafkaClientFactory) {
doSetProperty("kafkaClientFactory", kafkaClientFactory);
return this;
}
/**
* Sets whether synchronous processing should be strictly used.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param synchronous the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param synchronous the value to set
* @return the dsl builder
*/
default AdvancedKafkaEndpointConsumerBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint producers for the Kafka component.
*/
public
|
AdvancedKafkaEndpointConsumerBuilder
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/property/access/spi/GetterMethodImplTest.java
|
{
"start": 3133,
"end": 3602
}
|
class ____ {
private String getRuntimeException() {
throw new RuntimeException();
}
private String getCheckedException() throws Exception {
throw new Exception();
}
private String getError() {
throw new Error();
}
}
private Getter getter(Class<?> clazz, String property) {
final Method getterMethod = ReflectHelper.findGetterMethod( clazz, property );
return new GetterMethodImpl( clazz, property, getterMethod );
}
}
|
TargetThrowingExceptions
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/OverrideVersionAnnotation.java
|
{
"start": 473,
"end": 1596
}
|
class ____ implements DialectOverride.Version {
private int major;
private int minor;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public OverrideVersionAnnotation(ModelsContext modelContext) {
this.minor = 0;
}
/**
* Used in creating annotation instances from JDK variant
*/
public OverrideVersionAnnotation(DialectOverride.Version annotation, ModelsContext modelContext) {
major( annotation.major() );
minor( annotation.minor() );
}
/**
* Used in creating annotation instances from Jandex variant
*/
public OverrideVersionAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
major( (Integer) attributeValues.get( "major" ) );
minor( (Integer) attributeValues.get( "minor" ) );
}
@Override
public Class<? extends Annotation> annotationType() {
return DialectOverride.Version.class;
}
@Override
public int major() {
return major;
}
public void major(int value) {
this.major = value;
}
@Override
public int minor() {
return minor;
}
public void minor(int value) {
this.minor = value;
}
}
|
OverrideVersionAnnotation
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/protocol/ApiKeysTest.java
|
{
"start": 1466,
"end": 4905
}
|
class ____ {
@Test
public void testForIdWithInvalidIdLow() {
assertThrows(IllegalArgumentException.class, () -> ApiKeys.forId(-1));
}
@Test
public void testForIdWithInvalidIdHigh() {
assertThrows(IllegalArgumentException.class, () -> ApiKeys.forId(10000));
}
@Test
public void testAlterPartitionIsClusterAction() {
assertTrue(ApiKeys.ALTER_PARTITION.clusterAction);
}
/**
* All valid client responses which may be throttled should have a field named
* 'throttle_time_ms' to return the throttle time to the client. Exclusions are
* <ul>
* <li> Cluster actions used only for inter-broker are throttled only if unauthorized
* <li> SASL_HANDSHAKE and SASL_AUTHENTICATE are not throttled when used for authentication
* when a connection is established or for re-authentication thereafter; these requests
* return an error response that may be throttled if they are sent otherwise.
* </ul>
*/
@Test
public void testResponseThrottleTime() {
Set<ApiKeys> authenticationKeys = EnumSet.of(ApiKeys.SASL_HANDSHAKE, ApiKeys.SASL_AUTHENTICATE);
// Newer protocol apis include throttle time ms even for cluster actions
Set<ApiKeys> clusterActionsWithThrottleTimeMs = EnumSet.of(ApiKeys.ALTER_PARTITION, ApiKeys.ALLOCATE_PRODUCER_IDS, ApiKeys.UPDATE_FEATURES);
for (ApiKeys apiKey: ApiKeys.clientApis()) {
Schema responseSchema = apiKey.messageType.responseSchemas()[apiKey.latestVersion()];
BoundField throttleTimeField = responseSchema.get("throttle_time_ms");
if ((apiKey.clusterAction && !clusterActionsWithThrottleTimeMs.contains(apiKey))
|| authenticationKeys.contains(apiKey))
assertNull(throttleTimeField, "Unexpected throttle time field: " + apiKey);
else
assertNotNull(throttleTimeField, "Throttle time field missing: " + apiKey);
}
}
@Test
public void testApiScope() {
Set<ApiKeys> apisMissingScope = new HashSet<>();
for (ApiKeys apiKey : ApiKeys.values()) {
if (apiKey.messageType.listeners().isEmpty() && apiKey.hasValidVersion()) {
apisMissingScope.add(apiKey);
}
}
assertEquals(Collections.emptySet(), apisMissingScope,
"Found some APIs missing scope definition");
}
@Test
public void testHasValidVersions() {
var apiKeysWithNoValidVersions = Set.of(ApiKeys.LEADER_AND_ISR, ApiKeys.STOP_REPLICA, ApiKeys.UPDATE_METADATA,
ApiKeys.CONTROLLED_SHUTDOWN);
for (ApiKeys apiKey : ApiKeys.values()) {
if (apiKeysWithNoValidVersions.contains(apiKey))
assertFalse(apiKey.hasValidVersion());
else
assertTrue(apiKey.hasValidVersion());
}
}
@Test
public void testHtmlOnlyHaveStableApi() {
String html = ApiKeys.toHtml();
for (ApiKeys apiKeys : ApiKeys.clientApis()) {
if (apiKeys.toApiVersion(false).isPresent()) {
assertTrue(html.contains("The_Messages_" + apiKeys.name), "Html should contain stable api: " + apiKeys.name);
} else {
assertFalse(html.contains("The_Messages_" + apiKeys.name), "Html should not contain unstable api: " + apiKeys.name);
}
}
}
}
|
ApiKeysTest
|
java
|
apache__dubbo
|
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.java
|
{
"start": 5136,
"end": 13124
}
|
class ____ implements ReflectionTypeDescriberRegistrar {
@Override
public List<TypeDescriber> getTypeDescribers() {
List<TypeDescriber> typeDescribers = new ArrayList<>();
Class[] classesWithDeclared = {
ClientAbilities.class,
ClientConfigAbility.class,
AbstractConfigRequest.class,
ConfigBatchListenRequest.class,
ConfigListenContext.class,
ConfigPublishRequest.class,
ConfigQueryRequest.class,
ConfigChangeBatchListenResponse.class,
ConfigContext.class,
ConfigPublishResponse.class,
ConfigQueryResponse.class,
ClientNamingAbility.class,
Instance.class,
ServiceInfo.class,
AbstractNamingRequest.class,
InstanceRequest.class,
NotifySubscriberRequest.class,
ServiceQueryRequest.class,
SubscribeServiceRequest.class,
InstanceResponse.class,
NotifySubscriberResponse.class,
QueryServiceResponse.class,
SubscribeServiceResponse.class,
ClientRemoteAbility.class,
ConnectionSetupRequest.class,
HealthCheckRequest.class,
InternalRequest.class,
Request.class,
ServerCheckRequest.class,
ServerRequest.class,
HealthCheckResponse.class,
Response.class,
ServerCheckResponse.class,
TlsConfig.class,
RpcClientTlsConfig.class
};
Class[] classesWithMethods = {
Metadata.class,
com.alibaba.nacos.api.grpc.auto.Metadata.Builder.class,
com.alibaba.nacos.api.grpc.auto.Payload.class,
com.alibaba.nacos.api.grpc.auto.Payload.Builder.class,
NamingService.class,
com.alibaba.nacos.api.remote.Payload.class,
NacosClientAuthServiceImpl.class,
RamClientAuthServiceImpl.class,
NacosConfigService.class,
NacosNamingService.class,
DefaultPublisher.class,
Any.class,
com.alibaba.nacos.shaded.com.google.protobuf.Any.Builder.class,
ExtensionRegistry.class,
AbstractByteBufAllocator.class,
ChannelDuplexHandler.class,
ChannelInboundHandlerAdapter.class,
NioSocketChannel.class,
ByteToMessageDecoder.class,
Http2ConnectionHandler.class,
ReferenceCountUtil.class
};
Class[] classesWithFields = {PropertyKeyConst.class, AbstractFuture.class, AbstractReferenceCountedByteBuf.class
};
Class[] classesWithDefault = {DnsNameResolverProvider.class, PickFirstLoadBalancerProvider.class};
String[] privateClasses = {
"com.alibaba.nacos.shaded.com.google.common.util.concurrent.AbstractFuture.Waiter",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.AbstractNettyHandler",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.WriteBufferingAndExceptionHandler",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.HeadContext",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.TailContext",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueColdProducerFields",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueConsumerFields",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueProducerFields",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueConsumerIndexField",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerIndexField",
"com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerLimitField"
};
for (Class className : classesWithDeclared) {
typeDescribers.add(buildTypeDescriberWithDeclared(className));
}
for (Class className : classesWithMethods) {
typeDescribers.add(buildTypeDescriberWithMethods(className));
}
for (Class className : classesWithFields) {
typeDescribers.add(buildTypeDescriberWithFields(className));
}
for (Class className : classesWithDefault) {
typeDescribers.add(buildTypeDescriberWithDefault(className));
}
for (String className : privateClasses) {
typeDescribers.add(buildTypeDescriberWithDeclared(className));
}
return typeDescribers;
}
private TypeDescriber buildTypeDescriberWithDeclared(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS);
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
memberCategories.add(MemberCategory.DECLARED_FIELDS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithFields(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.DECLARED_FIELDS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithMethods(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS);
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithDefault(Class<?> cl) {
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>());
}
private TypeDescriber buildTypeDescriberWithDeclared(String className) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS);
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
memberCategories.add(MemberCategory.DECLARED_FIELDS);
return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithFields(String className) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.DECLARED_FIELDS);
return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithMethods(String className) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS);
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithDefault(String className) {
return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>());
}
}
|
NacosReflectionTypeDescriberRegistrar
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ExecComponentBuilderFactory.java
|
{
"start": 3907,
"end": 4665
}
|
class ____
extends AbstractComponentBuilder<ExecComponent>
implements ExecComponentBuilder {
@Override
protected ExecComponent buildConcreteComponent() {
return new ExecComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "lazyStartProducer": ((ExecComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((ExecComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
}
|
ExecComponentBuilderImpl
|
java
|
junit-team__junit5
|
junit-jupiter-params/src/main/java/org/junit/jupiter/params/ResolverFacade.java
|
{
"start": 25827,
"end": 26523
}
|
class ____ implements ParameterDeclaration {
/**
* Determine if the supplied {@link Parameter} is an aggregator (i.e., of
* type {@link ArgumentsAccessor} or annotated with {@link AggregateWith}).
*
* @return {@code true} if the parameter is an aggregator
*/
boolean isAggregator() {
return ArgumentsAccessor.class.isAssignableFrom(getParameterType())
|| isAnnotated(getAnnotatedElement(), AggregateWith.class);
}
abstract @Nullable Object resolve(Resolver resolver, ExtensionContext extensionContext,
EvaluatedArgumentSet arguments, int invocationIndex,
Optional<ParameterContext> originalParameterContext);
}
private static
|
ResolvableParameterDeclaration
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/BuildProfileTest.java
|
{
"start": 3780,
"end": 4231
}
|
class ____ implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("X-RF-1", "Value");
}
}
@IfBuildProperty(name = "some.prop1", stringValue = "v") // won't be enabled because the value doesn't match
@Provider
public static
|
ResponseFilter1
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/DescribeTableCommand.java
|
{
"start": 1141,
"end": 2333
}
|
class ____ extends AbstractDdbCommand {
public DescribeTableCommand(DynamoDbClient ddbClient, Ddb2Configuration configuration, Exchange exchange) {
super(ddbClient, configuration, exchange);
}
@Override
public void execute() {
DescribeTableResponse result
= ddbClient.describeTable(DescribeTableRequest.builder().tableName(determineTableName()).build());
Message msg = getMessageForResponse(exchange);
msg.setHeader(Ddb2Constants.TABLE_NAME, result.table().tableName());
msg.setHeader(Ddb2Constants.TABLE_STATUS, result.table().tableStatus());
msg.setHeader(Ddb2Constants.CREATION_DATE, result.table().creationDateTime());
msg.setHeader(Ddb2Constants.ITEM_COUNT, result.table().itemCount());
msg.setHeader(Ddb2Constants.KEY_SCHEMA, result.table().keySchema());
msg.setHeader(Ddb2Constants.READ_CAPACITY, result.table().provisionedThroughput().readCapacityUnits());
msg.setHeader(Ddb2Constants.WRITE_CAPACITY, result.table().provisionedThroughput().writeCapacityUnits());
msg.setHeader(Ddb2Constants.TABLE_SIZE, result.table().tableSizeBytes());
}
}
|
DescribeTableCommand
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/classpermitall/ClassPermitAllBaseResourceWithPath_SecurityOnBase.java
|
{
"start": 1512,
"end": 4239
}
|
class ____ extends ClassPermitAllParentResourceWithoutPath_SecurityOnBase {
@POST
@Path(CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + CLASS_PERMIT_ALL_PATH)
public String get_ClassPathOnResource_ImplOnBase_ImplMethodWithPath_ClassPermitAllPath(JsonObject array) {
return CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + CLASS_PERMIT_ALL_PATH;
}
@PermitAll
@POST
@Path(CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH)
public String get_ClassPathOnResource_ImplOnBase_ImplMethodWithPath_ClassPermitAllMethodPermitAllPath(JsonObject array) {
return CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH;
}
@Override
public String classPathOnResource_ImplOnBase_InterfaceMethodWithPath_ClassPermitAll(JsonObject array) {
return CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + CLASS_PERMIT_ALL_PATH;
}
@PermitAll
@Override
public String classPathOnResource_ImplOnBase_InterfaceMethodWithPath_ClassPermitAllMethodPermitAll(JsonObject array) {
return CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH;
}
@Override
public String test_ClassPathOnResource_ImplOnBase_ParentMethodWithPath_ClassPermitAll(JsonObject array) {
return CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + PARENT_METHOD_WITH_PATH + CLASS_PERMIT_ALL_PATH;
}
@PermitAll
@Override
public String test_ClassPathOnResource_ImplOnBase_ParentMethodWithPath_ClassPermitAllMethodPermitAll(JsonObject array) {
return CLASS_PATH_ON_RESOURCE + IMPL_ON_BASE + PARENT_METHOD_WITH_PATH + CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH;
}
@Path(CLASS_PATH_ON_RESOURCE + SUB_DECLARED_ON_BASE + SUB_IMPL_ON_BASE + CLASS_PERMIT_ALL_PATH)
public ClassPermitAllSubResourceWithoutPath classPathOnResource_SubDeclaredOnBase_SubImplOnBase_ClassPermitAll() {
return new ClassPermitAllSubResourceWithoutPath(
CLASS_PATH_ON_RESOURCE + SUB_DECLARED_ON_BASE + SUB_IMPL_ON_BASE + CLASS_PERMIT_ALL_PATH);
}
@PermitAll
@Path(CLASS_PATH_ON_RESOURCE + SUB_DECLARED_ON_BASE + SUB_IMPL_ON_BASE + CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH)
public ClassPermitAllSubResourceWithoutPath classPathOnResource_SubDeclaredOnBase_SubImplOnBase_ClassPermitAllMethodPermitAll() {
return new ClassPermitAllSubResourceWithoutPath(
CLASS_PATH_ON_RESOURCE + SUB_DECLARED_ON_BASE + SUB_IMPL_ON_BASE + CLASS_PERMIT_ALL_METHOD_PERMIT_ALL_PATH);
}
}
|
ClassPermitAllBaseResourceWithPath_SecurityOnBase
|
java
|
quarkusio__quarkus
|
integration-tests/spring-web/src/test/java/io/quarkus/it/spring/web/SpringCacheControllerTest.java
|
{
"start": 222,
"end": 1000
}
|
class ____ {
@Test
public void testCache() {
// first invocation
RestAssured.when().get("/cache/greet/george").then()
.contentType("application/json")
.body(containsString("george"), containsString("0"));
// second invocation should yield same count
RestAssured.when().get("/cache/greet/george").then()
.contentType("application/json")
.body(containsString("george"), containsString("0"));
// invocation with different key should yield different count
RestAssured.when().get("/cache/greet/michael").then()
.contentType("application/json")
.body(containsString("michael"), containsString("1"));
}
}
|
SpringCacheControllerTest
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/TestSliceTestContextBootstrapper.java
|
{
"start": 1462,
"end": 2437
}
|
class ____<T extends Annotation> extends SpringBootTestContextBootstrapper {
private final Class<T> annotationType;
@SuppressWarnings("unchecked")
protected TestSliceTestContextBootstrapper() {
Class<T> annotationType = (Class<T>) ResolvableType.forClass(getClass())
.as(TestSliceTestContextBootstrapper.class)
.getGeneric(0)
.resolve();
Assert.notNull(annotationType, "'%s' doesn't contain type parameter of '%s'".formatted(getClass().getName(),
TestSliceTestContextBootstrapper.class.getName()));
this.annotationType = annotationType;
}
@Override
protected String @Nullable [] getProperties(Class<?> testClass) {
MergedAnnotation<T> annotation = MergedAnnotations.search(SearchStrategy.TYPE_HIERARCHY)
.withEnclosingClasses(TestContextAnnotationUtils::searchEnclosingClass)
.from(testClass)
.get(this.annotationType);
return annotation.isPresent() ? annotation.getStringArray("properties") : null;
}
}
|
TestSliceTestContextBootstrapper
|
java
|
apache__flink
|
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGeneratorWithOperatorAttributesTest.java
|
{
"start": 18644,
"end": 19171
}
|
class ____<IN, OUT>
extends StreamMap<IN, OUT> {
private final OperatorAttributes attributes;
public StreamOperatorWithConfigurableOperatorAttributes(
MapFunction<IN, OUT> mapper, OperatorAttributes attributes) {
super(mapper);
this.attributes = attributes;
}
@Override
public OperatorAttributes getOperatorAttributes() {
return attributes;
}
}
private static
|
StreamOperatorWithConfigurableOperatorAttributes
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/test/java/org/apache/hadoop/yarn/service/MockRunningServiceContext.java
|
{
"start": 2859,
"end": 8437
}
|
class ____ extends ServiceContext {
public MockRunningServiceContext(ServiceTestUtils.ServiceFSWatcher fsWatcher,
Service serviceDef) throws Exception {
super();
this.service = serviceDef;
this.fs = fsWatcher.getFs();
ContainerLaunchService mockLaunchService = mock(
ContainerLaunchService.class);
this.scheduler = new ServiceScheduler(this) {
@Override
protected YarnRegistryViewForProviders
createYarnRegistryOperations(
ServiceContext context, RegistryOperations registryClient) {
return mock(YarnRegistryViewForProviders.class);
}
@Override
public NMClientAsync createNMClient() {
NMClientAsync nmClientAsync = super.createNMClient();
NMClient nmClient = mock(NMClient.class);
try {
when(nmClient.getContainerStatus(any(), any()))
.thenAnswer(
(Answer<ContainerStatus>) invocation -> ContainerStatus
.newInstance((ContainerId) invocation.getArguments()[0],
org.apache.hadoop.yarn.api.records.ContainerState
.RUNNING,
"", 0));
} catch (YarnException | IOException e) {
throw new RuntimeException(e);
}
nmClientAsync.setClient(nmClient);
return nmClientAsync;
}
@Override
public ContainerLaunchService getContainerLaunchService() {
return mockLaunchService;
}
@Override
public ServiceUtils.ProcessTerminationHandler getTerminationHandler() {
return new
ServiceUtils.ProcessTerminationHandler() {
public void terminate(int exitCode) {
}
};
}
@Override
protected ServiceManager createServiceManager() {
return ServiceTestUtils.createServiceManager(
MockRunningServiceContext.this);
}
};
this.scheduler.init(fsWatcher.getConf());
when(mockLaunchService.launchCompInstance(any(), any(),
any(), any())).thenAnswer(
(Answer<Future<ProviderService.ResolvedLaunchParams>>)
this::launchAndReinitHelper);
when(mockLaunchService.reInitCompInstance(any(), any(),
any(), any())).thenAnswer((
Answer<Future<ProviderService.ResolvedLaunchParams>>)
this::launchAndReinitHelper);
stabilizeComponents(this);
}
private Future<ProviderService.ResolvedLaunchParams> launchAndReinitHelper(
InvocationOnMock invocation) throws IOException, SliderException {
AbstractLauncher launcher = new AbstractLauncher(
scheduler.getContext());
ComponentInstance instance = (ComponentInstance)
invocation.getArguments()[1];
Container container = (Container) invocation.getArguments()[2];
ContainerLaunchService.ComponentLaunchContext clc =
(ContainerLaunchService.ComponentLaunchContext)
invocation.getArguments()[3];
ProviderService.ResolvedLaunchParams resolvedParams =
new ProviderService.ResolvedLaunchParams();
ProviderUtils.createConfigFileAndAddLocalResource(launcher, fs, clc,
new HashMap<>(), instance, scheduler.getContext(), resolvedParams);
ProviderUtils.handleStaticFilesForLocalization(launcher, fs, clc,
resolvedParams);
return Futures.immediateFuture(resolvedParams);
}
private void stabilizeComponents(ServiceContext context) {
ApplicationId appId = ApplicationId.fromString(context.service.getId());
ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(appId, 1);
context.attemptId = attemptId;
Map<String, Component>
componentState = context.scheduler.getAllComponents();
int counter = 0;
for (org.apache.hadoop.yarn.service.api.records.Component componentSpec :
context.service.getComponents()) {
Component component = new org.apache.hadoop.yarn.service.component.
Component(componentSpec, 1L, context);
componentState.put(component.getName(), component);
component.handle(
new ComponentEvent(component.getName(), ComponentEventType.FLEX)
.setDesired(
component.getComponentSpec().getNumberOfContainers()));
for (int i = 0; i < componentSpec.getNumberOfContainers(); i++) {
counter++;
assignNewContainer(attemptId, counter, component);
}
component.handle(new ComponentEvent(component.getName(),
ComponentEventType.CHECK_STABLE));
}
}
public void assignNewContainer(ApplicationAttemptId attemptId,
long containerNum, Component component) {
Container container = org.apache.hadoop.yarn.api.records.Container
.newInstance(ContainerId.newContainerId(attemptId, containerNum),
NODE_ID, "localhost", null, null,
null);
component.handle(new ComponentEvent(component.getName(),
ComponentEventType.CONTAINER_ALLOCATED)
.setContainer(container).setContainerId(container.getId()));
ComponentInstance instance = this.scheduler.getLiveInstances().get(
container.getId());
ComponentInstanceEvent startEvent = new ComponentInstanceEvent(
container.getId(), ComponentInstanceEventType.START);
instance.handle(startEvent);
ComponentInstanceEvent readyEvent = new ComponentInstanceEvent(
container.getId(), ComponentInstanceEventType.BECOME_READY);
instance.handle(readyEvent);
}
private static final NodeId NODE_ID = NodeId.fromString("localhost:0");
}
|
MockRunningServiceContext
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/util/concurrent/FluentFutureTest.java
|
{
"start": 1857,
"end": 3242
}
|
class ____ extends TestCase {
@SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method
public void testFromFluentFuture() {
FluentFuture<String> f = FluentFuture.from(SettableFuture.create());
assertThat(FluentFuture.from(f)).isSameInstanceAs(f);
}
public void testFromFluentFuturePassingAsNonFluent() {
ListenableFuture<String> f = FluentFuture.from(SettableFuture.create());
assertThat(FluentFuture.from(f)).isSameInstanceAs(f);
}
public void testFromNonFluentFuture() throws Exception {
ListenableFuture<String> f =
new SimpleForwardingListenableFuture<String>(immediateFuture("a")) {};
verify(!(f instanceof FluentFuture));
assertThat(FluentFuture.from(f).get()).isEqualTo("a");
// TODO(cpovirk): Test forwarding more extensively.
}
public void testAddCallback() {
FluentFuture<String> f = FluentFuture.from(immediateFuture("a"));
boolean[] called = new boolean[1];
f.addCallback(
new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
called[0] = true;
}
@Override
public void onFailure(Throwable t) {}
},
directExecutor());
assertThat(called[0]).isTrue();
}
// Avoid trouble with automatic mapping between JRE and Kotlin runtime classes.
static
|
FluentFutureTest
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/web/service/invoker/NamedValueArgumentResolverTests.java
|
{
"start": 6378,
"end": 7314
}
|
class ____ extends AbstractNamedValueArgumentResolver {
private final MultiValueMap<String, String> testValues = new LinkedMultiValueMap<>();
TestNamedValueArgumentResolver() {
super(new DefaultFormattingConversionService());
}
public MultiValueMap<String, String> getTestValues() {
return this.testValues;
}
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
TestValue annot = parameter.getParameterAnnotation(TestValue.class);
return (annot == null ? null :
new NamedValueInfo(annot.name(), annot.required(), annot.defaultValue(), "test value", true));
}
@Override
protected void addRequestValue(String name, Object value, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
this.testValues.add(name, (String) value);
}
}
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@
|
TestNamedValueArgumentResolver
|
java
|
apache__flink
|
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Over.java
|
{
"start": 1436,
"end": 2425
}
|
class ____ {
/**
* Partitions the elements on some partition keys.
*
* <p>Each partition is individually sorted and aggregate functions are applied to each
* partition separately.
*
* @param partitionBy list of field references
* @return an over window with defined partitioning
*/
public static OverWindowPartitioned partitionBy(Expression... partitionBy) {
return new OverWindowPartitioned(Arrays.asList(partitionBy));
}
/**
* Specifies the time attribute on which rows are ordered.
*
* <p>For streaming tables, reference a rowtime or proctime time attribute here to specify the
* time mode.
*
* <p>For batch tables, refer to a timestamp or long attribute.
*
* @param orderBy field reference
* @return an over window with defined order
*/
public static OverWindowPartitionedOrdered orderBy(Expression orderBy) {
return partitionBy().orderBy(orderBy);
}
}
|
Over
|
java
|
quarkusio__quarkus
|
integration-tests/picocli-native/src/test/java/io/quarkus/it/picocli/PicocliTest.java
|
{
"start": 5214,
"end": 5638
}
|
class ____ implements QuarkusTestResourceLifecycleManager {
@Override
public Map<String, String> start() {
return Collections.emptyMap();
}
@Override
public void inject(TestInjector testInjector) {
testInjector.injectIntoFields("dummy", f -> f.getName().equals("value"));
}
@Override
public void stop() {
}
}
}
|
TestResource
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/util/JSONPObjectTest.java
|
{
"start": 263,
"end": 1658
}
|
class ____ extends DatabindTestUtil
{
private final String CALLBACK = "callback";
private final ObjectMapper MAPPER = new ObjectMapper();
/**
* Unit tests for checking that JSONP breaking characters U+2028 and U+2029 are escaped when creating a {@link JSONPObject}.
*/
@Test
public void testU2028Escaped() throws IOException {
String containsU2028 = String.format("This string contains %c char", '\u2028');
JSONPObject jsonpObject = new JSONPObject(CALLBACK, containsU2028);
String valueAsString = MAPPER.writeValueAsString(jsonpObject);
assertFalse(valueAsString.contains("\u2028"));
}
@Test
public void testU2029Escaped() throws IOException {
String containsU2029 = String.format("This string contains %c char", '\u2029');
JSONPObject jsonpObject = new JSONPObject(CALLBACK, containsU2029);
String valueAsString = MAPPER.writeValueAsString(jsonpObject);
assertFalse(valueAsString.contains("\u2029"));
}
@Test
public void testU2030NotEscaped() throws IOException {
String containsU2030 = String.format("This string contains %c char", '\u2030');
JSONPObject jsonpObject = new JSONPObject(CALLBACK, containsU2030);
String valueAsString = MAPPER.writeValueAsString(jsonpObject);
assertTrue(valueAsString.contains("\u2030"));
}
}
|
JSONPObjectTest
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/CmSmsComponentBuilderFactory.java
|
{
"start": 3905,
"end": 4655
}
|
class ____
extends AbstractComponentBuilder<CMComponent>
implements CmSmsComponentBuilder {
@Override
protected CMComponent buildConcreteComponent() {
return new CMComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "lazyStartProducer": ((CMComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((CMComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
}
|
CmSmsComponentBuilderImpl
|
java
|
grpc__grpc-java
|
xds/src/test/java/io/grpc/xds/XdsClientWrapperForServerSdsTestMisc.java
|
{
"start": 3904,
"end": 16664
}
|
class ____ {
private static final int PORT = 7000;
private static final int START_WAIT_AFTER_LISTENER_MILLIS = 100;
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private EmbeddedChannel channel;
private ChannelPipeline pipeline;
@Mock private TlsContextManager tlsContextManager;
private InetSocketAddress localAddress;
private DownstreamTlsContext tlsContext1;
private DownstreamTlsContext tlsContext2;
private DownstreamTlsContext tlsContext3;
@Mock
private ServerBuilder<?> mockBuilder;
@Mock
Server mockServer;
@Mock
private XdsServingStatusListener listener;
private FakeXdsClient xdsClient = new FakeXdsClient();
private FilterChainSelectorManager selectorManager = new FilterChainSelectorManager();
private XdsServerWrapper xdsServerWrapper;
@Before
public void setUp() {
tlsContext1 =
CommonTlsContextTestsUtil.buildTestInternalDownstreamTlsContext("CERT1", "VA1");
tlsContext2 =
CommonTlsContextTestsUtil.buildTestInternalDownstreamTlsContext("CERT2", "VA2");
tlsContext3 =
CommonTlsContextTestsUtil.buildTestInternalDownstreamTlsContext("CERT3", "VA3");
when(mockBuilder.build()).thenReturn(mockServer);
when(mockServer.isShutdown()).thenReturn(false);
xdsServerWrapper = new XdsServerWrapper("0.0.0.0:" + PORT, mockBuilder, listener,
selectorManager, new FakeXdsClientPoolFactory(xdsClient),
XdsServerTestHelper.RAW_BOOTSTRAP, FilterRegistry.newRegistry());
}
@Test
public void nonInetSocketAddress_expectNull() throws Exception {
sendListenerUpdate(new InProcessSocketAddress("test1"), null, null, tlsContextManager);
assertThat(getSslContextProviderSupplier(selectorManager.getSelectorToUpdateSelector()))
.isNull();
}
@Test
public void emptyFilterChain_expectNull() throws Exception {
InetAddress ipLocalAddress = InetAddress.getByName("10.1.2.3");
final InetSocketAddress localAddress = new InetSocketAddress(ipLocalAddress, PORT);
InetAddress ipRemoteAddress = InetAddress.getByName("10.4.5.6");
final InetSocketAddress remoteAddress = new InetSocketAddress(ipRemoteAddress, 1234);
channel = new EmbeddedChannel() {
@Override
public SocketAddress localAddress() {
return localAddress;
}
@Override
public SocketAddress remoteAddress() {
return remoteAddress;
}
};
pipeline = channel.pipeline();
final SettableFuture<Server> start = SettableFuture.create();
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
start.set(xdsServerWrapper.start());
} catch (Exception ex) {
start.setException(ex);
}
}
});
String ldsWatched = xdsClient.ldsResource.get(5, TimeUnit.SECONDS);
assertThat(ldsWatched).isEqualTo("grpc/server?udpa.resource.listening_address=0.0.0.0:" + PORT);
EnvoyServerProtoData.Listener tcpListener =
EnvoyServerProtoData.Listener.create(
"listener1",
"0.0.0.0:7000",
ImmutableList.of(),
null,
Protocol.TCP);
LdsUpdate listenerUpdate = LdsUpdate.forTcpListener(tcpListener);
xdsClient.ldsWatcher.onChanged(listenerUpdate);
verify(listener, timeout(5000)).onServing();
start.get(START_WAIT_AFTER_LISTENER_MILLIS, TimeUnit.MILLISECONDS);
FilterChainSelector selector = selectorManager.getSelectorToUpdateSelector();
assertThat(getSslContextProviderSupplier(selector)).isNull();
}
@Test
public void registerServerWatcher_notifyNotFound() throws Exception {
final SettableFuture<Server> start = SettableFuture.create();
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
start.set(xdsServerWrapper.start());
} catch (Exception ex) {
start.setException(ex);
}
}
});
String ldsWatched = xdsClient.ldsResource.get(5, TimeUnit.SECONDS);
xdsClient.ldsWatcher.onResourceDoesNotExist(ldsWatched);
verify(listener, timeout(5000)).onNotServing(any());
try {
start.get(START_WAIT_AFTER_LISTENER_MILLIS, TimeUnit.MILLISECONDS);
fail("Start should throw exception");
} catch (TimeoutException ex) {
assertThat(start.isDone()).isFalse();
}
assertThat(selectorManager.getSelectorToUpdateSelector()).isSameInstanceAs(NO_FILTER_CHAIN);
}
@Test
public void releaseOldSupplierOnChanged_noCloseDueToLazyLoading() throws Exception {
InetAddress ipLocalAddress = InetAddress.getByName("10.1.2.3");
localAddress = new InetSocketAddress(ipLocalAddress, PORT);
sendListenerUpdate(localAddress, tlsContext2, null,
tlsContextManager);
verify(tlsContextManager, never())
.findOrCreateServerSslContextProvider(any(DownstreamTlsContext.class));
}
@Test
public void releaseOldSupplierOnChangedOnShutdown_verifyClose() throws Exception {
SslContextProvider sslContextProvider1 = mock(SslContextProvider.class);
when(tlsContextManager.findOrCreateServerSslContextProvider(eq(tlsContext1)))
.thenReturn(sslContextProvider1);
InetAddress ipLocalAddress = InetAddress.getByName("10.1.2.3");
localAddress = new InetSocketAddress(ipLocalAddress, PORT);
sendListenerUpdate(localAddress, tlsContext1, null,
tlsContextManager);
SslContextProviderSupplier returnedSupplier =
getSslContextProviderSupplier(selectorManager.getSelectorToUpdateSelector());
assertThat(returnedSupplier.getTlsContext()).isSameInstanceAs(tlsContext1);
callUpdateSslContext(returnedSupplier);
XdsServerTestHelper
.generateListenerUpdate(xdsClient, ImmutableList.of(1234), tlsContext2,
tlsContext3, tlsContextManager);
returnedSupplier = getSslContextProviderSupplier(selectorManager.getSelectorToUpdateSelector());
assertThat(returnedSupplier.getTlsContext()).isSameInstanceAs(tlsContext2);
verify(tlsContextManager, times(1)).releaseServerSslContextProvider(eq(sslContextProvider1));
reset(tlsContextManager);
SslContextProvider sslContextProvider2 = mock(SslContextProvider.class);
when(tlsContextManager.findOrCreateServerSslContextProvider(eq(tlsContext2)))
.thenReturn(sslContextProvider2);
SslContextProvider sslContextProvider3 = mock(SslContextProvider.class);
when(tlsContextManager.findOrCreateServerSslContextProvider(eq(tlsContext3)))
.thenReturn(sslContextProvider3);
callUpdateSslContext(returnedSupplier);
InetAddress ipRemoteAddress = InetAddress.getByName("10.4.5.6");
final InetSocketAddress remoteAddress = new InetSocketAddress(ipRemoteAddress, 1111);
channel = new EmbeddedChannel() {
@Override
public SocketAddress localAddress() {
return localAddress;
}
@Override
public SocketAddress remoteAddress() {
return remoteAddress;
}
};
pipeline = channel.pipeline();
returnedSupplier = getSslContextProviderSupplier(selectorManager.getSelectorToUpdateSelector());
assertThat(returnedSupplier.getTlsContext()).isSameInstanceAs(tlsContext3);
callUpdateSslContext(returnedSupplier);
xdsServerWrapper.shutdown();
assertThat(xdsClient.ldsResource).isNull();
verify(tlsContextManager, never()).releaseServerSslContextProvider(eq(sslContextProvider1));
verify(tlsContextManager, times(1)).releaseServerSslContextProvider(eq(sslContextProvider2));
verify(tlsContextManager, times(1)).releaseServerSslContextProvider(eq(sslContextProvider3));
}
@Test
public void releaseOldSupplierOnNotFound_verifyClose() throws Exception {
SslContextProvider sslContextProvider1 = mock(SslContextProvider.class);
when(tlsContextManager.findOrCreateServerSslContextProvider(eq(tlsContext1)))
.thenReturn(sslContextProvider1);
InetAddress ipLocalAddress = InetAddress.getByName("10.1.2.3");
localAddress = new InetSocketAddress(ipLocalAddress, PORT);
sendListenerUpdate(localAddress, tlsContext1, null,
tlsContextManager);
SslContextProviderSupplier returnedSupplier =
getSslContextProviderSupplier(selectorManager.getSelectorToUpdateSelector());
assertThat(returnedSupplier.getTlsContext()).isSameInstanceAs(tlsContext1);
callUpdateSslContext(returnedSupplier);
xdsClient.ldsWatcher.onResourceDoesNotExist("not-found Error");
verify(tlsContextManager, times(1)).releaseServerSslContextProvider(eq(sslContextProvider1));
}
@Test
public void releaseOldSupplierOnTemporaryError_noClose() throws Exception {
SslContextProvider sslContextProvider1 = mock(SslContextProvider.class);
when(tlsContextManager.findOrCreateServerSslContextProvider(eq(tlsContext1)))
.thenReturn(sslContextProvider1);
InetAddress ipLocalAddress = InetAddress.getByName("10.1.2.3");
localAddress = new InetSocketAddress(ipLocalAddress, PORT);
sendListenerUpdate(localAddress, tlsContext1, null,
tlsContextManager);
SslContextProviderSupplier returnedSupplier =
getSslContextProviderSupplier(selectorManager.getSelectorToUpdateSelector());
assertThat(returnedSupplier.getTlsContext()).isSameInstanceAs(tlsContext1);
callUpdateSslContext(returnedSupplier);
xdsClient.ldsWatcher.onError(Status.CANCELLED);
verify(tlsContextManager, never()).releaseServerSslContextProvider(eq(sslContextProvider1));
}
private void callUpdateSslContext(SslContextProviderSupplier sslContextProviderSupplier) {
assertThat(sslContextProviderSupplier).isNotNull();
SslContextProvider.Callback callback = mock(SslContextProvider.Callback.class);
sslContextProviderSupplier.updateSslContext(callback, false);
}
private void sendListenerUpdate(
final SocketAddress localAddress, DownstreamTlsContext tlsContext,
DownstreamTlsContext tlsContextForDefaultFilterChain, TlsContextManager tlsContextManager)
throws Exception {
final SettableFuture<Server> start = SettableFuture.create();
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
start.set(xdsServerWrapper.start());
} catch (Exception ex) {
start.setException(ex);
}
}
});
xdsClient.ldsResource.get(5, TimeUnit.SECONDS);
XdsServerTestHelper
.generateListenerUpdate(xdsClient, ImmutableList.of(), tlsContext,
tlsContextForDefaultFilterChain, tlsContextManager);
verify(listener, timeout(5000)).onServing();
start.get(START_WAIT_AFTER_LISTENER_MILLIS, TimeUnit.MILLISECONDS);
InetAddress ipRemoteAddress = InetAddress.getByName("10.4.5.6");
final InetSocketAddress remoteAddress = new InetSocketAddress(ipRemoteAddress, 1234);
channel = new EmbeddedChannel() {
@Override
public SocketAddress localAddress() {
return localAddress;
}
@Override
public SocketAddress remoteAddress() {
return remoteAddress;
}
};
pipeline = channel.pipeline();
}
private SslContextProviderSupplier getSslContextProviderSupplier(
FilterChainSelector selector) throws Exception {
final SettableFuture<SslContextProviderSupplier> sslSet = SettableFuture.create();
ChannelHandler next = new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
ProtocolNegotiationEvent e = (ProtocolNegotiationEvent)evt;
sslSet.set(InternalProtocolNegotiationEvent.getAttributes(e)
.get(ATTR_SERVER_SSL_CONTEXT_PROVIDER_SUPPLIER));
ctx.pipeline().remove(this);
}
};
ProtocolNegotiator mockDelegate = mock(ProtocolNegotiator.class);
GrpcHttp2ConnectionHandler grpcHandler = FakeGrpcHttp2ConnectionHandler.newHandler();
when(mockDelegate.newHandler(grpcHandler)).thenReturn(next);
FilterChainSelectorManager manager = new FilterChainSelectorManager();
manager.updateSelector(selector);
FilterChainMatchingHandler filterChainMatchingHandler =
new FilterChainMatchingHandler(grpcHandler, manager, mockDelegate);
pipeline.addLast(filterChainMatchingHandler);
ProtocolNegotiationEvent event = InternalProtocolNegotiationEvent.getDefault();
pipeline.fireUserEventTriggered(event);
channel.runPendingTasks();
sslSet.set(InternalProtocolNegotiationEvent.getAttributes(event)
.get(ATTR_SERVER_SSL_CONTEXT_PROVIDER_SUPPLIER));
return sslSet.get();
}
private static final
|
XdsClientWrapperForServerSdsTestMisc
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTest.java
|
{
"start": 214979,
"end": 216091
}
|
class ____ {
OperatorSubtaskState subtaskState;
TestingOperatorStateHandle managedOpHandle;
TestingOperatorStateHandle rawOpHandle;
OperatorSubtaskStateMock() {
this.managedOpHandle = new TestingOperatorStateHandle();
this.rawOpHandle = new TestingOperatorStateHandle();
this.subtaskState =
OperatorSubtaskState.builder()
.setManagedOperatorState(managedOpHandle)
.setRawOperatorState(rawOpHandle)
.build();
}
public OperatorSubtaskState getSubtaskState() {
return this.subtaskState;
}
public void reset() {
managedOpHandle.reset();
rawOpHandle.reset();
}
public void verifyDiscard() {
assert (managedOpHandle.isDiscarded() && rawOpHandle.discarded);
}
public void verifyNotDiscard() {
assert (!managedOpHandle.isDiscarded() && !rawOpHandle.isDiscarded());
}
private static
|
OperatorSubtaskStateMock
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/javadoc/NotJavadoc.java
|
{
"start": 2241,
"end": 4531
}
|
class ____ extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableMap<Integer, TreePath> javadocableTrees = getJavadoccableTrees(tree);
ImmutableSet<Integer> seeminglyJavadocableTrees = getSeeminglyJavadocableTrees(tree);
ImmutableRangeSet<Integer> suppressedRegions = suppressedRegions(state);
for (ErrorProneToken token : getTokens(state.getSourceCode().toString(), state.context)) {
for (ErrorProneComment comment : token.comments()) {
if (!comment.getStyle().equals(ErrorProneCommentStyle.JAVADOC_BLOCK)
|| comment.getText().equals("/**/")) {
continue;
}
if (javadocableTrees.containsKey(token.pos())) {
continue;
}
if (suppressedRegions.intersects(
Range.closed(
comment.getSourcePos(0), comment.getSourcePos(comment.getText().length() - 1)))) {
continue;
}
int endPos = 2;
while (comment.getText().charAt(endPos) == '*') {
endPos++;
}
var message =
seeminglyJavadocableTrees.contains(token.pos())
? "This comment seems to be attached to a method or class, but methods and classes"
+ " nested within methods cannot be documented with Javadoc."
: message();
state.reportMatch(
buildDescription(getDiagnosticPosition(comment.getSourcePos(0), tree))
.setMessage(message)
.addFix(replace(comment.getSourcePos(1), comment.getSourcePos(endPos - 1), ""))
.build());
}
}
return NO_MATCH;
}
private static ImmutableSet<Integer> getSeeminglyJavadocableTrees(CompilationUnitTree tree) {
ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
tree.accept(
new TreeScanner<Void, Void>() {
@Override
public Void scan(Tree tree, Void unused) {
if (tree instanceof MethodTree || tree instanceof ClassTree) {
builder.add(getStartPosition(tree));
}
return super.scan(tree, null);
}
},
null);
return builder.build();
}
}
|
NotJavadoc
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/plugins/PluginsServiceTests.java
|
{
"start": 39120,
"end": 39346
}
|
class ____ implements TestExtensionPoint {
public ThrowingConstructorExtension() {
throw new IllegalArgumentException("test constructor failure");
}
}
public static
|
ThrowingConstructorExtension
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-it/src/test/resources/jbang/it/from-source-dir/FromDirectoryRoute.java
|
{
"start": 857,
"end": 1123
}
|
class ____ extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:java?period={{time:1000}}")
.setBody()
.simple("Hello world!")
.log("${body}");
}
}
|
FromDirectoryRoute
|
java
|
apache__camel
|
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvContainingMultiQuoteCharEscapeFalseTest.java
|
{
"start": 1435,
"end": 5019
}
|
class ____ extends CamelTestSupport {
@EndpointInject("mock:resultMarshal1")
private MockEndpoint mockEndPointMarshal1;
@EndpointInject("mock:resultUnMarshal1")
private MockEndpoint mockEndPointUnMarshal1;
@EndpointInject("mock:resultMarshal2")
private MockEndpoint mockEndPointMarshal2;
@EndpointInject("mock:resultUnMarshal2")
private MockEndpoint mockEndPointUnMarshal2;
@Test
public void testMarshallCsvRecordFieldContainingMultiEscapedQuoteChar() throws Exception {
mockEndPointMarshal1.expectedMessageCount(1);
mockEndPointMarshal1
.expectedBodiesReceived("\"123\",\"\"\"foo\"\"\",\"10\"" + ConverterUtils.getStringCarriageReturn("WINDOWS"));
BindyCsvRowFormat75191 body = new BindyCsvRowFormat75191();
body.setFirstField("123");
body.setSecondField("\"foo\"");
body.setNumber(new BigDecimal(10));
template.sendBody("direct:startMarshal1", body);
MockEndpoint.assertIsSatisfied(context);
BindyCsvRowFormat75191 model
= mockEndPointUnMarshal1.getReceivedExchanges().get(0).getIn().getBody(BindyCsvRowFormat75191.class);
assertEquals("123", model.getFirstField());
assertEquals("\"foo\"", model.getSecondField());
assertEquals(new BigDecimal(10), model.getNumber());
}
@Test
public void testMarshallCsvRecordFieldContainingMultiNonEscapedQuoteChar() throws Exception {
mockEndPointMarshal2.expectedMessageCount(1);
mockEndPointMarshal2.expectedBodiesReceived("'123','''foo''','10'" + ConverterUtils.getStringCarriageReturn("WINDOWS"));
BindyCsvRowFormat75192 body = new BindyCsvRowFormat75192();
body.setFirstField("123");
body.setSecondField("''foo''");
body.setNumber(new BigDecimal(10));
template.sendBody("direct:startMarshal2", body);
MockEndpoint.assertIsSatisfied(context);
BindyCsvRowFormat75192 model
= mockEndPointUnMarshal2.getReceivedExchanges().get(0).getIn().getBody(BindyCsvRowFormat75192.class);
assertEquals("123", model.getFirstField());
assertEquals("''foo''", model.getSecondField());
assertEquals(new BigDecimal(10), model.getNumber());
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
BindyCsvDataFormat camelDataFormat1 = new BindyCsvDataFormat(BindyCsvRowFormat75191.class);
from("direct:startMarshal1")
.marshal(camelDataFormat1)
.to("mock:resultMarshal1")
.to("direct:middle1");
from("direct:middle1")
.unmarshal(camelDataFormat1)
.to("mock:resultUnMarshal1");
BindyCsvDataFormat camelDataFormat2 = new BindyCsvDataFormat(BindyCsvRowFormat75192.class);
from("direct:startMarshal2")
.marshal(camelDataFormat2)
.to("mock:resultMarshal2")
.to("direct:middle2");
from("direct:middle2")
.unmarshal(camelDataFormat2)
.to("mock:resultUnMarshal2");
}
};
}
//from https://issues.apache.org/jira/browse/CAMEL-7519
@CsvRecord(separator = ",", quote = "\"", quoting = true, quotingEscaped = false)
public static
|
BindySimpleCsvContainingMultiQuoteCharEscapeFalseTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/OptionalMapUnusedValueTest.java
|
{
"start": 2085,
"end": 2456
}
|
class ____ {
private Integer foo(Integer v) {
return v;
}
public void bar(Optional<Integer> optional) {
optional.map(v -> foo(v));
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.util.Optional;
|
Test
|
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/event/SchedulerEventType.java
|
{
"start": 887,
"end": 1710
}
|
enum ____ {
// Source: Node
NODE_ADDED,
NODE_REMOVED,
NODE_UPDATE,
NODE_RESOURCE_UPDATE,
NODE_LABELS_UPDATE,
NODE_ATTRIBUTES_UPDATE,
// Source: RMApp
APP_ADDED,
APP_REMOVED,
// Source: RMAppAttempt
APP_ATTEMPT_ADDED,
APP_ATTEMPT_REMOVED,
// Source: ContainerAllocationExpirer
CONTAINER_EXPIRED,
// Source: SchedulerAppAttempt::pullNewlyUpdatedContainer.
RELEASE_CONTAINER,
/* Source: SchedulingEditPolicy */
KILL_RESERVED_CONTAINER,
// Mark a container for preemption
MARK_CONTAINER_FOR_PREEMPTION,
// Mark a for-preemption container killable
MARK_CONTAINER_FOR_KILLABLE,
// Cancel a killable container
MARK_CONTAINER_FOR_NONKILLABLE,
//Queue Management Change
MANAGE_QUEUE,
// Auto created queue, auto deletion check
AUTO_QUEUE_DELETION
}
|
SchedulerEventType
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/jta/JtaAwareConnectionProviderImpl.java
|
{
"start": 28436,
"end": 46798
}
|
class ____ implements PreparedStatement {
private final PreparedStatement delegate;
private final ConnectionWrapper connectionWrapper;
private PreparedStatementWrapper(PreparedStatement delegate, ConnectionWrapper connectionWrapper) {
this.delegate = delegate;
this.connectionWrapper = connectionWrapper;
}
@Override
public ResultSet executeQuery() throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeQuery();
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public int executeUpdate() throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeUpdate();
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
delegate.setNull( parameterIndex, sqlType );
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
delegate.setBoolean( parameterIndex, x );
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
delegate.setByte( parameterIndex, x );
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
delegate.setShort( parameterIndex, x );
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
delegate.setInt( parameterIndex, x );
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
delegate.setLong( parameterIndex, x );
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
delegate.setFloat( parameterIndex, x );
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
delegate.setDouble( parameterIndex, x );
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
delegate.setBigDecimal( parameterIndex, x );
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
delegate.setString( parameterIndex, x );
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
delegate.setBytes( parameterIndex, x );
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
delegate.setDate( parameterIndex, x );
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
delegate.setTime( parameterIndex, x );
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
delegate.setTimestamp( parameterIndex, x );
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
delegate.setAsciiStream( parameterIndex, x, length );
}
@Override
@Deprecated(since = "1.2")
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
delegate.setUnicodeStream( parameterIndex, x, length );
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
delegate.setBinaryStream( parameterIndex, x, length );
}
@Override
public void clearParameters() throws SQLException {
delegate.clearParameters();
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
delegate.setObject( parameterIndex, x, targetSqlType );
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
delegate.setObject( parameterIndex, x );
}
@Override
public boolean execute() throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.execute();
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public void addBatch() throws SQLException {
delegate.addBatch();
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
delegate.setCharacterStream( parameterIndex, reader, length );
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
delegate.setRef( parameterIndex, x );
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
delegate.setBlob( parameterIndex, x );
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
delegate.setClob( parameterIndex, x );
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
delegate.setArray( parameterIndex, x );
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return delegate.getMetaData();
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
delegate.setDate( parameterIndex, x, cal );
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
delegate.setTime( parameterIndex, x, cal );
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
delegate.setTimestamp( parameterIndex, x, cal );
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
delegate.setNull( parameterIndex, sqlType, typeName );
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
delegate.setURL( parameterIndex, x );
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return delegate.getParameterMetaData();
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
delegate.setRowId( parameterIndex, x );
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
delegate.setNString( parameterIndex, value );
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
delegate.setNCharacterStream( parameterIndex, value, length );
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
delegate.setNClob( parameterIndex, value );
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
delegate.setClob( parameterIndex, reader, length );
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
delegate.setBlob( parameterIndex, inputStream, length );
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
delegate.setNClob( parameterIndex, reader, length );
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
delegate.setSQLXML( parameterIndex, xmlObject );
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
delegate.setObject( parameterIndex, x, targetSqlType, scaleOrLength );
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
delegate.setAsciiStream( parameterIndex, x, length );
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
delegate.setBinaryStream( parameterIndex, x, length );
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
delegate.setCharacterStream( parameterIndex, reader, length );
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
delegate.setAsciiStream( parameterIndex, x );
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
delegate.setBinaryStream( parameterIndex, x );
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
delegate.setCharacterStream( parameterIndex, reader );
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
delegate.setNCharacterStream( parameterIndex, value );
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
delegate.setClob( parameterIndex, reader );
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
delegate.setBlob( parameterIndex, inputStream );
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
delegate.setNClob( parameterIndex, reader );
}
@Override
public void setObject(int parameterIndex, Object x, SQLType targetSqlType, int scaleOrLength)
throws SQLException {
delegate.setObject( parameterIndex, x, targetSqlType, scaleOrLength );
}
@Override
public void setObject(int parameterIndex, Object x, SQLType targetSqlType) throws SQLException {
delegate.setObject( parameterIndex, x, targetSqlType );
}
@Override
public long executeLargeUpdate() throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeLargeUpdate();
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeQuery( sql );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public int executeUpdate(String sql) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeUpdate( sql );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public void close() throws SQLException {
delegate.close();
}
@Override
public int getMaxFieldSize() throws SQLException {
return delegate.getMaxFieldSize();
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
delegate.setMaxFieldSize( max );
}
@Override
public int getMaxRows() throws SQLException {
return delegate.getMaxRows();
}
@Override
public void setMaxRows(int max) throws SQLException {
delegate.setMaxRows( max );
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
delegate.setEscapeProcessing( enable );
}
@Override
public int getQueryTimeout() throws SQLException {
return delegate.getQueryTimeout();
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
delegate.setQueryTimeout( seconds );
}
@Override
public void cancel() throws SQLException {
delegate.cancel();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return delegate.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
delegate.clearWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
delegate.setCursorName( name );
}
@Override
public boolean execute(String sql) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.execute( sql );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public ResultSet getResultSet() throws SQLException {
return delegate.getResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return delegate.getUpdateCount();
}
@Override
public boolean getMoreResults() throws SQLException {
return delegate.getMoreResults();
}
@Override
public void setFetchDirection(int direction) throws SQLException {
delegate.setFetchDirection( direction );
}
@Override
public int getFetchDirection() throws SQLException {
return delegate.getFetchDirection();
}
@Override
public void setFetchSize(int rows) throws SQLException {
delegate.setFetchSize( rows );
}
@Override
public int getFetchSize() throws SQLException {
return delegate.getFetchSize();
}
@Override
public int getResultSetConcurrency() throws SQLException {
return delegate.getResultSetConcurrency();
}
@Override
public int getResultSetType() throws SQLException {
return delegate.getResultSetType();
}
@Override
public void addBatch(String sql) throws SQLException {
delegate.addBatch( sql );
}
@Override
public void clearBatch() throws SQLException {
delegate.clearBatch();
}
@Override
public int[] executeBatch() throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeBatch();
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public Connection getConnection() throws SQLException {
return connectionWrapper;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return delegate.getMoreResults( current );
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return delegate.getGeneratedKeys();
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeUpdate( sql, autoGeneratedKeys );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeUpdate( sql, columnIndexes );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeUpdate( sql, columnNames );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.execute( sql, autoGeneratedKeys );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.execute( sql, columnIndexes );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.execute( sql, columnNames );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public int getResultSetHoldability() throws SQLException {
return delegate.getResultSetHoldability();
}
@Override
public boolean isClosed() throws SQLException {
return delegate.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
delegate.setPoolable( poolable );
}
@Override
public boolean isPoolable() throws SQLException {
return delegate.isPoolable();
}
@Override
public void closeOnCompletion() throws SQLException {
delegate.closeOnCompletion();
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return delegate.isCloseOnCompletion();
}
@Override
public long getLargeUpdateCount() throws SQLException {
return delegate.getLargeUpdateCount();
}
@Override
public void setLargeMaxRows(long max) throws SQLException {
delegate.setLargeMaxRows( max );
}
@Override
public long getLargeMaxRows() throws SQLException {
return delegate.getLargeMaxRows();
}
@Override
public long[] executeLargeBatch() throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeLargeBatch();
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public long executeLargeUpdate(String sql) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeLargeUpdate( sql );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeLargeUpdate( sql, autoGeneratedKeys );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeLargeUpdate( sql, columnIndexes );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException {
try {
connectionWrapper.setRunningStatement( delegate );
return delegate.executeLargeUpdate( sql, columnNames );
}
finally {
connectionWrapper.setRunningStatement( null );
}
}
@Override
public String enquoteLiteral(String val) throws SQLException {
return delegate.enquoteLiteral( val );
}
@Override
public String enquoteIdentifier(String identifier, boolean alwaysQuote) throws SQLException {
return delegate.enquoteIdentifier( identifier, alwaysQuote );
}
@Override
public boolean isSimpleIdentifier(String identifier) throws SQLException {
return delegate.isSimpleIdentifier( identifier );
}
@Override
public String enquoteNCharLiteral(String val) throws SQLException {
return delegate.enquoteNCharLiteral( val );
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return delegate.unwrap( iface );
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return delegate.isWrapperFor( iface );
}
}
private static
|
PreparedStatementWrapper
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/discovery/pkg2/PackageLevelSoftDeleteTests2.java
|
{
"start": 586,
"end": 938
}
|
class ____ {
@Test
public void verifySchema(SessionFactoryScope scope) {
final MappingMetamodelImplementor metamodel = scope.getSessionFactory().getMappingMetamodel();
MappingVerifier.verifyMapping(
metamodel.getEntityDescriptor( AnEntity.class ).getSoftDeleteMapping(),
"gone",
"the_table",
'T'
);
}
}
|
PackageLevelSoftDeleteTests2
|
java
|
greenrobot__greendao
|
DaoCore/src/main/java/org/greenrobot/greendao/internal/SqlUtils.java
|
{
"start": 860,
"end": 6577
}
|
class ____ {
private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static StringBuilder appendProperty(StringBuilder builder, String tablePrefix, Property property) {
if (tablePrefix != null) {
builder.append(tablePrefix).append('.');
}
builder.append('"').append(property.columnName).append('"');
return builder;
}
public static StringBuilder appendColumn(StringBuilder builder, String column) {
builder.append('"').append(column).append('"');
return builder;
}
public static StringBuilder appendColumn(StringBuilder builder, String tableAlias, String column) {
builder.append(tableAlias).append(".\"").append(column).append('"');
return builder;
}
public static StringBuilder appendColumns(StringBuilder builder, String tableAlias, String[] columns) {
int length = columns.length;
for (int i = 0; i < length; i++) {
appendColumn(builder, tableAlias, columns[i]);
if (i < length - 1) {
builder.append(',');
}
}
return builder;
}
public static StringBuilder appendColumns(StringBuilder builder, String[] columns) {
int length = columns.length;
for (int i = 0; i < length; i++) {
builder.append('"').append(columns[i]).append('"');
if (i < length - 1) {
builder.append(',');
}
}
return builder;
}
public static StringBuilder appendPlaceholders(StringBuilder builder, int count) {
for (int i = 0; i < count; i++) {
if (i < count - 1) {
builder.append("?,");
} else {
builder.append('?');
}
}
return builder;
}
public static StringBuilder appendColumnsEqualPlaceholders(StringBuilder builder, String[] columns) {
for (int i = 0; i < columns.length; i++) {
appendColumn(builder, columns[i]).append("=?");
if (i < columns.length - 1) {
builder.append(',');
}
}
return builder;
}
public static StringBuilder appendColumnsEqValue(StringBuilder builder, String tableAlias, String[] columns) {
for (int i = 0; i < columns.length; i++) {
appendColumn(builder, tableAlias, columns[i]).append("=?");
if (i < columns.length - 1) {
builder.append(',');
}
}
return builder;
}
public static String createSqlInsert(String insertInto, String tablename, String[] columns) {
StringBuilder builder = new StringBuilder(insertInto);
builder.append('"').append(tablename).append('"').append(" (");
appendColumns(builder, columns);
builder.append(") VALUES (");
appendPlaceholders(builder, columns.length);
builder.append(')');
return builder.toString();
}
/** Creates an select for given columns with a trailing space */
public static String createSqlSelect(String tablename, String tableAlias, String[] columns, boolean distinct) {
if (tableAlias == null || tableAlias.length() < 0) {
throw new DaoException("Table alias required");
}
StringBuilder builder = new StringBuilder(distinct ? "SELECT DISTINCT " : "SELECT ");
SqlUtils.appendColumns(builder, tableAlias, columns).append(" FROM ");
builder.append('"').append(tablename).append('"').append(' ').append(tableAlias).append(' ');
return builder.toString();
}
/** Creates SELECT COUNT(*) with a trailing space. */
public static String createSqlSelectCountStar(String tablename, String tableAliasOrNull) {
StringBuilder builder = new StringBuilder("SELECT COUNT(*) FROM ");
builder.append('"').append(tablename).append('"').append(' ');
if (tableAliasOrNull != null) {
builder.append(tableAliasOrNull).append(' ');
}
return builder.toString();
}
/** Remember: SQLite does not support joins nor table alias for DELETE. */
public static String createSqlDelete(String tablename, String[] columns) {
String quotedTablename = '"' + tablename + '"';
StringBuilder builder = new StringBuilder("DELETE FROM ");
builder.append(quotedTablename);
if (columns != null && columns.length > 0) {
builder.append(" WHERE ");
appendColumnsEqValue(builder, quotedTablename, columns);
}
return builder.toString();
}
public static String createSqlUpdate(String tablename, String[] updateColumns, String[] whereColumns) {
String quotedTablename = '"' + tablename + '"';
StringBuilder builder = new StringBuilder("UPDATE ");
builder.append(quotedTablename).append(" SET ");
appendColumnsEqualPlaceholders(builder, updateColumns);
builder.append(" WHERE ");
appendColumnsEqValue(builder, quotedTablename, whereColumns);
return builder.toString();
}
public static String createSqlCount(String tablename) {
return "SELECT COUNT(*) FROM \"" + tablename +'"';
}
public static String escapeBlobArgument(byte[] bytes) {
return "X'" + toHex(bytes) + '\'';
}
public static String toHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int byteValue = bytes[i] & 0xFF;
hexChars[i * 2] = HEX_ARRAY[byteValue >>> 4];
hexChars[i * 2 + 1] = HEX_ARRAY[byteValue & 0x0F];
}
return new String(hexChars);
}
}
|
SqlUtils
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListConsumer.java
|
{
"start": 1732,
"end": 11569
}
|
class ____ extends ProcessWatchCommand {
@CommandLine.Parameters(description = "Name or pid of running Camel integration", arity = "0..1")
String name = "*";
@CommandLine.Option(names = { "--sort" }, completionCandidates = PidNameAgeCompletionCandidates.class,
description = "Sort by pid, name or age", defaultValue = "pid")
String sort;
@CommandLine.Option(names = { "--limit" },
description = "Filter consumers by limiting to the given number of rows")
int limit;
@CommandLine.Option(names = { "--filter" },
description = "Filter consumers by URI")
String filter;
@CommandLine.Option(names = { "--scheduled" },
description = "Filter consumer to only show scheduled based consumers")
boolean scheduled;
@CommandLine.Option(names = { "--short-uri" },
description = "List endpoint URI without query parameters (short)")
boolean shortUri;
@CommandLine.Option(names = { "--wide-uri" },
description = "List endpoint URI in full details")
boolean wideUri;
public ListConsumer(CamelJBangMain main) {
super(main);
}
@Override
public Integer doProcessWatchCall() throws Exception {
List<Row> rows = new ArrayList<>();
// make it easier to filter
if (filter != null && !filter.endsWith("*")) {
filter += "*";
}
List<Long> pids = findPids(name);
ProcessHandle.allProcesses()
.filter(ph -> pids.contains(ph.pid()))
.forEach(ph -> {
JsonObject root = loadStatus(ph.pid());
if (root != null) {
JsonObject context = (JsonObject) root.get("context");
JsonObject jo = (JsonObject) root.get("consumers");
if (context != null && jo != null) {
JsonArray array = (JsonArray) jo.get("consumers");
for (int i = 0; i < array.size(); i++) {
JsonObject o = (JsonObject) array.get(i);
Row row = new Row();
row.name = context.getString("name");
if ("CamelJBang".equals(row.name)) {
row.name = ProcessHelper.extractName(root, ph);
}
row.pid = Long.toString(ph.pid());
row.id = o.getString("id");
row.uri = o.getString("uri");
row.state = o.getString("state");
row.className = o.getString("class");
row.hostedService = o.getBooleanOrDefault("hostedService", false);
row.scheduled = o.getBoolean("scheduled");
row.inflight = o.getInteger("inflight");
row.polling = o.getBoolean("polling");
row.totalCounter = o.getLong("totalCounter");
row.delay = o.getLong("delay");
row.period = o.getLong("period");
row.uptime = extractSince(ph);
row.age = TimeUtils.printSince(row.uptime);
Map<String, ?> stats = o.getMap("statistics");
if (stats != null) {
Object last = stats.get("lastCreatedExchangeTimestamp");
if (last != null) {
long time = Long.parseLong(last.toString());
row.sinceLastStarted = TimeUtils.printSince(time);
}
last = stats.get("lastCompletedExchangeTimestamp");
if (last != null) {
long time = Long.parseLong(last.toString());
row.sinceLastCompleted = TimeUtils.printSince(time);
}
last = stats.get("lastFailedExchangeTimestamp");
if (last != null) {
long time = Long.parseLong(last.toString());
row.sinceLastFailed = TimeUtils.printSince(time);
}
}
boolean add = true;
if (filter != null) {
String f = filter;
boolean negate = filter.startsWith("-");
if (negate) {
f = f.substring(1);
}
boolean match = PatternHelper.matchPattern(row.uri, f);
if (negate) {
match = !match;
}
if (!match) {
add = false;
}
}
if (scheduled && !row.scheduled) {
add = false;
}
if (limit > 0 && rows.size() >= limit) {
add = false;
}
if (add) {
rows.add(row);
}
}
}
}
});
// sort rows
rows.sort(this::sortRow);
if (!rows.isEmpty()) {
printTable(rows);
}
return 0;
}
protected void printTable(List<Row> rows) {
printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, Arrays.asList(
new Column().header("PID").headerAlign(HorizontalAlign.CENTER).with(r -> r.pid),
new Column().header("NAME").dataAlign(HorizontalAlign.LEFT).maxWidth(30, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(r -> r.name),
new Column().header("AGE").headerAlign(HorizontalAlign.CENTER).with(r -> r.age),
new Column().header("ID").dataAlign(HorizontalAlign.LEFT).maxWidth(20, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(r -> r.id),
new Column().header("STATUS").headerAlign(HorizontalAlign.CENTER).with(this::getState),
new Column().header("TYPE").dataAlign(HorizontalAlign.LEFT).maxWidth(20, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getType),
new Column().header("INFLIGHT").with(r -> Integer.toString(r.inflight)),
new Column().header("POLL").with(this::getTotal),
new Column().header("PERIOD").visible(scheduled).with(this::getPeriod),
new Column().header("SINCE-LAST").with(this::getSinceLast),
new Column().header("URI").visible(!wideUri).dataAlign(HorizontalAlign.LEFT)
.maxWidth(90, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getUri),
new Column().header("URI").visible(wideUri).dataAlign(HorizontalAlign.LEFT)
.maxWidth(140, OverflowBehaviour.NEWLINE)
.with(this::getUri))));
}
private String getUri(Row r) {
String u = r.uri;
if (shortUri) {
int pos = u.indexOf('?');
if (pos > 0) {
u = u.substring(0, pos);
}
}
return u;
}
private String getState(Row r) {
if (r.polling != null && r.polling) {
return "Polling";
}
return r.state;
}
private String getType(Row r) {
String s = r.className;
if (s.endsWith("Consumer")) {
s = s.substring(0, s.length() - 8);
}
return s;
}
private String getTotal(Row r) {
if (r.totalCounter != null) {
return String.valueOf(r.totalCounter);
}
return "";
}
private String getPeriod(Row r) {
// favour using period, fallback to delay
if (r.period != null) {
return String.valueOf(r.period);
} else if (r.delay != null) {
return String.valueOf(r.delay);
}
return "";
}
protected String getSinceLast(Row r) {
String s1 = r.sinceLastStarted != null ? r.sinceLastStarted : "-";
String s2 = r.sinceLastCompleted != null ? r.sinceLastCompleted : "-";
String s3 = r.sinceLastFailed != null ? r.sinceLastFailed : "-";
return s1 + "/" + s2 + "/" + s3;
}
protected int sortRow(Row o1, Row o2) {
String s = sort;
int negate = 1;
if (s.startsWith("-")) {
s = s.substring(1);
negate = -1;
}
switch (s) {
case "pid":
return Long.compare(Long.parseLong(o1.pid), Long.parseLong(o2.pid)) * negate;
case "name":
return o1.name.compareToIgnoreCase(o2.name) * negate;
case "age":
return Long.compare(o1.uptime, o2.uptime) * negate;
default:
return 0;
}
}
static
|
ListConsumer
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/AnnotationEnclosingClassSample.java
|
{
"start": 938,
"end": 1007
}
|
class ____ {
@EnclosedTwo
public static
|
AnnotationEnclosingClassSample
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/transforms/TransformHealthIssue.java
|
{
"start": 793,
"end": 4511
}
|
class ____ implements Writeable, ToXContentObject {
private static final String TYPE = "type";
private static final String ISSUE = "issue";
private static final String DETAILS = "details";
private static final String COUNT = "count";
private static final String FIRST_OCCURRENCE = "first_occurrence";
private static final String FIRST_OCCURRENCE_HUMAN_READABLE = FIRST_OCCURRENCE + "_string";
private static final String DEFAULT_TYPE_PRE_8_8 = "unknown";
private final String type;
private final String issue;
private final String details;
private final int count;
private final Instant firstOccurrence;
public TransformHealthIssue(String type, String issue, String details, int count, Instant firstOccurrence) {
this.type = Objects.requireNonNull(type);
this.issue = Objects.requireNonNull(issue);
this.details = details;
if (count < 1) {
throw new IllegalArgumentException("[count] must be at least 1, got: " + count);
}
this.count = count;
this.firstOccurrence = firstOccurrence != null ? firstOccurrence.truncatedTo(ChronoUnit.MILLIS) : null;
}
public TransformHealthIssue(StreamInput in) throws IOException {
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
this.type = in.readString();
} else {
this.type = DEFAULT_TYPE_PRE_8_8;
}
this.issue = in.readString();
this.details = in.readOptionalString();
this.count = in.readVInt();
this.firstOccurrence = in.readOptionalInstant();
}
public String getType() {
return type;
}
public String getIssue() {
return issue;
}
public String getDetails() {
return details;
}
public int getCount() {
return count;
}
public Instant getFirstOccurrence() {
return firstOccurrence;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(TYPE, type);
builder.field(ISSUE, issue);
if (Strings.isNullOrEmpty(details) == false) {
builder.field(DETAILS, details);
}
builder.field(COUNT, count);
if (firstOccurrence != null) {
builder.timestampFieldsFromUnixEpochMillis(FIRST_OCCURRENCE, FIRST_OCCURRENCE_HUMAN_READABLE, firstOccurrence.toEpochMilli());
}
return builder.endObject();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
out.writeString(type);
}
out.writeString(issue);
out.writeOptionalString(details);
out.writeVInt(count);
out.writeOptionalInstant(firstOccurrence);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
TransformHealthIssue that = (TransformHealthIssue) other;
return this.count == that.count
&& Objects.equals(this.type, that.type)
&& Objects.equals(this.issue, that.issue)
&& Objects.equals(this.details, that.details)
&& Objects.equals(this.firstOccurrence, that.firstOccurrence);
}
@Override
public int hashCode() {
return Objects.hash(type, issue, details, count, firstOccurrence);
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
}
|
TransformHealthIssue
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/calcite/rex/RexUtil.java
|
{
"start": 119915,
"end": 121906
}
|
class ____ extends RexShuttle {
private final RexBuilder rexBuilder;
private final @Nullable RexProgram program;
private final int maxComplexity;
SearchExpandingShuttle(
@Nullable RexProgram program, RexBuilder rexBuilder, int maxComplexity) {
this.program = program;
this.rexBuilder = rexBuilder;
this.maxComplexity = maxComplexity;
}
@Override
public RexNode visitCall(RexCall call) {
final boolean[] update = {false};
final List<RexNode> clonedOperands;
switch (call.getKind()) {
// Flatten AND/OR operands.
case OR:
clonedOperands = visitList(call.operands, update);
if (update[0]) {
return composeDisjunction(rexBuilder, clonedOperands);
} else {
return call;
}
case AND:
clonedOperands = visitList(call.operands, update);
if (update[0]) {
return composeConjunction(rexBuilder, clonedOperands);
} else {
return call;
}
case SEARCH:
final RexNode ref = call.operands.get(0);
final RexLiteral literal = (RexLiteral) deref(program, call.operands.get(1));
final Sarg sarg = requireNonNull(literal.getValueAs(Sarg.class), "Sarg");
if (maxComplexity < 0 || sarg.complexity() < maxComplexity) {
return sargRef(
rexBuilder, ref, sarg, literal.getType(), RexUnknownAs.UNKNOWN);
}
// Sarg is complex (therefore useful); fall through
default:
return super.visitCall(call);
}
}
}
}
|
SearchExpandingShuttle
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalTest.java
|
{
"start": 831,
"end": 2523
}
|
class ____ extends TestCase {
public void testEval() throws Exception {
assertEquals("A", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "?", "A"));
assertEquals(123, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "?", 123));
}
public void testEval_1() throws Exception {
assertEquals("AB", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? + ?", "A", "B"));
assertEquals(234, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? + ?", 123, 111));
}
public void testEval_2() throws Exception {
assertEquals(110, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? * ?", 10, 11));
}
public void testEval_3() throws Exception {
assertEquals(new BigDecimal("110"), SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? * ?",
new BigDecimal("10"),
new BigDecimal("11")));
}
public void testEval_4() throws Exception {
assertEquals(new BigDecimal("110"),
SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? * 11", new BigDecimal("10")));
}
public void testEval_5() throws Exception {
assertEquals(new BigDecimal("110.0"),
SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? * 11.0", new BigDecimal("10")));
}
public void testEval_6() throws Exception {
assertEquals(new BigDecimal("110.0"),
SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? * 11", new BigDecimal("10.0")));
}
public void testEval_7() throws Exception {
assertEquals(new BigDecimal("110.0"),
SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "? * 11.0", "10"));
}
}
|
EvalTest
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/util/Encode.java
|
{
"start": 572,
"end": 18301
}
|
class ____ {
private static final String UTF_8 = StandardCharsets.UTF_8.name();
private static final Pattern PARAM_REPLACEMENT = Pattern.compile("_resteasy_uri_parameter");
private static final String[] pathEncoding = new String[128];
private static final String[] pathSegmentEncoding = new String[128];
private static final String[] matrixParameterEncoding = new String[128];
private static final String[] queryNameValueEncoding = new String[128];
private static final String[] queryStringEncoding = new String[128];
static {
/*
* Encode via <a href="https://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. PCHAR is allowed allong with '/'
*
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*
*/
for (int i = 0; i < 128; i++) {
if (i >= 'a' && i <= 'z')
continue;
if (i >= 'A' && i <= 'Z')
continue;
if (i >= '0' && i <= '9')
continue;
switch ((char) i) {
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case '/':
case ';':
case '=':
case ':':
case '@':
continue;
}
pathEncoding[i] = encodeString(String.valueOf((char) i));
}
pathEncoding[' '] = "%20";
System.arraycopy(pathEncoding, 0, matrixParameterEncoding, 0, pathEncoding.length);
matrixParameterEncoding[';'] = "%3B";
matrixParameterEncoding['='] = "%3D";
matrixParameterEncoding['/'] = "%2F"; // RESTEASY-729
System.arraycopy(pathEncoding, 0, pathSegmentEncoding, 0, pathEncoding.length);
pathSegmentEncoding['/'] = "%2F";
/*
* Encode via <a href="https://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* space encoded as '+'
*
*/
for (int i = 0; i < 128; i++) {
if (i >= 'a' && i <= 'z')
continue;
if (i >= 'A' && i <= 'Z')
continue;
if (i >= '0' && i <= '9')
continue;
switch ((char) i) {
case '-':
case '.':
case '_':
case '~':
continue;
case '?':
queryNameValueEncoding[i] = "%3F";
continue;
case ' ':
queryNameValueEncoding[i] = "+";
continue;
}
queryNameValueEncoding[i] = encodeString(String.valueOf((char) i));
}
/*
* query = *( pchar / "/" / "?" )
*
*/
for (int i = 0; i < 128; i++) {
if (i >= 'a' && i <= 'z')
continue;
if (i >= 'A' && i <= 'Z')
continue;
if (i >= '0' && i <= '9')
continue;
switch ((char) i) {
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case ';':
case '=':
case ':':
case '@':
case '?':
case '/':
continue;
case ' ':
queryStringEncoding[i] = "%20";
continue;
}
queryStringEncoding[i] = encodeString(String.valueOf((char) i));
}
}
/**
* Keep encoded values "%..." and template parameters intact.
*
* @param value query string
* @return encoded query string
*/
public static String encodeQueryString(String value) {
return encodeValue(value, queryStringEncoding);
}
/**
* Keep encoded values "%...", matrix parameters, template parameters, and '/' characters intact.
*
* @param value path
* @return encoded path
*/
public static String encodePath(String value) {
return encodeValue(value, pathEncoding);
}
/**
* Keep encoded values "%...", matrix parameters and template parameters intact.
*
* @param value path segment
* @return encoded path segment
*/
public static String encodePathSegment(String value) {
return encodeValue(value, pathSegmentEncoding);
}
/**
* Keep encoded values "%..." and template parameters intact.
*
* @param value uri fragment
* @return encoded uri fragment
*/
public static String encodeFragment(String value) {
return encodeValue(value, queryStringEncoding);
}
/**
* Keep encoded values "%..." and template parameters intact.
*
* @param value matrix parameter
* @return encoded matrix parameter
*/
public static String encodeMatrixParam(String value) {
return encodeValue(value, matrixParameterEncoding);
}
/**
* Keep encoded values "%..." and template parameters intact.
*
* @param value query parameter
* @return encoded query parameter
*/
public static String encodeQueryParam(String value) {
return encodeValue(value, queryNameValueEncoding);
}
//private static final Pattern nonCodes = Pattern.compile("%([^a-fA-F0-9]|$)");
private static final Pattern nonCodes = Pattern.compile("%([^a-fA-F0-9]|[a-fA-F0-9]$|$|[a-fA-F0-9][^a-fA-F0-9])");
private static final Pattern encodedChars = Pattern.compile("%([a-fA-F0-9][a-fA-F0-9])");
private static final Pattern encodedCharsMulti = Pattern.compile("((%[a-fA-F0-9][a-fA-F0-9])+)");
public static String decodePath(String path) {
// FIXME: this doesn't appear to pass the TCK, because it fails to decode what it throws at it
// also it doesn't decode slashes (it should) and it decodes + (it should not)
// return URLUtils.decode(path, StandardCharsets.UTF_8, false, null);
// So let's use the Vertx decoder for now
return URIDecoder.decodeURIComponent(path, false);
}
private static String decodeBytes(String enc, CharsetDecoder decoder) {
Matcher matcher = encodedChars.matcher(enc);
ByteBuffer bytes = ByteBuffer.allocate(enc.length() / 3);
while (matcher.find()) {
int b = Integer.parseInt(matcher.group(1), 16);
bytes.put((byte) b);
}
bytes.flip();
try {
return decoder.decode(bytes).toString();
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
}
/**
* Encode '%' if it is not an encoding sequence
*
* @param string value to encode
* @return encoded value
*/
public static String encodeNonCodes(String string) {
Matcher matcher = nonCodes.matcher(string);
StringBuilder builder = new StringBuilder();
// FYI: we do not use the no-arg matcher.find()
// coupled with matcher.appendReplacement()
// because the matched text may contain
// a second % and we must make sure we
// encode it (if necessary).
int idx = 0;
while (matcher.find(idx)) {
int start = matcher.start();
builder.append(string.substring(idx, start));
builder.append("%25");
idx = start + 1;
}
builder.append(string.substring(idx));
return builder.toString();
}
public static boolean savePathParams(String segmentString, StringBuilder newSegment, List<String> params) {
boolean foundParam = false;
// Regular expressions can have '{' and '}' characters. Replace them to do match
CharSequence segment = PathHelper.replaceEnclosedCurlyBracesCS(segmentString);
Matcher matcher = PathHelper.URI_TEMPLATE_PATTERN.matcher(segment);
int start = 0;
while (matcher.find()) {
newSegment.append(segment, start, matcher.start());
foundParam = true;
String group = matcher.group();
// Regular expressions can have '{' and '}' characters. Recover earlier replacement
params.add(PathHelper.recoverEnclosedCurlyBraces(group));
newSegment.append("_resteasy_uri_parameter");
start = matcher.end();
}
newSegment.append(segment, start, segment.length());
return foundParam;
}
/**
* Keep encoded values "%..." and template parameters intact i.e. "{x}"
*
* @param segment value to encode
* @param encoding encoding
* @return encoded value
*/
public static String encodeValue(String segment, String[] encoding) {
ArrayList<String> params = new ArrayList<String>();
boolean foundParam = false;
StringBuilder newSegment = new StringBuilder();
if (savePathParams(segment, newSegment, params)) {
foundParam = true;
segment = newSegment.toString();
}
String result = encodeFromArray(segment, encoding, false);
result = encodeNonCodes(result);
segment = result;
if (foundParam) {
segment = pathParamReplacement(segment, params);
}
return segment;
}
/**
* Encode via <a href="https://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. PCHAR is allowed allong with '/'
* <p>
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*
* @param segment value to encode
* @return encoded value
*/
public static String encodePathAsIs(String segment) {
return encodeFromArray(segment, pathEncoding, true);
}
/**
* Keep any valid encodings from string i.e. keep "%2D" but don't keep "%p"
*
* @param segment value to encode
* @return encoded value
*/
public static String encodePathSaveEncodings(String segment) {
String result = encodeFromArray(segment, pathEncoding, false);
result = encodeNonCodes(result);
return result;
}
/**
* Encode via <a href="https://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. PCHAR is allowed allong with '/'
* <p>
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*
* @param segment value to encode
* @return encoded value
*/
public static String encodePathSegmentAsIs(String segment) {
return encodeFromArray(segment, pathSegmentEncoding, true);
}
/**
* Keep any valid encodings from string i.e. keep "%2D" but don't keep "%p"
*
* @param segment value to encode
* @return encoded value
*/
public static String encodePathSegmentSaveEncodings(String segment) {
String result = encodeFromArray(segment, pathSegmentEncoding, false);
result = encodeNonCodes(result);
return result;
}
/**
* Encodes everything of a query parameter name or value.
*
* @param nameOrValue value to encode
* @return encoded value
*/
public static String encodeQueryParamAsIs(String nameOrValue) {
return encodeFromArray(nameOrValue, queryNameValueEncoding, true);
}
/**
* Keep any valid encodings from string i.e. keep "%2D" but don't keep "%p"
*
* @param segment value to encode
* @return encoded value
*/
public static String encodeQueryParamSaveEncodings(String segment) {
String result = encodeFromArray(segment, queryNameValueEncoding, false);
result = encodeNonCodes(result);
return result;
}
public static String encodeFragmentAsIs(String nameOrValue) {
return encodeFromArray(nameOrValue, queryNameValueEncoding, true);
}
protected static String encodeFromArray(String segment, String[] encodingMap, boolean encodePercent) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < segment.length(); i++) {
char currentChar = segment.charAt(i);
if (!encodePercent && currentChar == '%') {
result.append(currentChar);
continue;
}
if (Character.isHighSurrogate(currentChar)) {
String part = segment.substring(i, i + 2);
result.append(URLEncoder.encode(part, StandardCharsets.UTF_8));
++i;
continue;
}
String encoding = encode(currentChar, encodingMap);
if (encoding == null) {
result.append(currentChar);
} else {
result.append(encoding);
}
}
return result.toString();
}
/**
* @param zhar integer representation of character
* @param encodingMap encoding map
* @return URL encoded character
*/
private static String encode(int zhar, String[] encodingMap) {
String encoded;
if (zhar < encodingMap.length) {
encoded = encodingMap[zhar];
} else {
encoded = encodeString(Character.toString((char) zhar));
}
return encoded;
}
/**
* Calls URLEncoder.encode(s, "UTF-8") on given input.
*
* @param s string to encode
* @return encoded string returned by URLEncoder.encode(s, "UTF-8")
*/
public static String encodeString(String s) {
try {
return URLEncoder.encode(s, UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static String pathParamReplacement(String segment, List<String> params) {
StringBuilder newSegment = new StringBuilder();
Matcher matcher = PARAM_REPLACEMENT.matcher(segment);
int i = 0;
int start = 0;
while (matcher.find()) {
newSegment.append(segment, start, matcher.start());
String replacement = params.get(i++);
newSegment.append(replacement);
start = matcher.end();
}
newSegment.append(segment, start, segment.length());
segment = newSegment.toString();
return segment;
}
/**
* decode an encoded map
*
* @param map map
* @return decoded map
*/
public static MultivaluedMap<String, String> decode(MultivaluedMap<String, String> map) {
MultivaluedMap<String, String> decoded = new QuarkusMultivaluedHashMap<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
try {
decoded.add(URLDecoder.decode(entry.getKey(), UTF_8), URLDecoder.decode(value, UTF_8));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
return decoded;
}
/**
* decode an encoded map
*
* @param map map
* @param charset charset
* @return decoded map
*/
public static MultivaluedMap<String, String> decode(MultivaluedMap<String, String> map, String charset) {
if (charset == null) {
charset = UTF_8;
}
MultivaluedMap<String, String> decoded = new QuarkusMultivaluedHashMap<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
try {
decoded.add(URLDecoder.decode(entry.getKey(), charset), URLDecoder.decode(value, charset));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
return decoded;
}
public static MultivaluedMap<String, String> encode(MultivaluedMap<String, String> map) {
MultivaluedMap<String, String> decoded = new QuarkusMultivaluedHashMap<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
try {
decoded.add(URLEncoder.encode(entry.getKey(), UTF_8), URLEncoder.encode(value, UTF_8));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
return decoded;
}
public static String decode(String string) {
try {
return URLDecoder.decode(string, UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
|
Encode
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/superclass/auditoverride/AuditedBaseEntity.java
|
{
"start": 466,
"end": 2078
}
|
class ____ implements Serializable {
@Id
@GeneratedValue
private Integer id;
private String str1;
private Integer number1;
public AuditedBaseEntity() {
}
public AuditedBaseEntity(String str1, Integer number1, Integer id) {
this.id = id;
this.str1 = str1;
this.number1 = number1;
}
public AuditedBaseEntity(String str1, Integer number1) {
this.str1 = str1;
this.number1 = number1;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
public Integer getNumber1() {
return number1;
}
public void setNumber1(Integer number1) {
this.number1 = number1;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof AuditedBaseEntity) ) {
return false;
}
AuditedBaseEntity that = (AuditedBaseEntity) o;
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
if ( number1 != null ? !number1.equals( that.number1 ) : that.number1 != null ) {
return false;
}
if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + (str1 != null ? str1.hashCode() : 0);
result = 31 * result + (number1 != null ? number1.hashCode() : 0);
return result;
}
public String toString() {
return "AuditedBaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")";
}
}
|
AuditedBaseEntity
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationTests.java
|
{
"start": 1200,
"end": 4552
}
|
class ____ {
@Test
@SuppressWarnings("NullAway") // Test null check
void createWithLogLevelWhenNameIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new LoggerConfiguration(null, null, LogLevel.DEBUG))
.withMessage("'name' must not be null");
}
@Test
@SuppressWarnings("NullAway") // Test null check
void createWithLogLevelWhenEffectiveLevelIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new LoggerConfiguration("test", null, (LogLevel) null))
.withMessage("'effectiveLevel' must not be null");
}
@Test
@SuppressWarnings("NullAway") // Test null check
void createWithLevelConfigurationWhenNameIsNullThrowsException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LoggerConfiguration(null, null, LevelConfiguration.of(LogLevel.DEBUG)))
.withMessage("'name' must not be null");
}
@Test
@SuppressWarnings("NullAway") // Test null check
void createWithLevelConfigurationWhenInheritedLevelConfigurationIsNullThrowsException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LoggerConfiguration("test", null, (LevelConfiguration) null))
.withMessage("'inheritedLevelConfiguration' must not be null");
}
@Test
void getNameReturnsName() {
LoggerConfiguration configuration = new LoggerConfiguration("test", null,
LevelConfiguration.of(LogLevel.DEBUG));
assertThat(configuration.getName()).isEqualTo("test");
}
@Test
void getConfiguredLevelWhenConfiguredReturnsLevel() {
LoggerConfiguration configuration = new LoggerConfiguration("test", LevelConfiguration.of(LogLevel.DEBUG),
LevelConfiguration.of(LogLevel.DEBUG));
assertThat(configuration.getConfiguredLevel()).isEqualTo(LogLevel.DEBUG);
}
@Test
void getConfiguredLevelWhenNotConfiguredReturnsNull() {
LoggerConfiguration configuration = new LoggerConfiguration("test", null,
LevelConfiguration.of(LogLevel.DEBUG));
assertThat(configuration.getConfiguredLevel()).isNull();
}
@Test
void getEffectiveLevelReturnsEffectiveLevel() {
LoggerConfiguration configuration = new LoggerConfiguration("test", null,
LevelConfiguration.of(LogLevel.DEBUG));
assertThat(configuration.getEffectiveLevel()).isEqualTo(LogLevel.DEBUG);
}
@Test
void getLevelConfigurationWithDirectScopeWhenConfiguredReturnsConfiguration() {
LevelConfiguration assigned = LevelConfiguration.of(LogLevel.DEBUG);
LoggerConfiguration configuration = new LoggerConfiguration("test", assigned,
LevelConfiguration.of(LogLevel.DEBUG));
assertThat(configuration.getLevelConfiguration(ConfigurationScope.DIRECT)).isEqualTo(assigned);
}
@Test
void getLevelConfigurationWithDirectScopeWhenNotConfiguredReturnsNull() {
LoggerConfiguration configuration = new LoggerConfiguration("test", null,
LevelConfiguration.of(LogLevel.DEBUG));
assertThat(configuration.getLevelConfiguration(ConfigurationScope.DIRECT)).isNull();
}
@Test
void getLevelConfigurationWithInheritedScopeReturnsConfiguration() {
LevelConfiguration effective = LevelConfiguration.of(LogLevel.DEBUG);
LoggerConfiguration configuration = new LoggerConfiguration("test", null, effective);
assertThat(configuration.getLevelConfiguration(ConfigurationScope.INHERITED)).isEqualTo(effective);
}
/**
* Tests for {@link LevelConfiguration}.
*/
@Nested
|
LoggerConfigurationTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joincolumn/StringToCharArrayJoinColumnTest.java
|
{
"start": 1096,
"end": 2623
}
|
class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
Vehicle vehicle = new Vehicle();
vehicle.setId( 1L );
vehicle.setCharArrayProp( "2020".toCharArray() );
session.persist( vehicle );
VehicleInvoice invoice = new VehicleInvoice();
invoice.setId( "2020" );
invoice.setVehicle( vehicle );
vehicle.getInvoices().add( invoice );
session.persist( invoice );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.createMutationQuery( "delete from VehicleInvoice" ).executeUpdate();
session.createMutationQuery( "delete from Vehicle" ).executeUpdate();
} );
}
@Test
public void testAssociation(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final VehicleInvoice vehicleInvoice = session.createQuery(
"from VehicleInvoice",
VehicleInvoice.class
).getSingleResult();
assertEquals( 1L, vehicleInvoice.getVehicle().getId() );
assertEquals( "2020", new String( vehicleInvoice.getVehicle().getCharArrayProp() ) );
} );
}
@Test
public void testInverse(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final Vehicle vehicle = session.createQuery(
"from Vehicle",
Vehicle.class
).getSingleResult();
assertEquals( 1, vehicle.getInvoices().size() );
assertEquals( "2020", vehicle.getInvoices().get( 0 ).getId() );
} );
}
@Entity(name = "VehicleInvoice")
public static
|
StringToCharArrayJoinColumnTest
|
java
|
quarkusio__quarkus
|
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/fieldvisibility/FieldVisibilityResource.java
|
{
"start": 685,
"end": 1102
}
|
class ____ {
public Book book;
public Customer customer;
public int count; // hidden in the schema
}
@Query
public Purchase someFirstQuery(Book book, Customer customer, Purchase purchase) {
return purchase;
}
@Query
public Customer someSecondQuery() {
return null;
}
@Query
public Book someThirdQuery() {
return null;
}
}
|
Purchase
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/format/datetime/standard/DurationFormatterUtilsTests.java
|
{
"start": 11598,
"end": 14538
}
|
class ____ {
@Test
void longValueFromUnit() {
Duration nanos = Duration.ofSeconds(3).plusMillis(22).plusNanos(1111);
assertThat(Unit.NANOS.longValue(nanos))
.as("NANOS")
.isEqualTo(3022001111L);
assertThat(Unit.MICROS.longValue(nanos))
.as("MICROS")
.isEqualTo(3022001);
assertThat(Unit.MILLIS.longValue(nanos))
.as("MILLIS")
.isEqualTo(3022);
assertThat(Unit.SECONDS.longValue(nanos))
.as("SECONDS")
.isEqualTo(3);
Duration minutes = Duration.ofHours(1).plusMinutes(23);
assertThat(Unit.MINUTES.longValue(minutes))
.as("MINUTES")
.isEqualTo(83);
assertThat(Unit.HOURS.longValue(minutes))
.as("HOURS")
.isEqualTo(1);
Duration days = Duration.ofHours(48 + 5);
assertThat(Unit.HOURS.longValue(days))
.as("HOURS in days")
.isEqualTo(53);
assertThat(Unit.DAYS.longValue(days))
.as("DAYS")
.isEqualTo(2);
}
@Test
void unitFromSuffix() {
assertThat(Unit.fromSuffix("ns")).as("ns").isEqualTo(Unit.NANOS);
assertThat(Unit.fromSuffix("us")).as("us").isEqualTo(Unit.MICROS);
assertThat(Unit.fromSuffix("ms")).as("ms").isEqualTo(Unit.MILLIS);
assertThat(Unit.fromSuffix("s")).as("s").isEqualTo(Unit.SECONDS);
assertThat(Unit.fromSuffix("m")).as("m").isEqualTo(Unit.MINUTES);
assertThat(Unit.fromSuffix("h")).as("h").isEqualTo(Unit.HOURS);
assertThat(Unit.fromSuffix("d")).as("d").isEqualTo(Unit.DAYS);
assertThatIllegalArgumentException().isThrownBy(() -> Unit.fromSuffix("ws"))
.withMessage("'ws' is not a valid simple duration Unit");
}
@Test
void unitFromChronoUnit() {
assertThat(Unit.fromChronoUnit(ChronoUnit.NANOS)).as("ns").isEqualTo(Unit.NANOS);
assertThat(Unit.fromChronoUnit(ChronoUnit.MICROS)).as("us").isEqualTo(Unit.MICROS);
assertThat(Unit.fromChronoUnit(ChronoUnit.MILLIS)).as("ms").isEqualTo(Unit.MILLIS);
assertThat(Unit.fromChronoUnit(ChronoUnit.SECONDS)).as("s").isEqualTo(Unit.SECONDS);
assertThat(Unit.fromChronoUnit(ChronoUnit.MINUTES)).as("m").isEqualTo(Unit.MINUTES);
assertThat(Unit.fromChronoUnit(ChronoUnit.HOURS)).as("h").isEqualTo(Unit.HOURS);
assertThat(Unit.fromChronoUnit(ChronoUnit.DAYS)).as("d").isEqualTo(Unit.DAYS);
assertThatIllegalArgumentException().isThrownBy(() -> Unit.fromChronoUnit(ChronoUnit.CENTURIES))
.withMessage("No matching Unit for ChronoUnit.CENTURIES");
}
@Test
void unitSuffixSmokeTest() {
assertThat(Arrays.stream(Unit.values()).map(u -> u.name() + "->" + u.asSuffix()))
.containsExactly("NANOS->ns", "MICROS->us", "MILLIS->ms", "SECONDS->s",
"MINUTES->m", "HOURS->h", "DAYS->d");
}
@Test
void chronoUnitSmokeTest() {
assertThat(Arrays.stream(Unit.values()).map(Unit::asChronoUnit))
.containsExactly(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS,
ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS);
}
}
}
|
DurationFormatUnit
|
java
|
apache__rocketmq
|
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/namesrv/QueryDataVersionResponseHeader.java
|
{
"start": 1061,
"end": 1653
}
|
class ____ implements CommandCustomHeader {
@CFNotNull
private Boolean changed;
@Override
public void checkFields() throws RemotingCommandException {
}
public Boolean getChanged() {
return changed;
}
public void setChanged(Boolean changed) {
this.changed = changed;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("QueryDataVersionResponseHeader{");
sb.append("changed=").append(changed);
sb.append('}');
return sb.toString();
}
}
|
QueryDataVersionResponseHeader
|
java
|
quarkusio__quarkus
|
extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/hotreload/MyResource.java
|
{
"start": 128,
"end": 240
}
|
class ____ {
@GET
public String hello() {
return "hello";
}
// <placeholder>
}
|
MyResource
|
java
|
quarkusio__quarkus
|
independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/utils/Patterns.java
|
{
"start": 123,
"end": 1946
}
|
class ____ {
public static boolean isExpression(String s) {
return s == null || s.isEmpty() ? false : s.contains("*") || s.contains("?");
}
public static Pattern toRegex(final String str) {
try {
String wildcardToRegex = wildcardToRegex(str);
if (wildcardToRegex != null && !wildcardToRegex.isEmpty()) {
return Pattern.compile(wildcardToRegex);
}
} catch (PatternSyntaxException e) {
//ignore it
}
return null;
}
private static String wildcardToRegex(String wildcard) {
// don't try with file match char in pattern
if (!isExpression(wildcard)) {
return null;
}
StringBuffer s = new StringBuffer(wildcard.length());
s.append("^.*");
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch (c) {
case '*':
s.append(".*");
break;
case '?':
s.append(".");
break;
case '^': // escape character in cmd.exe
s.append("\\");
break;
// escape special regexp-characters
case '(':
case ')':
case '[':
case ']':
case '$':
case '.':
case '{':
case '}':
case '|':
case '\\':
s.append("\\");
s.append(c);
break;
default:
s.append(c);
break;
}
}
s.append(".*$");
return (s.toString());
}
}
|
Patterns
|
java
|
micronaut-projects__micronaut-core
|
aop/src/main/java/io/micronaut/aop/Introduction.java
|
{
"start": 1343,
"end": 1790
}
|
interface ____ {
* }
* </code></pre>
*
* <p>Note that the annotation MUST be {@link java.lang.annotation.RetentionPolicy#RUNTIME} and the specified {@link io.micronaut.context.annotation.Type} must implement {@link MethodInterceptor}</p>
*
* @author Graeme Rocher
* @since 1.0
*/
@Documented
@Retention(RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
@InterceptorBinding(kind = InterceptorKind.INTRODUCTION)
public @
|
Example
|
java
|
apache__dubbo
|
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServletExchanger.java
|
{
"start": 1067,
"end": 2023
}
|
class ____ {
private static final AtomicReference<URL> url = new AtomicReference<>();
private static final AtomicReference<Integer> serverPort = new AtomicReference<>();
private static boolean ENABLED = false;
public static void init(Configuration configuration) {
ENABLED = configuration.getBoolean(Constants.H2_SETTINGS_SERVLET_ENABLED, false);
}
private ServletExchanger() {}
public static boolean isEnabled() {
return ENABLED;
}
public static void bind(URL url) {
ServletExchanger.url.compareAndSet(null, url);
}
public static void bindServerPort(int serverPort) {
ServletExchanger.serverPort.compareAndSet(null, serverPort);
}
public static URL getUrl() {
return Objects.requireNonNull(url.get(), "ServletExchanger not bound to triple protocol");
}
public static Integer getServerPort() {
return serverPort.get();
}
}
|
ServletExchanger
|
java
|
netty__netty
|
common/src/main/java/io/netty/util/concurrent/ProgressiveFuture.java
|
{
"start": 763,
"end": 1568
}
|
interface ____<V> extends Future<V> {
@Override
ProgressiveFuture<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
@Override
ProgressiveFuture<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
@Override
ProgressiveFuture<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);
@Override
ProgressiveFuture<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
@Override
ProgressiveFuture<V> sync() throws InterruptedException;
@Override
ProgressiveFuture<V> syncUninterruptibly();
@Override
ProgressiveFuture<V> await() throws InterruptedException;
@Override
ProgressiveFuture<V> awaitUninterruptibly();
}
|
ProgressiveFuture
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java
|
{
"start": 2567,
"end": 2687
}
|
class ____ {
@Id
private Integer id;
public Role() {
}
public Role(Integer id) {
this.id = id;
}
}
}
|
Role
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java
|
{
"start": 6393,
"end": 8955
}
|
class ____ any of its constructors or for any of its {@code @Bean} methods.
*/
private boolean reliesOnPackageVisibility(Class<?> configSuperClass) {
int mod = configSuperClass.getModifiers();
if (!Modifier.isPublic(mod) && !Modifier.isProtected(mod)) {
return true;
}
for (Constructor<?> ctor : configSuperClass.getDeclaredConstructors()) {
mod = ctor.getModifiers();
if (!Modifier.isPublic(mod) && !Modifier.isProtected(mod)) {
return true;
}
}
for (Method method : ReflectionUtils.getDeclaredMethods(configSuperClass)) {
if (BeanAnnotationHelper.isBeanAnnotated(method)) {
mod = method.getModifiers();
if (!Modifier.isPublic(mod) && !Modifier.isProtected(mod)) {
return true;
}
}
}
return false;
}
/**
* Creates a new CGLIB {@link Enhancer} instance.
*/
private Enhancer newEnhancer(Class<?> configSuperClass, @Nullable ClassLoader classLoader) {
Enhancer enhancer = new Enhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader smartClassLoader &&
smartClassLoader.isClassReloadable(configSuperClass)) {
enhancer.setUseCache(false);
}
}
enhancer.setSuperclass(configSuperClass);
enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
enhancer.setUseFactory(false);
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setAttemptLoad(enhancer.getUseCache() && AotDetector.useGeneratedArtifacts());
enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
enhancer.setCallbackFilter(CALLBACK_FILTER);
enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
return enhancer;
}
/**
* Uses enhancer to generate a subclass of superclass,
* ensuring that callbacks are registered for the new subclass.
*/
private Class<?> createClass(Enhancer enhancer, boolean fallback) {
Class<?> subclass;
try {
subclass = enhancer.createClass();
}
catch (Throwable ex) {
if (!fallback) {
throw (ex instanceof CodeGenerationException cgex ? cgex : new CodeGenerationException(ex));
}
// Possibly a package-visible @Bean method declaration not accessible
// in the given ClassLoader -> retry with original ClassLoader
enhancer.setClassLoader(null);
subclass = enhancer.createClass();
}
// Registering callbacks statically (as opposed to thread-local)
// is critical for usage in an OSGi environment (SPR-5932)...
Enhancer.registerStaticCallbacks(subclass, CALLBACKS);
return subclass;
}
/**
* Marker
|
and
|
java
|
apache__camel
|
components/camel-undertow/src/main/java/org/apache/camel/component/undertow/handlers/RestConsumerPath.java
|
{
"start": 991,
"end": 1780
}
|
class ____ implements RestConsumerContextPathMatcher.ConsumerPath<UndertowConsumer> {
private final UndertowConsumer consumer;
public RestConsumerPath(UndertowConsumer consumer) {
this.consumer = consumer;
}
@Override
public String getRestrictMethod() {
return consumer.getEndpoint().getHttpMethodRestrict();
}
@Override
public String getConsumerPath() {
return consumer.getEndpoint().getHttpURI().getPath();
}
@Override
public UndertowConsumer getConsumer() {
return consumer;
}
@Override
public boolean isMatchOnUriPrefix() {
return consumer.getEndpoint().isMatchOnUriPrefix();
}
@Override
public String toString() {
return getConsumerPath();
}
}
|
RestConsumerPath
|
java
|
apache__flink
|
flink-table/flink-table-api-scala/src/test/java/org/apache/flink/table/api/typeutils/ScalaEitherSerializerUpgradeTest.java
|
{
"start": 3005,
"end": 3493
}
|
class ____
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Either<Integer, String>> {
@Override
public TypeSerializer<Either<Integer, String>> createPriorSerializer() {
return new EitherSerializer<>(IntSerializer.INSTANCE, StringSerializer.INSTANCE);
}
@Override
public Either<Integer, String> createTestData() {
return new Right<>("Hello world");
}
}
/**
* This
|
EitherSerializerSetup
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java
|
{
"start": 1621,
"end": 9789
}
|
class ____ {
private static final Log logger = LogFactory.getLog(JdbcTestUtils.class);
/**
* Count the rows in the given table.
* @param jdbcTemplate the {@link JdbcOperations} with which to perform JDBC
* operations
* @param tableName name of the table to count rows in
* @return the number of rows in the table
*/
public static int countRowsInTable(JdbcOperations jdbcTemplate, String tableName) {
return countRowsInTable(JdbcClient.create(jdbcTemplate), tableName);
}
/**
* Count the rows in the given table.
* @param jdbcClient the {@link JdbcClient} with which to perform JDBC
* operations
* @param tableName name of the table to count rows in
* @return the number of rows in the table
* @since 6.1
*/
public static int countRowsInTable(JdbcClient jdbcClient, String tableName) {
return countRowsInTableWhere(jdbcClient, tableName, null);
}
/**
* Count the rows in the given table, using the provided {@code WHERE} clause.
* <p>If the provided {@code WHERE} clause contains text, it will be prefixed
* with {@code " WHERE "} and then appended to the generated {@code SELECT}
* statement. For example, if the provided table name is {@code "person"} and
* the provided where clause is {@code "name = 'Bob' and age > 25"}, the
* resulting SQL statement to execute will be
* {@code "SELECT COUNT(0) FROM person WHERE name = 'Bob' and age > 25"}.
* @param jdbcTemplate the {@link JdbcOperations} with which to perform JDBC
* operations
* @param tableName the name of the table to count rows in
* @param whereClause the {@code WHERE} clause to append to the query
* @return the number of rows in the table that match the provided
* {@code WHERE} clause
*/
public static int countRowsInTableWhere(
JdbcOperations jdbcTemplate, String tableName, @Nullable String whereClause) {
return countRowsInTableWhere(JdbcClient.create(jdbcTemplate), tableName, whereClause);
}
/**
* Count the rows in the given table, using the provided {@code WHERE} clause.
* <p>If the provided {@code WHERE} clause contains text, it will be prefixed
* with {@code " WHERE "} and then appended to the generated {@code SELECT}
* statement. For example, if the provided table name is {@code "person"} and
* the provided where clause is {@code "name = 'Bob' and age > 25"}, the
* resulting SQL statement to execute will be
* {@code "SELECT COUNT(0) FROM person WHERE name = 'Bob' and age > 25"}.
* @param jdbcClient the {@link JdbcClient} with which to perform JDBC
* operations
* @param tableName the name of the table to count rows in
* @param whereClause the {@code WHERE} clause to append to the query
* @return the number of rows in the table that match the provided
* {@code WHERE} clause
* @since 6.1
*/
public static int countRowsInTableWhere(
JdbcClient jdbcClient, String tableName, @Nullable String whereClause) {
String sql = "SELECT COUNT(0) FROM " + tableName;
if (StringUtils.hasText(whereClause)) {
sql += " WHERE " + whereClause;
}
return jdbcClient.sql(sql).query(Integer.class).single();
}
/**
* Delete all rows from the specified tables.
* @param jdbcTemplate the {@link JdbcOperations} with which to perform JDBC
* operations
* @param tableNames the names of the tables to delete from
* @return the total number of rows deleted from all specified tables
*/
public static int deleteFromTables(JdbcOperations jdbcTemplate, String... tableNames) {
return deleteFromTables(JdbcClient.create(jdbcTemplate), tableNames);
}
/**
* Delete all rows from the specified tables.
* @param jdbcClient the {@link JdbcClient} with which to perform JDBC
* operations
* @param tableNames the names of the tables to delete from
* @return the total number of rows deleted from all specified tables
* @since 6.1
*/
public static int deleteFromTables(JdbcClient jdbcClient, String... tableNames) {
int totalRowCount = 0;
for (String tableName : tableNames) {
int rowCount = jdbcClient.sql("DELETE FROM " + tableName).update();
totalRowCount += rowCount;
if (logger.isInfoEnabled()) {
logger.info("Deleted " + rowCount + " rows from table " + tableName);
}
}
return totalRowCount;
}
/**
* Delete rows from the given table, using the provided {@code WHERE} clause.
* <p>If the provided {@code WHERE} clause contains text, it will be prefixed
* with {@code " WHERE "} and then appended to the generated {@code DELETE}
* statement. For example, if the provided table name is {@code "person"} and
* the provided where clause is {@code "name = 'Bob' and age > 25"}, the
* resulting SQL statement to execute will be
* {@code "DELETE FROM person WHERE name = 'Bob' and age > 25"}.
* <p>As an alternative to hard-coded values, the {@code "?"} placeholder can
* be used within the {@code WHERE} clause, binding to the given arguments.
* @param jdbcTemplate the {@link JdbcOperations} with which to perform JDBC
* operations
* @param tableName the name of the table to delete rows from
* @param whereClause the {@code WHERE} clause to append to the query
* @param args arguments to bind to the query (leaving it to the PreparedStatement
* to guess the corresponding SQL type); may also contain {@link SqlParameterValue}
* objects which indicate not only the argument value but also the SQL type and
* optionally the scale.
* @return the number of rows deleted from the table
*/
public static int deleteFromTableWhere(
JdbcOperations jdbcTemplate, String tableName, String whereClause, Object... args) {
return deleteFromTableWhere(JdbcClient.create(jdbcTemplate), tableName, whereClause, args);
}
/**
* Delete rows from the given table, using the provided {@code WHERE} clause.
* <p>If the provided {@code WHERE} clause contains text, it will be prefixed
* with {@code " WHERE "} and then appended to the generated {@code DELETE}
* statement. For example, if the provided table name is {@code "person"} and
* the provided where clause is {@code "name = 'Bob' and age > 25"}, the
* resulting SQL statement to execute will be
* {@code "DELETE FROM person WHERE name = 'Bob' and age > 25"}.
* <p>As an alternative to hard-coded values, the {@code "?"} placeholder can
* be used within the {@code WHERE} clause, binding to the given arguments.
* @param jdbcClient the {@link JdbcClient} with which to perform JDBC
* operations
* @param tableName the name of the table to delete rows from
* @param whereClause the {@code WHERE} clause to append to the query
* @param args arguments to bind to the query (leaving it to the PreparedStatement
* to guess the corresponding SQL type); may also contain {@link SqlParameterValue}
* objects which indicate not only the argument value but also the SQL type and
* optionally the scale.
* @return the number of rows deleted from the table
* @since 6.1
*/
public static int deleteFromTableWhere(
JdbcClient jdbcClient, String tableName, String whereClause, Object... args) {
String sql = "DELETE FROM " + tableName;
if (StringUtils.hasText(whereClause)) {
sql += " WHERE " + whereClause;
}
int rowCount = jdbcClient.sql(sql).params(args).update();
if (logger.isInfoEnabled()) {
logger.info("Deleted " + rowCount + " rows from table " + tableName);
}
return rowCount;
}
/**
* Drop the specified tables.
* @param jdbcTemplate the {@link JdbcOperations} with which to perform JDBC
* operations
* @param tableNames the names of the tables to drop
*/
public static void dropTables(JdbcOperations jdbcTemplate, String... tableNames) {
dropTables(JdbcClient.create(jdbcTemplate), tableNames);
}
/**
* Drop the specified tables.
* @param jdbcClient the {@link JdbcClient} with which to perform JDBC operations
* @param tableNames the names of the tables to drop
* @since 6.1
*/
public static void dropTables(JdbcClient jdbcClient, String... tableNames) {
for (String tableName : tableNames) {
jdbcClient.sql("DROP TABLE " + tableName).update();
if (logger.isInfoEnabled()) {
logger.info("Dropped table " + tableName);
}
}
}
}
|
JdbcTestUtils
|
java
|
apache__rocketmq
|
controller/src/main/java/org/apache/rocketmq/controller/impl/DLedgerController.java
|
{
"start": 20274,
"end": 23933
}
|
class ____<T> implements EventHandler<T> {
private final String name;
private final Supplier<ControllerResult<T>> supplier;
private final CompletableFuture<RemotingCommand> future;
private final boolean isWriteEvent;
ControllerEventHandler(final String name, final Supplier<ControllerResult<T>> supplier,
final boolean isWriteEvent) {
this.name = name;
this.supplier = supplier;
this.future = new CompletableFuture<>();
this.isWriteEvent = isWriteEvent;
}
@Override
public void run() throws Throwable {
final ControllerResult<T> result = this.supplier.get();
log.info("Event queue run event {}, get the result {}", this.name, result);
boolean appendSuccess = true;
if (!this.isWriteEvent || result.getEvents() == null || result.getEvents().isEmpty()) {
// read event, or write event with empty events in response which also equals to read event
if (DLedgerController.this.controllerConfig.isProcessReadEvent()) {
// Now the DLedger don't have the function of Read-Index or Lease-Read,
// So we still need to propose an empty request to DLedger.
final AppendEntryRequest request = new AppendEntryRequest();
request.setBody(new byte[0]);
appendSuccess = appendToDLedgerAndWait(request);
}
} else {
// write event
final List<EventMessage> events = result.getEvents();
final List<byte[]> eventBytes = new ArrayList<>(events.size());
for (final EventMessage event : events) {
if (event != null) {
final byte[] data = DLedgerController.this.eventSerializer.serialize(event);
if (data != null && data.length > 0) {
eventBytes.add(data);
}
}
}
// Append events to DLedger
if (!eventBytes.isEmpty()) {
// batch append events
final BatchAppendEntryRequest request = new BatchAppendEntryRequest();
request.setBatchMsgs(eventBytes);
appendSuccess = appendToDLedgerAndWait(request);
}
}
if (appendSuccess) {
final RemotingCommand response = RemotingCommand.createResponseCommandWithHeader(result.getResponseCode(), (CommandCustomHeader) result.getResponse());
if (result.getBody() != null) {
response.setBody(result.getBody());
}
if (result.getRemark() != null) {
response.setRemark(result.getRemark());
}
this.future.complete(response);
} else {
log.error("Failed to append event to DLedger, the response is {}, try cancel the future", result.getResponse());
this.future.cancel(true);
}
}
@Override
public CompletableFuture<RemotingCommand> future() {
return this.future;
}
@Override
public void handleException(final Throwable t) {
log.error("Error happen when handle event {}", this.name, t);
this.future.completeExceptionally(t);
}
}
/**
* Role change handler, trigger the startScheduling() and stopScheduling() when role change.
*/
|
ControllerEventHandler
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/records/impl/pb/RouterStoreTokenPBImpl.java
|
{
"start": 1832,
"end": 6371
}
|
class ____ extends RouterStoreToken {
private RouterStoreTokenProto proto = RouterStoreTokenProto.getDefaultInstance();
private RouterStoreTokenProto.Builder builder = null;
private boolean viaProto = false;
private YARNDelegationTokenIdentifier rMDelegationTokenIdentifier = null;
private Long renewDate;
private String tokenInfo;
public RouterStoreTokenPBImpl() {
builder = RouterStoreTokenProto.newBuilder();
}
public RouterStoreTokenPBImpl(RouterStoreTokenProto storeTokenProto) {
this.proto = storeTokenProto;
viaProto = true;
}
public RouterStoreTokenProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
private void mergeLocalToProto() {
if (viaProto) {
maybeInitBuilder();
}
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void mergeLocalToBuilder() {
if (this.rMDelegationTokenIdentifier != null) {
YARNDelegationTokenIdentifierProto idProto = this.rMDelegationTokenIdentifier.getProto();
if (!idProto.equals(builder.getTokenIdentifier())) {
builder.setTokenIdentifier(convertToProtoFormat(this.rMDelegationTokenIdentifier));
}
}
if (this.renewDate != null) {
builder.setRenewDate(this.renewDate);
}
if (this.tokenInfo != null) {
builder.setTokenInfo(this.tokenInfo);
}
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = RouterStoreTokenProto.newBuilder(proto);
}
viaProto = false;
}
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;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
@Override
public YARNDelegationTokenIdentifier getTokenIdentifier() throws IOException {
RouterStoreTokenProtoOrBuilder p = viaProto ? proto : builder;
if (rMDelegationTokenIdentifier != null) {
return rMDelegationTokenIdentifier;
}
if(!p.hasTokenIdentifier()){
return null;
}
YARNDelegationTokenIdentifierProto identifierProto = p.getTokenIdentifier();
ByteArrayInputStream in = new ByteArrayInputStream(identifierProto.toByteArray());
RMDelegationTokenIdentifier identifier = new RMDelegationTokenIdentifier();
identifier.readFields(new DataInputStream(in));
this.rMDelegationTokenIdentifier = identifier;
return identifier;
}
@Override
public Long getRenewDate() {
RouterStoreTokenProtoOrBuilder p = viaProto ? proto : builder;
if (this.renewDate != null) {
return this.renewDate;
}
if (!p.hasRenewDate()) {
return null;
}
this.renewDate = p.getRenewDate();
return this.renewDate;
}
@Override
public void setIdentifier(YARNDelegationTokenIdentifier identifier) {
maybeInitBuilder();
if(identifier == null) {
builder.clearTokenIdentifier();
return;
}
this.rMDelegationTokenIdentifier = identifier;
this.builder.setTokenIdentifier(identifier.getProto());
}
@Override
public void setRenewDate(Long renewDate) {
maybeInitBuilder();
if(renewDate == null) {
builder.clearRenewDate();
return;
}
this.renewDate = renewDate;
this.builder.setRenewDate(renewDate);
}
@Override
public String getTokenInfo() {
RouterStoreTokenProtoOrBuilder p = viaProto ? proto : builder;
if (this.tokenInfo != null) {
return this.tokenInfo;
}
if (!p.hasTokenInfo()) {
return null;
}
this.tokenInfo = p.getTokenInfo();
return this.tokenInfo;
}
@Override
public void setTokenInfo(String tokenInfo) {
maybeInitBuilder();
if (tokenInfo == null) {
builder.clearTokenInfo();
return;
}
this.tokenInfo = tokenInfo;
this.builder.setTokenInfo(tokenInfo);
}
private YARNDelegationTokenIdentifierProto convertToProtoFormat(
YARNDelegationTokenIdentifier delegationTokenIdentifier) {
return delegationTokenIdentifier.getProto();
}
public byte[] toByteArray() throws IOException {
return builder.build().toByteArray();
}
public void readFields(DataInput in) throws IOException {
builder.mergeFrom((DataInputStream) in);
}
}
|
RouterStoreTokenPBImpl
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/support/incrementer/OracleSequenceMaxValueIncrementer.java
|
{
"start": 912,
"end": 1571
}
|
class ____ extends AbstractSequenceMaxValueIncrementer {
/**
* Default constructor for bean property style usage.
* @see #setDataSource
* @see #setIncrementerName
*/
public OracleSequenceMaxValueIncrementer() {
}
/**
* Convenience constructor.
* @param dataSource the DataSource to use
* @param incrementerName the name of the sequence/table to use
*/
public OracleSequenceMaxValueIncrementer(DataSource dataSource, String incrementerName) {
super(dataSource, incrementerName);
}
@Override
protected String getSequenceQuery() {
return "select " + getIncrementerName() + ".nextval from dual";
}
}
|
OracleSequenceMaxValueIncrementer
|
java
|
apache__camel
|
components/camel-debezium/camel-debezium-postgres/src/test/java/org/apache/camel/component/debezium/postgres/configuration/PostgresConnectorEmbeddedDebeziumConfigurationTest.java
|
{
"start": 1509,
"end": 4621
}
|
class ____ {
@Test
void testIfCreatesConfig() {
final PostgresConnectorEmbeddedDebeziumConfiguration configuration
= new PostgresConnectorEmbeddedDebeziumConfiguration();
configuration.setName("test_config");
configuration.setDatabaseUser("test_user");
configuration.setMaxQueueSize(1212);
final Configuration dbzConfigurations = configuration.createDebeziumConfiguration();
assertEquals("test_config", dbzConfigurations.getString(AsyncEmbeddedEngine.ENGINE_NAME));
assertEquals("test_user", dbzConfigurations.getString(PostgresConnectorConfig.USER));
assertEquals(1212, dbzConfigurations.getInteger(CommonConnectorConfig.MAX_QUEUE_SIZE));
assertEquals(PostgresConnector.class.getName(), dbzConfigurations.getString(AsyncEmbeddedEngine.CONNECTOR_CLASS));
assertEquals(DebeziumConstants.DEFAULT_OFFSET_STORAGE,
dbzConfigurations.getString(AsyncEmbeddedEngine.OFFSET_STORAGE));
}
@Test
void testIfValidatesConfigurationCorrectly() {
final PostgresConnectorEmbeddedDebeziumConfiguration configuration
= new PostgresConnectorEmbeddedDebeziumConfiguration();
configuration.setName("test_config");
configuration.setDatabaseUser("test_db");
configuration.setTopicPrefix("test_server");
configuration.setOffsetStorageFileName("/offset/file");
configuration.setSchemaHistoryInternalFileFilename("/database_history/file");
assertFalse(configuration.validateConfiguration().isValid());
configuration.setDatabaseHostname("localhost");
configuration.setDatabasePassword("test_pwd");
assertTrue(configuration.validateConfiguration().isValid());
}
@Test
void testValidateConfigurationsForAllRequiredFields() {
final PostgresConnectorEmbeddedDebeziumConfiguration configuration
= new PostgresConnectorEmbeddedDebeziumConfiguration();
configuration.setName("test_config");
configuration.setDatabaseUser("test_db");
configuration.setDatabaseHostname("localhost");
configuration.setDatabasePassword("test_pwd");
configuration.setTopicPrefix("test_server");
configuration.setOffsetStorageFileName("/offset/file");
configuration.setSchemaHistoryInternalFileFilename("/database_history/file");
final ConfigurationValidation validation = configuration.validateConfiguration();
assertTrue(validation.isValid());
assertEquals("test_config", configuration.getName());
assertEquals("test_db", configuration.getDatabaseUser());
assertEquals("localhost", configuration.getDatabaseHostname());
assertEquals("test_pwd", configuration.getDatabasePassword());
assertEquals("test_server", configuration.getTopicPrefix());
assertEquals("/offset/file", configuration.getOffsetStorageFileName());
assertEquals("/database_history/file", configuration.getSchemaHistoryInternalFileFilename());
}
}
|
PostgresConnectorEmbeddedDebeziumConfigurationTest
|
java
|
apache__camel
|
core/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBean.java
|
{
"start": 8384,
"end": 19034
}
|
class ____ for when we actually do start things up
contextClassLoaderOnStart = Thread.currentThread().getContextClassLoader();
}
public T getObject() throws Exception {
return getContext();
}
public abstract Class<T> getObjectType();
public boolean isSingleton() {
return true;
}
public ClassLoader getContextClassLoaderOnStart() {
return contextClassLoaderOnStart;
}
public void afterPropertiesSet() throws Exception {
if (org.apache.camel.util.ObjectHelper.isEmpty(getId())) {
throw new IllegalArgumentException("Id must be set");
}
// set properties as early as possible
setupPropertiesComponent();
// set the package scan resolver as soon as possible
setupPackageScanResolver();
// also set type converter registry as early as possible
setupTypeConverters();
// setup whether to load health checks as early as possible
setupHealthCheckEagerLoadPolicy();
// then set custom properties
setCustomProperties();
// set the custom registry if defined
initCustomRegistry(getContext());
// setup property placeholder so we got it as early as possible
initPropertyPlaceholder();
// then setup JMX
initJMXAgent();
// setup all misc services
setupCustomServices();
setupCommonServices();
// custom type converters defined as <bean>s
setupCustomTypeConverters();
// set the event notifier strategies if defined
setupEventNotifierStrategies();
// set endpoint strategies if defined
setupEndpointStrategies();
// shutdown
setupShutdownStrategy();
// add global interceptors
addGlobalInterceptors();
// set the lifecycle strategy if defined
setupLifecycleStrategy();
// set the node lifecycle strategy if defined
setupNodeLifecycleStrategy();
// cluster service
setupClusterService();
// service registry
setupServiceRegistry();
// add route policy factories
addRoutePolicyFactories();
// Health check registry
setupHealthCheckRegistry();
// Dev console registry
setupDevConsoleRegistry();
// UuidGenerator
setupUuidGenerator();
// LogListener
setupLogListener();
// set the default thread pool profile if defined
initThreadPoolProfiles(getContext());
// Set the application context and camelContext for the beanPostProcessor
initBeanPostProcessor(getContext());
// init camel context
initCamelContext(getContext());
// init stream caching strategy
initStreamCachingStrategy();
// init route controller
initRouteController();
}
private void setupPropertiesComponent() {
PropertiesComponent pc = getBeanForType(PropertiesComponent.class);
if (pc != null) {
LOG.debug("Using PropertiesComponent: {}", pc);
getContext().setPropertiesComponent(pc);
}
}
private void setupPackageScanResolver() {
PackageScanClassResolver packageResolver = getBeanForType(PackageScanClassResolver.class);
if (packageResolver != null) {
LOG.info("Using custom PackageScanClassResolver: {}", packageResolver);
getContext().getCamelContextExtension().addContextPlugin(PackageScanClassResolver.class, packageResolver);
}
}
private void setupHealthCheckEagerLoadPolicy() {
if (getLoadHealthChecks() != null) {
String s = getContext().resolvePropertyPlaceholders(getLoadHealthChecks());
getContext().setLoadHealthChecks(Boolean.parseBoolean(s));
}
}
private void setupLogListener() {
Map<String, LogListener> logListeners = getContext().getRegistry().findByTypeWithName(LogListener.class);
if (logListeners != null && !logListeners.isEmpty()) {
for (Entry<String, LogListener> entry : logListeners.entrySet()) {
LogListener logListener = entry.getValue();
if (getContext().getCamelContextExtension().getLogListeners() == null
|| !getContext().getCamelContextExtension().getLogListeners().contains(logListener)) {
LOG.info("Using custom LogListener with id: {} and implementation: {}", entry.getKey(), logListener);
getContext().getCamelContextExtension().addLogListener(logListener);
}
}
}
}
private void setupUuidGenerator() {
UuidGenerator uuidGenerator = getBeanForType(UuidGenerator.class);
if (uuidGenerator != null) {
LOG.info("Using custom UuidGenerator: {}", uuidGenerator);
getContext().setUuidGenerator(uuidGenerator);
}
}
private void setupDevConsoleRegistry() {
DevConsoleRegistry devConsoleRegistry = getBeanForType(DevConsoleRegistry.class);
if (devConsoleRegistry != null) {
devConsoleRegistry.setCamelContext(getContext());
LOG.debug("Using DevConsoleRegistry: {}", devConsoleRegistry);
getContext().getCamelContextExtension().addContextPlugin(DevConsoleRegistry.class, devConsoleRegistry);
} else {
// okay attempt to inject this camel context into existing dev console (if any)
devConsoleRegistry = DevConsoleRegistry.get(getContext());
if (devConsoleRegistry != null) {
devConsoleRegistry.setCamelContext(getContext());
}
}
if (devConsoleRegistry != null) {
Set<DevConsole> consoles = getContext().getRegistry().findByType(DevConsole.class);
for (DevConsole console : consoles) {
devConsoleRegistry.register(console);
}
}
}
private void setupHealthCheckRegistry() {
HealthCheckRegistry healthCheckRegistry = getBeanForType(HealthCheckRegistry.class);
if (healthCheckRegistry != null) {
healthCheckRegistry.setCamelContext(getContext());
LOG.debug("Using HealthCheckRegistry: {}", healthCheckRegistry);
getContext().getCamelContextExtension().addContextPlugin(HealthCheckRegistry.class, healthCheckRegistry);
} else {
// okay attempt to inject this camel context into existing health check (if any)
healthCheckRegistry = HealthCheckRegistry.get(getContext());
if (healthCheckRegistry != null) {
healthCheckRegistry.setCamelContext(getContext());
}
}
if (healthCheckRegistry != null) {
// Health check repository
Set<HealthCheckRepository> repositories = getContext().getRegistry().findByType(HealthCheckRepository.class);
if (org.apache.camel.util.ObjectHelper.isNotEmpty(repositories)) {
for (HealthCheckRepository repository : repositories) {
healthCheckRegistry.register(repository);
}
}
}
}
private void addRoutePolicyFactories() {
Map<String, RoutePolicyFactory> routePolicyFactories
= getContext().getRegistry().findByTypeWithName(RoutePolicyFactory.class);
if (routePolicyFactories != null && !routePolicyFactories.isEmpty()) {
for (Entry<String, RoutePolicyFactory> entry : routePolicyFactories.entrySet()) {
RoutePolicyFactory factory = entry.getValue();
LOG.info("Using custom RoutePolicyFactory with id: {} and implementation: {}", entry.getKey(), factory);
getContext().addRoutePolicyFactory(factory);
}
}
}
private void setupServiceRegistry() throws Exception {
Map<String, ServiceRegistry> serviceRegistries = getContext().getRegistry().findByTypeWithName(ServiceRegistry.class);
if (serviceRegistries != null && !serviceRegistries.isEmpty()) {
for (Entry<String, ServiceRegistry> entry : serviceRegistries.entrySet()) {
ServiceRegistry service = entry.getValue();
if (service.getId() == null) {
service.setGeneratedId(getContext().getUuidGenerator().generateUuid());
}
LOG.info("Using ServiceRegistry with id: {} and implementation: {}", service.getId(), service);
getContext().addService(service);
}
}
}
private void setupClusterService() throws Exception {
Map<String, CamelClusterService> clusterServices
= getContext().getRegistry().findByTypeWithName(CamelClusterService.class);
if (clusterServices != null && !clusterServices.isEmpty()) {
for (Entry<String, CamelClusterService> entry : clusterServices.entrySet()) {
CamelClusterService service = entry.getValue();
LOG.info("Using CamelClusterService with id: {} and implementation: {}", service.getId(), service);
getContext().addService(service);
}
}
}
private void setupNodeLifecycleStrategy() {
Map<String, ModelLifecycleStrategy> modelLifecycleStrategies
= getContext().getRegistry().findByTypeWithName(ModelLifecycleStrategy.class);
if (modelLifecycleStrategies != null && !modelLifecycleStrategies.isEmpty()) {
for (Entry<String, ModelLifecycleStrategy> entry : modelLifecycleStrategies.entrySet()) {
ModelLifecycleStrategy strategy = entry.getValue();
ModelCamelContext mcc = getContext();
if (!mcc.getModelLifecycleStrategies().contains(strategy)) {
LOG.info("Using custom ModelLifecycleStrategy with id: {} and implementation: {}", entry.getKey(),
strategy);
mcc.addModelLifecycleStrategy(strategy);
}
}
}
}
private void setupLifecycleStrategy() {
Map<String, LifecycleStrategy> lifecycleStrategies
= getContext().getRegistry().findByTypeWithName(LifecycleStrategy.class);
if (lifecycleStrategies != null && !lifecycleStrategies.isEmpty()) {
for (Entry<String, LifecycleStrategy> entry : lifecycleStrategies.entrySet()) {
LifecycleStrategy strategy = entry.getValue();
// do not add if already added, for instance a tracer that is also an InterceptStrategy
|
loader
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java
|
{
"start": 2755,
"end": 23439
}
|
class ____ {
private final List<HttpMessageConverter<?>> messageConverters = List.of(new StringHttpMessageConverter());
@Test
void method() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("HEAD", "/", true);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.method()).isEqualTo(HttpMethod.HEAD);
}
@Test
void uri() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setServerName("example.com");
servletRequest.setScheme("https");
servletRequest.setServerPort(443);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.uri()).isEqualTo(URI.create("https://example.com/"));
}
@Test
void uriBuilder() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/path", true);
servletRequest.setQueryString("a=1");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
URI result = request.uriBuilder().build();
assertThat(result.getScheme()).isEqualTo("http");
assertThat(result.getHost()).isEqualTo("localhost");
assertThat(result.getPort()).isEqualTo(-1);
assertThat(result.getPath()).isEqualTo("/path");
assertThat(result.getQuery()).isEqualTo("a=1");
}
@Test
void attribute() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setAttribute("foo", "bar");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.attribute("foo")).contains("bar");
}
@Test
void attributes() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setAttribute("foo", "bar");
servletRequest.setAttribute("baz", "qux");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Map<String, Object> attributesMap = request.attributes();
assertThat(attributesMap).isNotEmpty();
assertThat(attributesMap).containsEntry("foo", "bar");
assertThat(attributesMap).containsEntry("baz", "qux");
assertThat(attributesMap).doesNotContainEntry("foo", "blah");
Set<Map.Entry<String, Object>> entrySet = attributesMap.entrySet();
assertThat(entrySet).isNotEmpty();
assertThat(entrySet).hasSize(attributesMap.size());
assertThat(entrySet).contains(Map.entry("foo", "bar"));
assertThat(entrySet).contains(Map.entry("baz", "qux"));
assertThat(entrySet).doesNotContain(Map.entry("foo", "blah"));
assertThat(entrySet).isUnmodifiable();
assertThat(entrySet.iterator()).toIterable().contains(Map.entry("foo", "bar"), Map.entry("baz", "qux"));
Iterator<String> attributes = servletRequest.getAttributeNames().asIterator();
Iterator<Map.Entry<String, Object>> entrySetIterator = entrySet.iterator();
while (attributes.hasNext()) {
attributes.next();
assertThat(entrySetIterator).hasNext();
entrySetIterator.next();
}
assertThat(entrySetIterator).isExhausted();
attributesMap.clear();
assertThat(attributesMap).isEmpty();
assertThat(attributesMap).hasSize(0);
assertThat(entrySet).isEmpty();
assertThat(entrySet).hasSize(0);
assertThat(entrySet.iterator()).isExhausted();
}
@Test
void params() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setParameter("foo", "bar");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.param("foo")).contains("bar");
}
@Test
void multipartData() throws Exception {
MockPart formPart = new MockPart("form", "foo".getBytes(UTF_8));
MockPart filePart = new MockPart("file", "foo.txt", "foo".getBytes(UTF_8));
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("POST", "/", true);
servletRequest.addPart(formPart);
servletRequest.addPart(filePart);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
MultiValueMap<String, Part> result = request.multipartData();
assertThat(result).hasSize(2);
assertThat(result.get("form")).containsExactly(formPart);
assertThat(result.get("file")).containsExactly(filePart);
}
@Test
void emptyQueryParam() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setParameter("foo", "");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.param("foo")).contains("");
}
@Test
void absentQueryParam() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setParameter("foo", "");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.param("bar")).isNotPresent();
}
@Test
void pathVariable() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
servletRequest.setAttribute(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.pathVariable("foo")).isEqualTo("bar");
}
@Test
void pathVariableNotFound() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
servletRequest.setAttribute(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThatIllegalArgumentException().isThrownBy(() -> request.pathVariable("baz"));
}
@Test
void pathVariables() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
servletRequest.setAttribute(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.pathVariables()).isEqualTo(pathVariables);
}
@Test
void header() {
HttpHeaders httpHeaders = new HttpHeaders();
List<MediaType> accept = Collections.singletonList(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(accept);
List<Charset> acceptCharset = Collections.singletonList(UTF_8);
httpHeaders.setAcceptCharset(acceptCharset);
long contentLength = 42L;
httpHeaders.setContentLength(contentLength);
MediaType contentType = MediaType.TEXT_PLAIN;
httpHeaders.setContentType(contentType);
InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
httpHeaders.setHost(host);
List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
httpHeaders.setRange(range);
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
httpHeaders.forEach(servletRequest::addHeader);
servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
ServerRequest.Headers headers = request.headers();
assertThat(headers.accept()).isEqualTo(accept);
assertThat(headers.acceptCharset()).isEqualTo(acceptCharset);
assertThat(headers.contentLength()).isEqualTo(OptionalLong.of(contentLength));
assertThat(headers.contentType()).contains(contentType);
assertThat(headers.header(HttpHeaders.CONTENT_TYPE)).containsExactly(MediaType.TEXT_PLAIN_VALUE);
assertThat(headers.firstHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders);
}
@Test
void cookies() {
Cookie cookie = new Cookie("foo", "bar");
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setCookies(cookie);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
MultiValueMap<String, Cookie> expected = new LinkedMultiValueMap<>();
expected.add("foo", cookie);
assertThat(request.cookies()).isEqualTo(expected);
}
@Test
void bodyClass() throws Exception {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
servletRequest.setContent("foo".getBytes(UTF_8));
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
String result = request.body(String.class);
assertThat(result).isEqualTo("foo");
}
@Test
void bodyParameterizedTypeReference() throws Exception {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);
servletRequest.setContent("[\"foo\",\"bar\"]".getBytes(UTF_8));
DefaultServerRequest request = new DefaultServerRequest(servletRequest,
List.of(new JacksonJsonHttpMessageConverter()));
List<String> result = request.body(new ParameterizedTypeReference<>() {});
assertThat(result).containsExactly("foo", "bar");
}
@Test
void bodyUnacceptable() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
servletRequest.setContent("foo".getBytes(UTF_8));
DefaultServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList());
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class)
.isThrownBy(() -> request.body(String.class));
}
@Test
void session() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
MockHttpSession session = new MockHttpSession();
servletRequest.setSession(session);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.session()).isEqualTo(session);
}
@Test
void principal() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
Principal principal = () -> "foo";
servletRequest.setUserPrincipal(principal);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThat(request.principal()).contains(principal);
}
@Test
void bindToConstructor() throws BindException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addParameter("foo", "FOO");
servletRequest.addHeader("bar", "BAR");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
ConstructorInjection result = request.bind(ConstructorInjection.class);
assertThat(result.getFoo()).isEqualTo("FOO");
assertThat(result.getBar()).isEqualTo("BAR");
}
@Test
void bindToProperties() throws BindException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addParameter("foo", "FOO");
servletRequest.addHeader("bar", "BAR");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
PropertyInjection result = request.bind(PropertyInjection.class);
assertThat(result.getFoo()).isEqualTo("FOO");
assertThat(result.getBar()).isEqualTo("BAR");
}
@Test
void bindToMixed() throws BindException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addParameter("foo", "FOO");
servletRequest.addHeader("bar", "BAR");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
MixedInjection result = request.bind(MixedInjection.class);
assertThat(result.getFoo()).isEqualTo("FOO");
assertThat(result.getBar()).isEqualTo("BAR");
}
@Test
void bindCustomizer() throws BindException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addParameter("foo", "FOO");
servletRequest.addParameter("bar", "BAR");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
PropertyInjection result = request.bind(PropertyInjection.class, dataBinder -> dataBinder.setAllowedFields("foo"));
assertThat(result.getFoo()).isEqualTo("FOO");
assertThat(result.getBar()).isNull();
}
@Test
void bindError() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addParameter("foo", "FOO");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
assertThatExceptionOfType(BindException.class).isThrownBy(() ->
request.bind(ErrorInjection.class)
);
}
@ParameterizedHttpMethodTest
void checkNotModifiedTimestamp(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, now.toEpochMilli());
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(now, "");
assertThat(result).hasValueSatisfying(serverResponse -> {
assertThat(serverResponse.statusCode()).isEqualTo(HttpStatus.NOT_MODIFIED);
assertThat(serverResponse.headers().getLastModified()).isEqualTo(now.toEpochMilli());
});
}
@ParameterizedHttpMethodTest
void checkModifiedTimestamp(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Instant oneMinuteAgo = now.minus(1, ChronoUnit.MINUTES);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, oneMinuteAgo.toEpochMilli());
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(now, "");
assertThat(result).isEmpty();
}
@ParameterizedHttpMethodTest
void checkNotModifiedETag(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String eTag = "\"Foo\"";
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(eTag);
assertThat(result).hasValueSatisfying(serverResponse -> {
assertThat(serverResponse.statusCode()).isEqualTo(HttpStatus.NOT_MODIFIED);
assertThat(serverResponse.headers().getETag()).isEqualTo(eTag);
});
}
@ParameterizedHttpMethodTest
void checkNotModifiedETagWithSeparatorChars(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String eTag = "\"Foo, Bar\"";
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(eTag);
assertThat(result).hasValueSatisfying(serverResponse -> {
assertThat(serverResponse.statusCode()).isEqualTo(HttpStatus.NOT_MODIFIED);
assertThat(serverResponse.headers().getETag()).isEqualTo(eTag);
});
}
@ParameterizedHttpMethodTest
void checkModifiedETag(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String currentETag = "\"Foo\"";
String oldEtag = "Bar";
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, oldEtag);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(currentETag);
assertThat(result).isEmpty();
}
@ParameterizedHttpMethodTest
void checkNotModifiedUnpaddedETag(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String eTag = "Foo";
String paddedEtag = String.format("\"%s\"", eTag);
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, paddedEtag);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(eTag);
assertThat(result).hasValueSatisfying(serverResponse -> {
assertThat(serverResponse.statusCode()).isEqualTo(HttpStatus.NOT_MODIFIED);
assertThat(serverResponse.headers().getETag()).isEqualTo(paddedEtag);
});
}
@ParameterizedHttpMethodTest
void checkModifiedUnpaddedETag(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String currentETag = "Foo";
String oldEtag = "Bar";
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, oldEtag);
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(currentETag);
assertThat(result).isEmpty();
}
@ParameterizedHttpMethodTest
void checkNotModifiedWildcardIsIgnored(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String eTag = "\"Foo\"";
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, "*");
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(eTag);
assertThat(result).isEmpty();
}
@ParameterizedHttpMethodTest
void checkNotModifiedETagAndTimestamp(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String eTag = "\"Foo\"";
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, now.toEpochMilli());
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(now, eTag);
assertThat(result).hasValueSatisfying(serverResponse -> {
assertThat(serverResponse.statusCode()).isEqualTo(HttpStatus.NOT_MODIFIED);
assertThat(serverResponse.headers().getETag()).isEqualTo(eTag);
assertThat(serverResponse.headers().getLastModified()).isEqualTo(now.toEpochMilli());
});
}
@ParameterizedHttpMethodTest
void checkNotModifiedETagAndModifiedTimestamp(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String eTag = "\"Foo\"";
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Instant oneMinuteAgo = now.minus(1, ChronoUnit.MINUTES);
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, oneMinuteAgo.toEpochMilli());
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(now, eTag);
assertThat(result).hasValueSatisfying(serverResponse -> {
assertThat(serverResponse.statusCode()).isEqualTo(HttpStatus.NOT_MODIFIED);
assertThat(serverResponse.headers().getETag()).isEqualTo(eTag);
assertThat(serverResponse.headers().getLastModified()).isEqualTo(now.toEpochMilli());
});
}
@ParameterizedHttpMethodTest
void checkModifiedETagAndNotModifiedTimestamp(String method) {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest(method, "/", true);
String currentETag = "\"Foo\"";
String oldEtag = "\"Bar\"";
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, oldEtag);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, now.toEpochMilli());
DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters);
Optional<ServerResponse> result = request.checkNotModified(now, currentETag);
assertThat(result).isEmpty();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ParameterizedTest(name = "[{index}] {0}")
@ValueSource(strings = { "GET", "HEAD" })
@
|
DefaultServerRequestTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/idprops/LineItemPK.java
|
{
"start": 225,
"end": 1198
}
|
class ____ implements Serializable {
private Order order;
private String productCode;
public LineItemPK() {
}
public LineItemPK(Order order, String productCode) {
this.order = order;
this.productCode = productCode;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
LineItemPK that = ( LineItemPK ) o;
if ( !order.equals( that.order ) ) {
return false;
}
if ( !productCode.equals( that.productCode ) ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = order.hashCode();
result = 31 * result + productCode.hashCode();
return result;
}
}
|
LineItemPK
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java
|
{
"start": 21776,
"end": 25868
}
|
class ____, so that the use of
// "foo.class = Bar" works in HQL
: subclass.getSubclassId();
initDiscriminatorProperties( dialect, k, subclassTable, discriminatorValue, isAbstract( subclass ) );
subclassesByDiscriminatorValue.put( discriminatorValue, subclass.getEntityName() );
final int tableId = getTableId(
subclassTable.getQualifiedName( sqlStringGenerationContext ),
subclassTableNameClosure
);
notNullColumnTableNumbers[k] = tableId;
notNullColumnNames[k] = subclassTableKeyColumnClosure[tableId][0];
}
}
}
subclassNamesBySubclassTable = buildSubclassNamesBySubclassTableMapping(
persistentClass,
sqlStringGenerationContext
);
initSubclassPropertyAliasesMap( persistentClass );
postConstruct( creationContext.getMetadata() );
}
private void initDiscriminatorProperties(Dialect dialect, int k, Table table, Object discriminatorValue, boolean isAbstract) {
final String tableName = determineTableName( table );
final String columnName = table.getPrimaryKey().getColumn( 0 ).getQuotedName( dialect );
discriminatorValuesByTableName.put( tableName, discriminatorValue );
discriminatorColumnNameByTableName.put( tableName, columnName );
discriminatorValues[k] = discriminatorValue.toString();
discriminatorAbstract[k] = isAbstract;
}
@Override
public Map<Object, String> getSubclassByDiscriminatorValue() {
return subclassesByDiscriminatorValue;
}
/**
* Used to hold the name of subclasses that each "subclass table" is part of. For example, given a hierarchy like:
* {@code JoinedEntity <- JoinedEntitySubclass <- JoinedEntitySubSubclass}..
* <p>
* For the persister for JoinedEntity, we'd have:
* <pre>
* subclassClosure[0] = "JoinedEntitySubSubclass"
* subclassClosure[1] = "JoinedEntitySubclass"
* subclassClosure[2] = "JoinedEntity"
*
* subclassTableNameClosure[0] = "T_JoinedEntity"
* subclassTableNameClosure[1] = "T_JoinedEntitySubclass"
* subclassTableNameClosure[2] = "T_JoinedEntitySubSubclass"
*
* subclassNameClosureBySubclassTable[0] = ["JoinedEntitySubSubclass", "JoinedEntitySubclass"]
* subclassNameClosureBySubclassTable[1] = ["JoinedEntitySubSubclass"]
* </pre>
* <p>
* Note that there are only 2 entries in subclassNameClosureBySubclassTable. That is because there are really only
* 2 tables here that make up the subclass mapping, the others make up the class/superclass table mappings. We
* do not need to account for those here. The "offset" is defined by the value of {@link #getTableSpan()}.
* Therefore the corresponding row in subclassNameClosureBySubclassTable for a given row in subclassTableNameClosure
* is calculated as {@code subclassTableNameClosureIndex - getTableSpan()}.
* <p>
* As we consider each subclass table we can look into this array based on the subclass table's index and see
* which subclasses would require it to be included. E.g., given {@code TREAT( x AS JoinedEntitySubSubclass )},
* when trying to decide whether to include join to "T_JoinedEntitySubclass" (subclassTableNameClosureIndex = 1),
* we'd look at {@code subclassNameClosureBySubclassTable[0]} and see if the TREAT-AS subclass name is included in
* its values. Since {@code subclassNameClosureBySubclassTable[1]} includes "JoinedEntitySubSubclass", we'd
* consider it included.
* <p>
* {@link #subclassTableNameClosure} also accounts for secondary tables and we properly handle those as we
* build the subclassNamesBySubclassTable array and they are therefore properly handled when we use it
*/
private final String[][] subclassNamesBySubclassTable;
/**
* Essentially we are building a mapping that we can later use to determine whether a given "subclass table"
* should be included in joins when JPA TREAT-AS is used.
*
* @return subclassNamesBySubclassTable
*/
private String[][] buildSubclassNamesBySubclassTableMapping(
PersistentClass persistentClass,
SqlStringGenerationContext context) {
// this value represents the number of subclasses (and not the
|
hierarchy
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintValidationTest.java
|
{
"start": 1911,
"end": 2125
}
|
class ____ implements Serializable {
@Id
protected Long id;
}
@Entity
@Table(name = "tbl_emptycolumnnamelistentity", uniqueConstraints = @UniqueConstraint(columnNames = {}))
public static
|
EmptyColumnNameEntity
|
java
|
elastic__elasticsearch
|
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/text/TextTemplateEngine.java
|
{
"start": 639,
"end": 3807
}
|
class ____ {
private final ScriptService service;
public TextTemplateEngine(ScriptService service) {
this.service = service;
}
public String render(TextTemplate textTemplate, Map<String, Object> model) {
if (textTemplate == null) {
return null;
}
String template = textTemplate.getTemplate();
String mediaType = compileParams(detectContentType(template));
template = trimContentType(textTemplate);
if (textTemplate.mayRequireCompilation() == false) {
return template;
}
Map<String, Object> mergedModel = new HashMap<>();
if (textTemplate.getParams() != null) {
mergedModel.putAll(textTemplate.getParams());
}
mergedModel.putAll(model);
Map<String, String> options = null;
if (textTemplate.getType() == ScriptType.INLINE) {
options = new HashMap<>();
if (textTemplate.getScript() != null && textTemplate.getScript().getOptions() != null) {
options.putAll(textTemplate.getScript().getOptions());
}
options.put(Script.CONTENT_TYPE_OPTION, mediaType);
}
Script script = new Script(
textTemplate.getType(),
textTemplate.getType() == ScriptType.STORED ? null : "mustache",
template,
options,
mergedModel
);
TemplateScript.Factory compiledTemplate = service.compile(script, Watcher.SCRIPT_TEMPLATE_CONTEXT);
return compiledTemplate.newInstance(mergedModel).execute();
}
private static String trimContentType(TextTemplate textTemplate) {
String template = textTemplate.getTemplate();
if (template.startsWith("__") == false) {
return template; // Doesn't even start with __ so can't have a content type
}
// There must be a __<content_type__:: prefix so the minimum length before detecting '__::' is 3
int index = template.indexOf("__::", 3);
// Assume that the content type name is less than 10 characters long otherwise we may falsely detect strings that start with '__
// and have '__::' somewhere in the content
if (index >= 0 && index < 12) {
if (template.length() == 6) {
template = "";
} else {
template = template.substring(index + 4);
}
}
return template;
}
private static XContentType detectContentType(String content) {
if (content.startsWith("__")) {
// There must be a __<content_type__:: prefix so the minimum length before detecting '__::' is 3
int endOfContentName = content.indexOf("__::", 3);
if (endOfContentName != -1) {
return XContentType.fromFormat(content.substring(2, endOfContentName));
}
}
return null;
}
private static String compileParams(XContentType contentType) {
if (contentType == XContentType.JSON) {
return "application/json";
} else {
return "text/plain";
}
}
}
|
TextTemplateEngine
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteQueueEndpointBuilderFactory.java
|
{
"start": 13890,
"end": 15985
}
|
class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final IgniteQueueHeaderNameBuilder INSTANCE = new IgniteQueueHeaderNameBuilder();
/**
* Allows you to dynamically change the queue operation.
*
* The option is a: {@code
* org.apache.camel.component.ignite.queue.IgniteQueueOperation} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteQueueOperation}.
*/
public String igniteQueueOperation() {
return "CamelIgniteQueueOperation";
}
/**
* When invoking the DRAIN operation, the amount of items to drain.
*
* The option is a: {@code Integer} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteQueueMaxElements}.
*/
public String igniteQueueMaxElements() {
return "CamelIgniteQueueMaxElements";
}
/**
* The amount of items transferred as the result of the DRAIN operation.
*
* The option is a: {@code Integer} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteQueueTransferredCount}.
*/
public String igniteQueueTransferredCount() {
return "CamelIgniteQueueTransferredCount";
}
/**
* Dynamically sets the timeout in milliseconds to use when invoking the
* OFFER or POLL operations.
*
* The option is a: {@code Long} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteQueueTimeoutMillis}.
*/
public String igniteQueueTimeoutMillis() {
return "CamelIgniteQueueTimeoutMillis";
}
}
static IgniteQueueEndpointBuilder endpointBuilder(String componentName, String path) {
|
IgniteQueueHeaderNameBuilder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/index/LegacySortedDocValues.java
|
{
"start": 1469,
"end": 3745
}
|
class ____ extends LegacyBinaryDocValues {
/** Sole constructor. (For invocation by subclass
* constructors, typically implicit.) */
protected LegacySortedDocValues() {}
/**
* Returns the ordinal for the specified docID.
* @param docID document ID to lookup
* @return ordinal for the document: this is dense, starts at 0, then
* increments by 1 for the next value in sorted order. Note that
* missing values are indicated by -1.
*/
public abstract int getOrd(int docID);
/** Retrieves the value for the specified ordinal. The returned
* {@link BytesRef} may be re-used across calls to {@link #lookupOrd(int)}
* so make sure to {@link BytesRef#deepCopyOf(BytesRef) copy it} if you want
* to keep it around.
* @param ord ordinal to lookup (must be >= 0 and < {@link #getValueCount()})
* @see #getOrd(int)
*/
public abstract BytesRef lookupOrd(int ord);
/**
* Returns the number of unique values.
* @return number of unique values in this SortedDocValues. This is
* also equivalent to one plus the maximum ordinal.
*/
public abstract int getValueCount();
private final BytesRef empty = new BytesRef();
@Override
public BytesRef get(int docID) {
int ord = getOrd(docID);
if (ord == -1) {
return empty;
} else {
return lookupOrd(ord);
}
}
/** If {@code key} exists, returns its ordinal, else
* returns {@code -insertionPoint-1}, like {@code
* Arrays.binarySearch}.
*
* @param key Key to look up
**/
public int lookupTerm(BytesRef key) {
int low = 0;
int high = getValueCount() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
final BytesRef term = lookupOrd(mid);
int cmp = term.compareTo(key);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
}
/**
* Returns a {@link TermsEnum} over the values.
* The
|
LegacySortedDocValues
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/matching/MultipleProducesTest.java
|
{
"start": 4214,
"end": 4931
}
|
class ____ implements MessageBodyWriter<Entity> {
@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return clazz.equals(Entity.class) && mediaType.isCompatible(MediaType.TEXT_PLAIN_TYPE);
}
@Override
public void writeTo(Entity myResponseEntity, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> multivaluedMap, OutputStream outputStream)
throws IOException, WebApplicationException {
outputStream.write("text/plain".getBytes());
}
}
@Provider
public static
|
TextPlainMessageBodyWriter
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteEventsEndpointBuilderFactory.java
|
{
"start": 1601,
"end": 6421
}
|
interface ____
extends
EndpointConsumerBuilder {
default AdvancedIgniteEventsEndpointBuilder advanced() {
return (AdvancedIgniteEventsEndpointBuilder) this;
}
/**
* The cluster group expression.
*
* The option is a:
* <code>org.apache.camel.component.ignite.ClusterGroupExpression</code>
* type.
*
* Group: consumer
*
* @param clusterGroupExpression the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder clusterGroupExpression(org.apache.camel.component.ignite.ClusterGroupExpression clusterGroupExpression) {
doSetProperty("clusterGroupExpression", clusterGroupExpression);
return this;
}
/**
* The cluster group expression.
*
* The option will be converted to a
* <code>org.apache.camel.component.ignite.ClusterGroupExpression</code>
* type.
*
* Group: consumer
*
* @param clusterGroupExpression the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder clusterGroupExpression(String clusterGroupExpression) {
doSetProperty("clusterGroupExpression", clusterGroupExpression);
return this;
}
/**
* The event types to subscribe to as a comma-separated string of event
* constants as defined in EventType. For example:
* EVT_CACHE_ENTRY_CREATED,EVT_CACHE_OBJECT_REMOVED,EVT_IGFS_DIR_CREATED.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: EVTS_ALL
* Group: consumer
*
* @param events the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder events(String events) {
doSetProperty("events", events);
return this;
}
/**
* Sets whether to propagate the incoming body if the return type of the
* underlying Ignite operation is void.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer
*
* @param propagateIncomingBodyIfNoReturnValue the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder propagateIncomingBodyIfNoReturnValue(boolean propagateIncomingBodyIfNoReturnValue) {
doSetProperty("propagateIncomingBodyIfNoReturnValue", propagateIncomingBodyIfNoReturnValue);
return this;
}
/**
* Sets whether to propagate the incoming body if the return type of the
* underlying Ignite operation is void.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: consumer
*
* @param propagateIncomingBodyIfNoReturnValue the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder propagateIncomingBodyIfNoReturnValue(String propagateIncomingBodyIfNoReturnValue) {
doSetProperty("propagateIncomingBodyIfNoReturnValue", propagateIncomingBodyIfNoReturnValue);
return this;
}
/**
* Sets whether to treat Collections as cache objects or as Collections
* of items to insert/update/compute, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param treatCollectionsAsCacheObjects the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder treatCollectionsAsCacheObjects(boolean treatCollectionsAsCacheObjects) {
doSetProperty("treatCollectionsAsCacheObjects", treatCollectionsAsCacheObjects);
return this;
}
/**
* Sets whether to treat Collections as cache objects or as Collections
* of items to insert/update/compute, etc.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param treatCollectionsAsCacheObjects the value to set
* @return the dsl builder
*/
default IgniteEventsEndpointBuilder treatCollectionsAsCacheObjects(String treatCollectionsAsCacheObjects) {
doSetProperty("treatCollectionsAsCacheObjects", treatCollectionsAsCacheObjects);
return this;
}
}
/**
* Advanced builder for endpoint for the Ignite Events component.
*/
public
|
IgniteEventsEndpointBuilder
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/UnmappedSignificantTerms.java
|
{
"start": 1465,
"end": 1925
}
|
class ____ extends InternalSignificantTerms<UnmappedSignificantTerms, UnmappedSignificantTerms.Bucket> {
public static final String NAME = "umsigterms";
/**
* Concrete type that can't be built because Java needs a concrete type so {@link InternalTerms.Bucket} can have a self type but
* {@linkplain UnmappedTerms} doesn't ever need to build it because it never returns any buckets.
*/
protected abstract static
|
UnmappedSignificantTerms
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/transport/ConnectionManager.java
|
{
"start": 797,
"end": 1701
}
|
interface ____ extends Closeable {
void addListener(TransportConnectionListener listener);
void removeListener(TransportConnectionListener listener);
void openConnection(DiscoveryNode node, ConnectionProfile connectionProfile, ActionListener<Transport.Connection> listener);
void connectToNode(
DiscoveryNode node,
@Nullable ConnectionProfile connectionProfile,
ConnectionValidator connectionValidator,
ActionListener<Releasable> listener
) throws ConnectTransportException;
Transport.Connection getConnection(DiscoveryNode node);
boolean nodeConnected(DiscoveryNode node);
void disconnectFromNode(DiscoveryNode node);
Set<DiscoveryNode> getAllConnectedNodes();
int size();
@Override
void close();
void closeNoBlock();
ConnectionProfile getConnectionProfile();
@FunctionalInterface
|
ConnectionManager
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/ClassUtils.java
|
{
"start": 49183,
"end": 49343
}
|
class ____ from.
* @param interfacesBehavior switch indicating whether to include or exclude interfaces.
* @return Iterable an Iterable over the
|
hierarchy
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/ext/jdk8/OptionalIntDeserializer.java
|
{
"start": 445,
"end": 2674
}
|
class ____ extends BaseScalarOptionalDeserializer<OptionalInt>
{
static final OptionalIntDeserializer INSTANCE = new OptionalIntDeserializer();
public OptionalIntDeserializer() {
super(OptionalInt.class, OptionalInt.empty());
}
@Override
public LogicalType logicalType() { return LogicalType.Integer; }
@Override
public OptionalInt deserialize(JsonParser p, DeserializationContext ctxt)
throws JacksonException
{
// minor optimization, first, for common case
if (p.hasToken(JsonToken.VALUE_NUMBER_INT)) {
return OptionalInt.of(p.getIntValue());
}
CoercionAction act;
switch (p.currentTokenId()) {
case JsonTokenId.ID_STRING:
String text = p.getString();
act = _checkFromStringCoercion(ctxt, text);
if (act == CoercionAction.AsNull) {
return (OptionalInt) getNullValue(ctxt);
}
if (act == CoercionAction.AsEmpty) {
return (OptionalInt) getEmptyValue(ctxt);
}
text = text.trim();
if (_checkTextualNull(ctxt, text)) {
return (OptionalInt) getNullValue(ctxt);
}
return OptionalInt.of(_parseIntPrimitive(p, ctxt, text));
case JsonTokenId.ID_NUMBER_FLOAT:
act = _checkFloatToIntCoercion(p, ctxt, _valueClass);
if (act == CoercionAction.AsNull) {
return (OptionalInt) getNullValue(ctxt);
}
if (act == CoercionAction.AsEmpty) {
return (OptionalInt) getEmptyValue(ctxt);
}
return OptionalInt.of(p.getValueAsInt());
case JsonTokenId.ID_NULL:
return _empty;
case JsonTokenId.ID_START_ARRAY:
if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
p.nextToken();
final OptionalInt parsed = deserialize(p, ctxt);
_verifyEndArrayForSingle(p, ctxt);
return parsed;
}
break;
default:
}
return (OptionalInt) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
}
|
OptionalIntDeserializer
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/convert/EmptyStringAsSingleValueTest.java
|
{
"start": 745,
"end": 7768
}
|
class ____ {
private final String s;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public StringWrapper(String s) {
this.s = s;
}
@Override
public String toString() {
return "StringWrapper{" + s + "}";
}
@Override
public boolean equals(Object obj) {
return obj instanceof StringWrapper && ((StringWrapper) obj).s.equals(s);
}
@Override
public int hashCode() {
return s.hashCode();
}
}
private final ObjectMapper NORMAL_MAPPER = jsonMapperBuilder()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.build();
private final ObjectMapper COERCION_MAPPER = jsonMapperBuilder()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
// same as XmlMapper
.withCoercionConfigDefaults(h -> {
h.setAcceptBlankAsEmpty(true)
.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty);
})
.build();
@Test
public void testEmptyToList() throws Exception {
// NO coercion + empty string input + StringCollectionDeserializer
assertEquals(Collections.singletonList(""),
NORMAL_MAPPER.readValue("\"\"", new TypeReference<List<String>>() {}));
}
@Test
public void testEmptyToListWrapper() throws Exception {
// NO coercion + empty string input + normal CollectionDeserializer
assertEquals(Collections.singletonList(new StringWrapper("")),
NORMAL_MAPPER.readValue("\"\"", new TypeReference<List<StringWrapper>>() {}));
}
@Test
public void testCoercedEmptyToList() throws Exception {
// YES coercion + empty string input + StringCollectionDeserializer
assertEquals(Collections.emptyList(), COERCION_MAPPER.readValue("\"\"",
new TypeReference<List<String>>() {}));
}
@Test
public void testCoercedEmptyToListWrapper() throws Exception {
// YES coercion + empty string input + normal CollectionDeserializer
assertEquals(Collections.emptyList(),
COERCION_MAPPER.readValue("\"\"", new TypeReference<List<StringWrapper>>() {}));
}
@Test
public void testCoercedListToList() throws Exception {
// YES coercion + empty LIST input + StringCollectionDeserializer
assertEquals(Collections.emptyList(),
COERCION_MAPPER.readValue("[]", new TypeReference<List<String>>() {}));
}
@Test
public void testCoercedListToListWrapper() throws Exception {
// YES coercion + empty LIST input + normal CollectionDeserializer
assertEquals(Collections.emptyList(),
COERCION_MAPPER.readValue("[]", new TypeReference<List<StringWrapper>>() {}));
}
@Test
public void testBlankToList() throws Exception {
// NO coercion + empty string input + StringCollectionDeserializer
assertEquals(Collections.singletonList(" "),
NORMAL_MAPPER.readValue("\" \"", new TypeReference<List<String>>() {}));
}
@Test
public void testBlankToListWrapper() throws Exception {
// NO coercion + empty string input + normal CollectionDeserializer
assertEquals(Collections.singletonList(new StringWrapper(" ")),
NORMAL_MAPPER.readValue("\" \"", new TypeReference<List<StringWrapper>>() {}));
}
@Test
public void testCoercedBlankToList() throws Exception {
// YES coercion + empty string input + StringCollectionDeserializer
assertEquals(Collections.emptyList(),
COERCION_MAPPER.readValue("\" \"", new TypeReference<List<String>>() {}));
}
@Test
public void testCoercedBlankToListWrapper() throws Exception {
// YES coercion + empty string input + normal CollectionDeserializer
assertEquals(Collections.emptyList(),
COERCION_MAPPER.readValue("\" \"", new TypeReference<List<StringWrapper>>() {}));
}
@Test
public void testEmptyToArray() throws Exception {
// NO coercion + empty string input + StringCollectionDeserializer
assertArrayEquals(new String[]{""},
NORMAL_MAPPER.readValue("\"\"", new TypeReference<String[]>() {}));
}
@Test
public void testEmptyToArrayWrapper() throws Exception {
// NO coercion + empty string input + normal CollectionDeserializer
assertArrayEquals(new StringWrapper[]{new StringWrapper("")},
NORMAL_MAPPER.readValue("\"\"", new TypeReference<StringWrapper[]>() {}));
}
@Test
public void testCoercedEmptyToArray() throws Exception {
// YES coercion + empty string input + StringCollectionDeserializer
assertArrayEquals(new String[0], COERCION_MAPPER.readValue("\"\"",
new TypeReference<String[]>() {}));
}
@Test
public void testCoercedEmptyToArrayWrapper() throws Exception {
// YES coercion + empty string input + normal CollectionDeserializer
assertArrayEquals(new StringWrapper[0],
COERCION_MAPPER.readValue("\"\"", new TypeReference<StringWrapper[]>() {}));
}
@Test
public void testCoercedListToArray() throws Exception {
// YES coercion + empty LIST input + StringCollectionDeserializer
assertArrayEquals(new String[0],
COERCION_MAPPER.readValue("[]", new TypeReference<String[]>() {}));
}
@Test
public void testCoercedListToArrayWrapper() throws Exception {
// YES coercion + empty LIST input + normal CollectionDeserializer
assertArrayEquals(new StringWrapper[0],
COERCION_MAPPER.readValue("[]", new TypeReference<StringWrapper[]>() {}));
}
@Test
public void testBlankToArray() throws Exception {
// NO coercion + empty string input + StringCollectionDeserializer
assertArrayEquals(new String[]{" "},
NORMAL_MAPPER.readValue("\" \"", new TypeReference<String[]>() {}));
}
@Test
public void testBlankToArrayWrapper() throws Exception {
// NO coercion + empty string input + normal CollectionDeserializer
assertArrayEquals(new StringWrapper[]{new StringWrapper(" ")},
NORMAL_MAPPER.readValue("\" \"", new TypeReference<StringWrapper[]>() {}));
}
@Test
public void testCoercedBlankToArray() throws Exception {
// YES coercion + empty string input + StringCollectionDeserializer
assertArrayEquals(new String[0],
COERCION_MAPPER.readValue("\" \"", new TypeReference<String[]>() {}));
}
@Test
public void testCoercedBlankToArrayWrapper() throws Exception {
// YES coercion + empty string input + normal CollectionDeserializer
assertArrayEquals(new StringWrapper[0],
COERCION_MAPPER.readValue("\" \"", new TypeReference<StringWrapper[]>() {}));
}
}
|
StringWrapper
|
java
|
alibaba__nacos
|
core/src/main/java/com/alibaba/nacos/core/remote/RuntimeConnectionEjector.java
|
{
"start": 813,
"end": 2034
}
|
class ____ {
/**
* 4 times of client keep alive.
*/
public static final long KEEP_ALIVE_TIME = 20000L;
/**
* current loader adjust count,only effective once,use to re balance.
*/
private int loadClient = -1;
String redirectAddress = null;
protected ConnectionManager connectionManager;
public RuntimeConnectionEjector() {
}
public ConnectionManager getConnectionManager() {
return connectionManager;
}
public void setConnectionManager(ConnectionManager connectionManager) {
this.connectionManager = connectionManager;
}
/**
* eject runtime connection.
*/
public abstract void doEject();
public int getLoadClient() {
return loadClient;
}
public void setLoadClient(int loadClient) {
this.loadClient = loadClient;
}
public String getRedirectAddress() {
return redirectAddress;
}
public void setRedirectAddress(String redirectAddress) {
this.redirectAddress = redirectAddress;
}
/**
* get name.
*
* @return
*/
public abstract String getName();
}
|
RuntimeConnectionEjector
|
java
|
netty__netty
|
codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexHandlerTest.java
|
{
"start": 1179,
"end": 4227
}
|
class ____ extends Http2MultiplexTest<Http2FrameCodec> {
@Override
protected Http2FrameCodec newCodec(TestChannelInitializer childChannelInitializer, Http2FrameWriter frameWriter) {
return new Http2FrameCodecBuilder(true).frameWriter(frameWriter).build();
}
@Override
protected ChannelHandler newMultiplexer(TestChannelInitializer childChannelInitializer) {
return new Http2MultiplexHandler(childChannelInitializer, null);
}
@Override
protected boolean useUserEventForResetFrame() {
return true;
}
@Override
protected boolean ignoreWindowUpdateFrames() {
return true;
}
@Override
protected boolean useUserEventForPriorityFrame() {
return true;
}
@Test
public void sslExceptionTriggersChildChannelException() {
final LastInboundHandler inboundHandler = new LastInboundHandler();
Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);
assertTrue(channel.isActive());
final RuntimeException testExc = new RuntimeException(new SSLException("foo"));
channel.parent().pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause != testExc) {
super.exceptionCaught(ctx, cause);
}
}
});
channel.parent().pipeline().fireExceptionCaught(testExc);
assertTrue(channel.isActive());
RuntimeException exc = assertThrows(RuntimeException.class, new Executable() {
@Override
public void execute() throws Throwable {
inboundHandler.checkException();
}
});
assertEquals(testExc, exc);
}
@Test
public void customExceptionForwarding() {
final LastInboundHandler inboundHandler = new LastInboundHandler();
Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);
assertTrue(channel.isActive());
final RuntimeException testExc = new RuntimeException("xyz");
channel.parent().pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause != testExc) {
super.exceptionCaught(ctx, cause);
} else {
ctx.pipeline().fireExceptionCaught(new Http2MultiplexActiveStreamsException(cause));
}
}
});
channel.parent().pipeline().fireExceptionCaught(testExc);
assertTrue(channel.isActive());
RuntimeException exc = assertThrows(RuntimeException.class, new Executable() {
@Override
public void execute() throws Throwable {
inboundHandler.checkException();
}
});
assertEquals(testExc, exc);
}
}
|
Http2MultiplexHandlerTest
|
java
|
playframework__playframework
|
core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java
|
{
"start": 779,
"end": 3910
}
|
class ____ {
@Test
public void addBindings() {
Injector injector =
new GuiceApplicationBuilder()
.bindings(new AModule())
.bindings(bind(B.class).to(B1.class))
.injector();
assertThat(injector.instanceOf(A.class)).isInstanceOf(A1.class);
assertThat(injector.instanceOf(B.class)).isInstanceOf(B1.class);
}
@Test
public void overrideBindings() {
Application app =
new GuiceApplicationBuilder()
.bindings(new AModule())
.overrides(
// override the scala api configuration, which should underlie the java api
// configuration
bind(play.api.Configuration.class)
.to(
new GuiceApplicationBuilderSpec.ExtendConfiguration(
Scala.varargs(Scala.Tuple("a", 1)))),
// also override the java api configuration
bind(Config.class)
.to(new ExtendConfiguration(ConfigFactory.parseMap(ImmutableMap.of("b", 2)))),
bind(A.class).to(A2.class))
.injector()
.instanceOf(Application.class);
assertThat(app.config().getInt("a")).isEqualTo(1);
assertThat(app.config().getInt("b")).isEqualTo(2);
assertThat(app.injector().instanceOf(A.class)).isInstanceOf(A2.class);
}
@Test
public void disableModules() {
Injector injector =
new GuiceApplicationBuilder().bindings(new AModule()).disable(AModule.class).injector();
assertThrows(ConfigurationException.class, () -> injector.instanceOf(A.class));
}
@Test
public void setInitialConfigurationLoader() {
Config extra = ConfigFactory.parseMap(ImmutableMap.of("a", 1));
Application app =
new GuiceApplicationBuilder()
.withConfigLoader(env -> extra.withFallback(ConfigFactory.load(env.classLoader())))
.build();
assertThat(app.config().getInt("a")).isEqualTo(1);
}
@Test
public void setModuleLoader() {
Injector injector =
new GuiceApplicationBuilder()
.withModuleLoader(
(env, conf) ->
ImmutableList.of(
Guiceable.modules(
new play.api.inject.BuiltinModule(),
new play.api.i18n.I18nModule(),
new play.api.mvc.CookiesModule()),
Guiceable.bindings(bind(A.class).to(A1.class))))
.injector();
assertThat(injector.instanceOf(A.class)).isInstanceOf(A1.class);
}
@Test
public void setLoadedModulesDirectly() {
Injector injector =
new GuiceApplicationBuilder()
.load(
Guiceable.modules(
new play.api.inject.BuiltinModule(),
new play.api.i18n.I18nModule(),
new play.api.mvc.CookiesModule()),
Guiceable.bindings(bind(A.class).to(A1.class)))
.injector();
assertThat(injector.instanceOf(A.class)).isInstanceOf(A1.class);
}
public static
|
GuiceApplicationBuilderTest
|
java
|
apache__camel
|
components/camel-activemq/src/generated/java/org/apache/camel/component/activemq/ActiveMQComponentConfigurer.java
|
{
"start": 728,
"end": 3320
}
|
class ____ extends JmsComponentConfigurer implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
ActiveMQComponent target = (ActiveMQComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "brokerurl":
case "brokerURL": target.setBrokerURL(property(camelContext, java.lang.String.class, value)); return true;
case "embedded": target.setEmbedded(property(camelContext, boolean.class, value)); return true;
case "trustallpackages":
case "trustAllPackages": target.setTrustAllPackages(property(camelContext, boolean.class, value)); return true;
case "usepooledconnection":
case "usePooledConnection": target.setUsePooledConnection(property(camelContext, boolean.class, value)); return true;
case "usesingleconnection":
case "useSingleConnection": target.setUseSingleConnection(property(camelContext, boolean.class, value)); return true;
default: return super.configure(camelContext, obj, name, value, ignoreCase);
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "brokerurl":
case "brokerURL": return java.lang.String.class;
case "embedded": return boolean.class;
case "trustallpackages":
case "trustAllPackages": return boolean.class;
case "usepooledconnection":
case "usePooledConnection": return boolean.class;
case "usesingleconnection":
case "useSingleConnection": return boolean.class;
default: return super.getOptionType(name, ignoreCase);
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
ActiveMQComponent target = (ActiveMQComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "brokerurl":
case "brokerURL": return target.getBrokerURL();
case "embedded": return target.isEmbedded();
case "trustallpackages":
case "trustAllPackages": return target.isTrustAllPackages();
case "usepooledconnection":
case "usePooledConnection": return target.isUsePooledConnection();
case "usesingleconnection":
case "useSingleConnection": return target.isUseSingleConnection();
default: return super.getOptionValue(obj, name, ignoreCase);
}
}
}
|
ActiveMQComponentConfigurer
|
java
|
apache__camel
|
core/camel-core-model/src/main/java/org/apache/camel/model/rest/ResponseHeaderDefinition.java
|
{
"start": 6525,
"end": 6902
}
|
enum ____
*/
public ResponseHeaderDefinition allowableValues(String... allowableValues) {
List<ValueDefinition> list = new ArrayList<>();
for (String av : allowableValues) {
list.add(new ValueDefinition(av));
}
setAllowableValues(list);
return this;
}
/**
* Allowed values of the parameter when its an
|
type
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/schedulers/AbstractSchedulerConcurrencyTests.java
|
{
"start": 1242,
"end": 15325
}
|
class ____ extends AbstractSchedulerTests {
/**
* Make sure canceling through {@code subscribeOn} works.
* Bug report: https://github.com/ReactiveX/RxJava/issues/431
* @throws InterruptedException if the test is interrupted
*/
@Test
public final void unSubscribeForScheduler() throws InterruptedException {
final AtomicInteger countReceived = new AtomicInteger();
final AtomicInteger countGenerated = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
Flowable.interval(50, TimeUnit.MILLISECONDS)
.map(new Function<Long, Long>() {
@Override
public Long apply(Long aLong) {
countGenerated.incrementAndGet();
return aLong;
}
})
.subscribeOn(getScheduler())
.observeOn(getScheduler())
.subscribe(new DefaultSubscriber<Long>() {
@Override
public void onComplete() {
System.out.println("--- completed");
}
@Override
public void onError(Throwable e) {
System.out.println("--- onError");
}
@Override
public void onNext(Long args) {
if (countReceived.incrementAndGet() == 2) {
cancel();
latch.countDown();
}
System.out.println("==> Received " + args);
}
});
latch.await(1000, TimeUnit.MILLISECONDS);
System.out.println("----------- it thinks it is finished ------------------ ");
int timeout = 10;
while (timeout-- > 0 && countGenerated.get() != 2) {
Thread.sleep(100);
}
assertEquals(2, countGenerated.get());
}
@Test
public void unsubscribeRecursiveScheduleFromOutside() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch unsubscribeLatch = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
final Worker inner = getScheduler().createWorker();
try {
inner.schedule(new Runnable() {
@Override
public void run() {
inner.schedule(new Runnable() {
int i;
@Override
public void run() {
System.out.println("Run: " + i++);
if (i == 10) {
latch.countDown();
try {
// wait for unsubscribe to finish so we are not racing it
unsubscribeLatch.await();
} catch (InterruptedException e) {
// we expect the countDown if unsubscribe is not working
// or to be interrupted if unsubscribe is successful since
// the unsubscribe will interrupt it as it is calling Future.cancel(true)
// so we will ignore the stacktrace
}
}
counter.incrementAndGet();
inner.schedule(this);
}
});
}
});
latch.await();
inner.dispose();
unsubscribeLatch.countDown();
Thread.sleep(200); // let time pass to see if the scheduler is still doing work
assertEquals(10, counter.get());
} finally {
inner.dispose();
}
}
@Test
public void unsubscribeRecursiveScheduleFromInside() throws InterruptedException {
final CountDownLatch unsubscribeLatch = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
final Worker inner = getScheduler().createWorker();
try {
inner.schedule(new Runnable() {
@Override
public void run() {
inner.schedule(new Runnable() {
int i;
@Override
public void run() {
System.out.println("Run: " + i++);
if (i == 10) {
inner.dispose();
}
counter.incrementAndGet();
inner.schedule(this);
}
});
}
});
unsubscribeLatch.countDown();
Thread.sleep(200); // let time pass to see if the scheduler is still doing work
assertEquals(10, counter.get());
} finally {
inner.dispose();
}
}
@Test
public void unsubscribeRecursiveScheduleWithDelay() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch unsubscribeLatch = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
final Worker inner = getScheduler().createWorker();
try {
inner.schedule(new Runnable() {
@Override
public void run() {
inner.schedule(new Runnable() {
long i = 1L;
@Override
public void run() {
if (i++ == 10) {
latch.countDown();
try {
// wait for unsubscribe to finish so we are not racing it
unsubscribeLatch.await();
} catch (InterruptedException e) {
// we expect the countDown if unsubscribe is not working
// or to be interrupted if unsubscribe is successful since
// the unsubscribe will interrupt it as it is calling Future.cancel(true)
// so we will ignore the stacktrace
}
}
counter.incrementAndGet();
inner.schedule(this, 10, TimeUnit.MILLISECONDS);
}
}, 10, TimeUnit.MILLISECONDS);
}
});
latch.await();
inner.dispose();
unsubscribeLatch.countDown();
Thread.sleep(200); // let time pass to see if the scheduler is still doing work
assertEquals(10, counter.get());
} finally {
inner.dispose();
}
}
@Test
public void recursionFromOuterActionAndUnsubscribeInside() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Worker inner = getScheduler().createWorker();
try {
inner.schedule(new Runnable() {
int i;
@Override
public void run() {
i++;
if (i % 100000 == 0) {
System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory());
}
if (i < 1000000L) {
inner.schedule(this);
} else {
latch.countDown();
}
}
});
latch.await();
} finally {
inner.dispose();
}
}
@Test
public void recursion() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Worker inner = getScheduler().createWorker();
try {
inner.schedule(new Runnable() {
private long i;
@Override
public void run() {
i++;
if (i % 100000 == 0) {
System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory());
}
if (i < 1000000L) {
inner.schedule(this);
} else {
latch.countDown();
}
}
});
latch.await();
} finally {
inner.dispose();
}
}
@Test
public void recursionAndOuterUnsubscribe() throws InterruptedException {
// use latches instead of Thread.sleep
final CountDownLatch latch = new CountDownLatch(10);
final CountDownLatch completionLatch = new CountDownLatch(1);
final Worker inner = getScheduler().createWorker();
try {
Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() {
@Override
public void subscribe(final Subscriber<? super Integer> subscriber) {
inner.schedule(new Runnable() {
@Override
public void run() {
subscriber.onNext(42);
latch.countDown();
// this will recursively schedule this task for execution again
inner.schedule(this);
}
});
subscriber.onSubscribe(new Subscription() {
@Override
public void cancel() {
inner.dispose();
subscriber.onComplete();
completionLatch.countDown();
}
@Override
public void request(long n) {
}
});
}
});
final AtomicInteger count = new AtomicInteger();
final AtomicBoolean completed = new AtomicBoolean(false);
ResourceSubscriber<Integer> s = new ResourceSubscriber<Integer>() {
@Override
public void onComplete() {
System.out.println("Completed");
completed.set(true);
}
@Override
public void onError(Throwable e) {
System.out.println("Error");
}
@Override
public void onNext(Integer args) {
count.incrementAndGet();
System.out.println(args);
}
};
obs.subscribe(s);
if (!latch.await(5000, TimeUnit.MILLISECONDS)) {
fail("Timed out waiting on onNext latch");
}
// now unsubscribe and ensure it stops the recursive loop
s.dispose();
System.out.println("unsubscribe");
if (!completionLatch.await(5000, TimeUnit.MILLISECONDS)) {
fail("Timed out waiting on completion latch");
}
// the count can be 10 or higher due to thread scheduling of the unsubscribe vs the scheduler looping to emit the count
assertTrue(count.get() >= 10);
assertTrue(completed.get());
} finally {
inner.dispose();
}
}
@Test
public final void subscribeWithScheduler() throws InterruptedException {
final Scheduler scheduler = getScheduler();
final AtomicInteger count = new AtomicInteger();
Flowable<Integer> f1 = Flowable.<Integer> just(1, 2, 3, 4, 5);
f1.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.println("Thread: " + Thread.currentThread().getName());
System.out.println("t: " + t);
count.incrementAndGet();
}
});
// the above should be blocking so we should see a count of 5
assertEquals(5, count.get());
count.set(0);
// now we'll subscribe with a scheduler and it should be async
final String currentThreadName = Thread.currentThread().getName();
// latches for deterministically controlling the test below across threads
final CountDownLatch latch = new CountDownLatch(5);
final CountDownLatch first = new CountDownLatch(1);
f1.subscribeOn(scheduler).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
try {
// we block the first one so we can assert this executes asynchronously with a count
first.await(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("The latch should have released if we are async.", e);
}
assertNotEquals(Thread.currentThread().getName(), currentThreadName);
System.out.println("Thread: " + Thread.currentThread().getName());
System.out.println("t: " + t);
count.incrementAndGet();
latch.countDown();
}
});
// assert we are async
assertEquals(0, count.get());
// release the latch so it can go forward
first.countDown();
// wait for all 5 responses
latch.await();
assertEquals(5, count.get());
}
}
|
AbstractSchedulerConcurrencyTests
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/injection/guice/Binder.java
|
{
"start": 1976,
"end": 3793
}
|
class ____ serve as an
* explicit <i>manifest</i> for the services it provides. Also, in rare cases,
* Guice may be unable to validate a binding at injector creation time unless it
* is given explicitly.
*
* <pre>
* bind(Service.class).to(ServiceImpl.class);</pre>
*
* Specifies that a request for a {@code Service} instance with no binding
* annotations should be treated as if it were a request for a
* {@code ServiceImpl} instance.
*
* <pre>
* bind(Service.class).toProvider(ServiceProvider.class);</pre>
*
* In this example, {@code ServiceProvider} must extend or implement
* {@code Provider<Service>}. This binding specifies that Guice should resolve
* an unannotated injection request for {@code Service} by first resolving an
* instance of {@code ServiceProvider} in the regular way, then calling
* {@link Provider#get get()} on the resulting Provider instance to obtain the
* {@code Service} instance.
*
* <p>The {@link Provider} you use here does not have to be a "factory"; that
* is, a provider which always <i>creates</i> each instance it provides.
* However, this is generally a good practice to follow.
*
* <pre>
* bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);</pre>
*
* Like the previous example, but only applies to injection requests that use
* the binding annotation {@code @Red}. If your module also includes bindings
* for particular <i>values</i> of the {@code @Red} annotation (see below),
* then this binding will serve as a "catch-all" for any values of {@code @Red}
* that have no exact match in the bindings.
*
* <pre>
* bind(ServiceImpl.class).in(Singleton.class);
* // or, alternatively
* bind(ServiceImpl.class).in(Scopes.SINGLETON);</pre>
*
* Either of these statements places the {@code ServiceImpl}
|
to
|
java
|
apache__camel
|
components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cloud/KubernetesDnsServiceDiscovery.java
|
{
"start": 1244,
"end": 2536
}
|
class ____ extends KubernetesServiceDiscovery {
private final ConcurrentMap<String, List<ServiceDefinition>> cache;
private final String namespace;
private final String zone;
public KubernetesDnsServiceDiscovery(KubernetesConfiguration configuration) {
super(configuration);
this.namespace
= configuration.getNamespace() != null ? configuration.getNamespace() : System.getenv("KUBERNETES_NAMESPACE");
this.zone = configuration.getDnsDomain();
// validation
ObjectHelper.notNull(namespace, "Namespace");
ObjectHelper.notNull(zone, "DNS Domain");
this.cache = new ConcurrentHashMap<>();
}
@Override
public List<ServiceDefinition> getServices(String name) {
return this.cache.computeIfAbsent(name, key -> Collections.singletonList(newService(name)));
}
private ServiceDefinition newService(String name) {
return new DefaultServiceDefinition(
name, name + "." + getConfiguration().getNamespace() + ".svc." + getConfiguration().getDnsDomain(), -1);
}
@Override
public String toString() {
return "KubernetesDnsServiceDiscovery{" + "namespace='" + namespace + '\'' + ", zone='" + zone + '\'' + '}';
}
}
|
KubernetesDnsServiceDiscovery
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/DuplicateDateFormatFieldTest.java
|
{
"start": 3012,
"end": 3548
}
|
class ____ {
public void foo() {
SimpleDateFormat format = new SimpleDateFormat();
// BUG: Diagnostic contains: uses the field 'm' more than once
format.applyPattern("mm/dd/yyyy hh:mm:ss");
}
}
""")
.doTest();
}
@Test
public void simpleDateFormat_applyLocalizedPattern() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import java.text.SimpleDateFormat;
|
Test
|
java
|
spring-projects__spring-boot
|
smoke-test/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/SampleWsApplicationTests.java
|
{
"start": 1468,
"end": 2473
}
|
class ____ {
private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
@LocalServerPort
private int serverPort;
@BeforeEach
void setUp() {
this.webServiceTemplate.setDefaultUri("http://localhost:" + this.serverPort + "/services/");
}
@Test
void testSendingHolidayRequest(CapturedOutput output) {
String request = """
<hr:HolidayRequest xmlns:hr="https://company.example.com/hr/schemas">
<hr:Holiday>
<hr:StartDate>2013-10-20</hr:StartDate>
<hr:EndDate>2013-11-22</hr:EndDate>
</hr:Holiday>
<hr:Employee>
<hr:Number>1</hr:Number>
<hr:FirstName>John</hr:FirstName>
<hr:LastName>Doe</hr:LastName>
</hr:Employee>
</hr:HolidayRequest>""";
StreamSource source = new StreamSource(new StringReader(request));
StreamResult result = new StreamResult(System.out);
this.webServiceTemplate.sendSourceAndReceiveToResult(source, result);
assertThat(output).contains("Booking holiday for");
}
}
|
SampleWsApplicationTests
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/operators/resettable/SpillingResettableIterator.java
|
{
"start": 1949,
"end": 7221
}
|
class ____<T> implements ResettableIterator<T> {
private static final Logger LOG = LoggerFactory.getLogger(SpillingResettableIterator.class);
// ------------------------------------------------------------------------
private T next;
private T instance;
protected DataInputView inView;
protected final TypeSerializer<T> serializer;
private long elementCount;
private long currentElementNum;
protected final SpillingBuffer buffer;
protected final Iterator<T> input;
protected final MemoryManager memoryManager;
private final List<MemorySegment> memorySegments;
private final boolean releaseMemoryOnClose;
// ------------------------------------------------------------------------
public SpillingResettableIterator(
Iterator<T> input,
TypeSerializer<T> serializer,
MemoryManager memoryManager,
IOManager ioManager,
int numPages,
AbstractInvokable parentTask)
throws MemoryAllocationException {
this(
input,
serializer,
memoryManager,
ioManager,
memoryManager.allocatePages(parentTask, numPages),
true);
}
public SpillingResettableIterator(
Iterator<T> input,
TypeSerializer<T> serializer,
MemoryManager memoryManager,
IOManager ioManager,
List<MemorySegment> memory) {
this(input, serializer, memoryManager, ioManager, memory, false);
}
private SpillingResettableIterator(
Iterator<T> input,
TypeSerializer<T> serializer,
MemoryManager memoryManager,
IOManager ioManager,
List<MemorySegment> memory,
boolean releaseMemOnClose) {
this.memoryManager = memoryManager;
this.input = input;
this.instance = serializer.createInstance();
this.serializer = serializer;
this.memorySegments = memory;
this.releaseMemoryOnClose = releaseMemOnClose;
if (LOG.isDebugEnabled()) {
LOG.debug(
"Creating spilling resettable iterator with "
+ memory.size()
+ " pages of memory.");
}
this.buffer =
new SpillingBuffer(
ioManager,
new ListMemorySegmentSource(memory),
memoryManager.getPageSize());
}
public void open() {
if (LOG.isDebugEnabled()) {
LOG.debug("Spilling Resettable Iterator opened.");
}
}
public void reset() throws IOException {
this.inView = this.buffer.flip();
this.currentElementNum = 0;
}
@Override
public boolean hasNext() {
if (this.next == null) {
if (this.inView != null) {
if (this.currentElementNum < this.elementCount) {
try {
this.instance = this.serializer.deserialize(this.instance, this.inView);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error reading element from buffer.", e);
}
this.next = this.instance;
this.currentElementNum++;
return true;
} else {
return false;
}
} else {
// writing pass (first)
if (this.input.hasNext()) {
this.next = this.input.next();
try {
this.serializer.serialize(this.next, this.buffer);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error writing element to buffer.", e);
}
this.elementCount++;
return true;
} else {
return false;
}
}
} else {
return true;
}
}
@Override
public T next() {
if (this.next != null || hasNext()) {
final T out = this.next;
this.next = null;
return out;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public List<MemorySegment> close() throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Spilling Resettable Iterator closing. Stored "
+ this.elementCount
+ " records.");
}
this.inView = null;
final List<MemorySegment> memory = this.buffer.close();
memory.addAll(this.memorySegments);
this.memorySegments.clear();
if (this.releaseMemoryOnClose) {
this.memoryManager.release(memory);
return Collections.emptyList();
} else {
return memory;
}
}
}
|
SpillingResettableIterator
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/annotation/DirtiesContext.java
|
{
"start": 3289,
"end": 3924
}
|
class ____ set to
* {@link ClassMode#AFTER_CLASS AFTER_CLASS}</li>
* </ul>
*
* <p>{@code BEFORE_*} modes are supported by the
* {@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener
* DirtiesContextBeforeModesTestExecutionListener}; {@code AFTER_*} modes are supported by the
* {@link org.springframework.test.context.support.DirtiesContextTestExecutionListener
* DirtiesContextTestExecutionListener}.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em>.
*
* <p>This annotation will be inherited from an enclosing test
|
mode
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.