language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__logging-log4j2
log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java
{ "start": 1220, "end": 1411 }
class ____ { Logger logger = LoggerFactory.getLogger("LoggerTest"); @Test void testLogger() { assertThat((Serializable) logger, serializesRoundTrip()); } }
SerializeTest
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/profiler/ProfilerTest.java
{ "start": 922, "end": 4097 }
class ____ { @Test void testProfiler() { ProfilerEntry one = Profiler.start("1"); ProfilerEntry two = Profiler.enter(one, "1-2"); ProfilerEntry three = Profiler.enter(two, "1-2-3"); ProfilerEntry four = Profiler.enter(three, "1-2-3-4"); Assertions.assertEquals(three, Profiler.release(four)); ProfilerEntry five = Profiler.enter(three, "1-2-3-5"); Assertions.assertEquals(three, Profiler.release(five)); Assertions.assertEquals(two, Profiler.release(three)); ProfilerEntry six = Profiler.enter(two, "1-2-6"); Assertions.assertEquals(two, Profiler.release(six)); ProfilerEntry seven = Profiler.enter(six, "1-2-6-7"); Assertions.assertEquals(six, Profiler.release(seven)); ProfilerEntry eight = Profiler.enter(six, "1-2-6-8"); Assertions.assertEquals(six, Profiler.release(eight)); Assertions.assertEquals(2, two.getSub().size()); Assertions.assertEquals(three, two.getSub().get(0)); Assertions.assertEquals(six, two.getSub().get(1)); Profiler.release(two); ProfilerEntry nine = Profiler.enter(one, "1-9"); Profiler.release(nine); Profiler.release(one); /* * Start time: 287395734500659 * +-[ Offset: 0.000000ms; Usage: 4.721583ms, 100% ] 1 * +-[ Offset: 0.013136ms; Usage: 4.706288ms, 99% ] 1-2 * | +-[ Offset: 0.027903ms; Usage: 4.662918ms, 98% ] 1-2-3 * | | +-[ Offset: 0.029742ms; Usage: 0.003785ms, 0% ] 1-2-3-4 * | | +-[ Offset: 4.688477ms; Usage: 0.001398ms, 0% ] 1-2-3-5 * | +-[ Offset: 4.693346ms; Usage: 0.000316ms, 0% ] 1-2-6 * | +-[ Offset: 4.695191ms; Usage: 0.000212ms, 0% ] 1-2-6-7 * | +-[ Offset: 4.696655ms; Usage: 0.000195ms, 0% ] 1-2-6-8 * +-[ Offset: 4.721044ms; Usage: 0.000270ms, 0% ] 1-9 */ Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(two)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(three)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(four)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(five)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(six)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(seven)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(eight)); Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(nine)); } @Test void testBizProfiler() { Assertions.assertNull(Profiler.getBizProfiler()); ProfilerEntry one = Profiler.start("1"); Profiler.setToBizProfiler(one); Profiler.release(Profiler.enter(Profiler.getBizProfiler(), "1-2")); Assertions.assertEquals(one, Profiler.getBizProfiler()); Assertions.assertEquals(1, one.getSub().size()); Profiler.removeBizProfiler(); Assertions.assertNull(Profiler.getBizProfiler()); } }
ProfilerTest
java
quarkusio__quarkus
extensions/smallrye-context-propagation/deployment/src/test/java/io/quarkus/smallrye/context/deployment/test/AllClearedConfigTest.java
{ "start": 377, "end": 946 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withEmptyApplication() .overrideConfigKey("mp.context.ThreadContext.propagated", ""); @Inject SmallRyeThreadContext ctx; @Test public void test() { ThreadContextProviderPlan plan = ctx.getPlan(); Assertions.assertTrue(plan.propagatedProviders.isEmpty()); Assertions.assertFalse(plan.clearedProviders.isEmpty()); Assertions.assertTrue(plan.unchangedProviders.isEmpty()); } }
AllClearedConfigTest
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 16048, "end": 16321 }
class ____ {}"); Source componentFile = CompilerTests.javaSource("test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component(modules = TestModule.class)", "
ParentDepIncluded
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 22017, "end": 22854 }
class ____ {", " @SuppressWarnings(\"mutable\")", " public abstract byte[] bytes();", " public static Baz create(byte[] bytes) {", " return new AutoValue_Baz(bytes);", " }", "}"); Compilation compilation = javac() .withProcessors(new AutoValueProcessor()) .withOptions("-Xlint:-processing", "-implicit:none") .compile(javaFileObject); assertThat(compilation).succeededWithoutWarnings(); } @Test public void autoValueMustBeClass() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "foo.bar.Baz", "package foo.bar;", "", "import com.google.auto.value.AutoValue;", "", "@AutoValue", "public
Baz
java
apache__rocketmq
tools/src/main/java/org/apache/rocketmq/tools/command/export/ExportConfigsCommand.java
{ "start": 1484, "end": 5441 }
class ____ implements SubCommand { @Override public String commandName() { return "exportConfigs"; } @Override public String commandDesc() { return "Export configs."; } @Override public Options buildCommandlineOptions(Options options) { Option opt = new Option("c", "clusterName", true, "choose a cluster to export"); opt.setRequired(true); options.addOption(opt); opt = new Option("f", "filePath", true, "export configs.json path | default /tmp/rocketmq/export"); opt.setRequired(false); options.addOption(opt); return options; } @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String clusterName = commandLine.getOptionValue('c').trim(); String filePath = !commandLine.hasOption('f') ? "/tmp/rocketmq/export" : commandLine.getOptionValue('f') .trim(); defaultMQAdminExt.start(); Map<String, Object> result = new HashMap<>(); // name servers List<String> nameServerAddressList = defaultMQAdminExt.getNameServerAddressList(); //broker int masterBrokerSize = 0; int slaveBrokerSize = 0; Map<String, Properties> brokerConfigs = new HashMap<>(); Map<String, List<String>> masterAndSlaveMap = CommandUtil.fetchMasterAndSlaveDistinguish(defaultMQAdminExt, clusterName); for (Entry<String, List<String>> masterAndSlaveEntry : masterAndSlaveMap.entrySet()) { Properties masterProperties = defaultMQAdminExt.getBrokerConfig(masterAndSlaveEntry.getKey()); masterBrokerSize++; slaveBrokerSize += masterAndSlaveEntry.getValue().size(); brokerConfigs.put(masterProperties.getProperty("brokerName"), needBrokerProprties(masterProperties)); } Map<String, Integer> clusterScaleMap = new HashMap<>(); clusterScaleMap.put("namesrvSize", nameServerAddressList.size()); clusterScaleMap.put("masterBrokerSize", masterBrokerSize); clusterScaleMap.put("slaveBrokerSize", slaveBrokerSize); result.put("brokerConfigs", brokerConfigs); result.put("clusterScale", clusterScaleMap); String path = filePath + "/configs.json"; MixAll.string2FileNotSafe(JSON.toJSONString(result, true), path); System.out.printf("export %s success", path); } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } private Properties needBrokerProprties(Properties properties) { List<String> propertyKeys = Arrays.asList( "brokerClusterName", "brokerId", "brokerName", "brokerRole", "fileReservedTime", "filterServerNums", "flushDiskType", "maxMessageSize", "messageDelayLevel", "msgTraceTopicName", "slaveReadEnable", "traceOn", "traceTopicEnable", "useTLS", "autoCreateTopicEnable", "autoCreateSubscriptionGroup" ); Properties newProperties = new Properties(); propertyKeys.stream() .filter(key -> properties.getProperty(key) != null) .forEach(key -> newProperties.setProperty(key, properties.getProperty(key))); return newProperties; } }
ExportConfigsCommand
java
spring-projects__spring-security
saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/Saml2X509CredentialTests.java
{ "start": 1264, "end": 6888 }
class ____ { private Saml2X509Credential credential; private PrivateKey key; private X509Certificate certificate; @BeforeEach public void setup() throws Exception { String keyData = "-----BEGIN PRIVATE KEY-----\n" + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANG7v8QjQGU3MwQE\n" + "VUBxvH6Uuiy/MhZT7TV0ZNjyAF2ExA1gpn3aUxx6jYK5UnrpxRRE/KbeLucYbOhK\n" + "cDECt77Rggz5TStrOta0BQTvfluRyoQtmQ5Nkt6Vqg7O2ZapFt7k64Sal7AftzH6\n" + "Q2BxWN1y04bLdDrH4jipqRj/2qEFAgMBAAECgYEAj4ExY1jjdN3iEDuOwXuRB+Nn\n" + "x7pC4TgntE2huzdKvLJdGvIouTArce8A6JM5NlTBvm69mMepvAHgcsiMH1zGr5J5\n" + "wJz23mGOyhM1veON41/DJTVG+cxq4soUZhdYy3bpOuXGMAaJ8QLMbQQoivllNihd\n" + "vwH0rNSK8LTYWWPZYIECQQDxct+TFX1VsQ1eo41K0T4fu2rWUaxlvjUGhK6HxTmY\n" + "8OMJptunGRJL1CUjIb45Uz7SP8TPz5FwhXWsLfS182kRAkEA3l+Qd9C9gdpUh1uX\n" + "oPSNIxn5hFUrSTW1EwP9QH9vhwb5Vr8Jrd5ei678WYDLjUcx648RjkjhU9jSMzIx\n" + "EGvYtQJBAMm/i9NR7IVyyNIgZUpz5q4LI21rl1r4gUQuD8vA36zM81i4ROeuCly0\n" + "KkfdxR4PUfnKcQCX11YnHjk9uTFj75ECQEFY/gBnxDjzqyF35hAzrYIiMPQVfznt\n" + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"; this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(StandardCharsets.UTF_8))); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); String certificateData = "-----BEGIN CERTIFICATE-----\n" + "MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBhMC\n" + "VVMxEzARBgNVBAgMCldhc2hpbmd0b24xEjAQBgNVBAcMCVZhbmNvdXZlcjEdMBsG\n" + "A1UECgwUU3ByaW5nIFNlY3VyaXR5IFNBTUwxCzAJBgNVBAsMAnNwMSAwHgYDVQQD\n" + "DBdzcC5zcHJpbmcuc2VjdXJpdHkuc2FtbDAeFw0xODA1MTQxNDMwNDRaFw0yODA1\n" + "MTExNDMwNDRaMIGEMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjES\n" + "MBAGA1UEBwwJVmFuY291dmVyMR0wGwYDVQQKDBRTcHJpbmcgU2VjdXJpdHkgU0FN\n" + "TDELMAkGA1UECwwCc3AxIDAeBgNVBAMMF3NwLnNwcmluZy5zZWN1cml0eS5zYW1s\n" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRu7/EI0BlNzMEBFVAcbx+lLos\n" + "vzIWU+01dGTY8gBdhMQNYKZ92lMceo2CuVJ66cUURPym3i7nGGzoSnAxAre+0YIM\n" + "+U0razrWtAUE735bkcqELZkOTZLelaoOztmWqRbe5OuEmpewH7cx+kNgcVjdctOG\n" + "y3Q6x+I4qakY/9qhBQIDAQABMA0GCSqGSIb3DQEBCwUAA4GBAAeViTvHOyQopWEi\n" + "XOfI2Z9eukwrSknDwq/zscR0YxwwqDBMt/QdAODfSwAfnciiYLkmEjlozWRtOeN+\n" + "qK7UFgP1bRl5qksrYX5S0z2iGJh0GvonLUt3e20Ssfl5tTEDDnAEUMLfBkyaxEHD\n" + "RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B\n" + "-----END CERTIFICATE-----"; this.certificate = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(StandardCharsets.UTF_8))); } @Test public void constructorWhenRelyingPartyWithCredentialsThenItSucceeds() { new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING); new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } @Test public void constructorWhenAssertingPartyWithCredentialsThenItSucceeds() { new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); } @Test public void constructorWhenRelyingPartyWithoutCredentialsThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> new Saml2X509Credential(null, (X509Certificate) null, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithoutPrivateKeyThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> new Saml2X509Credential(null, this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithoutCertificateThenItFails() { assertThatIllegalArgumentException().isThrownBy( () -> new Saml2X509Credential(this.key, null, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenAssertingPartyWithoutCertificateThenItFails() { assertThatIllegalArgumentException() .isThrownBy(() -> new Saml2X509Credential(null, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithEncryptionUsageThenItFails() { assertThatIllegalStateException().isThrownBy(() -> new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION)); } @Test public void constructorWhenRelyingPartyWithVerificationUsageThenItFails() { assertThatIllegalStateException().isThrownBy(() -> new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION)); } @Test public void constructorWhenAssertingPartyWithSigningUsageThenItFails() { assertThatIllegalStateException().isThrownBy( () -> new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenAssertingPartyWithDecryptionUsageThenItFails() { assertThatIllegalStateException().isThrownBy(() -> new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION)); } }
Saml2X509CredentialTests
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeInformationTest.java
{ "start": 2312, "end": 2428 }
class ____ { public Integer intField; public Recursive2Pojo rec; } public static
Recursive1Pojo
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_913/DomainWithoutSetterDtoWithPresenceCheckMapper.java
{ "start": 520, "end": 1475 }
interface ____ { DomainWithoutSetterDtoWithPresenceCheckMapper INSTANCE = Mappers.getMapper( DomainWithoutSetterDtoWithPresenceCheckMapper.class ); @Mappings({ @Mapping(target = "strings", source = "strings"), @Mapping(target = "longs", source = "strings"), @Mapping(target = "stringsInitialized", source = "stringsInitialized"), @Mapping(target = "longsInitialized", source = "stringsInitialized"), @Mapping(target = "stringsWithDefault", source = "stringsWithDefault", defaultValue = "3") }) DomainWithoutSetter create(DtoWithPresenceCheck source); @InheritConfiguration( name = "create" ) void update(DtoWithPresenceCheck source, @MappingTarget DomainWithoutSetter target); @InheritConfiguration( name = "create" ) DomainWithoutSetter updateWithReturn(DtoWithPresenceCheck source, @MappingTarget DomainWithoutSetter target); }
DomainWithoutSetterDtoWithPresenceCheckMapper
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/Logger.java
{ "start": 2258, "end": 2349 }
interface ____. * </p> * * Since 2.4, methods have been added to the {@code Logger}
directly
java
google__truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
{ "start": 4211, "end": 13084 }
class ____ { /** * Returns a new instance that invokes the given {@link FailureStrategy} when a check fails. Most * users should not need this. If you think you do, see the documentation on {@link * FailureStrategy}. */ public static StandardSubjectBuilder forCustomFailureStrategy(FailureStrategy strategy) { return new StandardSubjectBuilder(FailureMetadata.forFailureStrategy(strategy)); } private final FailureMetadata metadataDoNotReferenceDirectly; /** * Constructor for use by {@link Expect}. To create an instance of {@link StandardSubjectBuilder}, * use {@link #forCustomFailureStrategy}. */ StandardSubjectBuilder(FailureMetadata metadata) { this.metadataDoNotReferenceDirectly = checkNotNull(metadata); } public final <ComparableT extends Comparable<?>> ComparableSubject<ComparableT> that( @Nullable ComparableT actual) { return about(ComparableSubject.<ComparableT>comparables()).that(actual); } public final BigDecimalSubject that(@Nullable BigDecimal actual) { return about(bigDecimals()).that(actual); } public final Subject that(@Nullable Object actual) { return about(objects()).that(actual); } @GwtIncompatible("ClassSubject.java") @J2ktIncompatible public final ClassSubject that(@Nullable Class<?> actual) { return about(classes()).that(actual); } public final ThrowableSubject that(@Nullable Throwable actual) { return about(throwables()).that(actual); } public final LongSubject that(@Nullable Long actual) { return about(longs()).that(actual); } public final DoubleSubject that(@Nullable Double actual) { return about(doubles()).that(actual); } public final FloatSubject that(@Nullable Float actual) { return about(floats()).that(actual); } public final IntegerSubject that(@Nullable Integer actual) { return about(integers()).that(actual); } public final BooleanSubject that(@Nullable Boolean actual) { return about(booleans()).that(actual); } public final StringSubject that(@Nullable String actual) { return about(strings()).that(actual); } public final IterableSubject that(@Nullable Iterable<?> actual) { return about(iterables()).that(actual); } @SuppressWarnings("AvoidObjectArrays") public final <T extends @Nullable Object> ObjectArraySubject<T> that(T @Nullable [] actual) { return about(ObjectArraySubject.<T>objectArrays()).that(actual); } public final PrimitiveBooleanArraySubject that(boolean @Nullable [] actual) { return about(booleanArrays()).that(actual); } public final PrimitiveShortArraySubject that(short @Nullable [] actual) { return about(shortArrays()).that(actual); } public final PrimitiveIntArraySubject that(int @Nullable [] actual) { return about(intArrays()).that(actual); } public final PrimitiveLongArraySubject that(long @Nullable [] actual) { return about(longArrays()).that(actual); } public final PrimitiveCharArraySubject that(char @Nullable [] actual) { return about(charArrays()).that(actual); } public final PrimitiveByteArraySubject that(byte @Nullable [] actual) { return about(byteArrays()).that(actual); } public final PrimitiveFloatArraySubject that(float @Nullable [] actual) { return about(floatArrays()).that(actual); } public final PrimitiveDoubleArraySubject that(double @Nullable [] actual) { return about(doubleArrays()).that(actual); } public final GuavaOptionalSubject that(com.google.common.base.@Nullable Optional<?> actual) { return about(guavaOptionals()).that(actual); } public final MapSubject that(@Nullable Map<?, ?> actual) { return about(maps()).that(actual); } public final MultimapSubject that(@Nullable Multimap<?, ?> actual) { return about(multimaps()).that(actual); } public final MultisetSubject that(@Nullable Multiset<?> actual) { return about(multisets()).that(actual); } public final TableSubject that(@Nullable Table<?, ?, ?> actual) { return about(tables()).that(actual); } /** * @since 1.3.0 (with access to {@link OptionalSubject} previously part of {@code * truth-java8-extension}) */ @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type public final OptionalSubject that(@Nullable Optional<?> actual) { return about(optionals()).that(actual); } /** * @since 1.4.0 (with access to {@link OptionalIntSubject} previously part of {@code * truth-java8-extension}) */ public final OptionalIntSubject that(@Nullable OptionalInt actual) { return about(optionalInts()).that(actual); } /** * @since 1.4.0 (with access to {@link OptionalLongSubject} previously part of {@code * truth-java8-extension}) */ public final OptionalLongSubject that(@Nullable OptionalLong actual) { return about(optionalLongs()).that(actual); } /** * @since 1.4.0 (with access to {@link OptionalDoubleSubject} previously part of {@code * truth-java8-extension}) */ public final OptionalDoubleSubject that(@Nullable OptionalDouble actual) { return about(optionalDoubles()).that(actual); } /** * @since 1.3.0 (with access to {@link StreamSubject} previously part of {@code * truth-java8-extension}) */ public final StreamSubject that(@Nullable Stream<?> actual) { return about(streams()).that(actual); } /** * @since 1.4.0 (with access to {@link IntStreamSubject} previously part of {@code * truth-java8-extension}) */ public final IntStreamSubject that(@Nullable IntStream actual) { return about(intStreams()).that(actual); } /** * @since 1.4.0 (with access to {@link LongStreamSubject} previously part of {@code * truth-java8-extension}) */ public final LongStreamSubject that(@Nullable LongStream actual) { return about(longStreams()).that(actual); } // TODO(b/64757353): Add support for DoubleStream? /** * @since 1.4.0 (with access to {@link PathSubject} previously part of {@code * truth-java8-extension}) */ @GwtIncompatible @J2ObjCIncompatible @J2ktIncompatible public final PathSubject that(@Nullable Path actual) { return about(paths()).that(actual); } /** * Returns a new instance that will output the given message before the main failure message. If * this method is called multiple times, the messages will appear in the order that they were * specified. */ public final StandardSubjectBuilder withMessage(@Nullable String message) { return withMessage("%s", message); } /** * Returns a new instance that will output the given message before the main failure message. If * this method is called multiple times, the messages will appear in the order that they were * specified. * * <p><b>Note:</b> the arguments will be substituted into the format template using {@link * com.google.common.base.Strings#lenientFormat Strings.lenientFormat}. Note this only supports * the {@code %s} specifier. * * @throws IllegalArgumentException if the number of placeholders in the format string does not * equal the number of given arguments */ public final StandardSubjectBuilder withMessage( String format, @Nullable Object... args) { return new StandardSubjectBuilder(metadata().withMessage(format, args)); } /** * Given a factory for some {@link Subject} class, returns a builder whose {@link * SimpleSubjectBuilder#that that(actual)} method creates instances of that class. Created * subjects use the previously set failure strategy and any previously set failure message. */ public final <S extends Subject, A> SimpleSubjectBuilder<S, A> about( Subject.Factory<S, A> factory) { return SimpleSubjectBuilder.create(metadata(), factory); } /** * A generic, advanced method of extension of Truth to new types, which is documented on {@link * CustomSubjectBuilder}. Extension creators should prefer {@link Subject.Factory} if possible. */ public final <CustomSubjectBuilderT extends CustomSubjectBuilder> CustomSubjectBuilderT about( CustomSubjectBuilder.Factory<CustomSubjectBuilderT> factory) { return factory.createSubjectBuilder(metadata()); } /** * Reports a failure. * * <p>To set a message, first call {@link #withMessage} (or, more commonly, use the shortcut * {@link Truth#assertWithMessage}). */ public final void fail() { metadata().fail(ImmutableList.of()); } private FailureMetadata metadata() { checkStatePreconditions(); return metadataDoNotReferenceDirectly; } /** * Extension point invoked before every assertion. This allows {@link Expect} to check that it's * been set up properly as a {@code TestRule}. */ void checkStatePreconditions() {} }
StandardSubjectBuilder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/TestingResultPartitionProvider.java
{ "start": 5710, "end": 6137 }
interface ____ { Optional<ResultSubpartitionView> createSubpartitionViewOrRegisterListener( ResultPartitionID partitionId, ResultSubpartitionIndexSet indexSet, BufferAvailabilityListener availabilityListener, PartitionRequestListener partitionRequestListener) throws IOException; } /** Testing
CreateSubpartitionViewOrRegisterListener
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/language/LanguageRouteNoTransformTest.java
{ "start": 1053, "end": 1745 }
class ____ extends ContextTestSupport { @Test public void testLanguage() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("World"); template.sendBody("direct:start", "World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { String script = URLEncoder.encode("Hello ${body}", StandardCharsets.UTF_8); from("direct:start").to("language:simple:" + script + "?transform=false").to("mock:result"); } }; } }
LanguageRouteNoTransformTest
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/catalog/JavaCatalogTableTest.java
{ "start": 13136, "end": 14827 }
class ____ implements CatalogTable { private final boolean streamingMode; private CustomCatalogTable(boolean streamingMode) { this.streamingMode = streamingMode; } @Override public boolean isPartitioned() { return false; } @Override public List<String> getPartitionKeys() { return Collections.emptyList(); } @Override public CatalogTable copy(Map<String, String> options) { return this; } @Override public Map<String, String> getOptions() { Map<String, String> map = new HashMap<>(); map.put("connector", "values"); map.put("bounded", Boolean.toString(!streamingMode)); return map; } @Override public TableSchema getSchema() { return TableSchema.builder() .field("count", DataTypes.BIGINT()) .field("rowtime", DataTypes.TIMESTAMP(3)) .field("proctime", DataTypes.TIMESTAMP(3), "proctime()") .watermark("rowtime", "rowtime - INTERVAL '5' SECONDS", DataTypes.TIMESTAMP()) .build(); } @Override public String getComment() { return null; } @Override public CatalogBaseTable copy() { return this; } @Override public Optional<String> getDescription() { return Optional.empty(); } @Override public Optional<String> getDetailedDescription() { return Optional.empty(); } } }
CustomCatalogTable
java
quarkusio__quarkus
extensions/devui/deployment/src/test/java/io/quarkus/devui/testrunner/params/ParamET.java
{ "start": 342, "end": 826 }
class ____ { @Test public void testHelloEndpoint() { given() .when().get("/hello") .then() .statusCode(200) .body(is("hello")); } @ParameterizedTest @ValueSource(ints = { 1, 4, 11, 17 }) void shouldValidateOddNumbers(int x) { given() .when().get("/odd/" + x) .then() .statusCode(200) .body(is("true")); } }
ParamET
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/util/EndConsumerHelper.java
{ "start": 5045, "end": 5812 }
class ____ the consumer to have a personalized * error message if the upstream already contains a non-cancelled Subscription. * @return true if successful, false if the content of the AtomicReference was non null */ public static boolean setOnce(AtomicReference<Subscription> upstream, Subscription next, Class<?> subscriber) { Objects.requireNonNull(next, "next is null"); if (!upstream.compareAndSet(null, next)) { next.cancel(); if (upstream.get() != SubscriptionHelper.CANCELLED) { reportDoubleSubscription(subscriber); } return false; } return true; } /** * Builds the error message with the consumer class. * @param consumer the
of
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/context/SecurityContextHolderFilterTests.java
{ "start": 2158, "end": 6108 }
class ____ { private static final String FILTER_APPLIED = "org.springframework.security.web.context.SecurityContextHolderFilter.APPLIED"; @Mock private SecurityContextRepository repository; @Mock private SecurityContextHolderStrategy strategy; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Captor private ArgumentCaptor<HttpServletRequest> requestArg; private SecurityContextHolderFilter filter; @BeforeEach void setup() { this.filter = new SecurityContextHolderFilter(this.repository); } @AfterEach void cleanup() { SecurityContextHolder.clearContext(); } @Test void doFilterThenSetsAndClearsSecurityContextHolder() throws Exception { Authentication authentication = TestAuthentication.authenticatedUser(); SecurityContext expectedContext = new SecurityContextImpl(authentication); given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy)); FilterChain filterChain = (request, response) -> assertThat(SecurityContextHolder.getContext()) .isEqualTo(expectedContext); this.filter.doFilter(this.request, this.response, filterChain); assertThat(SecurityContextHolder.getContext()).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test void doFilterThenSetsAndClearsSecurityContextHolderStrategy() throws Exception { Authentication authentication = TestAuthentication.authenticatedUser(); SecurityContext expectedContext = new SecurityContextImpl(authentication); given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy)); FilterChain filterChain = (request, response) -> { }; this.filter.setSecurityContextHolderStrategy(this.strategy); this.filter.doFilter(this.request, this.response, filterChain); ArgumentCaptor<Supplier<SecurityContext>> deferredContextArg = ArgumentCaptor.forClass(Supplier.class); verify(this.strategy).setDeferredContext(deferredContextArg.capture()); assertThat(deferredContextArg.getValue().get()).isEqualTo(expectedContext); verify(this.strategy).clearContext(); } @Test void doFilterWhenFilterAppliedThenDoNothing() throws Exception { given(this.request.getAttribute(FILTER_APPLIED)).willReturn(true); this.filter.doFilter(this.request, this.response, new MockFilterChain()); verify(this.request, times(1)).getAttribute(FILTER_APPLIED); verifyNoInteractions(this.repository, this.response); } @Test void doFilterWhenNotAppliedThenSetsAndRemovesAttribute() throws Exception { given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(SecurityContextHolder::createEmptyContext, this.strategy)); this.filter.doFilter(this.request, this.response, new MockFilterChain()); InOrder inOrder = inOrder(this.request, this.repository); inOrder.verify(this.request).setAttribute(FILTER_APPLIED, true); inOrder.verify(this.repository).loadDeferredContext(this.request); inOrder.verify(this.request).removeAttribute(FILTER_APPLIED); } @ParameterizedTest @EnumSource(DispatcherType.class) void doFilterWhenAnyDispatcherTypeThenFilter(DispatcherType dispatcherType) throws Exception { lenient().when(this.request.getDispatcherType()).thenReturn(dispatcherType); Authentication authentication = TestAuthentication.authenticatedUser(); SecurityContext expectedContext = new SecurityContextImpl(authentication); given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy)); FilterChain filterChain = (request, response) -> assertThat(SecurityContextHolder.getContext()) .isEqualTo(expectedContext); this.filter.doFilter(this.request, this.response, filterChain); } }
SecurityContextHolderFilterTests
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/TemplateResolverInterceptor.java
{ "start": 1078, "end": 2037 }
interface ____<V, C extends TemplateResolverContext<V, C>> { /** * Main plugin category for {@link TemplateResolverInterceptor} implementations. */ String CATEGORY = "JsonTemplateResolverInterceptor"; /** * The targeted value class. */ Class<V> getValueClass(); /** * The targeted {@link TemplateResolverContext} class. */ Class<C> getContextClass(); /** * Intercept the read template before compiler (i.e., * {@link TemplateResolvers#ofTemplate(TemplateResolverContext, String)} * starts injecting resolvers. * <p> * This is the right place to introduce, say, contextual additional fields. * * @param node the root object of the read template * @return the root object of the template to be compiled */ default Object processTemplateBeforeResolverInjection(final C context, final Object node) { return node; } }
TemplateResolverInterceptor
java
processing__processing4
java/src/processing/mode/java/debug/Debugger.java
{ "start": 29918, "end": 39796 }
class ____ of this */ protected String thisName(ThreadReference t) { try { if (!t.isSuspended() || t.frameCount() == 0) { return ""; } ObjectReference ref = t.frame(0).thisObject(); return ref == null ? "" : ref.referenceType().name(); } catch (IncompatibleThreadStateException ex) { logitse(ex); return ""; } } /** * Get a description of the current location in a suspended thread. * Format: class.method:translated_line_number * @param t a suspended thread * @return descriptive string for the given location */ protected String currentLocation(ThreadReference t) { try { if (!t.isSuspended() || t.frameCount() == 0) { return ""; } return locationToString(t.frame(0).location()); } catch (IncompatibleThreadStateException ex) { logitse(ex); return ""; } } /** * Get a string describing a location. * Format: class.method:translated_line_number * @param loc a location * @return descriptive string for the given location */ protected String locationToString(Location loc) { LineID line = locationToLineID(loc); int lineNumber = (line != null) ? (line.lineIdx() + 1) : loc.lineNumber(); return loc.declaringType().name() + "." + loc.method().name() + ":" + lineNumber; } /** * Compile a list of current locals usable for insertion into a * {@link JTree}. Recursively resolves object references. * @param t the suspended thread to get locals for * @param depth how deep to resolve nested object references. 0 will not * resolve nested objects. * @return the list of current locals */ protected List<VariableNode> getLocals(ThreadReference t, int depth) { //System.out.println("getting locals"); List<VariableNode> vars = new ArrayList<>(); try { if (t.frameCount() > 0) { StackFrame sf = t.frame(0); for (LocalVariable lv : sf.visibleVariables()) { //System.out.println("local var: " + lv.name()); Value val = sf.getValue(lv); VariableNode var = new LocalVariableNode(lv.name(), lv.typeName(), val, lv, sf); if (depth > 0) { var.addChildren(getFields(val, depth - 1, true)); } vars.add(var); } } } catch (IncompatibleThreadStateException ex) { logitse(ex); } catch (AbsentInformationException ex) { loge("local variable information not available", ex); } return vars; } /** * Compile a list of fields in the current this object usable for insertion * into a {@link JTree}. Recursively resolves object references. * @param t the suspended thread to get locals for * @param depth how deep to resolve nested object references. 0 will not * resolve nested objects. * @return the list of fields in the current this object */ protected List<VariableNode> getThisFields(ThreadReference t, int depth, boolean includeInherited) { try { if (t.frameCount() > 0) { StackFrame sf = t.frame(0); ObjectReference thisObj = sf.thisObject(); return getFields(thisObj, depth, includeInherited); } } catch (IncompatibleThreadStateException ex) { logitse(ex); } return new ArrayList<>(); } /** * Recursively get the fields of a {@link Value} for insertion into a * {@link JTree}. * @param value must be an instance of {@link ObjectReference} * @param depth the current depth * @param maxDepth the depth to stop at (inclusive) * @return list of child fields of the given value */ protected List<VariableNode> getFields(Value value, int depth, int maxDepth, boolean includeInherited) { // remember: Value <- ObjectReference, ArrayReference List<VariableNode> vars = new ArrayList<>(); if (depth <= maxDepth) { if (value instanceof ArrayReference) { return getArrayFields((ArrayReference) value); } else if (value instanceof ObjectReference) { ObjectReference obj = (ObjectReference) value; // get the fields of this object List<Field> fields = includeInherited ? obj.referenceType().visibleFields() : obj.referenceType().fields(); for (Field field : fields) { Value val = obj.getValue(field); // get the value, may be null VariableNode var = new FieldNode(field.name(), field.typeName(), val, field, obj); // recursively add children if (val != null) { var.addChildren(getFields(val, depth + 1, maxDepth, includeInherited)); } vars.add(var); } } } return vars; } /** * Recursively get the fields of a {@link Value} for insertion into a * {@link JTree}. * * @param value must be an instance of {@link ObjectReference} * @param maxDepth max recursion depth. 0 will give only direct children * @return list of child fields of the given value */ public List<VariableNode> getFields(Value value, int maxDepth, boolean includeInherited) { return getFields(value, 0, maxDepth, includeInherited); } /** * Get the fields of an array for insertion into a {@link JTree}. * @param array the array reference * @return list of array fields */ protected List<VariableNode> getArrayFields(ArrayReference array) { List<VariableNode> fields = new ArrayList<>(); if (array != null) { String arrayType = array.type().name(); if (arrayType.endsWith("[]")) { arrayType = arrayType.substring(0, arrayType.length() - 2); } int i = 0; for (Value val : array.getValues()) { VariableNode var = new ArrayFieldNode("[" + i + "]", arrayType, val, array, i); fields.add(var); i++; } } return fields; } /** * Get the current call stack trace usable for insertion into a * {@link JTree}. * @param t the suspended thread to retrieve the call stack from * @return call stack as list of {@link DefaultMutableTreeNode}s */ protected List<DefaultMutableTreeNode> getStackTrace(ThreadReference t) { List<DefaultMutableTreeNode> stack = new ArrayList<>(); try { for (StackFrame f : t.frames()) { stack.add(new DefaultMutableTreeNode(locationToString(f.location()))); } } catch (IncompatibleThreadStateException ex) { logitse(ex); } return stack; } /** * Print visible fields of current "this" object on a suspended thread. * Prints type, name and value. * @param t suspended thread */ protected void printThis(ThreadReference t) { if (!t.isSuspended()) { return; } try { if (t.frameCount() == 0) { // TODO: needs to be handled in a better way System.out.println("call stack empty"); } else { StackFrame sf = t.frame(0); ObjectReference thisObject = sf.thisObject(); if (thisObject != null) { ReferenceType type = thisObject.referenceType(); System.out.println("fields in this (" + type.name() + "):"); for (Field f : type.visibleFields()) { System.out.println(f.typeName() + " " + f.name() + " = " + thisObject.getValue(f)); } } else { System.out.println("can't get this (in native or static method)"); } } } catch (IncompatibleThreadStateException ex) { logitse(ex); } } /** * Print source code snippet of current location in a suspended thread. * @param t suspended thread */ protected void printSourceLocation(ThreadReference t) { try { if (t.frameCount() == 0) { // TODO: needs to be handled in a better way System.out.println("call stack empty"); } else { Location l = t.frame(0).location(); // current stack frame location printSourceLocation(l); } } catch (IncompatibleThreadStateException ex) { logitse(ex); } } /** * Print source code snippet. * @param l {@link Location} object to print source code for */ protected void printSourceLocation(Location l) { try { //System.out.println(l.sourceName() + ":" + l.lineNumber()); System.out.println("in method " + l.method() + ":"); System.out.println(getSourceLine(l.sourcePath(), l.lineNumber(), 2)); } catch (AbsentInformationException ex) { log("absent information", ex); } } /** * Read a line from the given file in the builds src folder. * 1-based i.e. first line has line no. 1 * @param filePath * @param lineNo * @return the requested source line */ protected String getSourceLine(String filePath, int lineNo, int radius) { if (lineNo == -1) { loge("invalid line number: " + lineNo, null); return ""; } //System.out.println("getting line: " + lineNo); File f = new File(srcPath + File.separator + filePath); String output = ""; try { BufferedReader r = new BufferedReader(new FileReader(f)); int i = 1; //String line = ""; while (i <= lineNo + radius) { String line = r.readLine(); // line no. i if (line == null) { break; // end of file } if (i >= lineNo - radius) { if (i > lineNo - radius) { output += "\n"; // add newlines before all lines but the first } output += f.getName() + ":" + i + (i == lineNo ? " => " : " ") + line; } i++; } r.close(); return output; } catch (FileNotFoundException ex) { //System.err.println(ex); return f.getName() + ":" + lineNo; } catch (IOException ex) { loge("other io exception", ex); return ""; } } /** * Print info about a ReferenceType. Prints
name
java
alibaba__nacos
persistence/src/test/java/com/alibaba/nacos/persistence/utils/DerbyUtilsTest.java
{ "start": 804, "end": 1836 }
class ____ { @Test void testDerbySqlCorrect() { final String testSql = "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);"; final String result = DerbyUtils.insertStatementCorrection(testSql); final String expect = "INSERT INTO CONFIG_INFO (ID, DATA_ID, GROUP_ID, CONTENT, MD5, GMT_CREATE, GMT_MODIFIED, SRC_USER, SRC_IP, APP_NAME, TENANT_ID, C_DESC, C_USE, EFFECT, TYPE, C_SCHEMA) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL)"; assertEquals(expect, result); } }
DerbyUtilsTest
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/EntityWithAssignedIdIntegrationTests.java
{ "start": 1390, "end": 1781 }
class ____ { @Autowired EntityWithAssignedIdRepository repository; @Test // DATAJPA-1535 void deletesEntityJustCreated() { EntityWithAssignedId entityWithAssignedId = repository.save(new EntityWithAssignedId()); repository.deleteById(entityWithAssignedId.getId()); assertThat(repository.existsById(entityWithAssignedId.getId())).isFalse(); } }
EntityWithAssignedIdIntegrationTests
java
google__guice
core/test/com/google/inject/MethodInterceptionTest.java
{ "start": 2434, "end": 2690 }
class ____ implements MethodInterceptor { @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { count.incrementAndGet(); return methodInvocation.proceed(); } } private static final
CountingInterceptor
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java
{ "start": 1881, "end": 15093 }
class ____ { private DefaultListableBeanFactory beanFactory; private CollectingReaderEventListener listener = new CollectingReaderEventListener(); @BeforeEach void setup() { this.beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.setEventListener(this.listener); reader.loadBeanDefinitions(new ClassPathResource("testUtilNamespace.xml", getClass())); } @Test void testConstant() { Integer min = (Integer) this.beanFactory.getBean("min"); assertThat(min).isEqualTo(Integer.MIN_VALUE); } @Test void testConstantWithDefaultName() { Integer max = (Integer) this.beanFactory.getBean("java.lang.Integer.MAX_VALUE"); assertThat(max).isEqualTo(Integer.MAX_VALUE); } @Test void testEvents() { ComponentDefinition propertiesComponent = this.listener.getComponentDefinition("myProperties"); assertThat(propertiesComponent).as("Event for 'myProperties' not sent").isNotNull(); AbstractBeanDefinition propertiesBean = (AbstractBeanDefinition) propertiesComponent.getBeanDefinitions()[0]; assertThat(propertiesBean.getBeanClass()).as("Incorrect BeanDefinition").isEqualTo(PropertiesFactoryBean.class); ComponentDefinition constantComponent = this.listener.getComponentDefinition("min"); assertThat(propertiesComponent).as("Event for 'min' not sent").isNotNull(); AbstractBeanDefinition constantBean = (AbstractBeanDefinition) constantComponent.getBeanDefinitions()[0]; assertThat(constantBean.getBeanClass()).as("Incorrect BeanDefinition").isEqualTo(FieldRetrievingFactoryBean.class); } @Test void testNestedProperties() { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); Properties props = bean.getSomeProperties(); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); } @Test void testPropertyPath() { String name = (String) this.beanFactory.getBean("name"); assertThat(name).isEqualTo("Rob Harrop"); } @Test void testNestedPropertyPath() { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); assertThat(bean.getName()).isEqualTo("Rob Harrop"); } @Test void testSimpleMap() { Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("simpleMap"); assertThat(map.get("foo")).isEqualTo("bar"); Map<?, ?> map2 = (Map<?, ?>) this.beanFactory.getBean("simpleMap"); assertThat(map).isSameAs(map2); } @Test void testScopedMap() { Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("scopedMap"); assertThat(map.get("foo")).isEqualTo("bar"); Map<?, ?> map2 = (Map<?, ?>) this.beanFactory.getBean("scopedMap"); assertThat(map2.get("foo")).isEqualTo("bar"); assertThat(map).isNotSameAs(map2); } @Test void testSimpleList() { assertThat(this.beanFactory.getBean("simpleList")) .asInstanceOf(InstanceOfAssertFactories.LIST).element(0).isEqualTo("Rob Harrop"); assertThat(this.beanFactory.getBean("simpleList")) .isSameAs(this.beanFactory.getBean("simpleList")); } @Test void testScopedList() { assertThat(this.beanFactory.getBean("scopedList")) .asInstanceOf(InstanceOfAssertFactories.LIST).element(0).isEqualTo("Rob Harrop"); assertThat(this.beanFactory.getBean("scopedList")) .asInstanceOf(InstanceOfAssertFactories.LIST).element(0).isEqualTo("Rob Harrop"); assertThat(this.beanFactory.getBean("scopedList")) .isNotSameAs(this.beanFactory.getBean("scopedList")); } @Test void testSimpleSet() { assertThat(this.beanFactory.getBean("simpleSet")).isInstanceOf(Set.class) .asInstanceOf(InstanceOfAssertFactories.collection(String.class)) .containsOnly("Rob Harrop"); assertThat(this.beanFactory.getBean("simpleSet")) .isSameAs(this.beanFactory.getBean("simpleSet")); } @Test void testScopedSet() { assertThat(this.beanFactory.getBean("scopedSet")).isInstanceOf(Set.class) .asInstanceOf(InstanceOfAssertFactories.collection(String.class)) .containsOnly("Rob Harrop"); assertThat(this.beanFactory.getBean("scopedSet")).isInstanceOf(Set.class) .asInstanceOf(InstanceOfAssertFactories.collection(String.class)) .containsOnly("Rob Harrop"); assertThat(this.beanFactory.getBean("scopedSet")) .isNotSameAs(this.beanFactory.getBean("scopedSet")); } @Test void testMapWithRef() throws Exception { Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("mapWithRef"); assertThat(map).isInstanceOf(TreeMap.class); assertThat(map.get("bean")).isEqualTo(this.beanFactory.getBean("testBean")); assertThat(this.beanFactory.resolveDependency( new DependencyDescriptor(getClass().getDeclaredField("mapWithRef"), true), null)) .isSameAs(map); } @Test void testMapWithTypes() throws Exception { Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("mapWithTypes"); assertThat(map).isInstanceOf(LinkedCaseInsensitiveMap.class); assertThat(map.get("bean")).isEqualTo(this.beanFactory.getBean("testBean")); assertThat(this.beanFactory.resolveDependency( new DependencyDescriptor(getClass().getDeclaredField("mapWithTypes"), true), null)) .isSameAs(map); } @Test void testNestedCollections() { TestBean bean = (TestBean) this.beanFactory.getBean("nestedCollectionsBean"); assertThat(bean.getSomeList()).singleElement().isEqualTo("foo"); assertThat(bean.getSomeSet()).singleElement().isEqualTo("bar"); assertThat(bean.getSomeMap()).hasSize(1).allSatisfy((key, nested) -> { assertThat(key).isEqualTo("foo"); assertThat(nested).isInstanceOf(Set.class).asInstanceOf( InstanceOfAssertFactories.collection(String.class)).containsOnly("bar"); }); TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedCollectionsBean"); assertThat(bean2.getSomeList()).isEqualTo(bean.getSomeList()); assertThat(bean2.getSomeSet()).isEqualTo(bean.getSomeSet()); assertThat(bean2.getSomeMap()).isEqualTo(bean.getSomeMap()); assertThat(bean.getSomeList()).isNotSameAs(bean2.getSomeList()); assertThat(bean.getSomeSet()).isNotSameAs(bean2.getSomeSet()); assertThat(bean.getSomeMap()).isNotSameAs(bean2.getSomeMap()); } @Test void testNestedShortcutCollections() { TestBean bean = (TestBean) this.beanFactory.getBean("nestedShortcutCollections"); assertThat(bean.getStringArray()).containsExactly("fooStr"); assertThat(bean.getSomeList()).singleElement().isEqualTo("foo"); assertThat(bean.getSomeSet()).singleElement().isEqualTo("bar"); TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedShortcutCollections"); assertThat(Arrays.equals(bean.getStringArray(), bean2.getStringArray())).isTrue(); assertThat(bean.getStringArray()).isNotSameAs(bean2.getStringArray()); assertThat(bean2.getSomeList()).isEqualTo(bean.getSomeList()); assertThat(bean2.getSomeSet()).isEqualTo(bean.getSomeSet()); assertThat(bean.getSomeList()).isNotSameAs(bean2.getSomeList()); assertThat(bean.getSomeSet()).isNotSameAs(bean2.getSomeSet()); } @Test void testNestedInCollections() { TestBean bean = (TestBean) this.beanFactory.getBean("nestedCustomTagBean"); assertThat(bean.getSomeList()).singleElement().isEqualTo(Integer.MIN_VALUE); assertThat(bean.getSomeSet()).asInstanceOf(InstanceOfAssertFactories.collection(Thread.State.class)) .containsOnly(Thread.State.NEW,Thread.State.RUNNABLE); assertThat(bean.getSomeMap()).hasSize(1).allSatisfy((key, value) -> { assertThat(key).isEqualTo("min"); assertThat(value).isEqualTo(CustomEnum.VALUE_1); }); TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedCustomTagBean"); assertThat(bean2.getSomeList()).isEqualTo(bean.getSomeList()); assertThat(bean2.getSomeSet()).isEqualTo(bean.getSomeSet()); assertThat(bean2.getSomeMap()).isEqualTo(bean.getSomeMap()); assertThat(bean.getSomeList()).isNotSameAs(bean2.getSomeList()); assertThat(bean.getSomeSet()).isNotSameAs(bean2.getSomeSet()); assertThat(bean.getSomeMap()).isNotSameAs(bean2.getSomeMap()); } @Test void testCircularCollections() { TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionsBean"); assertThat(bean.getSomeList()).singleElement().isSameAs(bean); assertThat(bean.getSomeSet()).singleElement().isSameAs(bean); assertThat(bean.getSomeMap()).hasSize(1).allSatisfy((key, value) -> { assertThat(key).isEqualTo("foo"); assertThat(value).isSameAs(bean); }); } @Test void testCircularCollectionBeansStartingWithList() { this.beanFactory.getBean("circularList"); TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean"); List<?> list = bean.getSomeList(); assertThat(Proxy.isProxyClass(list.getClass())).isTrue(); assertThat(list).singleElement().isSameAs(bean); Set<?> set = bean.getSomeSet(); assertThat(Proxy.isProxyClass(set.getClass())).isFalse(); assertThat(set).singleElement().isSameAs(bean); Map<?, ?> map = bean.getSomeMap(); assertThat(Proxy.isProxyClass(map.getClass())).isFalse(); assertThat(map).hasSize(1).allSatisfy((key, value) -> { assertThat(key).isEqualTo("foo"); assertThat(value).isSameAs(bean); }); } @Test void testCircularCollectionBeansStartingWithSet() { this.beanFactory.getBean("circularSet"); TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean"); List<?> list = bean.getSomeList(); assertThat(Proxy.isProxyClass(list.getClass())).isFalse(); assertThat(list).singleElement().isSameAs(bean); Set<?> set = bean.getSomeSet(); assertThat(Proxy.isProxyClass(set.getClass())).isTrue(); assertThat(set).singleElement().isSameAs(bean); Map<?, ?> map = bean.getSomeMap(); assertThat(Proxy.isProxyClass(map.getClass())).isFalse(); assertThat(map).hasSize(1).allSatisfy((key, value) -> { assertThat(key).isEqualTo("foo"); assertThat(value).isSameAs(bean); }); } @Test void testCircularCollectionBeansStartingWithMap() { this.beanFactory.getBean("circularMap"); TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean"); List<?> list = bean.getSomeList(); assertThat(Proxy.isProxyClass(list.getClass())).isFalse(); assertThat(list).singleElement().isSameAs(bean); Set<?> set = bean.getSomeSet(); assertThat(Proxy.isProxyClass(set.getClass())).isFalse(); assertThat(set).singleElement().isSameAs(bean); Map<?, ?> map = bean.getSomeMap(); assertThat(Proxy.isProxyClass(map.getClass())).isTrue(); assertThat(map).hasSize(1).allSatisfy((key, value) -> { assertThat(key).isEqualTo("foo"); assertThat(value).isSameAs(bean); }); } @Test void testNestedInConstructor() { TestBean bean = (TestBean) this.beanFactory.getBean("constructedTestBean"); assertThat(bean.getName()).isEqualTo("Rob Harrop"); } @Test void testLoadProperties() { Properties props = (Properties) this.beanFactory.getBean("myProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); assertThat(props).as("Incorrect property value").doesNotContainKey("foo2"); Properties props2 = (Properties) this.beanFactory.getBean("myProperties"); assertThat(props).isSameAs(props2); } @Test void testScopedProperties() { Properties props = (Properties) this.beanFactory.getBean("myScopedProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); assertThat(props).as("Incorrect property value").doesNotContainKey("foo2"); Properties props2 = (Properties) this.beanFactory.getBean("myScopedProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); assertThat(props).as("Incorrect property value").doesNotContainKey("foo2"); assertThat(props).isNotSameAs(props2); } @Test void testLocalProperties() { Properties props = (Properties) this.beanFactory.getBean("myLocalProperties"); assertThat(props).as("Incorrect property value").doesNotContainKey("foo"); assertThat(props).as("Incorrect property value").containsEntry("foo2", "bar2"); } @Test void testMergedProperties() { Properties props = (Properties) this.beanFactory.getBean("myMergedProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); assertThat(props).as("Incorrect property value").containsEntry("foo2", "bar2"); } @Test void testLocalOverrideDefault() { Properties props = (Properties) this.beanFactory.getBean("defaultLocalOverrideProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); assertThat(props).as("Incorrect property value").containsEntry("foo2", "local2"); } @Test void testLocalOverrideFalse() { Properties props = (Properties) this.beanFactory.getBean("falseLocalOverrideProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); assertThat(props).as("Incorrect property value").containsEntry("foo2", "local2"); } @Test void testLocalOverrideTrue() { Properties props = (Properties) this.beanFactory.getBean("trueLocalOverrideProperties"); assertThat(props).as("Incorrect property value").containsEntry("foo", "local"); assertThat(props).as("Incorrect property value").containsEntry("foo2", "local2"); } // For DependencyDescriptor resolution Map<String, TestBean> mapWithRef; Map<String, TestBean> mapWithTypes; }
UtilNamespaceHandlerTests
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/core/Completable.java
{ "start": 110619, "end": 111740 }
class ____ implements CompletableOperator { * &#64;Override * public CompletableObserver apply(CompletableObserver upstream) { * return new CustomCompletableObserver(upstream); * } * } * * // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it * // or reusing an existing one. * * Completable.complete() * .lift(new CustomCompletableOperator()) * .test() * .assertResult(); * </code></pre> * <p> * Creating custom operators can be complicated and it is recommended one consults the * <a href="https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0">RxJava wiki: Writing operators</a> page about * the tools, requirements, rules, considerations and pitfalls of implementing them. * <p> * Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring * an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Completable} *
CustomCompletableOperator
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfView.java
{ "start": 2075, "end": 7700 }
class ____ extends AbstractView { /** * This constructor sets the appropriate content type "application/pdf". * Note that IE won't take much notice of this, but there's not a lot we * can do about this. Generated documents should have a ".pdf" extension. */ public AbstractPdfView() { setContentType("application/pdf"); } @Override protected boolean generatesDownloadContent() { return true; } @Override protected final void renderMergedOutputModel( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // IE workaround: write into byte array first. ByteArrayOutputStream baos = createTemporaryOutputStream(); // Apply preferences and build metadata. Document document = newDocument(); PdfWriter writer = newWriter(document, baos); prepareWriter(model, writer, request); buildPdfMetadata(model, document, request); // Build PDF document. document.open(); buildPdfDocument(model, document, writer, request, response); document.close(); // Flush to HTTP response. writeToResponse(response, baos); } /** * Create a new document to hold the PDF contents. * <p>By default returns an A4 document, but the subclass can specify any * Document, possibly parameterized via bean properties defined on the View. * @return the newly created iText Document instance * @see com.lowagie.text.Document#Document(com.lowagie.text.Rectangle) */ protected Document newDocument() { return new Document(PageSize.A4); } /** * Create a new PdfWriter for the given iText Document. * @param document the iText Document to create a writer for * @param os the OutputStream to write to * @return the PdfWriter instance to use * @throws DocumentException if thrown during writer creation */ protected PdfWriter newWriter(Document document, OutputStream os) throws DocumentException { return PdfWriter.getInstance(document, os); } /** * Prepare the given PdfWriter. Called before building the PDF document, * that is, before the call to {@code Document.open()}. * <p>Useful for registering a page event listener, for example. * The default implementation sets the viewer preferences as returned * by this class's {@code getViewerPreferences()} method. * @param model the model, in case meta information must be populated from it * @param writer the PdfWriter to prepare * @param request in case we need locale etc. Shouldn't look at attributes. * @throws DocumentException if thrown during writer preparation * @see com.lowagie.text.Document#open() * @see com.lowagie.text.pdf.PdfWriter#setPageEvent * @see com.lowagie.text.pdf.PdfWriter#setViewerPreferences * @see #getViewerPreferences() */ protected void prepareWriter(Map<String, Object> model, PdfWriter writer, HttpServletRequest request) throws DocumentException { writer.setViewerPreferences(getViewerPreferences()); } /** * Return the viewer preferences for the PDF file. * <p>By default returns {@code AllowPrinting} and * {@code PageLayoutSinglePage}, but can be subclassed. * The subclass can either have fixed preferences or retrieve * them from bean properties defined on the View. * @return an int containing the bits information against PdfWriter definitions * @see com.lowagie.text.pdf.PdfWriter#ALLOW_PRINTING * @see com.lowagie.text.pdf.PdfWriter#PageLayoutSinglePage */ protected int getViewerPreferences() { return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage; } /** * Populate the iText Document's meta fields (author, title, etc.). * <br>Default is an empty implementation. Subclasses may override this method * to add meta fields such as title, subject, author, creator, keywords, etc. * This method is called after assigning a PdfWriter to the Document and * before calling {@code document.open()}. * @param model the model, in case meta information must be populated from it * @param document the iText document being populated * @param request in case we need locale etc. Shouldn't look at attributes. * @see com.lowagie.text.Document#addTitle * @see com.lowagie.text.Document#addSubject * @see com.lowagie.text.Document#addKeywords * @see com.lowagie.text.Document#addAuthor * @see com.lowagie.text.Document#addCreator * @see com.lowagie.text.Document#addProducer * @see com.lowagie.text.Document#addCreationDate * @see com.lowagie.text.Document#addHeader */ protected void buildPdfMetadata(Map<String, Object> model, Document document, HttpServletRequest request) { } /** * Subclasses must implement this method to build an iText PDF document, * given the model. Called between {@code Document.open()} and * {@code Document.close()} calls. * <p>Note that the passed-in HTTP response is just supposed to be used * for setting cookies or other HTTP headers. The built PDF document itself * will automatically get written to the response after this method returns. * @param model the model Map * @param document the iText Document to add elements to * @param writer the PdfWriter to use * @param request in case we need locale etc. Shouldn't look at attributes. * @param response in case we need to set cookies. Shouldn't write to it. * @throws Exception any exception that occurred during document building * @see com.lowagie.text.Document#open() * @see com.lowagie.text.Document#close() */ protected abstract void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception; }
AbstractPdfView
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/TestReservationSystem.java
{ "start": 2662, "end": 8140 }
class ____ extends ParameterizedSchedulerTestBase { private final static String ALLOC_FILE = new File( FairSchedulerTestBase.TEST_DIR, TestReservationSystem.class.getName() + ".xml").getAbsolutePath(); private AbstractYarnScheduler scheduler; private AbstractReservationSystem reservationSystem; private RMContext rmContext; private Configuration conf; private RMContext mockRMContext; public void initTestReservationSystem(SchedulerType type) throws IOException { initParameterizedSchedulerTestBase(type); setUp(); } public void setUp() throws IOException { scheduler = initializeScheduler(); rmContext = getRMContext(); reservationSystem = configureReservationSystem(); reservationSystem.setRMContext(rmContext); DefaultMetricsSystem.setMiniClusterMode(true); } @AfterEach public void tearDown() { conf = null; reservationSystem = null; rmContext = null; scheduler = null; clearRMContext(); QueueMetrics.clearQueueMetrics(); } @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testInitialize(SchedulerType type) throws IOException { initTestReservationSystem(type); try { reservationSystem.reinitialize(scheduler.getConfig(), rmContext); } catch (YarnException e) { fail(e.getMessage()); } if (getSchedulerType().equals(SchedulerType.CAPACITY)) { ReservationSystemTestUtil.validateReservationQueue(reservationSystem, ReservationSystemTestUtil.getReservationQueueName()); } else { ReservationSystemTestUtil.validateReservationQueue(reservationSystem, ReservationSystemTestUtil.getFullReservationQueueName()); } } @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testReinitialize(SchedulerType type) throws IOException { initTestReservationSystem(type); conf = scheduler.getConfig(); try { reservationSystem.reinitialize(conf, rmContext); } catch (YarnException e) { fail(e.getMessage()); } if (getSchedulerType().equals(SchedulerType.CAPACITY)) { ReservationSystemTestUtil.validateReservationQueue(reservationSystem, ReservationSystemTestUtil.getReservationQueueName()); } else { ReservationSystemTestUtil.validateReservationQueue(reservationSystem, ReservationSystemTestUtil.getFullReservationQueueName()); } // Dynamically add a plan String newQ = "reservation"; assertNull(reservationSystem.getPlan(newQ)); updateSchedulerConf(conf, newQ); try { scheduler.reinitialize(conf, rmContext); } catch (IOException e) { fail(e.getMessage()); } try { reservationSystem.reinitialize(conf, rmContext); } catch (YarnException e) { fail(e.getMessage()); } ReservationSystemTestUtil.validateReservationQueue( reservationSystem, "root." + newQ); } @SuppressWarnings("rawtypes") public AbstractYarnScheduler initializeScheduler() throws IOException { switch (getSchedulerType()) { case CAPACITY: return initializeCapacityScheduler(); case FAIR: return initializeFairScheduler(); } return null; } public AbstractReservationSystem configureReservationSystem() { switch (getSchedulerType()) { case CAPACITY: return new CapacityReservationSystem(); case FAIR: return new FairReservationSystem(); } return null; } public void updateSchedulerConf(Configuration conf, String newQ) throws IOException { switch (getSchedulerType()) { case CAPACITY: ReservationSystemTestUtil.updateQueueConfiguration( (CapacitySchedulerConfiguration) conf, newQ); case FAIR: ReservationSystemTestUtil.updateFSAllocationFile(ALLOC_FILE); } } public RMContext getRMContext() { return mockRMContext; } public void clearRMContext() { mockRMContext = null; } private CapacityScheduler initializeCapacityScheduler() { // stolen from TestCapacityScheduler CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); ReservationSystemTestUtil.setupQueueConfiguration(conf); CapacityScheduler cs = spy(new CapacityScheduler()); cs.setConf(conf); CSMaxRunningAppsEnforcer enforcer = mock(CSMaxRunningAppsEnforcer.class); cs.setMaxRunningAppsEnforcer(enforcer); mockRMContext = ReservationSystemTestUtil.createRMContext(conf); cs.setRMContext(mockRMContext); try { cs.serviceInit(conf); } catch (Exception e) { fail(e.getMessage()); } ReservationSystemTestUtil.initializeRMContext(10, cs, mockRMContext); return cs; } private Configuration createFSConfiguration() { FairSchedulerTestBase testHelper = new FairSchedulerTestBase(); Configuration conf = testHelper.createConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class, ResourceScheduler.class); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); return conf; } private FairScheduler initializeFairScheduler() throws IOException { Configuration conf = createFSConfiguration(); ReservationSystemTestUtil.setupFSAllocationFile(ALLOC_FILE); // Setup mockRMContext = ReservationSystemTestUtil.createRMContext(conf); return ReservationSystemTestUtil .setupFairScheduler(mockRMContext, conf, 10); } }
TestReservationSystem
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java
{ "start": 2577, "end": 4714 }
class ____ between "common" interceptors: shared for all proxies it * creates, and "specific" interceptors: unique per bean instance. There need not be any * common interceptors. If there are, they are set using the interceptorNames property. * As with {@link org.springframework.aop.framework.ProxyFactoryBean}, interceptors names * in the current factory are used rather than bean references to allow correct handling * of prototype advisors and interceptors: for example, to support stateful mixins. * Any advice type is supported for {@link #setInterceptorNames "interceptorNames"} entries. * * <p>Such auto-proxying is particularly useful if there's a large number of beans that * need to be wrapped with similar proxies, i.e. delegating to the same interceptors. * Instead of x repetitive proxy definitions for x target beans, you can register * one single such post processor with the bean factory to achieve the same effect. * * <p>Subclasses can apply any strategy to decide if a bean is to be proxied, for example, by type, * by name, by definition details, etc. They can also return additional interceptors that * should just be applied to the specific bean instance. A simple concrete implementation is * {@link BeanNameAutoProxyCreator}, identifying the beans to be proxied via given names. * * <p>Any number of {@link TargetSourceCreator} implementations can be used to create * a custom target source: for example, to pool prototype objects. Auto-proxying will * occur even if there is no advice, as long as a TargetSourceCreator specifies a custom * {@link org.springframework.aop.TargetSource}. If there are no TargetSourceCreators set, * or if none matches, a {@link org.springframework.aop.target.SingletonTargetSource} * will be used by default to wrap the target bean instance. * * @author Juergen Hoeller * @author Rod Johnson * @author Rob Harrop * @author Sam Brannen * @since 13.10.2003 * @see #setInterceptorNames * @see #getAdvicesAndAdvisorsForBean * @see BeanNameAutoProxyCreator * @see DefaultAdvisorAutoProxyCreator */ @SuppressWarnings("serial") public abstract
distinguishes
java
apache__flink
flink-table/flink-table-code-splitter/src/test/java/org/apache/flink/table/codesplit/JavaCodeSplitterTest.java
{ "start": 2849, "end": 5027 }
interface ____ {}", 10, 0)) .cause() .hasMessage("maxClassMemberCount must be greater than 0"); } /** * Check whether the given and expected classes are actually a valid Java code -> it compiles. * If this test fails on "expected" files, it probably means that code split logic is invalid * and an issue was missed when preparing test files. */ @Test void shouldCompileGivenAndExpectedCode() throws Exception { CodeSplitTestUtil.tryCompile("splitter/code/"); CodeSplitTestUtil.tryCompile("splitter/expected/"); } private void runTest(String filename, int maxLength, int maxMembers) { try { String code = FileUtils.readFileUtf8( new File( JavaCodeSplitterTest.class .getClassLoader() .getResource("splitter/code/" + filename + ".java") .toURI())); String expected = FileUtils.readFileUtf8( new File( JavaCodeSplitterTest.class .getClassLoader() .getResource("splitter/expected/" + filename + ".java") .toURI())); // Trying to mitigate any indentation issues between all sort of platforms by simply // trim every line of the "class". Before this change, code-splitter test could fail on // Windows machines while passing on Unix. expected = trimLines(expected); String actual = JavaCodeSplitter.split(code, maxLength, maxMembers); assertThat(trimLines(actual)).isEqualTo(expected); } catch (Exception e) { throw new RuntimeException(e); } finally { // we reset the counter to ensure the variable names after rewrite are as expected CodeSplitUtil.getCounter().set(0L); } } }
DummyInterface
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableTimeout.java
{ "start": 10660, "end": 12303 }
class ____ extends AtomicReference<Subscription> implements FlowableSubscriber<Object>, Disposable { private static final long serialVersionUID = 8708641127342403073L; final TimeoutSelectorSupport parent; final long idx; TimeoutConsumer(long idx, TimeoutSelectorSupport parent) { this.idx = idx; this.parent = parent; } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override public void onNext(Object t) { Subscription upstream = get(); if (upstream != SubscriptionHelper.CANCELLED) { upstream.cancel(); lazySet(SubscriptionHelper.CANCELLED); parent.onTimeout(idx); } } @Override public void onError(Throwable t) { if (get() != SubscriptionHelper.CANCELLED) { lazySet(SubscriptionHelper.CANCELLED); parent.onTimeoutError(idx, t); } else { RxJavaPlugins.onError(t); } } @Override public void onComplete() { if (get() != SubscriptionHelper.CANCELLED) { lazySet(SubscriptionHelper.CANCELLED); parent.onTimeout(idx); } } @Override public void dispose() { SubscriptionHelper.cancel(this); } @Override public boolean isDisposed() { return this.get() == SubscriptionHelper.CANCELLED; } } }
TimeoutConsumer
java
quarkusio__quarkus
extensions/funqy/funqy-knative-events/deployment/src/test/java/io/quarkus/funqy/test/GreetTestBase.java
{ "start": 198, "end": 3358 }
class ____ { protected abstract String getCeSource(); protected abstract String getCeType(); @Test public void testVanilla() { RestAssured.given().contentType("application/json") .body("{\"name\": \"Bill\"}") .post("/") .then().statusCode(200) .header("ce-id", nullValue()) .body("name", equalTo("Bill")) .body("message", equalTo("Hello Bill!")); } @Test public void testVanillaNPE() { RestAssured.given().contentType("application/json") .body("null") .post("/") .then().statusCode(500); } @Test public void testBinary() { RestAssured.given().contentType("application/json") .body("{\"name\": \"Bill\"}") .header("ce-id", "1234") .header("ce-specversion", "1.0") .post("/") .then().statusCode(200) .header("ce-id", notNullValue()) .header("ce-specversion", equalTo("1.0")) .header("ce-source", equalTo(getCeSource())) .header("ce-type", equalTo(getCeType())) .body("name", equalTo("Bill")) .body("message", equalTo("Hello Bill!")); } @Test public void testBinaryNPE() { RestAssured.given().contentType("application/json") .body("null") .header("ce-id", "1234") .header("ce-specversion", "1.0") .post("/") .then().statusCode(500); } static final String event = "{ \"id\" : \"1234\", " + " \"specversion\": \"1.0\", " + " \"source\": \"/foo\", " + " \"type\": \"sometype\", " + " \"datacontenttype\": \"application/json\", " + " \"data\": { \"name\": \"Bill\" } " + "}"; @Test public void testStructured() { RestAssured.given().contentType("application/cloudevents+json") .body(event) .post("/") .then().statusCode(200) .defaultParser(Parser.JSON) .body("id", notNullValue()) .body("specversion", equalTo("1.0")) .body("type", equalTo(getCeType())) .body("source", equalTo(getCeSource())) .body("datacontenttype", equalTo("application/json")) .body("data.name", equalTo("Bill")) .body("data.message", equalTo("Hello Bill!")); } static final String eventWithNullData = "{ \"id\" : \"1234\", " + " \"specversion\": \"1.0\", " + " \"source\": \"/foo\", " + " \"type\": \"sometype\", " + " \"datacontenttype\": \"application/json\", " + " \"data\": null " + "}"; @Test public void testStructuredNPE() { RestAssured.given().contentType("application/cloudevents+json") .body(eventWithNullData) .post("/") .then().statusCode(500); } }
GreetTestBase
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/main/java/io/quarkus/websockets/next/deployment/CloseReasonCallbackArgument.java
{ "start": 236, "end": 823 }
class ____ implements CallbackArgument { @Override public boolean matches(ParameterContext context) { return context.callbackAnnotation().name().equals(WebSocketDotNames.ON_CLOSE) && context.parameter().type().name().equals(WebSocketDotNames.CLOSE_REASON); } @Override public Expr get(InvocationBytecodeContext context) { return context.bytecode().invokeVirtual( MethodDesc.of(WebSocketConnectionBase.class, "closeReason", CloseReason.class), context.getConnection()); } }
CloseReasonCallbackArgument
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/concurrent/IncrementalDelayRetryStrategy.java
{ "start": 1029, "end": 3202 }
class ____ implements RetryStrategy { private final int remainingRetries; private final Duration currentRetryDelay; private final Duration increment; private final Duration maxRetryDelay; /** * @param remainingRetries number of times to retry * @param currentRetryDelay the current delay between retries * @param increment the delay increment between retries * @param maxRetryDelay the max delay between retries */ public IncrementalDelayRetryStrategy( int remainingRetries, Duration currentRetryDelay, Duration increment, Duration maxRetryDelay) { Preconditions.checkArgument( remainingRetries >= 0, "The number of retries must be greater or equal to 0."); this.remainingRetries = remainingRetries; Preconditions.checkArgument( currentRetryDelay.toMillis() >= 0, "The currentRetryDelay must be positive"); this.currentRetryDelay = currentRetryDelay; Preconditions.checkArgument( increment.toMillis() >= 0, "The delay increment must be greater or equal to 0."); this.increment = increment; Preconditions.checkArgument( maxRetryDelay.toMillis() >= 0, "The maxRetryDelay must be positive"); this.maxRetryDelay = maxRetryDelay; } @Override public int getNumRemainingRetries() { return remainingRetries; } @Override public Duration getRetryDelay() { return currentRetryDelay; } @Override public RetryStrategy getNextRetryStrategy() { int nextRemainingRetries = remainingRetries - 1; Preconditions.checkState( nextRemainingRetries >= 0, "The number of remaining retries must not be negative"); long nextRetryDelayMillis = Math.min(currentRetryDelay.plus(increment).toMillis(), maxRetryDelay.toMillis()); return new IncrementalDelayRetryStrategy( nextRemainingRetries, Duration.ofMillis(nextRetryDelayMillis), increment, maxRetryDelay); } }
IncrementalDelayRetryStrategy
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/TypeConvertible.java
{ "start": 1151, "end": 1496 }
class ____<F, T> { private final Class<F> from; private final Class<T> to; private final int hash; /** * Constructs a new type convertible pair. This is likely only used by core camel code and auto-generated bulk * loaders. This is an internal API and not meant for end users. * * @param from The
TypeConvertible
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/ConnectionIdleException.java
{ "start": 943, "end": 1352 }
class ____ extends ConnectionException { private static final long serialVersionUID = 5103778538635217293L; public ConnectionIdleException(String message) { super(message); } public ConnectionIdleException(String message, Throwable cause) { super(message, cause); } public ConnectionIdleException(Throwable cause) { super(cause); } }
ConnectionIdleException
java
google__guava
android/guava/src/com/google/common/collect/ImmutableMultiset.java
{ "start": 6024, "end": 6483 }
class ____. * * @throws NullPointerException if any element is null * @since 6.0 (source-compatible since 2.0) */ public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { return new Builder<E>().add(e1).add(e2).add(e3).add(e4).add(e5).add(e6).add(others).build(); } /** * Returns an immutable multiset containing the given elements, in the "grouped iteration order" * described in the
documentation
java
quarkusio__quarkus
independent-projects/enforcer-rules/src/main/java/io/quarkus/enforcer/RequiresMinimalDeploymentDependency.java
{ "start": 626, "end": 5649 }
class ____ extends DeploymentDependencyRuleSupport { private static final String REQ_TYPE = "pom"; private static final String REQ_SCOPE = "test"; private static final String DEP_TEMPLATE = " <dependency>\n" + " <groupId>%s</groupId>\n" + " <artifactId>%s</artifactId>\n" + " <version>${project.version}</version>\n" + " <type>" + REQ_TYPE + "</type>\n" + " <scope>" + REQ_SCOPE + "</scope>\n" + " <exclusions>\n" + " <exclusion>\n" + " <groupId>*</groupId>\n" + " <artifactId>*</artifactId>\n" + " </exclusion>\n" + " </exclusions>\n" + " </dependency>"; @Override public void execute(MavenProject project, Map<String, Artifact> nonDeploymentArtifactsByGAV, Map<String, Dependency> directDepsByGAV) throws EnforcerRuleException { String projArtifactKey = buildGAVKey(project.getArtifact()); Set<String> existingUnmatchedDeploymentDeps = directDepsByGAV.entrySet().stream() .filter(entry -> entry.getKey().contains(DEPLOYMENT_ARTIFACT_ID_SUFFIX)) .filter(entry -> REQ_TYPE.equals(entry.getValue().getType())) .filter(entry -> REQ_SCOPE.equals(entry.getValue().getScope())) .filter(entry -> entry.getValue().getExclusions().stream() .anyMatch(excl -> "*".equals(excl.getGroupId()) && "*".equals(excl.getArtifactId()))) .map(Entry::getKey) .collect(Collectors.toSet()); List<String> missingDeploymentDeps = nonDeploymentArtifactsByGAV.entrySet().parallelStream() .filter(entry -> directDepsByGAV.containsKey(entry.getKey())) // only direct deps .map(entry -> parseDeploymentGAV(entry.getKey(), entry.getValue())) .sequential() .filter(optDeploymentGAV -> optDeploymentGAV .map(deploymentGAV -> !isMinDeploymentDepPresent(deploymentGAV, projArtifactKey, existingUnmatchedDeploymentDeps)) .orElse(false)) .map(Optional::get) .sorted() .collect(Collectors.toList()); if (!missingDeploymentDeps.isEmpty()) { String requiredDeps = missingDeploymentDeps.stream() .map(gav -> (Object[]) gav.split(":")) .map(gavArray -> String.format(DEP_TEMPLATE, gavArray)) .collect(Collectors.joining("\n")); throw new EnforcerRuleException(missingDeploymentDeps.size() + " minimal *-deployment dependencies are missing/configured incorrectly:\n" + " " + missingDeploymentDeps.stream().collect(Collectors.joining("\n ")) + "\n\nTo fix this issue, add the following dependencies to pom.xml:\n\n" + " <!-- Minimal test dependencies to *-deployment artifacts for consistent build order -->\n" + requiredDeps); } if (!existingUnmatchedDeploymentDeps.isEmpty()) { Set<String> nonSuperfluous = parseNonSuperfluosArtifactIdsFromProperty(project); if (!nonSuperfluous.isEmpty()) { existingUnmatchedDeploymentDeps .removeIf(gav -> nonSuperfluous.stream().anyMatch(aid -> gav.contains(":" + aid + ":"))); } if (!existingUnmatchedDeploymentDeps.isEmpty()) { String superfluousDeps = existingUnmatchedDeploymentDeps.stream() .map(gav -> " " + gav) .sorted() .collect(Collectors.joining("\n")); throw new EnforcerRuleException(existingUnmatchedDeploymentDeps.size() + " minimal *-deployment dependencies are superfluous and must be removed from pom.xml:\n" + superfluousDeps); } } } private boolean isMinDeploymentDepPresent(String deploymentGAV, String projArtifactKey, Set<String> existingDeploymentDeps) { return deploymentGAV.equals(projArtifactKey) // special case: current project itself is the "required dependency" || existingDeploymentDeps.remove(deploymentGAV); } private Set<String> parseNonSuperfluosArtifactIdsFromProperty(MavenProject project) { String propValue = project.getProperties().getProperty("enforcer.requiresMinimalDeploymentDependency.nonSuperfluous"); if (propValue != null) { return Arrays.stream(propValue.split(",")).map(String::trim).collect(Collectors.toSet()); } else { return Collections.emptySet(); } } }
RequiresMinimalDeploymentDependency
java
spring-projects__spring-boot
module/spring-boot-elasticsearch/src/test/java/org/springframework/boot/elasticsearch/autoconfigure/ElasticsearchRestClientAutoConfigurationTests.java
{ "start": 18267, "end": 18463 }
class ____ { @Bean Rest5Client customRest5Client(Rest5ClientBuilder builder) { return builder.build(); } } @Configuration(proxyBeanMethods = false) static
CustomRest5ClientConfiguration
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/method/configuration/PrePostMethodSecurityConfigurationTests.java
{ "start": 72968, "end": 73108 }
interface ____ { String value(); } @Retention(RetentionPolicy.RUNTIME) @PreFilter("filterObject.contains('{value}')") @
ResultStartsWith
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java
{ "start": 11794, "end": 12072 }
class ____ { public static Resource getResource(URL url) throws IOException { return new VfsResource(VfsUtils.getRoot(url)); } public static Resource getResource(URI uri) throws IOException { return new VfsResource(VfsUtils.getRoot(uri)); } } }
VfsResourceDelegate
java
apache__avro
lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyServerWithSSL.java
{ "start": 1337, "end": 2415 }
class ____ extends TestNettyServer { private static final String TEST_CERTIFICATE = "servercert.p12"; private static final String TEST_CERTIFICATE_FILEPASS = "serverpass.txt"; @BeforeAll public static void initializeConnections() throws Exception { initializeConnections(ch -> { SSLEngine sslEngine = createServerSSLContext().createSSLEngine(); sslEngine.setUseClientMode(false); SslHandler handler = new SslHandler(sslEngine, false); ch.pipeline().addLast("SSL", handler); }, ch -> { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { new BogusTrustManager() }, null); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); SslHandler handler = new SslHandler(sslEngine, false); ch.pipeline().addLast("SSL", handler); } catch (Exception e) { e.printStackTrace(); } }); } /** * Bogus trust manager accepting any certificate */ private static
TestNettyServerWithSSL
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/DefaultLoggingExceptionMapper.java
{ "start": 91, "end": 173 }
class ____ extends LoggingExceptionMapper<Throwable> { }
DefaultLoggingExceptionMapper
java
apache__spark
sql/hive-thriftserver/src/main/java/org/apache/hive/service/auth/PasswdAuthenticationProvider.java
{ "start": 900, "end": 1687 }
interface ____ { /** * The Authenticate method is called by the HiveServer2 authentication layer * to authenticate users for their requests. * If a user is to be granted, return nothing/throw nothing. * When a user is to be disallowed, throw an appropriate {@link AuthenticationException}. * * For an example implementation, see {@link LdapAuthenticationProviderImpl}. * * @param user The username received over the connection request * @param password The password received over the connection request * * @throws AuthenticationException When a user is found to be * invalid by the implementation */ void Authenticate(String user, String password) throws AuthenticationException; }
PasswdAuthenticationProvider
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RListMultimapCacheNative.java
{ "start": 991, "end": 1087 }
interface ____<K, V> extends RListMultimap<K, V>, RMultimapCache<K, V> { }
RListMultimapCacheNative
java
resilience4j__resilience4j
resilience4j-spring/src/main/java/io/github/resilience4j/ratelimiter/configure/RxJava3RateLimiterAspectExt.java
{ "start": 561, "end": 3289 }
class ____ implements RateLimiterAspectExt { private static final Logger logger = LoggerFactory.getLogger(RxJava3RateLimiterAspectExt.class); private final Set<Class> rxSupportedTypes = newHashSet(ObservableSource.class, SingleSource.class, CompletableSource.class, MaybeSource.class, Flowable.class); /** * @param returnType the AOP method return type class * @return boolean if the method has Rx java 3 rerun type */ @SuppressWarnings("unchecked") @Override public boolean canHandleReturnType(Class returnType) { return rxSupportedTypes.stream() .anyMatch(classType -> classType.isAssignableFrom(returnType)); } /** * @param proceedingJoinPoint Spring AOP proceedingJoinPoint * @param rateLimiter the configured rateLimiter * @param methodName the method name * @return the result object * @throws Throwable exception in case of faulty flow */ @Override public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter, String methodName) throws Throwable { RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter); Object returnValue = proceedingJoinPoint.proceed(); return executeRxJava3Aspect(rateLimiterOperator, returnValue); } @SuppressWarnings("unchecked") private Object executeRxJava3Aspect(RateLimiterOperator rateLimiterOperator, Object returnValue) { if (returnValue instanceof ObservableSource) { Observable<?> observable = (Observable) returnValue; return observable.compose(rateLimiterOperator); } else if (returnValue instanceof SingleSource) { Single<?> single = (Single) returnValue; return single.compose(rateLimiterOperator); } else if (returnValue instanceof CompletableSource) { Completable completable = (Completable) returnValue; return completable.compose(rateLimiterOperator); } else if (returnValue instanceof MaybeSource) { Maybe<?> maybe = (Maybe) returnValue; return maybe.compose(rateLimiterOperator); } else if (returnValue instanceof Flowable) { Flowable<?> flowable = (Flowable) returnValue; return flowable.compose(rateLimiterOperator); } else { logger.error("Unsupported type for Rate limiter RxJava3 {}", returnValue.getClass().getTypeName()); throw new IllegalArgumentException( "Not Supported type for the Rate limiter in RxJava3 :" + returnValue.getClass() .getName()); } } }
RxJava3RateLimiterAspectExt
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/FeatureUpdate.java
{ "start": 1064, "end": 3957 }
enum ____ { UNKNOWN(0), UPGRADE(1), SAFE_DOWNGRADE(2), UNSAFE_DOWNGRADE(3); private final byte code; UpgradeType(int code) { this.code = (byte) code; } public byte code() { return code; } public static UpgradeType fromCode(int code) { if (code == 1) { return UPGRADE; } else if (code == 2) { return SAFE_DOWNGRADE; } else if (code == 3) { return UNSAFE_DOWNGRADE; } else { return UNKNOWN; } } } /** * @param maxVersionLevel The new maximum version level for the finalized feature. * a value of zero is special and indicates that the update is intended to * delete the finalized feature, and should be accompanied by setting * the upgradeType to safe or unsafe. * @param upgradeType Indicate what kind of upgrade should be performed in this operation. * - UPGRADE: upgrading the feature level * - SAFE_DOWNGRADE: only downgrades which do not result in metadata loss are permitted * - UNSAFE_DOWNGRADE: any downgrade, including those which may result in metadata loss, are permitted */ public FeatureUpdate(final short maxVersionLevel, final UpgradeType upgradeType) { if (maxVersionLevel == 0 && upgradeType.equals(UpgradeType.UPGRADE)) { throw new IllegalArgumentException(String.format( "The upgradeType flag should be set to SAFE_DOWNGRADE or UNSAFE_DOWNGRADE when the provided maxVersionLevel:%d is < 1.", maxVersionLevel)); } if (maxVersionLevel < 0) { throw new IllegalArgumentException("Cannot specify a negative version level."); } this.maxVersionLevel = maxVersionLevel; this.upgradeType = upgradeType; } public short maxVersionLevel() { return maxVersionLevel; } public UpgradeType upgradeType() { return upgradeType; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof FeatureUpdate)) { return false; } final FeatureUpdate that = (FeatureUpdate) other; return this.maxVersionLevel == that.maxVersionLevel && this.upgradeType.equals(that.upgradeType); } @Override public int hashCode() { return Objects.hash(maxVersionLevel, upgradeType); } @Override public String toString() { return String.format("FeatureUpdate{maxVersionLevel:%d, upgradeType:%s}", maxVersionLevel, upgradeType); } }
UpgradeType
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/subjects/BehaviorSubject.java
{ "start": 7234, "end": 14776 }
class ____<T> extends Subject<T> { final AtomicReference<Object> value; final AtomicReference<BehaviorDisposable<T>[]> observers; @SuppressWarnings("rawtypes") static final BehaviorDisposable[] EMPTY = new BehaviorDisposable[0]; @SuppressWarnings("rawtypes") static final BehaviorDisposable[] TERMINATED = new BehaviorDisposable[0]; final ReadWriteLock lock; final Lock readLock; final Lock writeLock; final AtomicReference<Throwable> terminalEvent; long index; /** * Creates a {@link BehaviorSubject} without a default item. * * @param <T> * the type of item the Subject will emit * @return the constructed {@link BehaviorSubject} */ @CheckReturnValue @NonNull public static <T> BehaviorSubject<T> create() { return new BehaviorSubject<>(null); } /** * Creates a {@link BehaviorSubject} that emits the last item it observed and all subsequent items to each * {@link Observer} that subscribes to it. * * @param <T> * the type of item the Subject will emit * @param defaultValue * the item that will be emitted first to any {@link Observer} as long as the * {@link BehaviorSubject} has not yet observed any items from its source {@code Observable} * @return the constructed {@link BehaviorSubject} * @throws NullPointerException if {@code defaultValue} is {@code null} */ @CheckReturnValue @NonNull public static <@NonNull T> BehaviorSubject<T> createDefault(T defaultValue) { Objects.requireNonNull(defaultValue, "defaultValue is null"); return new BehaviorSubject<>(defaultValue); } /** * Constructs an empty BehaviorSubject. * @param defaultValue the initial value, not null (verified) * @since 2.0 */ @SuppressWarnings("unchecked") BehaviorSubject(T defaultValue) { this.lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); this.observers = new AtomicReference<>(EMPTY); this.value = new AtomicReference<>(defaultValue); this.terminalEvent = new AtomicReference<>(); } @Override protected void subscribeActual(Observer<? super T> observer) { BehaviorDisposable<T> bs = new BehaviorDisposable<>(observer, this); observer.onSubscribe(bs); if (add(bs)) { if (bs.cancelled) { remove(bs); } else { bs.emitFirst(); } } else { Throwable ex = terminalEvent.get(); if (ex == ExceptionHelper.TERMINATED) { observer.onComplete(); } else { observer.onError(ex); } } } @Override public void onSubscribe(Disposable d) { if (terminalEvent.get() != null) { d.dispose(); } } @Override public void onNext(T t) { ExceptionHelper.nullCheck(t, "onNext called with a null value."); if (terminalEvent.get() != null) { return; } Object o = NotificationLite.next(t); setCurrent(o); for (BehaviorDisposable<T> bs : observers.get()) { bs.emitNext(o, index); } } @Override public void onError(Throwable t) { ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); if (!terminalEvent.compareAndSet(null, t)) { RxJavaPlugins.onError(t); return; } Object o = NotificationLite.error(t); for (BehaviorDisposable<T> bs : terminate(o)) { bs.emitNext(o, index); } } @Override public void onComplete() { if (!terminalEvent.compareAndSet(null, ExceptionHelper.TERMINATED)) { return; } Object o = NotificationLite.complete(); for (BehaviorDisposable<T> bs : terminate(o)) { bs.emitNext(o, index); // relaxed read okay since this is the only mutator thread } } @Override @CheckReturnValue public boolean hasObservers() { return observers.get().length != 0; } @CheckReturnValue /* test support*/ int subscriberCount() { return observers.get().length; } @Override @Nullable @CheckReturnValue public Throwable getThrowable() { Object o = value.get(); if (NotificationLite.isError(o)) { return NotificationLite.getError(o); } return null; } /** * Returns a single value the Subject currently has or null if no such value exists. * <p>The method is thread-safe. * @return a single value the Subject currently has or null if no such value exists */ @Nullable @CheckReturnValue public T getValue() { Object o = value.get(); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { return null; } return NotificationLite.getValue(o); } @Override @CheckReturnValue public boolean hasComplete() { Object o = value.get(); return NotificationLite.isComplete(o); } @Override @CheckReturnValue public boolean hasThrowable() { Object o = value.get(); return NotificationLite.isError(o); } /** * Returns true if the subject has any value. * <p>The method is thread-safe. * @return true if the subject has any value */ @CheckReturnValue public boolean hasValue() { Object o = value.get(); return o != null && !NotificationLite.isComplete(o) && !NotificationLite.isError(o); } boolean add(BehaviorDisposable<T> rs) { for (;;) { BehaviorDisposable<T>[] a = observers.get(); if (a == TERMINATED) { return false; } int len = a.length; @SuppressWarnings("unchecked") BehaviorDisposable<T>[] b = new BehaviorDisposable[len + 1]; System.arraycopy(a, 0, b, 0, len); b[len] = rs; if (observers.compareAndSet(a, b)) { return true; } } } @SuppressWarnings("unchecked") void remove(BehaviorDisposable<T> rs) { for (;;) { BehaviorDisposable<T>[] a = observers.get(); int len = a.length; if (len == 0) { return; } int j = -1; for (int i = 0; i < len; i++) { if (a[i] == rs) { j = i; break; } } if (j < 0) { return; } BehaviorDisposable<T>[] b; if (len == 1) { b = EMPTY; } else { b = new BehaviorDisposable[len - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, len - j - 1); } if (observers.compareAndSet(a, b)) { return; } } } @SuppressWarnings("unchecked") BehaviorDisposable<T>[] terminate(Object terminalValue) { setCurrent(terminalValue); return observers.getAndSet(TERMINATED); } void setCurrent(Object o) { writeLock.lock(); index++; value.lazySet(o); writeLock.unlock(); } static final
BehaviorSubject
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/EntityGraphRepositoryMethodsIntegrationTests.java
{ "start": 2581, "end": 9221 }
class ____ { @Autowired EntityManager em; @Autowired RepositoryMethodsWithEntityGraphConfigRepository repository; private User tom; private User ollie; private User christoph; private Role role; private PersistenceUtil util = Persistence.getPersistenceUtil(); @BeforeEach void setup() { tom = new User("Thomas", "Darimont", "tdarimont@example.org"); ollie = new User("Oliver", "Gierke", "ogierke@example.org"); christoph = new User("Christoph", "Strobl", "cstrobl@example.org"); role = new Role("Developer"); em.persist(role); tom.getRoles().add(role); tom = repository.save(tom); ollie = repository.save(ollie); tom.getColleagues().add(ollie); christoph.addRole(role); christoph = repository.save(christoph); ollie.getColleagues().add(christoph); repository.save(ollie); } @Test // DATAJPA-612 void shouldRespectConfiguredJpaEntityGraph() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); List<User> result = repository.findAll(); assertThat(result).hasSize(3); assertThat(util.isLoaded(result.get(0), "roles")).isTrue(); assertThat(result.get(0)).isEqualTo(tom); } @Test // DATAJPA-689 void shouldRespectConfiguredJpaEntityGraphInFindOne() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); User user = repository.findById(tom.getId()).get(); assertThat(user).isNotNull(); assertThat(util.isLoaded(user, "colleagues")) // .describedAs("colleagues should be fetched with 'user.detail' fetchgraph") // .isTrue(); } @Test // DATAJPA-696 void shouldRespectInferFetchGraphFromMethodName() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); User user = repository.getOneWithDefinedEntityGraphById(tom.getId()); assertThat(user).isNotNull(); assertThat(util.isLoaded(user, "colleagues")) // .describedAs("colleagues should be fetched with 'user.detail' fetchgraph") // .isTrue(); } @Test // DATAJPA-696 void shouldRespectDynamicFetchGraphForGetOneWithAttributeNamesById() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); User user = repository.getOneWithAttributeNamesById(tom.getId()); assertThat(user).isNotNull(); assertThat(util.isLoaded(user, "colleagues")) // .describedAs("colleagues should be fetched with 'user.detail' fetchgraph") // .isTrue(); assertThat(util.isLoaded(user, "colleagues")).isTrue(); SoftAssertions softly = new SoftAssertions(); for (User colleague : user.getColleagues()) { softly.assertThat(util.isLoaded(colleague, "roles")).isTrue(); } softly.assertAll(); } @Test // DATAJPA-790, DATAJPA-1087 void shouldRespectConfiguredJpaEntityGraphWithPaginationAndQueryDslPredicates() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); Page<User> page = repository.findAll(QUser.user.firstname.isNotNull(), PageRequest.of(0, 100)); List<User> result = page.getContent(); assertThat(result).hasSize(3); assertThat(util.isLoaded(result.get(0), "roles")).isTrue(); assertThat(result.get(0)).isEqualTo(tom); } @Test // DATAJPA-1207 void shouldRespectConfiguredJpaEntityGraphWithPaginationAndSpecification() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); Page<User> page = repository.findAll( // (Specification<User>) this::firstNameIsNotNull, // PageRequest.of(0, 100) // ); List<User> result = page.getContent(); assertThat(result).hasSize(3); assertThat(util.isLoaded(result.get(0), "roles")).isTrue(); assertThat(result.get(0)).isEqualTo(tom); } @Test // DATAJPA-1041 void shouldRespectNamedEntitySubGraph() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); User user = repository.findOneWithMultipleSubGraphsUsingNamedEntityGraphById(tom.getId()); assertThat(user).isNotNull(); SoftAssertions softly = new SoftAssertions(); softly.assertThat(util.isLoaded(user, "colleagues")) // .describedAs("colleagues on root should have been fetched by named 'User.colleagues' subgraph declaration") // .isTrue(); for (User colleague : user.getColleagues()) { softly.assertThat(util.isLoaded(colleague, "colleagues")).isTrue(); softly.assertThat(util.isLoaded(colleague, "roles")).isTrue(); } softly.assertAll(); } @Test // DATAJPA-1041 void shouldRespectMultipleSubGraphForSameAttributeWithDynamicFetchGraph() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); User user = repository.findOneWithMultipleSubGraphsById(tom.getId()); assertThat(user).isNotNull(); SoftAssertions softly = new SoftAssertions(); softly.assertThat(util.isLoaded(user, "colleagues")) // .describedAs("colleagues on root should have been fetched by dynamic subgraph declaration") // .isTrue(); for (User colleague : user.getColleagues()) { softly.assertThat(util.isLoaded(colleague, "colleagues")).isTrue(); softly.assertThat(util.isLoaded(colleague, "roles")).isTrue(); } softly.assertAll(); } @Test // DATAJPA-1041, DATAJPA-1075 @Disabled // likely broken due to the fixes made for HHH-15391 void shouldCreateDynamicGraphWithMultipleLevelsOfSubgraphs() { assumeThat(currentEntityManagerIsAJpa21EntityManager(em)).isTrue(); em.flush(); em.clear(); User user = repository.findOneWithDeepGraphById(tom.getId()); assertThat(user).isNotNull(); SoftAssertions softly = new SoftAssertions(); softly.assertThat(Persistence.getPersistenceUtil().isLoaded(user, "colleagues")) // .describedAs("Colleagues on root should have been fetched by dynamic subgraph declaration") // .isTrue(); for (User colleague : user.getColleagues()) { softly.assertThat(Persistence.getPersistenceUtil().isLoaded(colleague, "colleagues")).isTrue(); softly.assertThat(Persistence.getPersistenceUtil().isLoaded(colleague, "roles")).isTrue(); for (User colleagueOfColleague : colleague.getColleagues()) { softly.assertThat(Persistence.getPersistenceUtil().isLoaded(colleagueOfColleague, "roles")).isTrue(); softly.assertThat(Persistence.getPersistenceUtil().isLoaded(colleagueOfColleague, "colleagues")).isFalse(); } } softly.assertAll(); } private Predicate firstNameIsNotNull(Root<User> root, CriteriaQuery<?> __, CriteriaBuilder criteriaBuilder) { return criteriaBuilder.isNotNull(root.get(User_.firstname)); } }
EntityGraphRepositoryMethodsIntegrationTests
java
redisson__redisson
redisson/src/main/java/org/redisson/client/RedisReconnectedException.java
{ "start": 688, "end": 833 }
class ____ extends RedisException { public RedisReconnectedException(String message) { super(message); } }
RedisReconnectedException
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/NamespaceUserRepositoryTests.java
{ "start": 1305, "end": 1707 }
class ____ extends UserRepositoryTests { @Autowired ListableBeanFactory beanFactory; @Test void registersPostProcessors() { hasAtLeastOneBeanOfType(PersistenceAnnotationBeanPostProcessor.class); } private void hasAtLeastOneBeanOfType(Class<?> beanType) { Map<String, ?> beans = beanFactory.getBeansOfType(beanType); assertFalse(beans.entrySet().isEmpty()); } }
NamespaceUserRepositoryTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/RoutingNode.java
{ "start": 1359, "end": 13673 }
class ____ implements Iterable<ShardRouting> { private final String nodeId; @Nullable private final DiscoveryNode node; private final LinkedHashMap<ShardId, ShardRouting> shards; // LinkedHashMap to preserve order private final LinkedHashSet<ShardRouting> initializingShards; private final LinkedHashSet<ShardRouting> relocatingShards; private final LinkedHashSet<ShardRouting> startedShards; private final Map<Index, Set<ShardRouting>> shardsByIndex; /** * @param nodeId node id of this routing node * @param node discovery node for this routing node * @param sizeGuess estimate for the number of shards that will be added to this instance to save re-hashing on subsequent calls to * {@link #add(ShardRouting)} */ RoutingNode(String nodeId, @Nullable DiscoveryNode node, int sizeGuess) { this.nodeId = nodeId; this.node = node; this.shards = Maps.newLinkedHashMapWithExpectedSize(sizeGuess); this.relocatingShards = new LinkedHashSet<>(); this.initializingShards = new LinkedHashSet<>(); this.startedShards = new LinkedHashSet<>(); this.shardsByIndex = Maps.newHashMapWithExpectedSize(sizeGuess); assert invariant(); } private RoutingNode(RoutingNode original) { this.nodeId = original.nodeId; this.node = original.node; this.shards = new LinkedHashMap<>(original.shards); this.relocatingShards = new LinkedHashSet<>(original.relocatingShards); this.initializingShards = new LinkedHashSet<>(original.initializingShards); this.startedShards = new LinkedHashSet<>(original.startedShards); this.shardsByIndex = Maps.copyOf(original.shardsByIndex, HashSet::new); assert invariant(); } RoutingNode copy() { return new RoutingNode(this); } @Override public Iterator<ShardRouting> iterator() { return Collections.unmodifiableCollection(shards.values()).iterator(); } /** * Returns the nodes {@link DiscoveryNode}. * * @return discoveryNode of this node */ @Nullable public DiscoveryNode node() { return this.node; } @Nullable public ShardRouting getByShardId(ShardId id) { return shards.get(id); } public boolean hasIndex(Index index) { return shardsByIndex.containsKey(index); } /** * Get the id of this node * @return id of the node */ public String nodeId() { return this.nodeId; } /** * Number of shards assigned to this node. Includes relocating shards. Use {@link #numberOfOwningShards()} to exclude relocating shards. */ public int size() { return shards.size(); } /** * Add a new shard to this node * @param shard Shard to create on this Node */ void add(ShardRouting shard) { addInternal(shard, true); } void addWithoutValidation(ShardRouting shard) { addInternal(shard, false); } private void addInternal(ShardRouting shard, boolean validate) { final ShardRouting existing = shards.putIfAbsent(shard.shardId(), shard); if (existing != null) { final IllegalStateException e = new IllegalStateException( "Trying to add a shard " + shard.shardId() + " to a node [" + nodeId + "] where it already exists. current [" + shards.get(shard.shardId()) + "]. new [" + shard + "]" ); assert false : e; throw e; } if (shard.initializing()) { initializingShards.add(shard); } else if (shard.relocating()) { relocatingShards.add(shard); } else if (shard.started()) { startedShards.add(shard); } shardsByIndex.computeIfAbsent(shard.index(), k -> new HashSet<>()).add(shard); assert validate == false || invariant(); } void update(ShardRouting oldShard, ShardRouting newShard) { if (shards.containsKey(oldShard.shardId()) == false) { // Shard was already removed by routing nodes iterator // TODO: change caller logic in RoutingNodes so that this check can go away return; } ShardRouting previousValue = shards.put(newShard.shardId(), newShard); assert previousValue == oldShard : "expected shard " + previousValue + " but was " + oldShard; if (oldShard.initializing()) { boolean exist = initializingShards.remove(oldShard); assert exist : "expected shard " + oldShard + " to exist in initializingShards"; } else if (oldShard.relocating()) { boolean exist = relocatingShards.remove(oldShard); assert exist : "expected shard " + oldShard + " to exist in relocatingShards"; } else if (oldShard.started()) { boolean exist = startedShards.remove(oldShard); assert exist : "expected shard " + oldShard + " to exist in startedShards"; } final Set<ShardRouting> byIndex = shardsByIndex.get(oldShard.index()); byIndex.remove(oldShard); byIndex.add(newShard); if (newShard.initializing()) { initializingShards.add(newShard); } else if (newShard.relocating()) { relocatingShards.add(newShard); } else if (newShard.started()) { startedShards.add(newShard); } assert invariant(); } void remove(ShardRouting shard) { ShardRouting previousValue = shards.remove(shard.shardId()); assert previousValue == shard : "expected shard " + previousValue + " but was " + shard; if (shard.initializing()) { boolean exist = initializingShards.remove(shard); assert exist : "expected shard " + shard + " to exist in initializingShards"; } else if (shard.relocating()) { boolean exist = relocatingShards.remove(shard); assert exist : "expected shard " + shard + " to exist in relocatingShards"; } else if (shard.started()) { boolean exist = startedShards.remove(shard); assert exist : "expected shard " + shard + " to exist in startedShards"; } final Set<ShardRouting> byIndex = shardsByIndex.get(shard.index()); byIndex.remove(shard); if (byIndex.isEmpty()) { shardsByIndex.remove(shard.index()); } assert invariant(); } public Iterable<ShardRouting> initializing() { return Iterables.assertReadOnly(initializingShards); } public Iterable<ShardRouting> relocating() { return Iterables.assertReadOnly(relocatingShards); } public Iterable<ShardRouting> started() { return Iterables.assertReadOnly(startedShards); } /** * Determine the number of shards with a specific state * @param state which should be counted * @return number of shards */ public int numberOfShardsWithState(ShardRoutingState state) { return internalGetShardsWithState(state).size(); } /** * Determine the shards with a specific state * @param state state which should be listed * @return List of shards */ public Stream<ShardRouting> shardsWithState(ShardRoutingState state) { return internalGetShardsWithState(state).stream(); } /** * Determine the shards of an index with a specific state * @param index id of the index * @param states set of states which should be listed * @return a list of shards */ public Stream<ShardRouting> shardsWithState(String index, ShardRoutingState... states) { return Stream.of(states).flatMap(state -> shardsWithState(index, state)); } public Stream<ShardRouting> shardsWithState(String index, ShardRoutingState state) { return shardsWithState(state).filter(shardRouting -> Objects.equals(shardRouting.getIndexName(), index)); } private LinkedHashSet<ShardRouting> internalGetShardsWithState(ShardRoutingState state) { return switch (state) { case UNASSIGNED -> throw new IllegalArgumentException("Unassigned shards are not linked to a routing node"); case INITIALIZING -> initializingShards; case STARTED -> startedShards; case RELOCATING -> relocatingShards; }; } /** * The number of shards on this node that will not be eventually relocated. */ public int numberOfOwningShards() { return shards.size() - relocatingShards.size(); } public int numberOfOwningShardsForIndex(final Index index) { final Set<ShardRouting> shardRoutings = shardsByIndex.get(index); if (shardRoutings == null) { return 0; } else { return Math.toIntExact(shardRoutings.stream().filter(Predicate.not(ShardRouting::relocating)).count()); } } public String prettyPrint() { StringBuilder sb = new StringBuilder(); sb.append("-----node_id[").append(nodeId).append("][").append(node == null ? "X" : "V").append("]\n"); for (ShardRouting entry : shards.values()) { sb.append("--------").append(entry.shortSummary()).append('\n'); } return sb.toString(); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("routingNode (["); if (node != null) { sb.append(node.getName()); sb.append("]["); sb.append(node.getId()); sb.append("]["); sb.append(node.getHostName()); sb.append("]["); sb.append(node.getHostAddress()); } else { sb.append("null"); } sb.append("], ["); sb.append(shards.size()); sb.append(" assigned shards])"); return sb.toString(); } private static final ShardRouting[] EMPTY_SHARD_ROUTING_ARRAY = new ShardRouting[0]; public ShardRouting[] copyShards() { return shards.values().toArray(EMPTY_SHARD_ROUTING_ARRAY); } public Index[] copyIndices() { return shardsByIndex.keySet().toArray(Index.EMPTY_ARRAY); } public boolean isEmpty() { return shards.isEmpty(); } boolean invariant() { var shardRoutingsInitializing = new ArrayList<ShardRouting>(shards.size()); var shardRoutingsRelocating = new ArrayList<ShardRouting>(shards.size()); var shardRoutingsStarted = new ArrayList<ShardRouting>(shards.size()); // this guess assumes 1 shard per index, this is not precise, but okay for assertion var shardRoutingsByIndex = Maps.<Index, Set<ShardRouting>>newHashMapWithExpectedSize(shards.size()); for (var shard : shards.values()) { switch (shard.state()) { case INITIALIZING -> shardRoutingsInitializing.add(shard); case RELOCATING -> shardRoutingsRelocating.add(shard); case STARTED -> shardRoutingsStarted.add(shard); } shardRoutingsByIndex.computeIfAbsent(shard.index(), k -> new HashSet<>(10)).add(shard); } assert initializingShards.size() == shardRoutingsInitializing.size() && initializingShards.containsAll(shardRoutingsInitializing); assert relocatingShards.size() == shardRoutingsRelocating.size() && relocatingShards.containsAll(shardRoutingsRelocating); assert startedShards.size() == shardRoutingsStarted.size() && startedShards.containsAll(shardRoutingsStarted); assert shardRoutingsByIndex.equals(shardsByIndex); return true; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RoutingNode that = (RoutingNode) o; return nodeId.equals(that.nodeId) && Objects.equals(node, that.node) && shards.equals(that.shards); } @Override public int hashCode() { return Objects.hash(nodeId, node, shards); } }
RoutingNode
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/translog/Translog.java
{ "start": 61455, "end": 67079 }
class ____ extends Operation { private static final int FORMAT_6_0 = 4; // 6.0 - * public static final int FORMAT_NO_PARENT = FORMAT_6_0 + 1; // since 7.0 public static final int FORMAT_NO_VERSION_TYPE = FORMAT_NO_PARENT + 1; public static final int FORMAT_NO_DOC_TYPE = FORMAT_NO_VERSION_TYPE + 1; // since 8.0 public static final int FORMAT_REORDERED = FORMAT_NO_DOC_TYPE + 1; public static final int SERIALIZATION_FORMAT = FORMAT_REORDERED; private final BytesRef uid; private final long version; private static Delete readFrom(StreamInput in) throws IOException { final int format = in.readVInt();// SERIALIZATION_FORMAT assert format >= FORMAT_6_0 : "format was: " + format; final BytesRef uid; final long version; final long seqNo; final long primaryTerm; if (format < FORMAT_REORDERED) { if (format < FORMAT_NO_DOC_TYPE) { in.readString(); // Can't assert that this is _doc because pre-8.0 indexes can have any name for a type } uid = Uid.encodeId(in.readString()); if (format < FORMAT_NO_DOC_TYPE) { final String docType = in.readString(); assert docType.equals(IdFieldMapper.NAME) : docType + " != " + IdFieldMapper.NAME; in.readSlicedBytesReference(); // uid } version = in.readLong(); if (format < FORMAT_NO_VERSION_TYPE) { in.readByte(); // versionType } seqNo = in.readLong(); primaryTerm = in.readLong(); } else { version = in.readLong(); seqNo = in.readLong(); primaryTerm = in.readLong(); uid = in.readBytesRef(); } return new Delete(uid, seqNo, primaryTerm, version); } public Delete(Engine.Delete delete, Engine.DeleteResult deleteResult) { this(delete.uid(), deleteResult.getSeqNo(), delete.primaryTerm(), deleteResult.getVersion()); } /** utility for testing */ public Delete(String id, long seqNo, long primaryTerm) { this(id, seqNo, primaryTerm, Versions.MATCH_ANY); } /** utility for testing */ public Delete(String id, long seqNo, long primaryTerm, long version) { this(Uid.encodeId(id), seqNo, primaryTerm, version); } public Delete(BytesRef uid, long seqNo, long primaryTerm, long version) { super(seqNo, primaryTerm); this.uid = Objects.requireNonNull(uid); this.version = version; } @Override public Type opType() { return Type.DELETE; } @Override public long estimateSize() { return uid.length + (3 * Long.BYTES); // seq_no, primary_term, and version; } @Override protected void writeHeader(int format, StreamOutput out) throws IOException { out.writeVInt(format); out.writeLong(version); out.writeLong(seqNo); out.writeLong(primaryTerm); out.writeBytesRef(uid); } public BytesRef uid() { return uid; } public long version() { return this.version; } @Override public void writeBody(final StreamOutput out) throws IOException { final int format = out.getTransportVersion().onOrAfter(TransportVersions.V_8_0_0) ? out.getTransportVersion().supports(REORDERED_TRANSLOG_OPERATIONS) ? SERIALIZATION_FORMAT : FORMAT_NO_DOC_TYPE : FORMAT_NO_VERSION_TYPE; if (format < FORMAT_REORDERED) { out.writeVInt(format); if (format < FORMAT_NO_DOC_TYPE) { out.writeString(MapperService.SINGLE_MAPPING_NAME); } out.writeString(Uid.decodeId(uid)); if (format < FORMAT_NO_DOC_TYPE) { out.writeString(IdFieldMapper.NAME); out.writeBytesRef(uid); } out.writeLong(version); out.writeLong(seqNo); out.writeLong(primaryTerm); } else { writeHeader(format, out); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Delete delete = (Delete) o; return uid.equals(delete.uid) && seqNo == delete.seqNo && primaryTerm == delete.primaryTerm && version == delete.version; } @Override public int hashCode() { int result = uid.hashCode(); result += 31 * Long.hashCode(seqNo); result = 31 * result + Long.hashCode(primaryTerm); result = 31 * result + Long.hashCode(version); return result; } @Override public String toString() { return "Delete{" + "id='" + Uid.decodeId(uid) + "', seqNo=" + seqNo + ", primaryTerm=" + primaryTerm + ", version=" + version + '}'; } } public static final
Delete
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/bind/ServletRequestParameterPropertyValues.java
{ "start": 1196, "end": 1471 }
class ____ not immutable to be able to efficiently remove property * values that should be ignored for binding. * * @author Rod Johnson * @author Juergen Hoeller * @see org.springframework.web.util.WebUtils#getParametersStartingWith */ @SuppressWarnings("serial") public
is
java
apache__camel
components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/TransientCamelContextManager.java
{ "start": 1748, "end": 10020 }
class ____ implements CamelContextManager { private static final Logger LOG = LoggerFactory.getLogger(TransientCamelContextManager.class); private final TestExecutionConfiguration testConfigurationBuilder; private final CamelContextConfiguration camelContextConfiguration; private final Service service; private ModelCamelContext context; protected ProducerTemplate template; protected FluentProducerTemplate fluentTemplate; protected ConsumerTemplate consumer; private Properties extra; private ExtensionContext.Store globalStore; public TransientCamelContextManager(TestExecutionConfiguration testConfigurationBuilder, CamelContextConfiguration camelContextConfiguration) { this.testConfigurationBuilder = testConfigurationBuilder; this.camelContextConfiguration = camelContextConfiguration; service = camelContextConfiguration.camelContextService(); } @Override public void createCamelContext(Object test) throws Exception { initialize(test); } @Override public void beforeContextStart(Object test) throws Exception { applyCamelPostProcessor(test); camelContextConfiguration.postProcessor().postSetup(); } private void initialize(Object test) throws Exception { LOG.debug("Initializing a new CamelContext"); // jmx is enabled if we have configured to use it, or if dump route coverage is enabled (it requires JMX) or if // the component camel-debug is in the classpath if (testConfigurationBuilder.isJmxEnabled() || testConfigurationBuilder.isRouteCoverageEnabled() || isCamelDebugPresent()) { enableJMX(); } else { disableJMX(); } context = (ModelCamelContext) camelContextConfiguration.camelContextSupplier().createCamelContext(); assert context != null : "No context found!"; // TODO: fixme (some tests try to access the context before it's set on the test) final Method setContextMethod = test.getClass().getMethod("setContext", ModelCamelContext.class); setContextMethod.invoke(test, context); // add custom beans camelContextConfiguration.registryBinder().bindToRegistry(context.getRegistry()); // reduce default shutdown timeout to avoid waiting for 300 seconds context.getShutdownStrategy().setTimeout(camelContextConfiguration.shutdownTimeout()); // set debugger if enabled if (camelContextConfiguration.useDebugger()) { CamelContextTestHelper.setupDebugger(context, camelContextConfiguration.breakpoint()); } setupTemplates(); // enable auto mocking if enabled final String mockPattern = camelContextConfiguration.mockEndpoints(); final String mockAndSkipPattern = camelContextConfiguration.mockEndpointsAndSkip(); CamelContextTestHelper.enableAutoMocking(context, mockPattern, mockAndSkipPattern); // enable auto stub if enabled final String stubPattern = camelContextConfiguration.stubEndpoints(); CamelContextTestHelper.enableAutoStub(context, stubPattern); // auto startup exclude final String excludePattern = camelContextConfiguration.autoStartupExcludePatterns(); if (excludePattern != null) { context.setAutoStartupExcludePattern(excludePattern); } // configure properties component (mandatory for testing) configurePropertiesComponent(); configureIncludeExcludePatterns(); // prepare for in-between tests beforeContextStart(test); if (testConfigurationBuilder.useRouteBuilder()) { setupRoutes(); tryStartCamelContext(); } else { CamelContextTestHelper.replaceFromEndpoints(context, camelContextConfiguration.fromEndpoints()); LOG.debug("Using route builder from the created context: {}", context); } LOG.debug("Routing Rules are: {}", context.getRoutes()); } private void setupTemplates() { template = context.createProducerTemplate(); template.start(); fluentTemplate = context.createFluentProducerTemplate(); fluentTemplate.start(); consumer = context.createConsumerTemplate(); consumer.start(); } private void configureIncludeExcludePatterns() { final String include = camelContextConfiguration.routeFilterIncludePattern(); final String exclude = camelContextConfiguration.routeFilterExcludePattern(); CamelContextTestHelper.configureIncludeExcludePatterns(context, include, exclude); } private void configurePropertiesComponent() { if (extra == null) { extra = camelContextConfiguration.useOverridePropertiesWithPropertiesComponent(); } Boolean ignore = camelContextConfiguration.ignoreMissingLocationWithPropertiesComponent(); CamelContextTestHelper.configurePropertiesComponent(context, extra, new JunitPropertiesSource(globalStore), ignore); } private void setupRoutes() throws Exception { RoutesBuilder[] builders = camelContextConfiguration.routesSupplier().createRouteBuilders(); CamelContextTestHelper.setupRoutes(context, builders); CamelContextTestHelper.replaceFromEndpoints(context, camelContextConfiguration.fromEndpoints()); } private void tryStartCamelContext() throws Exception { boolean skip = CamelContextTestHelper.isSkipAutoStartContext(testConfigurationBuilder); if (skip) { LOG.info( "Skipping starting CamelContext as system property skipStartingCamelContext is set to be true or auto start context is false."); } else if (testConfigurationBuilder.isUseAdviceWith()) { LOG.info("Skipping starting CamelContext as isUseAdviceWith is set to true."); } else { CamelContextTestHelper.startCamelContextOrService(context, camelContextConfiguration.camelContextService()); } } /** * Disables the JMX agent. */ protected void disableJMX() { DefaultCamelContext.setDisableJmx(true); } /** * Enables the JMX agent. */ protected void enableJMX() { DefaultCamelContext.setDisableJmx(false); } @Override public ModelCamelContext context() { return context; } @Override public ProducerTemplate template() { return template; } @Override public FluentProducerTemplate fluentTemplate() { return fluentTemplate; } @Override public ConsumerTemplate consumer() { return consumer; } @Override public Service camelContextService() { return service; } @Override public void startCamelContext() throws Exception { CamelContextTestHelper.startCamelContextOrService(context, camelContextConfiguration.camelContextService()); } @Override public void stopCamelContext() { doStopCamelContext(context, camelContextConfiguration.camelContextService()); } @Override public void stop() { doStopTemplates(consumer, template, fluentTemplate); doStopCamelContext(context, service); } @Override public void stopTemplates() { } @Override public void close() { // NO-OP } private static void doStopTemplates( ConsumerTemplate consumer, ProducerTemplate template, FluentProducerTemplate fluentTemplate) { if (consumer != null) { consumer.stop(); } if (template != null) { template.stop(); } if (fluentTemplate != null) { fluentTemplate.stop(); } } protected void doStopCamelContext(CamelContext context, Service camelContextService) { if (camelContextService != null) { camelContextService.stop(); } else { if (context != null) { context.stop(); } } } protected void applyCamelPostProcessor(Object test) throws Exception { // use the bean post processor if the test
TransientCamelContextManager
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/MessageTableHelper.java
{ "start": 15410, "end": 21347 }
class ____ { String kind; String type; String key; Object value; Long position; Long size; Boolean important = Boolean.FALSE; TableRow(String kind, String type, String key, Object value) { this(kind, type, key, value, null, null); } TableRow(String kind, String type, String key, Object value, Boolean important) { this(kind, type, key, value, null, null); this.important = important; } TableRow(String kind, String type, String key, Object value, Long size, Long position) { this.kind = kind; this.type = type; this.key = key; this.value = value; this.position = position; this.size = size; } String valueAsString() { if (value == null || "null".equals(value)) { value = "null"; if (loggingColor) { value = Ansi.ansi().fgBrightDefault().a(Ansi.Attribute.INTENSITY_FAINT).a(value).reset().toString(); } } if (loggingColor && important) { value = Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(value).reset().toString(); } return value.toString(); } String valueAsStringPretty() { return CamelCommandHelper.valueAsStringPretty(value, loggingColor); } String valueAsStringRed() { if (value != null) { if (loggingColor) { return Ansi.ansi().fgRed().a(value).reset().toString(); } else { return value.toString(); } } return ""; } String keyAsString() { if (key == null) { return ""; } return key; } String kindAsString() { return kind; } String kindAsStringRed() { if (loggingColor) { return Ansi.ansi().fgRed().a(kind).reset().toString(); } else { return kind; } } String typeAsString() { String s; if (type == null) { s = "null"; } else if (type.startsWith("java.util.concurrent")) { s = type.substring(21); } else if (type.startsWith("java.lang.") || type.startsWith("java.util.")) { s = type.substring(10); } else if (type.startsWith("org.apache.camel.support.")) { s = type.substring(25); } else if (type.equals("org.apache.camel.converter.stream.CachedOutputStream.WrappedInputStream")) { s = "WrappedInputStream"; } else if (type.startsWith("org.apache.camel.converter.stream.")) { s = type.substring(34); } else if (type.length() > 34) { // type must not be too long int pos = type.lastIndexOf('.'); if (pos == -1) { pos = type.length() - 34; } s = type.substring(pos + 1); } else { s = type; } s = "(" + s + ")"; if (loggingColor) { s = Ansi.ansi().fgBrightDefault().a(Ansi.Attribute.INTENSITY_FAINT).a(s).reset().toString(); } return s; } String typeAndLengthAsString() { String s; if (type == null) { s = "null"; } else if (type.startsWith("java.util.concurrent")) { s = type.substring(21); } else if (type.startsWith("java.lang.") || type.startsWith("java.util.")) { s = type.substring(10); } else if (type.startsWith("org.apache.camel.support.")) { s = type.substring(25); } else if (type.equals("org.apache.camel.converter.stream.CachedOutputStream.WrappedInputStream")) { s = "WrappedInputStream"; } else if (type.startsWith("org.apache.camel.converter.stream.")) { s = type.substring(34); } else { s = type; } s = "(" + s + ")"; int l = valueLength(); long sz = size != null ? size : -1; long p = position != null ? position : -1; StringBuilder sb = new StringBuilder(); if (sz != -1) { sb.append(" size: ").append(sz); } if (p != -1) { sb.append(" pos: ").append(p); } if (l != -1) { sb.append(" bytes: ").append(l); } if (!sb.isEmpty()) { s = s + " (" + sb.toString().trim() + ")"; } if (loggingColor) { s = Ansi.ansi().fgBrightDefault().a(Ansi.Attribute.INTENSITY_FAINT).a(s).reset().toString(); } return s; } String mepAsKey() { String s = key; if (loggingColor) { s = Ansi.ansi().fgBrightMagenta().a(Ansi.Attribute.INTENSITY_FAINT).a(s).reset().toString(); } return s; } String exchangeIdAsValue() { if (value == null) { return ""; } String s = value.toString(); if (loggingColor) { Ansi.Color color = exchangeIdColorChooser != null ? exchangeIdColorChooser.color(s) : Ansi.Color.DEFAULT; s = Ansi.ansi().fg(color).a(s).reset().toString(); } return s; } int valueLength() { if (value == null) { return -1; } else { return valueAsString().length(); } } } }
TableRow
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/admin/FakeForwardingAdmin.java
{ "start": 871, "end": 1017 }
class ____ extends ForwardingAdmin { public FakeForwardingAdmin(Map<String, Object> configs) { super(configs); } }
FakeForwardingAdmin
java
elastic__elasticsearch
x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/MainResponse.java
{ "start": 381, "end": 1690 }
class ____ { private final String nodeName; private final String version; private final String clusterName; private final String clusterUuid; public MainResponse(String nodeName, String version, String clusterName, String clusterUuid) { this.nodeName = nodeName; this.version = version; this.clusterName = clusterName; this.clusterUuid = clusterUuid; } public String getNodeName() { return nodeName; } public String getVersion() { return version; } public String getClusterName() { return clusterName; } public String getClusterUuid() { return clusterUuid; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MainResponse other = (MainResponse) o; return Objects.equals(nodeName, other.nodeName) && Objects.equals(version, other.version) && Objects.equals(clusterUuid, other.clusterUuid) && Objects.equals(clusterName, other.clusterName); } @Override public int hashCode() { return Objects.hash(nodeName, version, clusterUuid, clusterName); } }
MainResponse
java
quarkusio__quarkus
independent-projects/tools/analytics-common/src/main/java/io/quarkus/analytics/dto/config/LocalConfig.java
{ "start": 79, "end": 464 }
class ____ implements AnalyticsLocalConfig, Serializable { private boolean disabled; public LocalConfig(boolean disabled) { this.disabled = disabled; } public LocalConfig() { } @Override public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } }
LocalConfig
java
elastic__elasticsearch
modules/data-streams/src/internalClusterTest/java/org/elasticsearch/datastreams/SystemDataStreamIT.java
{ "start": 19244, "end": 25051 }
class ____ extends Plugin implements SystemIndexPlugin { @Override public Collection<SystemDataStreamDescriptor> getSystemDataStreamDescriptors() { try { CompressedXContent mappings = new CompressedXContent("{\"properties\":{\"name\":{\"type\":\"keyword\"}}}"); return List.of( new SystemDataStreamDescriptor( ".test-data-stream", "system data stream test", Type.EXTERNAL, ComposableIndexTemplate.builder() .indexPatterns(List.of(".test-data-stream")) .template(new Template(Settings.EMPTY, mappings, null)) .dataStreamTemplate(new DataStreamTemplate()) .build(), Map.of(), List.of("product"), "product", ExecutorNames.DEFAULT_SYSTEM_DATA_STREAM_THREAD_POOLS ), new SystemDataStreamDescriptor( ".test-failure-store", "system data stream test with failure store", Type.EXTERNAL, ComposableIndexTemplate.builder() .indexPatterns(List.of(".test-failure-store")) .template( Template.builder() .mappings(new CompressedXContent(""" { "properties": { "@timestamp" : { "type": "date" }, "count": { "type": "long" } } }""")) .dataStreamOptions( new DataStreamOptions.Template(DataStreamFailureStore.builder().enabled(true).buildTemplate()) ) ) .dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate()) .build(), Map.of(), List.of("product"), "product", ExecutorNames.DEFAULT_SYSTEM_DATA_STREAM_THREAD_POOLS ) ); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public String getFeatureName() { return SystemDataStreamIT.class.getSimpleName(); } @Override public String getFeatureDescription() { return "Integration testing of system data streams"; } @Override public void cleanUpFeature( ClusterService clusterService, ProjectResolver projectResolver, Client client, TimeValue masterNodeTimeout, ActionListener<ResetFeatureStateStatus> listener ) { Collection<SystemDataStreamDescriptor> dataStreamDescriptors = getSystemDataStreamDescriptors(); final DeleteDataStreamAction.Request request = new DeleteDataStreamAction.Request( TEST_REQUEST_TIMEOUT, dataStreamDescriptors.stream() .map(SystemDataStreamDescriptor::getDataStreamName) .collect(Collectors.toList()) .toArray(Strings.EMPTY_ARRAY) ); request.indicesOptions( IndicesOptions.builder(request.indicesOptions()) .concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ALLOW_UNAVAILABLE_TARGETS) .build() ); try { client.execute( DeleteDataStreamAction.INSTANCE, request, ActionListener.wrap( response -> SystemIndexPlugin.super.cleanUpFeature( clusterService, projectResolver, client, masterNodeTimeout, listener ), e -> { Throwable unwrapped = ExceptionsHelper.unwrapCause(e); if (unwrapped instanceof ResourceNotFoundException) { SystemIndexPlugin.super.cleanUpFeature( clusterService, projectResolver, client, masterNodeTimeout, listener ); } else { listener.onFailure(e); } } ) ); } catch (Exception e) { Throwable unwrapped = ExceptionsHelper.unwrapCause(e); if (unwrapped instanceof ResourceNotFoundException) { SystemIndexPlugin.super.cleanUpFeature(clusterService, projectResolver, client, masterNodeTimeout, listener); } else { listener.onFailure(e); } } } } }
TestSystemDataStreamPlugin
java
quarkusio__quarkus
extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/DeleteMethodImplementor.java
{ "start": 1105, "end": 6701 }
class ____ extends StandardMethodImplementor { private static final String METHOD_NAME = "delete"; private static final String RESOURCE_METHOD_NAME = "delete"; private static final String EXCEPTION_MESSAGE = "Failed to delete an entity"; private static final String REL = "remove"; public DeleteMethodImplementor(Capabilities capabilities) { super(capabilities); } /** * Generate JAX-RS DELETE method. * * The RESTEasy Classic version exposes {@link RestDataResource#delete(Object)} * and the generated code looks more or less like this: * * <pre> * {@code * &#64;DELETE * &#64;Path("{id}") * &#64;LinkResource(rel = "remove", entityClassName = "com.example.Entity") * public Response delete(@PathParam("id") ID id) throws RestDataPanacheException { * try { * boolean deleted = restDataResource.delete(id); * if (deleted) { * return Response.noContent().build(); * } else { * return Response.status(404).build(); * } * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> * * The RESTEasy Reactive version exposes {@link io.quarkus.rest.data.panache.ReactiveRestDataResource#delete(Object)} * and the generated code looks more or less like this: * * <pre> * {@code * &#64;DELETE * &#64;Path("{id}") * &#64;LinkResource(rel = "remove", entityClassName = "com.example.Entity") * public Uni<Response> delete(@PathParam("id") ID id) throws RestDataPanacheException { * try { * return restDataResource.delete(id) * .map(deleted -> deleted ? Response.noContent().build() : Response.status(404).build()); * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> */ @Override protected void implementInternal(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(METHOD_NAME, classCreator, isNotReactivePanache() ? responseType(resourceMetadata.getEntityType()) : uniType(resourceMetadata.getEntityType()), param("id", resourceMetadata.getIdType())); // Add method annotations addPathAnnotation(methodCreator, appendToPath(resourceProperties.getPath(RESOURCE_METHOD_NAME), "{id}")); addDeleteAnnotation(methodCreator); addPathParamAnnotation(methodCreator.getParameterAnnotations(0), "id"); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, RestResponse.Status.NO_CONTENT); addSecurityAnnotations(methodCreator, resourceProperties); ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis()); ResultHandle id = methodCreator.getMethodParam(0); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle deleted = tryBlock.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), RESOURCE_METHOD_NAME, boolean.class, Object.class), resource, id); // Return response BranchResult entityWasDeleted = tryBlock.ifNonZero(deleted); entityWasDeleted.trueBranch().returnValue(responseImplementor.noContent(entityWasDeleted.trueBranch())); entityWasDeleted.falseBranch().returnValue(responseImplementor.notFound(entityWasDeleted.falseBranch())); tryBlock.close(); } else { ResultHandle uniDeleted = methodCreator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), RESOURCE_METHOD_NAME, Uni.class, Object.class), resource, id); methodCreator.returnValue(UniImplementor.map(methodCreator, uniDeleted, EXCEPTION_MESSAGE, (body, entity) -> { ResultHandle deleted = body.checkCast(entity, Boolean.class); // Workaround to have boolean type, otherwise it's an integer. ResultHandle falseDefault = body.invokeStaticMethod( ofMethod(Boolean.class, "valueOf", Boolean.class, String.class), body.load("false")); ResultHandle deletedAsInt = body.invokeVirtualMethod( ofMethod(Boolean.class, "compareTo", int.class, Boolean.class), deleted, falseDefault); BranchResult entityWasDeleted = body.ifNonZero(deletedAsInt); entityWasDeleted.trueBranch() .returnValue(responseImplementor.noContent(entityWasDeleted.trueBranch())); entityWasDeleted.falseBranch() .returnValue(responseImplementor.notFound(entityWasDeleted.falseBranch())); })); } methodCreator.close(); } @Override protected String getResourceMethodName() { return RESOURCE_METHOD_NAME; } }
DeleteMethodImplementor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/fetchmode/toone/EagerToOneWithJoinFetchModeTests.java
{ "start": 10800, "end": 11241 }
class ____ { @Id private Integer id; private String name; @ManyToOne @Fetch(FetchMode.JOIN) private SimpleEntity manyToOneSimpleEntity; @OneToOne @Fetch(FetchMode.JOIN) private SimpleEntity oneToOneSimpleEntity; public RootEntity() { } public RootEntity(Integer id, String name) { this.id = id; this.name = name; } } @Entity(name = "SimpleEntity") @Table(name = "simple_entity") public static
RootEntity
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/RecipientListParallelFineGrainedErrorHandlingTest.java
{ "start": 1257, "end": 5013 }
class ____ extends ContextTestSupport { private static int counter; @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("fail", new MyFailBean()); return jndi; } @Test public void testRecipientListOk() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2); from("direct:start").to("mock:a").recipientList(header("foo")).stopOnException().parallelProcessing(); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); getMockEndpoint("mock:baz").expectedMessageCount(1); template.sendBodyAndHeader("direct:start", "Hello World", "foo", "mock:foo,mock:bar,mock:baz"); assertMockEndpointsSatisfied(); } @Test public void testRecipientListError() throws Exception { counter = 0; context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2); from("direct:start").to("mock:a").recipientList(header("foo")).stopOnException().parallelProcessing(); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); // can be 0 or 1 depending whether the task was executed or not (we run // parallel) getMockEndpoint("mock:foo").expectedMinimumMessageCount(0); getMockEndpoint("mock:bar").expectedMinimumMessageCount(0); getMockEndpoint("mock:baz").expectedMinimumMessageCount(0); try { template.sendBodyAndHeader("direct:start", "Hello World", "foo", "mock:foo,mock:bar,bean:fail,mock:baz"); fail("Should throw exception"); } catch (Exception e) { // expected } assertMockEndpointsSatisfied(); assertEquals(3, counter); } @Test public void testRecipientListAsBeanError() throws Exception { counter = 0; context.addRoutes(new RouteBuilder() { @Override public void configure() { context.setTracing(true); onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2); from("direct:start").to("mock:a").bean(MyRecipientBean.class); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); // can be 0 or 1 depending whether the task was executed or not (we run // parallel) getMockEndpoint("mock:foo").expectedMinimumMessageCount(0); getMockEndpoint("mock:bar").expectedMinimumMessageCount(0); getMockEndpoint("mock:baz").expectedMinimumMessageCount(0); try { template.sendBody("direct:start", "Hello World"); fail("Should throw exception"); } catch (CamelExecutionException e) { // expected assertIsInstanceOf(CamelExchangeException.class, e.getCause()); assertIsInstanceOf(IllegalArgumentException.class, e.getCause().getCause()); assertEquals("Damn", e.getCause().getCause().getMessage()); } assertMockEndpointsSatisfied(); assertEquals(3, counter); } @Override public boolean isUseRouteBuilder() { return false; } public static
RecipientListParallelFineGrainedErrorHandlingTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/GenericReturnValueMappedSuperclassEnhancementTest.java
{ "start": 1153, "end": 1446 }
class ____<T extends Marker> { @Id @GeneratedValue public int id; @Access(AccessType.PROPERTY) private T entity; public T getEntity() { return entity; } public void setEntity(T entity) { this.entity = entity; } } public
AbstractMappedSuperclassWithGenericReturnValue
java
quarkusio__quarkus
extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/SqlClientInstrumenterVertxTracer.java
{ "start": 1112, "end": 4029 }
class ____ implements InstrumenterVertxTracer<SqlClientInstrumenterVertxTracer.QueryTrace, SqlClientInstrumenterVertxTracer.QueryTrace> { private final Instrumenter<QueryTrace, QueryTrace> sqlClientInstrumenter; public SqlClientInstrumenterVertxTracer(final OpenTelemetry openTelemetry, final OTelRuntimeConfig runtimeConfig) { SqlClientAttributesGetter sqlClientAttributesGetter = new SqlClientAttributesGetter(); InstrumenterBuilder<QueryTrace, QueryTrace> serverBuilder = Instrumenter.builder( openTelemetry, INSTRUMENTATION_NAME, DbClientSpanNameExtractor.create(sqlClientAttributesGetter)); serverBuilder.setEnabled(!runtimeConfig.sdkDisabled()); this.sqlClientInstrumenter = serverBuilder .addAttributesExtractor(SqlClientAttributesExtractor.create(sqlClientAttributesGetter)) .addAttributesExtractor(NetworkAttributesExtractor.create(sqlClientAttributesGetter)) .buildClientInstrumenter((queryTrace, key, value) -> { }); } @Override public <R> boolean canHandle(final R request, final TagExtractor<R> tagExtractor) { if (request instanceof QueryTrace) { return true; } return "sql".equals(tagExtractor.extract(request).get("db.type")); } @Override @SuppressWarnings("unchecked") public <R> OpenTelemetryVertxTracer.SpanOperation sendRequest( final Context context, final SpanKind kind, final TracingPolicy policy, final R request, final String operation, final BiConsumer<String, String> headers, final TagExtractor<R> tagExtractor) { R queryTrace = (R) QueryTrace.queryTrace(tagExtractor.extract(request)); return InstrumenterVertxTracer.super.sendRequest(context, kind, policy, queryTrace, operation, headers, tagExtractor); } @Override public <R> void receiveResponse( final Context context, final R response, final OpenTelemetryVertxTracer.SpanOperation spanOperation, final Throwable failure, final TagExtractor<R> tagExtractor) { InstrumenterVertxTracer.super.receiveResponse(context, response, spanOperation, failure, tagExtractor); } @Override public Instrumenter<QueryTrace, QueryTrace> getReceiveRequestInstrumenter() { return null; } @Override public Instrumenter<QueryTrace, QueryTrace> getSendResponseInstrumenter() { return null; } @Override public Instrumenter<QueryTrace, QueryTrace> getSendRequestInstrumenter() { return sqlClientInstrumenter; } @Override public Instrumenter<QueryTrace, QueryTrace> getReceiveResponseInstrumenter() { return sqlClientInstrumenter; } static
SqlClientInstrumenterVertxTracer
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/PluralAttributeNature.java
{ "start": 359, "end": 908 }
enum ____ { BAG( Collection.class, false ), ID_BAG( Collection.class, false ), SET( Set.class, false ), LIST( List.class, true ), ARRAY( Object[].class, true ), MAP( Map.class, true ); private final boolean indexed; private final Class<?> reportedJavaType; PluralAttributeNature(Class<?> reportedJavaType, boolean indexed) { this.reportedJavaType = reportedJavaType; this.indexed = indexed; } public Class<?> reportedJavaType() { return reportedJavaType; } public boolean isIndexed() { return indexed; } }
PluralAttributeNature
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/parser/SQLInsertValueHandler.java
{ "start": 106, "end": 1344 }
interface ____ { Object newRow() throws SQLException; void processInteger(Object row, int index, Number value) throws SQLException; void processString(Object row, int index, String value) throws SQLException; void processDate(Object row, int index, String value) throws SQLException; void processDate(Object row, int index, java.util.Date value) throws SQLException; void processTimestamp(Object row, int index, String value) throws SQLException; void processTimestamp(Object row, int index, java.util.Date value) throws SQLException; void processTime(Object row, int index, String value) throws SQLException; void processDecimal(Object row, int index, BigDecimal value) throws SQLException; void processBoolean(Object row, int index, boolean value) throws SQLException; void processNull(Object row, int index) throws SQLException; void processFunction(Object row, int index, String funcName, long funcNameHashCode64, Object... values) throws SQLException; void processRow(Object row) throws SQLException; void processComplete() throws SQLException; }
SQLInsertValueHandler
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/test/MockClusterAlertScriptEngine.java
{ "start": 3598, "end": 4252 }
class ____ implements WatcherTransformScript.Factory { private final MockDeterministicScript script; MockWatcherTransformScript(MockDeterministicScript script) { this.script = script; } @Override public WatcherTransformScript newInstance(Map<String, Object> params, WatchExecutionContext watcherContext, Payload payload) { return new WatcherTransformScript(params, watcherContext, payload) { @Override public Object execute() { return script.apply(getParams()); } }; } } }
MockWatcherTransformScript
java
elastic__elasticsearch
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/pivot/CompositeBucketsChangeCollector.java
{ "start": 2610, "end": 2653 }
class ____ collect bucket changes */ public
to
java
quarkusio__quarkus
extensions/vertx/deployment/src/test/java/io/quarkus/vertx/deployment/HeadersMessageConsumerMethodTest.java
{ "start": 5943, "end": 6763 }
class ____ { static volatile CountDownLatch latch; static final List<Map.Entry<io.vertx.core.MultiMap, String>> MESSAGES = new CopyOnWriteArrayList<>(); @ConsumeEvent("vertx-headers") void consume(io.vertx.core.MultiMap headers, String body) { MESSAGES.add(Map.entry(headers, body)); latch.countDown(); } @ConsumeEvent("vertx-headers-reply") String reply(io.vertx.core.MultiMap headers, String body) { return headers.get("header") + ":" + body; } @ConsumeEvent("vertx-headers-replyUni") Uni<String> replyUni(io.vertx.core.MultiMap headers, String body) { return Uni.createFrom().item(headers.get("header") + ":" + body); } } @ApplicationScoped static
VertxMessageConsumers
java
google__guava
android/guava/src/com/google/common/collect/Synchronized.java
{ "start": 22327, "end": 24316 }
class ____< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap(SortedSetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(@Nullable Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public @Nullable Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> Collection<E> typePreservingCollection( Collection<E> collection, @Nullable Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E extends @Nullable Object> Set<E> typePreservingSet( Set<E> set, @Nullable Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } static final
SynchronizedSortedSetMultimap
java
dropwizard__dropwizard
dropwizard-validation/src/main/java/io/dropwizard/validation/MaxDurationValidator.java
{ "start": 333, "end": 1211 }
class ____ implements ConstraintValidator<MaxDuration, Duration> { private long maxQty = 0; private TimeUnit maxUnit = TimeUnit.MILLISECONDS; private boolean inclusive = true; @Override public void initialize(MaxDuration constraintAnnotation) { this.maxQty = constraintAnnotation.value(); this.maxUnit = constraintAnnotation.unit(); this.inclusive = constraintAnnotation.inclusive(); } @Override public boolean isValid(Duration value, ConstraintValidatorContext context) { if (value == null) { return true; } long valueNanos = value.toNanoseconds(); long annotationNanos = maxUnit.toNanos(maxQty); if (inclusive) { return valueNanos <= annotationNanos; } else { return valueNanos < annotationNanos; } } }
MaxDurationValidator
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java
{ "start": 1271, "end": 5545 }
class ____<T> { public double size() { return 10; } public Collection<T> subList(int fromIndex, int toIndex) { return new ArrayList<T>(); } } @Test public void when_not_stubbed_delegate_should_be_called() { List<String> delegatedList = new ArrayList<String>(); delegatedList.add("un"); List<String> mock = mock(List.class, delegatesTo(delegatedList)); mock.add("two"); assertEquals(2, mock.size()); } @Test public void when_stubbed_the_delegate_should_not_be_called() { List<String> delegatedList = new ArrayList<String>(); delegatedList.add("un"); List<String> mock = mock(List.class, delegatesTo(delegatedList)); doReturn(10).when(mock).size(); mock.add("two"); assertEquals(10, mock.size()); assertEquals(2, delegatedList.size()); } @Test public void delegate_should_not_be_called_when_stubbed2() { List<String> delegatedList = new ArrayList<String>(); delegatedList.add("un"); List<String> mockedList = mock(List.class, delegatesTo(delegatedList)); doReturn(false).when(mockedList).add(Mockito.anyString()); mockedList.add("two"); assertEquals(1, mockedList.size()); assertEquals(1, delegatedList.size()); } @Test public void null_wrapper_dont_throw_exception_from_org_mockito_package() { IMethods methods = mock(IMethods.class, delegatesTo(new MethodsImpl())); assertThat(methods.byteObjectReturningMethod()).isNull(); } @Test public void instance_of_different_class_can_be_called() { List<String> mock = mock(List.class, delegatesTo(new FakeList<String>())); mock.set(1, "1"); assertThat(mock.get(1).equals("1")).isTrue(); } @Test public void method_with_subtype_return_can_be_called() { List<String> mock = mock(List.class, delegatesTo(new FakeList<String>())); List<String> subList = mock.subList(0, 0); assertThat(subList.isEmpty()).isTrue(); } @Test public void calling_missing_method_should_throw_exception() { List<String> mock = mock(List.class, delegatesTo(new FakeList<String>())); try { mock.isEmpty(); fail(); } catch (MockitoException e) { assertThat(e.toString()).contains("Methods called on mock must exist"); } } @Test public void calling_method_with_wrong_primitive_return_should_throw_exception() { List<String> mock = mock(List.class, delegatesTo(new FakeListWithWrongMethods<String>())); try { mock.size(); fail(); } catch (MockitoException e) { assertThat(e.toString()) .contains( "Methods called on delegated instance must have compatible return type"); } } @Test public void calling_method_with_wrong_reference_return_should_throw_exception() { List<String> mock = mock(List.class, delegatesTo(new FakeListWithWrongMethods<String>())); try { mock.subList(0, 0); fail(); } catch (MockitoException e) { assertThat(e.toString()) .contains( "Methods called on delegated instance must have compatible return type"); } } @Test public void exception_should_be_propagated_from_delegate() throws Exception { final RuntimeException failure = new RuntimeException("angry-method"); IMethods methods = mock( IMethods.class, delegatesTo( new MethodsImpl() { @Override public String simpleMethod() { throw failure; } })); try { methods.simpleMethod(); // delegate throws an exception fail(); } catch (RuntimeException e) { assertThat(e).isEqualTo(failure); } }
FakeListWithWrongMethods
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/ast/MemberElement.java
{ "start": 4524, "end": 6818 }
class ____ in a different package then // the method or field is not visible and hence reflection is required final ClassElement declaringType = getDeclaringType(); String packageName = declaringType.getPackageName(); if (!packageName.equals(callingType.getPackageName())) { return allowReflection && hasAnnotation(ReflectiveAccess.class); } if (packagePrivate) { // Check if there is a subtype that breaks the package friendship ClassElement superClass = getOwningType(); while (superClass != null && !superClass.equals(declaringType)) { if (!packageName.equals(superClass.getPackageName())) { return allowReflection && hasAnnotation(ReflectiveAccess.class); } superClass = superClass.getSuperType().orElse(null); } } return true; } if (isPrivate()) { return allowReflection && hasAnnotation(ReflectiveAccess.class); } return true; } /** * Returns whether this member element can be invoked or retrieved at runtime. * It can be accessible by a simple invocation or a reflection invocation. * * <p>This method uses {@link #isReflectionRequired()} with a checks if the reflection access is allowed. * By checking for {@link io.micronaut.core.annotation.ReflectiveAccess} annotation. * </p> * * @param callingType The calling type * @return Will return {@code true} if is accessible. * @since 3.7.0 */ default boolean isAccessible(@NonNull ClassElement callingType) { return isAccessible(callingType, true); } @Override default MemberElement withAnnotationMetadata(AnnotationMetadata annotationMetadata) { return (MemberElement) Element.super.withAnnotationMetadata(annotationMetadata); } /** * Checks if this member element hides another. * * @param hidden The possibly hidden element * @return true if this member element hides passed field element * @since 4.0.0 */ default boolean hides(@NonNull MemberElement hidden) { return false; } }
is
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh12225/Vehicle.java
{ "start": 173, "end": 5029 }
class ____ { public static final long serialVersionUID = 1L; public static final String STATUS_NEW = "new"; public static final String STATUS_USED = "used"; private Long _id; private Integer _version; private Date _creationDate; private Date _modifiedDate; private String _vin; private boolean _dirty; private Double _msrp; private Double _residualValue; private Double _invoicePrice; private Integer _decodeAttempts; private String _model; private String _modelDetail; private Integer _year; private Integer _odometer; private String _license; private String _status; private String _vehicleType; private String _classification; private String _country; private String _engineType; private String _assemblyPlant; private Integer _sequenceNumber; private String _bodyType; private String _fuelType; private String _driveLineType; private VehicleContract _contract; /** * default constructor */ public Vehicle() { _decodeAttempts = 0; } public Long getId() { return _id; } public void setId(Long id) { _id = id; } public Integer getVersion() { return _version; } public void setVersion(Integer version) { _version = version; } public Date getCreationDate() { return _creationDate; } public void setCreationDate(Date creationDate) { _creationDate = creationDate; } public Date getModifiedDate() { return _modifiedDate; } public void setModifiedDate(Date modifiedDate) { _modifiedDate = modifiedDate; } public String getVin() { return _vin; } public void setVin(String vin) { _vin = vin; } public boolean isDirty() { return _dirty; } public void setDirty(boolean dirty) { _dirty = dirty; } public Double getMsrp() { return _msrp; } public void setMsrp(Double msrp) { _msrp = msrp; } public Integer getDecodeAttempts() { return _decodeAttempts; } public void setDecodeAttempts(Integer decodeAttempts) { _decodeAttempts = decodeAttempts; } public String getModel() { return _model; } public void setModel(String model) { _model = model; } public String getModelDetail() { return _modelDetail; } public void setModelDetail(String modelDetail) { _modelDetail = modelDetail; } public Integer getYear() { return _year; } public void setYear(Integer year) { _year = year; } public Integer getOdometer() { return _odometer; } public void setOdometer(Integer odometer) { _odometer = odometer; } public String getLicense() { return _license; } public void setLicense(String license) { _license = license; } public String getStatus() { return _status; } public void setStatus(String status) { _status = status; } public String getVehicleType() { return _vehicleType; } public void setVehicleType(String vehicleType) { _vehicleType = vehicleType; } public String getCountry() { return _country; } public void setCountry(String country) { _country = country; } public String getEngineType() { return _engineType; } public void setEngineType(String engineType) { _engineType = engineType; } public String getAssemblyPlant() { return _assemblyPlant; } public void setAssemblyPlant(String assemblyPlant) { _assemblyPlant = assemblyPlant; } public Integer getSequenceNumber() { return _sequenceNumber; } public void setSequenceNumber(Integer sequenceNumber) { _sequenceNumber = sequenceNumber; } public String getBodyType() { return _bodyType; } public void setBodyType(String bodyType) { _bodyType = bodyType; } public String getFuelType() { return _fuelType; } public void setFuelType(String fuelType) { _fuelType = fuelType; } public String getDriveLineType() { return _driveLineType; } public void setDriveLineType(String driveLineType) { _driveLineType = driveLineType; } public VehicleContract getContract() { return _contract; } public void setContract(VehicleContract contract) { _contract = contract; } public String getClassification() { return _classification; } public void setClassification(String classification) { _classification = classification; } public Double getResidualValue() { return _residualValue; } public void setResidualValue(Double residualValue) { _residualValue = residualValue; } public Double getInvoicePrice() { return _invoicePrice; } public void setInvoicePrice(Double invoicePrice) { _invoicePrice = invoicePrice; } public String toString() { return String.valueOf( _vin ); } public boolean equals(Object obj) { if ( obj == null ) { return false; } if ( obj == this ) { return true; } if ( obj instanceof Vehicle ) { //TODO - needs to include contract equals comparision return _vin.equals( ( (Vehicle) obj ).getVin() ); } return false; } public int hashCode() { return _vin.hashCode(); } }
Vehicle
java
mockito__mockito
mockito-core/src/main/java/org/mockito/MockedConstruction.java
{ "start": 1533, "end": 1735 }
interface ____ consumes a newly created mock and the mock context. * <p> * Used to attach behaviours to new mocks. * * @param <T> the mock type. */ @FunctionalInterface
that
java
netty__netty
codec-http3/src/main/java/io/netty/handler/codec/http3/Http3RequestStreamFrameTypeValidator.java
{ "start": 752, "end": 1576 }
class ____ implements Http3FrameTypeValidator { static final Http3RequestStreamFrameTypeValidator INSTANCE = new Http3RequestStreamFrameTypeValidator(); private Http3RequestStreamFrameTypeValidator() { } @Override public void validate(long type, boolean first) throws Http3Exception { switch ((int) type) { case Http3CodecUtils.HTTP3_CANCEL_PUSH_FRAME_TYPE: case Http3CodecUtils.HTTP3_GO_AWAY_FRAME_TYPE: case Http3CodecUtils.HTTP3_MAX_PUSH_ID_FRAME_TYPE: case Http3CodecUtils.HTTP3_SETTINGS_FRAME_TYPE: throw new Http3Exception(Http3ErrorCode.H3_FRAME_UNEXPECTED, "Unexpected frame type '" + type + "' received"); default: break; } } }
Http3RequestStreamFrameTypeValidator
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/persistent/PersistentTasksClusterServiceTests.java
{ "start": 4253, "end": 53903 }
class ____ extends ESTestCase { /** Needed by {@link ClusterService} **/ private static ThreadPool threadPool; /** Needed by {@link PersistentTasksClusterService} **/ private ClusterService clusterService; private volatile boolean nonClusterStateCondition; private PersistentTasksExecutor.Scope scope; @BeforeClass public static void setUpThreadPool() { threadPool = new TestThreadPool(PersistentTasksClusterServiceTests.class.getSimpleName()); } @Before public void setUp() throws Exception { super.setUp(); clusterService = createClusterService(threadPool); scope = randomFrom(PersistentTasksExecutor.Scope.values()); } @AfterClass public static void tearDownThreadPool() { terminate(threadPool); } @After public void tearDown() throws Exception { super.tearDown(); clusterService.close(); } public void testReassignmentRequired() { final PersistentTasksClusterService service = createService( (params, candidateNodes, clusterState) -> "never_assign".equals(((TestParams) params).getTestParam()) ? NO_NODE_FOUND : randomNodeAssignment(clusterState.nodes().getAllNodes()) ); int numberOfIterations = randomIntBetween(1, 30); ClusterState clusterState = initialState(); for (int i = 0; i < numberOfIterations; i++) { boolean significant = randomBoolean(); ClusterState previousState = clusterState; logger.info("inter {} significant: {}", i, significant); if (significant) { clusterState = significantChange(clusterState); } else { clusterState = insignificantChange(clusterState); } ClusterChangedEvent event = new ClusterChangedEvent("test", clusterState, previousState); assertThat(dumpEvent(event), service.shouldReassignPersistentTasks(event), equalTo(significant)); } } public void testReassignmentRequiredOnMetadataChanges() { EnableAssignmentDecider.Allocation allocation = randomFrom(EnableAssignmentDecider.Allocation.values()); DiscoveryNodes nodes = DiscoveryNodes.builder() .add(DiscoveryNodeUtils.create("_node")) .localNodeId("_node") .masterNodeId("_node") .build(); boolean unassigned = randomBoolean(); var tasks = tasksBuilder(null).addTask( "_task_1", TestPersistentTasksExecutor.NAME, null, new Assignment(unassigned ? null : "_node", "_reason") ); Metadata metadata = updateTasksCustomMetadata(Metadata.builder(), tasks).persistentSettings( Settings.builder().put(EnableAssignmentDecider.CLUSTER_TASKS_ALLOCATION_ENABLE_SETTING.getKey(), allocation.toString()).build() ).build(); ClusterState previous = ClusterState.builder(new ClusterName("_name")).nodes(nodes).metadata(metadata).build(); ClusterState current; final boolean changed = randomBoolean(); if (changed) { allocation = randomValueOtherThan(allocation, () -> randomFrom(EnableAssignmentDecider.Allocation.values())); current = ClusterState.builder(previous) .metadata( Metadata.builder(previous.metadata()) .persistentSettings( Settings.builder() .put(EnableAssignmentDecider.CLUSTER_TASKS_ALLOCATION_ENABLE_SETTING.getKey(), allocation.toString()) .build() ) .build() ) .build(); } else { current = ClusterState.builder(previous).build(); } final ClusterChangedEvent event = new ClusterChangedEvent("test", current, previous); final PersistentTasksClusterService service = createService( (params, candidateNodes, clusterState) -> randomNodeAssignment(clusterState.nodes().getAllNodes()) ); assertThat(dumpEvent(event), service.shouldReassignPersistentTasks(event), equalTo(changed && unassigned)); } public void testReassignTasksWithNoTasks() { ClusterState clusterState = initialState(); assertThat(getPersistentTasks(reassign(clusterState)), nullValue()); } public void testReassignConsidersClusterStateUpdates() { ClusterState clusterState = initialState(); ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = tasksBuilder(getPersistentTasks(clusterState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes()); addTestNodes(nodes, randomIntBetween(1, 10)); int numberOfTasks = randomIntBetween(2, 40); for (int i = 0; i < numberOfTasks; i++) { addTask(tasks, "assign_one", randomBoolean() ? null : "no_longer_exists"); } Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(clusterState.metadata()), tasks); clusterState = builder.metadata(metadata).nodes(nodes).build(); ClusterState newClusterState = reassign(clusterState); var tasksInProgress = getPersistentTasks(newClusterState); assertThat(tasksInProgress, notNullValue()); } public void testNonClusterStateConditionAssignment() { ClusterState clusterState = initialState(); ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = tasksBuilder(getPersistentTasks(clusterState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes()); addTestNodes(nodes, randomIntBetween(1, 3)); addTask(tasks, "assign_based_on_non_cluster_state_condition", null); Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(clusterState.metadata()), tasks); clusterState = builder.metadata(metadata).nodes(nodes).build(); nonClusterStateCondition = false; ClusterState newClusterState = reassign(clusterState); var tasksInProgress = getPersistentTasks(newClusterState); assertThat(tasksInProgress, notNullValue()); for (PersistentTask<?> task : tasksInProgress.tasks()) { assertThat(task.getExecutorNode(), nullValue()); assertThat(task.isAssigned(), equalTo(false)); assertThat(task.getAssignment().getExplanation(), equalTo("non-cluster state condition prevents assignment")); } assertThat(tasksInProgress.tasks().size(), equalTo(1)); nonClusterStateCondition = true; ClusterState finalClusterState = reassign(newClusterState); tasksInProgress = getPersistentTasks(finalClusterState); assertThat(tasksInProgress, notNullValue()); for (PersistentTask<?> task : tasksInProgress.tasks()) { assertThat(task.getExecutorNode(), notNullValue()); assertThat(task.isAssigned(), equalTo(true)); assertThat(task.getAssignment().getExplanation(), equalTo("test assignment")); } assertThat(tasksInProgress.tasks().size(), equalTo(1)); } public void testReassignTasks() { ClusterState clusterState = initialState(); ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = tasksBuilder(getPersistentTasks(clusterState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes()); addTestNodes(nodes, randomIntBetween(1, 10)); int numberOfTasks = randomIntBetween(0, 40); for (int i = 0; i < numberOfTasks; i++) { switch (randomInt(2)) { case 0 -> // add an unassigned task that should get assigned because it's assigned to a non-existing node or unassigned addTask(tasks, "assign_me", randomBoolean() ? null : "no_longer_exists"); case 1 -> // add a task assigned to non-existing node that should not get assigned addTask(tasks, "dont_assign_me", randomBoolean() ? null : "no_longer_exists"); case 2 -> addTask(tasks, "assign_one", randomBoolean() ? null : "no_longer_exists"); } } Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(clusterState.metadata()), tasks); clusterState = builder.metadata(metadata).nodes(nodes).build(); ClusterState newClusterState = reassign(clusterState); var tasksInProgress = getPersistentTasks(newClusterState); assertThat(tasksInProgress, notNullValue()); assertThat("number of tasks shouldn't change as a result or reassignment", numberOfTasks, equalTo(tasksInProgress.tasks().size())); int assignOneCount = 0; for (PersistentTask<?> task : tasksInProgress.tasks()) { // explanation should correspond to the action name switch (((TestParams) task.getParams()).getTestParam()) { case "assign_me": assertThat(task.getExecutorNode(), notNullValue()); assertThat(task.isAssigned(), equalTo(true)); if (clusterState.nodes().nodeExists(task.getExecutorNode()) == false) { logger.info(getPersistentTasks(clusterState).toString()); } assertThat( "task should be assigned to a node that is in the cluster, was assigned to " + task.getExecutorNode(), clusterState.nodes().nodeExists(task.getExecutorNode()), equalTo(true) ); assertThat(task.getAssignment().getExplanation(), equalTo("test assignment")); break; case "dont_assign_me": assertThat(task.getExecutorNode(), nullValue()); assertThat(task.isAssigned(), equalTo(false)); assertThat(task.getAssignment().getExplanation(), equalTo("no appropriate nodes found for the assignment")); break; case "assign_one": if (task.isAssigned()) { assignOneCount++; assertThat("more than one assign_one tasks are assigned", assignOneCount, lessThanOrEqualTo(1)); assertThat(task.getAssignment().getExplanation(), equalTo("test assignment")); } else { assertThat(task.getAssignment().getExplanation(), equalTo("only one task can be assigned at a time")); } break; default: fail("Unknown action " + task.getTaskName()); } } } public void testPersistentTasksChangedNoTasks() { DiscoveryNodes nodes = DiscoveryNodes.builder().add(DiscoveryNodeUtils.create("_node_1")).build(); ClusterState previous = ClusterState.builder(new ClusterName("_name")).nodes(nodes).build(); ClusterState current = ClusterState.builder(new ClusterName("_name")).nodes(nodes).build(); assertFalse("persistent tasks unchanged (no tasks)", persistentTasksChanged(new ClusterChangedEvent("test", current, previous))); } public void testPersistentTasksChangedTaskAdded() { DiscoveryNodes nodes = DiscoveryNodes.builder().add(DiscoveryNodeUtils.create("_node_1")).build(); ClusterState previous = ClusterState.builder(new ClusterName("_name")).nodes(nodes).build(); var tasks = tasksBuilder(null).addTask("_task_1", "test", null, new Assignment(null, "_reason")); ClusterState current = ClusterState.builder(new ClusterName("_name")) .nodes(nodes) .metadata(updateTasksCustomMetadata(Metadata.builder(), tasks)) .build(); assertTrue("persistent tasks changed (task added)", persistentTasksChanged(new ClusterChangedEvent("test", current, previous))); } public void testPersistentTasksChangedTaskRemoved() { DiscoveryNodes nodes = DiscoveryNodes.builder() .add(DiscoveryNodeUtils.create("_node_1")) .add(DiscoveryNodeUtils.create("_node_2")) .build(); var previousTasks = tasksBuilder(null).addTask("_task_1", "test", null, new Assignment("_node_1", "_reason")) .addTask("_task_2", "test", null, new Assignment("_node_1", "_reason")) .addTask("_task_3", "test", null, new Assignment("_node_2", "_reason")); ClusterState previous = ClusterState.builder(new ClusterName("_name")) .nodes(nodes) .metadata(updateTasksCustomMetadata(Metadata.builder(), previousTasks)) .build(); var currentTasks = tasksBuilder(null).addTask("_task_1", "test", null, new Assignment("_node_1", "_reason")) .addTask("_task_3", "test", null, new Assignment("_node_2", "_reason")); ClusterState current = ClusterState.builder(new ClusterName("_name")) .nodes(nodes) .metadata(updateTasksCustomMetadata(Metadata.builder(), currentTasks)) .build(); assertTrue("persistent tasks changed (task removed)", persistentTasksChanged(new ClusterChangedEvent("test", current, previous))); } public void testPersistentTasksAssigned() { DiscoveryNodes nodes = DiscoveryNodes.builder() .add(DiscoveryNodeUtils.create("_node_1")) .add(DiscoveryNodeUtils.create("_node_2")) .build(); var previousTasks = tasksBuilder(null).addTask("_task_1", "test", null, new Assignment("_node_1", "")) .addTask("_task_2", "test", null, new Assignment(null, "unassigned")); ClusterState previous = ClusterState.builder(new ClusterName("_name")) .nodes(nodes) .metadata(updateTasksCustomMetadata(Metadata.builder(), previousTasks)) .build(); var currentTasks = tasksBuilder(null).addTask("_task_1", "test", null, new Assignment("_node_1", "")) .addTask("_task_2", "test", null, new Assignment("_node_2", "")); ClusterState current = ClusterState.builder(new ClusterName("_name")) .nodes(nodes) .metadata(updateTasksCustomMetadata(Metadata.builder(), currentTasks)) .build(); assertTrue("persistent tasks changed (task assigned)", persistentTasksChanged(new ClusterChangedEvent("test", current, previous))); } public void testNeedsReassignment() { DiscoveryNodes nodes = DiscoveryNodes.builder() .add(DiscoveryNodeUtils.create("_node_1")) .add(DiscoveryNodeUtils.create("_node_2")) .build(); assertTrue(needsReassignment(new Assignment(null, "unassigned"), nodes)); assertTrue(needsReassignment(new Assignment("_node_left", "assigned to a node that left"), nodes)); assertFalse(needsReassignment(new Assignment("_node_1", "assigned"), nodes)); } public void testPeriodicRecheck() throws Exception { ClusterState initialState = initialState(); ClusterState.Builder builder = ClusterState.builder(initialState); var tasks = tasksBuilder(getPersistentTasks(initialState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(initialState.nodes()); addTestNodes(nodes, randomIntBetween(1, 3)); addTask(tasks, "assign_based_on_non_cluster_state_condition", null); Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(initialState.metadata()), tasks); ClusterState clusterState = builder.metadata(metadata).nodes(nodes).build(); nonClusterStateCondition = false; boolean shouldSimulateFailure = randomBoolean(); ClusterService recheckTestClusterService = createStateUpdateClusterState(clusterState, shouldSimulateFailure); PersistentTasksClusterService service = createService( recheckTestClusterService, (params, candidateNodes, currentState) -> assignBasedOnNonClusterStateCondition(candidateNodes) ); ClusterChangedEvent event = new ClusterChangedEvent("test", clusterState, initialState); service.clusterChanged(event); ClusterState newClusterState = recheckTestClusterService.state(); { var tasksInProgress = getPersistentTasks(newClusterState); assertThat(tasksInProgress, notNullValue()); for (PersistentTask<?> task : tasksInProgress.tasks()) { assertThat(task.getExecutorNode(), nullValue()); assertThat(task.isAssigned(), equalTo(false)); assertThat( task.getAssignment().getExplanation(), equalTo( shouldSimulateFailure ? "explanation: assign_based_on_non_cluster_state_condition" : "non-cluster state condition prevents assignment" ) ); } assertThat(tasksInProgress.tasks().size(), equalTo(1)); } nonClusterStateCondition = true; service.setRecheckInterval(TimeValue.timeValueMillis(1)); assertBusy(() -> { var tasksInProgress = getPersistentTasks(recheckTestClusterService.state()); assertThat(tasksInProgress, notNullValue()); for (PersistentTask<?> task : tasksInProgress.tasks()) { assertThat(task.getExecutorNode(), notNullValue()); assertThat(task.isAssigned(), equalTo(true)); assertThat(task.getAssignment().getExplanation(), equalTo("test assignment")); } assertThat(tasksInProgress.tasks().size(), equalTo(1)); }); } public void testPeriodicRecheckOffMaster() { ClusterState initialState = initialState(); ClusterState.Builder builder = ClusterState.builder(initialState); var tasks = tasksBuilder(getPersistentTasks(initialState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(initialState.nodes()); addTestNodes(nodes, randomIntBetween(1, 3)); addTask(tasks, "assign_based_on_non_cluster_state_condition", null); Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(initialState.metadata()), tasks); ClusterState clusterState = builder.metadata(metadata).nodes(nodes).build(); nonClusterStateCondition = false; ClusterService recheckTestClusterService = createStateUpdateClusterState(clusterState, false); PersistentTasksClusterService service = createService( recheckTestClusterService, (params, candidateNodes, currentState) -> assignBasedOnNonClusterStateCondition(candidateNodes) ); ClusterChangedEvent event = new ClusterChangedEvent("test", clusterState, initialState); service.clusterChanged(event); ClusterState newClusterState = recheckTestClusterService.state(); { var tasksInProgress = getPersistentTasks(newClusterState); assertThat(tasksInProgress, notNullValue()); for (PersistentTask<?> task : tasksInProgress.tasks()) { assertThat(task.getExecutorNode(), nullValue()); assertThat(task.isAssigned(), equalTo(false)); assertThat(task.getAssignment().getExplanation(), equalTo("non-cluster state condition prevents assignment")); } assertThat(tasksInProgress.tasks().size(), equalTo(1)); } // The rechecker should recheck indefinitely on the master node as the // task can never be assigned while nonClusterStateCondition = false assertTrue(service.getPeriodicRechecker().isScheduled()); // Now simulate the node ceasing to be the master builder = ClusterState.builder(clusterState); nodes = DiscoveryNodes.builder(clusterState.nodes()); nodes.add(DiscoveryNodeUtils.create("a_new_master_node")); nodes.masterNodeId("a_new_master_node"); ClusterState nonMasterClusterState = builder.nodes(nodes).build(); event = new ClusterChangedEvent("test", nonMasterClusterState, clusterState); service.clusterChanged(event); // The service should have cancelled the rechecker on learning it is no longer running on the master node assertFalse(service.getPeriodicRechecker().isScheduled()); } public void testUnassignTask() throws InterruptedException { ClusterState clusterState = initialState(); ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = tasksBuilder(getPersistentTasks(clusterState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder() .add(DiscoveryNodeUtils.create("_node_1")) .localNodeId("_node_1") .masterNodeId("_node_1") .add(DiscoveryNodeUtils.create("_node_2")); String unassignedId = addTask(tasks, "unassign", "_node_2"); Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(clusterState.metadata()), tasks); clusterState = builder.metadata(metadata).nodes(nodes).build(); setState(clusterService, clusterState); PersistentTasksClusterService service = createService((params, candidateNodes, currentState) -> new Assignment("_node_2", "test")); final var countDownLatch = new CountDownLatch(1); service.unassignPersistentTask( Metadata.DEFAULT_PROJECT_ID, unassignedId, tasks.getLastAllocationId(), "unassignment test", ActionTestUtils.assertNoFailureListener(task -> { assertThat(task.getAssignment().getExecutorNode(), is(nullValue())); assertThat(task.getId(), equalTo(unassignedId)); assertThat(task.getAssignment().getExplanation(), equalTo("unassignment test")); countDownLatch.countDown(); }) ); assertTrue(countDownLatch.await(10, TimeUnit.SECONDS)); } public void testUnassignNonExistentTask() throws InterruptedException { ClusterState clusterState = initialState(); ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = tasksBuilder(getPersistentTasks(clusterState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder() .add(DiscoveryNodeUtils.create("_node_1")) .localNodeId("_node_1") .masterNodeId("_node_1") .add(DiscoveryNodeUtils.create("_node_2")); Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(clusterState.metadata()), tasks); clusterState = builder.metadata(metadata).nodes(nodes).build(); setState(clusterService, clusterState); PersistentTasksClusterService service = createService((params, candidateNodes, currentState) -> new Assignment("_node_2", "test")); final var countDownLatch = new CountDownLatch(1); service.unassignPersistentTask( Metadata.DEFAULT_PROJECT_ID, "missing-task", tasks.getLastAllocationId(), "unassignment test", ActionListener.wrap(task -> fail(), e -> { assertThat(e, instanceOf(ResourceNotFoundException.class)); countDownLatch.countDown(); }) ); assertTrue(countDownLatch.await(10, TimeUnit.SECONDS)); } public void testTasksNotAssignedToShuttingDownNodes() { for (SingleNodeShutdownMetadata.Type type : List.of( SingleNodeShutdownMetadata.Type.RESTART, SingleNodeShutdownMetadata.Type.REMOVE, SingleNodeShutdownMetadata.Type.SIGTERM )) { ClusterState clusterState = initialState(); ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = tasksBuilder(getPersistentTasks(clusterState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes()); addTestNodes(nodes, randomIntBetween(2, 10)); int numberOfTasks = randomIntBetween(20, 40); for (int i = 0; i < numberOfTasks; i++) { addTask( tasks, randomFrom("assign_me", "assign_one", "assign_based_on_non_cluster_state_condition"), randomBoolean() ? null : "no_longer_exists" ); } Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(clusterState.metadata()), tasks); clusterState = builder.metadata(metadata).nodes(nodes).build(); // Now that we have a bunch of tasks that need to be assigned, let's // mark half the nodes as shut down and make sure they do not have any // tasks assigned var allNodes = clusterState.nodes(); var shutdownMetadataMap = allNodes.stream() .limit(Math.floorDiv(allNodes.size(), 2)) .collect( toMap( DiscoveryNode::getId, node -> SingleNodeShutdownMetadata.builder() .setNodeId(node.getId()) .setNodeEphemeralId(node.getEphemeralId()) .setReason("shutdown for a unit test") .setType(type) .setStartedAtMillis(randomNonNegativeLong()) .setGracePeriod(type == SIGTERM ? randomTimeValue() : null) .build() ) ); logger.info("--> nodes marked as shutting down: {}", shutdownMetadataMap.keySet()); ClusterState shutdownState = ClusterState.builder(clusterState) .metadata( Metadata.builder(clusterState.metadata()) .putCustom(NodesShutdownMetadata.TYPE, new NodesShutdownMetadata(shutdownMetadataMap)) .build() ) .build(); logger.info("--> assigning after marking nodes as shutting down"); nonClusterStateCondition = randomBoolean(); clusterState = reassign(shutdownState); var tasksInProgress = getPersistentTasks(clusterState); assertThat(tasksInProgress, notNullValue()); Set<String> nodesWithTasks = tasksInProgress.tasks() .stream() .map(PersistentTask::getAssignment) .map(Assignment::getExecutorNode) .filter(Objects::nonNull) .collect(Collectors.toSet()); Set<String> shutdownNodes = shutdownMetadataMap.keySet(); assertTrue( "expected shut down nodes: " + shutdownNodes + " to have no nodes in common with nodes assigned tasks: " + nodesWithTasks, Sets.haveEmptyIntersection(shutdownNodes, nodesWithTasks) ); } } public void testReassignOnlyOnce() throws Exception { CountDownLatch latch = new CountDownLatch(1); ClusterState initialState = initialState(); ClusterState.Builder builder = ClusterState.builder(initialState); var tasks = tasksBuilder(getPersistentTasks(initialState)); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(initialState.nodes()); addTestNodes(nodes, randomIntBetween(1, 3)); addTask(tasks, "assign_based_on_non_cluster_state_condition", null); Metadata.Builder metadata = updateTasksCustomMetadata(Metadata.builder(initialState.metadata()), tasks); ClusterState clusterState = builder.metadata(metadata).nodes(nodes).build(); boolean shouldSimulateFailure = randomBoolean(); ClusterService recheckTestClusterService = createStateUpdateClusterState(clusterState, shouldSimulateFailure, latch); PersistentTasksClusterService service = createService( recheckTestClusterService, (params, candidateNodes, currentState) -> assignBasedOnNonClusterStateCondition(candidateNodes) ); verify(recheckTestClusterService, atLeastOnce()).getClusterSettings(); verify(recheckTestClusterService, atLeastOnce()).addListener(any()); Thread t1 = new Thread(service::reassignPersistentTasks); Thread t2 = new Thread(service::reassignPersistentTasks); try { t1.start(); // Make sure we have at least one reassign check before we count down the latch assertBusy( () -> verify(recheckTestClusterService, atLeastOnce()).submitUnbatchedStateUpdateTask( eq("reassign persistent tasks"), any() ) ); t2.start(); } finally { t2.join(); latch.countDown(); t1.join(); service.reassignPersistentTasks(); } // verify that our reassignment is possible again, here we have once from the previous reassignment in the `try` block // And one from the line above once the other threads have joined assertBusy( () -> verify(recheckTestClusterService, times(2)).submitUnbatchedStateUpdateTask(eq("reassign persistent tasks"), any()) ); verifyNoMoreInteractions(recheckTestClusterService); } private ClusterService createStateUpdateClusterState(ClusterState initialState, boolean shouldSimulateFailure) { return createStateUpdateClusterState(initialState, shouldSimulateFailure, null); } private ClusterService createStateUpdateClusterState(ClusterState initialState, boolean shouldSimulateFailure, CountDownLatch await) { AtomicBoolean testFailureNextTime = new AtomicBoolean(shouldSimulateFailure); AtomicReference<ClusterState> state = new AtomicReference<>(initialState); ClusterService recheckTestClusterService = mock(ClusterService.class); when(recheckTestClusterService.getClusterSettings()).thenReturn(clusterService.getClusterSettings()); doAnswer(invocationOnMock -> state.get().getNodes().getLocalNode()).when(recheckTestClusterService).localNode(); doAnswer(invocationOnMock -> state.get()).when(recheckTestClusterService).state(); doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") ClusterStateUpdateTask task = (ClusterStateUpdateTask) invocationOnMock.getArguments()[1]; ClusterState before = state.get(); ClusterState after = task.execute(before); if (await != null) { await.await(); } if (testFailureNextTime.compareAndSet(true, false)) { task.onFailure(new RuntimeException("foo")); } else { state.set(after); task.clusterStateProcessed(before, after); } return null; }).when(recheckTestClusterService).submitUnbatchedStateUpdateTask(anyString(), any(ClusterStateUpdateTask.class)); return recheckTestClusterService; } private void addTestNodes(DiscoveryNodes.Builder nodes, int nonLocalNodesCount) { for (int i = 0; i < nonLocalNodesCount; i++) { nodes.add(DiscoveryNodeUtils.create("other_node_" + i)); } } private ClusterState reassign(ClusterState clusterState) { PersistentTasksClusterService service = createService((params, candidateNodes, currentState) -> { TestParams testParams = (TestParams) params; switch (testParams.getTestParam()) { case "assign_me" -> { logger.info( "--> assigning task randomly from candidates [{}]", candidateNodes.stream().map(DiscoveryNode::getId).collect(Collectors.joining(",")) ); Assignment assignment = randomNodeAssignment(candidateNodes); logger.info("--> assigned task to {}", assignment); return assignment; } case "dont_assign_me" -> { logger.info("--> not assigning task"); return NO_NODE_FOUND; } case "fail_me_if_called" -> { logger.info("--> failing test from task assignment"); fail("the decision decider shouldn't be called on this task"); return null; } case "assign_one" -> { logger.info("--> assigning only a single task"); return assignOnlyOneTaskAtATime(candidateNodes, currentState); } case "assign_based_on_non_cluster_state_condition" -> { logger.info("--> assigning based on non cluster state condition: {}", nonClusterStateCondition); return assignBasedOnNonClusterStateCondition(candidateNodes); } default -> fail("unknown param " + testParams.getTestParam()); } return NO_NODE_FOUND; }); return service.reassignTasks(clusterState); } private Assignment assignOnlyOneTaskAtATime(Collection<DiscoveryNode> candidateNodes, ClusterState clusterState) { DiscoveryNodes nodes = clusterState.nodes(); var tasksInProgress = getPersistentTasks(clusterState); if (tasksInProgress.findTasks( TestPersistentTasksExecutor.NAME, task -> "assign_one".equals(((TestParams) task.getParams()).getTestParam()) && task.getExecutorNode() != null && nodes.nodeExists(task.getExecutorNode()) ).isEmpty()) { return randomNodeAssignment(candidateNodes); } else { return new Assignment(null, "only one task can be assigned at a time"); } } private Assignment assignBasedOnNonClusterStateCondition(Collection<DiscoveryNode> candidateNodes) { if (nonClusterStateCondition) { return randomNodeAssignment(candidateNodes); } else { return new Assignment(null, "non-cluster state condition prevents assignment"); } } private Assignment randomNodeAssignment(Collection<DiscoveryNode> nodes) { if (nodes.isEmpty()) { return NO_NODE_FOUND; } return Optional.ofNullable(randomFrom(nodes)).map(node -> new Assignment(node.getId(), "test assignment")).orElse(NO_NODE_FOUND); } private String dumpEvent(ClusterChangedEvent event) { return "nodes_changed: " + event.nodesChanged() + " nodes_removed:" + event.nodesRemoved() + " routing_table_changed:" + event.routingTableChanged() + " tasks: " + getPersistentTasks(event.state()); } private ClusterState significantChange(ClusterState clusterState) { ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = getPersistentTasks(clusterState); if (tasks != null) { if (randomBoolean()) { for (PersistentTask<?> task : tasks.tasks()) { if (task.isAssigned() && clusterState.nodes().nodeExists(task.getExecutorNode())) { logger.info("removed node {}", task.getExecutorNode()); builder.nodes(DiscoveryNodes.builder(clusterState.nodes()).remove(task.getExecutorNode())); return builder.build(); } } } } boolean tasksOrNodesChanged = false; // add a new unassigned task if (hasAssignableTasks(tasks, clusterState.nodes()) == false) { // we don't have any unassigned tasks - add some if (randomBoolean()) { logger.info("added random task"); addRandomTask(builder, Metadata.builder(clusterState.metadata()), tasksBuilder(tasks), null); tasksOrNodesChanged = true; } else { logger.info("added unassignable task with custom assignment message"); addRandomTask( builder, Metadata.builder(clusterState.metadata()), tasksBuilder(tasks), new Assignment(null, "change me"), "never_assign" ); tasksOrNodesChanged = true; } } // add a node if there are unassigned tasks if (clusterState.nodes().getNodes().isEmpty()) { logger.info("added random node"); builder.nodes(DiscoveryNodes.builder(clusterState.nodes()).add(newNode(randomAlphaOfLength(10)))); tasksOrNodesChanged = true; } if (tasksOrNodesChanged == false) { // change routing table to simulate a change logger.info("changed routing table"); Metadata.Builder metadata = Metadata.builder(clusterState.metadata()); RoutingTable.Builder routingTable = RoutingTable.builder( TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY, clusterState.routingTable() ); changeRoutingTable(metadata, routingTable); builder.metadata(metadata).routingTable(routingTable.build()); } return builder.build(); } private PersistentTasks removeTasksWithChangingAssignment(PersistentTasks tasks) { if (tasks != null) { boolean changed = false; var tasksBuilder = tasksBuilder(tasks); for (PersistentTask<?> task : tasks.tasks()) { // Remove all unassigned tasks that cause changing assignments they might trigger a significant change if ("never_assign".equals(((TestParams) task.getParams()).getTestParam()) && "change me".equals(task.getAssignment().getExplanation())) { logger.info("removed task with changing assignment {}", task.getId()); tasksBuilder.removeTask(task.getId()); changed = true; } } if (changed) { return tasksBuilder.build(); } } return tasks; } private ClusterState insignificantChange(ClusterState clusterState) { ClusterState.Builder builder = ClusterState.builder(clusterState); var tasks = getPersistentTasks(clusterState); tasks = removeTasksWithChangingAssignment(tasks); var tasksBuilder = tasksBuilder(tasks); if (randomBoolean()) { if (hasAssignableTasks(tasks, clusterState.nodes()) == false) { // we don't have any unassigned tasks - adding a node or changing a routing table shouldn't affect anything if (randomBoolean()) { logger.info("added random node"); builder.nodes(DiscoveryNodes.builder(clusterState.nodes()).add(newNode(randomAlphaOfLength(10)))); } if (randomBoolean()) { logger.info("added random unassignable task"); addRandomTask(builder, Metadata.builder(clusterState.metadata()), tasksBuilder, NO_NODE_FOUND, "never_assign"); return builder.build(); } logger.info("changed routing table"); Metadata.Builder metadata = Metadata.builder(clusterState.metadata()); updateTasksCustomMetadata(metadata, tasksBuilder); RoutingTable.Builder routingTable = RoutingTable.builder( TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY, clusterState.routingTable() ); changeRoutingTable(metadata, routingTable); builder.metadata(metadata).routingTable(routingTable.build()); return builder.build(); } } if (randomBoolean()) { // remove a node that doesn't have any tasks assigned to it and it's not the master node for (DiscoveryNode node : clusterState.nodes()) { if (hasTasksAssignedTo(tasks, node.getId()) == false && "this_node".equals(node.getId()) == false) { logger.info("removed unassigned node {}", node.getId()); return builder.nodes(DiscoveryNodes.builder(clusterState.nodes()).remove(node.getId())).build(); } } } if (randomBoolean()) { // clear the task if (randomBoolean()) { logger.info("removed all tasks"); Metadata.Builder metadata = updateTasksCustomMetadata( Metadata.builder(clusterState.metadata()), scope == PersistentTasksExecutor.Scope.CLUSTER ? ClusterPersistentTasksCustomMetadata.builder() : PersistentTasksCustomMetadata.builder() ); return builder.metadata(metadata).build(); } else { logger.info("set task custom to null"); Metadata.Builder metadata; if (scope == PersistentTasksExecutor.Scope.CLUSTER) { metadata = Metadata.builder(clusterState.metadata()).removeCustom(ClusterPersistentTasksCustomMetadata.TYPE); } else { metadata = Metadata.builder(clusterState.metadata()) .put( ProjectMetadata.builder(clusterState.metadata().getProject()).removeCustom(PersistentTasksCustomMetadata.TYPE) ); } return builder.metadata(metadata).build(); } } logger.info("removed all unassigned tasks and changed routing table"); if (tasks != null) { for (PersistentTask<?> task : tasks.tasks()) { if (task.getExecutorNode() == null || "never_assign".equals(((TestParams) task.getParams()).getTestParam())) { tasksBuilder.removeTask(task.getId()); } } } // Just add a random index - that shouldn't change anything IndexMetadata indexMetadata = IndexMetadata.builder(randomAlphaOfLength(10)) .settings(Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersionUtils.randomVersion())) .numberOfShards(1) .numberOfReplicas(1) .build(); Metadata.Builder metadata = updateTasksCustomMetadata( Metadata.builder(clusterState.metadata()).put(indexMetadata, false), tasksBuilder ); return builder.metadata(metadata).build(); } private boolean hasAssignableTasks(PersistentTasks tasks, DiscoveryNodes discoveryNodes) { if (tasks == null || tasks.tasks().isEmpty()) { return false; } return tasks.tasks().stream().anyMatch(task -> { if (task.getExecutorNode() == null || discoveryNodes.nodeExists(task.getExecutorNode())) { return "never_assign".equals(((TestParams) task.getParams()).getTestParam()) == false; } return false; }); } private boolean hasTasksAssignedTo(PersistentTasks tasks, String nodeId) { return tasks != null && tasks.tasks().stream().anyMatch(task -> nodeId.equals(task.getExecutorNode())) == false; } private ClusterState.Builder addRandomTask( ClusterState.Builder clusterStateBuilder, Metadata.Builder metadata, PersistentTasks.Builder<?> tasks, String node ) { return addRandomTask(clusterStateBuilder, metadata, tasks, new Assignment(node, randomAlphaOfLength(10)), randomAlphaOfLength(10)); } private ClusterState.Builder addRandomTask( ClusterState.Builder clusterStateBuilder, Metadata.Builder metadata, PersistentTasks.Builder<?> tasks, Assignment assignment, String param ) { final var persistentTasks = tasks.addTask(UUIDs.base64UUID(), TestPersistentTasksExecutor.NAME, new TestParams(param), assignment) .build(); if (scope == PersistentTasksExecutor.Scope.CLUSTER) { metadata.putCustom(ClusterPersistentTasksCustomMetadata.TYPE, (ClusterPersistentTasksCustomMetadata) persistentTasks); } else { metadata.putCustom(PersistentTasksCustomMetadata.TYPE, (PersistentTasksCustomMetadata) persistentTasks); } return clusterStateBuilder.metadata(metadata); } private String addTask(PersistentTasks.Builder<?> tasks, String param, String node) { String id = UUIDs.base64UUID(); tasks.addTask(id, TestPersistentTasksExecutor.NAME, new TestParams(param), new Assignment(node, "explanation: " + param)); return id; } private DiscoveryNode newNode(String nodeId) { return DiscoveryNodeUtils.builder(nodeId).roles(Set.of(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.DATA_ROLE)).build(); } private ClusterState initialState() { Metadata.Builder metadata = Metadata.builder(); RoutingTable.Builder routingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY); int randomIndices = randomIntBetween(0, 5); for (int i = 0; i < randomIndices; i++) { changeRoutingTable(metadata, routingTable); } DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(); nodes.add(DiscoveryNodeUtils.create("this_node")); nodes.localNodeId("this_node"); nodes.masterNodeId("this_node"); return ClusterState.builder(ClusterName.DEFAULT).nodes(nodes).metadata(metadata).routingTable(routingTable.build()).build(); } private void changeRoutingTable(Metadata.Builder metadata, RoutingTable.Builder routingTable) { IndexMetadata indexMetadata = IndexMetadata.builder(randomAlphaOfLength(10)) .settings(Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersionUtils.randomVersion())) .numberOfShards(1) .numberOfReplicas(1) .build(); metadata.put(indexMetadata, false); routingTable.addAsNew(indexMetadata); } private PersistentTasks getPersistentTasks(ClusterState clusterState) { if (scope == PersistentTasksExecutor.Scope.CLUSTER) { return ClusterPersistentTasksCustomMetadata.get(clusterState.metadata()); } else { return PersistentTasksCustomMetadata.get(clusterState.metadata().getProject()); } } private Metadata.Builder updateTasksCustomMetadata(Metadata.Builder metadata, PersistentTasks.Builder<?> tasksBuilder) { if (scope == PersistentTasksExecutor.Scope.CLUSTER) { metadata.putCustom(ClusterPersistentTasksCustomMetadata.TYPE, (ClusterPersistentTasksCustomMetadata) tasksBuilder.build()); } else { metadata.putCustom(PersistentTasksCustomMetadata.TYPE, (PersistentTasksCustomMetadata) tasksBuilder.build()); } return metadata; } private PersistentTasks.Builder<?> tasksBuilder(PersistentTasks tasks) { if (tasks == null) { return scope == PersistentTasksExecutor.Scope.CLUSTER ? ClusterPersistentTasksCustomMetadata.builder() : PersistentTasksCustomMetadata.builder(); } else { return tasks.toBuilder(); } } /** Creates a PersistentTasksClusterService with a single PersistentTasksExecutor implemented by a BiFunction **/ private <P extends PersistentTaskParams> PersistentTasksClusterService createService( final TriFunction<P, Collection<DiscoveryNode>, ClusterState, Assignment> fn ) { return createService(clusterService, fn); } private <P extends PersistentTaskParams> PersistentTasksClusterService createService( ClusterService clusterService, final TriFunction<P, Collection<DiscoveryNode>, ClusterState, Assignment> fn ) { PersistentTasksExecutorRegistry registry = new PersistentTasksExecutorRegistry( singleton(new PersistentTasksExecutor<P>(TestPersistentTasksExecutor.NAME, null) { @Override public Scope scope() { return scope; } @Override protected Assignment doGetAssignment( P params, Collection<DiscoveryNode> candidateNodes, ClusterState clusterState, ProjectId projectId ) { return fn.apply(params, candidateNodes, clusterState); } @Override protected void nodeOperation(AllocatedPersistentTask task, P params, PersistentTaskState state) { throw new UnsupportedOperationException(); } }) ); return new PersistentTasksClusterService(Settings.EMPTY, registry, clusterService, threadPool); } }
PersistentTasksClusterServiceTests
java
spring-projects__spring-boot
core/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleBeanPostProcessor.java
{ "start": 2575, "end": 7007 }
class ____ implements DestructionAwareBeanPostProcessor { private static final Log logger = LogFactory.getLog(TestcontainersLifecycleBeanPostProcessor.class); private final ConfigurableListableBeanFactory beanFactory; private final TestcontainersStartup startup; private final AtomicReference<Startables> startables = new AtomicReference<>(Startables.UNSTARTED); private final AtomicBoolean containersInitialized = new AtomicBoolean(); TestcontainersLifecycleBeanPostProcessor(ConfigurableListableBeanFactory beanFactory, TestcontainersStartup startup) { this.beanFactory = beanFactory; this.startup = startup; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (this.beanFactory.isConfigurationFrozen() && !isAotProcessingInProgress()) { initializeContainers(); } if (bean instanceof Startable startableBean) { if (this.startables.compareAndExchange(Startables.UNSTARTED, Startables.STARTING) == Startables.UNSTARTED) { initializeStartables(startableBean, beanName); } else if (this.startables.get() == Startables.STARTED) { logger.trace(LogMessage.format("Starting container %s", beanName)); TestcontainersStartup.start(startableBean); } } return bean; } private boolean isAotProcessingInProgress() { return Boolean.getBoolean(AbstractAotProcessor.AOT_PROCESSING); } private void initializeStartables(Startable startableBean, String startableBeanName) { logger.trace(LogMessage.format("Initializing startables")); List<String> beanNames = new ArrayList<>(getBeanNames(Startable.class)); beanNames.remove(startableBeanName); List<Object> beans = getBeans(beanNames); if (beans == null) { logger.trace(LogMessage.format("Failed to obtain startables %s", beanNames)); this.startables.set(Startables.UNSTARTED); return; } beanNames.add(startableBeanName); beans.add(startableBean); logger.trace(LogMessage.format("Starting startables %s", beanNames)); start(beans); this.startables.set(Startables.STARTED); if (!beanNames.isEmpty()) { logger.debug(LogMessage.format("Initialized and started startable beans '%s'", beanNames)); } } private void start(List<Object> beans) { Set<Startable> startables = beans.stream() .filter(Startable.class::isInstance) .map(Startable.class::cast) .collect(Collectors.toCollection(LinkedHashSet::new)); this.startup.start(startables); } private void initializeContainers() { if (this.containersInitialized.compareAndSet(false, true)) { logger.trace("Initializing containers"); List<String> beanNames = getBeanNames(ContainerState.class); List<Object> beans = getBeans(beanNames); if (beans != null) { logger.trace(LogMessage.format("Initialized containers %s", beanNames)); } else { logger.trace(LogMessage.format("Failed to initialize containers %s", beanNames)); this.containersInitialized.set(false); } } } private List<String> getBeanNames(Class<?> type) { return List.of(this.beanFactory.getBeanNamesForType(type, true, false)); } private @Nullable List<Object> getBeans(List<String> beanNames) { List<Object> beans = new ArrayList<>(beanNames.size()); for (String beanName : beanNames) { try { beans.add(this.beanFactory.getBean(beanName)); } catch (BeanCreationException ex) { if (ex.contains(BeanCurrentlyInCreationException.class)) { return null; } throw ex; } } return beans; } @Override public boolean requiresDestruction(Object bean) { return bean instanceof Startable; } @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { if (bean instanceof Startable startable && !isDestroyedByFramework(beanName) && !isReusedContainer(bean)) { startable.close(); } } private boolean isDestroyedByFramework(String beanName) { try { BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition(beanName); String destroyMethodName = beanDefinition.getDestroyMethodName(); return !"".equals(destroyMethodName); } catch (NoSuchBeanDefinitionException ex) { return false; } } private boolean isReusedContainer(Object bean) { return (bean instanceof GenericContainer<?> container) && container.isShouldBeReused() && TestcontainersConfiguration.getInstance().environmentSupportsReuse(); }
TestcontainersLifecycleBeanPostProcessor
java
apache__flink
flink-formats/flink-protobuf/src/test/java/org/apache/flink/formats/protobuf/MultiLevelMessageRowToProtoTest.java
{ "start": 1217, "end": 2362 }
class ____ { @Test public void testMultipleLevelMessage() throws Exception { RowData subSubRow = GenericRowData.of(1, 2L); RowData subRow = GenericRowData.of(subSubRow, false); RowData row = GenericRowData.of(1, 2L, false, subRow); byte[] bytes = ProtobufTestHelper.rowToPbBytes(row, MultipleLevelMessageTest.class); MultipleLevelMessageTest test = MultipleLevelMessageTest.parseFrom(bytes); assertFalse(test.getD().getC()); assertEquals(1, test.getD().getA().getA()); assertEquals(2L, test.getD().getA().getB()); assertEquals(1, test.getA()); } @Test public void testNull() throws Exception { RowData row = GenericRowData.of(1, 2L, false, null); byte[] bytes = ProtobufTestHelper.rowToPbBytes(row, MultipleLevelMessageTest.class); MultipleLevelMessageTest test = MultipleLevelMessageTest.parseFrom(bytes); MultipleLevelMessageTest.InnerMessageTest1 empty = MultipleLevelMessageTest.InnerMessageTest1.newBuilder().build(); assertEquals(empty, test.getD()); } }
MultiLevelMessageRowToProtoTest
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/SimpleCommandLineArgumentProvider.java
{ "start": 897, "end": 1239 }
class ____ implements CommandLineArgumentProvider { private final List<String> arguments; public SimpleCommandLineArgumentProvider(String... arguments) { this.arguments = Arrays.asList(arguments); } @Override public Iterable<String> asArguments() { return arguments; } }
SimpleCommandLineArgumentProvider
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 77094, "end": 77454 }
interface ____"); } @Test public void autoValueBuilderMissingSetter() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "foo.bar.Baz", "package foo.bar;", "", "import com.google.auto.value.AutoValue;", "", "@AutoValue", "public abstract
Builder2
java
redisson__redisson
redisson/src/main/java/org/redisson/api/listener/StreamAddListener.java
{ "start": 939, "end": 1138 }
interface ____ extends ObjectListener { /** * Invoked when a new entry is added to RStream object * * @param name object name */ void onAdd(String name); }
StreamAddListener
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SpringBatchEndpointBuilderFactory.java
{ "start": 1579, "end": 5179 }
interface ____ extends EndpointProducerBuilder { default AdvancedSpringBatchEndpointBuilder advanced() { return (AdvancedSpringBatchEndpointBuilder) this; } /** * Explicitly defines if the jobName should be taken from the headers * instead of the URI. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer * * @param jobFromHeader the value to set * @return the dsl builder */ default SpringBatchEndpointBuilder jobFromHeader(boolean jobFromHeader) { doSetProperty("jobFromHeader", jobFromHeader); return this; } /** * Explicitly defines if the jobName should be taken from the headers * instead of the URI. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer * * @param jobFromHeader the value to set * @return the dsl builder */ default SpringBatchEndpointBuilder jobFromHeader(String jobFromHeader) { doSetProperty("jobFromHeader", jobFromHeader); return this; } /** * Explicitly specifies a JobLauncher to be used. * * The option is a: * <code>org.springframework.batch.core.launch.JobLauncher</code> type. * * Group: producer * * @param jobLauncher the value to set * @return the dsl builder */ default SpringBatchEndpointBuilder jobLauncher(org.springframework.batch.core.launch.JobLauncher jobLauncher) { doSetProperty("jobLauncher", jobLauncher); return this; } /** * Explicitly specifies a JobLauncher to be used. * * The option will be converted to a * <code>org.springframework.batch.core.launch.JobLauncher</code> type. * * Group: producer * * @param jobLauncher the value to set * @return the dsl builder */ default SpringBatchEndpointBuilder jobLauncher(String jobLauncher) { doSetProperty("jobLauncher", jobLauncher); return this; } /** * Explicitly specifies a JobRegistry to be used. * * The option is a: * <code>org.springframework.batch.core.configuration.JobRegistry</code> * type. * * Group: producer * * @param jobRegistry the value to set * @return the dsl builder */ default SpringBatchEndpointBuilder jobRegistry(org.springframework.batch.core.configuration.JobRegistry jobRegistry) { doSetProperty("jobRegistry", jobRegistry); return this; } /** * Explicitly specifies a JobRegistry to be used. * * The option will be converted to a * <code>org.springframework.batch.core.configuration.JobRegistry</code> * type. * * Group: producer * * @param jobRegistry the value to set * @return the dsl builder */ default SpringBatchEndpointBuilder jobRegistry(String jobRegistry) { doSetProperty("jobRegistry", jobRegistry); return this; } } /** * Advanced builder for endpoint for the Spring Batch component. */ public
SpringBatchEndpointBuilder
java
elastic__elasticsearch
x-pack/qa/rolling-upgrade-multi-cluster/src/test/java/org/elasticsearch/upgrades/AbstractMultiClusterUpgradeTestCase.java
{ "start": 1102, "end": 1687 }
enum ____ { NONE, ONE_THIRD, TWO_THIRD, ALL; public static UpgradeState parse(String value) { return switch (value) { case "none" -> NONE; case "one_third" -> ONE_THIRD; case "two_third" -> TWO_THIRD; case "all" -> ALL; default -> throw new AssertionError("unknown cluster type: " + value); }; } } protected final UpgradeState upgradeState = UpgradeState.parse(System.getProperty("tests.rest.upgrade_state"));
UpgradeState
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableFunction.java
{ "start": 5612, "end": 9454 }
class ____<T> extends UserDefinedFunction { /** The code generated collector used to emit rows. */ private transient Collector<T> collector; /** Internal use. Sets the current collector. */ public final void setCollector(Collector<T> collector) { this.collector = collector; } /** * Returns the result type of the evaluation method. * * @deprecated This method uses the old type system and is based on the old reflective * extraction logic. The method will be removed in future versions and is only called when * using the deprecated {@code TableEnvironment.registerFunction(...)} method. The new * reflective extraction logic (possibly enriched with {@link DataTypeHint} and {@link * FunctionHint}) should be powerful enough to cover most use cases. For advanced users, it * is possible to override {@link UserDefinedFunction#getTypeInference(DataTypeFactory)}. */ @Deprecated public TypeInformation<T> getResultType() { return null; } /** * Returns {@link TypeInformation} about the operands of the evaluation method with a given * signature. * * @deprecated This method uses the old type system and is based on the old reflective * extraction logic. The method will be removed in future versions and is only called when * using the deprecated {@code TableEnvironment.registerFunction(...)} method. The new * reflective extraction logic (possibly enriched with {@link DataTypeHint} and {@link * FunctionHint}) should be powerful enough to cover most use cases. For advanced users, it * is possible to override {@link UserDefinedFunction#getTypeInference(DataTypeFactory)}. */ @Deprecated public TypeInformation<?>[] getParameterTypes(Class<?>[] signature) { final TypeInformation<?>[] types = new TypeInformation<?>[signature.length]; for (int i = 0; i < signature.length; i++) { try { types[i] = TypeExtractor.getForClass(signature[i]); } catch (InvalidTypesException e) { throw new ValidationException( "Parameter types of table function " + this.getClass().getCanonicalName() + " cannot be automatically determined. Please provide type information manually."); } } return types; } /** * Emits an (implicit or explicit) output row. * * <p>If null is emitted as an explicit row, it will be skipped by the runtime. For implicit * rows, the row's field will be null. * * @param row the output row */ protected final void collect(T row) { collector.collect(row); } @Override public final FunctionKind getKind() { return FunctionKind.TABLE; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public TypeInference getTypeInference(DataTypeFactory typeFactory) { return TypeInferenceExtractor.forTableFunction(typeFactory, (Class) getClass()); } /** * This method is called at the end of data processing. After this method is called, no more * records can be produced for the downstream operators. * * <p><b>NOTE:</b>This method does not need to close any resources. You should release external * resources in the {@link #close()} method. More details can see {@link * StreamOperator#finish()}. * * <p><b>Important:</b>Emit record in the {@link #close()} method is impossible since * flink-1.14, if you need to emit records at the end of data processing, do so in the {@link * #finish()} method. */ public void finish() throws Exception { // do nothing } }
TableFunction
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/netty/TieredStorageConsumerClientTest.java
{ "start": 2428, "end": 7395 }
class ____ { private static final TieredStoragePartitionId DEFAULT_PARTITION_ID = TieredStorageIdMappingUtils.convertId(new ResultPartitionID()); private static final TieredStorageSubpartitionId DEFAULT_SUBPARTITION_ID = new TieredStorageSubpartitionId(0); private static final TieredStorageInputChannelId DEFAULT_INPUT_CHANNEL_ID = new TieredStorageInputChannelId(0); private static final ResultSubpartitionIndexSet DEFAULT_SUBPARTITION_ID_SET = new ResultSubpartitionIndexSet(0); @Test void testStart() { CompletableFuture<Void> future = new CompletableFuture<>(); TestingTierConsumerAgent tierConsumerAgent = new TestingTierConsumerAgent.Builder() .setStartNotifier(() -> future.complete(null)) .build(); TieredStorageConsumerClient consumerClient = createTieredStorageConsumerClient(tierConsumerAgent); consumerClient.start(); assertThat(future).isDone(); } @Test void testGetNextBuffer() throws IOException { Buffer buffer = BufferBuilderTestUtils.buildSomeBuffer(0); TestingTierConsumerAgent tierConsumerAgent = new TestingTierConsumerAgent.Builder().setBufferSupplier(() -> buffer).build(); TieredStorageConsumerClient consumerClient = createTieredStorageConsumerClient(tierConsumerAgent); assertThat(consumerClient.getNextBuffer(DEFAULT_PARTITION_ID, DEFAULT_SUBPARTITION_ID)) .hasValue(buffer); } @Test void testRegisterAvailabilityNotifier() { CompletableFuture<Void> future = new CompletableFuture<>(); TestingTierConsumerAgent tierConsumerAgent = new TestingTierConsumerAgent.Builder() .setAvailabilityNotifierRegistrationRunnable(() -> future.complete(null)) .build(); TieredStorageConsumerClient consumerClient = createTieredStorageConsumerClient(tierConsumerAgent); consumerClient.registerAvailabilityNotifier( new TestingAvailabilityNotifier.Builder().build()); assertThat(future).isDone(); } @Test void testUpdateTierShuffleDescriptor() { CompletableFuture<Void> future = new CompletableFuture<>(); TestingTierConsumerAgent tierConsumerAgent = new TestingTierConsumerAgent.Builder() .setUpdateTierShuffleDescriptorRunnable(() -> future.complete(null)) .build(); assertThat(future).isNotDone(); TieredStorageConsumerClient consumerClient = createTieredStorageConsumerClient(tierConsumerAgent); consumerClient.updateTierShuffleDescriptors( DEFAULT_PARTITION_ID, DEFAULT_INPUT_CHANNEL_ID, DEFAULT_SUBPARTITION_ID, Collections.singletonList( new TierShuffleDescriptor() { private static final long serialVersionUID = 1L; })); assertThat(future).isDone(); } @Test void testClose() throws IOException { CompletableFuture<Void> future = new CompletableFuture<>(); TestingTierConsumerAgent tierConsumerAgent = new TestingTierConsumerAgent.Builder() .setCloseNotifier(() -> future.complete(null)) .build(); TieredStorageConsumerClient consumerClient = createTieredStorageConsumerClient(tierConsumerAgent); consumerClient.close(); assertThat(future).isDone(); } private TieredStorageConsumerClient createTieredStorageConsumerClient( TierConsumerAgent tierConsumerAgent) { TierShuffleDescriptor emptyTierShuffleDescriptor = new TierShuffleDescriptor() { private static final long serialVersionUID = 1L; }; return new TieredStorageConsumerClient( Collections.singletonList( new TestingTierFactory.Builder() .setTierConsumerAgentSupplier( (tieredStorageConsumerSpecs, nettyService) -> tierConsumerAgent) .build()), Collections.singletonList( new TieredStorageConsumerSpec( 0, DEFAULT_PARTITION_ID, DEFAULT_INPUT_CHANNEL_ID, DEFAULT_SUBPARTITION_ID_SET)), Collections.singletonList(Collections.singletonList(emptyTierShuffleDescriptor)), new TestingTieredStorageNettyService.Builder().build()); } }
TieredStorageConsumerClientTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/javatime/deser/ZoneOffsetDeserTest.java
{ "start": 1352, "end": 8073 }
class ____ extends DateTimeTestBase { private final static ObjectMapper MAPPER = newMapper(); private final static ObjectReader READER = MAPPER.readerFor(ZoneOffset.class); private final TypeReference<Map<String, ZoneOffset>> MAP_TYPE_REF = new TypeReference<Map<String, ZoneOffset>>() { }; @Test public void testSimpleZoneOffsetDeser() throws Exception { assertEquals(ZoneOffset.of("Z"), READER.readValue("\"Z\""), "The value is not correct."); assertEquals(ZoneOffset.of("+0300"), READER.readValue(q("+0300")), "The value is not correct."); assertEquals(ZoneOffset.of("-0630"), READER.readValue("\"-06:30\""), "The value is not correct."); } @Test public void testPolymorphicZoneOffsetDeser() throws Exception { ObjectMapper mapper = newMapperBuilder() .addMixIn(ZoneId.class, MockObjectConfiguration.class) .build(); ZoneId value = mapper.readValue("[\"" + ZoneOffset.class.getName() + "\",\"+0415\"]", ZoneId.class); assertTrue(value instanceof ZoneOffset); assertEquals(ZoneOffset.of("+0415"), value); } @Test public void testDeserializationWithTypeInfo03() throws Exception { ObjectMapper mapper = mapperBuilder() .addMixIn(ZoneId.class, MockObjectConfiguration.class) .build(); ZoneId value = mapper.readValue("[\"" + ZoneOffset.class.getName() + "\",\"+0415\"]", ZoneId.class); assertTrue(value instanceof ZoneOffset, "The value should be a ZoneOffset."); assertEquals(ZoneOffset.of("+0415"), value, "The value is not correct."); } @Test public void testBadDeserializationAsString01() throws Throwable { try { READER.readValue("\"notazonedoffset\""); fail("expected MismatchedInputException"); } catch (MismatchedInputException e) { verifyException(e, "Invalid ID for ZoneOffset"); } } @Test public void testDeserializationAsArrayDisabled() throws Throwable { try { READER.readValue("[\"+0300\"]"); fail("expected MismatchedInputException"); } catch (MismatchedInputException e) { verifyException(e, "Cannot deserialize value of type `java.time.ZoneOffset` from Array value"); } } @Test public void testDeserializationAsEmptyArrayDisabled() throws Throwable { try { READER.readValue("[]"); fail("expected MismatchedInputException"); } catch (MismatchedInputException e) { verifyException(e, "Cannot deserialize value of type `java.time.ZoneOffset` from Array value"); } try { READER .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue("[]"); fail("expected MismatchedInputException"); } catch (MismatchedInputException e) { verifyException(e, "Cannot deserialize value of type `java.time.ZoneOffset` from Array value"); } } @Test public void testDeserializationAsArrayEnabled() throws Throwable { ZoneOffset value = READER .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue("[\"+0300\"]"); assertEquals(ZoneOffset.of("+0300"), value, "The value is not correct."); } @Test public void testDeserializationAsEmptyArrayEnabled() throws Throwable { ZoneOffset value = READER .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) .readValue("[]"); assertNull(value); } /* /********************************************************** /* Tests for empty string handling /********************************************************** */ @Test public void testLenientDeserializeFromEmptyString() throws Exception { String key = "zoneOffset"; ObjectMapper mapper = newMapper(); ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String valueFromNullStr = mapper.writeValueAsString(asMap(key, null)); Map<String, ZoneOffset> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); ZoneId actualDateFromNullStr = actualMapFromNullStr.get(key); assertNull(actualDateFromNullStr); String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, "")); Map<String, ZoneOffset> actualMapFromEmptyStr = objectReader.readValue(valueFromEmptyStr); ZoneId actualDateFromEmptyStr = actualMapFromEmptyStr.get(key); assertEquals(null, actualDateFromEmptyStr, "empty string failed to deserialize to null with lenient setting"); } @Test public void testStrictDeserializeFromEmptyString() throws Exception { final String key = "zoneOffset"; final ObjectMapper mapper = mapperBuilder() .withCoercionConfig(LogicalType.DateTime, cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail)) .build(); final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String valueFromNullStr = mapper.writeValueAsString(asMap(key, null)); Map<String, ZoneOffset> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); assertNull(actualMapFromNullStr.get(key)); String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, "")); try { objectReader.readValue(valueFromEmptyStr); fail("Should not pass"); } catch (MismatchedInputException e) { verifyException(e, "Cannot coerce empty String"); verifyException(e, ZoneOffset.class.getName()); } } // [module-java8#68] @Test public void testZoneOffsetDeserFromEmpty() throws Exception { // by default, should be fine assertNull(MAPPER.readValue(q(" "), ZoneOffset.class)); // but fail if coercion illegal final ObjectMapper mapper = mapperBuilder() .withCoercionConfig(LogicalType.DateTime, cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail)) .build(); try { mapper.readerFor(ZoneOffset.class) .readValue(q(" ")); fail("Should not pass"); } catch (MismatchedInputException e) { verifyException(e, "Cannot coerce empty String"); verifyException(e, ZoneOffset.class.getName()); } } }
ZoneOffsetDeserTest
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/runners/util/RunnerProviderTest.java
{ "start": 386, "end": 781 }
class ____ extends TestBase { @Test public void shouldCreateRunnerInstance() throws Throwable { // given RunnerProvider provider = new RunnerProvider(); // when InternalRunner runner = provider.newInstance(DefaultInternalRunner.class.getName(), this.getClass(), null); // then assertNotNull(runner); } }
RunnerProviderTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/types/JavaToValueConverter.java
{ "start": 915, "end": 3236 }
class ____ { public static Value convertBoxedJavaType(Object boxed) { if (boxed == null) { return null; } final Class<?> clazz = boxed.getClass(); if (clazz == String.class) { return new StringValue((String) boxed); } else if (clazz == Integer.class) { return new IntValue((Integer) boxed); } else if (clazz == Long.class) { return new LongValue((Long) boxed); } else if (clazz == Double.class) { return new DoubleValue((Double) boxed); } else if (clazz == Float.class) { return new FloatValue((Float) boxed); } else if (clazz == Boolean.class) { return new BooleanValue((Boolean) boxed); } else if (clazz == Byte.class) { return new ByteValue((Byte) boxed); } else if (clazz == Short.class) { return new ShortValue((Short) boxed); } else if (clazz == Character.class) { return new CharValue((Character) boxed); } else { throw new IllegalArgumentException("Object is no primitive Java type."); } } public static Object convertValueType(Value value) { if (value == null) { return null; } if (value instanceof StringValue) { return ((StringValue) value).getValue(); } else if (value instanceof IntValue) { return ((IntValue) value).getValue(); } else if (value instanceof LongValue) { return ((LongValue) value).getValue(); } else if (value instanceof DoubleValue) { return ((DoubleValue) value).getValue(); } else if (value instanceof FloatValue) { return ((FloatValue) value).getValue(); } else if (value instanceof BooleanValue) { return ((BooleanValue) value).getValue(); } else if (value instanceof ByteValue) { return ((ByteValue) value).getValue(); } else if (value instanceof ShortValue) { return ((ShortValue) value).getValue(); } else if (value instanceof CharValue) { return ((CharValue) value).getValue(); } else { throw new IllegalArgumentException("Object is no primitive Java type."); } } }
JavaToValueConverter
java
alibaba__druid
core/src/main/java/com/alibaba/druid/pool/xa/JtdsXAResource.java
{ "start": 980, "end": 3700 }
class ____ implements XAResource { private static final Log LOG = LogFactory.getLog(JtdsXAResource.class); private final Connection connection; private final JtdsXAConnection xaConnection; private String rmHost; private static Method method; public JtdsXAResource(JtdsXAConnection xaConnection, Connection connection) { this.xaConnection = xaConnection; this.connection = connection; if (method == null) { try { method = connection.getClass().getMethod("getRmHost"); } catch (Exception e) { LOG.error("getRmHost method error", e); } } if (method != null) { try { rmHost = (String) method.invoke(connection); } catch (Exception e) { LOG.error("getRmHost error", e); } } } protected JtdsXAConnection getResourceManager() { return xaConnection; } protected String getRmHost() { return this.rmHost; } @Override public void commit(Xid xid, boolean commit) throws XAException { XASupport.xa_commit(connection, xaConnection.getXAConnectionID(), xid, commit); } @Override public void end(Xid xid, int flags) throws XAException { XASupport.xa_end(connection, xaConnection.getXAConnectionID(), xid, flags); } @Override public void forget(Xid xid) throws XAException { XASupport.xa_forget(connection, xaConnection.getXAConnectionID(), xid); } @Override public int getTransactionTimeout() throws XAException { return 0; } @Override public boolean isSameRM(XAResource xares) throws XAException { if (xares instanceof JtdsXAResource) { if (((JtdsXAResource) xares).getRmHost().equals(this.rmHost)) { return true; } } return false; } @Override public int prepare(Xid xid) throws XAException { return XASupport.xa_prepare(connection, xaConnection.getXAConnectionID(), xid); } @Override public Xid[] recover(int flags) throws XAException { return XASupport.xa_recover(connection, xaConnection.getXAConnectionID(), flags); } @Override public void rollback(Xid xid) throws XAException { XASupport.xa_rollback(connection, xaConnection.getXAConnectionID(), xid); } @Override public boolean setTransactionTimeout(int seconds) throws XAException { return false; } @Override public void start(Xid xid, int flags) throws XAException { XASupport.xa_start(connection, xaConnection.getXAConnectionID(), xid, flags); } }
JtdsXAResource
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/GeoHexBoundedPredicate.java
{ "start": 665, "end": 1786 }
class ____ { private final boolean crossesDateline; private final GeoBoundingBox bbox, scratch; GeoHexBoundedPredicate(GeoBoundingBox bbox) { this.crossesDateline = bbox.right() < bbox.left(); this.bbox = bbox; this.scratch = new GeoBoundingBox(new org.elasticsearch.common.geo.GeoPoint(), new org.elasticsearch.common.geo.GeoPoint()); } public boolean validHex(long hex) { H3SphericalUtil.computeGeoBounds(hex, scratch); if (bbox.top() > scratch.bottom() && bbox.bottom() < scratch.top()) { if (scratch.left() > scratch.right()) { return intersects(-180, scratch.right()) || intersects(scratch.left(), 180); } else { return intersects(scratch.left(), scratch.right()); } } return false; } private boolean intersects(double minLon, double maxLon) { if (crossesDateline) { return bbox.left() < maxLon || bbox.right() > minLon; } else { return bbox.left() < maxLon && bbox.right() > minLon; } } }
GeoHexBoundedPredicate
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/dynamicfiltering/DynamicFilteringDataCollectorOperatorTest.java
{ "start": 1996, "end": 5597 }
class ____ { @Test void testCollectDynamicFilteringData() throws Exception { RowType rowType = RowType.of(new IntType(), new BigIntType(), new VarCharType()); List<Integer> indexes = Arrays.asList(0, 1, 3); MockOperatorEventGateway gateway = new MockOperatorEventGateway(); DynamicFilteringDataCollectorOperator operator = new DynamicFilteringDataCollectorOperator(null, rowType, indexes, -1, gateway); ConcurrentLinkedQueue<Object> output; try (OneInputStreamOperatorTestHarness<RowData, Object> harness = new OneInputStreamOperatorTestHarness<>(operator)) { output = harness.getOutput(); harness.setup(); harness.open(); for (long i = 0L; i < 3L; i++) { harness.processElement(rowData(1, 1L, 0, "a"), i); } harness.processElement(rowData(2, 1L, 0, null), 3L); // operator.finish is called when closing } assertThat(output).isEmpty(); assertThat(gateway.getEventsSent()).hasSize(1); OperatorEvent event = gateway.getEventsSent().get(0); assertThat(event).isInstanceOf(SourceEventWrapper.class); SourceEvent dynamicFilteringEvent = ((SourceEventWrapper) event).getSourceEvent(); assertThat(dynamicFilteringEvent).isInstanceOf(DynamicFilteringEvent.class); DynamicFilteringData data = ((DynamicFilteringEvent) dynamicFilteringEvent).getData(); assertThat(data.isFiltering()).isTrue(); assertThat(data.getData()).hasSize(2); assertThat(data.contains(rowData(1, 1L, "a"))).isTrue(); assertThat(data.contains(rowData(2, 1L, null))).isTrue(); } @Test void testExceedsThreshold() throws Exception { RowType rowType = RowType.of(new IntType(), new BigIntType(), new VarCharType()); List<Integer> indexes = Arrays.asList(0, 1, 3); MockOperatorEventGateway gateway = new MockOperatorEventGateway(); // Can hold at most 2 rows int thresholds = 100; DynamicFilteringDataCollectorOperator operator = new DynamicFilteringDataCollectorOperator( null, rowType, indexes, thresholds, gateway); try (OneInputStreamOperatorTestHarness<RowData, Object> harness = new OneInputStreamOperatorTestHarness<>(operator)) { harness.setup(); harness.open(); harness.processElement(rowData(1, 1L, 0, "a"), 1L); harness.processElement(rowData(2, 1L, 0, "b"), 2L); harness.processElement(rowData(3, 1L, 0, "c"), 3L); } assertThat(gateway.getEventsSent()).hasSize(1); OperatorEvent event = gateway.getEventsSent().get(0); assertThat(event).isInstanceOf(SourceEventWrapper.class); SourceEvent dynamicFilteringEvent = ((SourceEventWrapper) event).getSourceEvent(); assertThat(dynamicFilteringEvent).isInstanceOf(DynamicFilteringEvent.class); DynamicFilteringData data = ((DynamicFilteringEvent) dynamicFilteringEvent).getData(); assertThat(data.isFiltering()).isFalse(); } private RowData rowData(Object... values) { GenericRowData rowData = new GenericRowData(values.length); for (int i = 0; i < values.length; ++i) { Object value = values[i]; value = value instanceof String ? new BinaryStringData((String) value) : value; rowData.setField(i, value); } return rowData; } }
DynamicFilteringDataCollectorOperatorTest
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/JmsPassThroughJmsKeyFormatStrategyEndpointTest.java
{ "start": 1523, "end": 4013 }
class ____ extends AbstractJMSTest { @Order(2) @RegisterExtension public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension(); protected CamelContext context; protected ProducerTemplate template; protected ConsumerTemplate consumer; private final String uri = "activemq:queue:JmsPassThroughJmsKeyFormatStrategyEndpointTest?jmsKeyFormatStrategy=passthrough"; @Test public void testSendWithHeaders() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).body().isEqualTo("Hello World"); mock.message(0).header("HEADER_1").isEqualTo("VALUE_1"); mock.message(0).header("HEADER_2").isEqualTo("VALUE_2"); template.sendBodyAndHeader(uri, "Hello World", "HEADER_1", "VALUE_1"); MockEndpoint.assertIsSatisfied(context); assertEquals("VALUE_1", mock.getReceivedExchanges().get(0).getIn().getHeader("HEADER_1")); assertEquals("VALUE_2", mock.getReceivedExchanges().get(0).getIn().getHeader("HEADER_2")); assertEquals("VALUE_1", mock.getReceivedExchanges().get(0).getIn().getHeaders().get("HEADER_1")); assertEquals("VALUE_2", mock.getReceivedExchanges().get(0).getIn().getHeaders().get("HEADER_2")); } @Override protected String getComponentName() { return "activemq"; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(uri) .process(exchange -> { Map<String, Object> headers = exchange.getIn().getHeaders(); assertEquals("VALUE_1", headers.get("HEADER_1")); assertEquals("VALUE_1", exchange.getIn().getHeader("HEADER_1")); }) .setHeader("HEADER_2", constant("VALUE_2")) .to("mock:result"); } }; } @Override public CamelContextExtension getCamelContextExtension() { return camelContextExtension; } @BeforeEach void setUpRequirements() { context = camelContextExtension.getContext(); template = camelContextExtension.getProducerTemplate(); consumer = camelContextExtension.getConsumerTemplate(); } }
JmsPassThroughJmsKeyFormatStrategyEndpointTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpressionTest.java
{ "start": 2199, "end": 6166 }
class ____ { public static int staticVar1 = 1; private StaticQualifiedUsingExpressionPositiveCase1 next; public static int staticTestMethod() { return 1; } public static Object staticTestMethod2() { return new Object(); } public static Object staticTestMethod3(Object x) { return null; } public void test1() { StaticQualifiedUsingExpressionPositiveCase1 testObj = new StaticQualifiedUsingExpressionPositiveCase1(); int i; // BUG: Diagnostic contains: variable staticVar1 // i = staticVar1 i = this.staticVar1; // BUG: Diagnostic contains: variable staticVar1 // i = staticVar1 i = testObj.staticVar1; // BUG: Diagnostic contains: variable staticVar1 // i = staticVar1 i = testObj.next.next.next.staticVar1; } public void test2() { int i; Integer integer = Integer.valueOf(1); // BUG: Diagnostic contains: variable MAX_VALUE // i = Integer.MAX_VALUE i = integer.MAX_VALUE; } public void test3() { String s1 = new String(); // BUG: Diagnostic contains: method valueOf // String s2 = String.valueOf(10) String s2 = s1.valueOf(10); // BUG: Diagnostic contains: method valueOf // s2 = String.valueOf(10) s2 = new String().valueOf(10); // BUG: Diagnostic contains: method staticTestMethod // int i = staticTestMethod() int i = this.staticTestMethod(); // BUG: Diagnostic contains: method staticTestMethod2 // String s3 = staticTestMethod2().toString String s3 = this.staticTestMethod2().toString(); // BUG: Diagnostic contains: method staticTestMethod // i = staticTestMethod() i = this.next.next.next.staticTestMethod(); } public void test4() { BigDecimal decimal = new BigDecimal(1); // BUG: Diagnostic contains: method valueOf // BigDecimal decimal2 = BigDecimal.valueOf(1) BigDecimal decimal2 = decimal.valueOf(1); } public static MyClass hiding; public void test5(MyClass hiding) { // BUG: Diagnostic contains: method staticTestMethod3 // Object o = staticTestMethod3(this.toString()) Object o = this.staticTestMethod3(this.toString()); // BUG: Diagnostic contains: variable myClass // x = MyClass.StaticInnerClass.myClass.FIELD; int x = new MyClass.StaticInnerClass().myClass.FIELD; // BUG: Diagnostic contains: variable STATIC_FIELD // x = MyClass.STATIC_FIELD; x = new MyClass.StaticInnerClass().myClass.STATIC_FIELD; // BUG: Diagnostic contains: variable hiding // StaticQualifiedUsingExpressionPositiveCase1.hiding = hiding; this.hiding = hiding; // BUG: Diagnostic contains: variable STATIC_FIELD // x = MyClass.STATIC_FIELD; x = MyStaticClass.myClass.STATIC_FIELD; // BUG: Diagnostic contains: method staticMethod // x = MyClass.staticMethod(); x = MyStaticClass.myClass.staticMethod(); x = MyStaticClass.myClass.FIELD; x = MyStaticClass.myClass.method(); } static
StaticQualifiedUsingExpressionPositiveCase1
java
grpc__grpc-java
benchmarks/src/generated/main/grpc/io/grpc/benchmarks/proto/BenchmarkServiceGrpc.java
{ "start": 15909, "end": 16268 }
class ____ implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return BenchmarkServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service BenchmarkService. */ public static final
BenchmarkServiceImplBase
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/PreferredAllocationRequestSlotMatchingStrategyTest.java
{ "start": 1894, "end": 10905 }
class ____ { private static final ResourceProfile finedGrainProfile = ResourceProfile.newBuilder().setCpuCores(1d).build(); private static final AllocationID allocationId1 = new AllocationID(); private static final AllocationID allocationId2 = new AllocationID(); private static final TaskManagerLocation tmLocation1 = new LocalTaskManagerLocation(); private static final TaskManagerLocation tmLocation2 = new LocalTaskManagerLocation(); // Slots on task-executor-1. private static final TestingPhysicalSlot slot1OfTm1 = createSlot(ResourceProfile.ANY, allocationId1, tmLocation1); private static final TestingPhysicalSlot slot2OfTm1 = createSlotAndAnyProfile(tmLocation1); private static final TestingPhysicalSlot slot3OfTm1 = createSlotAndAnyProfile(tmLocation1); private static final TestingPhysicalSlot slot4OfTm1 = createSlotAndGrainProfile(tmLocation1); private static final TestingPhysicalSlot slot5OfTm1 = createSlotAndGrainProfile(tmLocation1); // Slots on task-executor-2. private static final TestingPhysicalSlot slot6OfTm2 = createSlot(finedGrainProfile, allocationId2, tmLocation2); private static final TestingPhysicalSlot slot7OfTm2 = createSlotAndAnyProfile(tmLocation2); private static final TestingPhysicalSlot slot8OfTm2 = createSlotAndAnyProfile(tmLocation2); private static final TestingPhysicalSlot slot9OfTm2 = createSlotAndGrainProfile(tmLocation2); private static final TestingPhysicalSlot slot10OfTm2 = createSlotAndGrainProfile(tmLocation2); // Slot requests. private static final PendingRequest request1 = createRequest(2, allocationId1); private static final PendingRequest request2 = createRequest(finedGrainProfile, 3, allocationId2); private static final PendingRequest request3 = createRequest(2, null); private static final PendingRequest request4 = createRequest(1, null); private static final PendingRequest request5 = createRequest(finedGrainProfile, 3, null); private static final PendingRequest request6 = createRequest(finedGrainProfile, 5, null); /** * This test ensures that new slots are matched against the preferred allocationIds of the * pending requests. */ @Test void testNewSlotsAreMatchedAgainstPreferredAllocationIDs() { final RequestSlotMatchingStrategy strategy = PreferredAllocationRequestSlotMatchingStrategy.create( SimpleRequestSlotMatchingStrategy.INSTANCE); final AllocationID allocationId1 = new AllocationID(); final AllocationID allocationId2 = new AllocationID(); final Collection<TestingPhysicalSlot> slots = Arrays.asList( TestingPhysicalSlot.builder().withAllocationID(allocationId1).build(), TestingPhysicalSlot.builder().withAllocationID(allocationId2).build()); final Collection<PendingRequest> pendingRequests = Arrays.asList( PendingRequest.createNormalRequest( new SlotRequestId(), ResourceProfile.UNKNOWN, DefaultLoadingWeight.EMPTY, Collections.singleton(allocationId2)), PendingRequest.createNormalRequest( new SlotRequestId(), ResourceProfile.UNKNOWN, DefaultLoadingWeight.EMPTY, Collections.singleton(allocationId1))); final Collection<RequestSlotMatchingStrategy.RequestSlotMatch> requestSlotMatches = strategy.matchRequestsAndSlots(slots, pendingRequests, new HashMap<>()); assertThat(requestSlotMatches).hasSize(2); for (RequestSlotMatchingStrategy.RequestSlotMatch requestSlotMatch : requestSlotMatches) { assertThat(requestSlotMatch.getPendingRequest().getPreferredAllocations()) .contains(requestSlotMatch.getSlot().getAllocationId()); } } /** * This test ensures that new slots are matched on {@link * PreviousAllocationSlotSelectionStrategy} and {@link * TasksBalancedRequestSlotMatchingStrategy}. */ @Test void testNewSlotsAreMatchedAgainstAllocationAndBalancedPreferredIDs() { final RequestSlotMatchingStrategy strategy = PreferredAllocationRequestSlotMatchingStrategy.create( TasksBalancedRequestSlotMatchingStrategy.INSTANCE); final Collection<PendingRequest> pendingRequests = Arrays.asList(request1, request2, request3, request4, request5, request6); List<TestingPhysicalSlot> slots = getSlots(); final Collection<RequestSlotMatchingStrategy.RequestSlotMatch> requestSlotMatches = strategy.matchRequestsAndSlots(slots, pendingRequests, new HashMap<>()); final Map<TaskManagerLocation, List<SlotRequestId>> expectedResult = getExpectedResult(); assertThat(requestSlotMatches).hasSize(6); expectedResult.forEach( (taskManagerLocation, slotRequestIds) -> { List<SlotRequestId> requestIdsOfTm = requestSlotMatches.stream() .filter( requestSlotMatch -> requestSlotMatch .getSlot() .getTaskManagerLocation() .equals(taskManagerLocation)) .map( requestSlotMatch -> requestSlotMatch .getPendingRequest() .getSlotRequestId()) .collect(Collectors.toList()); assertThat(requestIdsOfTm).containsAll(slotRequestIds); }); } private static Map<TaskManagerLocation, List<SlotRequestId>> getExpectedResult() { final Map<TaskManagerLocation, List<SlotRequestId>> expectedResult = new HashMap<>(2); expectedResult.put( tmLocation1, Arrays.asList( request1.getSlotRequestId(), request6.getSlotRequestId(), request4.getSlotRequestId())); expectedResult.put( tmLocation2, Arrays.asList( request2.getSlotRequestId(), request5.getSlotRequestId(), request3.getSlotRequestId())); return expectedResult; } private static List<TestingPhysicalSlot> getSlots() { return Arrays.asList( slot1OfTm1, slot2OfTm1, slot3OfTm1, slot4OfTm1, slot5OfTm1, slot6OfTm2, slot7OfTm2, slot8OfTm2, slot9OfTm2, slot10OfTm2); } private static PendingRequest createRequest( ResourceProfile requestProfile, float loading, @Nullable AllocationID preferAllocationId) { final List<AllocationID> preferAllocationIds = Objects.isNull(preferAllocationId) ? Collections.emptyList() : Collections.singletonList(preferAllocationId); return PendingRequest.createNormalRequest( new SlotRequestId(), requestProfile, new DefaultLoadingWeight(loading), preferAllocationIds); } private static PendingRequest createRequest( float loading, @Nullable AllocationID preferAllocationId) { return createRequest(ResourceProfile.UNKNOWN, loading, preferAllocationId); } private static TestingPhysicalSlot createSlotAndAnyProfile(TaskManagerLocation tmLocation) { return createSlot(ResourceProfile.ANY, new AllocationID(), tmLocation); } private static TestingPhysicalSlot createSlotAndGrainProfile(TaskManagerLocation tmLocation) { return createSlot(finedGrainProfile, new AllocationID(), tmLocation); } static TestingPhysicalSlot createSlot( ResourceProfile profile, AllocationID allocationId, TaskManagerLocation tmLocation) { return TestingPhysicalSlot.builder() .withAllocationID(allocationId) .withTaskManagerLocation(tmLocation) .withResourceProfile(profile) .build(); } }
PreferredAllocationRequestSlotMatchingStrategyTest
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpToMockIT.java
{ "start": 1006, "end": 1798 }
class ____ extends FtpServerTestSupport { protected String expectedBody = "Hello there!"; private String getFtpUrl() { return "ftp://admin@localhost:{{ftp.server.port}}/tmp/camel?password=admin&recursive=true"; } @Test public void testFtpRoute() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); resultEndpoint.expectedBodiesReceived(expectedBody); template.sendBodyAndHeader(getFtpUrl(), expectedBody, "cheese", 123); resultEndpoint.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(getFtpUrl()).to("mock:result"); } }; } }
FromFtpToMockIT
java
spring-projects__spring-boot
module/spring-boot-data-redis/src/main/java/org/springframework/boot/data/redis/autoconfigure/PropertiesDataRedisConnectionDetails.java
{ "start": 4319, "end": 4692 }
class ____ implements MasterReplica { private final List<Node> nodes; PropertiesMasterReplica(DataRedisProperties.Masterreplica properties) { this.nodes = asNodes(properties.getNodes()); } @Override public List<Node> getNodes() { return this.nodes; } } /** * {@link Sentinel} implementation backed by properties. */ private
PropertiesMasterReplica
java
hibernate__hibernate-orm
hibernate-spatial/src/main/java/org/hibernate/spatial/JTSGeometryJavaType.java
{ "start": 1067, "end": 3803 }
class ____ extends AbstractJavaType<Geometry> { /** * An instance of this descriptor */ public static final JTSGeometryJavaType GEOMETRY_INSTANCE = new JTSGeometryJavaType( Geometry.class ); public static final JTSGeometryJavaType POINT_INSTANCE = new JTSGeometryJavaType( Point.class ); public static final JTSGeometryJavaType LINESTRING_INSTANCE = new JTSGeometryJavaType( LineString.class ); public static final JTSGeometryJavaType POLYGON_INSTANCE = new JTSGeometryJavaType( Polygon.class ); public static final JTSGeometryJavaType GEOMETRYCOLL_INSTANCE = new JTSGeometryJavaType( GeometryCollection.class ); public static final JTSGeometryJavaType MULTIPOINT_INSTANCE = new JTSGeometryJavaType( MultiPoint.class ); public static final JTSGeometryJavaType MULTILINESTRING_INSTANCE = new JTSGeometryJavaType( MultiLineString.class ); public static final JTSGeometryJavaType MULTIPOLYGON_INSTANCE = new JTSGeometryJavaType( MultiPolygon.class ); /** * Initialize a type descriptor for the geolatte-geom {@code Geometry} type. */ public JTSGeometryJavaType(Class<? extends Geometry> type) { super( type ); } @Override public String toString(Geometry value) { return value.toText(); } @Override public Geometry fromString(CharSequence string) { final WKTReader reader = new WKTReader(); try { return reader.read( string.toString() ); } catch (ParseException e) { throw new RuntimeException( String.format( Locale.ENGLISH, "Can't parse string %s as WKT", string ) ); } } @Override public JdbcType getRecommendedJdbcType(JdbcTypeIndicators indicators) { return indicators.getJdbcType( SqlTypes.GEOMETRY ); } @Override public boolean areEqual(Geometry one, Geometry another) { return JTSUtils.equalsExact3D( one, another ); } @SuppressWarnings("unchecked") @Override public <X> X unwrap(Geometry value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( Geometry.class.isAssignableFrom( type ) ) { return (X) value; } if ( org.geolatte.geom.Geometry.class.isAssignableFrom( type ) ) { return (X) JTS.from( value ); } if ( String.class.isAssignableFrom( type ) ) { return (X) toString( value ); } throw unknownUnwrap( type ); } @Override public <X> Geometry wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if ( value instanceof Geometry ) { return (Geometry) value; } if ( value instanceof org.geolatte.geom.Geometry ) { return JTS.to( (org.geolatte.geom.Geometry<?>) value ); } if ( value instanceof CharSequence ) { return fromString( (CharSequence) value ); } throw unknownWrap( value.getClass() ); } }
JTSGeometryJavaType
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/aot/hint/BindingReflectionHintsRegistrarTests.java
{ "start": 15861, "end": 16053 }
enum ____ { value1, value2 } record SampleRecord(String name) {} record SampleRecordWithProperty(String name) { public String getNameProperty() { return ""; } } static
SampleEnum
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableInternalHelper.java
{ "start": 9812, "end": 10532 }
class ____<T> implements Supplier<ConnectableFlowable<T>> { private final Flowable<T> parent; private final long time; private final TimeUnit unit; private final Scheduler scheduler; final boolean eagerTruncate; TimedReplay(Flowable<T> parent, long time, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) { this.parent = parent; this.time = time; this.unit = unit; this.scheduler = scheduler; this.eagerTruncate = eagerTruncate; } @Override public ConnectableFlowable<T> get() { return parent.replay(time, unit, scheduler, eagerTruncate); } } }
TimedReplay