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
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/inject/beans/inheritance/AbstractService.java
|
{
"start": 64,
"end": 123
}
|
class ____<T> implements ServiceContract<T> {
}
|
AbstractService
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/errors/TransactionExceptionHierarchyTest.java
|
{
"start": 1256,
"end": 1583
}
|
class ____ `RetriableException`
* and does **not** extend `RefreshRetriableException`.
*
* Using `RefreshRetriableException` changes the exception handling behavior,
* so only exceptions extending `RetriableException` directly are considered valid here.
*
* @param exceptionClass the exception
|
extends
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SetHeaderProcessor.java
|
{
"start": 924,
"end": 1344
}
|
class ____ implements Processor {
private String headerName;
private Object headerValue;
public void setHeaderName(String name) {
headerName = name;
}
public void setHeaderValue(Object value) {
headerValue = value;
}
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(headerName, headerValue);
}
}
|
SetHeaderProcessor
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/HeapKeyedStateBackend.java
|
{
"start": 26841,
"end": 27081
}
|
interface ____ {
<K, N, SV, S extends State, IS extends S> IS updateState(
StateDescriptor<S, SV> stateDesc, StateTable<K, N, SV> stateTable, IS existingState)
throws Exception;
}
}
|
StateUpdateFactory
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jackson/src/test/java/org/springframework/boot/jackson/NameAndAgeJacksonComponent.java
|
{
"start": 1492,
"end": 1894
}
|
class ____ extends ObjectValueDeserializer<NameAndAge> {
@Override
protected NameAndAge deserializeObject(JsonParser jsonParser, DeserializationContext context, JsonNode tree) {
String name = nullSafeValue(tree.get("name"), String.class);
Integer age = nullSafeValue(tree.get("age"), Integer.class);
assertThat(age).isNotNull();
return NameAndAge.create(name, age);
}
}
}
|
Deserializer
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/cglib/proxy/Enhancer.java
|
{
"start": 33382,
"end": 34026
}
|
class ____ instantiate
* @return newly created instance
*/
private Object createUsingReflection(Class type) {
setThreadCallbacks(type, callbacks);
try {
if (argumentTypes != null) {
return ReflectUtils.newInstance(type, argumentTypes, arguments);
}
else {
return ReflectUtils.newInstance(type);
}
}
finally {
// clear thread callbacks to allow them to be gc'd
setThreadCallbacks(type, null);
}
}
/**
* Helper method to create an intercepted object.
* For finer control over the generated instance, use a new instance of <code>Enhancer</code>
* instead of this static method.
* @param type
|
to
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/ByteArrayManager.java
|
{
"start": 9923,
"end": 13263
}
|
class ____ extends ByteArrayManager {
private final Conf conf;
private final CounterMap counters;
private final ManagerMap managers;
Impl(Conf conf) {
this.conf = conf;
this.counters = new CounterMap(conf.countResetTimePeriodMs);
this.managers = new ManagerMap(conf.countLimit);
}
/**
* Allocate a byte array, where the length of the allocated array
* is the least power of two of the given length
* unless the given length is less than {@link #MIN_ARRAY_LENGTH}.
* In such case, the returned array length is equal to {@link
* #MIN_ARRAY_LENGTH}.
*
* If the number of allocated arrays exceeds the capacity,
* the current thread is blocked until
* the number of allocated arrays drops to below the capacity.
*
* The byte array allocated by this method must be returned for recycling
* via the {@link Impl#release(byte[])} method.
*
* @return a byte array with length larger than or equal to the given
* length.
*/
@Override
public byte[] newByteArray(final int arrayLength)
throws InterruptedException {
Preconditions.checkArgument(arrayLength >= 0);
if (LOG.isDebugEnabled()) {
DEBUG_MESSAGE.get().append("allocate(").append(arrayLength).append(")");
}
final byte[] array;
if (arrayLength == 0) {
array = EMPTY_BYTE_ARRAY;
} else {
final int powerOfTwo = arrayLength <= MIN_ARRAY_LENGTH?
MIN_ARRAY_LENGTH: leastPowerOfTwo(arrayLength);
final long count = counters.get(powerOfTwo, true).increment();
final boolean aboveThreshold = count > conf.countThreshold;
// create a new manager only if the count is above threshold.
final FixedLengthManager manager =
managers.get(powerOfTwo, aboveThreshold);
if (LOG.isDebugEnabled()) {
DEBUG_MESSAGE.get().append(": count=").append(count)
.append(aboveThreshold? ", aboveThreshold": ", belowThreshold");
}
array = manager != null? manager.allocate(): new byte[powerOfTwo];
}
if (LOG.isDebugEnabled()) {
DEBUG_MESSAGE.get().append(", return byte[")
.append(array.length).append("]");
logDebugMessage();
}
return array;
}
/**
* Recycle the given byte array.
*
* The byte array may or may not be allocated
* by the {@link Impl#newByteArray(int)} method.
*
* This is a non-blocking call.
*/
@Override
public int release(final byte[] array) {
Preconditions.checkNotNull(array);
if (LOG.isDebugEnabled()) {
DEBUG_MESSAGE.get()
.append("recycle: array.length=").append(array.length);
}
final int freeQueueSize;
if (array.length == 0) {
freeQueueSize = -1;
} else {
final FixedLengthManager manager = managers.get(array.length, false);
freeQueueSize = manager == null? -1: manager.recycle(array);
}
if (LOG.isDebugEnabled()) {
DEBUG_MESSAGE.get().append(", freeQueueSize=").append(freeQueueSize);
logDebugMessage();
}
return freeQueueSize;
}
CounterMap getCounters() {
return counters;
}
ManagerMap getManagers() {
return managers;
}
}
}
|
Impl
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/ibmwatsonx/request/IbmWatsonxChatCompletionRequest.java
|
{
"start": 965,
"end": 2639
}
|
class ____ implements IbmWatsonxRequest {
private final IbmWatsonxChatCompletionModel model;
private final UnifiedChatInput chatInput;
public IbmWatsonxChatCompletionRequest(UnifiedChatInput chatInput, IbmWatsonxChatCompletionModel model) {
this.chatInput = Objects.requireNonNull(chatInput);
this.model = Objects.requireNonNull(model);
}
@Override
public HttpRequest createHttpRequest() {
HttpPost httpPost = new HttpPost(model.uri());
ByteArrayEntity byteEntity = new ByteArrayEntity(
Strings.toString(new IbmWatsonxChatCompletionRequestEntity(chatInput, model)).getBytes(StandardCharsets.UTF_8)
);
httpPost.setEntity(byteEntity);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaType());
decorateWithAuth(httpPost);
return new HttpRequest(httpPost, getInferenceEntityId());
}
@Override
public URI getURI() {
return model.uri();
}
public void decorateWithAuth(HttpPost httpPost) {
IbmWatsonxRequest.decorateWithBearerToken(httpPost, model.getSecretSettings(), model.getInferenceEntityId());
}
@Override
public Request truncate() {
// No truncation for IBM watsonx chat completions
return this;
}
@Override
public boolean[] getTruncationInfo() {
// No truncation for IBM watsonx chat completions
return null;
}
@Override
public String getInferenceEntityId() {
return model.getInferenceEntityId();
}
@Override
public boolean isStreaming() {
return chatInput.stream();
}
}
|
IbmWatsonxChatCompletionRequest
|
java
|
apache__camel
|
components/camel-syslog/src/main/java/org/apache/camel/component/syslog/SyslogMessage.java
|
{
"start": 882,
"end": 2705
}
|
class ____ {
private SyslogFacility facility;
private SyslogSeverity severity;
private String remoteAddress;
private String localAddress;
private String hostname;
private String logMessage;
private Calendar timestamp;
public String getLogMessage() {
return logMessage;
}
public void setLogMessage(String logMessage) {
this.logMessage = logMessage;
}
public String getLocalAddress() {
return localAddress;
}
public void setLocalAddress(String localAddress) {
this.localAddress = localAddress;
}
public SyslogFacility getFacility() {
return facility;
}
public void setFacility(SyslogFacility facility) {
this.facility = facility;
}
public Calendar getTimestamp() {
return timestamp;
}
public void setTimestamp(Calendar timestamp) {
this.timestamp = timestamp;
}
public SyslogSeverity getSeverity() {
return severity;
}
public void setSeverity(SyslogSeverity severity) {
this.severity = severity;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
@Override
public String toString() {
return "SyslogMessage{" + "content='" + logMessage + '\'' + ", facility=" + facility + ", severity=" + severity
+ ", remoteAddress='" + remoteAddress + '\''
+ ", localAddress='" + localAddress + '\'' + ", hostname='" + hostname + '\'' + ", messageTime=" + timestamp
+ '}';
}
}
|
SyslogMessage
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestGlobExpander.java
|
{
"start": 994,
"end": 2478
}
|
class ____ {
@Test
public void testExpansionIsIdentical() throws IOException {
checkExpansionIsIdentical("");
checkExpansionIsIdentical("/}");
checkExpansionIsIdentical("/}{a,b}");
checkExpansionIsIdentical("{/");
checkExpansionIsIdentical("{a}");
checkExpansionIsIdentical("{a,b}/{b,c}");
checkExpansionIsIdentical("p\\{a/b,c/d\\}s");
checkExpansionIsIdentical("p{a\\/b,c\\/d}s");
}
@Test
public void testExpansion() throws IOException {
checkExpansion("{a/b}", "a/b");
checkExpansion("/}{a/b}", "/}a/b");
checkExpansion("p{a/b,c/d}s", "pa/bs", "pc/ds");
checkExpansion("{a/b,c/d,{e,f}}", "a/b", "c/d", "{e,f}");
checkExpansion("{a/b,c/d}{e,f}", "a/b{e,f}", "c/d{e,f}");
checkExpansion("{a,b}/{b,{c/d,e/f}}", "{a,b}/b", "{a,b}/c/d", "{a,b}/e/f");
checkExpansion("{a,b}/{c/\\d}", "{a,b}/c/d");
}
private void checkExpansionIsIdentical(String filePattern) throws IOException {
checkExpansion(filePattern, filePattern);
}
private void checkExpansion(String filePattern, String... expectedExpansions)
throws IOException {
List<String> actualExpansions = GlobExpander.expand(filePattern);
assertEquals(expectedExpansions.length,
actualExpansions.size(), "Different number of expansions");
for (int i = 0; i < expectedExpansions.length; i++) {
assertEquals(expectedExpansions[i],
actualExpansions.get(i), "Expansion of " + filePattern);
}
}
}
|
TestGlobExpander
|
java
|
quarkusio__quarkus
|
core/processor/src/main/java/io/quarkus/annotation/processor/Options.java
|
{
"start": 55,
"end": 305
}
|
class ____ {
public static final String LEGACY_CONFIG_ROOT = "legacyConfigRoot";
public static final String GENERATE_DOC = "generateDoc";
public static final String SPLIT_ON_CONFIG_ROOT_DESCRIPTION = "splitOnConfigRootDescription";
}
|
Options
|
java
|
google__error-prone
|
annotation/src/test/java/com/google/errorprone/BugPatternValidatorTest.java
|
{
"start": 4002,
"end": 4542
}
|
class ____ {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void customSuppressionAnnotation() throws Exception {
@BugPattern(
name = "customSuppressionAnnotation",
summary = "Uses a custom suppression annotation",
explanation = "Uses a custom suppression annotation",
severity = SeverityLevel.ERROR,
suppressionAnnotations = CustomSuppressionAnnotation.class)
final
|
BugPatternTestClass
|
java
|
quarkusio__quarkus
|
extensions/hibernate-search-standalone-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/HibernateSearchStandaloneBuildTimeConfig.java
|
{
"start": 818,
"end": 3056
}
|
interface ____ {
/**
* Whether Hibernate Search Standalone is enabled **during the build**.
*
* If Hibernate Search is disabled during the build, all processing related to Hibernate Search will be skipped,
* but it will not be possible to activate Hibernate Search at runtime:
* `quarkus.hibernate-search-standalone.active` will default to `false` and setting it to `true` will lead to an error.
*
* @asciidoclet
*/
@WithDefault("true")
boolean enabled();
/**
* Configuration for Elasticsearch/OpenSearch backends.
*/
@ConfigDocSection
@WithName("elasticsearch")
@WithUnnamedKey // The default backend has the null key
@ConfigDocMapKey("backend-name")
Map<String, HibernateSearchBackendElasticsearchBuildTimeConfig> backends();
/**
* A xref:hibernate-search-standalone-elasticsearch.adoc#bean-reference-note-anchor[bean reference] to a component
* that should be notified of any failure occurring in a background process
* (mainly index operations).
*
* The referenced bean must implement `FailureHandler`.
*
* See
* link:{hibernate-search-docs-url}#configuration-background-failure-handling[this section of the reference documentation]
* for more information.
*
* [NOTE]
* ====
* Instead of setting this configuration property,
* you can simply annotate your custom `FailureHandler` implementation with `@SearchExtension`
* and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically.
* See xref:hibernate-search-standalone-elasticsearch.adoc#plugging-in-custom-components[this section]
* for more information.
*
* If this configuration property is set, it takes precedence over any `@SearchExtension` annotation.
* ====
*
* @asciidoclet
*/
Optional<String> backgroundFailureHandler();
/**
* Management interface.
*/
@ConfigDocSection
HibernateSearchStandaloneBuildTimeConfigManagement management();
/**
* Configuration related to the mapping.
*/
MappingConfig mapping();
@ConfigGroup
|
HibernateSearchStandaloneBuildTimeConfig
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest64.java
|
{
"start": 974,
"end": 2050
}
|
class ____ extends MysqlTest {
@Test
public void test_one() throws Exception {
String sql = "create table t (c char(10) ,unique key a using hash (c(1))) charset = utf8mb4 engine=heap;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
SQLStatement stmt = parser.parseCreateTable();
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE t ("
+ "\n\tc char(10),"
+ "\n\tUNIQUE KEY a USING hash (c(1))"
+ "\n) CHARSET = utf8mb4 ENGINE = heap", output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("create table t ("
+ "\n\tc char(10),"
+ "\n\tunique key a using hash (c(1))"
+ "\n) charset = utf8mb4 engine = heap", output);
}
}
}
|
MySqlCreateTableTest64
|
java
|
netty__netty
|
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexActiveStreamsException.java
|
{
"start": 940,
"end": 1185
}
|
class ____ extends Exception {
public Http2MultiplexActiveStreamsException(Throwable cause) {
super(cause);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
|
Http2MultiplexActiveStreamsException
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/hbm/simple/dynamic/SimpleDynamicXmlTests.java
|
{
"start": 1348,
"end": 2732
}
|
class ____ {
@Test
public void testBinding(SessionFactoryScope factoryScope) {
final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory();
final EntityPersister entityDescriptor = sessionFactory.getRuntimeMetamodels()
.getMappingMetamodel()
.findEntityDescriptor( "SimpleDynamicEntity" );
final EntityIdentifierMapping identifierMapping = entityDescriptor.getIdentifierMapping();
assertThat( identifierMapping, instanceOf( BasicEntityIdentifierMapping.class ) );
final BasicEntityIdentifierMapping bid = (BasicEntityIdentifierMapping) identifierMapping;
assertThat( bid.getFetchableName(), is( "id" ) );
assertThat( bid.getPartName(), is( EntityIdentifierMapping.ID_ROLE_NAME ) );
assertThat( entityDescriptor.getNumberOfAttributeMappings(), is( 1 ) );
assertThat( entityDescriptor.getNumberOfDeclaredAttributeMappings(), is( 1 ) );
final AttributeMapping nameAttr = entityDescriptor.findAttributeMapping( "name" );
assertThat( nameAttr, notNullValue() );
}
@Test
public void testUsage(SessionFactoryScope factoryScope) {
factoryScope.inTransaction( (session) -> {
session.createQuery( "from SimpleDynamicEntity" ).list();
session.createQuery( "select e from SimpleDynamicEntity e" ).list();
session.createQuery( "select e from SimpleDynamicEntity e where e.name = 'abc'" ).list();
} );
}
}
|
SimpleDynamicXmlTests
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/state/StateDescriptorTest.java
|
{
"start": 1915,
"end": 11577
}
|
class ____ {
// ------------------------------------------------------------------------
// Tests for serializer initialization
// ------------------------------------------------------------------------
@Test
void testInitializeWithSerializer() throws Exception {
final TypeSerializer<String> serializer = StringSerializer.INSTANCE;
final TestStateDescriptor<String> descr = new TestStateDescriptor<>("test", serializer);
assertThat(descr.isSerializerInitialized()).isTrue();
assertThat(descr.getSerializer()).isNotNull();
assertThat(descr.getSerializer()).isInstanceOf(StringSerializer.class);
// this should not have any effect
descr.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(descr.isSerializerInitialized()).isTrue();
assertThat(descr.getSerializer()).isNotNull();
assertThat(descr.getSerializer()).isInstanceOf(StringSerializer.class);
TestStateDescriptor<String> clone = CommonTestUtils.createCopySerializable(descr);
assertThat(clone.isSerializerInitialized()).isTrue();
assertThat(clone.getSerializer()).isNotNull();
assertThat(clone.getSerializer()).isInstanceOf(StringSerializer.class);
}
@Test
void testInitializeSerializerBeforeSerialization() throws Exception {
final TestStateDescriptor<String> descr = new TestStateDescriptor<>("test", String.class);
assertThat(descr.isSerializerInitialized()).isFalse();
try {
descr.getSerializer();
fail("should fail with an exception");
} catch (IllegalStateException ignored) {
}
descr.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(descr.isSerializerInitialized()).isTrue();
assertThat(descr.getSerializer()).isNotNull();
assertThat(descr.getSerializer()).isInstanceOf(StringSerializer.class);
TestStateDescriptor<String> clone = CommonTestUtils.createCopySerializable(descr);
assertThat(clone.isSerializerInitialized()).isTrue();
assertThat(clone.getSerializer()).isNotNull();
assertThat(clone.getSerializer()).isInstanceOf(StringSerializer.class);
}
@Test
void testInitializeSerializerAfterSerialization() throws Exception {
final TestStateDescriptor<String> descr = new TestStateDescriptor<>("test", String.class);
assertThat(descr.isSerializerInitialized()).isFalse();
assertThatThrownBy(descr::getSerializer)
.isInstanceOf(IllegalStateException.class)
.describedAs("should fail with an exception");
TestStateDescriptor<String> clone = CommonTestUtils.createCopySerializable(descr);
assertThat(clone.isSerializerInitialized()).isFalse();
assertThatThrownBy(clone::getSerializer)
.isInstanceOf(IllegalStateException.class)
.describedAs("should fail with an exception");
clone.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(clone.isSerializerInitialized()).isTrue();
assertThat(clone.getSerializer()).isNotNull();
assertThat(clone.getSerializer()).isInstanceOf(StringSerializer.class);
}
@Test
void testInitializeSerializerAfterSerializationWithCustomConfig() throws Exception {
// guard our test assumptions.
assertThat(
new KryoSerializer<>(String.class, new SerializerConfigImpl())
.getKryo()
.getRegistration(File.class)
.getId())
.as("broken test assumption")
.isEqualTo(-1);
final ExecutionConfig config = new ExecutionConfig();
((SerializerConfigImpl) config.getSerializerConfig()).registerKryoType(File.class);
final TestStateDescriptor<Path> original = new TestStateDescriptor<>("test", Path.class);
TestStateDescriptor<Path> clone = CommonTestUtils.createCopySerializable(original);
clone.initializeSerializerUnlessSet(config);
// serialized one (later initialized) carries the registration
assertThat(
((KryoSerializer<?>) clone.getSerializer())
.getKryo()
.getRegistration(File.class)
.getId()
> 0)
.isTrue();
}
// ------------------------------------------------------------------------
// Tests for serializer initialization
// ------------------------------------------------------------------------
/**
* FLINK-6775, tests that the returned serializer is duplicated. This allows to share the state
* descriptor across threads.
*/
@Test
void testSerializerDuplication() {
// we need a serializer that actually duplicates for testing (a stateful one)
// we use Kryo here, because it meets these conditions
TypeSerializer<String> statefulSerializer =
new KryoSerializer<>(String.class, new SerializerConfigImpl());
TestStateDescriptor<String> descr = new TestStateDescriptor<>("foobar", statefulSerializer);
TypeSerializer<String> serializerA = descr.getSerializer();
TypeSerializer<String> serializerB = descr.getSerializer();
// check that the retrieved serializers are not the same
assertThat(serializerB).isNotSameAs(serializerA);
}
// ------------------------------------------------------------------------
// Test hashCode() and equals()
// ------------------------------------------------------------------------
@Test
void testHashCodeAndEquals() throws Exception {
final String name = "testName";
TestStateDescriptor<String> original = new TestStateDescriptor<>(name, String.class);
TestStateDescriptor<String> same = new TestStateDescriptor<>(name, String.class);
TestStateDescriptor<String> sameBySerializer =
new TestStateDescriptor<>(name, StringSerializer.INSTANCE);
// test that hashCode() works on state descriptors with initialized and uninitialized
// serializers
assertThat(same).hasSameHashCodeAs(original);
assertThat(sameBySerializer).hasSameHashCodeAs(original);
assertThat(same).isEqualTo(original);
assertThat(sameBySerializer).isEqualTo(original);
// equality with a clone
TestStateDescriptor<String> clone = CommonTestUtils.createCopySerializable(original);
assertThat(clone).isEqualTo(original);
// equality with an initialized
clone.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(clone).isEqualTo(original);
original.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(same).isEqualTo(original);
}
@Test
void testEqualsSameNameAndTypeDifferentClass() {
final String name = "test name";
final TestStateDescriptor<String> descr1 = new TestStateDescriptor<>(name, String.class);
final OtherTestStateDescriptor<String> descr2 =
new OtherTestStateDescriptor<>(name, String.class);
assertThat(descr2).isNotEqualTo(descr1);
}
@Test
void testSerializerLazyInitializeInParallel() throws Exception {
final String name = "testSerializerLazyInitializeInParallel";
// use PojoTypeInfo which will create a new serializer when createSerializer is invoked.
final TestStateDescriptor<String> desc =
new TestStateDescriptor<>(
name, new PojoTypeInfo<>(String.class, new ArrayList<>()));
final int threadNumber = 20;
final ArrayList<CheckedThread> threads = new ArrayList<>(threadNumber);
final ExecutionConfig executionConfig = new ExecutionConfig();
final ConcurrentHashMap<Integer, TypeSerializer<String>> serializers =
new ConcurrentHashMap<>();
for (int i = 0; i < threadNumber; i++) {
threads.add(
new CheckedThread() {
@Override
public void go() {
desc.initializeSerializerUnlessSet(executionConfig);
TypeSerializer<String> serializer = desc.getOriginalSerializer();
serializers.put(System.identityHashCode(serializer), serializer);
}
});
}
threads.forEach(Thread::start);
for (CheckedThread t : threads) {
t.sync();
}
assertThat(serializers)
.as("Should use only one serializer but actually: " + serializers)
.hasSize(1);
threads.clear();
}
@Test
void testStateTTlConfig() {
ValueStateDescriptor<Integer> stateDescriptor =
new ValueStateDescriptor<>("test-state", IntSerializer.INSTANCE);
stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Duration.ofMinutes(60)).build());
assertThat(stateDescriptor.getTtlConfig().isEnabled()).isTrue();
stateDescriptor.enableTimeToLive(StateTtlConfig.DISABLED);
assertThat(stateDescriptor.getTtlConfig().isEnabled()).isFalse();
}
// ------------------------------------------------------------------------
// Mock implementations and test types
// ------------------------------------------------------------------------
private static
|
StateDescriptorTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpoint.java
|
{
"start": 2556,
"end": 3088
}
|
class ____ {
*
* @ConditionalOnAvailableEndpoint
* @Bean
* public MyEndpointWebExtension myEndpointWebExtension() {
* ...
* }
*
* }</pre>
* <p>
* In the sample above, {@code MyEndpointWebExtension} will be created if the endpoint is
* available as defined by the rules above. {@code MyEndpointWebExtension} must be a
* regular extension that refers to an endpoint, something like:
*
* <pre class="code">
* @EndpointWebExtension(endpoint = MyEndpoint.class)
* public
|
MyConfiguration
|
java
|
spring-projects__spring-framework
|
spring-tx/src/main/java/org/springframework/transaction/support/CallbackPreferringPlatformTransactionManager.java
|
{
"start": 1344,
"end": 1801
}
|
interface ____ choose to prepare a
* callback instead of explicit transaction demarcation control.
*
* <p>Spring's {@link TransactionTemplate} and
* {@link org.springframework.transaction.interceptor.TransactionInterceptor}
* detect and use this PlatformTransactionManager variant automatically.
*
* @author Juergen Hoeller
* @since 2.0
* @see TransactionTemplate
* @see org.springframework.transaction.interceptor.TransactionInterceptor
*/
public
|
to
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldHaveMessageFindingMatchRegex_create_Test.java
|
{
"start": 995,
"end": 1898
}
|
class ____ {
@Test
void should_create_error_message() {
// GIVEN
String regex = "regex";
RuntimeException actual = new RuntimeException("error %s message");
// WHEN
String errorMessage = shouldHaveMessageFindingMatchRegex(actual, regex).create(new TestDescription("TEST"));
// THEN
then(errorMessage).isEqualTo("[TEST] %n" +
"Expecting message:%n" +
" \"error %%s message\"%n" +
"to be found for regex:%n" +
" \"regex\"%n" +
"but did not.%n" +
"%n" +
"Throwable that failed the check:%n" +
"%n%s",
getStackTrace(actual));
}
}
|
ShouldHaveMessageFindingMatchRegex_create_Test
|
java
|
elastic__elasticsearch
|
test/yaml-rest-runner/src/main/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApi.java
|
{
"start": 1606,
"end": 6875
}
|
enum ____ {
NOT_SUPPORTED,
OPTIONAL,
REQUIRED
}
ClientYamlSuiteRestApi(String location, String name) {
this.location = location;
this.name = name;
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
void addPath(String path, String[] methods, Set<String> parts, boolean deprecated) {
Objects.requireNonNull(path, name + " API: path must not be null");
Objects.requireNonNull(methods, name + " API: methods must not be null");
if (methods.length == 0) {
throw new IllegalArgumentException(name + " API: methods is empty, at least one method is required");
}
Objects.requireNonNull(parts, name + " API: parts must not be null");
for (String part : parts) {
if (path.contains("{" + part + "}") == false) {
throw new IllegalArgumentException(name + " API: part [" + part + "] not contained in path [" + path + "]");
}
}
boolean add = this.paths.add(new Path(path, methods, parts, deprecated));
if (add == false) {
throw new IllegalArgumentException(name + " API: found duplicate path [" + path + "]");
}
}
public Collection<Path> getPaths() {
return paths;
}
/**
* Gets all parameters supported by the api. For every parameter defines if it
* is required or optional.
*/
public Map<String, Boolean> getParams() {
return params;
}
void addParam(String param, boolean required) {
this.params.put(param, required);
}
void setBodyOptional() {
this.body = Body.OPTIONAL;
}
void setBodyRequired() {
this.body = Body.REQUIRED;
}
public boolean isBodySupported() {
return body != Body.NOT_SUPPORTED;
}
public boolean isBodyRequired() {
return body == Body.REQUIRED;
}
public void setStability(String stability) {
this.stability = Stability.valueOf(stability.toUpperCase(Locale.ROOT));
}
public Stability getStability() {
return this.stability;
}
public void setVisibility(String visibility) {
this.visibility = Visibility.valueOf(visibility.toUpperCase(Locale.ROOT));
}
public Visibility getVisibility() {
return this.visibility;
}
public void setFeatureFlag(String featureFlag) {
this.featureFlag = featureFlag;
}
public String getFeatureFlag() {
return this.featureFlag;
}
public void setResponseMimeTypes(List<String> mimeTypes) {
this.responseMimeTypes = mimeTypes;
}
public List<String> getResponseMimeTypes() {
return this.responseMimeTypes;
}
public void setRequestMimeTypes(List<String> mimeTypes) {
this.requestMimeTypes = mimeTypes;
}
public List<String> getRequestMimeTypes() {
return this.requestMimeTypes;
}
/**
* Returns the best matching paths based on the provided parameters, which may include either path parts or query_string parameters.
* The best path is the one that has exactly the same number of placeholders to replace
* (e.g. /{index}/{type}/{id} when the path params are exactly index, type and id).
* It returns a list instead of a single path as there are cases where there is more than one best matching path:
* - /{index}/_alias/{name}, /{index}/_aliases/{name}
* - /{index}/{type}/_mapping, /{index}/{type}/_mappings, /{index}/_mappings/{type}, /{index}/_mapping/{type}
*/
public List<ClientYamlSuiteRestApi.Path> getBestMatchingPaths(Set<String> pathParams) {
PriorityQueue<Tuple<Integer, Path>> queue = new PriorityQueue<>(Comparator.comparing(Tuple::v1, (a, b) -> Integer.compare(b, a)));
for (ClientYamlSuiteRestApi.Path path : paths) {
int matches = 0;
for (String actualParameter : pathParams) {
if (path.parts().contains(actualParameter)) {
matches++;
}
}
if (matches == path.parts.size()) {
queue.add(Tuple.tuple(matches, path));
}
}
if (queue.isEmpty()) {
throw new IllegalStateException("Unable to find a matching path for api [" + name + "]" + pathParams);
}
List<Path> pathsByRelevance = new ArrayList<>();
Tuple<Integer, Path> poll = queue.poll();
int maxMatches = poll.v1();
do {
pathsByRelevance.add(poll.v2());
poll = queue.poll();
} while (poll != null && poll.v1() == maxMatches);
return pathsByRelevance;
}
public record Path(String path, String[] methods, Set<String> parts, boolean deprecated) {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Path other = (Path) o;
return this.path.equals(other.path);
}
@Override
public int hashCode() {
return Objects.hash(path);
}
}
}
|
Body
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java
|
{
"start": 495,
"end": 1168
}
|
class ____ extends TestBase {
@Mock List mock;
@Test
public void handles_bad_exception() {
Assertions.assertThatThrownBy(
new ThrowableAssert.ThrowingCallable() {
public void call() {
doThrow(UninstantiableException.class).when(mock).clear();
}
})
.isInstanceOf(
InstantiationError.class); // because the exception cannot be instantiated
// ensure that the state is cleaned
Mockito.validateMockitoUsage();
}
abstract static
|
StubbingWithBadThrowablesTest
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/LifecycleMethodOverridingTests.java
|
{
"start": 1009,
"end": 1121
}
|
class ____ {
@Nested
@DisplayName("a protected lifecycle method in a subclass")
|
PackagePrivateSuperClassTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/index/ComponentIndexTest.java
|
{
"start": 991,
"end": 1856
}
|
class ____ {
@Test
public void testTheIndexIsGenerated(ServiceRegistryScope registryScope, DomainModelScope modelScope) {
final List<String> commands = new SchemaCreatorImpl( registryScope.getRegistry() )
.generateCreationCommands( modelScope.getDomainModel(), false );
assertThatCreateIndexCommandIsGenerated( commands );
}
private void assertThatCreateIndexCommandIsGenerated(List<String> commands) {
boolean createIndexCommandIsGenerated = false;
for ( String command : commands ) {
if ( command.toLowerCase().contains( "create index city_index" ) ) {
createIndexCommandIsGenerated = true;
break;
}
}
Assertions.assertTrue( createIndexCommandIsGenerated, "Expected create index command not found" );
}
@Entity(name = "user")
@Table(indexes = @Index(name = "city_index", columnList = "city"))
public static
|
ComponentIndexTest
|
java
|
micronaut-projects__micronaut-core
|
inject/src/main/java/io/micronaut/context/condition/OperatingSystem.java
|
{
"start": 842,
"end": 3027
}
|
class ____ {
private static volatile OperatingSystem instance;
private final Family family;
private OperatingSystem(Family family) {
this.family = family;
}
/**
* Resolves and returns the current operating system.
*
* @return the current operating system.
*/
public static OperatingSystem getCurrent() {
if (instance == null) {
synchronized (OperatingSystem.class) {
if (instance == null) {
String osName = CachedEnvironment.getProperty("os.name").toLowerCase(Locale.ENGLISH);
Family osFamily;
if (osName.contains("linux")) {
osFamily = Family.LINUX;
} else if (osName.startsWith("mac") || osName.startsWith("darwin")) {
osFamily = Family.MAC_OS;
} else if (osName.contains("windows")) {
osFamily = Family.WINDOWS;
} else if (osName.contains("sunos")) {
osFamily = Family.SOLARIS;
} else {
osFamily = Family.OTHER;
}
instance = new OperatingSystem(osFamily);
}
}
}
return instance;
}
/**
* @return <code>true</code> if the current operating system is in the Linux family.
*/
public boolean isLinux() {
return family == Family.LINUX;
}
/**
* @return <code>true</code> if the current operating system is in the Windows family.
*/
public boolean isWindows() {
return family == Family.WINDOWS;
}
/**
* @return <code>true</code> if the current operating system is in the macOS family.
*/
public boolean isMacOs() {
return family == Family.MAC_OS;
}
/**
* @return <code>true</code> if the current operating system is in the Solaris family.
*/
public boolean isSolaris() {
return family == Family.SOLARIS;
}
/**
* @return The OS family
*/
public Family getFamily() {
return family;
}
}
|
OperatingSystem
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/sqlprovider/SqlProviderTest.java
|
{
"start": 38898,
"end": 39047
}
|
interface ____ {
@SelectProvider(type = SqlProvider.class)
String selectDatabaseId();
@SuppressWarnings("unused")
final
|
DatabaseIdMapper
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/nestedsourceproperties/_target/ChartPositions.java
|
{
"start": 303,
"end": 617
}
|
class ____ {
private final List<Long> positions = new ArrayList<>();
public List<Long> getPositions() {
return positions;
}
public Long addPosition(Long position) {
AdderUsageObserver.setUsed( true );
positions.add( position );
return position;
}
}
|
ChartPositions
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/repeatable/RepeatableDeleteTest.java
|
{
"start": 1092,
"end": 6488
}
|
class ____ {
@Test
void hsql() throws IOException, SQLException {
SqlSessionFactory sqlSessionFactory;
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-hsql");
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/repeatable/CreateDB.sql");
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.count();
int targetCount = mapper.countByCurrentDatabase("HSQL");
mapper.delete();
Assertions.assertEquals(count - targetCount, mapper.count());
Assertions.assertEquals(0, mapper.countByCurrentDatabase("HSQL"));
}
}
@Test
void hsqlUsingProvider() throws IOException, SQLException {
SqlSessionFactory sqlSessionFactory;
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-hsql");
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/repeatable/CreateDB.sql");
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.count();
int targetCount = mapper.countByCurrentDatabase("HSQL");
mapper.deleteUsingProvider();
Assertions.assertEquals(count - targetCount, mapper.count());
Assertions.assertEquals(0, mapper.countByCurrentDatabase("HSQL"));
}
}
@Test
void derby() throws IOException, SQLException {
SqlSessionFactory sqlSessionFactory;
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-derby");
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/repeatable/CreateDB.sql");
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.count();
int targetCount = mapper.countByCurrentDatabase("DERBY");
mapper.delete();
Assertions.assertEquals(count - targetCount, mapper.count());
Assertions.assertEquals(0, mapper.countByCurrentDatabase("DERBY"));
}
}
@Test
void derbyUsingProvider() throws IOException, SQLException {
SqlSessionFactory sqlSessionFactory;
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-derby");
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/repeatable/CreateDB.sql");
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.count();
int targetCount = mapper.countByCurrentDatabase("DERBY");
mapper.deleteUsingProvider();
Assertions.assertEquals(count - targetCount, mapper.count());
Assertions.assertEquals(0, mapper.countByCurrentDatabase("DERBY"));
}
}
@Test
void h2() throws IOException, SQLException {
SqlSessionFactory sqlSessionFactory;
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-h2");
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/repeatable/CreateDB.sql");
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.count();
int targetCount = mapper.countByCurrentDatabase("DEFAULT");
mapper.delete();
Assertions.assertEquals(count - targetCount, mapper.count());
Assertions.assertEquals(0, mapper.countByCurrentDatabase("DEFAULT"));
}
}
@Test
void h2UsingProvider() throws IOException, SQLException {
SqlSessionFactory sqlSessionFactory;
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/repeatable/mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development-h2");
}
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/repeatable/CreateDB.sql");
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.count();
int targetCount = mapper.countByCurrentDatabase("DEFAULT");
mapper.deleteUsingProvider();
Assertions.assertEquals(count - targetCount, mapper.count());
Assertions.assertEquals(0, mapper.countByCurrentDatabase("DEFAULT"));
}
}
}
|
RepeatableDeleteTest
|
java
|
apache__camel
|
components/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithAliasTest.java
|
{
"start": 1084,
"end": 1647
}
|
class ____ extends JpaTest {
@Override
protected String getEndpointUri() {
return "jpa://SendEmail";
}
@Override
protected void setUpComponent() {
Component compValue = camelContext.getComponent("jpa");
assertNotNull(compValue, "Could not find component!");
assertTrue(compValue instanceof JpaComponent, "Should be a JPA component but was: " + compValue);
component = (JpaComponent) compValue;
component.setAliases(Collections.singletonMap("SendEmail", SendEmail.class));
}
}
|
JpaWithAliasTest
|
java
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/inject/field/listinjection/B.java
|
{
"start": 713,
"end": 817
}
|
class ____ {
@Inject
private List<A> all;
List<A> getAll() {
return this.all;
}
}
|
B
|
java
|
apache__camel
|
components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/mtom/MtomTestHelper.java
|
{
"start": 1086,
"end": 4961
}
|
class ____ {
static final String SERVICE_TYPES_NS = "http://apache.org/camel/cxf/mtom_feature/types";
static final String XOP_NS = "http://www.w3.org/2004/08/xop/include";
static final byte[] REQ_PHOTO_DATA = { 1, 0, -1, 34, 23, 3, 23, 55, 33 };
static final byte[] RESP_PHOTO_DATA = { 5, -7, 23, 1, 0, -1, 34, 23, 3, 23, 55, 33, 3 };
static final String REQ_PHOTO_CID = "e33b6792-6666-4837-b0d9-68c88c8cadcb-1@apache.org";
static final String REQ_IMAGE_CID = "e33b6792-6666-4837-b0d9-68c88c8cadcb-2@apache.org";
static final String REQ_MESSAGE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<Detail xmlns=\"http://apache.org/camel/cxf/mtom_feature/types\">"
+ "<photo><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\""
+ " href=\"cid:" + REQ_PHOTO_CID + "\"/>"
+ "</photo><image><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\""
+ " href=\"cid:" + REQ_IMAGE_CID + "\"/></image></Detail>";
static final String MTOM_DISABLED_REQ_MESSAGE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<Detail xmlns=\"http://apache.org/camel/cxf/mtom_feature/types\">"
+ "<photo>cid:" + REQ_PHOTO_CID + "</photo>"
+ "<image>cid:" + REQ_IMAGE_CID + "</image></Detail>";
static final String RESP_PHOTO_CID = "4c7b78dc-356a-4fca-8877-068ee2f31824-7@apache.org";
static final String RESP_IMAGE_CID = "4c7b78dc-356a-4fca-8877-068ee2f31824-8@apache.org";
static final String RESP_MESSAGE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<DetailResponse xmlns=\"http://apache.org/camel/cxf/mtom_feature/types\">"
+ "<photo><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\""
+ " href=\"cid:" + RESP_PHOTO_CID + "\"/>"
+ "</photo><image><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\""
+ " href=\"cid:" + RESP_IMAGE_CID + "\"/></image></DetailResponse>";
static final String MTOM_DISABLED_RESP_MESSAGE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<DetailResponse xmlns=\"http://apache.org/camel/cxf/mtom_feature/types\">"
+ "<photo>cid:" + RESP_PHOTO_CID + "</photo>"
+ "<image>cid:" + RESP_IMAGE_CID + "</image></DetailResponse>";
static byte[] requestJpeg;
static byte[] responseJpeg;
private static final Logger LOG = LoggerFactory.getLogger(MtomTestHelper.class);
static {
try {
requestJpeg = IOUtils.readBytesFromStream(CxfMtomConsumerPayloadModeTest.class.getResourceAsStream("/java.jpg"));
responseJpeg = IOUtils.readBytesFromStream(CxfMtomConsumerPayloadModeTest.class.getResourceAsStream("/Splash.jpg"));
} catch (IOException e) {
LOG.warn("I/O error reading bytes from stream: {}", e.getMessage(), e);
}
}
private MtomTestHelper() {
// utility class
}
static boolean isAwtHeadless(org.apache.commons.logging.Log log, org.slf4j.Logger logger) {
assertFalse(log == null && logger == null, "Both loggers are not allowed to be null!");
boolean headless = Boolean.getBoolean("java.awt.headless");
if (headless) {
// having the conversion characters %c{1} inside log4j.properties will reveal us the
// test
|
MtomTestHelper
|
java
|
spring-projects__spring-security
|
crypto/src/test/java/org/springframework/security/crypto/password4j/Pbkdf2Password4jPasswordEncoderTests.java
|
{
"start": 1032,
"end": 5697
}
|
class ____ {
private static final String PASSWORD = "password";
private static final String DIFFERENT_PASSWORD = "differentpassword";
@Test
void constructorWithNullFunctionShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new Pbkdf2Password4jPasswordEncoder(null))
.withMessage("pbkdf2Function cannot be null");
}
@Test
void constructorWithInvalidSaltLengthShouldThrowException() {
PBKDF2Function function = AlgorithmFinder.getPBKDF2Instance();
assertThatIllegalArgumentException().isThrownBy(() -> new Pbkdf2Password4jPasswordEncoder(function, 0))
.withMessage("saltLength must be positive");
assertThatIllegalArgumentException().isThrownBy(() -> new Pbkdf2Password4jPasswordEncoder(function, -1))
.withMessage("saltLength must be positive");
}
@Test
void defaultConstructorShouldWork() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded = encoder.encode(PASSWORD);
assertThat(encoded).isNotNull().isNotEqualTo(PASSWORD).contains(":");
assertThat(encoder.matches(PASSWORD, encoded)).isTrue();
}
@Test
void customFunctionConstructorShouldWork() {
PBKDF2Function customFunction = AlgorithmFinder.getPBKDF2Instance();
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder(customFunction);
String encoded = encoder.encode(PASSWORD);
assertThat(encoded).isNotNull().isNotEqualTo(PASSWORD).contains(":");
assertThat(encoder.matches(PASSWORD, encoded)).isTrue();
}
@Test
void customSaltLengthConstructorShouldWork() {
PBKDF2Function function = AlgorithmFinder.getPBKDF2Instance();
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder(function, 16);
String encoded = encoder.encode(PASSWORD);
assertThat(encoded).isNotNull().isNotEqualTo(PASSWORD).contains(":");
assertThat(encoder.matches(PASSWORD, encoded)).isTrue();
}
@Test
void encodeShouldIncludeSaltInOutput() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded = encoder.encode(PASSWORD);
assertThat(encoded).contains(":");
String[] parts = encoded.split(":");
assertThat(parts).hasSize(2);
assertThat(parts[0]).isNotEmpty(); // salt part
assertThat(parts[1]).isNotEmpty(); // hash part
}
@Test
void matchesShouldReturnTrueForCorrectPassword() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded = encoder.encode(PASSWORD);
boolean matches = encoder.matches(PASSWORD, encoded);
assertThat(matches).isTrue();
}
@Test
void matchesShouldReturnFalseForIncorrectPassword() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded = encoder.encode(PASSWORD);
boolean matches = encoder.matches(DIFFERENT_PASSWORD, encoded);
assertThat(matches).isFalse();
}
@Test
void matchesShouldReturnFalseForMalformedEncodedPassword() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
assertThat(encoder.matches(PASSWORD, "malformed")).isFalse();
assertThat(encoder.matches(PASSWORD, "no:delimiter:in:wrong:places")).isFalse();
assertThat(encoder.matches(PASSWORD, "invalid_base64!:hash")).isFalse();
}
@Test
void multipleEncodingsShouldProduceDifferentHashesButAllMatch() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded1 = encoder.encode(PASSWORD);
String encoded2 = encoder.encode(PASSWORD);
assertThat(encoded1).isNotEqualTo(encoded2); // Different salts should produce
// different results
assertThat(encoder.matches(PASSWORD, encoded1)).isTrue();
assertThat(encoder.matches(PASSWORD, encoded2)).isTrue();
}
@Test
void upgradeEncodingShouldReturnFalse() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded = encoder.encode(PASSWORD);
boolean shouldUpgrade = encoder.upgradeEncoding(encoded);
assertThat(shouldUpgrade).isFalse();
}
@Test
void encodeNullShouldReturnNull() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
assertThat(encoder.encode(null)).isNull();
}
@Test
void matchesWithNullOrEmptyValuesShouldReturnFalse() {
Pbkdf2Password4jPasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder();
String encoded = encoder.encode(PASSWORD);
assertThat(encoder.matches(null, encoded)).isFalse();
assertThat(encoder.matches("", encoded)).isFalse();
assertThat(encoder.matches(PASSWORD, null)).isFalse();
assertThat(encoder.matches(PASSWORD, "")).isFalse();
}
}
|
Pbkdf2Password4jPasswordEncoderTests
|
java
|
spring-projects__spring-boot
|
smoke-test/spring-boot-smoke-test-xml/src/main/java/smoketest/xml/SampleSpringXmlApplication.java
|
{
"start": 995,
"end": 1518
}
|
class ____ implements CommandLineRunner {
private static final String CONTEXT_XML = "classpath:/META-INF/application-context.xml";
@Autowired
private HelloWorldService helloWorldService;
@Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) {
SpringApplication application = new SpringApplication();
application.setSources(Collections.singleton(CONTEXT_XML));
application.run(args);
}
}
|
SampleSpringXmlApplication
|
java
|
apache__flink
|
flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/table/api/bridge/java/internal/StreamTableEnvironmentImpl.java
|
{
"start": 3439,
"end": 11127
}
|
class ____ extends AbstractStreamTableEnvironmentImpl
implements StreamTableEnvironment {
public StreamTableEnvironmentImpl(
CatalogManager catalogManager,
ModuleManager moduleManager,
ResourceManager resourceManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode) {
super(
catalogManager,
moduleManager,
resourceManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
executionEnvironment);
}
public static StreamTableEnvironment create(
StreamExecutionEnvironment executionEnvironment, EnvironmentSettings settings) {
final MutableURLClassLoader userClassLoader =
FlinkUserCodeClassLoaders.create(
new URL[0], settings.getUserClassLoader(), settings.getConfiguration());
final Executor executor = lookupExecutor(userClassLoader, executionEnvironment);
final TableConfig tableConfig = TableConfig.getDefault();
tableConfig.setRootConfiguration(executor.getConfiguration());
tableConfig.addConfiguration(settings.getConfiguration());
final ResourceManager resourceManager =
new ResourceManager(settings.getConfiguration(), userClassLoader);
final ModuleManager moduleManager = new ModuleManager();
final CatalogStoreFactory catalogStoreFactory =
TableFactoryUtil.findAndCreateCatalogStoreFactory(
settings.getConfiguration(), userClassLoader);
final CatalogStoreFactory.Context catalogStoreFactoryContext =
TableFactoryUtil.buildCatalogStoreFactoryContext(
settings.getConfiguration(), userClassLoader);
catalogStoreFactory.open(catalogStoreFactoryContext);
final CatalogStore catalogStore =
settings.getCatalogStore() != null
? settings.getCatalogStore()
: catalogStoreFactory.createCatalogStore();
final CatalogManager catalogManager =
CatalogManager.newBuilder()
.classLoader(userClassLoader)
.config(tableConfig)
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.catalogModificationListeners(
TableFactoryUtil.findCatalogModificationListenerList(
settings.getConfiguration(), userClassLoader))
.catalogStoreHolder(
CatalogStoreHolder.newBuilder()
.classloader(userClassLoader)
.config(tableConfig)
.catalogStore(catalogStore)
.factory(catalogStoreFactory)
.build())
.build();
final FunctionCatalog functionCatalog =
new FunctionCatalog(tableConfig, resourceManager, catalogManager, moduleManager);
final Planner planner =
PlannerFactoryUtil.createPlanner(
executor,
tableConfig,
userClassLoader,
moduleManager,
catalogManager,
functionCatalog);
return new StreamTableEnvironmentImpl(
catalogManager,
moduleManager,
resourceManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode());
}
@Override
public <T> Table fromDataStream(DataStream<T> dataStream) {
return fromStreamInternal(dataStream, null, null, ChangelogMode.insertOnly());
}
@Override
public <T> Table fromDataStream(DataStream<T> dataStream, Schema schema) {
Preconditions.checkNotNull(schema, "Schema must not be null.");
return fromStreamInternal(dataStream, schema, null, ChangelogMode.insertOnly());
}
@Override
public Table fromChangelogStream(DataStream<Row> dataStream) {
return fromStreamInternal(dataStream, null, null, ChangelogMode.all());
}
@Override
public Table fromChangelogStream(DataStream<Row> dataStream, Schema schema) {
Preconditions.checkNotNull(schema, "Schema must not be null.");
return fromStreamInternal(dataStream, schema, null, ChangelogMode.all());
}
@Override
public Table fromChangelogStream(
DataStream<Row> dataStream, Schema schema, ChangelogMode changelogMode) {
Preconditions.checkNotNull(schema, "Schema must not be null.");
return fromStreamInternal(dataStream, schema, null, changelogMode);
}
@Override
public <T> void createTemporaryView(String path, DataStream<T> dataStream) {
createTemporaryView(
path, fromStreamInternal(dataStream, null, path, ChangelogMode.insertOnly()));
}
@Override
public <T> void createTemporaryView(String path, DataStream<T> dataStream, Schema schema) {
createTemporaryView(
path, fromStreamInternal(dataStream, schema, path, ChangelogMode.insertOnly()));
}
@Override
public DataStream<Row> toDataStream(Table table) {
Preconditions.checkNotNull(table, "Table must not be null.");
// include all columns of the query (incl. metadata and computed columns)
final DataType sourceType = table.getResolvedSchema().toSourceRowDataType();
if (!(table.getQueryOperation() instanceof ExternalQueryOperation)) {
return toDataStream(table, sourceType);
}
DataTypeFactory dataTypeFactory = getCatalogManager().getDataTypeFactory();
SchemaResolver schemaResolver = getCatalogManager().getSchemaResolver();
ExternalQueryOperation<?> queryOperation =
(ExternalQueryOperation<?>) table.getQueryOperation();
DataStream<?> dataStream = queryOperation.getDataStream();
SchemaTranslator.ConsumingResult consumingResult =
SchemaTranslator.createConsumingResult(dataTypeFactory, dataStream.getType(), null);
ResolvedSchema defaultSchema = consumingResult.getSchema().resolve(schemaResolver);
if (queryOperation.getChangelogMode().equals(ChangelogMode.insertOnly())
&& table.getResolvedSchema().equals(defaultSchema)
&& dataStream.getType() instanceof RowTypeInfo) {
return (DataStream<Row>) dataStream;
}
return toDataStream(table, sourceType);
}
@Override
@SuppressWarnings("unchecked")
public <T> DataStream<T> toDataStream(Table table, Class<T> targetClass) {
Preconditions.checkNotNull(table, "Table must not be null.");
Preconditions.checkNotNull(targetClass, "Target
|
StreamTableEnvironmentImpl
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/ConstraintOnStaticMethodTest.java
|
{
"start": 803,
"end": 943
}
|
class ____ {
public static void validateName(@Pattern(regexp = "A.*") String name) {
// do nothing
}
}
}
|
MyUtil
|
java
|
apache__kafka
|
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/Plugins.java
|
{
"start": 2374,
"end": 8033
}
|
enum ____ {
CURRENT_CLASSLOADER,
PLUGINS
}
private static final Logger log = LoggerFactory.getLogger(Plugins.class);
private final DelegatingClassLoader delegatingLoader;
private final PluginScanResult scanResult;
public Plugins(Map<String, String> props) {
this(props, Plugins.class.getClassLoader(), new ClassLoaderFactory());
}
// VisibleForTesting
@SuppressWarnings("this-escape")
Plugins(Map<String, String> props, ClassLoader parent, ClassLoaderFactory factory) {
String pluginPath = WorkerConfig.pluginPath(props);
PluginDiscoveryMode discoveryMode = WorkerConfig.pluginDiscovery(props);
Set<Path> pluginLocations = PluginUtils.pluginLocations(pluginPath, false);
delegatingLoader = factory.newDelegatingClassLoader(parent);
Set<PluginSource> pluginSources = PluginUtils.pluginSources(pluginLocations, delegatingLoader, factory);
scanResult = initLoaders(pluginSources, discoveryMode);
}
public PluginScanResult initLoaders(Set<PluginSource> pluginSources, PluginDiscoveryMode discoveryMode) {
PluginScanResult empty = new PluginScanResult(List.of());
PluginScanResult serviceLoadingScanResult;
try {
serviceLoadingScanResult = discoveryMode.serviceLoad() ?
new ServiceLoaderScanner().discoverPlugins(pluginSources) : empty;
} catch (Throwable t) {
throw new ConnectException(String.format(
"Unable to perform ServiceLoader scanning as requested by %s=%s. It may be possible to fix this issue by reconfiguring %s=%s",
WorkerConfig.PLUGIN_DISCOVERY_CONFIG, discoveryMode,
WorkerConfig.PLUGIN_DISCOVERY_CONFIG, PluginDiscoveryMode.ONLY_SCAN), t);
}
PluginScanResult reflectiveScanResult = discoveryMode.reflectivelyScan() ?
new ReflectionScanner().discoverPlugins(pluginSources) : empty;
PluginScanResult scanResult = new PluginScanResult(List.of(reflectiveScanResult, serviceLoadingScanResult));
maybeReportHybridDiscoveryIssue(discoveryMode, serviceLoadingScanResult, scanResult);
delegatingLoader.installDiscoveredPlugins(scanResult);
return scanResult;
}
// visible for testing
static void maybeReportHybridDiscoveryIssue(PluginDiscoveryMode discoveryMode, PluginScanResult serviceLoadingScanResult, PluginScanResult mergedResult) {
SortedSet<PluginDesc<?>> missingPlugins = new TreeSet<>();
mergedResult.forEach(missingPlugins::add);
serviceLoadingScanResult.forEach(missingPlugins::remove);
if (missingPlugins.isEmpty()) {
if (discoveryMode == PluginDiscoveryMode.HYBRID_WARN || discoveryMode == PluginDiscoveryMode.HYBRID_FAIL) {
log.warn("All plugins have ServiceLoader manifests, consider reconfiguring {}={}",
WorkerConfig.PLUGIN_DISCOVERY_CONFIG, PluginDiscoveryMode.SERVICE_LOAD);
}
} else {
String message = String.format(
"One or more plugins are missing ServiceLoader manifests may not be usable with %s=%s: %s%n" +
"Read the documentation at %s for instructions on migrating your plugins " +
"to take advantage of the performance improvements of %s mode.",
WorkerConfig.PLUGIN_DISCOVERY_CONFIG,
PluginDiscoveryMode.SERVICE_LOAD,
missingPlugins.stream()
.map(pluginDesc -> pluginDesc.location() + "\t" + pluginDesc.className() + "\t" + pluginDesc.type() + "\t" + pluginDesc.version())
.collect(Collectors.joining("\n", "[\n", "\n]")),
"https://kafka.apache.org/documentation.html#connect_plugindiscovery",
PluginDiscoveryMode.SERVICE_LOAD
);
if (discoveryMode == PluginDiscoveryMode.HYBRID_WARN) {
log.warn("{} To silence this warning, set {}={} in the worker config.",
message, WorkerConfig.PLUGIN_DISCOVERY_CONFIG, PluginDiscoveryMode.ONLY_SCAN);
} else if (discoveryMode == PluginDiscoveryMode.HYBRID_FAIL) {
throw new ConnectException(String.format("%s To silence this error, set %s=%s in the worker config.",
message, WorkerConfig.PLUGIN_DISCOVERY_CONFIG, PluginDiscoveryMode.HYBRID_WARN));
}
}
}
private static <T> String pluginNames(Collection<PluginDesc<T>> plugins) {
return plugins.stream().map(PluginDesc::toString).collect(Collectors.joining(", "));
}
private <T> T newPlugin(Class<T> klass) {
// KAFKA-8340: The thread classloader is used during static initialization and must be
// set to the plugin's classloader during instantiation
try (LoaderSwap loaderSwap = withClassLoader(klass.getClassLoader())) {
return Utils.newInstance(klass);
} catch (Throwable t) {
throw new ConnectException("Instantiation error", t);
}
}
@SuppressWarnings("unchecked")
protected <U> Class<? extends U> pluginClassFromConfig(
AbstractConfig config,
String propertyName,
Class<U> pluginClass,
Collection<PluginDesc<U>> plugins
) {
Class<?> klass = config.getClass(propertyName);
if (pluginClass.isAssignableFrom(klass)) {
return (Class<? extends U>) klass;
}
throw new ConnectException(
"Failed to find any
|
ClassLoaderUsage
|
java
|
elastic__elasticsearch
|
x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java
|
{
"start": 31471,
"end": 33169
}
|
class ____ implements ServiceDisruptionScheme {
private InternalTestCluster cluster;
private boolean frozen;
@Override
public void applyToCluster(InternalTestCluster cluster) {
this.cluster = cluster;
}
@Override
public void removeFromCluster(InternalTestCluster cluster) {
stopDisrupting();
}
@Override
public void removeAndEnsureHealthy(InternalTestCluster cluster) {
stopDisrupting();
}
@Override
public synchronized void applyToNode(String node, InternalTestCluster cluster) {
if (frozen) {
((ClockMock) cluster.getInstance(ClockHolder.class, node).clock).freeze();
}
}
@Override
public void removeFromNode(String node, InternalTestCluster cluster) {
((ClockMock) cluster.getInstance(ClockHolder.class, node).clock).unfreeze();
}
@Override
public synchronized void startDisrupting() {
frozen = true;
for (String node : cluster.getNodeNames()) {
applyToNode(node, cluster);
}
}
@Override
public void stopDisrupting() {
frozen = false;
for (String node : cluster.getNodeNames()) {
removeFromNode(node, cluster);
}
}
@Override
public void testClusterClosed() {}
@Override
public TimeValue expectedTimeToHeal() {
return TimeValue.ZERO;
}
@Override
public String toString() {
return "time frozen";
}
}
}
|
TimeFreezeDisruption
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2236/Issue2236Test.java
|
{
"start": 555,
"end": 1655
}
|
class ____ {
@ProcessorTest
public void shouldCorrectlyMapSameTypesWithDifferentNestedMappings() {
Vehicle vehicle = new Vehicle();
vehicle.setType( "Sedan" );
CarDto carDto = new CarDto();
vehicle.setCarDto( carDto );
carDto.setName( "Private car" );
carDto.setOwnerNameA( "Owner A" );
carDto.setOwnerCityA( "Zurich" );
carDto.setOwnerNameB( "Owner B" );
carDto.setOwnerCityB( "Bern" );
Car car = CarMapper.INSTANCE.vehicleToCar( vehicle );
assertThat( car ).isNotNull();
assertThat( car.getType() ).isEqualTo( "Sedan" );
assertThat( car.getName() ).isEqualTo( "Private car" );
assertThat( car.getOwnerA() ).isNotNull();
assertThat( car.getOwnerA().getName() ).isEqualTo( "Owner A" );
assertThat( car.getOwnerA().getCity() ).isEqualTo( "Zurich" );
assertThat( car.getOwnerB() ).isNotNull();
assertThat( car.getOwnerB().getName() ).isEqualTo( "Owner B" );
assertThat( car.getOwnerB().getCity() ).isEqualTo( "Bern" );
}
}
|
Issue2236Test
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/MockUserServiceBeanPostProcessor.java
|
{
"start": 929,
"end": 1435
}
|
class ____ implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof PostProcessedMockUserDetailsService) {
((PostProcessedMockUserDetailsService) bean).setPostProcessorWasHere("Hello from the post processor!");
}
return bean;
}
}
|
MockUserServiceBeanPostProcessor
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/test/TestSslUtils.java
|
{
"start": 30176,
"end": 37332
}
|
class ____ {
final ConnectionMode connectionMode;
String tlsProtocol;
boolean useClientCert;
boolean createTrustStore;
File trustStoreFile;
Password trustStorePassword;
Password keyStorePassword;
Password keyPassword;
String certAlias;
String cn;
String algorithm;
CertificateBuilder certBuilder;
boolean usePem;
public SslConfigsBuilder(ConnectionMode connectionMode) {
this.connectionMode = connectionMode;
this.tlsProtocol = DEFAULT_TLS_PROTOCOL_FOR_TESTS;
trustStorePassword = new Password(TRUST_STORE_PASSWORD);
keyStorePassword = connectionMode == ConnectionMode.SERVER ? new Password("ServerPassword") : new Password("ClientPassword");
keyPassword = keyStorePassword;
this.certBuilder = new CertificateBuilder();
this.cn = "localhost";
this.certAlias = connectionMode.name().toLowerCase(Locale.ROOT);
this.algorithm = "RSA";
this.createTrustStore = true;
}
public SslConfigsBuilder tlsProtocol(String tlsProtocol) {
this.tlsProtocol = tlsProtocol;
return this;
}
public SslConfigsBuilder createNewTrustStore(File trustStoreFile) {
this.trustStoreFile = trustStoreFile;
this.createTrustStore = true;
return this;
}
public SslConfigsBuilder useExistingTrustStore(File trustStoreFile) {
this.trustStoreFile = trustStoreFile;
this.createTrustStore = false;
return this;
}
public SslConfigsBuilder useClientCert(boolean useClientCert) {
this.useClientCert = useClientCert;
return this;
}
public SslConfigsBuilder certAlias(String certAlias) {
this.certAlias = certAlias;
return this;
}
public SslConfigsBuilder cn(String cn) {
this.cn = cn;
return this;
}
public SslConfigsBuilder algorithm(String algorithm) {
this.algorithm = algorithm;
return this;
}
public SslConfigsBuilder certBuilder(CertificateBuilder certBuilder) {
this.certBuilder = certBuilder;
return this;
}
public SslConfigsBuilder usePem(boolean usePem) {
this.usePem = usePem;
return this;
}
public Map<String, Object> build() throws IOException, GeneralSecurityException {
if (usePem) {
return buildPem();
} else
return buildJks();
}
private Map<String, Object> buildJks() throws IOException, GeneralSecurityException {
Map<String, X509Certificate> certs = new HashMap<>();
File keyStoreFile = null;
if (connectionMode == ConnectionMode.CLIENT && useClientCert) {
keyStoreFile = TestUtils.tempFile("clientKS", ".jks");
KeyPair cKP = generateKeyPair(algorithm);
X509Certificate cCert = certBuilder.generate("CN=" + cn + ", O=A client", cKP);
createKeyStore(keyStoreFile.getPath(), keyStorePassword, keyPassword, "client", cKP.getPrivate(), cCert);
certs.put(certAlias, cCert);
} else if (connectionMode == ConnectionMode.SERVER) {
keyStoreFile = TestUtils.tempFile("serverKS", ".jks");
KeyPair sKP = generateKeyPair(algorithm);
X509Certificate sCert = certBuilder.generate("CN=" + cn + ", O=A server", sKP);
createKeyStore(keyStoreFile.getPath(), keyStorePassword, keyPassword, "server", sKP.getPrivate(), sCert);
certs.put(certAlias, sCert);
keyStoreFile.deleteOnExit();
}
if (createTrustStore) {
createTrustStore(trustStoreFile.getPath(), trustStorePassword, certs);
trustStoreFile.deleteOnExit();
}
Map<String, Object> sslConfigs = new HashMap<>();
sslConfigs.put(SslConfigs.SSL_PROTOCOL_CONFIG, tlsProtocol); // protocol to create SSLContext
if (connectionMode == ConnectionMode.SERVER || (connectionMode == ConnectionMode.CLIENT && keyStoreFile != null)) {
sslConfigs.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, keyStoreFile.getPath());
sslConfigs.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "JKS");
sslConfigs.put(SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, TrustManagerFactory.getDefaultAlgorithm());
sslConfigs.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, keyStorePassword);
sslConfigs.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, keyPassword);
}
sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, trustStoreFile.getPath());
sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, trustStorePassword);
sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "JKS");
sslConfigs.put(SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, TrustManagerFactory.getDefaultAlgorithm());
sslConfigs.put(SslConfigs.SSL_CIPHER_SUITES_CONFIG, List.of());
List<String> enabledProtocols = new ArrayList<>();
enabledProtocols.add(tlsProtocol);
sslConfigs.put(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, enabledProtocols);
return sslConfigs;
}
private Map<String, Object> buildPem() throws IOException, GeneralSecurityException {
if (!createTrustStore) {
throw new IllegalArgumentException("PEM configs cannot be created with existing trust stores");
}
Map<String, Object> sslConfigs = new HashMap<>();
sslConfigs.put(SslConfigs.SSL_PROTOCOL_CONFIG, tlsProtocol);
sslConfigs.put(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, List.of(tlsProtocol));
sslConfigs.put(SslConfigs.SSL_CIPHER_SUITES_CONFIG, List.of());
if (connectionMode != ConnectionMode.CLIENT || useClientCert) {
KeyPair keyPair = generateKeyPair(algorithm);
X509Certificate cert = certBuilder.generate("CN=" + cn + ", O=A " + connectionMode.name().toLowerCase(Locale.ROOT), keyPair);
Password privateKeyPem = new Password(pem(keyPair.getPrivate(), keyPassword));
Password certPem = new Password(pem(cert));
sslConfigs.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, PEM_TYPE);
sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, PEM_TYPE);
sslConfigs.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, privateKeyPem);
sslConfigs.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, certPem);
sslConfigs.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, keyPassword);
sslConfigs.put(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, certPem);
}
return sslConfigs;
}
}
public static final
|
SslConfigsBuilder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/rest/action/RestUpdateTransformAction.java
|
{
"start": 1218,
"end": 2629
}
|
class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, TransformField.REST_BASE_PATH_TRANSFORMS_BY_ID + "_update"));
}
@Override
public String getName() {
return "transform_update_transform_action";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
if (restRequest.contentLength() > MAX_REQUEST_SIZE.getBytes()) {
throw ExceptionsHelper.badRequestException(
"Request is too large: was [{}b], expected at most [{}]",
restRequest.contentLength(),
MAX_REQUEST_SIZE
);
}
String id = restRequest.param(TransformField.ID.getPreferredName());
boolean deferValidation = restRequest.paramAsBoolean(TransformField.DEFER_VALIDATION.getPreferredName(), false);
TimeValue timeout = restRequest.paramAsTime(TransformField.TIMEOUT.getPreferredName(), AcknowledgedRequest.DEFAULT_ACK_TIMEOUT);
XContentParser parser = restRequest.contentParser();
UpdateTransformAction.Request request = UpdateTransformAction.Request.fromXContent(parser, id, deferValidation, timeout);
return channel -> client.execute(UpdateTransformAction.INSTANCE, request, new RestToXContentListener<>(channel));
}
}
|
RestUpdateTransformAction
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/test/compiler/InMemoryJavaCompiler.java
|
{
"start": 4601,
"end": 5516
}
|
class ____
*/
public static Map<String, byte[]> compile(Map<String, CharSequence> sources, String... options) {
var files = sources.entrySet().stream().map(e -> new InMemoryJavaFileObject(e.getKey(), e.getValue())).toList();
try (FileManagerWrapper wrapper = new FileManagerWrapper(files)) {
CompilationTask task = getCompilationTask(wrapper, options);
boolean result = task.call();
if (result == false) {
throw new RuntimeException("Could not compile " + sources.entrySet().stream().toList());
}
} catch (IOException e) {
throw new RuntimeException("Could not close file manager for " + sources.entrySet().stream().toList());
}
return files.stream().collect(Collectors.toMap(InMemoryJavaFileObject::getClassName, InMemoryJavaFileObject::getByteCode));
}
/**
* Compiles the
|
name
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/AntlrMySqlTest.java
|
{
"start": 471,
"end": 2356
}
|
class ____ extends TestCase {
public void test_for_antlr_examples() throws Exception {
SchemaStatVisitor schemaStatVisitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL);
WallConfig config = new WallConfig();
config.setConditionDoubleConstAllow(true);
config.setConditionAndAlwayTrueAllow(true);
config.setSelectIntoOutfileAllow(true);
config.setSelectWhereAlwayTrueCheck(false); //FIXME 此处是否要禁用审核h
config.setSelectUnionCheck(false); //FIXME 此处是否要禁用审核
config.setCommentAllow(true);
config.setHintAllow(true);
MySqlWallProvider provider = new MySqlWallProvider(config);
String path = "bvt/parser/antlr_grammers_v4_mysql/examples/";
URL resource = Thread.currentThread().getContextClassLoader().getResource(path);
File dir = new File(resource.getFile());
for (File file : dir.listFiles()) {
System.out.println(file);
String sql = FileUtils.readFileToString(file);
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
for (SQLStatement stmt : stmtList) {
String stmtSql = stmt.toString();
stmt.accept(schemaStatVisitor);
assertTrue(stmtSql, provider.checkValid(stmtSql));
}
// test different style newline.
if (sql.indexOf("\r\n") == -1) {
sql = sql.replace("\n", "\r\n");
} else {
sql = sql.replace("\r\n", "\n");
}
stmtList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
for (SQLStatement stmt : stmtList) {
String stmtSql = stmt.toString();
stmt.accept(schemaStatVisitor);
assertTrue(provider.checkValid(stmtSql));
}
}
}
}
|
AntlrMySqlTest
|
java
|
quarkusio__quarkus
|
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithServiceAccountTest.java
|
{
"start": 594,
"end": 2652
}
|
class ____ {
private static final String APP_NAME = "kubernetes-with-service-account";
private static final String SERVICE_ACCOUNT = "my-service-account";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
.setApplicationName(APP_NAME)
.setApplicationVersion("0.1-SNAPSHOT")
.overrideConfigKey("quarkus.kubernetes.service-account", SERVICE_ACCOUNT);
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
public void assertGeneratedResources() throws IOException {
final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
List<HasMetadata> kubernetesList = DeserializationUtil
.deserializeAsList(kubernetesDir.resolve("kubernetes.yml"));
Deployment deployment = getDeploymentByName(kubernetesList, APP_NAME).get();
assertThat(deployment.getSpec().getTemplate().getSpec().getServiceAccountName()).isEqualTo(SERVICE_ACCOUNT);
Optional<ServiceAccount> serviceAccount = getServiceAccountByName(kubernetesList, SERVICE_ACCOUNT);
assertThat(serviceAccount.isPresent()).isFalse();
}
private Optional<Deployment> getDeploymentByName(List<HasMetadata> kubernetesList, String name) {
return getResourceByName(kubernetesList, Deployment.class, name);
}
private Optional<ServiceAccount> getServiceAccountByName(List<HasMetadata> kubernetesList, String saName) {
return getResourceByName(kubernetesList, ServiceAccount.class, saName);
}
private <T extends HasMetadata> Optional<T> getResourceByName(List<HasMetadata> kubernetesList, Class<T> clazz,
String name) {
return kubernetesList.stream()
.filter(r -> r.getMetadata().getName().equals(name))
.filter(clazz::isInstance)
.map(clazz::cast)
.findFirst();
}
}
|
KubernetesWithServiceAccountTest
|
java
|
spring-projects__spring-security
|
config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java
|
{
"start": 8912,
"end": 9795
}
|
class ____ {
private List<String> payloads = new ArrayList<>();
@MessageMapping({ "secure.retrieve-mono", "retrieve-mono" })
String retrieveMono(String payload) {
add(payload);
return "Hi " + payload;
}
@MessageMapping({ "secure.retrieve-flux", "retrieve-flux" })
Flux<String> retrieveFlux(Flux<String> payload) {
return payload.doOnNext(this::add).map((p) -> "hello " + p);
}
@MessageMapping({ "secure.send", "send" })
Mono<Void> send(Mono<String> payload) {
return payload.doOnNext(this::add).then(Mono.fromRunnable(this::doNotifyAll));
}
private synchronized void doNotifyAll() {
this.notifyAll();
}
private synchronized List<String> awaitPayloads() throws InterruptedException {
this.wait(TimeUnit.SECONDS.toMillis(1));
return this.payloads;
}
private void add(String p) {
this.payloads.add(p);
}
}
}
|
ServerController
|
java
|
apache__spark
|
sql/hive-thriftserver/src/main/java/org/apache/hive/service/server/ThreadWithGarbageCleanup.java
|
{
"start": 1261,
"end": 2808
}
|
class ____ extends Thread {
private static final SparkLogger LOG = SparkLoggerFactory.getLogger(ThreadWithGarbageCleanup.class);
Map<Long, RawStore> threadRawStoreMap =
ThreadFactoryWithGarbageCleanup.getThreadRawStoreMap();
public ThreadWithGarbageCleanup(Runnable runnable) {
super(runnable);
}
/**
* Add any Thread specific garbage cleanup code here.
* Currently, it shuts down the RawStore object for this thread if it is not null.
*/
@Override
public void finalize() throws Throwable {
cleanRawStore();
super.finalize();
}
private void cleanRawStore() {
Long threadId = this.getId();
RawStore threadLocalRawStore = threadRawStoreMap.get(threadId);
if (threadLocalRawStore != null) {
LOG.debug("RawStore: " + threadLocalRawStore + ", for the thread: " +
this.getName() + " will be closed now.");
threadLocalRawStore.shutdown();
threadRawStoreMap.remove(threadId);
}
}
/**
* Cache the ThreadLocal RawStore object. Called from the corresponding thread.
*/
public void cacheThreadLocalRawStore() {
Long threadId = this.getId();
RawStore threadLocalRawStore = HiveMetaStore.HMSHandler.getRawStore();
if (threadLocalRawStore != null && !threadRawStoreMap.containsKey(threadId)) {
LOG.debug("Adding RawStore: " + threadLocalRawStore + ", for the thread: " +
this.getName() + " to threadRawStoreMap for future cleanup.");
threadRawStoreMap.put(threadId, threadLocalRawStore);
}
}
}
|
ThreadWithGarbageCleanup
|
java
|
apache__spark
|
sql/api/src/main/java/org/apache/spark/sql/api/java/UDF20.java
|
{
"start": 981,
"end": 1305
}
|
interface ____<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, R> extends Serializable {
R call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19, T20 t20) throws Exception;
}
|
UDF20
|
java
|
apache__avro
|
lang/java/avro/src/main/java/org/apache/avro/SchemaBuilder.java
|
{
"start": 55653,
"end": 65377
}
|
class ____<R> {
private final List<Field> fields = new ArrayList<>();
private final Completion<R> context;
private final NameContext names;
private final Schema record;
private FieldAssembler(Completion<R> context, NameContext names, Schema record) {
this.context = context;
this.names = names;
this.record = record;
}
/**
* Add a field with the given name.
*
* @return A {@link FieldBuilder} for the given name.
*/
public FieldBuilder<R> name(String fieldName) {
return new FieldBuilder<>(this, names, fieldName);
}
/**
* Shortcut for creating a boolean field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().booleanType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredBoolean(String fieldName) {
return name(fieldName).type().booleanType().noDefault();
}
/**
* Shortcut for creating an optional boolean field: a union of null and boolean
* with null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().booleanType()
* </pre>
*/
public FieldAssembler<R> optionalBoolean(String fieldName) {
return name(fieldName).type().optional().booleanType();
}
/**
* Shortcut for creating a nullable boolean field: a union of boolean and null
* with an boolean default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().booleanType().booleanDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableBoolean(String fieldName, boolean defaultVal) {
return name(fieldName).type().nullable().booleanType().booleanDefault(defaultVal);
}
/**
* Shortcut for creating an int field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().intType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredInt(String fieldName) {
return name(fieldName).type().intType().noDefault();
}
/**
* Shortcut for creating an optional int field: a union of null and int with
* null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().intType()
* </pre>
*/
public FieldAssembler<R> optionalInt(String fieldName) {
return name(fieldName).type().optional().intType();
}
/**
* Shortcut for creating a nullable int field: a union of int and null with an
* int default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().intType().intDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableInt(String fieldName, int defaultVal) {
return name(fieldName).type().nullable().intType().intDefault(defaultVal);
}
/**
* Shortcut for creating a long field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().longType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredLong(String fieldName) {
return name(fieldName).type().longType().noDefault();
}
/**
* Shortcut for creating an optional long field: a union of null and long with
* null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().longType()
* </pre>
*/
public FieldAssembler<R> optionalLong(String fieldName) {
return name(fieldName).type().optional().longType();
}
/**
* Shortcut for creating a nullable long field: a union of long and null with a
* long default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().longType().longDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableLong(String fieldName, long defaultVal) {
return name(fieldName).type().nullable().longType().longDefault(defaultVal);
}
/**
* Shortcut for creating a float field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().floatType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredFloat(String fieldName) {
return name(fieldName).type().floatType().noDefault();
}
/**
* Shortcut for creating an optional float field: a union of null and float with
* null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().floatType()
* </pre>
*/
public FieldAssembler<R> optionalFloat(String fieldName) {
return name(fieldName).type().optional().floatType();
}
/**
* Shortcut for creating a nullable float field: a union of float and null with
* a float default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().floatType().floatDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableFloat(String fieldName, float defaultVal) {
return name(fieldName).type().nullable().floatType().floatDefault(defaultVal);
}
/**
* Shortcut for creating a double field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().doubleType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredDouble(String fieldName) {
return name(fieldName).type().doubleType().noDefault();
}
/**
* Shortcut for creating an optional double field: a union of null and double
* with null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().doubleType()
* </pre>
*/
public FieldAssembler<R> optionalDouble(String fieldName) {
return name(fieldName).type().optional().doubleType();
}
/**
* Shortcut for creating a nullable double field: a union of double and null
* with a double default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().doubleType().doubleDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableDouble(String fieldName, double defaultVal) {
return name(fieldName).type().nullable().doubleType().doubleDefault(defaultVal);
}
/**
* Shortcut for creating a string field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().stringType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredString(String fieldName) {
return name(fieldName).type().stringType().noDefault();
}
/**
* Shortcut for creating an optional string field: a union of null and string
* with null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().stringType()
* </pre>
*/
public FieldAssembler<R> optionalString(String fieldName) {
return name(fieldName).type().optional().stringType();
}
/**
* Shortcut for creating a nullable string field: a union of string and null
* with a string default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().stringType().stringDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableString(String fieldName, String defaultVal) {
return name(fieldName).type().nullable().stringType().stringDefault(defaultVal);
}
/**
* Shortcut for creating a bytes field with the given name and no default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().bytesType().noDefault()
* </pre>
*/
public FieldAssembler<R> requiredBytes(String fieldName) {
return name(fieldName).type().bytesType().noDefault();
}
/**
* Shortcut for creating an optional bytes field: a union of null and bytes with
* null default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().optional().bytesType()
* </pre>
*/
public FieldAssembler<R> optionalBytes(String fieldName) {
return name(fieldName).type().optional().bytesType();
}
/**
* Shortcut for creating a nullable bytes field: a union of bytes and null with
* a bytes default.
* <p/>
* This is equivalent to:
*
* <pre>
* name(fieldName).type().nullable().bytesType().bytesDefault(defaultVal)
* </pre>
*/
public FieldAssembler<R> nullableBytes(String fieldName, byte[] defaultVal) {
return name(fieldName).type().nullable().bytesType().bytesDefault(defaultVal);
}
/**
* End adding fields to this record, returning control to the context that this
* record builder was created in.
*/
public R endRecord() {
record.setFields(fields);
return context.complete(record);
}
private FieldAssembler<R> addField(Field field) {
fields.add(field);
return this;
}
}
/**
* Builds a Field in the context of a {@link FieldAssembler}.
*
* Usage is to first configure any of the optional parameters and then to call
* one of the type methods to complete the field. For example
*
* <pre>
* .namespace("org.apache.example").orderDescending().type()
* </pre>
*
* Optional parameters for a field are namespace, doc, order, and aliases.
*/
public final static
|
FieldAssembler
|
java
|
apache__camel
|
core/camel-xml-jaxp/src/main/java/org/apache/camel/support/processor/validation/DefaultValidationErrorHandler.java
|
{
"start": 1307,
"end": 3059
}
|
class ____ implements ValidatorErrorHandler {
private static final Logger LOG = LoggerFactory.getLogger(DefaultValidationErrorHandler.class);
private final List<SAXParseException> warnings = new ArrayList<>();
private final List<SAXParseException> errors = new ArrayList<>();
private final List<SAXParseException> fatalErrors = new ArrayList<>();
@Override
public void warning(SAXParseException e) throws SAXException {
if (LOG.isDebugEnabled()) {
LOG.debug("Validation warning: {}", e, e);
}
warnings.add(e);
}
@Override
public void error(SAXParseException e) throws SAXException {
if (LOG.isDebugEnabled()) {
LOG.debug("Validation error: {}", e, e);
}
errors.add(e);
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
if (LOG.isDebugEnabled()) {
LOG.debug("Validation fatalError: {}", e, e);
}
fatalErrors.add(e);
}
@Override
public void reset() {
warnings.clear();
errors.clear();
fatalErrors.clear();
}
public boolean isValid() {
return errors.isEmpty() && fatalErrors.isEmpty();
}
@Override
public void handleErrors(Exchange exchange, Schema schema, Result result) throws ValidationException {
if (!isValid()) {
throw new SchemaValidationException(exchange, schema, fatalErrors, errors, warnings);
}
}
public void handleErrors(Exchange exchange, Object schema) throws ValidationException {
if (!isValid()) {
throw new SchemaValidationException(exchange, schema, fatalErrors, errors, warnings);
}
}
}
|
DefaultValidationErrorHandler
|
java
|
apache__camel
|
components/camel-joor/src/main/java/org/apache/camel/language/joor/JoorCompiler.java
|
{
"start": 1488,
"end": 6209
}
|
class ____ extends ServiceSupport implements StaticService {
private static final Pattern BEAN_INJECTION_PATTERN = Pattern.compile("(#bean:)([A-Za-z0-9-_]*)");
private static final Pattern BODY_AS_PATTERN = Pattern.compile("(optionalBodyAs|bodyAs)\\(([A-Za-z0-9.$]*)(.class)\\)");
private static final Pattern BODY_AS_PATTERN_NO_CLASS = Pattern.compile("(optionalBodyAs|bodyAs)\\(([A-Za-z0-9.$]*)\\)");
private static final Pattern HEADER_AS_PATTERN
= Pattern.compile("(optionalHeaderAs|headerAs)\\((['|\"][A-Za-z0-9.$]*['|\"]\\s*),\\s*([A-Za-z0-9.$]*.class)\\)");
private static final Pattern HEADER_AS_PATTERN_NO_CLASS
= Pattern.compile("(optionalHeaderAs|headerAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,\\s*([A-Za-z0-9.$]*)\\)");
private static final Pattern HEADER_AS_DEFAULT_VALUE_PATTERN
= Pattern.compile("(headerAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,(.+),\\s*([A-Za-z0-9.$]*.class)\\)");
private static final Pattern HEADER_AS_DEFAULT_VALUE_PATTERN_NO_CLASS
= Pattern.compile("(headerAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,(.+),\\s*([A-Za-z0-9.$]*)\\)");
private static final Pattern EXCHANGE_PROPERTY_AS_PATTERN
= Pattern.compile(
"(optionalExchangePropertyAs|exchangePropertyAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,\\s*([A-Za-z0-9.$]*.class)\\)");
private static final Pattern EXCHANGE_PROPERTY_AS_PATTERN_NO_CLASS
= Pattern.compile(
"(optionalExchangePropertyAs|exchangePropertyAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,\\s*([A-Za-z0-9.$]*)\\)");
private static final Pattern EXCHANGE_PROPERTY_AS_DEFAULT_VALUE_PATTERN
= Pattern.compile(
"(exchangePropertyAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,(.+),\\s*([A-Za-z0-9.$]*.class)\\)");
private static final Pattern EXCHANGE_PROPERTY_AS_DEFAULT_VALUE_PATTERN_NO_CLASS
= Pattern.compile(
"(exchangePropertyAs)\\((['|\"][A-Za-z0-9.$]*['|\"])\\s*,(.+),\\s*([A-Za-z0-9.$]*)\\)");
private static final Logger LOG = LoggerFactory.getLogger(JoorCompiler.class);
private static final AtomicInteger UUID = new AtomicInteger();
private Set<String> imports = new TreeSet<>();
private Map<String, String> aliases;
private int counter;
private long taken;
public Set<String> getImports() {
return imports;
}
public void setImports(Set<String> imports) {
this.imports = imports;
}
public Map<String, String> getAliases() {
return aliases;
}
public void setAliases(Map<String, String> aliases) {
this.aliases = aliases;
}
@Override
protected void doStop() throws Exception {
super.doStop();
if (counter > 0) {
LOG.debug("Java compiled {} {} in {}", counter, counter == 1 ? "script" : "scripts",
TimeUtils.printDuration(taken, true));
}
}
public JoorMethod compile(CamelContext camelContext, String script, boolean singleQuotes) {
StopWatch watch = new StopWatch();
JoorMethod answer;
String className = nextFQN();
String code = evalCode(camelContext, className, script, singleQuotes);
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Compiling code:\n\n{}\n", code);
}
LOG.debug("Compiling: {}", className);
Reflect ref = Reflect.compile(className, code);
Class<?> clazz = ref.type();
LOG.debug("Compiled to Java class: {}", clazz);
answer = (JoorMethod) clazz.getConstructor(CamelContext.class).newInstance(camelContext);
} catch (Exception e) {
throw new JoorCompilationException(className, code, e);
}
counter++;
taken += watch.taken();
return answer;
}
public String evalCode(CamelContext camelContext, String fqn, String script, boolean singleQuotes) {
String qn = fqn.substring(0, fqn.lastIndexOf('.'));
String name = fqn.substring(fqn.lastIndexOf('.') + 1);
// reload script
script = ScriptHelper.resolveOptionalExternalScript(camelContext, script);
// trim text
script = script.trim();
// special for evaluating aggregation strategy via a BiFunction
boolean biFunction = script.startsWith("(e1, e2) ->");
script = staticHelper(script);
script = alias(script);
Set<String> scriptImports = new LinkedHashSet<>();
Map<String, Class> scriptBeans = new HashMap<>();
script = evalDependencyInjection(camelContext, scriptImports, scriptBeans, script);
// wrap text into a
|
JoorCompiler
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/metamodel/internal/EmbeddableInstantiatorDynamicMap.java
|
{
"start": 462,
"end": 1242
}
|
class ____
extends AbstractDynamicMapInstantiator
implements StandardEmbeddableInstantiator {
private final Supplier<EmbeddableMappingType> runtimeDescriptorAccess;
public EmbeddableInstantiatorDynamicMap(
Component bootDescriptor,
Supplier<EmbeddableMappingType> runtimeDescriptorAccess) {
super( bootDescriptor.getRoleName() );
this.runtimeDescriptorAccess = runtimeDescriptorAccess;
}
@Override
public Object instantiate(ValueAccess valuesAccess) {
final Map<?,?> dataMap = generateDataMap();
final var values = valuesAccess == null ? null : valuesAccess.getValues();
if ( values != null ) {
final var mappingType = runtimeDescriptorAccess.get();
mappingType.setValues( dataMap, values );
}
return dataMap;
}
}
|
EmbeddableInstantiatorDynamicMap
|
java
|
apache__maven
|
compat/maven-model-builder/src/main/java/org/apache/maven/model/management/DefaultPluginManagementInjector.java
|
{
"start": 2120,
"end": 4637
}
|
class ____ extends MavenModelMerger {
public void mergeManagedBuildPlugins(Model model) {
Build build = model.getBuild();
if (build != null) {
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
mergePluginContainerPlugins(build, pluginManagement);
}
}
}
private void mergePluginContainerPlugins(PluginContainer target, PluginContainer source) {
List<Plugin> src = source.getPlugins();
if (!src.isEmpty()) {
List<Plugin> tgt = target.getPlugins();
Map<Object, Plugin> managedPlugins = new LinkedHashMap<>(src.size() * 2);
Map<Object, Object> context = Collections.emptyMap();
for (Plugin element : src) {
Object key = getPluginKey(element);
managedPlugins.put(key, element);
}
for (Plugin element : tgt) {
Object key = getPluginKey(element);
Plugin managedPlugin = managedPlugins.get(key);
if (managedPlugin != null) {
mergePlugin(element, managedPlugin, false, context);
}
}
}
}
@Override
protected void mergePlugin_Executions(
Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context) {
List<PluginExecution> src = source.getExecutions();
if (!src.isEmpty()) {
List<PluginExecution> tgt = target.getExecutions();
Map<Object, PluginExecution> merged = new LinkedHashMap<>((src.size() + tgt.size()) * 2);
for (PluginExecution element : src) {
Object key = getPluginExecutionKey(element);
merged.put(key, element.clone());
}
for (PluginExecution element : tgt) {
Object key = getPluginExecutionKey(element);
PluginExecution existing = merged.get(key);
if (existing != null) {
mergePluginExecution(element, existing, sourceDominant, context);
}
merged.put(key, element);
}
target.setExecutions(new ArrayList<>(merged.values()));
}
}
}
}
|
ManagementModelMerger
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java
|
{
"start": 45177,
"end": 48808
}
|
class ____ of this persister
if ( innerJoinOptimization && tablesToInnerJoin.isEmpty() ) {
final var subclassTableNames = getSubclassTableNames();
for ( int i = 0; i < subclassTableNames.length; i++ ) {
if ( isClassOrSuperclassTable[i] ) {
tablesToInnerJoin.add( subclassTableNames[i] );
}
}
}
final var tableReferenceJoins = tableGroup.getTableReferenceJoins();
if ( needsTreatDiscriminator ) {
if ( tableReferenceJoins.isEmpty() ) {
// We need to apply the discriminator predicate to the primary table reference itself
final String discriminatorPredicate =
getPrunedDiscriminatorPredicate( entityNameUses, metamodel, "t" );
if ( discriminatorPredicate != null ) {
final var tableReference = (NamedTableReference) tableGroup.getPrimaryTableReference();
tableReference.setPrunedTableExpression( "(select * from " + getRootTableName() + " t where " + discriminatorPredicate + ")" );
}
}
else {
// We have to apply the discriminator condition to the root table reference join
boolean applied = applyDiscriminatorPredicate(
tableReferenceJoins.get( 0 ),
(NamedTableReference) tableGroup.getPrimaryTableReference(),
entityNameUses,
metamodel
);
int i = 0;
for ( ; !applied && i < tableReferenceJoins.size(); i++ ) {
final var join = tableReferenceJoins.get( i );
applied = applyDiscriminatorPredicate( join, join.getJoinedTableReference(), entityNameUses, metamodel );
}
assert applied : "Could not apply treat discriminator predicate to root table join";
if ( i != 0 ) {
// Always retain the root table reference join where the discriminator was applied
retainedTableReferences.add( tableReferenceJoins.get( i - 1 ).getJoinedTableReference() );
}
}
}
if ( !tableReferenceJoins.isEmpty() ) {
// The optimization is to remove all table reference joins that are not contained in the retainedTableReferences
// In addition, we switch from a possible LEFT join, to an INNER join for all tablesToInnerJoin
if ( innerJoinOptimization ) {
final var oldJoins = tableReferenceJoins.toArray( new TableReferenceJoin[0] );
tableReferenceJoins.clear();
for ( var oldJoin : oldJoins ) {
final var joinedTableReference = oldJoin.getJoinedTableReference();
if ( retainedTableReferences.contains( joinedTableReference ) ) {
final var join =
oldJoin.getJoinType() != SqlAstJoinType.INNER
&& tablesToInnerJoin.contains( joinedTableReference.getTableExpression() )
? new TableReferenceJoin( true, joinedTableReference, oldJoin.getPredicate() )
: oldJoin;
tableReferenceJoins.add( join );
}
else {
for ( int i = subclassCoreTableSpan; i < subclassTableNameClosure.length; i++ ) {
if ( joinedTableReference.getTableExpression().equals( subclassTableNameClosure[i] ) ) {
// Retain joins to secondary tables
tableReferenceJoins.add( oldJoin );
break;
}
}
}
}
}
else {
tableReferenceJoins.removeIf( join -> !retainedTableReferences.contains( join.getJoinedTableReference() ) );
}
}
}
private void optimizeInnerJoins(
TableGroup tableGroup,
EntityNameUse.UseKind useKind,
JoinedSubclassEntityPersister persister,
Set<String> tablesToInnerJoin,
Set<TableReference> retainedTableReferences) {
if ( useKind == EntityNameUse.UseKind.TREAT || useKind == EntityNameUse.UseKind.FILTER ) {
final var subclassTableNames = persister.getSubclassTableNames();
// Build the intersection of all tables names that are of the
|
tables
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
|
{
"start": 26394,
"end": 26582
}
|
interface ____ {",
" Object conflict();",
"",
" B.Builder b();",
"",
" @Module(subcomponents = B.class)",
" static
|
A
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/CombineSequenceFileInputFormat.java
|
{
"start": 1376,
"end": 2090
}
|
class ____<K,V>
extends CombineFileInputFormat<K,V> {
@SuppressWarnings({ "rawtypes", "unchecked" })
public RecordReader<K,V> createRecordReader(InputSplit split,
TaskAttemptContext context) throws IOException {
return new CombineFileRecordReader((CombineFileSplit)split, context,
SequenceFileRecordReaderWrapper.class);
}
/**
* A record reader that may be passed to <code>CombineFileRecordReader</code>
* so that it can be used in a <code>CombineFileInputFormat</code>-equivalent
* for <code>SequenceFileInputFormat</code>.
*
* @see CombineFileRecordReader
* @see CombineFileInputFormat
* @see SequenceFileInputFormat
*/
private static
|
CombineSequenceFileInputFormat
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/failures/ContextLoadFailureTests.java
|
{
"start": 1731,
"end": 2789
}
|
class ____ {
@BeforeEach
@AfterEach
void clearFailures() {
TrackingApplicationContextFailureProcessor.loadFailures.clear();
}
@Test
void customBootstrapperAppliesApplicationContextFailureProcessor() {
assertThat(TrackingApplicationContextFailureProcessor.loadFailures).isEmpty();
EngineTestKit.engine("junit-jupiter")
.selectors(selectClass(ExplosiveContextTestCase.class))//
.execute()
.testEvents()
.assertStatistics(stats -> stats.started(1).succeeded(0).failed(1));
assertThat(TrackingApplicationContextFailureProcessor.loadFailures).hasSize(1);
LoadFailure loadFailure = TrackingApplicationContextFailureProcessor.loadFailures.get(0);
assertThat(loadFailure.context()).isExactlyInstanceOf(GenericApplicationContext.class);
assertThat(loadFailure.exception())
.isInstanceOf(BeanCreationException.class)
.cause().isInstanceOf(BeanInstantiationException.class)
.rootCause().isInstanceOf(StackOverflowError.class).hasMessage("Boom!");
}
@FailingTestCase
@SpringJUnitConfig
static
|
ContextLoadFailureTests
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java
|
{
"start": 4157,
"end": 5811
}
|
enum ____ {
/* Custom metadata should be returned as part of API call */
API,
/* Custom metadata should be stored as part of the persistent cluster state */
GATEWAY,
/* Custom metadata should be stored as part of a snapshot */
SNAPSHOT;
public static XContentContext from(ToXContent.Params params) {
return valueOf(params.param(CONTEXT_MODE_PARAM, CONTEXT_MODE_API));
}
}
/**
* Indicates that this custom metadata will be returned as part of an API call but will not be persisted
*/
public static final EnumSet<XContentContext> API_ONLY = EnumSet.of(XContentContext.API);
/**
* Indicates that this custom metadata will be returned as part of an API call and will be persisted between
* node restarts, but will not be a part of a snapshot global state
*/
public static final EnumSet<XContentContext> API_AND_GATEWAY = EnumSet.of(XContentContext.API, XContentContext.GATEWAY);
/**
* Indicates that this custom metadata will be returned as part of an API call and stored as a part of
* a snapshot global state, but will not be persisted between node restarts
*/
public static final EnumSet<XContentContext> API_AND_SNAPSHOT = EnumSet.of(XContentContext.API, XContentContext.SNAPSHOT);
/**
* Indicates that this custom metadata will be returned as part of an API call, stored as a part of
* a snapshot global state, and will be persisted between node restarts
*/
public static final EnumSet<XContentContext> ALL_CONTEXTS = EnumSet.allOf(XContentContext.class);
public
|
XContentContext
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDetachedTest.java
|
{
"start": 2244,
"end": 2705
}
|
class ____ {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
Long id;
String firstName;
String lastName;
@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn
Book book;
@Basic( fetch = FetchType.LAZY )
char[] charArrayCode;
public Author() {
}
public Author(String firstName, String lastName, char[] charArrayCode) {
this.firstName = firstName;
this.lastName = lastName;
this.charArrayCode = charArrayCode;
}
}
}
|
Author
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java
|
{
"start": 1504,
"end": 3892
}
|
class ____ {
@Test
void testPrompt() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.channelRead0(context, "");
verify(context).writeAndFlush(QosProcessHandler.PROMPT);
}
@Test
void testBye() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush("BYE!\n")).thenReturn(future);
handler.channelRead0(context, "quit");
verify(future).addListener(ChannelFutureListener.CLOSE);
}
@Test
void testUnknownCommand() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
handler.channelRead0(context, "unknown");
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(context, Mockito.atLeastOnce()).writeAndFlush(captor.capture());
assertThat(captor.getAllValues(), contains("unknown :no such command", "\r\ndubbo>"));
}
@Test
void testGreeting() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.channelRead0(context, "greeting");
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(context).writeAndFlush(captor.capture());
assertThat(captor.getValue(), containsString("greeting"));
assertThat(captor.getValue(), containsString("dubbo>"));
}
}
|
TelnetProcessHandlerTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/seqno/RetentionLease.java
|
{
"start": 1545,
"end": 8401
}
|
class ____ implements ToXContentObject, Writeable {
private final String id;
/**
* The identifier for this retention lease. This identifier should be unique per lease and is set during construction by the caller.
*
* @return the identifier
*/
public String id() {
return id;
}
private final long retainingSequenceNumber;
/**
* The retaining sequence number of this retention lease. The retaining sequence number is the minimum sequence number that this
* retention lease wants to retain during merge operations. The retaining sequence number is set during construction by the caller.
*
* @return the retaining sequence number
*/
public long retainingSequenceNumber() {
return retainingSequenceNumber;
}
private final long timestamp;
/**
* The timestamp of when this retention lease was created or renewed.
*
* @return the timestamp used as a basis for determining lease expiration
*/
public long timestamp() {
return timestamp;
}
private final String source;
/**
* The source of this retention lease. The source is set during construction by the caller.
*
* @return the source
*/
public String source() {
return source;
}
/**
* Constructs a new retention lease.
*
* @param id the identifier of the retention lease
* @param retainingSequenceNumber the retaining sequence number
* @param timestamp the timestamp of when the retention lease was created or renewed
* @param source the source of the retention lease
*/
public RetentionLease(final String id, final long retainingSequenceNumber, final long timestamp, final String source) {
Objects.requireNonNull(id);
if (id.isEmpty()) {
throw new IllegalArgumentException("retention lease ID can not be empty");
}
if (retainingSequenceNumber < 0) {
throw new IllegalArgumentException("retention lease retaining sequence number [" + retainingSequenceNumber + "] out of range");
}
if (timestamp < 0) {
throw new IllegalArgumentException("retention lease timestamp [" + timestamp + "] out of range");
}
Objects.requireNonNull(source);
if (source.isEmpty()) {
throw new IllegalArgumentException("retention lease source can not be empty");
}
this.id = id;
this.retainingSequenceNumber = retainingSequenceNumber;
this.timestamp = timestamp;
// deduplicate the string instances to save memory for the known possible source values
this.source = switch (source) {
case "ccr" -> "ccr";
case ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE -> ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE;
default -> source;
};
}
/**
* Constructs a new retention lease from a stream. The retention lease should have been written via {@link #writeTo(StreamOutput)}.
*
* @param in the stream to construct the retention lease from
* @throws IOException if an I/O exception occurs reading from the stream
*/
public RetentionLease(final StreamInput in) throws IOException {
this(in.readString(), in.readZLong(), in.readVLong(), in.readString());
}
/**
* Writes a retention lease to a stream in a manner suitable for later reconstruction via {@link #RetentionLease(StreamInput)}.
*
* @param out the stream to write the retention lease to
* @throws IOException if an I/O exception occurs writing to the stream
*/
@Override
public void writeTo(final StreamOutput out) throws IOException {
out.writeString(id);
out.writeZLong(retainingSequenceNumber);
out.writeVLong(timestamp);
out.writeString(source);
}
private static final ParseField ID_FIELD = new ParseField("id");
private static final ParseField RETAINING_SEQUENCE_NUMBER_FIELD = new ParseField("retaining_sequence_number");
private static final ParseField TIMESTAMP_FIELD = new ParseField("timestamp");
private static final ParseField SOURCE_FIELD = new ParseField("source");
private static final ConstructingObjectParser<RetentionLease, Void> PARSER = new ConstructingObjectParser<>(
"retention_leases",
(a) -> new RetentionLease((String) a[0], (Long) a[1], (Long) a[2], (String) a[3])
);
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD);
PARSER.declareLong(ConstructingObjectParser.constructorArg(), RETAINING_SEQUENCE_NUMBER_FIELD);
PARSER.declareLong(ConstructingObjectParser.constructorArg(), TIMESTAMP_FIELD);
PARSER.declareString(ConstructingObjectParser.constructorArg(), SOURCE_FIELD);
}
@Override
public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException {
builder.startObject();
{
builder.field(ID_FIELD.getPreferredName(), id);
builder.field(RETAINING_SEQUENCE_NUMBER_FIELD.getPreferredName(), retainingSequenceNumber);
builder.field(TIMESTAMP_FIELD.getPreferredName(), timestamp);
builder.field(SOURCE_FIELD.getPreferredName(), source);
}
builder.endObject();
return builder;
}
/**
* Parses a retention lease from {@link org.elasticsearch.xcontent.XContent}. This method assumes that the retention lease was
* converted to {@link org.elasticsearch.xcontent.XContent} via {@link #toXContent(XContentBuilder, Params)}.
*
* @param parser the parser
* @return a retention lease
*/
public static RetentionLease fromXContent(final XContentParser parser) {
return PARSER.apply(parser, null);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final RetentionLease that = (RetentionLease) o;
return Objects.equals(id, that.id)
&& retainingSequenceNumber == that.retainingSequenceNumber
&& timestamp == that.timestamp
&& Objects.equals(source, that.source);
}
@Override
public int hashCode() {
return Objects.hash(id, retainingSequenceNumber, timestamp, source);
}
@Override
public String toString() {
return "RetentionLease{"
+ "id='"
+ id
+ '\''
+ ", retainingSequenceNumber="
+ retainingSequenceNumber
+ ", timestamp="
+ timestamp
+ ", source='"
+ source
+ '\''
+ '}';
}
}
|
RetentionLease
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_1.java
|
{
"start": 159,
"end": 2219
}
|
class ____ extends TestCase {
public void test_0() throws Exception {
String json = "[{\"id\":1001},{\"id\":1002},{\"id\":1003},[1],123,-4,\"a\\\"bc\"]";
assertEquals("{\"id\":1001}"
, JSONPath.extract(json, "$.0")
.toString());
assertEquals("{\"id\":1002}"
, JSONPath.extract(json, "$.1")
.toString());
assertEquals("{\"id\":1003}"
, JSONPath.extract(json, "$.2")
.toString());
assertEquals("[1]"
, JSONPath.extract(json, "$.3")
.toString());
assertEquals("123"
, JSONPath.extract(json, "$.4")
.toString());
assertEquals("-4"
, JSONPath.extract(json, "$.5")
.toString());
assertEquals("a\"bc"
, JSONPath.extract(json, "$.6")
.toString());
}
public void test_1() throws Exception {
String json = "[\"a\\\"bc\",123]";
assertEquals("a\"bc"
, JSONPath.extract(json, "$.0")
.toString());
assertEquals("123"
, JSONPath.extract(json, "$.1")
.toString());
}
public void test_2() throws Exception {
String json = "[\"a\\\\bc\",123]";
assertEquals("a\\bc"
, JSONPath.extract(json, "$.0")
.toString());
assertEquals("123"
, JSONPath.extract(json, "$.1")
.toString());
}
public void test_3() throws Exception {
String json = "[\"a\\\"b\\\\c\\\"d\\\"e\",123]";
assertEquals("a\"b\\c\"d\"e"
, JSONPath.extract(json, "$.0")
.toString());
assertEquals("123"
, JSONPath.extract(json, "$.1")
.toString());
assertNull(JSONPath.extract(json, "$.2"));
}
}
|
JSONPath_extract_1
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/errors/ProcessingExceptionHandler.java
|
{
"start": 2452,
"end": 3147
}
|
enum ____ {
/** Continue processing. */
CONTINUE(1, "CONTINUE"),
/** Fail processing. */
FAIL(2, "FAIL");
/**
* An english description for the used option. This is for debugging only and may change.
*/
public final String name;
/**
* The permanent and immutable id for the used option. This can't change ever.
*/
public final int id;
ProcessingHandlerResponse(final int id, final String name) {
this.id = id;
this.name = name;
}
}
/**
* Enumeration that describes the response from the exception handler.
*/
|
ProcessingHandlerResponse
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/jmx/export/MBeanExporterListener.java
|
{
"start": 962,
"end": 1539
}
|
interface ____ {
/**
* Called by {@link MBeanExporter} after an MBean has been <i>successfully</i>
* registered with an {@link javax.management.MBeanServer}.
* @param objectName the {@code ObjectName} of the registered MBean
*/
void mbeanRegistered(ObjectName objectName);
/**
* Called by {@link MBeanExporter} after an MBean has been <i>successfully</i>
* unregistered from an {@link javax.management.MBeanServer}.
* @param objectName the {@code ObjectName} of the unregistered MBean
*/
void mbeanUnregistered(ObjectName objectName);
}
|
MBeanExporterListener
|
java
|
grpc__grpc-java
|
gcp-observability/src/test/java/io/grpc/gcp/observability/LoggingTest.java
|
{
"start": 8438,
"end": 11400
}
|
class ____ implements Runnable {
@Override
public void run() {
Sink mockSink = mock(GcpLogSink.class);
ObservabilityConfig config = mock(ObservabilityConfig.class);
LogHelper spyLogHelper = spy(new LogHelper(mockSink));
ConfigFilterHelper mockFilterHelper2 = mock(ConfigFilterHelper.class);
InternalLoggingChannelInterceptor.Factory channelInterceptorFactory =
new InternalLoggingChannelInterceptor.FactoryImpl(spyLogHelper, mockFilterHelper2);
InternalLoggingServerInterceptor.Factory serverInterceptorFactory =
new InternalLoggingServerInterceptor.FactoryImpl(spyLogHelper, mockFilterHelper2);
when(config.isEnableCloudLogging()).thenReturn(true);
FilterParams logAlwaysFilterParams = FilterParams.create(true, 0, 0);
when(mockFilterHelper2.logRpcMethod(anyString(), eq(true)))
.thenReturn(logAlwaysFilterParams);
when(mockFilterHelper2.logRpcMethod(anyString(), eq(false)))
.thenReturn(logAlwaysFilterParams);
try (GcpObservability observability =
GcpObservability.grpcInit(
mockSink, config, channelInterceptorFactory, serverInterceptorFactory)) {
Server server =
ServerBuilder.forPort(0)
.addService(new ObservabilityTestHelper.SimpleServiceImpl())
.build()
.start();
int port = cleanupRule.register(server).getPort();
SimpleServiceGrpc.SimpleServiceBlockingStub stub =
SimpleServiceGrpc.newBlockingStub(
cleanupRule.register(
ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build()));
assertThat(ObservabilityTestHelper.makeUnaryRpcViaClientStub("buddy", stub))
.isEqualTo("Hello buddy");
// Total number of calls should have been 14 (6 from client and 6 from server)
// Since cancel is not invoked, it will be 12.
// Request message(Total count:2 (1 from client and 1 from server) and Response
// message(count:2)
// events are not in the event_types list, i.e 14 - 2(cancel) - 2(req_msg) - 2(resp_msg)
// = 8
assertThat(Mockito.mockingDetails(mockSink).getInvocations().size()).isEqualTo(12);
ArgumentCaptor<GrpcLogRecord> captor = ArgumentCaptor.forClass(GrpcLogRecord.class);
verify(mockSink, times(12)).write(captor.capture(),
AdditionalMatchers.or(ArgumentMatchers.isNull(),
ArgumentMatchers.any(SpanContext.class)));
for (GrpcLogRecord record : captor.getAllValues()) {
assertThat(record.getType()).isInstanceOf(GrpcLogRecord.EventType.class);
assertThat(record.getLogger()).isInstanceOf(GrpcLogRecord.EventLogger.class);
}
} catch (IOException e) {
throw new AssertionError("Exception while testing logging using mock sink", e);
}
}
}
}
|
StaticTestingClassLogEventsUsingMockSink
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/transaction/ejb/dao/RequiresNewEjbTxTestEntityDao.java
|
{
"start": 1224,
"end": 1554
}
|
class ____ extends AbstractEjbTxTestEntityDao {
@Override
public int getCount(String name) {
return super.getCountInternal(name);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Override
public int incrementCount(String name) {
return super.incrementCountInternal(name);
}
}
|
RequiresNewEjbTxTestEntityDao
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/reader/TimelineParserForRelationFilters.java
|
{
"start": 1383,
"end": 2574
}
|
class ____ extends
TimelineParserForEqualityExpr {
private final String valueDelimiter;
public TimelineParserForRelationFilters(String expression, char valuesDelim,
String valueDelim) {
super(expression, "Relation Filter", valuesDelim);
valueDelimiter = valueDelim;
}
@Override
protected TimelineFilter createFilter() {
return new TimelineKeyValuesFilter();
}
@Override
protected void setCompareOpToCurrentFilter(TimelineCompareOp compareOp) {
((TimelineKeyValuesFilter)getCurrentFilter()).setCompareOp(compareOp);
}
@Override
protected void setValueToCurrentFilter(String value)
throws TimelineParseException {
if (value != null) {
String[] pairStrs = value.split(valueDelimiter);
if (pairStrs.length < 2) {
throw new TimelineParseException("Invalid relation filter expression");
}
String key = pairStrs[0].trim();
Set<Object> values = new HashSet<Object>();
for (int i = 1; i < pairStrs.length; i++) {
values.add(pairStrs[i].trim());
}
((TimelineKeyValuesFilter)getCurrentFilter()).
setKeyAndValues(key, values);
}
}
}
|
TimelineParserForRelationFilters
|
java
|
apache__camel
|
components/camel-caffeine/src/main/java/org/apache/camel/component/caffeine/DefaultCaffeineSendDynamicAware.java
|
{
"start": 1134,
"end": 4223
}
|
class ____ extends SendDynamicAwareSupport {
@Override
public boolean isLenientProperties() {
return false;
}
@Override
public DynamicAwareEntry prepare(Exchange exchange, String uri, String originalUri) throws Exception {
Map<String, Object> properties = endpointProperties(exchange, uri);
return new DynamicAwareEntry(uri, originalUri, properties, null);
}
@Override
public String resolveStaticUri(Exchange exchange, DynamicAwareEntry entry) throws Exception {
Object action = exchange.getMessage().getHeader(CaffeineConstants.ACTION);
Object key = exchange.getMessage().getHeader(CaffeineConstants.KEY);
Object keys = exchange.getMessage().getHeader(CaffeineConstants.KEYS);
Object value = exchange.getMessage().getHeader(CaffeineConstants.VALUE);
if (action == null && key == null && keys == null && value == null) {
// remove keys
Map<String, Object> copy = new LinkedHashMap<>(entry.getProperties());
copy.remove("action");
copy.remove("key");
copy.remove("keys");
copy.remove("value");
// build static uri
String u = entry.getUri();
// remove query parameters
if (u.contains("?")) {
u = StringHelper.before(u, "?");
}
String query = URISupport.createQueryString(copy);
if (!query.isEmpty()) {
return u + "?" + query;
} else {
return u;
}
} else {
// no optimisation possible
return null;
}
}
@Override
public Processor createPreProcessor(Exchange exchange, DynamicAwareEntry entry) throws Exception {
// store as headers
return ex -> {
Object action = entry.getProperties().get("action");
if (action != null) {
ex.getMessage().setHeader(CaffeineConstants.ACTION, action);
}
Object key = entry.getProperties().get("key");
if (key != null) {
ex.getMessage().setHeader(CaffeineConstants.KEY, key);
}
Object keys = entry.getProperties().get("keys");
if (keys != null) {
ex.getMessage().setHeader(CaffeineConstants.KEYS, key);
}
Object value = entry.getProperties().get("value");
if (value != null) {
ex.getMessage().setHeader(CaffeineConstants.VALUE, value);
}
};
}
@Override
public Processor createPostProcessor(Exchange exchange, DynamicAwareEntry entry) throws Exception {
// cleanup and remove the headers we used
return ex -> {
ex.getMessage().removeHeader(CaffeineConstants.ACTION);
ex.getMessage().removeHeader(CaffeineConstants.KEY);
ex.getMessage().removeHeader(CaffeineConstants.KEYS);
ex.getMessage().removeHeader(CaffeineConstants.VALUE);
};
}
}
|
DefaultCaffeineSendDynamicAware
|
java
|
quarkusio__quarkus
|
extensions/agroal/deployment/src/test/java/io/quarkus/agroal/test/FlushOnCloseDataSourceConfigTest.java
|
{
"start": 2745,
"end": 3283
}
|
class ____ implements AgroalPoolInterceptor {
@Override
public void onConnectionAcquire(Connection connection) {
try {
LOGGER.info("connection acquired ClientUser:" + connection.getClientInfo("ClientUser"));
} catch (SQLException e) {
Assertions.fail(e);
}
}
@Override
public void onConnectionReturn(Connection connection) {
Assertions.fail("unexpected connection return");
}
}
}
|
ClientUserTrackerInterceptor
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/Hamlet.java
|
{
"start": 15223,
"end": 31385
}
|
class ____<T extends __> extends EImp<T> implements HamletSpec.TD {
public TD(String name, T parent, EnumSet<EOpt> opts) {
super(name, parent, opts);
}
@Override
public TD<T> $headers(String value) {
addAttr("headers", value);
return this;
}
@Override
public TD<T> $scope(Scope value) {
addAttr("scope", value);
return this;
}
@Override
public TD<T> $rowspan(int value) {
addAttr("rowspan", value);
return this;
}
@Override
public TD<T> $colspan(int value) {
addAttr("colspan", value);
return this;
}
@Override
public TD<T> $id(String value) {
addAttr("id", value);
return this;
}
@Override
public TD<T> $class(String value) {
addAttr("class", value);
return this;
}
@Override
public TD<T> $title(String value) {
addAttr("title", value);
return this;
}
@Override
public TD<T> $style(String value) {
addAttr("style", value);
return this;
}
@Override
public TD<T> $lang(String value) {
addAttr("lang", value);
return this;
}
@Override
public TD<T> $dir(Dir value) {
addAttr("dir", value);
return this;
}
@Override
public TD<T> $onclick(String value) {
addAttr("onclick", value);
return this;
}
@Override
public TD<T> $ondblclick(String value) {
addAttr("ondblclick", value);
return this;
}
@Override
public TD<T> $onmousedown(String value) {
addAttr("onmousedown", value);
return this;
}
@Override
public TD<T> $onmouseup(String value) {
addAttr("onmouseup", value);
return this;
}
@Override
public TD<T> $onmouseover(String value) {
addAttr("onmouseover", value);
return this;
}
@Override
public TD<T> $onmousemove(String value) {
addAttr("onmousemove", value);
return this;
}
@Override
public TD<T> $onmouseout(String value) {
addAttr("onmouseout", value);
return this;
}
@Override
public TD<T> $onkeypress(String value) {
addAttr("onkeypress", value);
return this;
}
@Override
public TD<T> $onkeydown(String value) {
addAttr("onkeydown", value);
return this;
}
@Override
public TD<T> $onkeyup(String value) {
addAttr("onkeyup", value);
return this;
}
@Override
public TABLE<TD<T>> table() {
closeAttrs();
return table_(this, false);
}
@Override
public TABLE<TD<T>> table(String selector) {
return setSelector(table(), selector);
}
@Override
public TD<T> address(String cdata) {
return address().__(cdata).__();
}
@Override
public ADDRESS<TD<T>> address() {
closeAttrs();
return address_(this, false);
}
@Override
public P<TD<T>> p(String selector) {
return setSelector(p(), selector);
}
@Override
public P<TD<T>> p() {
closeAttrs();
return p_(this, false);
}
@Override
public TD<T> __(Class<? extends SubView> cls) {
_v(cls);
return this;
}
@Override
public HR<TD<T>> hr() {
closeAttrs();
return hr_(this, false);
}
@Override
public TD<T> hr(String selector) {
return setSelector(hr(), selector).__();
}
@Override
public DL<TD<T>> dl(String selector) {
return setSelector(dl(), selector);
}
@Override
public DL<TD<T>> dl() {
closeAttrs();
return dl_(this, false);
}
@Override
public DIV<TD<T>> div(String selector) {
return setSelector(div(), selector);
}
@Override
public DIV<TD<T>> div() {
closeAttrs();
return div_(this, false);
}
@Override
public BLOCKQUOTE<TD<T>> blockquote() {
closeAttrs();
return blockquote_(this, false);
}
@Override
public BLOCKQUOTE<TD<T>> bq() {
closeAttrs();
return blockquote_(this, false);
}
@Override
public TD<T> h1(String cdata) {
return h1().__(cdata).__();
}
@Override
public H1<TD<T>> h1() {
closeAttrs();
return h1_(this, false);
}
@Override
public TD<T> h1(String selector, String cdata) {
return setSelector(h1(), selector).__(cdata).__();
}
@Override
public TD<T> h2(String cdata) {
return h2().__(cdata).__();
}
@Override
public H2<TD<T>> h2() {
closeAttrs();
return h2_(this, false);
}
@Override
public TD<T> h2(String selector, String cdata) {
return setSelector(h2(), selector).__(cdata).__();
}
@Override
public H3<TD<T>> h3() {
closeAttrs();
return h3_(this, false);
}
@Override
public TD<T> h3(String cdata) {
return h3().__(cdata).__();
}
@Override
public TD<T> h3(String selector, String cdata) {
return setSelector(h3(), selector).__(cdata).__();
}
@Override
public H4<TD<T>> h4() {
closeAttrs();
return h4_(this, false);
}
@Override
public TD<T> h4(String cdata) {
return h4().__(cdata).__();
}
@Override
public TD<T> h4(String selector, String cdata) {
return setSelector(h4(), selector).__(cdata).__();
}
@Override
public H5<TD<T>> h5() {
closeAttrs();
return h5_(this, false);
}
@Override
public TD<T> h5(String cdata) {
return h5().__(cdata).__();
}
@Override
public TD<T> h5(String selector, String cdata) {
return setSelector(h5(), selector).__(cdata).__();
}
@Override
public H6<TD<T>> h6() {
closeAttrs();
return h6_(this, false);
}
@Override
public TD<T> h6(String cdata) {
return h6().__(cdata).__();
}
@Override
public TD<T> h6(String selector, String cdata) {
return setSelector(h6(), selector).__(cdata).__();
}
@Override
public UL<TD<T>> ul() {
closeAttrs();
return ul_(this, false);
}
@Override
public UL<TD<T>> ul(String selector) {
return setSelector(ul(), selector);
}
@Override
public OL<TD<T>> ol() {
closeAttrs();
return ol_(this, false);
}
@Override
public OL<TD<T>> ol(String selector) {
return setSelector(ol(), selector);
}
@Override
public PRE<TD<T>> pre() {
closeAttrs();
return pre_(this, false);
}
@Override
public PRE<TD<T>> pre(String selector) {
return setSelector(pre(), selector);
}
@Override
public FORM<TD<T>> form() {
closeAttrs();
return form_(this, false);
}
@Override
public FORM<TD<T>> form(String selector) {
return setSelector(form(), selector);
}
@Override
public FIELDSET<TD<T>> fieldset() {
closeAttrs();
return fieldset_(this, false);
}
@Override
public FIELDSET<TD<T>> fieldset(String selector) {
return setSelector(fieldset(), selector);
}
@Override
public TD<T> __(Object... lines) {
_p(true, lines);
return this;
}
@Override
public TD<T> _r(Object... lines) {
_p(false, lines);
return this;
}
@Override
public B<TD<T>> b() {
closeAttrs();
return b_(this, true);
}
@Override
public TD<T> b(String cdata) {
return b().__(cdata).__();
}
@Override
public TD<T> b(String selector, String cdata) {
return setSelector(b(), selector).__(cdata).__();
}
@Override
public I<TD<T>> i() {
closeAttrs();
return i_(this, true);
}
@Override
public TD<T> i(String cdata) {
return i().__(cdata).__();
}
@Override
public TD<T> i(String selector, String cdata) {
return setSelector(i(), selector).__(cdata).__();
}
@Override
public SMALL<TD<T>> small() {
closeAttrs();
return small_(this, true);
}
@Override
public TD<T> small(String cdata) {
return small().__(cdata).__();
}
@Override
public TD<T> small(String selector, String cdata) {
return setSelector(small(), selector).__(cdata).__();
}
@Override
public TD<T> em(String cdata) {
return em().__(cdata).__();
}
@Override
public EM<TD<T>> em() {
closeAttrs();
return em_(this, true);
}
@Override
public TD<T> em(String selector, String cdata) {
return setSelector(em(), selector).__(cdata).__();
}
@Override
public STRONG<TD<T>> strong() {
closeAttrs();
return strong_(this, true);
}
@Override
public TD<T> strong(String cdata) {
return strong().__(cdata).__();
}
@Override
public TD<T> strong(String selector, String cdata) {
return setSelector(strong(), selector).__(cdata).__();
}
@Override
public DFN<TD<T>> dfn() {
closeAttrs();
return dfn_(this, true);
}
@Override
public TD<T> dfn(String cdata) {
return dfn().__(cdata).__();
}
@Override
public TD<T> dfn(String selector, String cdata) {
return setSelector(dfn(), selector).__(cdata).__();
}
@Override
public CODE<TD<T>> code() {
closeAttrs();
return code_(this, true);
}
@Override
public TD<T> code(String cdata) {
return code().__(cdata).__();
}
@Override
public TD<T> code(String selector, String cdata) {
return setSelector(code(), selector).__(cdata).__();
}
@Override
public TD<T> samp(String cdata) {
return samp().__(cdata).__();
}
@Override
public SAMP<TD<T>> samp() {
closeAttrs();
return samp_(this, true);
}
@Override
public TD<T> samp(String selector, String cdata) {
return setSelector(samp(), selector).__(cdata).__();
}
@Override
public KBD<TD<T>> kbd() {
closeAttrs();
return kbd_(this, true);
}
@Override
public TD<T> kbd(String cdata) {
return kbd().__(cdata).__();
}
@Override
public TD<T> kbd(String selector, String cdata) {
return setSelector(kbd(), selector).__(cdata).__();
}
@Override
public VAR<TD<T>> var() {
closeAttrs();
return var_(this, true);
}
@Override
public TD<T> var(String cdata) {
return var().__(cdata).__();
}
@Override
public TD<T> var(String selector, String cdata) {
return setSelector(var(), selector).__(cdata).__();
}
@Override
public CITE<TD<T>> cite() {
closeAttrs();
return cite_(this, true);
}
@Override
public TD<T> cite(String cdata) {
return cite().__(cdata).__();
}
@Override
public TD<T> cite(String selector, String cdata) {
return setSelector(cite(), selector).__(cdata).__();
}
@Override
public ABBR<TD<T>> abbr() {
closeAttrs();
return abbr_(this, true);
}
@Override
public TD<T> abbr(String cdata) {
return abbr().__(cdata).__();
}
@Override
public TD<T> abbr(String selector, String cdata) {
return setSelector(abbr(), selector).__(cdata).__();
}
@Override
public A<TD<T>> a() {
closeAttrs();
return a_(this, true);
}
@Override
public A<TD<T>> a(String selector) {
return setSelector(a(), selector);
}
@Override
public TD<T> a(String href, String anchorText) {
return a().$href(href).__(anchorText).__();
}
@Override
public TD<T> a(String selector, String href, String anchorText) {
return setSelector(a(), selector).$href(href).__(anchorText).__();
}
@Override
public IMG<TD<T>> img() {
closeAttrs();
return img_(this, true);
}
@Override
public TD<T> img(String src) {
return img().$src(src).__();
}
@Override
public OBJECT<TD<T>> object() {
closeAttrs();
return object_(this, true);
}
@Override
public OBJECT<TD<T>> object(String selector) {
return setSelector(object(), selector);
}
@Override
public SUB<TD<T>> sub() {
closeAttrs();
return sub_(this, true);
}
@Override
public TD<T> sub(String cdata) {
return sub().__(cdata).__();
}
@Override
public TD<T> sub(String selector, String cdata) {
return setSelector(sub(), selector).__(cdata).__();
}
@Override
public SUP<TD<T>> sup() {
closeAttrs();
return sup_(this, true);
}
@Override
public TD<T> sup(String cdata) {
return sup().__(cdata).__();
}
@Override
public TD<T> sup(String selector, String cdata) {
return setSelector(sup(), selector).__(cdata).__();
}
@Override
public MAP<TD<T>> map() {
closeAttrs();
return map_(this, true);
}
@Override
public MAP<TD<T>> map(String selector) {
return setSelector(map(), selector);
}
@Override
public TD<T> q(String cdata) {
return q().__(cdata).__();
}
@Override
public TD<T> q(String selector, String cdata) {
return setSelector(q(), selector).__(cdata).__();
}
@Override
public Q<TD<T>> q() {
closeAttrs();
return q_(this, true);
}
@Override
public BR<TD<T>> br() {
closeAttrs();
return br_(this, true);
}
@Override
public TD<T> br(String selector) {
return setSelector(br(), selector).__();
}
@Override
public BDO<TD<T>> bdo() {
closeAttrs();
return bdo_(this, true);
}
@Override
public TD<T> bdo(Dir dir, String cdata) {
return bdo().$dir(dir).__(cdata).__();
}
@Override
public SPAN<TD<T>> span() {
closeAttrs();
return span_(this, true);
}
@Override
public TD<T> span(String cdata) {
return span().__(cdata).__();
}
@Override
public TD<T> span(String selector, String cdata) {
return setSelector(span(), selector).__(cdata).__();
}
@Override
public SCRIPT<TD<T>> script() {
closeAttrs();
return script_(this, true);
}
@Override
public TD<T> script(String src) {
return setScriptSrc(script(), src).__();
}
@Override
public INS<TD<T>> ins() {
closeAttrs();
return ins_(this, true);
}
@Override
public TD<T> ins(String cdata) {
return ins().__(cdata).__();
}
@Override
public DEL<TD<T>> del() {
closeAttrs();
return del_(this, true);
}
@Override
public TD<T> del(String cdata) {
return del().__(cdata).__();
}
@Override
public LABEL<TD<T>> label() {
closeAttrs();
return label_(this, true);
}
@Override
public TD<T> label(String forId, String cdata) {
return label().$for(forId).__(cdata).__();
}
@Override
public INPUT<TD<T>> input(String selector) {
return setSelector(input(), selector);
}
@Override
public INPUT<TD<T>> input() {
closeAttrs();
return input_(this, true);
}
@Override
public SELECT<TD<T>> select() {
closeAttrs();
return select_(this, true);
}
@Override
public SELECT<TD<T>> select(String selector) {
return setSelector(select(), selector);
}
@Override
public TEXTAREA<TD<T>> textarea(String selector) {
return setSelector(textarea(), selector);
}
@Override
public TEXTAREA<TD<T>> textarea() {
closeAttrs();
return textarea_(this, true);
}
@Override
public TD<T> textarea(String selector, String cdata) {
return setSelector(textarea(), selector).__(cdata).__();
}
@Override
public BUTTON<TD<T>> button() {
closeAttrs();
return button_(this, true);
}
@Override
public BUTTON<TD<T>> button(String selector) {
return setSelector(button(), selector);
}
@Override
public TD<T> button(String selector, String cdata) {
return setSelector(button(), selector).__(cdata).__();
}
}
public
|
TD
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/fetching/ProfileFetchingTest.java
|
{
"start": 3331,
"end": 3848
}
|
class ____ {
@Id
private Long id;
@NaturalId
private String username;
@Column(name = "pswd")
@ColumnTransformer(
read = "decrypt('AES', '00', pswd )",
write = "encrypt('AES', '00', ?)"
)
private String password;
private int accessLevel;
@ManyToOne(fetch = FetchType.LAZY)
private Department department;
@ManyToMany(mappedBy = "employees")
private List<Project> projects = new ArrayList<>();
//Getters and setters omitted for brevity
}
@Entity(name = "Project")
public
|
Employee
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/type/EsqlDataTypeRegistryTests.java
|
{
"start": 1025,
"end": 2687
}
|
class ____ extends ESTestCase {
public void testCounter() {
resolve("long", TimeSeriesParams.MetricType.COUNTER, DataType.COUNTER_LONG);
resolve("integer", TimeSeriesParams.MetricType.COUNTER, DataType.COUNTER_INTEGER);
resolve("double", TimeSeriesParams.MetricType.COUNTER, DataType.COUNTER_DOUBLE);
}
public void testGauge() {
resolve("long", TimeSeriesParams.MetricType.GAUGE, DataType.LONG);
}
public void testLong() {
resolve("long", null, DataType.LONG);
}
private void resolve(String esTypeName, TimeSeriesParams.MetricType metricType, DataType expected) {
String idx = "idx-" + randomAlphaOfLength(5);
String field = "f" + randomAlphaOfLength(3);
List<FieldCapabilitiesIndexResponse> idxResponses = List.of(
new FieldCapabilitiesIndexResponse(
idx,
idx,
Map.of(field, new IndexFieldCapabilitiesBuilder(field, esTypeName).metricType(metricType).build()),
true,
IndexMode.TIME_SERIES
)
);
FieldCapabilitiesResponse caps = FieldCapabilitiesResponse.builder().withIndexResponses(idxResponses).build();
// IndexResolver uses EsqlDataTypeRegistry directly
IndexResolution resolution = IndexResolver.mergedMappings(
"idx-*",
new IndexResolver.FieldsInfo(caps, TransportVersion.current(), false, false, false),
IndexResolver.DO_NOT_GROUP
);
EsField f = resolution.get().mapping().get(field);
assertThat(f.getDataType(), equalTo(expected));
}
}
|
EsqlDataTypeRegistryTests
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/grant/MySqlGrantTest_27.java
|
{
"start": 969,
"end": 2378
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "GRANT REPLICATION CLIENT ON mydb.* TO 'someuser'@'somehost';";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("GRANT REPLICATION CLIENT ON mydb.* TO 'someuser'@'somehost';", //
output);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("City")));
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2")));
// assertTrue(visitor.getColumns().contains(new Column("t2", "id")));
}
}
|
MySqlGrantTest_27
|
java
|
apache__camel
|
components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaNoResponseFromServerTest.java
|
{
"start": 1725,
"end": 2806
}
|
class ____ extends BaseMinaTest {
@BindToRegistry("myCodec")
private final MyCodec codec1 = new MyCodec();
@Test
public void testNoResponse() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
final String format = String.format("mina:tcp://localhost:%1$s?sync=true&codec=#myCodec", getPort());
RuntimeCamelException e = assertThrows(RuntimeCamelException.class,
() -> template.requestBody(format, "Hello World"),
"Should throw a CamelExchangeException");
assertIsInstanceOf(CamelExchangeException.class, e.getCause());
mock.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
fromF("mina:tcp://localhost:%1$s?sync=true&codec=#myCodec", getPort())
.transform(constant("Bye World")).to("mock:result");
}
};
}
private static
|
MinaNoResponseFromServerTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
|
{
"start": 1988,
"end": 2504
}
|
class ____ {
private Inner(ExemptedByReceiverParameter ExemptedByReceiverParameter.this) {
// the receiver parameter should not be marked as unused
}
}
}
""")
.doTest();
}
@Test
public void unicodeBytes() {
helper
.addSourceLines(
"UnicodeBytes.java",
"""
package unusedvars;
/** This file contains Unicode characters: ❁❁❁❁❁❁❁❁❁ */
public
|
Inner
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/deser/CharArrayDeserializerTest.java
|
{
"start": 145,
"end": 1459
}
|
class ____ extends TestCase {
public void test_charArray() throws Exception {
Assert.assertEquals(null, JSON.parseObject("{}", VO.class).getValue());
Assert.assertEquals(null, JSON.parseObject("{value:null}", VO.class).getValue());
Assert.assertEquals(null, JSON.parseObject("{'value':null}", VO.class).getValue());
Assert.assertEquals(null, JSON.parseObject("{\"value\":null}", VO.class).getValue());
Assert.assertEquals(0, JSON.parseObject("{\"value\":\"\"}", VO.class).getValue().length);
Assert.assertEquals(2, JSON.parseObject("{\"value\":\"ab\"}", VO.class).getValue().length);
Assert.assertEquals("ab", new String(JSON.parseObject("{\"value\":\"ab\"}", VO.class).getValue()));
Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12}", VO.class).getValue()));
Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12L}", VO.class).getValue()));
Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12S}", VO.class).getValue()));
Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12B}", VO.class).getValue()));
Assert.assertEquals("{}", new String(JSON.parseObject("{\"value\":{}}", VO.class).getValue()));
}
public static
|
CharArrayDeserializerTest
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SpringEventComponentBuilderFactory.java
|
{
"start": 1838,
"end": 5341
}
|
interface ____ extends ComponentBuilder<EventComponent> {
/**
* 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
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default SpringEventComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SpringEventComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default SpringEventComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
|
SpringEventComponentBuilder
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/common/recycler/AbstractRecyclerTestCase.java
|
{
"start": 702,
"end": 4781
}
|
class ____ extends ESTestCase {
// marker states for data
protected static final byte FRESH = 1;
protected static final byte RECYCLED = 2;
protected static final byte DEAD = 42;
protected static final Recycler.C<byte[]> RECYCLER_C = new AbstractRecyclerC<byte[]>() {
@Override
public byte[] newInstance() {
byte[] value = new byte[pageSize()];
// "fresh" is intentionally not 0 to ensure we covered this code path
Arrays.fill(value, FRESH);
return value;
}
@Override
public void recycle(byte[] value) {
Arrays.fill(value, RECYCLED);
}
@Override
public void destroy(byte[] value) {
// we cannot really free the internals of a byte[], so mark it for verification
Arrays.fill(value, DEAD);
}
@Override
public int pageSize() {
return 10;
}
};
protected void assertFresh(byte[] data) {
assertNotNull(data);
for (int i = 0; i < data.length; ++i) {
assertEquals(FRESH, data[i]);
}
}
protected void assertRecycled(byte[] data) {
assertNotNull(data);
for (int i = 0; i < data.length; ++i) {
assertEquals(RECYCLED, data[i]);
}
}
protected void assertDead(byte[] data) {
assertNotNull(data);
for (int i = 0; i < data.length; ++i) {
assertEquals(DEAD, data[i]);
}
}
protected abstract Recycler<byte[]> newRecycler(int limit);
protected int limit = randomIntBetween(5, 10);
public void testReuse() {
Recycler<byte[]> r = newRecycler(limit);
Recycler.V<byte[]> o = r.obtain();
assertFalse(o.isRecycled());
final byte[] b1 = o.v();
assertFresh(b1);
o.close();
assertRecycled(b1);
o = r.obtain();
final byte[] b2 = o.v();
if (o.isRecycled()) {
assertRecycled(b2);
assertSame(b1, b2);
} else {
assertFresh(b2);
assertNotSame(b1, b2);
}
o.close();
}
public void testRecycle() {
Recycler<byte[]> r = newRecycler(limit);
Recycler.V<byte[]> o = r.obtain();
assertFresh(o.v());
random().nextBytes(o.v());
o.close();
o = r.obtain();
assertRecycled(o.v());
o.close();
}
public void testDoubleRelease() {
final Recycler<byte[]> r = newRecycler(limit);
final Recycler.V<byte[]> v1 = r.obtain();
v1.close();
try {
v1.close();
} catch (IllegalStateException e) {
// impl has protection against double release: ok
return;
}
// otherwise ensure that the impl may not be returned twice
final Recycler.V<byte[]> v2 = r.obtain();
final Recycler.V<byte[]> v3 = r.obtain();
assertNotSame(v2.v(), v3.v());
}
public void testDestroyWhenOverCapacity() {
Recycler<byte[]> r = newRecycler(limit);
// get & keep reference to new/recycled data
Recycler.V<byte[]> o = r.obtain();
byte[] data = o.v();
assertFresh(data);
// now exhaust the recycler
List<V<byte[]>> vals = new ArrayList<>(limit);
for (int i = 0; i < limit; ++i) {
vals.add(r.obtain());
}
// Recycler size increases on release, not on obtain!
for (V<byte[]> v : vals) {
v.close();
}
// release first ref, verify for destruction
o.close();
assertDead(data);
}
public void testClose() {
Recycler<byte[]> r = newRecycler(limit);
// get & keep reference to pooled data
Recycler.V<byte[]> o = r.obtain();
byte[] data = o.v();
assertFresh(data);
// randomize & return to pool
random().nextBytes(data);
o.close();
// verify that recycle() ran
assertRecycled(data);
}
}
|
AbstractRecyclerTestCase
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-federation-balance/src/main/java/org/apache/hadoop/tools/fedbalance/procedure/BalanceJob.java
|
{
"start": 1671,
"end": 2322
}
|
class ____<T extends BalanceProcedure> implements Writable {
private String id;
private BalanceProcedureScheduler scheduler;
private volatile boolean jobDone = false;
private Exception error;
public static final Logger LOG = LoggerFactory.getLogger(BalanceJob.class);
private Map<String, T> procedureTable = new HashMap<>();
private T firstProcedure;
private T curProcedure;
private T lastProcedure;
private boolean removeAfterDone;
static final String NEXT_PROCEDURE_NONE = "NONE";
private static Set<String> reservedNames = new HashSet<>();
static {
reservedNames.add(NEXT_PROCEDURE_NONE);
}
public static
|
BalanceJob
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/MutationTests.java
|
{
"start": 1063,
"end": 2118
}
|
class ____ {
@Test
public void testSimpleDeleteTranslation(SessionFactoryScope scope) {
final SqmDeleteStatement<?> sqmDelete = (SqmDeleteStatement<?>) scope.getSessionFactory()
.getQueryEngine()
.getHqlTranslator()
.translate( "delete BasicEntity", null );
assertThat( sqmDelete, notNullValue() );
assertThat( sqmDelete.getTarget().getEntityName(), is( BasicEntity.class.getName() ) );
assertThat( sqmDelete.getRestriction(), nullValue() );
}
@Test
public void testSimpleRestrictedDeleteTranslation(SessionFactoryScope scope) {
final SqmDeleteStatement<?> sqmDelete = (SqmDeleteStatement<?>) scope.getSessionFactory()
.getQueryEngine()
.getHqlTranslator()
.translate( "delete BasicEntity where data = 'abc'", null );
assertThat( sqmDelete, notNullValue() );
assertThat( sqmDelete.getTarget().getEntityName(), is( BasicEntity.class.getName() ) );
assertThat( sqmDelete.getRestriction(), notNullValue() );
assertThat( sqmDelete.getRestriction(), instanceOf( SqmComparisonPredicate.class ) );
}
}
|
MutationTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/ibmwatsonx/completion/IbmWatsonxChatCompletionModel.java
|
{
"start": 1517,
"end": 5759
}
|
class ____ extends IbmWatsonxModel {
/**
* Constructor for IbmWatsonxChatCompletionModel.
*
* @param inferenceEntityId The unique identifier for the inference entity.
* @param taskType The type of task this model is designed for.
* @param service The name of the service this model belongs to.
* @param serviceSettings The settings specific to the Ibm Granite chat completion service.
* @param secrets The secrets required for accessing the service.
* @param context The context for parsing configuration settings.
*/
public IbmWatsonxChatCompletionModel(
String inferenceEntityId,
TaskType taskType,
String service,
Map<String, Object> serviceSettings,
@Nullable Map<String, Object> secrets,
ConfigurationParseContext context
) {
this(
inferenceEntityId,
taskType,
service,
IbmWatsonxChatCompletionServiceSettings.fromMap(serviceSettings, context),
DefaultSecretSettings.fromMap(secrets)
);
}
/**
* Creates a new IbmWatsonxChatCompletionModel with overridden service settings.
*
* @param model The original IbmWatsonxChatCompletionModel.
* @param request The UnifiedCompletionRequest containing the model override.
* @return A new IbmWatsonxChatCompletionModel with the overridden model ID.
*/
public static IbmWatsonxChatCompletionModel of(IbmWatsonxChatCompletionModel model, UnifiedCompletionRequest request) {
if (request.model() == null) {
// If no model is specified in the request, return the original model
return model;
}
var originalModelServiceSettings = model.getServiceSettings();
var overriddenServiceSettings = new IbmWatsonxChatCompletionServiceSettings(
originalModelServiceSettings.uri(),
originalModelServiceSettings.apiVersion(),
request.model(),
originalModelServiceSettings.projectId(),
originalModelServiceSettings.rateLimitSettings()
);
return new IbmWatsonxChatCompletionModel(
model.getInferenceEntityId(),
model.getTaskType(),
model.getConfigurations().getService(),
overriddenServiceSettings,
model.getSecretSettings()
);
}
// should only be used for testing
IbmWatsonxChatCompletionModel(
String inferenceEntityId,
TaskType taskType,
String service,
IbmWatsonxChatCompletionServiceSettings serviceSettings,
@Nullable DefaultSecretSettings secretSettings
) {
super(
new ModelConfigurations(inferenceEntityId, taskType, service, serviceSettings),
new ModelSecrets(secretSettings),
serviceSettings
);
}
@Override
public IbmWatsonxChatCompletionServiceSettings getServiceSettings() {
return (IbmWatsonxChatCompletionServiceSettings) super.getServiceSettings();
}
@Override
public DefaultSecretSettings getSecretSettings() {
return (DefaultSecretSettings) super.getSecretSettings();
}
public URI uri() {
URI uri;
try {
uri = buildUri(this.getServiceSettings().uri().toString(), this.getServiceSettings().apiVersion());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return uri;
}
/**
* Accepts a visitor to create an executable action. The returned action will not return documents in the response.
* @param visitor Interface for creating {@link ExecutableAction} instances for IBM watsonx models.
* @return the completion action
*/
public ExecutableAction accept(IbmWatsonxActionVisitor visitor, Map<String, Object> taskSettings) {
return visitor.create(this);
}
public static URI buildUri(String uri, String apiVersion) throws URISyntaxException {
return new URIBuilder().setScheme("https")
.setHost(uri)
.setPathSegments(ML, V1, TEXT, COMPLETIONS)
.setParameter("version", apiVersion)
.build();
}
}
|
IbmWatsonxChatCompletionModel
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
|
{
"start": 8190,
"end": 11698
}
|
class ____ extends Error {}
CyclicBarrier barrier = new CyclicBarrier(2);
// we need to make sure the error gets thrown on a different thread.
ExecutorService service = newSingleThreadExecutor();
try {
SequentialExecutor executor = new SequentialExecutor(service);
Runnable errorTask =
new Runnable() {
@Override
public void run() {
throw new MyError();
}
};
Runnable barrierTask =
new Runnable() {
@Override
public void run() {
try {
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
executor.execute(errorTask);
service.execute(barrierTask); // submit directly to the service
// the barrier task runs after the error task so we know that the error has been observed by
// SequentialExecutor by the time the barrier is satisfied
barrier.await(1, SECONDS);
executor.execute(barrierTask);
// timeout means the second task wasn't even tried
barrier.await(1, SECONDS);
} finally {
service.shutdown();
}
}
public void testRejectedExecutionThrownWithMultipleCalls() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
SettableFuture<?> future = SettableFuture.create();
Executor delegate =
new Executor() {
@Override
public void execute(Runnable task) {
if (future.set(null)) {
awaitUninterruptibly(latch);
}
throw new RejectedExecutionException();
}
};
SequentialExecutor executor = new SequentialExecutor(delegate);
ExecutorService blocked = newCachedThreadPool();
Future<?> first =
blocked.submit(
new Runnable() {
@Override
public void run() {
executor.execute(Runnables.doNothing());
}
});
future.get(10, SECONDS);
assertThrows(RejectedExecutionException.class, () -> executor.execute(Runnables.doNothing()));
latch.countDown();
ExecutionException expected =
assertThrows(ExecutionException.class, () -> first.get(10, SECONDS));
assertThat(expected).hasCauseThat().isInstanceOf(RejectedExecutionException.class);
}
public void testToString() {
Runnable[] currentTask = new Runnable[1];
Executor delegate =
new Executor() {
@Override
public void execute(Runnable task) {
currentTask[0] = task;
task.run();
currentTask[0] = null;
}
@Override
public String toString() {
return "theDelegate";
}
};
Executor sequential1 = newSequentialExecutor(delegate);
Executor sequential2 = newSequentialExecutor(delegate);
assertThat(sequential1.toString()).contains("theDelegate");
assertThat(sequential1.toString()).isNotEqualTo(sequential2.toString());
String[] whileRunningToString = new String[1];
sequential1.execute(
new Runnable() {
@Override
public void run() {
whileRunningToString[0] = "" + currentTask[0];
}
@Override
public String toString() {
return "my runnable's toString";
}
});
assertThat(whileRunningToString[0]).contains("my runnable's toString");
}
}
|
MyError
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ_C.java
|
{
"start": 71,
"end": 292
}
|
class ____ {
private int a;
private int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
|
ObjectJ_C
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/IncorrectMainMethodTest.java
|
{
"start": 2951,
"end": 3310
}
|
class ____ {
// BUG: Diagnostic contains:
public void main(String[] args) {}
}
""")
.doTest();
}
@Test
public void negativeNonPublic() {
assume().that(Runtime.version().feature()).isAtLeast(25);
testHelper
.addSourceLines(
"Test.java",
"""
|
Test
|
java
|
micronaut-projects__micronaut-core
|
inject/src/main/java/io/micronaut/context/conditions/MatchesAbsenceOfClassNamesCondition.java
|
{
"start": 1009,
"end": 2214
}
|
class ____
* @author Denis Stepanov
* @since 4.6
*/
@UsedByGeneratedCode
@Internal
public record MatchesAbsenceOfClassNamesCondition(String[] classes) implements Condition {
@Override
public boolean matches(ConditionContext context) {
final ClassLoader classLoader = context.getBeanContext().getClassLoader();
for (String name : classes) {
if (ClassUtils.isPresent(name, classLoader)) {
context.fail("Class [" + name + "] is not absent");
return false;
}
}
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MatchesAbsenceOfClassNamesCondition that = (MatchesAbsenceOfClassNamesCondition) o;
return Objects.deepEquals(classes, that.classes);
}
@Override
public int hashCode() {
return Arrays.hashCode(classes);
}
@Override
public String toString() {
return "MatchesAbsenceOfClassNamesCondition{" +
"classes=" + Arrays.toString(classes) +
'}';
}
}
|
names
|
java
|
apache__flink
|
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/SqlAlterCatalogComment.java
|
{
"start": 1368,
"end": 2198
}
|
class ____ extends SqlAlterCatalog {
private final SqlCharStringLiteral comment;
public SqlAlterCatalogComment(
SqlParserPos position, SqlIdentifier catalogName, SqlCharStringLiteral comment) {
super(position, catalogName);
this.comment = requireNonNull(comment, "comment cannot be null");
}
@Override
public List<SqlNode> getOperandList() {
return ImmutableNullableList.of(name, comment);
}
public String getComment() {
return SqlParseUtils.extractString(comment);
}
@Override
protected void unparseAlterOperation(SqlWriter writer, int leftPrec, int rightPrec) {
super.unparseAlterOperation(writer, leftPrec, rightPrec);
SqlUnparseUtils.unparseComment(comment, false, writer, leftPrec, rightPrec);
}
}
|
SqlAlterCatalogComment
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/http/HttpLogging.java
|
{
"start": 1847,
"end": 2041
}
|
class ____ wrap it with a composite
* that delegates to it or to the fallback logger
* "org.springframework.web.HttpLogging", if the primary is not enabled.
* @param primaryLoggerClass the
|
and
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/federation/FederationClientMethod.java
|
{
"start": 1235,
"end": 3835
}
|
class ____<R> {
public static final Logger LOG =
LoggerFactory.getLogger(FederationClientMethod.class);
/**
* List of parameters: static and dynamic values, matchings types.
*/
private final Object[] params;
/**
* List of method parameters types, matches parameters.
*/
private final Class<?>[] types;
/**
* String name of the method.
*/
private final String methodName;
private FederationStateStore stateStoreClient = null;
private Clock clock = null;
private Class<R> clazz;
public FederationClientMethod(String method, Class<?>[] pTypes, Object... pParams)
throws YarnException {
if (pParams.length != pTypes.length) {
throw new YarnException("Invalid parameters for method " + method);
}
this.params = pParams;
this.types = Arrays.copyOf(pTypes, pTypes.length);
this.methodName = method;
}
public FederationClientMethod(String method, Class pTypes, Object pParams)
throws YarnException {
this(method, new Class[]{pTypes}, new Object[]{pParams});
}
public FederationClientMethod(String method, Class pTypes, Object pParams, Class<R> rTypes,
FederationStateStore fedStateStore, Clock fedClock) throws YarnException {
this(method, pTypes, pParams);
this.stateStoreClient = fedStateStore;
this.clock = fedClock;
this.clazz = rTypes;
}
public Object[] getParams() {
return Arrays.copyOf(this.params, this.params.length);
}
public String getMethodName() {
return methodName;
}
/**
* Get the calling types for this method.
*
* @return An array of calling types.
*/
public Class<?>[] getTypes() {
return Arrays.copyOf(this.types, this.types.length);
}
/**
* We will use the invoke method to call the method in FederationStateStoreService.
*
* @return The result returned after calling the interface.
* @throws YarnException yarn exception.
*/
protected R invoke() throws YarnException {
try {
long startTime = clock.getTime();
Method method = FederationStateStore.class.getMethod(methodName, types);
R result = clazz.cast(method.invoke(stateStoreClient, params));
long stopTime = clock.getTime();
FederationStateStoreServiceMetrics.succeededStateStoreServiceCall(
methodName, stopTime - startTime);
return result;
} catch (Exception e) {
LOG.error("stateStoreClient call method {} error.", methodName, e);
FederationStateStoreServiceMetrics.failedStateStoreServiceCall(methodName);
throw new YarnException(e);
}
}
}
|
FederationClientMethod
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2197/Issue2197Mapper.java
|
{
"start": 308,
"end": 473
}
|
interface ____ {
Issue2197Mapper INSTANCE = Mappers.getMapper( Issue2197Mapper.class );
_0Target map(Source source);
// CHECKSTYLE:OFF
|
Issue2197Mapper
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
|
{
"start": 6514,
"end": 6893
}
|
class ____<B extends @Nullable Object> implements Serializable {
private final Map<Class<? extends @NonNull B>, B> backingMap;
SerializedForm(Map<Class<? extends @NonNull B>, B> backingMap) {
this.backingMap = backingMap;
}
Object readResolve() {
return create(backingMap);
}
private static final long serialVersionUID = 0;
}
}
|
SerializedForm
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java
|
{
"start": 6983,
"end": 7589
}
|
class ____ {
public String getMessage(int x) {
switch (x) {
case 0:
return "zero";
default:
return "non-zero";
}
}
}
""")
.doTest();
}
@Test
public void voidReturn() {
createCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java",
"""
package com.google.errorprone.bugpatterns.nullness;
abstract
|
LiteralNullReturnTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/onetoone/QueryOneToOnePKIsNullTest.java
|
{
"start": 681,
"end": 1281
}
|
class ____ {
@Test
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction(entityManager -> {
var parent1 = new Parent(1);
new Child(parent1);
entityManager.persist(parent1);
var parent2 = new Parent(2);
entityManager.persist(parent2);
});
scope.inTransaction(entityManager -> {
var query = entityManager.createQuery("from Parent p where p.child is null", Parent.class);
var parents = query.getResultList();
assertEquals(1, parents.size());
assertEquals(2L, parents.get(0).getId());
});
}
@Entity(name = "Parent")
static
|
QueryOneToOnePKIsNullTest
|
java
|
micronaut-projects__micronaut-core
|
http-server-tck/src/main/java/io/micronaut/http/server/tck/CorsAssertion.java
|
{
"start": 3456,
"end": 7198
}
|
class ____ {
private String vary;
private String accessControlAllowCredentials;
private String origin;
private List<HttpMethod> allowMethods;
private String maxAge;
private Boolean allowPrivateNetwork;
/**
*
* @param varyValue The expected value for the HTTP Header {@value HttpHeaders#VARY}.
* @return The Builder
*/
public Builder vary(String varyValue) {
this.vary = varyValue;
return this;
}
/**
*
* @param accessControlAllowCredentials The expected value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_CREDENTIALS}.
* @return The Builder
*/
public Builder allowCredentials(String accessControlAllowCredentials) {
this.accessControlAllowCredentials = accessControlAllowCredentials;
return this;
}
/**
*
* Set expectation of value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_CREDENTIALS} to {@value StringUtils#TRUE}.
* @return The Builder
*/
public Builder allowCredentials() {
return allowCredentials(StringUtils.TRUE);
}
/**
*
* Set expectation of value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_CREDENTIALS} to {@value StringUtils#TRUE}.
* @param allowCredentials Set expectation of value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_CREDENTIALS}
* @return The Builder
*/
public Builder allowCredentials(boolean allowCredentials) {
return allowCredentials ? allowCredentials(StringUtils.TRUE) : allowCredentials("");
}
/**
*
* @param origin The expected value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_ORIGIN}.
* @return The Builder
*/
public Builder allowOrigin(String origin) {
this.origin = origin;
return this;
}
/**
*
* @param method The expected value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_METHODS}.
* @return The Builder
*/
public Builder allowMethods(HttpMethod method) {
if (allowMethods == null) {
this.allowMethods = new ArrayList<>();
}
this.allowMethods.add(method);
return this;
}
/**
*
* @param allowPrivateNetwork The expected value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK}.
* @return The Builder
*/
public Builder allowPrivateNetwork(Boolean allowPrivateNetwork) {
this.allowPrivateNetwork = allowPrivateNetwork;
return this;
}
/**
*
* Set expectation of value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK} to {@value StringUtils#TRUE}.
* @return The Builder
*/
public Builder allowPrivateNetwork() {
return allowPrivateNetwork(Boolean.TRUE);
}
/**
*
* @param maxAge The expected value for the HTTP Header {@value HttpHeaders#ACCESS_CONTROL_MAX_AGE}.
* @return The Builder
*/
public Builder maxAge(String maxAge) {
this.maxAge = maxAge;
return this;
}
/**
*
* @return A CORS assertion.
*/
public CorsAssertion build() {
return new CorsAssertion(vary, accessControlAllowCredentials, origin, allowMethods, maxAge, allowPrivateNetwork);
}
}
}
|
Builder
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java
|
{
"start": 39643,
"end": 40026
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) -> headers
.defaultsDisabled()
.referrerPolicy((referrer) -> referrer.policy(ReferrerPolicy.SAME_ORIGIN)));
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static
|
ReferrerPolicyCustomConfig
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/tests/http/impl/CookieJarTest.java
|
{
"start": 315,
"end": 3751
}
|
class ____ {
@Test
public void testInsert() {
CookieJar jar = new CookieJar();
assertEquals(0, jar.size());
jar.add(new CookieImpl("foo", "bar"));
assertEquals(1, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setDomain("vertx.io"));
assertEquals(2, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setDomain("vertx.io").setPath("/secret"));
assertEquals(3, jar.size());
}
@Test
public void testReplace() {
CookieJar jar = new CookieJar();
assertEquals(0, jar.size());
jar.add(new CookieImpl("foo", "bar"));
assertEquals(1, jar.size());
// will replace
jar.add(new CookieImpl("foo", "barista"));
assertEquals(1, jar.size());
for (ServerCookie cookie : jar) {
assertEquals("barista", cookie.getValue());
}
}
@Test
public void testSameName() {
CookieJar jar = new CookieJar();
assertEquals(0, jar.size());
jar.add(new CookieImpl("foo", "bar"));
assertEquals(1, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setDomain("a"));
assertEquals(2, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setDomain("b"));
assertEquals(3, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setPath("a"));
assertEquals(4, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setPath("b"));
assertEquals(5, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setPath("a").setDomain("a"));
assertEquals(6, jar.size());
jar.add((ServerCookie) new CookieImpl("foo", "bar").setPath("b").setDomain("b"));
assertEquals(7, jar.size());
}
@Test
public void testFilterByName() {
CookieJar jar = new CookieJar();
jar.add(new CookieImpl("a", "a"));
jar.add((ServerCookie) new CookieImpl("a", "a").setPath("p"));
jar.add(new CookieImpl("b", "b"));
Set<Cookie> subJar = (Set) jar.getAll("a");
assertEquals(2, subJar.size());
}
@Test
public void testFilterByUniqueId() {
CookieJar jar = new CookieJar();
jar.add(new CookieImpl("a", "a"));
jar.add((ServerCookie) new CookieImpl("a", "a").setPath("p"));
jar.add(new CookieImpl("b", "b"));
Cookie cookie = jar.get("a", null, "p");
assertNotNull(cookie);
}
@Test
public void testRemoveFromIterator() {
CookieJar jar = new CookieJar();
jar.add(new CookieImpl("a", "a"));
jar.add((ServerCookie) new CookieImpl("a", "a").setPath("p"));
jar.add(new CookieImpl("b", "b"));
Iterator<ServerCookie> it = jar.iterator();
assertTrue(it.hasNext());
it.next();
// should be allowed
it.remove();
}
@Test(expected = UnsupportedOperationException.class)
public void testRemoveFromIteratorSubJar() {
CookieJar jar = new CookieJar();
jar.add(new CookieImpl("a", "a"));
jar.add((ServerCookie) new CookieImpl("a", "a").setPath("p"));
jar.add(new CookieImpl("b", "b"));
Set<Cookie> subJar = (Set) jar.getAll("a");
Iterator<Cookie> it = subJar.iterator();
assertTrue(it.hasNext());
it.next();
// should not be allowed
it.remove();
}
@Test
public void testPropertyPropagation() {
CookieJar jar = new CookieJar();
jar.add(new CookieImpl("a", "a"));
for (ServerCookie cookie : jar.getAll("a")) {
cookie.setValue("b");
}
assertEquals("b", jar.get("a").getValue());
}
}
|
CookieJarTest
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/SmtpAppender.java
|
{
"start": 3579,
"end": 4254
}
|
class ____ extends AbstractAppender {
private static final int DEFAULT_BUFFER_SIZE = 512;
/** The SMTP Manager */
private final MailManager manager;
private SmtpAppender(
final String name,
final Filter filter,
final Layout<? extends Serializable> layout,
final MailManager manager,
final boolean ignoreExceptions,
final Property[] properties) {
super(name, filter, layout, ignoreExceptions, properties);
this.manager = manager;
}
public MailManager getManager() {
return manager;
}
/**
* @since 2.13.2
*/
public static
|
SmtpAppender
|
java
|
spring-projects__spring-security
|
access/src/test/java/org/springframework/security/access/annotation/SecuredAnnotationSecurityMetadataSourceTests.java
|
{
"start": 7817,
"end": 8299
}
|
class ____ implements AnnotationMetadataExtractor<CustomSecurityAnnotation> {
@Override
public Collection<? extends ConfigAttribute> extractAttributes(CustomSecurityAnnotation securityAnnotation) {
SecurityEnum[] values = securityAnnotation.value();
return EnumSet.copyOf(Arrays.asList(values));
}
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Secured("CUSTOM")
public @
|
CustomSecurityAnnotationMetadataExtractor
|
java
|
quarkusio__quarkus
|
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/builditemtemplate/AdditionalTemplatePathDuplicatesTest.java
|
{
"start": 518,
"end": 2297
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot(root -> root
.addAsResource(new StringAsset("Hi {name}!"), "templates/hi.txt"))
.overrideConfigKey("quarkus.qute.duplicit-templates-strategy", "fail")
.addBuildChainCustomizer(buildCustomizer())
.setExpectedException(IllegalStateException.class, true);
static Consumer<BuildChainBuilder> buildCustomizer() {
return new Consumer<BuildChainBuilder>() {
@Override
public void accept(BuildChainBuilder builder) {
builder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
context.produce(TemplatePathBuildItem.builder()
.path("hi.txt")
.extensionInfo("test-ext")
.content("Hello {name}!").build());
}
}).produces(TemplatePathBuildItem.class)
.build();
builder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
context.produce(TemplatePathBuildItem.builder()
.path("hi.txt")
.extensionInfo("test-ext")
.content("Hello {name}!").build());
}
}).produces(TemplatePathBuildItem.class)
.build();
}
};
}
@Test
public void test() {
fail();
}
}
|
AdditionalTemplatePathDuplicatesTest
|
java
|
elastic__elasticsearch
|
test/external-modules/delayed-aggs/src/test/java/org/elasticsearch/test/delayedshard/DelayedShardAggregationBuilderTests.java
|
{
"start": 729,
"end": 1197
}
|
class ____ extends BaseAggregationTestCase<DelayedShardAggregationBuilder> {
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return Arrays.asList(DelayedShardAggregationPlugin.class);
}
@Override
protected DelayedShardAggregationBuilder createTestAggregatorBuilder() {
return new DelayedShardAggregationBuilder(randomAlphaOfLength(10), TimeValue.timeValueMillis(100));
}
}
|
DelayedShardAggregationBuilderTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CriteriaUpdateAndDeleteWithJoinTest.java
|
{
"start": 1193,
"end": 2986
}
|
class ____ {
private static final String CHILD_CODE = "123";
@BeforeEach
public void setup(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
Child child = new Child( 1L, CHILD_CODE );
Parent parent = new Parent( 2L, "456", child );
entityManager.persist( parent );
}
);
}
@AfterEach
public void teardown(EntityManagerFactoryScope scope) {
scope.releaseEntityManagerFactory();
}
@Test
public void testUpdate(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaUpdate<Parent> update = cb.createCriteriaUpdate(Parent.class);
Root<Parent> root = update.from(Parent.class);
Join<Parent,Child> joinColor = root.join("child", JoinType.INNER);
update.set(root.get("code"), "l1s2");
update.where(cb.equal(joinColor.get("code"), cb.parameter(String.class, "code")));
int count = entityManager.createQuery(update).setParameter("code", CHILD_CODE).executeUpdate();
assertThat(count).isEqualTo(1);
}
);
}
@Test
public void testDelete(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaDelete<Parent> delete = cb.createCriteriaDelete(Parent.class);
Root<Parent> root = delete.from(Parent.class);
Join<Parent,Child> joinColor = root.join("child", JoinType.INNER);
delete.where(cb.equal(joinColor.get("code"), cb.parameter(String.class, "code")));
int count = entityManager.createQuery(delete).setParameter("code", CHILD_CODE).executeUpdate();
assertThat(count).isEqualTo(1);
}
);
}
@Entity(name = "Parent")
public static
|
CriteriaUpdateAndDeleteWithJoinTest
|
java
|
quarkusio__quarkus
|
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/examples/funqy-amazon-lambda-example/java/src/main/java/org/acme/funqy/GreetingFunction.java
|
{
"start": 63,
"end": 202
}
|
class ____ {
@Funq
public String myFunqyGreeting(Person friend) {
return "Hello " + friend.getName();
}
}
|
GreetingFunction
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.