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
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MisformattedTestDataTest.java
{ "start": 4975, "end": 5154 }
class ____ { void method(BugCheckerRefactoringTestHelper h) { h.addInputLines( "Test.java", // "package foo;
Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/TestCreators.java
{ "start": 1494, "end": 1659 }
class ____ { Double d; @JsonCreator protected DoubleConstructorBean(Double d) { this.d = d; } } static
DoubleConstructorBean
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/selector/JndiContextSelector.java
{ "start": 2159, "end": 3757 }
class ____ <code>java:comp/env/log4j/context-name</code>. * * <p>For security reasons, JNDI must be enabled by setting system property <code>log4j2.enableJndiContextSelector=true</code>.</p> * <p> * Here is an example of an <code>env-entry</code>: * </p> * <blockquote> * * <pre> * &lt;env-entry&gt; * &lt;description&gt;JNDI logging context name for this app&lt;/description&gt; * &lt;env-entry-name&gt;log4j/context-name&lt;/env-entry-name&gt; * &lt;env-entry-value&gt;aDistinctiveLoggingContextName&lt;/env-entry-value&gt; * &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt; * &lt;/env-entry&gt; * </pre> * * </blockquote> * * <p> * <em>If multiple applications use the same logging context name, then they * will share the same logging context.</em> * </p> * * <p> * You can also specify the URL for this context's configuration resource. This repository selector * (ContextJNDISelector) will use this resource to automatically configure the log4j repository. * </p> ** <blockquote> * * <pre> * &lt;env-entry&gt; * &lt;description&gt;URL for configuring log4j context&lt;/description&gt; * &lt;env-entry-name&gt;log4j/configuration-resource&lt;/env-entry-name&gt; * &lt;env-entry-value&gt;urlOfConfigurationResource&lt;/env-entry-value&gt; * &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt; * &lt;/env-entry&gt; * </pre> * * </blockquote> * * <p> * It usually good practice for configuration resources of distinct applications to have distinct names. However, if * this is not possible Naming * </p> */ public
is
java
apache__spark
sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/OperationHandle.java
{ "start": 967, "end": 3144 }
class ____ extends Handle { private final OperationType opType; private final TProtocolVersion protocol; private boolean hasResultSet = false; public OperationHandle(OperationType opType, TProtocolVersion protocol) { super(); this.opType = opType; this.protocol = protocol; } // dummy handle for ThriftCLIService public OperationHandle(TOperationHandle tOperationHandle) { this(tOperationHandle, TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1); } public OperationHandle(TOperationHandle tOperationHandle, TProtocolVersion protocol) { super(tOperationHandle.getOperationId()); this.opType = OperationType.getOperationType(tOperationHandle.getOperationType()); this.hasResultSet = tOperationHandle.isHasResultSet(); this.protocol = protocol; } public OperationType getOperationType() { return opType; } public void setHasResultSet(boolean hasResultSet) { this.hasResultSet = hasResultSet; } public boolean hasResultSet() { return hasResultSet; } public TOperationHandle toTOperationHandle() { TOperationHandle tOperationHandle = new TOperationHandle(); tOperationHandle.setOperationId(getHandleIdentifier().toTHandleIdentifier()); tOperationHandle.setOperationType(opType.toTOperationType()); tOperationHandle.setHasResultSet(hasResultSet); return tOperationHandle; } public TProtocolVersion getProtocolVersion() { return protocol; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((opType == null) ? 0 : opType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof OperationHandle)) { return false; } OperationHandle other = (OperationHandle) obj; if (opType != other.opType) { return false; } return true; } @Override public String toString() { return "OperationHandle [opType=" + opType + ", getHandleIdentifier()=" + getHandleIdentifier() + "]"; } }
OperationHandle
java
spring-projects__spring-boot
core/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/service/connection/ContainerConnectionDetailsFactory.java
{ "start": 2448, "end": 6396 }
class ____<C extends Container<?>, D extends ConnectionDetails> implements ConnectionDetailsFactory<ContainerConnectionSource<C>, D> { /** * Constant passed to the constructor when any connection name is accepted. */ protected static final @Nullable String ANY_CONNECTION_NAME = null; private final List<String> connectionNames; private final String[] requiredClassNames; /** * Create a new {@link ContainerConnectionDetailsFactory} instance that accepts * {@link #ANY_CONNECTION_NAME any connection name}. */ protected ContainerConnectionDetailsFactory() { this(ANY_CONNECTION_NAME); } /** * Create a new {@link ContainerConnectionDetailsFactory} instance with the given * connection name restriction. * @param connectionName the required connection name or {@link #ANY_CONNECTION_NAME} * @param requiredClassNames the names of classes that must be present */ protected ContainerConnectionDetailsFactory(@Nullable String connectionName, String... requiredClassNames) { this(Arrays.asList(connectionName), requiredClassNames); } /** * Create a new {@link ContainerConnectionDetailsFactory} instance with the given * supported connection names. * @param connectionNames the supported connection names * @param requiredClassNames the names of classes that must be present * @since 3.4.0 */ protected ContainerConnectionDetailsFactory(List<String> connectionNames, String... requiredClassNames) { Assert.notEmpty(connectionNames, "'connectionNames' must not be empty"); this.connectionNames = connectionNames; this.requiredClassNames = requiredClassNames; } @Override public final @Nullable D getConnectionDetails(ContainerConnectionSource<C> source) { if (!hasRequiredClasses()) { return null; } try { @Nullable Class<?>[] generics = resolveGenerics(); Class<?> requiredContainerType = generics[0]; Class<?> requiredConnectionDetailsType = generics[1]; Assert.state(requiredContainerType != null, "'requiredContainerType' must not be null"); Assert.state(requiredConnectionDetailsType != null, "'requiredConnectionDetailsType' must not be null"); if (sourceAccepts(source, requiredContainerType, requiredConnectionDetailsType)) { return getContainerConnectionDetails(source); } } catch (NoClassDefFoundError ex) { // Ignore } return null; } /** * Return if the given source accepts the connection. By default this method checks * each connection name. * @param source the container connection source * @param requiredContainerType the required container type * @param requiredConnectionDetailsType the required connection details type * @return if the source accepts the connection * @since 3.4.0 */ protected boolean sourceAccepts(ContainerConnectionSource<C> source, Class<?> requiredContainerType, Class<?> requiredConnectionDetailsType) { for (String requiredConnectionName : this.connectionNames) { if (source.accepts(requiredConnectionName, requiredContainerType, requiredConnectionDetailsType)) { return true; } } return false; } private boolean hasRequiredClasses() { return ObjectUtils.isEmpty(this.requiredClassNames) || Arrays.stream(this.requiredClassNames) .allMatch((requiredClassName) -> ClassUtils.isPresent(requiredClassName, null)); } private @Nullable Class<?>[] resolveGenerics() { return ResolvableType.forClass(ContainerConnectionDetailsFactory.class, getClass()).resolveGenerics(); } /** * Get the {@link ConnectionDetails} from the given {@link ContainerConnectionSource} * {@code source}. May return {@code null} if no connection can be created. Result * types should consider extending {@link ContainerConnectionDetails}. * @param source the source * @return the service connection or {@code null}. */ protected abstract @Nullable D getContainerConnectionDetails(ContainerConnectionSource<C> source); /** * Base
ContainerConnectionDetailsFactory
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
{ "start": 1396, "end": 7700 }
class ____ extends TestBase { @Mock IMethods mock; private Invocation invocation; private List<? extends ArgumentMatcher<?>> matchers; private RecordingAction recordAction; @Before public void before() { recordAction = new RecordingAction(); } @Test public void shouldKnowWhenActualArgsSizeIsDifferent1() { // given invocation = varargs("1"); matchers = asList(new Equals("1")); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(RETURN_ALWAYS_FALSE); // then assertFalse(match); } @Test public void shouldKnowWhenActualArgsSizeIsDifferent2() { // given invocation = varargs("1"); matchers = asList(new Equals("1")); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(RETURN_ALWAYS_TRUE); // then assertTrue(match); } @Test public void shouldKnowWhenActualArgsSizeIsDifferent() { // given invocation = varargs("1", "2"); matchers = asList(new Equals("1")); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(RETURN_ALWAYS_TRUE); // then assertFalse(match); } @Test public void shouldKnowWhenMatchersSizeIsDifferent() { // given invocation = varargs("1"); matchers = asList(new Equals("1"), new Equals("2")); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(RETURN_ALWAYS_TRUE); // then assertFalse(match); } @Test public void shouldKnowWhenVarargsMatch() { // given invocation = varargs("1", "2", "3"); matchers = asList(new Equals("1"), Any.ANY, new InstanceOf(String.class)); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then assertTrue(match); } @Test public void shouldNotMatchVarargsWithNoMatchers() { // given invocation = varargs("1", "2"); matchers = asList(); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then assertFalse("Should not match when matchers list is empty", match); recordAction.assertIsEmpty(); } @Test public void shouldAllowAnyMatchEntireVararg() { // given invocation = varargs("1", "2"); matchers = asList(ANY, ANY); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then assertTrue(match); } @Test public void shouldNotAllowAnyWithMixedVarargs() { // given invocation = mixedVarargs(1, "1", "2"); matchers = asList(new Equals(1)); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then assertFalse(match); } @Test public void shouldAllowAnyWithMixedVarargs() { // given invocation = mixedVarargs(1, "1", "2"); matchers = asList(new Equals(1), ANY, ANY); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then assertTrue(match); } @Test public void shouldAnyDealWithDifferentSizeOfArgs() { // given invocation = mixedVarargs(1, "1", "2"); matchers = asList(new Equals(1)); // when boolean match = getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then assertFalse(match); recordAction.assertIsEmpty(); } @Test public void shouldMatchAnyEvenIfOneOfTheArgsIsNull() { // given invocation = mixedVarargs(null, null, "2"); matchers = asList(new Equals(null), ANY, ANY); // when getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then recordAction.assertContainsExactly(new Equals(null), ANY, ANY); } @Test public void shouldMatchAnyEvenIfMatcherIsDecorated() { // given invocation = varargs("1", "2"); matchers = asList(ANY, ANY); // when getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then recordAction.assertContainsExactly(ANY, ANY); } @Test public void shouldMatchAnyEvenIfMatcherIsWrappedInHamcrestMatcher() { // given invocation = varargs("1", "2"); HamcrestArgumentMatcher<Integer> argumentMatcher = new HamcrestArgumentMatcher<>(new IntMatcher()); matchers = asList(argumentMatcher, argumentMatcher); // when getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then recordAction.assertContainsExactly(argumentMatcher, argumentMatcher); } @Test public void shouldMatchAnyThatMatchesRawVarArgType() { // given invocation = varargs("1", "2"); InstanceOf any = new InstanceOf(String[].class, "<any String[]>"); matchers = asList(any); // when getMatcherApplicationStrategyFor(invocation, matchers) .forEachMatcherAndArgument(recordAction); // then recordAction.assertContainsExactly(any); } // Helper
MatcherApplicationStrategyTest
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/test/fakedns/FakeDNSServer.java
{ "start": 7525, "end": 11907 }
class ____ extends HashMap<String, String> implements ResourceRecord { private final String domainName; private final RecordType recordType; private final RecordClass recordClass; private final int ttl; public Record(String domainName, RecordType recordType, RecordClass recordClass, int ttl) { this.domainName = domainName; this.recordType = recordType; this.recordClass = recordClass; this.ttl = ttl; } public Record ipAddress(String ipAddress) { return set(DnsAttribute.IP_ADDRESS, ipAddress); } public Record set(String name, Object value) { put(name, "" + value); return this; } @Override public String getDomainName() { return domainName; } @Override public RecordType getRecordType() { return recordType; } @Override public RecordClass getRecordClass() { return recordClass; } @Override public int getTimeToLive() { return ttl; } @Override public String get(String id) { return get((Object)id); } } public FakeDNSServer testLookup4(String ip) { return store(questionRecord -> { Set<ResourceRecord> set = new HashSet<>(); if (questionRecord.getRecordType() == RecordType.A) { set.add(a("vertx.io", 100).ipAddress(ip)); } return set; }); } public FakeDNSServer testLookup6(String ip) { return store(questionRecord -> { Set<ResourceRecord> set = new HashSet<>(); if (questionRecord.getRecordType() == RecordType.AAAA) { set.add(aaaa("vertx.io", 100).ipAddress(ip)); } return set; }); } public FakeDNSServer testLookupNonExisting() { return store(questionRecord -> null); } public FakeDNSServer testReverseLookup(final String ptr) { return store(questionRecord -> Collections.singleton(ptr(ptr, 100) .set(DnsAttribute.DOMAIN_NAME, "vertx.io"))); } public FakeDNSServer testResolveASameServer(final String ipAddress) { return store(A_store(Collections.singletonMap("vertx.io", ipAddress))); } public FakeDNSServer testLookup4CNAME(final String cname, final String ip) { return store(questionRecord -> { // use LinkedHashSet since the order of the result records has to be preserved to make sure the unit test fails Set<ResourceRecord> set = new LinkedHashSet<>(); ResourceRecordModifier rm = new ResourceRecordModifier(); set.add(cname("vertx.io", 100).set(DnsAttribute.DOMAIN_NAME, cname)); set.add(a(cname, 100).ipAddress(ip)); return set; }); } @Override public void start() throws IOException { DnsProtocolHandler handler = new DnsProtocolHandler(this, question -> { RecordStore actual = store; if (actual == null) { return Collections.emptySet(); } else { return actual.getRecords(question); } }) { @Override public void sessionCreated(IoSession session) { // Use our own codec to support AAAA testing if (session.getTransportMetadata().isConnectionless()) { session.getFilterChain().addFirst( "codec", new ProtocolCodecFilter(new TestDnsProtocolUdpCodecFactory())); } else { session.getFilterChain().addFirst( "codec", new ProtocolCodecFilter(new TestDnsProtocolTcpCodecFactory())); } } @Override public void messageReceived(IoSession session, Object message) { if (message instanceof DnsMessage) { synchronized (FakeDNSServer.this) { currentMessage.add((DnsMessage) message); } } super.messageReceived(session, message); } }; UdpTransport udpTransport = new UdpTransport(ipAddress, port); udpTransport.getAcceptor().getSessionConfig().setReuseAddress(true); TcpTransport tcpTransport = new TcpTransport(ipAddress, port); tcpTransport.getAcceptor().getSessionConfig().setReuseAddress(true); setTransports(udpTransport, tcpTransport); for (Transport transport : getTransports()) { IoAcceptor acceptor = transport.getAcceptor(); acceptor.setHandler(handler); // Start the listener acceptor.bind(); } } @Override public void stop() { for (Transport transport : getTransports()) { transport.getAcceptor().dispose(); } } public static
Record
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OidcUserRefreshedEventListener.java
{ "start": 1911, "end": 3987 }
class ____ implements ApplicationListener<OidcUserRefreshedEvent> { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository(); @Override public void onApplicationEvent(OidcUserRefreshedEvent event) { SecurityContext securityContext = this.securityContextHolderStrategy.createEmptyContext(); securityContext.setAuthentication(event.getAuthentication()); this.securityContextHolderStrategy.setContext(securityContext); RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (!(requestAttributes instanceof ServletRequestAttributes servletRequestAttributes)) { return; } HttpServletRequest request = servletRequestAttributes.getRequest(); HttpServletResponse response = servletRequestAttributes.getResponse(); this.securityContextRepository.saveContext(securityContext, request, response); } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * @param securityContextHolderStrategy the {@link SecurityContextHolderStrategy} to * use */ void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} upon * receiving an {@link OidcUserRefreshedEvent}. * @param securityContextRepository the {@link SecurityContextRepository} to use */ void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } }
OidcUserRefreshedEventListener
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnnotationCheckerTest.java
{ "start": 10066, "end": 10591 }
class ____ implements Annotation { public Class<? extends Annotation> annotationType() { return Deprecated.class; } } { new MyAnno() {}; } } """) .doTest(); } @Test public void jucImmutable() { compilationHelper .addSourceLines( "Lib.java", """ import javax.annotation.concurrent.Immutable; @Immutable
MyAnno
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/language/AbstractSingleInputTypedLanguageTest.java
{ "start": 1160, "end": 1426 }
class ____ tests willing to validate the behavior of a language that supports a result type and different * sources of input data. * * @param <T> the type of the builder used to build the language * @param <E> the type of the target expression */ public abstract
of
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/main/java/org/springframework/boot/webmvc/test/autoconfigure/MockMvcPrintOnlyOnFailureTestExecutionListener.java
{ "start": 1147, "end": 1642 }
class ____ extends AbstractTestExecutionListener { @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 100; } @Override public void afterTestMethod(TestContext testContext) throws Exception { DeferredLinesWriter writer = DeferredLinesWriter.get(testContext.getApplicationContext()); if (writer != null) { if (testContext.getTestException() != null) { writer.writeDeferredResult(); } writer.clear(); } } }
MockMvcPrintOnlyOnFailureTestExecutionListener
java
google__guice
extensions/dagger-adapter/test/com/google/inject/daggeradapter/DaggerAdapterTest.java
{ "start": 3089, "end": 3145 }
interface ____ {} @dagger.Module static
AnnotationOnSet
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/AbstractInferenceServiceParameterizedTests.java
{ "start": 1236, "end": 1320 }
class ____ testing inference services using parameterized tests. */ public abstract
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/SimpleLazyGroupUpdateTest.java
{ "start": 3816, "end": 4282 }
class ____ { @Id Long id; String name; @Basic( fetch = FetchType.LAZY ) @LazyGroup( "grp1" ) String lifeStory; @Basic( fetch = FetchType.LAZY ) @LazyGroup( "grp2" ) String reallyBigString; TestEntity() { } TestEntity(Long id, String name, String lifeStory, String reallyBigString) { this.id = id; this.name = name; this.lifeStory = lifeStory; this.reallyBigString = reallyBigString; } } // --- // public static
TestEntity
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/policies/FederationPolicyInitializationContext.java
{ "start": 1308, "end": 4412 }
class ____ { private SubClusterPolicyConfiguration federationPolicyConfiguration; private SubClusterResolver federationSubclusterResolver; private FederationStateStoreFacade federationStateStoreFacade; private SubClusterId homeSubcluster; public FederationPolicyInitializationContext() { federationPolicyConfiguration = null; federationSubclusterResolver = null; federationStateStoreFacade = null; } public FederationPolicyInitializationContext( SubClusterPolicyConfiguration policy, SubClusterResolver resolver, FederationStateStoreFacade storeFacade, SubClusterId home) { this.federationPolicyConfiguration = policy; this.federationSubclusterResolver = resolver; this.federationStateStoreFacade = storeFacade; this.homeSubcluster = home; } /** * Getter for the {@link SubClusterPolicyConfiguration}. * * @return the {@link SubClusterPolicyConfiguration} to be used for * initialization. */ public SubClusterPolicyConfiguration getSubClusterPolicyConfiguration() { return federationPolicyConfiguration; } /** * Setter for the {@link SubClusterPolicyConfiguration}. * * @param fedPolicyConfiguration the {@link SubClusterPolicyConfiguration} to * be used for initialization. */ public void setSubClusterPolicyConfiguration( SubClusterPolicyConfiguration fedPolicyConfiguration) { this.federationPolicyConfiguration = fedPolicyConfiguration; } /** * Getter for the {@link SubClusterResolver}. * * @return the {@link SubClusterResolver} to be used for initialization. */ public SubClusterResolver getFederationSubclusterResolver() { return federationSubclusterResolver; } /** * Setter for the {@link SubClusterResolver}. * * @param federationSubclusterResolver the {@link SubClusterResolver} to be * used for initialization. */ public void setFederationSubclusterResolver( SubClusterResolver federationSubclusterResolver) { this.federationSubclusterResolver = federationSubclusterResolver; } /** * Getter for the {@link FederationStateStoreFacade}. * * @return the facade. */ public FederationStateStoreFacade getFederationStateStoreFacade() { return federationStateStoreFacade; } /** * Setter for the {@link FederationStateStoreFacade}. * * @param federationStateStoreFacade the facade. */ public void setFederationStateStoreFacade( FederationStateStoreFacade federationStateStoreFacade) { this.federationStateStoreFacade = federationStateStoreFacade; } /** * Returns the current home sub-cluster. Useful for default policy behaviors. * * @return the home sub-cluster. */ public SubClusterId getHomeSubcluster() { return homeSubcluster; } /** * Sets in the context the home sub-cluster. Useful for default policy * behaviors. * * @param homeSubcluster value to set. */ public void setHomeSubcluster(SubClusterId homeSubcluster) { this.homeSubcluster = homeSubcluster; } }
FederationPolicyInitializationContext
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/CriteriaSubqueryInPredicateTest.java
{ "start": 2321, "end": 2811 }
interface ____<T> { Predicate accept(Subquery<T> sub); } @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new BasicEntity( 1, "entity_1" ) ); session.persist( new BasicEntity( 2, "entity_2" ) ); session.persist( new BasicEntity( 3, "entity_3" ) ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } }
InPredicateProducer
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/MultisetTypeInfoTest.java
{ "start": 1025, "end": 1416 }
class ____ extends TypeInformationTestBase<MultisetTypeInfo<?>> { @Override protected MultisetTypeInfo<?>[] getTestData() { return new MultisetTypeInfo<?>[] { new MultisetTypeInfo<>(BasicTypeInfo.STRING_TYPE_INFO), new MultisetTypeInfo<>(BasicTypeInfo.INT_TYPE_INFO), new MultisetTypeInfo<>(Long.class) }; } }
MultisetTypeInfoTest
java
apache__kafka
tools/src/test/java/org/apache/kafka/tools/ClientMetricsCommandTest.java
{ "start": 2043, "end": 16815 }
class ____ { private final String bootstrapServer = "localhost:9092"; private final String clientMetricsName = "cm"; @Test public void testOptionsNoActionFails() { assertInitializeInvalidOptionsExitCode(1, new String[] {"--bootstrap-server", bootstrapServer}); } @Test public void testOptionsListSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--list"}); assertTrue(opts.hasListOption()); } @Test public void testOptionsDescribeNoNameSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--describe"}); assertTrue(opts.hasDescribeOption()); } @Test public void testOptionsDescribeWithNameSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--describe", "--name", clientMetricsName}); assertTrue(opts.hasDescribeOption()); } @Test public void testOptionsDeleteNoNameFails() { assertInitializeInvalidOptionsExitCode(1, new String[] {"--bootstrap-server", bootstrapServer, "--delete"}); } @Test public void testOptionsDeleteWithNameSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--delete", "--name", clientMetricsName}); assertTrue(opts.hasDeleteOption()); } @Test public void testOptionsAlterNoNameFails() { assertInitializeInvalidOptionsExitCode(1, new String[] {"--bootstrap-server", bootstrapServer, "--alter"}); } @Test public void testOptionsAlterGenerateNameSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--alter", "--generate-name"}); assertTrue(opts.hasAlterOption()); } @Test public void testOptionsAlterWithNameSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--alter", "--name", clientMetricsName}); assertTrue(opts.hasAlterOption()); } @Test public void testOptionsAlterAllOptionsSucceeds() { ClientMetricsCommand.ClientMetricsCommandOptions opts = new ClientMetricsCommand.ClientMetricsCommandOptions( new String[] {"--bootstrap-server", bootstrapServer, "--alter", "--name", clientMetricsName, "--interval", "1000", "--match", "client_id=abc", "--metrics", "org.apache.kafka."}); assertTrue(opts.hasAlterOption()); } @Test public void testOptionsAlterInvalidInterval() { Exception exception = assertThrows(IllegalArgumentException.class, () -> new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--alter", "--name", clientMetricsName, "--interval", "abc"})); assertEquals("Invalid interval value. Enter an integer, or leave empty to reset.", exception.getMessage()); } @Test public void testAlter() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); AlterConfigsResult result = AdminClientTestUtils.alterConfigsResult(new ConfigResource(ConfigResource.Type.CLIENT_METRICS, clientMetricsName)); when(adminClient.incrementalAlterConfigs(any(), any())).thenReturn(result); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.alterClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--alter", "--name", clientMetricsName, "--metrics", "org.apache.kafka.producer.", "--interval", "5000", "--match", "client_id=CLIENT1"})); } catch (Throwable t) { fail(t); } }); assertTrue(capturedOutput.contains("Altered client metrics config for " + clientMetricsName + ".")); } @Test public void testAlterGenerateName() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); AlterConfigsResult result = AdminClientTestUtils.alterConfigsResult(new ConfigResource(ConfigResource.Type.CLIENT_METRICS, "whatever")); when(adminClient.incrementalAlterConfigs(any(), any())).thenReturn(result); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.alterClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--alter", "--generate-name", "--metrics", "org.apache.kafka.producer.", "--interval", "5000", "--match", "client_id=CLIENT1"})); } catch (Throwable t) { fail(t); } }); assertTrue(capturedOutput.contains("Altered client metrics config")); } @Test public void testAlterResetConfigs() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); AlterConfigsResult result = AdminClientTestUtils.alterConfigsResult(new ConfigResource(ConfigResource.Type.CLIENT_METRICS, clientMetricsName)); @SuppressWarnings("unchecked") final ArgumentCaptor<Map<ConfigResource, Collection<AlterConfigOp>>> configCaptor = ArgumentCaptor.forClass(Map.class); when(adminClient.incrementalAlterConfigs(configCaptor.capture(), any())).thenReturn(result); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.alterClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--alter", "--name", clientMetricsName, "--metrics", "", "--interval", "", "--match", ""})); } catch (Throwable t) { fail(t); } }); Map<ConfigResource, Collection<AlterConfigOp>> alteredConfigOps = configCaptor.getValue(); assertNotNull(alteredConfigOps, "alteredConfigOps should not be null"); assertEquals(1, alteredConfigOps.size(), "Should have exactly one ConfigResource"); assertEquals(3, alteredConfigOps.values().iterator().next().size(), "Should have exactly 3 operations"); for (Collection<AlterConfigOp> operations : alteredConfigOps.values()) { for (AlterConfigOp op : operations) { assertEquals(AlterConfigOp.OpType.DELETE, op.opType(), "Expected DELETE operation for config: " + op.configEntry().name()); } } assertTrue(capturedOutput.contains("Altered client metrics config for " + clientMetricsName + ".")); } @Test public void testDelete() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); ConfigResource cr = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, clientMetricsName); Config cfg = new Config(Set.of(new ConfigEntry("metrics", "org.apache.kafka.producer."))); DescribeConfigsResult describeResult = AdminClientTestUtils.describeConfigsResult(cr, cfg); when(adminClient.describeConfigs(any())).thenReturn(describeResult); AlterConfigsResult alterResult = AdminClientTestUtils.alterConfigsResult(cr); when(adminClient.incrementalAlterConfigs(any(), any())).thenReturn(alterResult); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.deleteClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--delete", "--name", clientMetricsName})); } catch (Throwable t) { fail(t); } }); assertTrue(capturedOutput.contains("Deleted client metrics config for " + clientMetricsName + ".")); } @Test public void testDescribe() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); ConfigResource cr = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, clientMetricsName); ListConfigResourcesResult listConfigResourcesResult = AdminClientTestUtils.listConfigResourcesResult(Map.of( ConfigResource.Type.CLIENT_METRICS, Set.of(clientMetricsName) )); when(adminClient.listConfigResources(any(), any())).thenReturn(listConfigResourcesResult); Config cfg = new Config(Set.of(new ConfigEntry("metrics", "org.apache.kafka.producer."))); DescribeConfigsResult describeResult = AdminClientTestUtils.describeConfigsResult(cr, cfg); when(adminClient.describeConfigs(any())).thenReturn(describeResult); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.describeClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--describe", "--name", clientMetricsName})); } catch (Throwable t) { fail(t); } }); assertTrue(capturedOutput.contains("Client metrics configs for " + clientMetricsName + " are:")); assertTrue(capturedOutput.contains("metrics=org.apache.kafka.producer.")); } @Test public void testDescribeNonExistentClientMetric() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); ListConfigResourcesResult listConfigResourcesResult = AdminClientTestUtils.listConfigResourcesResult(Map.of( ConfigResource.Type.CLIENT_METRICS, Set.of() )); when(adminClient.listConfigResources(any(), any())).thenReturn(listConfigResourcesResult); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.describeClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--describe", "--name", clientMetricsName})); } catch (Throwable t) { fail(t); } }); assertTrue(capturedOutput.contains("The client metric resource " + clientMetricsName + " doesn't exist and doesn't have dynamic config.")); } @Test public void testDescribeAll() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); ListConfigResourcesResult result = AdminClientTestUtils.listConfigResourcesResult(clientMetricsName); when(adminClient.listConfigResources(any(), any())).thenReturn(result); ConfigResource cr = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, clientMetricsName); Config cfg = new Config(Set.of(new ConfigEntry("metrics", "org.apache.kafka.producer."))); DescribeConfigsResult describeResult = AdminClientTestUtils.describeConfigsResult(cr, cfg); when(adminClient.describeConfigs(any())).thenReturn(describeResult); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.describeClientMetrics(new ClientMetricsCommand.ClientMetricsCommandOptions( new String[]{"--bootstrap-server", bootstrapServer, "--describe"})); } catch (Throwable t) { fail(t); } }); assertTrue(capturedOutput.contains("Client metrics configs for " + clientMetricsName + " are:")); assertTrue(capturedOutput.contains("metrics=org.apache.kafka.producer.")); } @Test public void testList() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); ListConfigResourcesResult result = AdminClientTestUtils.listConfigResourcesResult("one", "two"); when(adminClient.listConfigResources(any(), any())).thenReturn(result); String capturedOutput = ToolsTestUtils.captureStandardOut(() -> { try { service.listClientMetrics(); } catch (Throwable t) { fail(t); } }); assertEquals("one,two", String.join(",", capturedOutput.split("\n"))); } @Test public void testListFailsWithUnsupportedVersionException() { Admin adminClient = mock(Admin.class); ClientMetricsCommand.ClientMetricsService service = new ClientMetricsCommand.ClientMetricsService(adminClient); ListConfigResourcesResult result = AdminClientTestUtils.listConfigResourcesResult(Errors.UNSUPPORTED_VERSION.exception()); when(adminClient.listConfigResources(any(), any())).thenReturn(result); assertThrows(ExecutionException.class, service::listClientMetrics); } private void assertInitializeInvalidOptionsExitCode(int expected, String[] options) { Exit.setExitProcedure((exitCode, message) -> { assertEquals(expected, exitCode); throw new RuntimeException(); }); try { assertThrows(RuntimeException.class, () -> new ClientMetricsCommand.ClientMetricsCommandOptions(options)); } finally { Exit.resetExitProcedure(); } } }
ClientMetricsCommandTest
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/scenario/RecommendedSettingsProvider.java
{ "start": 271, "end": 396 }
class ____ standardize client configurations across tests and provides optimized settings for fast reconnection. */ public
helps
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/Html.java
{ "start": 942, "end": 1049 }
class ____ utility functions for HTML */ @InterfaceAudience.LimitedPrivate({"YARN", "MapReduce"}) public
holds
java
apache__flink
flink-metrics/flink-metrics-otel/src/main/java/org/apache/flink/metrics/otel/OpenTelemetryMetricAdapter.java
{ "start": 2146, "end": 2314 }
class ____ translates from Flink metrics to Otel metrics which can exported with the * standard Otel {@link io.opentelemetry.sdk.metrics.export.MetricExporter}s. */
which
java
apache__camel
test-infra/camel-test-infra-tensorflow-serving/src/test/java/org/apache/camel/test/infra/tensorflow/serving/services/TensorFlowServingServiceFactory.java
{ "start": 960, "end": 1481 }
class ____ { private TensorFlowServingServiceFactory() { } public static SimpleTestServiceBuilder<TensorFlowServingService> builder() { return new SimpleTestServiceBuilder<>("tensorflow-serving"); } public static TensorFlowServingService createService() { return builder() .addLocalMapping(TensorFlowServingLocalContainerService::new) .addRemoteMapping(TensorFlowServingRemoteService::new) .build(); } }
TensorFlowServingServiceFactory
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/metrics/stats/Max.java
{ "start": 1008, "end": 1629 }
class ____ extends SampledStat { public Max() { super(Double.NEGATIVE_INFINITY); } @Override protected void update(Sample sample, MetricConfig config, double value, long now) { sample.value = Math.max(sample.value, value); } @Override public double combine(List<Sample> samples, MetricConfig config, long now) { double max = Double.NEGATIVE_INFINITY; long count = 0; for (Sample sample : samples) { max = Math.max(max, sample.value); count += sample.eventCount; } return count == 0 ? Double.NaN : max; } }
Max
java
micronaut-projects__micronaut-core
router/src/main/java/io/micronaut/web/router/exceptions/UnsatisfiedCookieValueRouteException.java
{ "start": 901, "end": 1434 }
class ____ extends UnsatisfiedRouteException { private final String name; /** * @param name The name of the cookie * @param argument The {@link Argument} */ public UnsatisfiedCookieValueRouteException(String name, Argument<?> argument) { super("Required CookieValue [" + name + "] not specified", argument); this.name = name; } /** * @return The name of the cookie */ public String getCookieName() { return name; } }
UnsatisfiedCookieValueRouteException
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beancreationeventlistener/A.java
{ "start": 118, "end": 152 }
class ____ implements AInterface { }
A
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractIterableAssert.java
{ "start": 132824, "end": 177033 }
class ____ 'first' and 'last' String properties * assertThat(employees).filteredOn("name.first", in("Yoda", "Luke")) * .containsOnly(yoda, luke); * * // 'notIn' filter is statically imported from Assertions.notIn * assertThat(employees).filteredOn("name.first", notIn("Yoda", "Luke")) * .containsOnly(obiwan);</code></pre> * * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable * elements. * <p> * Note that combining filter operators is not supported, thus the following code is not correct: * <pre><code class='java'> // Combining filter operators like not(in(800)) is NOT supported * // -&gt; throws UnsupportedOperationException * assertThat(employees).filteredOn("age", not(in(800))) * .contains(luke);</code></pre> * <p> * You can chain filters: * <pre><code class='java'> // fellowshipOfTheRing is a list of TolkienCharacter having race and name fields * // 'not' filter is statically imported from Assertions.not * * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man") * .filteredOn("name", not("Boromir")) * .containsOnly(aragorn);</code></pre> * * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}. * * @param propertyOrFieldName the name of the property or field to read * @param filterOperator the filter operator to apply * @return a new assertion object with the filtered iterable under test * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty. */ @CheckReturnValue public SELF filteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator) { checkNotNull(filterOperator); Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual).with(propertyOrFieldName); filterOperator.applyOn(filter); return newAbstractIterableAssert(filter.get()).withAssertionState(myself); } /** * Filters the iterable under test keeping only elements matching the given {@link Condition}. * <p> * If you prefer {@link Predicate} over {@link Condition}, use {@link #filteredOn(Predicate)}. * <p> * Example: check old employees whose age &gt; 100: * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800); * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); * Employee noname = new Employee(4L, null, 50); * * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname); * * // old employee condition, "old employees" describes the condition in error message * // you just have to implement 'matches' method * Condition&lt;Employee&gt; oldEmployees = new Condition&lt;Employee&gt;("old employees") { * {@literal @}Override * public boolean matches(Employee employee) { * return employee.getAge() &gt; 100; * } * }; * } * assertThat(employees).filteredOn(oldEmployees) * .containsOnly(yoda, obiwan);</code></pre> * * You can combine {@link Condition} with condition operator like {@link Not}: * <pre><code class='java'> // 'not' filter is statically imported from Assertions.not * assertThat(employees).filteredOn(not(oldEmployees)) * .contains(luke, noname);</code></pre> * * @param condition the filter condition / predicate * @return a new assertion object with the filtered iterable under test * @throws IllegalArgumentException if the given condition is {@code null}. */ @CheckReturnValue public SELF filteredOn(Condition<? super ELEMENT> condition) { Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual); Iterable<? extends ELEMENT> filteredIterable = filter.being(condition).get(); return newAbstractIterableAssert(filteredIterable).withAssertionState(myself); } /** * Filters the iterable under test keeping only elements for which the result of the {@code function} is equal to {@code expectedValue}. * <p> * It allows to filter elements more safely than by using {@link #filteredOn(String, Object)} as it doesn't utilize introspection. * <p> * As an example, let's check all employees 800 years old (yes, special employees): * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800); * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); * Employee noname = new Employee(4L, null, 50); * * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname); * * assertThat(employees).filteredOn(Employee::getAge, 800) * .containsOnly(yoda, obiwan); * * assertThat(employees).filteredOn(e -&gt; e.getName(), null) * .containsOnly(noname);</code></pre> * * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}. * * @param <T> result type of the filter function * @param function the filter function * @param expectedValue the expected value of the filter function * @return a new assertion object with the filtered iterable under test * @throws IllegalArgumentException if the given function is {@code null}. * @since 3.17.0 */ @CheckReturnValue public <T> SELF filteredOn(Function<? super ELEMENT, T> function, T expectedValue) { checkArgument(function != null, "The filter function should not be null"); // call internalFilteredOn to avoid double proxying in soft assertions return internalFilteredOn(element -> java.util.Objects.equals(function.apply(element), expectedValue)); } /** * Filters the iterable under test keeping only elements matching the given assertions specified with a {@link Consumer}. * <p> * Example: check young hobbits whose age &lt; 34: * * <pre><code class='java'> TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); * TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT); * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); * * List&lt;TolkienCharacter&gt; hobbits = list(frodo, sam, merry, pippin); * * assertThat(hobbits).filteredOnAssertions(hobbit -&gt; assertThat(hobbit.age).isLessThan(34)) * .containsOnly(frodo, pippin);</code></pre> * * @param elementAssertions containing AssertJ assertions to filter on * @return a new assertion object with the filtered iterable under test * @throws IllegalArgumentException if the given {@link Consumer} is {@code null}. * @since 3.11.0 */ public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions) { return internalFilteredOnAssertions(elementAssertions); } /** * Filters the iterable under test keeping only elements matching the given assertions specified with a {@link ThrowingConsumer}. * <p> * This is the same assertion as {@link #filteredOnAssertions(Consumer)} but the given consumer can throw checked exceptions.<br> * More precisely, {@link RuntimeException} and {@link AssertionError} are rethrown as they are and {@link Throwable} wrapped in a {@link RuntimeException}. * <p> * Example: check young hobbits whose age &lt; 34: * * <pre><code class='java'> TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); * TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT); * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); * * List&lt;TolkienCharacter&gt; hobbits = list(frodo, sam, merry, pippin); * * // the code would compile even if getAge() threw a checked exception * assertThat(hobbits).filteredOnAssertions(hobbit -&gt; assertThat(hobbit.getAge()).isLessThan(34)) * .containsOnly(frodo, pippin);</code></pre> * * @param elementAssertions containing AssertJ assertions to filter on * @return a new assertion object with the filtered iterable under test * @throws IllegalArgumentException if the given {@link ThrowingConsumer} is {@code null}. * @since 3.21.0 */ public SELF filteredOnAssertions(ThrowingConsumer<? super ELEMENT> elementAssertions) { return internalFilteredOnAssertions(elementAssertions); } private SELF internalFilteredOnAssertions(Consumer<? super ELEMENT> elementAssertions) { checkArgument(elementAssertions != null, "The element assertions should not be null"); List<? extends ELEMENT> filteredIterable = stream(actual.spliterator(), false).filter(byPassingAssertions(elementAssertions)) .collect(toList()); return newAbstractIterableAssert(filteredIterable).withAssertionState(myself); } // navigable assertions /** * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test. * <p> * By default, available assertions after {@code first()} are {@code Object} assertions, it is possible though to * get more specific assertions with {@link #first(InstanceOfAssertFactory)}. * <p> * Example: * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin); * * // assertion succeeds, only Object assertions are available after first() * assertThat(hobbits).first() * .isEqualTo(frodo); * * // assertion fails * assertThat(hobbits).first() * .isEqualTo(pippin);</code></pre> * * @return the assertion on the first element * @throws AssertionError if the actual {@link Iterable} is empty. * @since 2.5.0 / 3.5.0 * @see #first(InstanceOfAssertFactory) */ @CheckReturnValue public ELEMENT_ASSERT first() { return internalFirst(); } /** * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test. * <p> * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the * assertions narrowed to the factory type. * <p> * Example: use of {@code String} assertions after {@code first(as(InstanceOfAssertFactories.STRING)} * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin"); * * // assertion succeeds * assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING)) * .startsWith("Fro") * .endsWith("do"); * // assertion fails * assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING)) * .startsWith("Pip"); * // assertion fails because of wrong factory type * assertThat(hobbits).first(as(InstanceOfAssertFactories.INTEGER)) * .isZero();</code></pre> * * @param <ASSERT> the type of the resulting {@code Assert} * @param assertFactory the factory which verifies the type and creates the new {@code Assert} * @return a new narrowed {@link Assert} instance for assertions chaining on the first element * @throws AssertionError if the actual {@link Iterable} is empty. * @throws NullPointerException if the given factory is {@code null} * @since 3.14.0 */ @CheckReturnValue public <ASSERT extends AbstractAssert<?, ?>> ASSERT first(InstanceOfAssertFactory<?, ASSERT> assertFactory) { return internalFirst().asInstanceOf(assertFactory); } private ELEMENT_ASSERT internalFirst() { isNotEmpty(); return toAssert(actual.iterator().next(), navigationDescription("check first element")); } /** * Navigate and allow to perform assertions on the last element of the {@link Iterable} under test. * <p> * By default, available assertions after {@code last()} are {@code Object} assertions, it is possible though to * get more specific assertions with {@link #last(InstanceOfAssertFactory)}. * <p> * Example: default {@code Object} assertions * <pre><code class='java'> Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin); * * // assertion succeeds, only Object assertions are available after last() * assertThat(hobbits).last() * .isEqualTo(pippin); * * // assertion fails * assertThat(hobbits).last() * .isEqualTo(frodo);</code></pre> * * @return the assertion on the last element * @throws AssertionError if the actual {@link Iterable} is empty. * @since 2.5.0 / 3.5.0 * @see #last(InstanceOfAssertFactory) */ @CheckReturnValue public ELEMENT_ASSERT last() { return internalLast(); } /** * Navigate and allow to perform assertions on the last element of the {@link Iterable} under test. * <p> * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the * assertions narrowed to the factory type. * <p> * Example: use of {@code String} assertions after {@code last(as(InstanceOfAssertFactories.STRING)} * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin"); * * // assertion succeeds * assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING)) * .startsWith("Pip") * .endsWith("pin"); * // assertion fails * assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING)) * .startsWith("Fro"); * // assertion fails because of wrong factory type * assertThat(hobbits).last(as(InstanceOfAssertFactories.INTEGER)) * .isZero();</code></pre> * * @param <ASSERT> the type of the resulting {@code Assert} * @param assertFactory the factory which verifies the type and creates the new {@code Assert} * @return a new narrowed {@link Assert} instance for assertions chaining on the last element * @throws AssertionError if the actual {@link Iterable} is empty. * @throws NullPointerException if the given factory is {@code null} * @since 3.14.0 */ @CheckReturnValue public <ASSERT extends AbstractAssert<?, ?>> ASSERT last(InstanceOfAssertFactory<?, ASSERT> assertFactory) { return internalLast().asInstanceOf(assertFactory); } private ELEMENT_ASSERT internalLast() { isNotEmpty(); return toAssert(lastElement(), navigationDescription("check last element")); } @SuppressWarnings("unchecked") private ELEMENT lastElement() { if (actual instanceof @SuppressWarnings("rawtypes") List list) { return (ELEMENT) list.get(list.size() - 1); } Iterator<? extends ELEMENT> actualIterator = actual.iterator(); ELEMENT last = actualIterator.next(); while (actualIterator.hasNext()) { last = actualIterator.next(); } return last; } /** * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test. * <p> * By default, available assertions after {@code element(index)} are {@code Object} assertions, it is possible though to * get more specific assertions with {@link #element(int, InstanceOfAssertFactory)}. * <p> * Example: default {@code Object} assertions * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin); * * // assertion succeeds, only Object assertions are available after element(index) * assertThat(hobbits).element(1) * .isEqualTo(sam); * * // assertion fails * assertThat(hobbits).element(1) * .isEqualTo(pippin);</code></pre> * * @param index the element's index * @return the assertion on the given element * @throws AssertionError if the given index is out of bound. * @since 2.5.0 / 3.5.0 * @see #element(int, InstanceOfAssertFactory) */ @CheckReturnValue public ELEMENT_ASSERT element(int index) { return internalElement(index); } /** * Allow to perform assertions on the elements corresponding to the given indices * (the iterable {@link Iterable} under test is changed to an iterable with the selected elements). * <p> * Example: * <pre><code class='java'> Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin); * * // assertion succeeds * assertThat(hobbits).elements(1, 2) * .hasSize(2) * .containsExactly(sam, pippin); * * // assertion fails * assertThat(hobbits).element(1, 2) * .containsExactly(frodo, pippin);</code></pre> * <p> * * @param indices the elements indices * @return the assertion on the given elements * @throws IllegalArgumentException if indices array is null or empty * @throws AssertionError if one of the given indices is out of bound or if the actual is empty * @since 3.20 */ @CheckReturnValue public SELF elements(int... indices) { isNotEmpty(); assertIndicesIsNotNull(indices); assertIndicesIsNotEmpty(indices); List<ELEMENT> indexedActual = newArrayList(actual); List<ELEMENT> filteredIterable = Arrays.stream(indices) .peek(index -> checkIndexValidity(index, indexedActual)) .mapToObj(indexedActual::get) .collect(toList()); // For soft assertions/assumptions, this must return a proxied iterable assert but, we can't put "elements" in // SoftProxies.METHODS_CHANGING_THE_OBJECT_UNDER_TEST because these methods are not proxied. // We want to proxy elements(int... indices) to capture isNotEmpty and checkIndexValidity assertion errors. // The solution is to introduce newAbstractIterableAssertForProxy which is going to be proxied as newAbstractIterableAssert // was added to SoftProxies.METHODS_CHANGING_THE_OBJECT_UNDER_TEST list and SoftProxies.methodsChangingTheObjectUnderTestNamed // will select newAbstractIterableAssertForProxy to be proxied. return newAbstractIterableAssertForProxy(filteredIterable); } // This method is protected in order to be proxied for SoftAssertions / Assumptions. protected SELF newAbstractIterableAssertForProxy(List<ELEMENT> filteredIterable) { return newAbstractIterableAssert(filteredIterable).withAssertionState(myself); } private static void assertIndicesIsNotNull(int[] indices) { if (indices == null) throw new IllegalArgumentException("indices must not be null"); } private static void assertIndicesIsNotEmpty(int[] indices) { if (indices.length == 0) throw new IllegalArgumentException("indices must not be empty"); } private void checkIndexValidity(int index, List<ELEMENT> indexedActual) { assertThat(indexedActual).describedAs("check actual size is enough to get element[" + index + "]") .hasSizeGreaterThan(index); } /** * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test. * <p> * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the * assertions narrowed to the factory type. * <p> * Example: use of {@code String} assertions after {@code element(index, as(InstanceOfAssertFactories.STRING)} * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin"); * * // assertion succeeds * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING)) * .startsWith("Sa") * .endsWith("am"); * // assertion fails * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING)) * .startsWith("Fro"); * // assertion fails because of wrong factory type * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.INTEGER)) * .isZero();</code></pre> * * @param <ASSERT> the type of the resulting {@code Assert} * @param index the element's index * @param assertFactory the factory which verifies the type and creates the new {@code Assert} * @return a new narrowed {@link Assert} instance for assertions chaining on the element at the given index * @throws AssertionError if the given index is out of bound. * @throws NullPointerException if the given factory is {@code null} * @since 3.14.0 */ @CheckReturnValue public <ASSERT extends AbstractAssert<?, ?>> ASSERT element(int index, InstanceOfAssertFactory<?, ASSERT> assertFactory) { return internalElement(index).asInstanceOf(assertFactory); } @SuppressWarnings("unchecked") private ELEMENT_ASSERT internalElement(int index) { isNotEmpty(); assertThat(index).describedAs(navigationDescription("check index validity")) .isBetween(0, IterableUtil.sizeOf(actual) - 1); ELEMENT elementAtIndex; if (actual instanceof @SuppressWarnings("rawtypes") List list) { elementAtIndex = (ELEMENT) list.get(index); } else { Iterator<? extends ELEMENT> actualIterator = actual.iterator(); for (int i = 0; i < index; i++) { actualIterator.next(); } elementAtIndex = actualIterator.next(); } return toAssert(elementAtIndex, navigationDescription("element at index " + index)); } /** * Verifies that the {@link Iterable} under test contains a single element and allows to perform assertions on that element. * <p> * This is a shorthand for <code>hasSize(1).first()</code>. * <p> * By default, available assertions after {@code singleElement()} are {@code Object} assertions, it is possible though to * get more specific assertions with {@link #singleElement(InstanceOfAssertFactory)}. * <p> * Example: * <pre><code class='java'> List&lt;String&gt; babySimpsons = list("Maggie"); * * // assertion succeeds, only Object assertions are available after singleElement() * assertThat(babySimpsons).singleElement() * .isEqualTo("Maggie"); * * // assertion fails * assertThat(babySimpsons).singleElement() * .isEqualTo("Homer"); * * // assertion fails because list contains no elements * assertThat(emptyList()).singleElement(); * * * // assertion fails because list contains more than one element * List&lt;String&gt; simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie"); * assertThat(simpsons).singleElement();</code></pre> * * @return the assertion on the first element * @throws AssertionError if the actual {@link Iterable} does not contain exactly one element. * @since 3.17.0 * @see #singleElement(InstanceOfAssertFactory) */ @CheckReturnValue public ELEMENT_ASSERT singleElement() { return internalSingleElement(); } /** * Verifies that the {@link Iterable} under test contains a single element and allows to perform assertions on that element, * the assertions are strongly typed according to the given {@link AssertFactory} parameter. * <p> * This is a shorthand for <code>hasSize(1).first(assertFactory)</code>. * <p> * Example: use of {@code String} assertions after {@code singleElement(as(STRING))} * <pre><code class='java'> import static org.assertj.core.api.InstanceOfAssertFactories.STRING; * import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER; * import static org.assertj.core.api.Assertions.as; // syntactic sugar * * List&lt;String&gt; babySimpsons = list("Maggie"); * * // assertion succeeds * assertThat(babySimpsons).singleElement(as(STRING)) * .startsWith("Mag"); * * // assertion fails * assertThat(babySimpsons).singleElement(as(STRING)) * .startsWith("Lis"); * * // assertion fails because of wrong factory type * assertThat(babySimpsons).singleElement(as(INTEGER)) * .isZero(); * * // assertion fails because list contains no elements * assertThat(emptyList()).singleElement(as(STRING)); * * // assertion fails because list contains more than one element * List&lt;String&gt; simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie"); * assertThat(simpsons).singleElement(as(STRING));</code></pre> * * @param <ASSERT> the type of the resulting {@code Assert} * @param assertFactory the factory which verifies the type and creates the new {@code Assert} * @return a new narrowed {@link Assert} instance for assertions chaining on the single element * @throws AssertionError if the actual {@link Iterable} does not contain exactly one element. * @throws NullPointerException if the given factory is {@code null}. * @since 3.17.0 */ @CheckReturnValue public <ASSERT extends AbstractAssert<?, ?>> ASSERT singleElement(InstanceOfAssertFactory<?, ASSERT> assertFactory) { return internalSingleElement().asInstanceOf(assertFactory); } private ELEMENT_ASSERT internalSingleElement() { iterables.assertHasSize(info, actual, 1); return toAssert(actual.iterator().next(), navigationDescription("check single element")); } /** * This method is used in navigating assertions like {@link #first()}, {@link #last()} and {@link #element(int)} to build the * assertion for the given element navigated to. * <p> * Typical implementation is returning an {@link ObjectAssert} but it is possible to return a more specialized assertions * should you know what type of elements the iterables contain. * * @param value the element value * @param description describes the element, ex: "check first element" for {@link #first()}, used in assertion description. * @return the assertion for the given element */ protected abstract ELEMENT_ASSERT toAssert(ELEMENT value, String description); protected String navigationDescription(String propertyName) { String text = descriptionText(); if (Strings.isNullOrEmpty(text)) { text = removeAssert(this.getClass().getSimpleName()); } return text + " " + propertyName; } private static String removeAssert(String text) { return text.endsWith(ASSERT) ? text.substring(0, text.length() - ASSERT.length()) : text; } /** * Filters the iterable under test keeping only elements matching the given {@link Predicate}. * <p> * Example: check old employees whose age &gt; 100: * * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800); * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); * * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan); * * assertThat(employees).filteredOn(employee -&gt; employee.getAge() &gt; 100) * .containsOnly(yoda, obiwan);</code></pre> * * @param predicate the filter predicate * @return a new assertion object with the filtered iterable under test * @throws IllegalArgumentException if the given predicate is {@code null}. */ public SELF filteredOn(Predicate<? super ELEMENT> predicate) { return internalFilteredOn(predicate); } /** * {@inheritDoc} */ @Override public SELF allMatch(Predicate<? super ELEMENT> predicate) { iterables.assertAllMatch(info, actual, predicate, PredicateDescription.GIVEN); return myself; } /** * {@inheritDoc} */ @Override public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) { iterables.assertAllMatch(info, actual, predicate, new PredicateDescription(predicateDescription)); return myself; } /** * {@inheritDoc} */ @Override public SELF allSatisfy(Consumer<? super ELEMENT> requirements) { return internalAllSatisfy(requirements); } /** * {@inheritDoc} */ @Override public SELF allSatisfy(ThrowingConsumer<? super ELEMENT> requirements) { return internalAllSatisfy(requirements); } private SELF internalAllSatisfy(Consumer<? super ELEMENT> requirements) { iterables.assertAllSatisfy(info, actual, requirements); return myself; } /** * {@inheritDoc} */ @Override public SELF anyMatch(Predicate<? super ELEMENT> predicate) { iterables.assertAnyMatch(info, actual, predicate, PredicateDescription.GIVEN); return myself; } /** * {@inheritDoc} */ @Override public SELF anyMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) { iterables.assertAnyMatch(info, actual, predicate, new PredicateDescription(predicateDescription)); return myself; } /** * Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ... * all satisfy the given {@code zipRequirements}. * <p> * This assertion assumes that actual and other have the same size but, they can contain different type of elements * making it handy to compare objects converted to another type, for example Domain and View/DTO objects. * <p> * Example: * <pre><code class='java'> List&lt;Address&gt; addressModels = findGoodRestaurants(); * List&lt;AddressView&gt; addressViews = convertToView(addressModels); * * // compare addressViews and addressModels respective paired elements. * assertThat(addressViews).zipSatisfy(addressModels, (AddressView view, Address model) -&gt; { * assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine()); * assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase()); * });</code></pre> * * @param <OTHER_ELEMENT> the type of the other iterable elements. * @param other the iterable to zip actual with. * @param zipRequirements the given requirements that each pair must satisfy. * @return {@code this} assertion object. * @throws NullPointerException if the given zipRequirements {@link BiConsumer} is {@code null}. * @throws NullPointerException if the other iterable to zip actual with is {@code null}. * @throws AssertionError if the {@code Iterable} under test is {@code null}. * @throws AssertionError if actual and other don't have the same size. * @throws AssertionError if one or more pairs don't satisfy the given requirements. * @since 3.9.0 */ public <OTHER_ELEMENT> SELF zipSatisfy(Iterable<OTHER_ELEMENT> other, BiConsumer<? super ELEMENT, OTHER_ELEMENT> zipRequirements) { iterables.assertZipSatisfy(info, actual, other, zipRequirements); return myself; } /** * {@inheritDoc} */ @Override public SELF anySatisfy(Consumer<? super ELEMENT> requirements) { return internalAnySatisfy(requirements); } /** * {@inheritDoc} */ @Override public SELF anySatisfy(ThrowingConsumer<? super ELEMENT> requirements) { return internalAnySatisfy(requirements); } private SELF internalAnySatisfy(Consumer<? super ELEMENT> requirements) { iterables.assertAnySatisfy(info, actual, requirements); return myself; } /** * {@inheritDoc} */ @Override public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions) { return internalNoneSatisfy(restrictions); } /** * {@inheritDoc} */ @Override public SELF noneSatisfy(ThrowingConsumer<? super ELEMENT> restrictions) { return internalNoneSatisfy(restrictions); } private SELF internalNoneSatisfy(Consumer<? super ELEMENT> restrictions) { iterables.assertNoneSatisfy(info, actual, restrictions); return myself; } /** * {@inheritDoc} */ @Override @SafeVarargs public final SELF satisfiesExactly(Consumer<? super ELEMENT>... requirements) { return satisfiesExactlyForProxy(requirements); } /** * {@inheritDoc} */ @Override @SafeVarargs public final SELF satisfiesExactly(ThrowingConsumer<? super ELEMENT>... requirements) { return satisfiesExactlyForProxy(requirements); } // This method is protected in order to be proxied for SoftAssertions / Assumptions. // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs // in order to avoid compiler warning in user code protected SELF satisfiesExactlyForProxy(Consumer<? super ELEMENT>[] requirements) { iterables.assertSatisfiesExactly(info, actual, requirements); return myself; } /** * {@inheritDoc} */ @Override @SafeVarargs public final SELF satisfiesExactlyInAnyOrder(Consumer<? super ELEMENT>... requirements) { return satisfiesExactlyInAnyOrderForProxy(requirements); } /** * {@inheritDoc} */ @Override @SafeVarargs public final SELF satisfiesExactlyInAnyOrder(ThrowingConsumer<? super ELEMENT>... requirements) { return satisfiesExactlyInAnyOrderForProxy(requirements); } // This method is protected in order to be proxied for SoftAssertions / Assumptions. // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs // in order to avoid compiler warning in user code protected SELF satisfiesExactlyInAnyOrderForProxy(Consumer<? super ELEMENT>[] requirements) { iterables.assertSatisfiesExactlyInAnyOrder(info, actual, requirements); return myself; } /** * {@inheritDoc} */ @Override public SELF satisfiesOnlyOnce(Consumer<? super ELEMENT> requirements) { return satisfiesOnlyOnceForProxy(requirements); } /** * {@inheritDoc} */ @Override public SELF satisfiesOnlyOnce(ThrowingConsumer<? super ELEMENT> requirements) { return satisfiesOnlyOnceForProxy(requirements); } // This method is protected in order to be proxied for SoftAssertions / Assumptions. // The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs // in order to avoid compiler warning in user code protected SELF satisfiesOnlyOnceForProxy(Consumer<? super ELEMENT> requirements) { iterables.assertSatisfiesOnlyOnce(info, actual, requirements); return myself; } // override methods to avoid compilation error when chaining an AbstractAssert method with a AbstractIterableAssert // one on raw types. @Override @CheckReturnValue public SELF as(String description, Object... args) { return super.as(description, args); } @Override @CheckReturnValue public SELF as(Description description) { return super.as(description); } @Override @CheckReturnValue public SELF describedAs(Description description) { return super.describedAs(description); } @Override @CheckReturnValue public SELF describedAs(String description, Object... args) { return super.describedAs(description, args); } @Override public SELF doesNotHave(Condition<? super ACTUAL> condition) { return super.doesNotHave(condition); } @Override public SELF doesNotHaveSameClassAs(Object other) { return super.doesNotHaveSameClassAs(other); } @Override public SELF has(Condition<? super ACTUAL> condition) { return super.has(condition); } @Override public SELF hasSameClassAs(Object other) { return super.hasSameClassAs(other); } @Override public SELF hasToString(String expectedToString) { return super.hasToString(expectedToString); } @Override public SELF is(Condition<? super ACTUAL> condition) { return super.is(condition); } @Override public SELF isEqualTo(Object expected) { return super.isEqualTo(expected); } @Override public SELF isExactlyInstanceOf(Class<?> type) { return super.isExactlyInstanceOf(type); } @Override public SELF isIn(Iterable<?> values) { return super.isIn(values); } @Override public SELF isIn(Object... values) { return super.isIn(values); } @Override public SELF isInstanceOf(Class<?> type) { return super.isInstanceOf(type); } @Override public SELF isInstanceOfAny(Class<?>... types) { return super.isInstanceOfAny(types); } @Override public SELF isNot(Condition<? super ACTUAL> condition) { return super.isNot(condition); } @Override public SELF isNotEqualTo(Object other) { return super.isNotEqualTo(other); } @Override public SELF isNotExactlyInstanceOf(Class<?> type) { return super.isNotExactlyInstanceOf(type); } @Override public SELF isNotIn(Iterable<?> values) { return super.isNotIn(values); } @Override public SELF isNotIn(Object... values) { return super.isNotIn(values); } @Override public SELF isNotInstanceOf(Class<?> type) { return super.isNotInstanceOf(type); } @Override public SELF isNotInstanceOfAny(Class<?>... types) { return super.isNotInstanceOfAny(types); } @Override public SELF isNotOfAnyClassIn(Class<?>... types) { return super.isNotOfAnyClassIn(types); } @Override public SELF isNotNull() { return super.isNotNull(); } @Override public SELF isNotSameAs(Object other) { return super.isNotSameAs(other); } @Override public SELF isOfAnyClassIn(Class<?>... types) { return super.isOfAnyClassIn(types); } @Override public SELF isSameAs(Object expected) { return super.isSameAs(expected); } @Override public SELF noneMatch(Predicate<? super ELEMENT> predicate) { iterables.assertNoneMatch(info, actual, predicate, PredicateDescription.GIVEN); return myself; } @Override public SELF noneMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) { iterables.assertNoneMatch(info, actual, predicate, new PredicateDescription(predicateDescription)); return myself; } @Override @CheckReturnValue public SELF overridingErrorMessage(String newErrorMessage, Object... args) { return super.overridingErrorMessage(newErrorMessage, args); } @Override @CheckReturnValue public SELF usingDefaultComparator() { return super.usingDefaultComparator(); } @Override @CheckReturnValue public SELF usingComparator(Comparator<? super ACTUAL> customComparator) { return usingComparator(customComparator, null); } @Override @CheckReturnValue public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) { return super.usingComparator(customComparator, customComparatorDescription); } @Override @CheckReturnValue public SELF withFailMessage(String newErrorMessage, Object... args) { return super.withFailMessage(newErrorMessage, args); } @Override @CheckReturnValue public SELF withThreadDumpOnError() { return super.withThreadDumpOnError(); } /** * Returns an {@code Assert} object that allows performing assertions on the size of the {@link Iterable} under test. * <p> * Once this method is called, the object under test is no longer the {@link Iterable} but its size, * to perform assertions on the {@link Iterable}, call {@link AbstractIterableSizeAssert#returnToIterable()}. * <p> * Example: * <pre><code class='java'> Iterable&lt;Ring&gt; elvesRings = newArrayList(vilya, nenya, narya); * * // assertion will pass: * assertThat(elvesRings).size().isGreaterThan(1) * .isLessThanOrEqualTo(3) * .returnToIterable().contains(narya) * .doesNotContain(oneRing); * * // assertion will fail: * assertThat(elvesRings).size().isGreaterThan(3);</code></pre> * * @return AbstractIterableSizeAssert built with the {@code Iterable}'s size. * @throws NullPointerException if the given {@code Iterable} is {@code null}. */ @SuppressWarnings({ "rawtypes" }) @CheckReturnValue public AbstractIterableSizeAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> size() { requireNonNull(actual, "Can not perform assertions on the size of a null iterable."); return new IterableSizeAssert(this, IterableUtil.sizeOf(actual)); } // lazy init TypeComparators protected TypeComparators getComparatorsByType() { if (comparatorsByType == null) comparatorsByType = defaultTypeComparators(); return comparatorsByType; } // lazy init TypeComparators protected TypeComparators getComparatorsForElementPropertyOrFieldTypes() { if (comparatorsForElementPropertyOrFieldTypes == null) comparatorsForElementPropertyOrFieldTypes = defaultTypeComparators(); return comparatorsForElementPropertyOrFieldTypes; } /** * This method is needed to build a new concrete instance of AbstractIterableAssert after a filtering operation is executed. * <p> * If you create your own subclass of AbstractIterableAssert, simply returns an instance of it in this method. * * @param iterable the iterable used to build the concrete instance of AbstractIterableAssert * @return concrete instance of AbstractIterableAssert */ protected abstract SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable); @SuppressWarnings({ "rawtypes" }) @Override SELF withAssertionState(AbstractAssert assertInstance) { if (assertInstance instanceof AbstractIterableAssert iterableAssert) { return (SELF) super.withAssertionState(assertInstance).withIterables(iterableAssert.iterables) .withTypeComparators(iterableAssert.comparatorsByType) .withComparatorsForElementPropertyOrFieldNames(iterableAssert.comparatorsForElementPropertyOrFieldNames) .withComparatorsForElementPropertyOrFieldTypes(iterableAssert.comparatorsForElementPropertyOrFieldTypes); } // we can go from ObjectArrayAssert -> IterableAssert when using extracting on an object array if (assertInstance instanceof AbstractObjectArrayAssert objectArrayAssert) { return (SELF) super.withAssertionState(assertInstance).withIterables(objectArrayAssert.iterables) .withTypeComparators(objectArrayAssert.comparatorsByType) .withComparatorsForElementPropertyOrFieldNames(objectArrayAssert.comparatorsForElementPropertyOrFieldNames) .withComparatorsForElementPropertyOrFieldTypes(objectArrayAssert.comparatorsForElementPropertyOrFieldTypes); } return super.withAssertionState(assertInstance); } SELF withIterables(Iterables iterables) { this.iterables = iterables; return myself; } SELF withTypeComparators(TypeComparators comparatorsByType) { this.comparatorsByType = comparatorsByType; return myself; } SELF withComparatorsForElementPropertyOrFieldNames(Map<String, Comparator<?>> comparatorsForElementPropertyOrFieldNames) { this.comparatorsForElementPropertyOrFieldNames = comparatorsForElementPropertyOrFieldNames; return myself; } SELF withComparatorsForElementPropertyOrFieldTypes(TypeComparators comparatorsForElementPropertyOrFieldTypes) { this.comparatorsForElementPropertyOrFieldTypes = comparatorsForElementPropertyOrFieldTypes; return myself; } private SELF internalFilteredOn(Predicate<? super ELEMENT> predicate) { checkArgument(predicate != null, "The filter predicate should not be null"); List<? extends ELEMENT> filteredIterable = stream(actual.spliterator(), false).filter(predicate).collect(toList()); return newAbstractIterableAssert(filteredIterable).withAssertionState(myself); } }
with
java
spring-projects__spring-boot
module/spring-boot-data-redis/src/main/java/org/springframework/boot/data/redis/autoconfigure/JedisClientConfigurationBuilderCustomizer.java
{ "start": 897, "end": 1177 }
interface ____ can be implemented by beans wishing to customize the * {@link JedisClientConfigurationBuilder} to fine-tune its auto-configuration before it * creates the {@link JedisClientConfiguration}. * * @author Mark Paluch * @since 4.0.0 */ @FunctionalInterface public
that
java
elastic__elasticsearch
x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/LifecycleOperationSnapshotTests.java
{ "start": 2442, "end": 6657 }
class ____ extends ESSingleNodeTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return List.of(LocalStateCompositeXPackPlugin.class, IndexLifecycle.class, SnapshotLifecycle.class); } @Override protected Settings nodeSettings() { return Settings.builder().put(super.nodeSettings()).put("slm.history_index_enabled", false).build(); } public void testModeSnapshotRestore() throws Exception { clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "repo") .setType("fs") .setSettings(Settings.builder().put("location", "repo").build()) .get(); client().execute( PutSnapshotLifecycleAction.INSTANCE, new PutSnapshotLifecycleAction.Request( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "slm-policy", new SnapshotLifecyclePolicy( "slm-policy", randomAlphaOfLength(4).toLowerCase(Locale.ROOT), randomSchedule(), "repo", null, randomRetention() ) ) ).get(); client().execute( ILMActions.PUT, new PutLifecycleRequest( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, new LifecyclePolicy( "ilm-policy", Map.of("warm", new Phase("warm", TimeValue.timeValueHours(1), Map.of("readonly", new ReadOnlyAction()))) ) ) ); assertThat(ilmMode(), equalTo(OperationMode.RUNNING)); assertThat(slmMode(), equalTo(OperationMode.RUNNING)); // Take snapshot ExecuteSnapshotLifecycleAction.Response resp = client().execute( ExecuteSnapshotLifecycleAction.INSTANCE, new ExecuteSnapshotLifecycleAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "slm-policy") ).get(); final String snapshotName = resp.getSnapshotName(); // Wait for the snapshot to be successful assertBusy(() -> { logger.info("--> checking for snapshot success"); try { GetSnapshotsResponse getResp = client().execute( TransportGetSnapshotsAction.TYPE, new GetSnapshotsRequest(TEST_REQUEST_TIMEOUT, new String[] { "repo" }, new String[] { snapshotName }) ).get(); assertThat(getResp.getSnapshots().size(), equalTo(1)); assertThat(getResp.getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); } catch (Exception e) { fail("snapshot does not yet exist"); } }); assertAcked(client().execute(ILMActions.STOP, new StopILMRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)).get()); assertAcked(client().execute(StopSLMAction.INSTANCE, new StopSLMAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)).get()); assertBusy(() -> assertThat(ilmMode(), equalTo(OperationMode.STOPPED))); assertBusy(() -> assertThat(slmMode(), equalTo(OperationMode.STOPPED))); // Restore snapshot client().execute( TransportRestoreSnapshotAction.TYPE, new RestoreSnapshotRequest(TEST_REQUEST_TIMEOUT, "repo", snapshotName).includeGlobalState(true) .indices(Strings.EMPTY_ARRAY) .waitForCompletion(true) ).get(); assertBusy(() -> assertThat(ilmMode(), equalTo(OperationMode.STOPPED))); assertBusy(() -> assertThat(slmMode(), equalTo(OperationMode.STOPPED))); } private OperationMode ilmMode() throws Exception { return client().execute(GetStatusAction.INSTANCE, new GetStatusAction.Request(TEST_REQUEST_TIMEOUT)).get().getMode(); } private OperationMode slmMode() throws Exception { return client().execute(GetSLMStatusAction.INSTANCE, new AcknowledgedRequest.Plain(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)) .get() .getOperationMode(); } }
LifecycleOperationSnapshotTests
java
elastic__elasticsearch
x-pack/plugin/migrate/src/internalClusterTest/java/org/elasticsearch/system_indices/action/SystemIndexMigrationIT.java
{ "start": 984, "end": 1088 }
class ____ for testing that when restarting a node, SystemIndexMigrationTaskState can be read. */ public
is
java
quarkusio__quarkus
extensions/reactive-mssql-client/runtime/src/main/java/io/quarkus/reactive/mssql/client/runtime/MSSQLPoolSupport.java
{ "start": 81, "end": 360 }
class ____ { private final Set<String> msSQLPoolNames; public MSSQLPoolSupport(Set<String> msSQLPoolNames) { this.msSQLPoolNames = Set.copyOf(msSQLPoolNames); } public Set<String> getMSSQLPoolNames() { return msSQLPoolNames; } }
MSSQLPoolSupport
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/ClassReader.java
{ "start": 165546, "end": 166577 }
class ____ or * adapters.</i> * * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table. * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified constant pool entry. */ private String readStringish(final int offset, final char[] charBuffer) { // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry // designated by the first two bytes of this cp_info. return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer); } /** * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. <i>This method is * intended for {@link Attribute} sub classes, and is normally not needed by
generators
java
elastic__elasticsearch
x-pack/qa/smoke-test-plugins-ssl/src/yamlRestTest/java/org/elasticsearch/smoketest/SmokeTestPluginsSslClientYamlTestSuiteIT.java
{ "start": 1026, "end": 2648 }
class ____ extends ESClientYamlSuiteTestCase { private static final String USER = "test_user"; private static final String PASS = "x-pack-test-password"; public SmokeTestPluginsSslClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return ESClientYamlSuiteTestCase.createParameters(); } static Path certificateAuthorities; @BeforeClass public static void getKeyStore() { try { certificateAuthorities = PathUtils.get(SmokeTestPluginsSslClientYamlTestSuiteIT.class.getResource("/testnode.crt").toURI()); } catch (URISyntaxException e) { throw new ElasticsearchException("exception while reading the store", e); } if (Files.exists(certificateAuthorities) == false) { throw new IllegalStateException("Keystore file [" + certificateAuthorities + "] does not exist."); } } @AfterClass public static void clearKeyStore() { certificateAuthorities = null; } @Override protected Settings restClientSettings() { String token = basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .put(ESRestTestCase.CERTIFICATE_AUTHORITIES, certificateAuthorities) .build(); } @Override protected String getProtocol() { return "https"; } }
SmokeTestPluginsSslClientYamlTestSuiteIT
java
apache__camel
core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedBacklogTracer.java
{ "start": 1257, "end": 6635 }
class ____ implements ManagedBacklogTracerMBean { private final CamelContext camelContext; private final BacklogTracer backlogTracer; public ManagedBacklogTracer(CamelContext camelContext, BacklogTracer backlogTracer) { this.camelContext = camelContext; this.backlogTracer = backlogTracer; } public void init(ManagementStrategy strategy) { // do nothing } public CamelContext getContext() { return camelContext; } public BacklogTracer getBacklogTracer() { return backlogTracer; } public boolean getEnabled() { return backlogTracer.isEnabled(); } @Override public String getCamelId() { return camelContext.getName(); } @Override public String getCamelManagementName() { return camelContext.getManagementName(); } @Override public boolean isStandby() { return backlogTracer.isStandby(); } @Override public void setEnabled(boolean enabled) { backlogTracer.setEnabled(enabled); } @Override public boolean isEnabled() { return backlogTracer.isEnabled(); } @Override public int getBacklogSize() { return backlogTracer.getBacklogSize(); } @Override public void setBacklogSize(int backlogSize) { backlogTracer.setBacklogSize(backlogSize); } @Override public boolean isRemoveOnDump() { return backlogTracer.isRemoveOnDump(); } @Override public void setRemoveOnDump(boolean removeOnDump) { backlogTracer.setRemoveOnDump(removeOnDump); } @Override public void setTracePattern(String pattern) { backlogTracer.setTracePattern(pattern); } @Override public String getTracePattern() { return backlogTracer.getTracePattern(); } @Override public void setTraceFilter(String predicate) { backlogTracer.setTraceFilter(predicate); } @Override public String getTraceFilter() { return backlogTracer.getTraceFilter(); } @Override public long getTraceCounter() { return backlogTracer.getTraceCounter(); } @Override public void resetTraceCounter() { backlogTracer.resetTraceCounter(); } @Override public long getQueueSize() { return backlogTracer.getQueueSize(); } @Override public int getBodyMaxChars() { return backlogTracer.getBodyMaxChars(); } @Override public void setBodyMaxChars(int bodyMaxChars) { backlogTracer.setBodyMaxChars(bodyMaxChars); } @Override public boolean isBodyIncludeStreams() { return backlogTracer.isBodyIncludeStreams(); } @Override public void setBodyIncludeStreams(boolean bodyIncludeStreams) { backlogTracer.setBodyIncludeStreams(bodyIncludeStreams); } @Override public boolean isBodyIncludeFiles() { return backlogTracer.isBodyIncludeFiles(); } @Override public void setBodyIncludeFiles(boolean bodyIncludeFiles) { backlogTracer.setBodyIncludeFiles(bodyIncludeFiles); } @Override public boolean isIncludeExchangeProperties() { return backlogTracer.isIncludeExchangeProperties(); } @Override public void setIncludeExchangeProperties(boolean includeExchangeProperties) { backlogTracer.setIncludeExchangeProperties(includeExchangeProperties); } @Override public boolean isIncludeExchangeVariables() { return backlogTracer.isIncludeExchangeVariables(); } @Override public void setIncludeExchangeVariables(boolean includeExchangeVariables) { backlogTracer.setIncludeExchangeVariables(includeExchangeVariables); } @Override public boolean isTraceRests() { return backlogTracer.isTraceRests(); } @Override public boolean isTraceTemplates() { return backlogTracer.isTraceTemplates(); } @Override public List<BacklogTracerEventMessage> dumpTracedMessages(String nodeOrRouteId) { return backlogTracer.dumpTracedMessages(nodeOrRouteId); } @Override public List<BacklogTracerEventMessage> dumpAllTracedMessages() { return backlogTracer.dumpAllTracedMessages(); } @Override public List<BacklogTracerEventMessage> dumpLatestMessageHistory() { return backlogTracer.dumpLatestMessageHistory(); } @Override public String dumpTracedMessagesAsXml(String nodeOrRouteId) { return backlogTracer.dumpTracedMessagesAsXml(nodeOrRouteId); } @Override public String dumpTracedMessagesAsJSon(String nodeOrRouteId) { return backlogTracer.dumpTracedMessagesAsJSon(nodeOrRouteId); } @Override public String dumpAllTracedMessagesAsXml() { return backlogTracer.dumpAllTracedMessagesAsXml(); } @Override public String dumpAllTracedMessagesAsJSon() { return backlogTracer.dumpAllTracedMessagesAsJSon(); } @Override public String dumpLatestMessageHistoryAsXml() { return backlogTracer.dumpLatestMessageHistoryAsXml(); } @Override public String dumpLatestMessageHistoryAsJSon() { return backlogTracer.dumpLatestMessageHistoryAsJSon(); } @Override public void clear() { backlogTracer.clear(); } }
ManagedBacklogTracer
java
netty__netty
example/src/main/java/io/netty/example/stomp/websocket/StompWebSocketClientPageHandler.java
{ "start": 1885, "end": 5757 }
class ____ extends SimpleChannelInboundHandler<FullHttpRequest> { static final StompWebSocketClientPageHandler INSTANCE = new StompWebSocketClientPageHandler(); private StompWebSocketClientPageHandler() { } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { if (request.headers().contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true)) { ctx.fireChannelRead(request.retain()); return; } if (request.decoderResult().isFailure()) { FullHttpResponse badRequest = new DefaultFullHttpResponse(request.protocolVersion(), BAD_REQUEST); sendResponse(badRequest, ctx, true); return; } if (!sendResource(request, ctx)) { FullHttpResponse notFound = new DefaultFullHttpResponse(request.protocolVersion(), NOT_FOUND); notFound.headers().set(CONTENT_TYPE, TEXT_PLAIN); String payload = "Requested resource " + request.uri() + " not found"; notFound.content().writeCharSequence(payload, CharsetUtil.UTF_8); HttpUtil.setContentLength(notFound, notFound.content().readableBytes()); sendResponse(notFound, ctx, true); } } private static boolean sendResource(FullHttpRequest request, ChannelHandlerContext ctx) { if (request.uri().isEmpty() || !request.uri().startsWith("/")) { return false; } String requestResource = request.uri().substring(1); if (requestResource.isEmpty()) { requestResource = "index.html"; } URL resourceUrl = INSTANCE.getClass().getResource(requestResource); if (resourceUrl == null) { return false; } RandomAccessFile raf = null; long fileLength = -1L; try { raf = new RandomAccessFile(resourceUrl.getFile(), "r"); fileLength = raf.length(); } catch (FileNotFoundException fne) { System.out.println("File not found " + fne.getMessage()); return false; } catch (IOException io) { System.out.println("Cannot read file length " + io.getMessage()); return false; } finally { if (fileLength < 0 && raf != null) { try { raf.close(); } catch (IOException io) { // Nothing to do } } } HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), OK); HttpUtil.setContentLength(response, fileLength); String contentType = "application/octet-stream"; if (requestResource.endsWith("html")) { contentType = "text/html; charset=UTF-8"; } else if (requestResource.endsWith("css")) { contentType = "text/css; charset=UTF-8"; } else if (requestResource.endsWith("js")) { contentType = "application/javascript"; } response.headers().set(CONTENT_TYPE, contentType); sendResponse(response, ctx, false); ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); return true; } private static void sendResponse(HttpResponse response, ChannelHandlerContext ctx, boolean autoFlush) { if (HttpUtil.isKeepAlive(response)) { if (response.protocolVersion().equals(HTTP_1_0)) { response.headers().set(CONNECTION, KEEP_ALIVE); } ctx.write(response); } else { response.headers().set(CONNECTION, CLOSE); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } if (autoFlush) { ctx.flush(); } } }
StompWebSocketClientPageHandler
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/internal/security/SslContextProviderSupplier.java
{ "start": 1582, "end": 5622 }
class ____ implements Closeable { private final BaseTlsContext tlsContext; private final TlsContextManager tlsContextManager; private SslContextProvider sslContextProvider; private boolean shutdown; public SslContextProviderSupplier( BaseTlsContext tlsContext, TlsContextManager tlsContextManager) { this.tlsContext = checkNotNull(tlsContext, "tlsContext"); this.tlsContextManager = checkNotNull(tlsContextManager, "tlsContextManager"); } public BaseTlsContext getTlsContext() { return tlsContext; } /** Updates SslContext via the passed callback. */ public synchronized void updateSslContext( final SslContextProvider.Callback callback, boolean autoSniSanValidationDoesNotApply) { checkNotNull(callback, "callback"); try { if (!shutdown) { if (sslContextProvider == null) { sslContextProvider = getSslContextProvider(); if (tlsContext instanceof UpstreamTlsContext && autoSniSanValidationDoesNotApply) { ((DynamicSslContextProvider) sslContextProvider).setAutoSniSanValidationDoesNotApply(); } } } // we want to increment the ref-count so call findOrCreate again... final SslContextProvider toRelease = getSslContextProvider(); toRelease.addCallback( new SslContextProvider.Callback(callback.getExecutor()) { @Override public void updateSslContextAndExtendedX509TrustManager( AbstractMap.SimpleImmutableEntry<SslContext, X509TrustManager> sslContextAndTm) { callback.updateSslContextAndExtendedX509TrustManager(sslContextAndTm); releaseSslContextProvider(toRelease); } @Override public void onException(Throwable throwable) { callback.onException(throwable); releaseSslContextProvider(toRelease); } }); } catch (final Throwable throwable) { callback.getExecutor().execute(new Runnable() { @Override public void run() { callback.onException(throwable); } }); } } private void releaseSslContextProvider(SslContextProvider toRelease) { if (tlsContext instanceof UpstreamTlsContext) { tlsContextManager.releaseClientSslContextProvider(toRelease); } else { tlsContextManager.releaseServerSslContextProvider(toRelease); } } private SslContextProvider getSslContextProvider() { return tlsContext instanceof UpstreamTlsContext ? tlsContextManager.findOrCreateClientSslContextProvider((UpstreamTlsContext) tlsContext) : tlsContextManager.findOrCreateServerSslContextProvider( (DownstreamTlsContext) tlsContext); } @VisibleForTesting public boolean isShutdown() { return shutdown; } /** Called by consumer when tlsContext changes. */ @Override public synchronized void close() { if (sslContextProvider != null) { if (tlsContext instanceof UpstreamTlsContext) { tlsContextManager.releaseClientSslContextProvider(sslContextProvider); } else { tlsContextManager.releaseServerSslContextProvider(sslContextProvider); } } sslContextProvider = null; shutdown = true; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SslContextProviderSupplier that = (SslContextProviderSupplier) o; return Objects.equals(tlsContext, that.tlsContext) && Objects.equals(tlsContextManager, that.tlsContextManager); } @Override public int hashCode() { return Objects.hash(tlsContext, tlsContextManager); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("tlsContext", tlsContext) .add("tlsContextManager", tlsContextManager) .add("sslContextProvider", sslContextProvider) .add("shutdown", shutdown) .toString(); } }
SslContextProviderSupplier
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/eviction/EvictionTest.java
{ "start": 1172, "end": 2962 }
class ____ { @BeforeEach public void prepare(SessionFactoryScope scope) { // Create a Parent scope.inTransaction( s -> { Parent p = new Parent(); p.name = "PARENT"; s.persist( p ); } ); } @Test public void test(SessionFactoryScope scope) { scope.inTransaction( s -> { // Delete the Parent Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) .setParameter( "name", "PARENT" ) .uniqueResult(); assertTyping( ManagedEntity.class, loadedParent ); ManagedEntity managedParent = (ManagedEntity) loadedParent; // before eviction assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); assertNotNull( managedParent.$$_hibernate_getEntityEntry() ); assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); assertTrue( s.contains( managedParent ) ); s.evict( managedParent ); // after eviction assertFalse( s.contains( managedParent ) ); assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); assertNull( managedParent.$$_hibernate_getEntityEntry() ); assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); // evict again s.evict( managedParent ); assertFalse( s.contains( managedParent ) ); assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); assertNull( managedParent.$$_hibernate_getEntityEntry() ); assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); s.remove( managedParent ); } ); } // --- // @Entity( name = "Parent" ) @Table( name = "PARENT" ) static
EvictionTest
java
apache__camel
components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppMessageTest.java
{ "start": 1533, "end": 6608 }
class ____ { private SmppMessage message; private CamelContext camelContext = new DefaultCamelContext(); @Test public void emptyConstructorShouldReturnAnInstanceWithoutACommand() { message = new SmppMessage(camelContext, null, new SmppConfiguration()); assertNull(message.getCommand()); assertTrue(message.getHeaders().isEmpty()); } @Test public void alertNotificationConstructorShouldReturnAnInstanceWithACommandAndHeaderAttributes() { AlertNotification command = new AlertNotification(); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertTrue(message.getCommand() instanceof AlertNotification); assertTrue(message.getHeaders().isEmpty()); assertTrue(message.isAlertNotification()); } @Test public void testSmppMessageDataSm() { DataSm command = new DataSm(); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertTrue(message.getCommand() instanceof DataSm); assertTrue(message.getHeaders().isEmpty()); assertTrue(message.isDataSm()); } @Test public void testSmppMessageDeliverSm() { DeliverSm command = new DeliverSm(); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertTrue(message.getCommand() instanceof DeliverSm); assertTrue(message.getHeaders().isEmpty()); assertTrue(message.isDeliverSm()); } @Test public void testSmppMessageDeliverReceipt() { DeliverSm command = new DeliverSm(); command.setSmscDeliveryReceipt(); command.setShortMessage( "id:2 sub:001 dlvrd:001 submit date:0908312310 done date:0908312311 stat:DELIVRD err:xxx Text:Hello SMPP world!" .getBytes()); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertTrue(message.getCommand() instanceof DeliverSm); assertTrue(message.getHeaders().isEmpty()); assertTrue(message.isDeliveryReceipt()); } @Test public void newInstanceShouldReturnAnInstanceWithoutACommand() { message = new SmppMessage(camelContext, null, new SmppConfiguration()); SmppMessage msg = message.newInstance(); assertNotNull(msg); assertNull(msg.getCommand()); assertTrue(msg.getHeaders().isEmpty()); } @Test public void createBodyShouldNotMangle8bitDataCodingShortMessage() { final Set<String> encodings = Charset.availableCharsets().keySet(); final byte[] dataCodings = { (byte) 0x02, (byte) 0x04, (byte) 0xF6, (byte) 0xF4 }; byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; DeliverSm command = new DeliverSm(); SmppConfiguration config = new SmppConfiguration(); for (byte dataCoding : dataCodings) { command.setDataCoding(dataCoding); command.setShortMessage(body); for (String encoding : encodings) { config.setEncoding(encoding); message = new SmppMessage(camelContext, command, config); assertArrayEquals( body, (byte[]) message.createBody(), String.format("data coding=0x%02X; encoding=%s", dataCoding, encoding)); } } } @Test public void createBodyShouldReturnNullIfTheCommandIsNull() { message = new SmppMessage(camelContext, null, new SmppConfiguration()); assertNull(message.createBody()); } @Test public void createBodyShouldReturnNullIfTheCommandIsNotAMessageRequest() { AlertNotification command = new AlertNotification(); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertNull(message.createBody()); } @Test public void createBodyShouldReturnTheShortMessageIfTheCommandIsAMessageRequest() { DeliverSm command = new DeliverSm(); command.setShortMessage("Hello SMPP world!".getBytes()); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertEquals("Hello SMPP world!", message.createBody()); } @Test public void toStringShouldReturnTheBodyIfTheCommandIsNull() { message = new SmppMessage(camelContext, null, new SmppConfiguration()); assertEquals("SmppMessage: null", message.toString()); } @Test public void toStringShouldReturnTheShortMessageIfTheCommandIsNotNull() { DeliverSm command = new DeliverSm(); command.setShortMessage("Hello SMPP world!".getBytes()); message = new SmppMessage(camelContext, command, new SmppConfiguration()); assertEquals("SmppMessage: PDUHeader(0, 00000000, 00000000, 0)", message.toString()); } }
SmppMessageTest
java
google__auto
value/src/test/java/com/google/auto/value/processor/NullablesTest.java
{ "start": 3760, "end": 5600 }
class ____ {", " void noAnnotations() {}", " abstract int noAnnotationsEither(int x);", " abstract @Irrelevant String noRelevantAnnotations(@Irrelevant int x);", " abstract @Nullable String nullableString();", " abstract String @Nullable [] nullableArrayOfString();", " abstract @Nullable String[] arrayOfNullableString();", " abstract @Nullable String @Nullable [] nullableArrayOfNullableString();", " abstract List<@Nullable String> listOfNullableString();", " abstract List<? extends @Nullable Object> listOfExtendsNullable();", " abstract List<? super @Nullable Number> listOfSuperNullable();", " abstract <T extends @Nullable Object> T nullableTypeParamBound();", " abstract <T> @Nullable T nullableTypeParamRef();", " void nullableParam(@Nullable String x) {}", " void nullableParamBound(List<? extends @Nullable String> x) {}", "}"); @Test public void nullableMentionedInMethods() { // Sadly we can't rely on JDK 8 to handle type annotations correctly. // Some versions do, some don't. So skip the test unless we are on at least JDK 9. double javaVersion = Double.parseDouble(JAVA_SPECIFICATION_VERSION.value()); assume().that(javaVersion).isAtLeast(9.0); NullableProcessor processor = new NullableProcessor(expect); Compilation compilation = Compiler.javac() .withProcessors(processor) .compile(JavaFileObjects.forSourceLines("foo.bar.Methods", METHOD_LINES)); assertThat(compilation).succeededWithoutWarnings(); assertThat(processor.ran).isTrue(); // If any `expect` calls failed then the test will fail now because of the Expect rule. } @SupportedAnnotationTypes("*") private static
Methods
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/function/array/ArrayIntersectsTest.java
{ "start": 1484, "end": 7766 }
class ____ { @BeforeEach public void prepareData(SessionFactoryScope scope) { scope.inTransaction( em -> { em.persist( new EntityWithArrays( 1L, new String[]{} ) ); em.persist( new EntityWithArrays( 2L, new String[]{ "abc", null, "def" } ) ); em.persist( new EntityWithArrays( 3L, null ) ); } ); } @AfterEach public void cleanup(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testIntersectsFully(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-intersects-example[] List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_intersects(e.theArray, array('abc', 'def'))", EntityWithArrays.class ) .getResultList(); //end::hql-array-intersects-example[] assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } @Test public void testDoesNotIntersect(SessionFactoryScope scope) { scope.inSession( em -> { List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_intersects(e.theArray, array('xyz'))", EntityWithArrays.class ) .getResultList(); assertEquals( 0, results.size() ); } ); } @Test public void testIntersects(SessionFactoryScope scope) { scope.inSession( em -> { List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_intersects(e.theArray, array('abc','xyz'))", EntityWithArrays.class ) .getResultList(); assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } @Test public void testIntersectsNullFully(SessionFactoryScope scope) { scope.inSession( em -> { List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_intersects_nullable(e.theArray, array(null))", EntityWithArrays.class ) .getResultList(); assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } @Test public void testIntersectsNull(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-intersects-nullable-example[] List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_intersects_nullable(e.theArray, array('xyz',null))", EntityWithArrays.class ) .getResultList(); //end::hql-array-intersects-nullable-example[] assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } @Test public void testNodeBuilderArray(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.arrayIntersects( root.get( "theArray" ), cb.arrayLiteral( "xyz" ) ), cb.arrayIntersects( root.get( "theArray" ), new String[]{ "xyz" } ), cb.arrayIntersects( new String[]{ "abc", "xyz" }, cb.arrayLiteral( "xyz" ) ), cb.arrayIntersectsNullable( root.get( "theArray" ), cb.arrayLiteral( "xyz" ) ), cb.arrayIntersectsNullable( root.get( "theArray" ), new String[]{ "xyz" } ), cb.arrayIntersectsNullable( new String[]{ "abc", "xyz" }, cb.arrayLiteral( "xyz" ) ) ); em.createQuery( cq ).getResultList(); // Should all fail to compile // cb.arrayIntersects( root.<Integer[]>get( "theArray" ), cb.arrayLiteral( "xyz" ) ); // cb.arrayIntersects( root.<Integer[]>get( "theArray" ), new String[]{ "xyz" } ); // cb.arrayIntersects( new String[0], cb.literal( 1 ) ); // cb.arrayIntersects( new Integer[0], cb.literal( "" ) ); // cb.arrayIntersectsNullable( root.<Integer[]>get( "theArray" ), cb.arrayLiteral( "xyz" ) ); // cb.arrayIntersectsNullable( root.<Integer[]>get( "theArray" ), new String[]{ "xyz" } ); // cb.arrayIntersectsNullable( new String[0], cb.literal( 1 ) ); // cb.arrayIntersectsNullable( new Integer[0], cb.literal( "" ) ); } ); } @Test public void testNodeBuilderCollection(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.collectionIntersects( root.<Collection<String>>get( "theCollection" ), cb.collectionLiteral( "xyz" ) ), cb.collectionIntersects( root.get( "theCollection" ), List.of( "xyz" ) ), cb.collectionIntersects( List.of( "abc", "xyz" ), cb.collectionLiteral( "xyz" ) ), cb.collectionIntersectsNullable( root.<Collection<String>>get( "theCollection" ), cb.collectionLiteral( "xyz" ) ), cb.collectionIntersectsNullable( root.get( "theCollection" ), List.of( "xyz" ) ), cb.collectionIntersectsNullable( List.of( "abc", "xyz" ), cb.collectionLiteral( "xyz" ) ) ); em.createQuery( cq ).getResultList(); // Should all fail to compile // cb.collectionIntersects( root.<Collection<Integer>>get( "theCollection" ), cb.collectionLiteral( "xyz" ) ); // cb.collectionIntersects( root.<Collection<Integer>>get( "theCollection" ), List.of( "xyz" ) ); // cb.collectionIntersects( Collections.<String>emptyList(), cb.literal( 1 ) ); // cb.collectionIntersects( Collections.<Integer>emptyList(), cb.literal( "" ) ); // cb.collectionIntersectsNullable( root.<Collection<Integer>>get( "theCollection" ), cb.collectionLiteral( "xyz" ) ); // cb.collectionIntersectsNullable( root.<Collection<Integer>>get( "theCollection" ), List.of( "xyz" ) ); // cb.collectionIntersectsNullable( Collections.<String>emptyList(), cb.literal( 1 ) ); // cb.collectionIntersectsNullable( Collections.<Integer>emptyList(), cb.literal( "" ) ); } ); } @Test public void testIntersectsSyntax(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-intersects-hql-example[] List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where e.theArray intersects ['abc','xyz']", EntityWithArrays.class ) .getResultList(); //end::hql-array-intersects-hql-example[] assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } }
ArrayIntersectsTest
java
alibaba__nacos
plugin/control/src/test/java/com/alibaba/nacos/plugin/control/connection/TestBConnectionMetricsCollector.java
{ "start": 678, "end": 999 }
class ____ implements ConnectionMetricsCollector { @Override public String getName() { return "testb"; } @Override public int getTotalCount() { return 10; } @Override public int getCountForIp(String ip) { return 5; } }
TestBConnectionMetricsCollector
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/DNS.java
{ "start": 8896, "end": 12019 }
interface ____ invalid */ public static String[] getHosts(String strInterface, @Nullable String nameserver, boolean tryfallbackResolution) throws UnknownHostException { final List<String> hosts = new Vector<String>(); final List<InetAddress> addresses = getIPsAsInetAddressList(strInterface, true); for (InetAddress address : addresses) { try { hosts.add(reverseDns(address, nameserver)); } catch (NamingException ignored) { } } if (hosts.isEmpty() && tryfallbackResolution) { for (InetAddress address : addresses) { final String canonicalHostName = address.getCanonicalHostName(); // Don't use the result if it looks like an IP address. if (!InetAddresses.isInetAddress(canonicalHostName)) { hosts.add(canonicalHostName); } } } if (hosts.isEmpty()) { LOG.warn("Unable to determine hostname for interface {}", strInterface); hosts.add(cachedHostname); } return hosts.toArray(new String[hosts.size()]); } /** * Determine the local hostname; retrieving it from cache if it is known * If we cannot determine our host name, return "localhost" * @return the local hostname or "localhost" */ private static String resolveLocalHostname() { String localhost; try { localhost = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { LOG.warn("Unable to determine local hostname -falling back to '{}'", LOCALHOST, e); localhost = LOCALHOST; } return localhost; } /** * Get the IPAddress of the local host as a string. * This will be a loop back value if the local host address cannot be * determined. * If the loopback address of "localhost" does not resolve, then the system's * network is in such a state that nothing is going to work. A message is * logged at the error level and a null pointer returned, a pointer * which will trigger failures later on the application * @return the IPAddress of the local host or null for a serious problem. */ private static String resolveLocalHostIPAddress() { String address; try { address = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { LOG.warn("Unable to determine address of the host " + "-falling back to '{}' address", LOCALHOST, e); try { address = InetAddress.getByName(LOCALHOST).getHostAddress(); } catch (UnknownHostException noLocalHostAddressException) { //at this point, deep trouble LOG.error("Unable to determine local loopback address of '{}' " + "-this system's network configuration is unsupported", LOCALHOST, e); address = null; } } return address; } /** * Returns all the host names associated by the default nameserver with the * address bound to the specified network interface * * @param strInterface * The name of the network
is
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/deepseek/DeepSeekRequestManager.java
{ "start": 1708, "end": 4384 }
class ____ extends BaseRequestManager { private static final Logger logger = LogManager.getLogger(DeepSeekRequestManager.class); private static final ResponseHandler CHAT_COMPLETION = createChatCompletionHandler(); private static final ResponseHandler COMPLETION = createCompletionHandler(); private final DeepSeekChatCompletionModel model; public DeepSeekRequestManager(DeepSeekChatCompletionModel model, ThreadPool threadPool) { super(threadPool, model.getInferenceEntityId(), model.rateLimitGroup(), model.rateLimitSettings()); this.model = Objects.requireNonNull(model); } @Override public void execute( InferenceInputs inferenceInputs, RequestSender requestSender, Supplier<Boolean> hasRequestCompletedFunction, ActionListener<InferenceServiceResults> listener ) { switch (inferenceInputs) { case UnifiedChatInput uci -> execute(uci, requestSender, hasRequestCompletedFunction, listener); case ChatCompletionInput cci -> execute(cci, requestSender, hasRequestCompletedFunction, listener); default -> throw createUnsupportedTypeException(inferenceInputs, UnifiedChatInput.class); } } private void execute( UnifiedChatInput inferenceInputs, RequestSender requestSender, Supplier<Boolean> hasRequestCompletedFunction, ActionListener<InferenceServiceResults> listener ) { var request = new DeepSeekChatCompletionRequest(inferenceInputs, model); execute(new ExecutableInferenceRequest(requestSender, logger, request, CHAT_COMPLETION, hasRequestCompletedFunction, listener)); } private void execute( ChatCompletionInput inferenceInputs, RequestSender requestSender, Supplier<Boolean> hasRequestCompletedFunction, ActionListener<InferenceServiceResults> listener ) { var unifiedInputs = new UnifiedChatInput(inferenceInputs.getInputs(), "user", inferenceInputs.stream()); var request = new DeepSeekChatCompletionRequest(unifiedInputs, model); execute(new ExecutableInferenceRequest(requestSender, logger, request, COMPLETION, hasRequestCompletedFunction, listener)); } private static ResponseHandler createChatCompletionHandler() { return new OpenAiUnifiedChatCompletionResponseHandler("deepseek chat completion", OpenAiChatCompletionResponseEntity::fromResponse); } private static ResponseHandler createCompletionHandler() { return new OpenAiChatCompletionResponseHandler("deepseek completion", OpenAiChatCompletionResponseEntity::fromResponse); } }
DeepSeekRequestManager
java
apache__avro
lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroMultipleInputs.java
{ "start": 4896, "end": 5466 }
class ____ use for this path */ public static void addInputPath(JobConf conf, Path path, Class<? extends AvroMapper> mapperClass, Schema inputSchema) { addInputPath(conf, path, inputSchema); String mapperMapping = path.toString() + ";" + mapperClass.getName(); LOG.info(mapperMapping); String mappers = conf.get(MAPPERS_KEY); conf.set(MAPPERS_KEY, mappers == null ? mapperMapping : mappers + "," + mapperMapping); conf.setMapperClass(DelegatingMapper.class); } /** * Retrieves a map of {@link Path}s to the {@link AvroMapper}
to
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java
{ "start": 18255, "end": 18601 }
interface ____ { ZipEntryCustomizer NONE = (entry) -> { }; /** * Customize the entry. * @param entry the entry to customize * @throws IOException on IO error */ void customize(ZipArchiveEntry entry) throws IOException; } /** * Callback used to write a zip entry data. */ @FunctionalInterface private
ZipEntryCustomizer
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_isEqualTo_with_maps_Test.java
{ "start": 1986, "end": 13458 }
class ____ extends WithComparingFieldsIntrospectionStrategyBaseTest { // TODO should_fail_when_comparing_actual_unordered_with_expected_ordered_map @Test void should_fail_when_comparing_actual_unsorted_with_expected_sorted_map() { WithMap<Long, Boolean> actual = new WithMap<>(new LinkedHashMap<>()); actual.map.put(1L, true); actual.map.put(2L, false); WithMap<Long, Boolean> expected = new WithMap<>(new TreeMap<>()); expected.map.put(2L, false); expected.map.put(1L, true); // WHEN/THEN ComparisonDifference mapDifference = diff("map", actual.map, expected.map, "expected field is a sorted map but actual field is not (java.util.LinkedHashMap)"); compareRecursivelyFailsWithDifferences(actual, expected, mapDifference); } @ParameterizedTest(name = "author 1 {0} / author 2 {1}") @MethodSource("sameMaps") void should_pass_when_comparing_same_map_fields(Map<String, Author> authors1, Map<String, Author> authors2) { // GIVEN WithMap<String, Author> actual = new WithMap<>(authors1); WithMap<String, Author> expected = new WithMap<>(authors2); // THEN then(actual).usingRecursiveComparison(recursiveComparisonConfiguration) .isEqualTo(expected); } static Stream<Arguments> sameMaps() { Author pratchett = new Author("Terry Pratchett"); Author georgeMartin = new Author("George Martin"); Author none = null; Map<String, Author> empty = newHashMap(); SortedMap<String, Author> martinAndPratchettSorted = of(pratchett.name, pratchett, georgeMartin.name, georgeMartin); Map<String, Author> singletonPratchettMap = singletonMap(pratchett.name, pratchett); LinkedHashMap<String, Author> pratchettAndMartin = mapOf(entry(pratchett.name, pratchett), entry(georgeMartin.name, georgeMartin)); LinkedHashMap<String, Author> martinAndPratchett = mapOf(entry(georgeMartin.name, georgeMartin), entry(pratchett.name, pratchett)); return Stream.of(arguments(singletonPratchettMap, singletonPratchettMap), arguments(pratchettAndMartin, pratchettAndMartin), arguments(martinAndPratchett, pratchettAndMartin), arguments(pratchettAndMartin, martinAndPratchett), arguments(martinAndPratchettSorted, martinAndPratchettSorted), arguments(martinAndPratchettSorted, martinAndPratchett), arguments(singletonMap(pratchett.name, none), singletonMap(pratchett.name, none)), arguments(mapOf(entry(pratchett.name, pratchett)), singletonPratchettMap), arguments(empty, empty)); } @ParameterizedTest(name = "authors 1 {0} / authors 2 {1} / path {2} / value 1 {3}/ value 2 {4}") @MethodSource("differentMaps") void should_fail_when_comparing_different_map_fields(Map<String, Author> authors1, Map<String, Author> authors2, String path, Object value1, Object value2, String desc) { // GIVEN WithMap<String, Author> actual = new WithMap<>(authors1); WithMap<String, Author> expected = new WithMap<>(authors2); // WHEN/THEN ComparisonDifference difference = desc == null ? diff(path, value1, value2) : diff(path, value1, value2, desc); compareRecursivelyFailsWithDifferences(actual, expected, difference); } static Stream<Arguments> differentMaps() { Author pratchett = new Author("Terry Pratchett"); Author georgeMartin = new Author("George Martin"); Author none = null; Map<String, Author> empty = newHashMap(); SortedMap<String, Author> sortedMartinAndPratchett = of(pratchett.name, pratchett, georgeMartin.name, georgeMartin); SortedMap<String, Author> sortedPratchettMap = of(pratchett.name, pratchett); Map<String, Author> nonSortedPratchettAndMartin = mapOf(entry(pratchett.name, pratchett), entry(georgeMartin.name, georgeMartin)); Map<String, Author> singletonPratchettMap = singletonMap(pratchett.name, pratchett); Map<String, Author> singletonGeorgeMartinMap = singletonMap(georgeMartin.name, georgeMartin); return Stream.of(arguments(singletonPratchettMap, singletonGeorgeMartinMap, "map", singletonPratchettMap, singletonGeorgeMartinMap, ("The following keys were not found in the actual map value:%n [\"George Martin\"]" + "%nThe following keys were present in the actual map value, but not in the expected map value:%n [\"Terry Pratchett\"]").formatted()), arguments(nonSortedPratchettAndMartin, singletonPratchettMap, "map", nonSortedPratchettAndMartin, singletonPratchettMap, ("actual and expected values are maps of different size, actual size=2 when expected size=1" + "%nThe following keys were present in the actual map value, but not in the expected map value:%n [\"George Martin\"]").formatted(), arguments(sortedMartinAndPratchett, sortedPratchettMap, "map", sortedMartinAndPratchett, sortedPratchettMap, "actual and expected values are sorted maps of different size, actual size=2 when expected size=1"), arguments(nonSortedPratchettAndMartin, sortedMartinAndPratchett, "map", nonSortedPratchettAndMartin, sortedMartinAndPratchett, "expected field is a sorted map but actual field is not (java.util.LinkedHashMap)"), arguments(singletonMap(pratchett.name, none), singletonPratchettMap, "map.Terry Pratchett", none, pratchett, null), arguments(singletonPratchettMap, singletonMap(georgeMartin.name, pratchett), "map", singletonPratchettMap, singletonMap(georgeMartin.name, pratchett), "The following keys were not found in the actual map value:%n [\"George Martin\"]".formatted()), arguments(singletonPratchettMap, empty, "map", singletonPratchettMap, empty, "actual and expected values are maps of different size, actual size=1 when expected size=0"))); } @ParameterizedTest(name = "authors {0} / object {1} / path {2} / value 1 {3}/ value 2 {4}") @MethodSource void should_fail_when_comparing_map_to_non_map(Object actualFieldValue, Map<String, Author> expectedFieldValue, String path, Object value1, Object value2, String desc) { // GIVEN WithObject actual = new WithObject(actualFieldValue); WithObject expected = new WithObject(expectedFieldValue); // WHEN/THEN ComparisonDifference difference = desc == null ? diff(path, value1, value2) : diff(path, value1, value2, desc); compareRecursivelyFailsWithDifferences(actual, expected, difference); } @Test void should_report_unmatched_elements() { // GIVEN Map<String, String> actual = ImmutableMap.of("a", "a", "b", "b", "e", "e"); Map<String, String> expected = ImmutableMap.of("a", "a", "c", "c", "d", "d"); // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).usingRecursiveComparison(recursiveComparisonConfiguration) .isEqualTo(expected)); // THEN then(assertionError).hasMessageContaining("The following keys were not found in the actual map value:%n [\"c\", \"d\"]".formatted()); } static Stream<Arguments> should_fail_when_comparing_map_to_non_map() { Author pratchett = new Author("Terry Pratchett"); Author georgeMartin = new Author("George Martin"); Author none = null; Map<String, Author> mapOfTwoAuthors = mapOf(entry(pratchett.name, pratchett), entry(georgeMartin.name, georgeMartin)); return Stream.of(arguments(pratchett, mapOfTwoAuthors, "value", pratchett, mapOfTwoAuthors, "expected field is a map but actual field is not (org.assertj.tests.core.api.recursive.data.Author)"), arguments(none, mapOfTwoAuthors, "value", none, mapOfTwoAuthors, null)); } record Item(String name, int quantity) { } @Test void should_honor_representation_in_unmatched_elements_when_comparing_unordered_iterables() { // GIVEN Map<String, Item> expectedItems = mapOf(entry("Shoes", new Item("Shoes", 2)), entry("Pants", new Item("Pants", 3))); Map<String, Item> actualItems = mapOf(entry("Pants", new Item("Pants", 3)), entry("Hat", new Item("Hat", 1))); registerFormatterForType(Item.class, item -> "Item(%s, %d)".formatted(item.name(), item.quantity())); // WHEN var assertionError = expectAssertionError(() -> assertThat(actualItems).usingRecursiveComparison(recursiveComparisonConfiguration) .isEqualTo(expectedItems)); // THEN then(assertionError).hasMessageContaining(format("The following keys were not found in the actual map value:%n" + " [\"Shoes\"]")); } // @Test // public void should_not_compare_data_object_with_map_by_default() { // // GIVEN // Data actual = new Data("Tom", 27); // Map<String, Object> expected = Map.of("name", "Foo", "age", 27); // // WHEN // var assertionError = expectAssertionError(() -> assertThat(actual).usingRecursiveComparison(recursiveComparisonConfiguration) // .isEqualTo(expected)); // // THEN // then(assertionError).hasMessageContaining("expected field is a map but actual field is not // (org.assertj.tests.core.api.recursive.comparison.fields.RecursiveComparisonAssert_isEqualTo_with_maps_Test.Data)"); // } // // @Test // public void should_not_compare_map_with_data_object_by_default() { // // GIVEN // Map<String, Object> actual = Map.of("name", "Foo", "age", 27); // Data expected = new Data("Tom", 27); // // WHEN // var assertionError = expectAssertionError(() -> assertThat(actual).usingRecursiveComparison(recursiveComparisonConfiguration) // .isEqualTo(expected)); // // THEN // then(assertionError).hasMessageContaining("expected field is a map but actual field is not // (org.assertj.tests.core.api.recursive.comparison.fields.RecursiveComparisonAssert_isEqualTo_with_maps_Test.Data)"); // } // // @ParameterizedTest // @MethodSource // void should_treat_map_as_a_data_object(Object actual, Object expected) { // assertThat(actual).usingRecursiveComparison() // .isEqualTo(expected); // } // // static Stream<Arguments> should_treat_map_as_a_data_object() { // return Stream.of(arguments(new Data("Tom", 27), Map.of("name", "Foo", "age", 27)), // arguments(new WithObject(new Data("Tom", 27)), new WithObject(Map.of("name", "Foo", "age", 27)))); // } record Data(String name, int age) { } }
RecursiveComparisonAssert_isEqualTo_with_maps_Test
java
quarkusio__quarkus
extensions/smallrye-metrics/deployment/src/test/java/io/quarkus/smallrye/metrics/registration/DefaultMethodTest.java
{ "start": 3093, "end": 3162 }
class ____ extends C { } // case with a method name clash - a
D
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IgniteQueueComponentBuilderFactory.java
{ "start": 5699, "end": 6941 }
class ____ extends AbstractComponentBuilder<IgniteQueueComponent> implements IgniteQueueComponentBuilder { @Override protected IgniteQueueComponent buildConcreteComponent() { return new IgniteQueueComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "configurationResource": ((IgniteQueueComponent) component).setConfigurationResource((java.lang.Object) value); return true; case "ignite": ((IgniteQueueComponent) component).setIgnite((org.apache.ignite.Ignite) value); return true; case "igniteConfiguration": ((IgniteQueueComponent) component).setIgniteConfiguration((org.apache.ignite.configuration.IgniteConfiguration) value); return true; case "lazyStartProducer": ((IgniteQueueComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((IgniteQueueComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
IgniteQueueComponentBuilderImpl
java
elastic__elasticsearch
libs/logstash-bridge/src/main/java/org/elasticsearch/logstashbridge/geoip/AbstractExternalIpDatabaseBridge.java
{ "start": 1512, "end": 2142 }
class ____ implements IpDatabase { @Override public String getDatabaseType() throws IOException { return AbstractExternalIpDatabaseBridge.this.getDatabaseType(); } @Override public <RESPONSE> RESPONSE getResponse(String ipAddress, CheckedBiFunction<Reader, String, RESPONSE, Exception> responseProvider) { return AbstractExternalIpDatabaseBridge.this.getResponse(ipAddress, responseProvider::apply); } @Override public void close() throws IOException { AbstractExternalIpDatabaseBridge.this.close(); } } }
ProxyExternal
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterUserStatement.java
{ "start": 3908, "end": 4060 }
enum ____ { PASSWORD_EXPIRE, PASSWORD_EXPIRE_DEFAULT, PASSWORD_EXPIRE_NEVER, PASSWORD_EXPIRE_INTERVAL } }
PasswordExpire
java
quarkusio__quarkus
extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLUIConfig.java
{ "start": 157, "end": 737 }
interface ____ { /** * The path where GraphQL UI is available. * The value `/` is not allowed as it blocks the application from serving anything else. * By default, this URL will be resolved as a path relative to `${quarkus.http.non-application-root-path}`. */ @WithDefault("graphql-ui") String rootPath(); /** * Always include the UI. By default, this will only be included in dev and test. * Setting this to true will also include the UI in Prod */ @WithDefault("false") boolean alwaysInclude(); }
SmallRyeGraphQLUIConfig
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/bind/ServletRequestUtils.java
{ "start": 19182, "end": 19876 }
class ____ extends ParameterParser<Integer> { @Override protected String getType() { return "int"; } @Override protected Integer doParse(String s) throws NumberFormatException { return Integer.valueOf(s); } public int parseInt(String name, String parameter) throws ServletRequestBindingException { return parse(name, parameter); } public int[] parseInts(String name, String[] values) throws ServletRequestBindingException { validateRequiredParameter(name, values); int[] parameters = new int[values.length]; for (int i = 0; i < values.length; i++) { parameters[i] = parseInt(name, values[i]); } return parameters; } } private static
IntParser
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-tos/src/main/java/org/apache/hadoop/fs/tosfs/util/RemoteIterators.java
{ "start": 1110, "end": 1887 }
class ____ { private RemoteIterators() { } /** * Create an iterator from a singleton. * * @param singleton instance * @param <T> type * @return a remote iterator */ public static <T> RemoteIterator<T> fromSingleton(@Nullable T singleton) { return new SingletonIterator<>(singleton); } /** * Create an iterator from an iterable and a transformation function. * * @param <S> source type * @param <T> result type * @param iterator source * @param mapper transformation * @return a remote iterator */ public static <S, T> RemoteIterator<T> fromIterable(Iterable<S> iterator, FunctionRaisingIOE<S, T> mapper) { return new IterableRemoteIterator<>(iterator, mapper); } public
RemoteIterators
java
apache__camel
components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2Configuration.java
{ "start": 1459, "end": 15476 }
class ____ implements Cloneable { @UriPath(description = "Name of the stream") @Metadata(required = true) private String streamName; @UriParam(label = "security", secret = true, description = "Amazon AWS Access Key") private String accessKey; @UriParam(label = "security", secret = true, description = "Amazon AWS Secret Key") private String secretKey; @UriParam(label = "security", secret = true, description = "Amazon AWS Session Token used when the user needs to assume a IAM role") private String sessionToken; @UriParam(enums = "ap-south-2,ap-south-1,eu-south-1,eu-south-2,us-gov-east-1,me-central-1,il-central-1,ca-central-1,eu-central-1,us-iso-west-1,eu-central-2,eu-isoe-west-1,us-west-1,us-west-2,af-south-1,eu-north-1,eu-west-3,eu-west-2,eu-west-1,ap-northeast-3,ap-northeast-2,ap-northeast-1,me-south-1,sa-east-1,ap-east-1,cn-north-1,ca-west-1,us-gov-west-1,ap-southeast-1,ap-southeast-2,us-iso-east-1,ap-southeast-3,ap-southeast-4,us-east-1,us-east-2,cn-northwest-1,us-isob-east-1,aws-global,aws-cn-global,aws-us-gov-global,aws-iso-global,aws-iso-b-global", description = "The region in which Kinesis Firehose client needs to work. When using this parameter, the configuration will expect the lowercase name of the " + "region (for example ap-east-1) You'll need to use the name Region.EU_WEST_1.id()") private String region; @UriParam(description = "Amazon Kinesis client to use for all requests for this endpoint") @Metadata(label = "advanced", autowired = true) private KinesisClient amazonKinesisClient; @UriParam(label = "consumer", description = "Maximum number of records that will be fetched in each poll", defaultValue = "1") private int maxResultsPerRequest = 1; @UriParam(label = "consumer", description = "Defines where in the Kinesis stream to start getting records", defaultValue = "TRIM_HORIZON") private ShardIteratorType iteratorType = ShardIteratorType.TRIM_HORIZON; @UriParam(label = "consumer", description = "Defines which shardId in the Kinesis stream to get records from") private String shardId = ""; @UriParam(label = "consumer", description = "The sequence number to start polling from. Required if iteratorType is set to AFTER_SEQUENCE_NUMBER or AT_SEQUENCE_NUMBER") private String sequenceNumber = ""; @UriParam(label = "consumer", description = "The message timestamp to start polling from. Required if iteratorType is set to AT_TIMESTAMP") private String messageTimestamp = ""; @UriParam(label = "consumer", defaultValue = "ignore", description = "Define what will be the behavior in case of shard closed. Possible value are ignore, silent and fail." + " In case of ignore a WARN message will be logged once and the consumer will not process new messages until restarted," + "in case of silent there will be no logging and the consumer will not process new messages until restarted," + "in case of fail a ReachedClosedStateException will be thrown") private Kinesis2ShardClosedStrategyEnum shardClosed; @UriParam(label = "proxy", enums = "HTTP,HTTPS", defaultValue = "HTTPS", description = "To define a proxy protocol when instantiating the Kinesis client") private Protocol proxyProtocol = Protocol.HTTPS; @UriParam(label = "proxy", description = "To define a proxy host when instantiating the Kinesis client") private String proxyHost; @UriParam(label = "proxy", description = "To define a proxy port when instantiating the Kinesis client") private Integer proxyPort; @UriParam(label = "security", description = "If we want to trust all certificates in case of overriding the endpoint") private boolean trustAllCertificates; @UriParam(label = "advanced", description = "If we want to a KinesisAsyncClient instance set it to true") private boolean asyncClient; @UriParam(label = "common", defaultValue = "true", description = "This option will set the CBOR_ENABLED property during the execution") private boolean cborEnabled = true; @UriParam(label = "common", defaultValue = "false", description = "Set the need for overriding the endpoint. This option needs to be used in combination with uriEndpointOverride" + " option") private boolean overrideEndpoint; @UriParam(label = "common", description = "Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option") private String uriEndpointOverride; @UriParam(label = "security", description = "Set whether the Kinesis client should expect to load credentials through a default credentials provider or to expect" + " static credentials to be passed in.") private boolean useDefaultCredentialsProvider; @UriParam(label = "security", description = "Set whether the Kinesis client should expect to load credentials through a profile credentials provider.") private boolean useProfileCredentialsProvider; @UriParam(label = "security", description = "Set whether the Kinesis client should expect to use Session Credentials. This is useful in situation in which the user" + " needs to assume a IAM role for doing operations in Kinesis.") private boolean useSessionCredentials; @UriParam(label = "security", description = "If using a profile credentials provider this parameter will set the profile name.") private String profileCredentialsName; @UriParam(label = "consumer,advanced", description = "The interval in milliseconds to wait between shard polling", defaultValue = "10000") private long shardMonitorInterval = 10000; // KCL specific parameters @UriParam(label = "advanced", description = "If we want to a KCL Consumer set it to true") private boolean useKclConsumers; @UriParam(label = "advanced", description = "If we want to a KCL Consumer, we can pass an instance of DynamoDbAsyncClient") private DynamoDbAsyncClient dynamoDbAsyncClient; @UriParam(label = "advanced", description = "If we want to a KCL Consumer, we can pass an instance of CloudWatchAsyncClient") private CloudWatchAsyncClient cloudWatchAsyncClient; @UriParam(label = "advanced", description = "If we want to use a KCL Consumer and disable the CloudWatch Metrics Export") private boolean kclDisableCloudwatchMetricsExport; @UriParam(description = "Supply a pre-constructed Amazon Kinesis async client to use for the KCL Consumer") @Metadata(label = "advanced", autowired = true) private KinesisAsyncClient amazonKinesisAsyncClient; @UriParam(description = "Name of the KCL application. This defaults to the stream name.") @Metadata(label = "advanced") private String applicationName; public KinesisAsyncClient getAmazonKinesisAsyncClient() { return amazonKinesisAsyncClient; } public void setAmazonKinesisAsyncClient(KinesisAsyncClient amazonKinesisAsyncClient) { this.amazonKinesisAsyncClient = amazonKinesisAsyncClient; } public KinesisClient getAmazonKinesisClient() { return amazonKinesisClient; } public void setAmazonKinesisClient(KinesisClient amazonKinesisClient) { this.amazonKinesisClient = amazonKinesisClient; } public int getMaxResultsPerRequest() { return maxResultsPerRequest; } public void setMaxResultsPerRequest(int maxResultsPerRequest) { this.maxResultsPerRequest = maxResultsPerRequest; } public String getStreamName() { return streamName; } public void setStreamName(String streamName) { this.streamName = streamName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public ShardIteratorType getIteratorType() { return iteratorType; } public void setIteratorType(ShardIteratorType iteratorType) { this.iteratorType = iteratorType; } public String getShardId() { return shardId; } public void setShardId(String shardId) { this.shardId = shardId; } public String getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; } public String getMessageTimestamp() { return messageTimestamp; } public void setMessageTimestamp(String messageTimestamp) { this.messageTimestamp = messageTimestamp; } public Kinesis2ShardClosedStrategyEnum getShardClosed() { return shardClosed; } public void setShardClosed(Kinesis2ShardClosedStrategyEnum shardClosed) { this.shardClosed = shardClosed; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public Protocol getProxyProtocol() { return proxyProtocol; } public void setProxyProtocol(Protocol proxyProtocol) { this.proxyProtocol = proxyProtocol; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public boolean isTrustAllCertificates() { return trustAllCertificates; } public void setTrustAllCertificates(boolean trustAllCertificates) { this.trustAllCertificates = trustAllCertificates; } public boolean isCborEnabled() { return cborEnabled; } public void setCborEnabled(boolean cborEnabled) { this.cborEnabled = cborEnabled; } public boolean isOverrideEndpoint() { return overrideEndpoint; } public void setOverrideEndpoint(boolean overrideEndpoint) { this.overrideEndpoint = overrideEndpoint; } public String getUriEndpointOverride() { return uriEndpointOverride; } public void setUriEndpointOverride(String uriEndpointOverride) { this.uriEndpointOverride = uriEndpointOverride; } public boolean isUseDefaultCredentialsProvider() { return useDefaultCredentialsProvider; } public void setUseDefaultCredentialsProvider(boolean useDefaultCredentialsProvider) { this.useDefaultCredentialsProvider = useDefaultCredentialsProvider; } public boolean isUseProfileCredentialsProvider() { return useProfileCredentialsProvider; } public void setUseProfileCredentialsProvider(boolean useProfileCredentialsProvider) { this.useProfileCredentialsProvider = useProfileCredentialsProvider; } public String getProfileCredentialsName() { return profileCredentialsName; } public void setProfileCredentialsName(String profileCredentialsName) { this.profileCredentialsName = profileCredentialsName; } public String getSessionToken() { return sessionToken; } public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public boolean isUseSessionCredentials() { return useSessionCredentials; } public void setUseSessionCredentials(boolean useSessionCredentials) { this.useSessionCredentials = useSessionCredentials; } public boolean isAsyncClient() { return asyncClient; } public void setAsyncClient(boolean asyncClient) { this.asyncClient = asyncClient; } public long getShardMonitorInterval() { return shardMonitorInterval; } public void setShardMonitorInterval(long shardMonitorInterval) { this.shardMonitorInterval = shardMonitorInterval; } public boolean isUseKclConsumers() { return useKclConsumers; } public void setUseKclConsumers(boolean useKclConsumers) { this.useKclConsumers = useKclConsumers; } public DynamoDbAsyncClient getDynamoDbAsyncClient() { return dynamoDbAsyncClient; } public void setDynamoDbAsyncClient(DynamoDbAsyncClient dynamoDbAsyncClient) { this.dynamoDbAsyncClient = dynamoDbAsyncClient; } public CloudWatchAsyncClient getCloudWatchAsyncClient() { return cloudWatchAsyncClient; } public void setCloudWatchAsyncClient(CloudWatchAsyncClient cloudWatchAsyncClient) { this.cloudWatchAsyncClient = cloudWatchAsyncClient; } public boolean isKclDisableCloudwatchMetricsExport() { return kclDisableCloudwatchMetricsExport; } public void setKclDisableCloudwatchMetricsExport(boolean kclDisableCloudwatchMetricsExport) { this.kclDisableCloudwatchMetricsExport = kclDisableCloudwatchMetricsExport; } // ************************************************* // // ************************************************* public Kinesis2Configuration copy() { try { return (Kinesis2Configuration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
Kinesis2Configuration
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/LastValueWithRetractAggFunctionWithOrderTest.java
{ "start": 7398, "end": 9523 }
class ____ extends LastValueWithRetractAggFunctionWithOrderTestBase<DecimalData> { private int precision = 20; private int scale = 6; @Override protected List<List<DecimalData>> getInputValueSets() { return Arrays.asList( Arrays.asList( DecimalDataUtils.castFrom("1", precision, scale), DecimalDataUtils.castFrom("1000.000001", precision, scale), DecimalDataUtils.castFrom("-1", precision, scale), DecimalDataUtils.castFrom("-999.998999", precision, scale), null, DecimalDataUtils.castFrom("0", precision, scale), DecimalDataUtils.castFrom("-999.999", precision, scale), null, DecimalDataUtils.castFrom("999.999", precision, scale)), Arrays.asList(null, null, null, null, null), Arrays.asList(null, DecimalDataUtils.castFrom("0", precision, scale))); } @Override protected List<List<Long>> getInputOrderSets() { return Arrays.asList( Arrays.asList(10L, 2L, 1L, 5L, null, 3L, 1L, 5L, 2L), Arrays.asList(6L, 5L, null, 8L, null), Arrays.asList(8L, 6L)); } @Override protected List<DecimalData> getExpectedResults() { return Arrays.asList( DecimalDataUtils.castFrom("1", precision, scale), null, DecimalDataUtils.castFrom("0", precision, scale)); } @Override protected AggregateFunction<DecimalData, LastValueWithRetractAccumulator<DecimalData>> getAggregator() { return new LastValueWithRetractAggFunction<>( DataTypes.DECIMAL(precision, scale).getLogicalType()); } } /** Test for {@link VarCharType}. */ @Nested final
DecimalLastValueWithRetractAggFunctionWithOrderTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/string_/StringAssert_isGreaterThanOrEqualTo_Test.java
{ "start": 792, "end": 1154 }
class ____ extends StringAssertBaseTest { @Override protected StringAssert invoke_api_method() { return assertions.isGreaterThanOrEqualTo("bar"); } @Override protected void verify_internal_effects() { verify(comparables).assertGreaterThanOrEqualTo(getInfo(assertions), getActual(assertions), "bar"); } }
StringAssert_isGreaterThanOrEqualTo_Test
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/failures/TrackingApplicationContextFailureProcessor.java
{ "start": 1155, "end": 1615 }
class ____ implements ApplicationContextFailureProcessor { public static final List<LoadFailure> loadFailures = Collections.synchronizedList(new ArrayList<>()); @Override public void processLoadFailure(ApplicationContext context, @Nullable Throwable exception) { loadFailures.add(new LoadFailure(context, exception)); } public record LoadFailure(ApplicationContext context, @Nullable Throwable exception) {} }
TrackingApplicationContextFailureProcessor
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/ByteBuddyEnhancementContext.java
{ "start": 1030, "end": 7551 }
class ____ { private static final ElementMatcher.Junction<MethodDescription> IS_GETTER = isGetter(); private final EnhancementContext enhancementContext; private final EnhancerImplConstants constants; private final ConcurrentHashMap<TypeDescription, Map<String, MethodDescription>> getterByTypeMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Object> locksMap = new ConcurrentHashMap<>(); ByteBuddyEnhancementContext(final EnhancementContext enhancementContext, EnhancerImplConstants enhancerConstants) { this.enhancementContext = Objects.requireNonNull( enhancementContext ); this.constants = enhancerConstants; } public boolean isEntityClass(TypeDescription classDescriptor) { return enhancementContext.isEntityClass( new UnloadedTypeDescription( classDescriptor ) ); } public boolean isCompositeClass(TypeDescription classDescriptor) { return enhancementContext.isCompositeClass( new UnloadedTypeDescription( classDescriptor ) ); } public boolean isMappedSuperclassClass(TypeDescription classDescriptor) { return enhancementContext.isMappedSuperclassClass( new UnloadedTypeDescription( classDescriptor ) ); } public boolean doDirtyCheckingInline() { return enhancementContext.doDirtyCheckingInline(); } public boolean doExtendedEnhancement() { return enhancementContext.doExtendedEnhancement(); } public boolean hasLazyLoadableAttributes(TypeDescription classDescriptor) { return enhancementContext.hasLazyLoadableAttributes( new UnloadedTypeDescription( classDescriptor ) ); } public boolean isPersistentField(AnnotatedFieldDescription field) { return enhancementContext.isPersistentField( field ); } public boolean isCompositeField(AnnotatedFieldDescription field) { return isCompositeClass( field.getType().asErasure() ) || field.hasAnnotation( Embedded.class ); } public AnnotatedFieldDescription[] order(AnnotatedFieldDescription[] persistentFields) { return (AnnotatedFieldDescription[]) enhancementContext.order( persistentFields ); } public boolean isLazyLoadable(AnnotatedFieldDescription field) { return enhancementContext.isLazyLoadable( field ); } public boolean isMappedCollection(AnnotatedFieldDescription field) { return enhancementContext.isMappedCollection( field ); } public boolean doBiDirectionalAssociationManagement() { return enhancementContext.doBiDirectionalAssociationManagement(); } public boolean isDiscoveredType(TypeDescription typeDescription) { return enhancementContext.isDiscoveredType( new UnloadedTypeDescription( typeDescription ) ); } public void registerDiscoveredType(TypeDescription typeDescription, Type.PersistenceType type) { enhancementContext.registerDiscoveredType( new UnloadedTypeDescription( typeDescription ), type ); } public UnsupportedEnhancementStrategy getUnsupportedEnhancementStrategy() { return enhancementContext.getUnsupportedEnhancementStrategy(); } public void discoverCompositeTypes(TypeDescription managedCtClass, TypePool typePool) { if ( isDiscoveredType( managedCtClass ) ) { return; } final Type.PersistenceType determinedPersistenceType; if ( isEntityClass( managedCtClass ) ) { determinedPersistenceType = Type.PersistenceType.ENTITY; } else if ( isCompositeClass( managedCtClass ) ) { determinedPersistenceType = Type.PersistenceType.EMBEDDABLE; } else if ( isMappedSuperclassClass( managedCtClass ) ) { determinedPersistenceType = Type.PersistenceType.MAPPED_SUPERCLASS; } else { // Default to assuming a basic type if this is not a managed type determinedPersistenceType = Type.PersistenceType.BASIC; } registerDiscoveredType( managedCtClass, determinedPersistenceType ); if ( determinedPersistenceType != Type.PersistenceType.BASIC ) { final EnhancerImpl.AnnotatedFieldDescription[] enhancedFields = PersistentAttributeTransformer.collectPersistentFields( managedCtClass, this, typePool, constants ) .getEnhancedFields(); for ( EnhancerImpl.AnnotatedFieldDescription enhancedField : enhancedFields ) { final TypeDescription type = enhancedField.getType().asErasure(); if ( !type.isInterface() && enhancedField.hasAnnotation( Embedded.class ) ) { registerDiscoveredType( type, Type.PersistenceType.EMBEDDABLE ); } discoverCompositeTypes( type, typePool ); } } } Optional<MethodDescription> resolveGetter(FieldDescription fieldDescription) { //There is a non-straightforward cache here, but we really need this to be able to //efficiently handle enhancement of large models. final TypeDescription erasure = fieldDescription.getDeclaringType().asErasure(); //Always try to get with a simple "get" before doing a "computeIfAbsent" operation, //otherwise large models might exhibit significant contention on the map. Map<String, MethodDescription> getters = getterByTypeMap.get( erasure ); if ( getters == null ) { //poor man lock striping: as CHM#computeIfAbsent has too coarse lock granularity //and has been shown to trigger significant, unnecessary contention. final String lockKey = erasure.toString(); final Object candidateLock = new Object(); final Object existingLock = locksMap.putIfAbsent( lockKey, candidateLock ); final Object lock = existingLock == null ? candidateLock : existingLock; synchronized ( lock ) { getters = getterByTypeMap.get( erasure ); if ( getters == null ) { getters = MethodGraph.Compiler.DEFAULT.compile( erasure ) .listNodes() .asMethodList() .filter( IS_GETTER ) .stream() .collect( Collectors.toMap( MethodDescription::getActualName, Function.identity() ) ); getterByTypeMap.put( erasure, getters ); } } } String capitalizedFieldName = Character.toUpperCase( fieldDescription.getName().charAt( 0 ) ) + fieldDescription.getName().substring( 1 ); MethodDescription getCandidate = getters.get( "get" + capitalizedFieldName ); MethodDescription isCandidate = getters.get( "is" + capitalizedFieldName ); if ( getCandidate != null ) { if ( isCandidate != null ) { // if there are two candidates, the existing code considered there was no getter. // not sure it's such a good idea but throwing an exception apparently throws exception // in cases where Hibernate does not usually throw a mapping error. return Optional.empty(); } return Optional.of( getCandidate ); } return Optional.ofNullable( isCandidate ); } }
ByteBuddyEnhancementContext
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DigitaloceanComponentBuilderFactory.java
{ "start": 1400, "end": 1922 }
interface ____ { /** * DigitalOcean (camel-digitalocean) * Manage Droplets and resources within the DigitalOcean cloud. * * Category: cloud,management * Since: 2.19 * Maven coordinates: org.apache.camel:camel-digitalocean * * @return the dsl builder */ static DigitaloceanComponentBuilder digitalocean() { return new DigitaloceanComponentBuilderImpl(); } /** * Builder for the DigitalOcean component. */
DigitaloceanComponentBuilderFactory
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/DefaultKeyedStateStore.java
{ "start": 2084, "end": 11439 }
class ____ implements KeyedStateStore { @Nullable protected final KeyedStateBackend<?> keyedStateBackend; @Nullable protected final AsyncKeyedStateBackend<?> asyncKeyedStateBackend; protected final SerializerFactory serializerFactory; protected SupportKeyedStateApiSet supportKeyedStateApiSet; public DefaultKeyedStateStore( KeyedStateBackend<?> keyedStateBackend, SerializerFactory serializerFactory) { this(keyedStateBackend, null, serializerFactory); } public DefaultKeyedStateStore( AsyncKeyedStateBackend<?> asyncKeyedStateBackend, SerializerFactory serializerFactory) { this(null, asyncKeyedStateBackend, serializerFactory); } public DefaultKeyedStateStore( @Nullable KeyedStateBackend<?> keyedStateBackend, @Nullable AsyncKeyedStateBackend<?> asyncKeyedStateBackend, SerializerFactory serializerFactory) { this.keyedStateBackend = keyedStateBackend; this.asyncKeyedStateBackend = asyncKeyedStateBackend; this.serializerFactory = Preconditions.checkNotNull(serializerFactory); if (keyedStateBackend != null) { // By default, we support state v1 this.supportKeyedStateApiSet = SupportKeyedStateApiSet.STATE_V1; } else if (asyncKeyedStateBackend != null) { this.supportKeyedStateApiSet = SupportKeyedStateApiSet.STATE_V2; } else { throw new IllegalArgumentException("The state backend must not be null."); } } @Override public <T> ValueState<T> getState(ValueStateDescriptor<T> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <T> ListState<T> getListState(ListStateDescriptor<T> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); ListState<T> originalState = getPartitionedState(stateProperties); return new UserFacingListState<>(originalState); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <T> ReducingState<T> getReducingState(ReducingStateDescriptor<T> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <IN, ACC, OUT> AggregatingState<IN, OUT> getAggregatingState( AggregatingStateDescriptor<IN, ACC, OUT> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <UK, UV> MapState<UK, UV> getMapState(MapStateDescriptor<UK, UV> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); MapState<UK, UV> originalState = getPartitionedState(stateProperties); return new UserFacingMapState<>(originalState); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } protected <S extends State> S getPartitionedState(StateDescriptor<S, ?> stateDescriptor) throws Exception { checkState( keyedStateBackend != null && supportKeyedStateApiSet == SupportKeyedStateApiSet.STATE_V1, "Current operator does not integrate the async processing logic, " + "thus only supports state v1 APIs. Please use StateDescriptor under " + "'org.apache.flink.runtime.state'."); return keyedStateBackend.getPartitionedState( VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, stateDescriptor); } @Override public <T> org.apache.flink.api.common.state.v2.ValueState<T> getValueState( @Nonnull org.apache.flink.api.common.state.v2.ValueStateDescriptor<T> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <T> org.apache.flink.api.common.state.v2.ListState<T> getListState( @Nonnull org.apache.flink.api.common.state.v2.ListStateDescriptor<T> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <UK, UV> org.apache.flink.api.common.state.v2.MapState<UK, UV> getMapState( @Nonnull org.apache.flink.api.common.state.v2.MapStateDescriptor<UK, UV> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <T> org.apache.flink.api.common.state.v2.ReducingState<T> getReducingState( @Nonnull org.apache.flink.api.common.state.v2.ReducingStateDescriptor<T> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public <IN, ACC, OUT> org.apache.flink.api.common.state.v2.AggregatingState<IN, OUT> getAggregatingState( @Nonnull org.apache.flink.api.common.state.v2.AggregatingStateDescriptor< IN, ACC, OUT> stateProperties) { requireNonNull(stateProperties, "The state properties must not be null"); try { stateProperties.initializeSerializerUnlessSet(serializerFactory); return getPartitionedState(stateProperties); } catch (Exception e) { throw new RuntimeException("Error while getting state", e); } } @Override public String getBackendTypeIdentifier() { if (keyedStateBackend != null) { return keyedStateBackend.getBackendTypeIdentifier(); } else { return asyncKeyedStateBackend.getBackendTypeIdentifier(); } } protected <S extends org.apache.flink.api.common.state.v2.State, SV> S getPartitionedState( org.apache.flink.api.common.state.v2.StateDescriptor<SV> stateDescriptor) throws Exception { checkState( asyncKeyedStateBackend != null && supportKeyedStateApiSet == SupportKeyedStateApiSet.STATE_V2, "Current operator integrates the async processing logic, " + "thus only supports state v2 APIs. Please use StateDescriptor under " + "'org.apache.flink.runtime.state.v2'."); return asyncKeyedStateBackend.getOrCreateKeyedState( VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, stateDescriptor); } public void setSupportKeyedStateApiSetV2() { requireNonNull( asyncKeyedStateBackend, "Current operator integrates the logic of async processing, " + "thus only support state v2 APIs. Please use StateDescriptor under " + "'org.apache.flink.runtime.state.v2'."); supportKeyedStateApiSet = SupportKeyedStateApiSet.STATE_V2; } /** * Currently, we only support one keyed state api set. This is determined by the stream * operator. */ private
DefaultKeyedStateStore
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigQueryRequestHandler.java
{ "start": 2811, "end": 9459 }
class ____ extends RequestHandler<ConfigQueryRequest, ConfigQueryResponse> { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigQueryRequestHandler.class); private final ConfigQueryChainService configQueryChainService; public ConfigQueryRequestHandler(ConfigQueryChainService configQueryChainService) { this.configQueryChainService = configQueryChainService; } @Override @NamespaceValidation @TpsControl(pointName = "ConfigQuery") @Secured(action = ActionTypes.READ, signType = SignType.CONFIG) @ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class) public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException { try { request.setTenant(NamespaceUtil.processNamespaceParameter(request.getTenant())); String dataId = request.getDataId(); String group = request.getGroup(); String tenant = request.getTenant(); String groupKey = GroupKey2.getKey(dataId, group, tenant); boolean notify = request.isNotify(); String requestIpApp = meta.getLabels().get(CLIENT_APPNAME_HEADER); String clientIp = meta.getClientIp(); ConfigQueryChainRequest chainRequest = ConfigChainRequestExtractorService.getExtractor() .extract(request, meta); ConfigQueryChainResponse chainResponse = configQueryChainService.handle(chainRequest); if (ResponseCode.FAIL.getCode() == chainResponse.getResultCode()) { return ConfigQueryResponse.buildFailResponse(ResponseCode.FAIL.getCode(), chainResponse.getMessage()); } if (chainResponse.getStatus() == ConfigQueryChainResponse.ConfigQueryStatus.CONFIG_NOT_FOUND) { return handlerConfigNotFound(request.getDataId(), request.getGroup(), request.getTenant(), requestIpApp, clientIp, notify); } if (chainResponse.getStatus() == ConfigQueryChainResponse.ConfigQueryStatus.CONFIG_QUERY_CONFLICT) { return handlerConfigConflict(clientIp, groupKey); } ConfigQueryResponse response = new ConfigQueryResponse(); // Check if there is a matched gray rule if (chainResponse.getStatus() == ConfigQueryChainResponse.ConfigQueryStatus.CONFIG_FOUND_GRAY) { if (BetaGrayRule.TYPE_BETA.equals(chainResponse.getMatchedGray().getGrayRule().getType())) { response.setBeta(true); } else if (TagGrayRule.TYPE_TAG.equals(chainResponse.getMatchedGray().getGrayRule().getType())) { response.setTag(URLEncoder.encode(chainResponse.getMatchedGray().getRawGrayRule(), ENCODE_UTF8)); } } // Check if there is a special tag if (chainResponse.getStatus() == ConfigQueryChainResponse.ConfigQueryStatus.SPECIAL_TAG_CONFIG_NOT_FOUND) { response.setTag(request.getTag()); } response.setMd5(chainResponse.getMd5()); response.setEncryptedDataKey(chainResponse.getEncryptedDataKey()); response.setContent(chainResponse.getContent()); response.setContentType(chainResponse.getConfigType()); response.setLastModified(chainResponse.getLastModified()); String pullType = ConfigTraceService.PULL_TYPE_OK; if (chainResponse.getContent() == null) { pullType = ConfigTraceService.PULL_TYPE_NOTFOUND; response.setErrorInfo(ConfigQueryResponse.CONFIG_NOT_FOUND, "config data not exist"); } else { response.setResultCode(ResponseCode.SUCCESS.getCode()); } String pullEvent = resolvePullEventType(chainResponse, request.getTag()); LogUtil.PULL_CHECK_LOG.warn("{}|{}|{}|{}", groupKey, clientIp, response.getMd5(), TimeUtils.getCurrentTimeStr()); final long delayed = System.currentTimeMillis() - response.getLastModified(); ConfigTraceService.logPullEvent(dataId, group, tenant, requestIpApp, response.getLastModified(), pullEvent, pullType, delayed, clientIp, notify, "grpc"); return response; } catch (Exception e) { LOGGER.error("Failed to handle grpc configuration query", e); return ConfigQueryResponse.buildFailResponse(ResponseCode.FAIL.getCode(), e.getMessage()); } } private ConfigQueryResponse handlerConfigConflict(String clientIp, String groupKey) { ConfigQueryResponse response = new ConfigQueryResponse(); PULL_LOG.info("[client-get] clientIp={}, {}, get data during dump", clientIp, groupKey); response.setErrorInfo(ConfigQueryResponse.CONFIG_QUERY_CONFLICT, "requested file is being modified, please try later."); return response; } private ConfigQueryResponse handlerConfigNotFound(String dataId, String group, String tenant, String requestIpApp, String clientIp, boolean notify) { //CacheItem No longer exists. It is impossible to simply calculate the push delayed. Here, simply record it as - 1. ConfigQueryResponse response = new ConfigQueryResponse(); ConfigTraceService.logPullEvent(dataId, group, tenant, requestIpApp, -1, ConfigTraceService.PULL_EVENT, ConfigTraceService.PULL_TYPE_NOTFOUND, -1, clientIp, notify, "grpc"); response.setErrorInfo(ConfigQueryResponse.CONFIG_NOT_FOUND, "config data not exist"); return response; } private String resolvePullEventType(ConfigQueryChainResponse chainResponse, String tag) { switch (chainResponse.getStatus()) { case CONFIG_FOUND_GRAY: ConfigCacheGray matchedGray = chainResponse.getMatchedGray(); if (matchedGray != null) { return ConfigTraceService.PULL_EVENT + "-" + matchedGray.getGrayName(); } else { return ConfigTraceService.PULL_EVENT; } case SPECIAL_TAG_CONFIG_NOT_FOUND: return ConfigTraceService.PULL_EVENT + "-" + TagGrayRule.TYPE_TAG + "-" + tag; default: return ConfigTraceService.PULL_EVENT; } } }
ConfigQueryRequestHandler
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestGetSpaceUsed.java
{ "start": 3782, "end": 4123 }
class ____ extends CachingGetSpaceUsed { public DummyDU(Builder builder) throws IOException { // Push to the base class. // Most times that's all that will need to be done. super(builder); } @Override protected void refresh() { // This is a test so don't du anything. } } private static
DummyDU
java
spring-projects__spring-security
oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AuthorizationGrantType.java
{ "start": 1384, "end": 3276 }
class ____ implements Serializable { private static final long serialVersionUID = 620L; public static final AuthorizationGrantType AUTHORIZATION_CODE = new AuthorizationGrantType("authorization_code"); public static final AuthorizationGrantType REFRESH_TOKEN = new AuthorizationGrantType("refresh_token"); public static final AuthorizationGrantType CLIENT_CREDENTIALS = new AuthorizationGrantType("client_credentials"); /** * @since 5.5 */ public static final AuthorizationGrantType JWT_BEARER = new AuthorizationGrantType( "urn:ietf:params:oauth:grant-type:jwt-bearer"); /** * @since 6.1 */ public static final AuthorizationGrantType DEVICE_CODE = new AuthorizationGrantType( "urn:ietf:params:oauth:grant-type:device_code"); /** * @since 6.3 */ public static final AuthorizationGrantType TOKEN_EXCHANGE = new AuthorizationGrantType( "urn:ietf:params:oauth:grant-type:token-exchange"); private final String value; /** * Constructs an {@code AuthorizationGrantType} using the provided value. * @param value the value of the authorization grant type */ public AuthorizationGrantType(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the authorization grant type. * @return the value of the authorization grant type */ public String getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } AuthorizationGrantType that = (AuthorizationGrantType) obj; return this.getValue().equals(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } @Override public String toString() { return "AuthorizationGrantType{" + "value='" + this.value + '\'' + '}'; } }
AuthorizationGrantType
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ConvertedListAttributeQueryTest.java
{ "start": 1062, "end": 3056 }
class ____ { private final static List<String> PHONE_NUMBERS = List.of( "0911 111 111", "0922 222 222" ); @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> session.persist( new Employee( 1, PHONE_NUMBERS ) ) ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> session.createMutationQuery( "delete from Employee" ) ); } @Test @SuppressWarnings( "rawtypes" ) public void testListHQL(SessionFactoryScope scope) { scope.inTransaction( session -> { final List resultList = session.createQuery( "select emp.phoneNumbers from Employee emp where emp.id = :EMP_ID", List.class ).setParameter( "EMP_ID", 1 ).getSingleResult(); assertThat( resultList ).isEqualTo( PHONE_NUMBERS ); } ); } @Test @SuppressWarnings( "rawtypes" ) public void testListCriteria(SessionFactoryScope scope) { scope.inTransaction( session -> { final CriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<List> q = cb.createQuery( List.class ); final Root<Employee> r = q.from( Employee.class ); q.select( r.get( "phoneNumbers" ) ); q.where( cb.equal( r.get( "id" ), 1 ) ); final List resultList = session.createQuery( q ).getSingleResult(); assertThat( resultList ).isEqualTo( PHONE_NUMBERS ); } ); } @Test public void testArrayCriteria(SessionFactoryScope scope) { scope.inTransaction( session -> { final CriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<Integer[]> q = cb.createQuery( Integer[].class ); final Root<Employee> r = q.from( Employee.class ); q.multiselect( r.get( "id" ), r.get( "id" ) ); q.where( cb.equal( r.get( "id" ), 1 ) ); final Object result = session.createQuery( q ).getSingleResult(); assertThat( result ).isInstanceOf( Object[].class ); assertThat( ( (Object[]) result ) ).containsExactly( 1, 1 ); } ); } @Entity( name = "Employee" ) public static
ConvertedListAttributeQueryTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-web-jsp/src/main/java/smoketest/jsp/WelcomeController.java
{ "start": 947, "end": 1343 }
class ____ { @Value("${application.message:Hello World}") private String message = "Hello World"; @GetMapping("/") public String welcome(Map<String, Object> model) { model.put("time", new Date()); model.put("message", this.message); return "welcome"; } @RequestMapping("/foo") public String foo(Map<String, Object> model) { throw new RuntimeException("Foo"); } }
WelcomeController
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/writeClassName/WriteClassNameTest_Collection.java
{ "start": 314, "end": 1149 }
class ____ extends TestCase { protected void setUp() throws Exception { com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.writeClassName.WriteClassNameTest_Collection"); } public void test_list() throws Exception { A a = new A(); a.setList(Collections.singletonList(new B())); String text = JSON.toJSONString(a, SerializerFeature.WriteClassName); System.out.println(text); Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.writeClassName.WriteClassNameTest_Collection$A\",\"list\":[{}]}", text); A a1 = (A) JSON.parse(text); Assert.assertEquals(1, a1.getList().size()); Assert.assertTrue(a1.getList().iterator().next() instanceof B); } private static
WriteClassNameTest_Collection
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh12076/Settlement.java
{ "start": 269, "end": 5002 }
class ____ { private Long _id; private Integer _version; private Date _creationDate; private Date _modifiedDate; private Boolean _override = false; private Boolean _started = false; private Boolean _taxable = false; private Double _units = 0.0; private Double _amount = 0.0; private Double _subtotal = 0.0; private Double _taxRate = 0.0; private Double _taxAmount = 0.0; private Double _goodwill = 0.0; private Double _totalAmount = 0.0; private Double _underinsuredAmount = 0.0; private Date _openDate; private Date _allocateDate; private Date _closeDate; private String _trackingId; private Claim _claim; private SettlementStatus _status = SettlementStatus.RESERVED; private Set<SettlementExtension> _extensions; private transient Map<Class<?>, SettlementExtension> _extensionMap; public Settlement() { _extensions = new HashSet<SettlementExtension>(); } public Long getId() { return _id; } protected 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 Claim getClaim() { return _claim; } public void setClaim(Claim claim) { _claim = claim; } public SettlementStatus getStatus() { return _status; } public void setStatus(SettlementStatus status) { _status = status; } public String getTrackingId() { return _trackingId; } public void setTrackingId(String trackingId) { _trackingId = trackingId; } public Double getUnits() { return _units; } public void setUnits(Double units) { _units = units; } public Double getAmount() { return _amount; } public void setAmount(Double amount) { _amount = amount; } public Double getTotalAmount() { return _totalAmount; } public void setTotalAmount(Double totalAmount) { _totalAmount = totalAmount; } public Date getCloseDate() { return _closeDate; } public void setCloseDate(Date settlementDate) { _closeDate = settlementDate; } public Set<SettlementExtension> getExtensions() { return _extensions; } public void setExtensions(Set<SettlementExtension> extensions) { _extensions = extensions; } public void addExtension(SettlementExtension extension) { if ( !hasExtension( extension.getClass() ) ) { if ( extension.getOrderIndex() == null ) { extension.setOrderIndex( _extensions.size() ); } extension.setSettlement( this ); _extensions.add( extension ); } } @SuppressWarnings("unchecked") public <X extends SettlementExtension> X getExtension(Class<X> extensionType) { if ( _extensionMap == null || _extensionMap.size() != _extensions.size() ) { Map<Class<?>, SettlementExtension> map = new HashMap<Class<?>, SettlementExtension>( _extensions.size() ); for ( SettlementExtension extension : _extensions ) { map.put( extension.getClass(), extension ); } _extensionMap = map; } return (X) _extensionMap.get( extensionType ); } public <X extends SettlementExtension> boolean hasExtension(Class<X> extensionType) { return getExtension( extensionType ) != null; } public Boolean isOverride() { return _override; } public void setOverride(Boolean override) { _override = override; } public Double getGoodwill() { return _goodwill; } public void setGoodwill(Double goodwill) { _goodwill = goodwill; } public Date getOpenDate() { return _openDate; } public void setOpenDate(Date startDate) { _openDate = startDate; } public Date getAllocateDate() { return _allocateDate; } public void setAllocateDate(Date allocateDate) { _allocateDate = allocateDate; } public Double getSubtotal() { return _subtotal; } public void setSubtotal(Double subtotal) { _subtotal = subtotal; } public Double getTaxRate() { return _taxRate; } public void setTaxRate(Double taxRate) { _taxRate = taxRate; } public Double getTaxAmount() { return _taxAmount; } public void setTaxAmount(Double taxAmount) { _taxAmount = taxAmount; } public Double getUnderinsuredAmount() { return _underinsuredAmount; } public void setUnderinsuredAmount(Double underinsuredAmount) { _underinsuredAmount = underinsuredAmount; } public Boolean isStarted() { return _started; } public void setStarted(Boolean started) { _started = started; } public Boolean isTaxable() { return _taxable; } public void setTaxable(Boolean taxable) { _taxable = taxable; } }
Settlement
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metagen/mappedsuperclass/idclass/AbstractAttributeId.java
{ "start": 335, "end": 513 }
class ____ implements Serializable { protected String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
AbstractAttributeId
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/expressions/ColumnReferenceFinder.java
{ "start": 4132, "end": 6332 }
class ____ extends ExpressionDefaultVisitor<Set<String>> { private final List<String> tableColumns; public ColumnReferenceVisitor(List<String> tableColumns) { this.tableColumns = tableColumns; } @Override public Set<String> visit(Expression expression) { if (expression instanceof LocalReferenceExpression) { return visit((LocalReferenceExpression) expression); } else if (expression instanceof FieldReferenceExpression) { return visit((FieldReferenceExpression) expression); } else if (expression instanceof RexNodeExpression) { return visit((RexNodeExpression) expression); } else if (expression instanceof CallExpression) { return visit((CallExpression) expression); } else { return super.visit(expression); } } @Override public Set<String> visit(FieldReferenceExpression fieldReference) { return Collections.singleton(fieldReference.getName()); } public Set<String> visit(LocalReferenceExpression localReference) { return Collections.singleton(localReference.getName()); } public Set<String> visit(RexNodeExpression rexNode) { // get the referenced column ref in table Set<RexInputRef> inputRefs = FlinkRexUtil.findAllInputRefs(rexNode.getRexNode()); // get the referenced column name by index return inputRefs.stream() .map(inputRef -> tableColumns.get(inputRef.getIndex())) .collect(Collectors.toSet()); } @Override public Set<String> visit(CallExpression call) { Set<String> references = new HashSet<>(); for (Expression expression : call.getChildren()) { references.addAll(visit(expression)); } return references; } @Override protected Set<String> defaultMethod(Expression expression) { throw new TableException("Unexpected expression: " + expression); } } }
ColumnReferenceVisitor
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/BlocklistDeclarativeSlotPool.java
{ "start": 2164, "end": 6584 }
class ____ extends DefaultDeclarativeSlotPool { private final BlockedTaskManagerChecker blockedTaskManagerChecker; BlocklistDeclarativeSlotPool( JobID jobId, AllocatedSlotPool slotPool, Consumer<? super Collection<ResourceRequirement>> notifyNewResourceRequirements, BlockedTaskManagerChecker blockedTaskManagerChecker, Duration idleSlotTimeout, Duration rpcTimeout, Duration slotRequestMaxInterval, ComponentMainThreadExecutor componentMainThreadExecutor) { super( jobId, slotPool, notifyNewResourceRequirements, idleSlotTimeout, rpcTimeout, slotRequestMaxInterval, componentMainThreadExecutor); this.blockedTaskManagerChecker = checkNotNull(blockedTaskManagerChecker); } @Override public Collection<SlotOffer> offerSlots( Collection<? extends SlotOffer> offers, TaskManagerLocation taskManagerLocation, TaskManagerGateway taskManagerGateway, long currentTime) { if (!isBlockedTaskManager(taskManagerLocation.getResourceID())) { return super.offerSlots(offers, taskManagerLocation, taskManagerGateway, currentTime); } else { return internalOfferSlotsFromBlockedTaskManager(offers, taskManagerLocation); } } @Override public Collection<SlotOffer> registerSlots( Collection<? extends SlotOffer> slots, TaskManagerLocation taskManagerLocation, TaskManagerGateway taskManagerGateway, long currentTime) { if (!isBlockedTaskManager(taskManagerLocation.getResourceID())) { return super.registerSlots(slots, taskManagerLocation, taskManagerGateway, currentTime); } else { return internalOfferSlotsFromBlockedTaskManager(slots, taskManagerLocation); } } private Collection<SlotOffer> internalOfferSlotsFromBlockedTaskManager( Collection<? extends SlotOffer> offers, TaskManagerLocation taskManagerLocation) { final Collection<SlotOffer> acceptedSlotOffers = new ArrayList<>(); final Collection<SlotOffer> rejectedSlotOffers = new ArrayList<>(); // we should accept a duplicate (already accepted) slot, even if it's from a currently // blocked task manager. Because the slot may already be assigned to an execution, rejecting // it will cause a task failover. for (SlotOffer offer : offers) { if (slotPool.containsSlot(offer.getAllocationId())) { // we have already accepted this offer acceptedSlotOffers.add(offer); } else { rejectedSlotOffers.add(offer); } } log.debug( "Received {} slots from a blocked TaskManager {}, {} was accepted before: {}, {} was rejected: {}.", offers.size(), taskManagerLocation, acceptedSlotOffers.size(), acceptedSlotOffers, rejectedSlotOffers.size(), rejectedSlotOffers); return acceptedSlotOffers; } @Override public ResourceCounter freeReservedSlot( AllocationID allocationId, @Nullable Throwable cause, long currentTime) { Optional<SlotInfo> slotInfo = slotPool.getSlotInformation(allocationId); if (!slotInfo.isPresent()) { return ResourceCounter.empty(); } ResourceID taskManagerId = slotInfo.get().getTaskManagerLocation().getResourceID(); if (!isBlockedTaskManager(taskManagerId)) { return super.freeReservedSlot(allocationId, cause, currentTime); } else { log.debug("Free reserved slot {}.", allocationId); return releaseSlot( allocationId, new FlinkRuntimeException( String.format( "Free reserved slot %s on blocked task manager %s.", allocationId, taskManagerId.getStringWithMetadata()))); } } private boolean isBlockedTaskManager(ResourceID resourceID) { return blockedTaskManagerChecker.isBlockedTaskManager(resourceID); } }
BlocklistDeclarativeSlotPool
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ForEachIterableTest.java
{ "start": 6612, "end": 7140 }
class ____<V> implements Iterable<V> { @Override public Iterator<V> iterator() { return null; } void test() { Iterator<V> iter = iterator(); while (iter.hasNext()) { iter.next(); } } } """) .addOutputLines( "out/Test.java", """ import java.util.Iterator; import java.lang.Iterable;
Test
java
apache__avro
lang/java/perf/src/main/java/org/apache/avro/perf/test/reflect/ReflectNestedObjectArrayTest.java
{ "start": 4967, "end": 5025 }
class ____ { BasicRecord[] value; } }
ObjectArrayWrapper
java
apache__camel
components/camel-google/camel-google-calendar/src/test/java/org/apache/camel/component/google/calendar/CalendarFreebusyIT.java
{ "start": 1811, "end": 3275 }
class ____ extends AbstractGoogleCalendarTestSupport { private static final Logger LOG = LoggerFactory.getLogger(CalendarFreebusyIT.class); private static final String PATH_PREFIX = GoogleCalendarApiCollection.getCollection().getApiName(CalendarFreebusyApiMethod.class).getName(); @Test public void testQuery() { // using com.google.api.services.calendar.model.FreeBusyRequest message // body for single parameter "content" com.google.api.services.calendar.model.FreeBusyRequest request = new FreeBusyRequest(); List<FreeBusyRequestItem> items = new ArrayList<>(); items.add(new FreeBusyRequestItem().setId(getCalendar().getId())); request.setItems(items); request.setTimeMin(DateTime.parseRfc3339("2014-11-10T20:45:30-00:00")); request.setTimeMax(DateTime.parseRfc3339("2014-11-10T21:45:30-00:00")); final com.google.api.services.calendar.model.FreeBusyResponse result = requestBody("direct://QUERY", request); assertNotNull(result, "query result"); LOG.debug("query: {}", result); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // test route for query from("direct://QUERY").to("google-calendar://" + PATH_PREFIX + "/query?inBody=content"); } }; } }
CalendarFreebusyIT
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/event/EagerTestExecutionEventPublishingTests.java
{ "start": 4121, "end": 4426 }
class ____.class, // PrepareTestInstanceEvent.class, // BeforeTestMethodEvent.class, // BeforeTestExecutionEvent.class, // AfterTestExecutionEvent.class, // AfterTestMethodEvent.class, // AfterTestClassEvent.class// ); } @SpringJUnitConfig(Config.class) static
BeforeTestClassEvent
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/jdk8/OptionalnclusionTest.java
{ "start": 627, "end": 757 }
class ____ { public Optional<String> myString = Optional.empty(); } // for [datatype-jdk8#18] static
OptionalData
java
apache__camel
components/camel-mail/src/test/java/org/apache/camel/component/mail/SearchTermBuilderTest.java
{ "start": 1441, "end": 5066 }
class ____ { @Test public void testSearchTermBuilderFromAndSubject() throws Exception { SearchTermBuilder build = new SearchTermBuilder(); SearchTerm st = build.from("someone@somewhere.com").subject("Camel").build(); assertNotNull(st); // create dummy message Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); MimeMessage msg = new MimeMessage(sender.getSession()); msg.setSubject("Yeah Camel rocks"); msg.setText("Apache Camel is a cool project. Have a fun ride."); msg.setFrom(new InternetAddress("someone@somewhere.com")); assertTrue(st.match(msg), "Should match message"); MimeMessage msg2 = new MimeMessage(sender.getSession()); msg2.setSubject("Apache Camel is fantastic"); msg2.setText("I like Camel."); msg2.setFrom(new InternetAddress("donotreply@somewhere.com")); assertFalse(st.match(msg2), "Should not match message, as from doesn't match"); } @Test public void testSearchTermBuilderFromOrSubject() throws Exception { SearchTermBuilder build = new SearchTermBuilder(); SearchTerm st = build.subject("Camel").from(or, "admin@apache.org").build(); assertNotNull(st); // create dummy message Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); MimeMessage msg = new MimeMessage(sender.getSession()); msg.setSubject("Yeah Camel rocks"); msg.setText("Apache Camel is a cool project. Have a fun ride."); msg.setFrom(new InternetAddress("someone@somewhere.com")); assertTrue(st.match(msg), "Should match message"); MimeMessage msg2 = new MimeMessage(sender.getSession()); msg2.setSubject("Beware"); msg2.setText("This is from the administrator."); msg2.setFrom(new InternetAddress("admin@apache.org")); assertTrue(st.match(msg2), "Should match message, as its from admin"); } @Test public void testSearchTermSentLast24Hours() throws Exception { SearchTermBuilder build = new SearchTermBuilder(); long offset = -1 * (24 * 60 * 60 * 1000L); SearchTerm st = build.subject("Camel").sentNow(Comparison.GE, offset).build(); assertNotNull(st); // create dummy message Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); MimeMessage msg = new MimeMessage(sender.getSession()); msg.setSubject("Yeah Camel rocks"); msg.setText("Apache Camel is a cool project. Have a fun ride."); msg.setFrom(new InternetAddress("someone@somewhere.com")); msg.setSentDate(new Date()); assertTrue(st.match(msg), "Should match message"); MimeMessage msg2 = new MimeMessage(sender.getSession()); msg2.setSubject("Camel in Action"); msg2.setText("Hey great book"); msg2.setFrom(new InternetAddress("dude@apache.org")); // mark it as sent 2 days ago long twoDays = 2 * 24 * 60 * 60 * 1000L; long time = new Date().getTime() - twoDays; msg2.setSentDate(new Date(time)); assertFalse(st.match(msg2), "Should not match message as its too old"); } @Test public void testComparison() { assertEquals(1, Comparison.LE.asNum()); assertEquals(2, Comparison.LT.asNum()); assertEquals(3, Comparison.EQ.asNum()); assertEquals(4, Comparison.NE.asNum()); assertEquals(5, Comparison.GT.asNum()); assertEquals(6, Comparison.GE.asNum()); } }
SearchTermBuilderTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitiveTest.java
{ "start": 3680, "end": 3955 }
class ____ { void f() { long x = 3; int y = Objects.hashCode(x); } } """) .addOutputLines( "Test.java", """ import java.util.Objects;
Test
java
hibernate__hibernate-orm
tooling/hibernate-gradle-plugin/src/test/java/org/hibernate/orm/tooling/gradle/JavaProjectTests.java
{ "start": 306, "end": 929 }
class ____ extends TestsBase { @Override protected String getProjectName() { return "simple"; } @Override protected String getSourceSetName() { return "main"; } @Override protected String getLanguageName() { return "java"; } @Override protected String getCompileTaskName() { return "compileJava"; } @Test @Override public void testEnhancement(@TempDir Path projectDir) throws Exception { super.testEnhancement( projectDir ); } @Test @Override public void testEnhancementUpToDate(@TempDir Path projectDir) throws Exception { super.testEnhancementUpToDate( projectDir ); } }
JavaProjectTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/logger/NetworkActionsLogger.java
{ "start": 1444, "end": 1479 }
class ____ method names. */ public
and
java
elastic__elasticsearch
x-pack/plugin/transform/qa/single-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/transform/integration/TransformRestTestCase.java
{ "start": 1620, "end": 30937 }
class ____ extends TransformCommonRestTestCase { protected static final String TEST_PASSWORD = "x-pack-test-password"; protected static final SecureString TEST_PASSWORD_SECURE_STRING = new SecureString(TEST_PASSWORD.toCharArray()); protected static final String TEST_USER_NAME = "transform_user"; protected static final String BASIC_AUTH_VALUE_TRANSFORM_USER = basicAuthHeaderValue(TEST_USER_NAME, TEST_PASSWORD_SECURE_STRING); protected static final String TEST_ADMIN_USER_NAME = "transform_admin"; protected static final String BASIC_AUTH_VALUE_TRANSFORM_ADMIN = basicAuthHeaderValue( TEST_ADMIN_USER_NAME, TEST_PASSWORD_SECURE_STRING ); private static final String BASIC_AUTH_VALUE_SUPER_USER = basicAuthHeaderValue("x_pack_rest_user", TEST_PASSWORD_SECURE_STRING); protected static final String REVIEWS_INDEX_NAME = "reviews"; protected static final String REVIEWS_DATE_NANO_INDEX_NAME = "reviews_nano"; @Override protected Settings restClientSettings() { return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", BASIC_AUTH_VALUE_SUPER_USER).build(); } protected void createReviewsIndex( String indexName, int numDocs, int numUsers, String dateType, boolean isDataStream, int userWithMissingBuckets, String missingBucketField ) throws IOException { putReviewsIndex(indexName, dateType, isDataStream); int[] distributionTable = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 1, 1, 1 }; // create index final StringBuilder bulk = new StringBuilder(); int day = 10; int hour = 10; int min = 10; for (int i = 0; i < numDocs; i++) { bulk.append(Strings.format(""" {"create":{"_index":"%s"}} """, indexName)); long user = Math.round(Math.pow(i * 31 % 1000, distributionTable[i % distributionTable.length]) % numUsers); int stars = distributionTable[(i * 33) % distributionTable.length]; long business = Math.round(Math.pow(user * stars, distributionTable[i % distributionTable.length]) % 13); long affiliate = Math.round(Math.pow(user * stars, distributionTable[i % distributionTable.length]) % 11); if (i % 12 == 0) { hour = 10 + (i % 13); } if (i % 5 == 0) { min = 10 + (i % 49); } int sec = 10 + (i % 49); String location = (((user + 10) % 180) - 90) + "," + (((user + 15) % 360) - 180); String date_string = "2017-01-" + day + "T" + hour + ":" + min + ":" + sec; if (dateType.equals("date_nanos")) { String randomNanos = "," + randomIntBetween(100000000, 999999999); date_string += randomNanos; } date_string += "Z"; bulk.append("{"); if ((user == userWithMissingBuckets && missingBucketField.equals("user_id")) == false) { bulk.append("\"user_id\":\"").append("user_").append(user).append("\","); } if ((user == userWithMissingBuckets && missingBucketField.equals("business_id")) == false) { bulk.append("\"business_id\":\"").append("business_").append(business).append("\","); } if ((user == userWithMissingBuckets && missingBucketField.equals("stars")) == false) { bulk.append("\"stars\":").append(stars).append(","); } if ((user == userWithMissingBuckets && missingBucketField.equals("stars_stats")) == false) { bulk.append("\"stars_stats\": { ") .append("\"min\": ") .append(stars - 1) .append(",") .append("\"max\": ") .append(stars + 1) .append(",") .append("\"sum\": ") .append(10 * stars) .append("},"); } if ((user == userWithMissingBuckets && missingBucketField.equals("location")) == false) { bulk.append("\"location\":\"").append(location).append("\","); } if ((user == userWithMissingBuckets && missingBucketField.equals("timestamp")) == false) { bulk.append("\"timestamp\":\"").append(date_string).append("\","); } if ((user == userWithMissingBuckets && missingBucketField.equals("affiliate_id")) == false) { bulk.append("\"affiliate_id\":\"").append("affiliate_").append(affiliate).append("\","); } // always add @timestamp to avoid complicated logic regarding ',' bulk.append("\"@timestamp\":\"").append(date_string).append("\""); bulk.append("}\n"); if (i % 50 == 0) { bulk.append("\r\n"); doBulk(bulk.toString(), true); // clear the builder bulk.setLength(0); day += 1; } } bulk.append("\r\n"); doBulk(bulk.toString(), true); } @SuppressWarnings("unchecked") protected void doBulk(String bulkDocuments, boolean refresh) throws IOException { Request bulkRequest = new Request("POST", "/_bulk"); if (refresh) { bulkRequest.addParameter("refresh", "true"); } bulkRequest.setJsonEntity(bulkDocuments); bulkRequest.setOptions(RequestOptions.DEFAULT); Response bulkResponse = client().performRequest(bulkRequest); assertOK(bulkResponse); var bulkMap = entityAsMap(bulkResponse); var hasErrors = (boolean) bulkMap.get("errors"); if (hasErrors) { var items = (List<Map<String, Object>>) bulkMap.get("items"); fail("Bulk item failures: " + items.toString()); } } protected void putReviewsIndex(String indexName, String dateType, boolean isDataStream) throws IOException { // create mapping try (XContentBuilder builder = jsonBuilder()) { builder.startObject(); { builder.startObject("mappings").startObject("properties"); builder.startObject("@timestamp").field("type", dateType); if (dateType.equals("date_nanos")) { builder.field("format", "strict_date_optional_time_nanos"); } builder.endObject(); builder.startObject("timestamp").field("type", dateType); if (dateType.equals("date_nanos")) { builder.field("format", "strict_date_optional_time_nanos"); } builder.endObject() .startObject("user_id") .field("type", "keyword") .endObject() .startObject("business_id") .field("type", "keyword") .endObject() .startObject("stars") .field("type", randomFrom("integer", "long")) // gh#64347 unsigned_long disabled .endObject() .startObject("stars_stats") .field("type", "aggregate_metric_double") .field("metrics", List.of("min", "max", "sum")) .field("default_metric", "max") .endObject() .startObject("location") .field("type", "geo_point") .endObject() .startObject("affiliate_id") .field("type", "keyword") .endObject() .endObject() .endObject(); } builder.endObject(); if (isDataStream) { Request createCompositeTemplate = new Request("PUT", "_index_template/" + indexName + "_template"); createCompositeTemplate.setJsonEntity(Strings.format(""" { "index_patterns": [ "%s" ], "data_stream": { }, "template": %s }""", indexName, Strings.toString(builder))); client().performRequest(createCompositeTemplate); client().performRequest(new Request("PUT", "_data_stream/" + indexName)); } else { final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON); Request req = new Request("PUT", indexName); req.setEntity(entity); client().performRequest(req); } } } /** * Create a simple dataset for testing with reviewers, ratings and businesses */ protected void createReviewsIndex() throws IOException { createReviewsIndex(REVIEWS_INDEX_NAME); } protected void createReviewsIndex(String indexName) throws IOException { createReviewsIndex(indexName, 1000, 27, "date", false, 5, "affiliate_id"); } protected void createPivotReviewsTransform(String transformId, String transformIndex, String query) throws IOException { createPivotReviewsTransform(transformId, transformIndex, query, null, null); } protected void createReviewsIndexNano() throws IOException { createReviewsIndex(REVIEWS_DATE_NANO_INDEX_NAME, 1000, 27, "date_nanos", false, -1, null); } protected void createContinuousPivotReviewsTransform(String transformId, String transformIndex, String authHeader) throws IOException { // Set frequency high for testing createContinuousPivotReviewsTransform(transformId, transformIndex, authHeader, "1s"); } protected void createContinuousPivotReviewsTransform(String transformId, String transformIndex, String authHeader, String frequency) throws IOException { String config = Strings.format(""" { "dest": { "index": "%s" }, "source": { "index": "%s" }, "sync": { "time": { "field": "timestamp", "delay": "15m" } }, "frequency": "%s", "pivot": { "group_by": { "reviewer": { "terms": { "field": "user_id" } } }, "aggregations": { "avg_rating": { "avg": { "field": "stars" } } } } }""", transformIndex, REVIEWS_INDEX_NAME, frequency); createReviewsTransform(transformId, authHeader, null, config); } protected void createPivotReviewsTransform( String transformId, String transformIndex, String query, String pipeline, List<DestAlias> destAliases, SettingsConfig settings, String authHeader, String secondaryAuthHeader, String sourceIndex ) throws IOException { String config = "{"; String destConfig = Strings.format(""" "dest": {"index":"%s" """, transformIndex); if (pipeline != null) { destConfig += Strings.format(""" , "pipeline":"%s" """, pipeline); } if (destAliases != null && destAliases.isEmpty() == false) { destConfig += ", \"aliases\":["; destConfig += String.join(",", destAliases.stream().map(Strings::toString).toList()); destConfig += "]"; } destConfig += "},"; config += destConfig; if (query != null) { config += Strings.format(""" "source": {"index":"%s", "query":{%s}},""", sourceIndex, query); } else { config += Strings.format(""" "source": {"index":"%s"},""", sourceIndex); } if (settings != null) { config += "\"settings\": " + Strings.toString(settings) + ","; } config += """ "pivot": { "group_by": { "reviewer": { "terms": { "field": "user_id" } } }, "aggregations": { "avg_rating": { "avg": { "field": "stars" } }, "affiliate_missing": { "missing": { "field": "affiliate_id" } }, "stats": { "stats": { "field": "stars" } } } }, "frequency": "1s" }"""; createReviewsTransform(transformId, authHeader, secondaryAuthHeader, config); } protected void createLatestReviewsTransform(String transformId, String transformIndex) throws IOException { String config = Strings.format(""" { "dest": { "index": "%s" }, "source": { "index": "%s" }, "latest": { "unique_key": [ "user_id" ], "sort": "@timestamp" }, "frequency": "1s" }""", transformIndex, REVIEWS_INDEX_NAME); createReviewsTransform(transformId, null, null, config); } protected void createReviewsTransform(String transformId, String authHeader, String secondaryAuthHeader, String config) throws IOException { final Request createTransformRequest = createRequestWithSecondaryAuth( "PUT", getTransformEndpoint() + transformId, authHeader, secondaryAuthHeader ); createTransformRequest.setJsonEntity(config); Map<String, Object> createTransformResponse = entityAsMap(client().performRequest(createTransformRequest)); assertThat(createTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); } protected void createPivotReviewsTransform(String transformId, String transformIndex, String query, String pipeline, String authHeader) throws IOException { createPivotReviewsTransform(transformId, transformIndex, query, pipeline, null, null, authHeader, null, REVIEWS_INDEX_NAME); } protected void updateTransform(String transformId, String update, boolean deferValidation) throws IOException { final Request updateTransformRequest = createRequestWithSecondaryAuth( "POST", getTransformEndpoint() + transformId + "/_update", null, null ); if (deferValidation) { updateTransformRequest.addParameter("defer_validation", String.valueOf(deferValidation)); } updateTransformRequest.setJsonEntity(update); assertOKAndConsume(client().performRequest(updateTransformRequest)); } protected void startTransform(String transformId) throws IOException { startTransform(transformId, null, null, null); } protected void startTransform(String transformId, String authHeader, String secondaryAuthHeader, String from, String... warnings) throws IOException { // start the transform final Request startTransformRequest = createRequestWithSecondaryAuth( "POST", getTransformEndpoint() + transformId + "/_start", authHeader, secondaryAuthHeader ); if (from != null) { startTransformRequest.addParameter(TransformField.FROM.getPreferredName(), from); } if (warnings.length > 0) { startTransformRequest.setOptions(expectWarnings(warnings)); } Map<String, Object> startTransformResponse = entityAsMap(client().performRequest(startTransformRequest)); assertThat(startTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); } protected void stopTransform(String transformId, boolean force) throws Exception { stopTransform(transformId, force, false); } protected void stopTransform(String transformId, boolean force, boolean waitForCheckpoint) throws Exception { stopTransform(transformId, null, force, false); } protected void stopTransform(String transformId, String authHeader, boolean force, boolean waitForCheckpoint) throws Exception { final Request stopTransformRequest = createRequestWithAuth("POST", getTransformEndpoint() + transformId + "/_stop", authHeader); stopTransformRequest.addParameter(TransformField.FORCE.getPreferredName(), Boolean.toString(force)); stopTransformRequest.addParameter(TransformField.WAIT_FOR_COMPLETION.getPreferredName(), Boolean.toString(true)); stopTransformRequest.addParameter(TransformField.WAIT_FOR_CHECKPOINT.getPreferredName(), Boolean.toString(waitForCheckpoint)); Map<String, Object> stopTransformResponse = entityAsMap(client().performRequest(stopTransformRequest)); assertThat(stopTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); } protected void startAndWaitForTransform(String transformId, String transformIndex) throws Exception { startAndWaitForTransform(transformId, transformIndex, null); } protected void startAndWaitForTransform(String transformId, String transformIndex, String authHeader) throws Exception { startAndWaitForTransform(transformId, transformIndex, authHeader, new String[0]); } protected void startAndWaitForTransform(String transformId, String transformIndex, String authHeader, String... warnings) throws Exception { startAndWaitForTransform(transformId, transformIndex, authHeader, null, warnings); } protected void startAndWaitForTransform( String transformId, String transformIndex, String authHeader, String secondaryAuthHeader, String... warnings ) throws Exception { // start the transform startTransform(transformId, authHeader, secondaryAuthHeader, null, warnings); assertTrue(indexExists(transformIndex)); assertBusy(() -> { Map<?, ?> transformStatsAsMap = getTransformStateAndStats(transformId); // wait until the transform has been created and all data is available assertEquals( "Stats were: " + transformStatsAsMap, 1, XContentMapValues.extractValue("checkpointing.last.checkpoint", transformStatsAsMap) ); // wait until the transform is stopped assertEquals("Stats were: " + transformStatsAsMap, "stopped", XContentMapValues.extractValue("state", transformStatsAsMap)); }, 30, TimeUnit.SECONDS); refreshIndex(transformIndex); } protected void startAndWaitForContinuousTransform(String transformId, String transformIndex, String authHeader) throws Exception { startAndWaitForContinuousTransform(transformId, transformIndex, authHeader, null, 1L); } protected void startAndWaitForContinuousTransform( String transformId, String transformIndex, String authHeader, String from, long checkpoint ) throws Exception { // start the transform startTransform(transformId, authHeader, null, from, new String[0]); assertTrue(indexExists(transformIndex)); // wait until the transform has been created and all data is available waitForTransformCheckpoint(transformId, checkpoint); refreshIndex(transformIndex); } protected void resetTransform(String transformId, boolean force) throws IOException { final Request resetTransformRequest = createRequestWithAuth("POST", getTransformEndpoint() + transformId + "/_reset", null); resetTransformRequest.addParameter(TransformField.FORCE.getPreferredName(), Boolean.toString(force)); Map<String, Object> resetTransformResponse = entityAsMap(client().performRequest(resetTransformRequest)); assertThat(resetTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); } protected void scheduleNowTransform(String transformId) throws IOException { final Request scheduleNowTransformRequest = createRequestWithAuth( "POST", getTransformEndpoint() + transformId + "/_schedule_now", null ); Map<String, Object> scheduleNowTransformResponse = entityAsMap(client().performRequest(scheduleNowTransformRequest)); assertThat(scheduleNowTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); } protected Request createRequestWithSecondaryAuth( final String method, final String endpoint, final String authHeader, final String secondaryAuthHeader ) { final Request request = new Request(method, endpoint); RequestOptions.Builder options = request.getOptions().toBuilder(); if (authHeader != null) { options.addHeader(AUTH_KEY, authHeader); } if (secondaryAuthHeader != null) { options.addHeader(SECONDARY_AUTH_KEY, secondaryAuthHeader); } request.setOptions(options); return request; } protected Request createRequestWithAuth(final String method, final String endpoint, final String authHeader) { return createRequestWithSecondaryAuth(method, endpoint, authHeader, null); } void waitForTransformCheckpoint(String transformId, long checkpoint) throws Exception { assertBusy(() -> { Map<?, ?> transformStatsAsMap = getTransformStateAndStats(transformId); assertNotEquals("Stats were: " + transformStatsAsMap, "failed", XContentMapValues.extractValue("state", transformStatsAsMap)); assertEquals( "Stats were: " + transformStatsAsMap, (int) checkpoint, XContentMapValues.extractValue("checkpointing.last.checkpoint", transformStatsAsMap) ); }, 30, TimeUnit.SECONDS); } @SuppressWarnings("unchecked") protected static List<Map<String, Object>> getTransforms(List<Map<String, String>> expectedErrors) throws IOException { Request request = new Request("GET", getTransformEndpoint() + "_all"); Response response = adminClient().performRequest(request); Map<String, Object> transforms = entityAsMap(response); List<Map<String, Object>> transformConfigs = (List<Map<String, Object>>) XContentMapValues.extractValue("transforms", transforms); List<Map<String, String>> errors = (List<Map<String, String>>) XContentMapValues.extractValue("errors", transforms); assertThat(errors, is(equalTo(expectedErrors))); return transformConfigs == null ? Collections.emptyList() : transformConfigs; } @SuppressWarnings("unchecked") protected static Map<String, Object> getTransforms(int from, int size) throws IOException { Request request = new Request("GET", getTransformEndpoint() + "_all?from=" + from + "&size=" + size); Response response = adminClient().performRequest(request); return entityAsMap(response); } protected Map<String, Object> getTransformConfig(String transformId, String authHeader) throws IOException { Request getRequest = createRequestWithAuth("GET", getTransformEndpoint() + transformId, authHeader); Map<String, Object> transforms = entityAsMap(client().performRequest(getRequest)); assertEquals(1, XContentMapValues.extractValue("count", transforms)); @SuppressWarnings("unchecked") Map<String, Object> transformConfig = ((List<Map<String, Object>>) transforms.get("transforms")).get(0); return transformConfig; } @SuppressWarnings("unchecked") protected Map<String, Object> getTransformConfig(String transformId, String authHeader, List<Map<String, String>> expectedErrors) throws IOException { Request getRequest = createRequestWithAuth("GET", getTransformEndpoint() + transformId, authHeader); Map<String, Object> transforms = entityAsMap(client().performRequest(getRequest)); assertEquals(1, XContentMapValues.extractValue("count", transforms)); List<Map<String, String>> errors = (List<Map<String, String>>) XContentMapValues.extractValue("errors", transforms); assertThat(errors, is(equalTo(expectedErrors))); return ((List<Map<String, Object>>) transforms.get("transforms")).get(0); } protected static String getTransformState(String transformId) throws IOException { Map<?, ?> transformStatsAsMap = getTransformStateAndStats(transformId); return transformStatsAsMap == null ? null : (String) XContentMapValues.extractValue("state", transformStatsAsMap); } protected static Map<?, ?> getTransformStateAndStats(String transformId) throws IOException { Response statsResponse = client().performRequest(new Request("GET", getTransformEndpoint() + transformId + "/_stats")); List<?> transforms = ((List<?>) entityAsMap(statsResponse).get("transforms")); if (transforms.isEmpty()) { return null; } return (Map<?, ?>) transforms.get(0); } protected static Map<String, Object> getTransformsStateAndStats(int from, int size) throws IOException { Response statsResponse = client().performRequest( new Request("GET", getTransformEndpoint() + "_stats?from=" + from + "&size=" + size) ); return entityAsMap(statsResponse); } protected static void deleteTransform(String transformId) throws IOException { // Ignore 404s because they imply someone was racing us to delete this transform. deleteTransform(transformId, true, false); } protected static void deleteTransform(String transformId, boolean ignoreNotFound, boolean deleteDestIndex) throws IOException { Request request = new Request("DELETE", getTransformEndpoint() + transformId); if (ignoreNotFound) { setIgnoredErrorResponseCodes(request, RestStatus.NOT_FOUND); } if (deleteDestIndex) { request.addParameter(TransformField.DELETE_DEST_INDEX.getPreferredName(), Boolean.TRUE.toString()); } adminClient().performRequest(request); } @After public void waitForTransform() throws Exception { ensureNoInitializingShards(); logAudits(); } @AfterClass public static void removeIndices() throws Exception { // we might have disabled wiping indices, but now its time to get rid of them // note: can not use super.cleanUpCluster() as this method must be static wipeAllIndices(); } protected void setupDataAccessRole(String role, String... indices) throws IOException { String indicesStr = Arrays.stream(indices).collect(Collectors.joining("\",\"", "\"", "\"")); Request request = new Request("PUT", "/_security/role/" + role); request.setJsonEntity(Strings.format(""" { "indices": [ { "names": [ %s ], "privileges": [ "create_index", "delete_index", "read", "write", "view_index_metadata", "manage" ] } ] }""", indicesStr)); client().performRequest(request); } protected void setupUser(String user, List<String> roles) throws IOException { String password = new String(TEST_PASSWORD_SECURE_STRING.getChars()); String rolesStr = roles.stream().collect(Collectors.joining("\",\"", "\"", "\"")); Request request = new Request("PUT", "/_security/user/" + user); request.setJsonEntity(Strings.format(""" { "password" : "%s", "roles" : [ %s ]} """, password, rolesStr)); client().performRequest(request); } protected void assertOnePivotValue(String query, double expected) throws IOException { Map<String, Object> searchResult = getAsMap(query); assertEquals(1, XContentMapValues.extractValue("hits.total.value", searchResult)); double actual = (Double) ((List<?>) XContentMapValues.extractValue("hits.hits._source.avg_rating", searchResult)).get(0); assertEquals(expected, actual, 0.000001); } protected void assertOneCount(String query, String field, int expected) throws IOException { Map<String, Object> searchResult = getAsMap(query); assertEquals(1, XContentMapValues.extractValue("hits.total.value", searchResult)); int actual = (Integer) ((List<?>) XContentMapValues.extractValue(field, searchResult)).get(0); assertEquals(expected, actual); } }
TransformRestTestCase
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/odps/ast/OdpsDeclareVariableStatement.java
{ "start": 211, "end": 1358 }
class ____ extends OdpsStatementImpl { private String variant; private SQLDataType dataType; private SQLExpr initValue; public OdpsDeclareVariableStatement() { } public OdpsDeclareVariableStatement(String variant, SQLExpr initValue) { this.variant = variant; this.initValue = initValue; } @Override protected void accept0(OdpsASTVisitor v) { if (v.visit(this)) { acceptChild(v, dataType); acceptChild(v, initValue); } v.endVisit(this); } public String getVariant() { return variant; } public void setVariant(String variant) { this.variant = variant; } public SQLExpr getInitValue() { return initValue; } public void setInitValue(SQLExpr x) { if (x != null) { x.setParent(this); } this.initValue = x; } public SQLDataType getDataType() { return dataType; } public void setDataType(SQLDataType x) { if (x != null) { x.setParent(this); } this.dataType = x; } }
OdpsDeclareVariableStatement
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/ids/EmbIdWithCustomTypeTestEntity.java
{ "start": 409, "end": 1520 }
class ____ { @EmbeddedId private EmbIdWithCustomType id; @Audited private String str1; public EmbIdWithCustomTypeTestEntity() { } public EmbIdWithCustomTypeTestEntity(EmbIdWithCustomType id, String str1) { this.id = id; this.str1 = str1; } public EmbIdWithCustomType getId() { return id; } public void setId(EmbIdWithCustomType id) { this.id = id; } public String getStr1() { return str1; } public void setStr1(String str1) { this.str1 = str1; } public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( !(obj instanceof EmbIdWithCustomTypeTestEntity) ) { return false; } EmbIdWithCustomTypeTestEntity that = (EmbIdWithCustomTypeTestEntity) obj; if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { return false; } return true; } public int hashCode() { int result; result = (id != null ? id.hashCode() : 0); result = 31 * result + (str1 != null ? str1.hashCode() : 0); return result; } }
EmbIdWithCustomTypeTestEntity
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/SocketOptionsUnitTests.java
{ "start": 1158, "end": 3661 }
class ____ { @Test void testNew() { checkAssertions(SocketOptions.create()); } @Test void testBuilder() { SocketOptions sut = SocketOptions.builder().connectTimeout(1, TimeUnit.MINUTES).keepAlive(true).tcpNoDelay(false) .build(); assertThat(sut.isKeepAlive()).isTrue(); assertThat(sut.isTcpNoDelay()).isFalse(); assertThat(sut.getConnectTimeout()).isEqualTo(Duration.ofMinutes(1)); } @Test void mutateShouldConfigureNewOptions() { SocketOptions sut = SocketOptions.builder().connectTimeout(Duration.ofSeconds(1)).keepAlive(true).tcpNoDelay(true) .build(); SocketOptions reconfigured = sut.mutate().tcpNoDelay(false).build(); assertThat(sut.isKeepAlive()).isTrue(); assertThat(sut.isTcpNoDelay()).isTrue(); assertThat(sut.getConnectTimeout()).isEqualTo(Duration.ofSeconds(1)); assertThat(reconfigured.isTcpNoDelay()).isFalse(); } @Test void shouldConfigureSimpleKeepAlive() { SocketOptions sut = SocketOptions.builder().keepAlive(true).build(); assertThat(sut.isKeepAlive()).isTrue(); assertThat(sut.isExtendedKeepAlive()).isFalse(); } @Test void shouldConfigureSimpleExtendedAlive() { SocketOptions sut = SocketOptions.builder().keepAlive(SocketOptions.KeepAliveOptions.builder().build()).build(); assertThat(sut.isKeepAlive()).isFalse(); assertThat(sut.isExtendedKeepAlive()).isTrue(); } @Test void testCopy() { checkAssertions(SocketOptions.copyOf(SocketOptions.builder().build())); } void checkAssertions(SocketOptions sut) { assertThat(sut.isKeepAlive()).isFalse(); assertThat(sut.isTcpNoDelay()).isTrue(); assertThat(sut.getConnectTimeout()).isEqualTo(Duration.ofSeconds(10)); } @Test void testDefaultTcpUserTimeoutOption() { SocketOptions sut = SocketOptions.builder().build(); assertThat(sut.isEnableTcpUserTimeout()).isFalse(); } @Test void testConfigTcpUserTimeoutOption() { SocketOptions sut = SocketOptions.builder() .tcpUserTimeout(TcpUserTimeoutOptions.builder().enable().tcpUserTimeout(Duration.ofSeconds(60)).build()) .build(); assertThat(sut.isEnableTcpUserTimeout()).isTrue(); assertThat(sut.getTcpUserTimeout().getTcpUserTimeout()).isEqualTo(Duration.ofSeconds(60)); } }
SocketOptionsUnitTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/sort/BucketedSort.java
{ "start": 19044, "end": 21515 }
class ____ extends BucketedSort { /** * The maximum size of buckets this can store. This is because we * store the next offset to write to in a float and floats only have * {@code 23} bits of mantissa so they can't accurate store values * higher than {@code 2 ^ 24}. */ public static final int MAX_BUCKET_SIZE = (int) Math.pow(2, 24); private FloatArray values; @SuppressWarnings("this-escape") public ForFloats(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); if (bucketSize > MAX_BUCKET_SIZE) { close(); throw new IllegalArgumentException("bucket size must be less than [2^24] but was [" + bucketSize + "]"); } boolean success = false; try { values = bigArrays.newFloatArray(1, false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { /* * This cast will not lose precision because we make sure never * to write values here that float can't store precisely. */ return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Float.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { float tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract
ForFloats
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SqlStoredEndpointBuilderFactory.java
{ "start": 1458, "end": 1598 }
interface ____ { /** * Builder for endpoint for the SQL Stored Procedure component. */ public
SqlStoredEndpointBuilderFactory
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/abilities/SupportsReadingMetadata.java
{ "start": 4297, "end": 7772 }
interface ____ { /** * Returns the map of metadata keys and their corresponding data types that can be produced by * this table source for reading. * * <p>The returned map will be used by the planner for validation and insertion of explicit * casts (see {@link LogicalTypeCasts#supportsExplicitCast(LogicalType, LogicalType)}) if * necessary. * * <p>The iteration order of the returned map determines the order of metadata keys in the list * passed in {@link #applyReadableMetadata(List, DataType)}. Therefore, it might be beneficial * to return a {@link LinkedHashMap} if a strict metadata column order is required. * * <p>If a source forwards metadata from one or more formats, we recommend the following column * order for consistency: * * <pre>{@code * KEY FORMAT METADATA COLUMNS + VALUE FORMAT METADATA COLUMNS + SOURCE METADATA COLUMNS * }</pre> * * <p>Metadata key names follow the same pattern as mentioned in {@link Factory}. In case of * duplicate names in format and source keys, format keys shall have higher precedence. * * <p>Regardless of the returned {@link DataType}s, a metadata column is always represented * using internal data structures (see {@link RowData}). * * @see DecodingFormat#listReadableMetadata() */ Map<String, DataType> listReadableMetadata(); /** * Provides a list of metadata keys that the produced {@link RowData} must contain as appended * metadata columns. * * <p>Implementations of this method must be idempotent. The planner might call this method * multiple times. * * <p>Note: Use the passed data type instead of {@link ResolvedSchema#toPhysicalRowDataType()} * for describing the final output data type when creating {@link TypeInformation}. If the * source implements {@link SupportsProjectionPushDown}, the projection is already considered in * the given output data type, use the {@code producedDataType} provided by this method instead * of the {@code producedDataType} provided by {@link * SupportsProjectionPushDown#applyProjection(int[][], DataType)}. * * @param metadataKeys a subset of the keys returned by {@link #listReadableMetadata()}, ordered * by the iteration order of returned map * @param producedDataType the final output type of the source, it is intended to be only * forwarded and the planner will decide on the field names to avoid collisions * @see DecodingFormat#applyReadableMetadata(List) */ void applyReadableMetadata(List<String> metadataKeys, DataType producedDataType); /** * Defines whether projections can be applied to metadata columns. * * <p>This method is only called if the source does <em>not</em> implement {@link * SupportsProjectionPushDown}. By default, the planner will only apply metadata columns which * have actually been selected in the query regardless. By returning {@code false} instead the * source can inform the planner to apply all metadata columns defined in the table's schema. * * <p>If the source implements {@link SupportsProjectionPushDown}, projections of metadata * columns are always considered before calling {@link #applyReadableMetadata(List, DataType)}. */ default boolean supportsMetadataProjection() { return true; } }
SupportsReadingMetadata
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DebeziumSqlserverComponentBuilderFactory.java
{ "start": 48091, "end": 66616 }
class ____ should be used to store and * recover database schema changes. The configuration properties for the * history are prefixed with the 'schema.history.internal.' string. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: io.debezium.storage.kafka.history.KafkaSchemaHistory * Group: sqlserver * * @param schemaHistoryInternal the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder schemaHistoryInternal(java.lang.String schemaHistoryInternal) { doSetProperty("schemaHistoryInternal", schemaHistoryInternal); return this; } /** * The path to the file that will be used to record the database schema * history. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: sqlserver * * @param schemaHistoryInternalFileFilename the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder schemaHistoryInternalFileFilename(java.lang.String schemaHistoryInternalFileFilename) { doSetProperty("schemaHistoryInternalFileFilename", schemaHistoryInternalFileFilename); return this; } /** * Controls the action Debezium will take when it meets a DDL statement * in binlog, that it cannot parse.By default the connector will stop * operating but by changing the setting it can ignore the statements * which it cannot parse. If skipping is enabled then Debezium can miss * metadata changes. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param schemaHistoryInternalSkipUnparseableDdl the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder schemaHistoryInternalSkipUnparseableDdl(boolean schemaHistoryInternalSkipUnparseableDdl) { doSetProperty("schemaHistoryInternalSkipUnparseableDdl", schemaHistoryInternalSkipUnparseableDdl); return this; } /** * Controls what DDL will Debezium store in database schema history. By * default (false) Debezium will store all incoming DDL statements. If * set to true, then only DDL that manipulates a table from captured * schema/database will be stored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param schemaHistoryInternalStoreOnlyCapturedDatabasesDdl the value * to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder schemaHistoryInternalStoreOnlyCapturedDatabasesDdl(boolean schemaHistoryInternalStoreOnlyCapturedDatabasesDdl) { doSetProperty("schemaHistoryInternalStoreOnlyCapturedDatabasesDdl", schemaHistoryInternalStoreOnlyCapturedDatabasesDdl); return this; } /** * Controls what DDL will Debezium store in database schema history. By * default (false) Debezium will store all incoming DDL statements. If * set to true, then only DDL that manipulates a captured table will be * stored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param schemaHistoryInternalStoreOnlyCapturedTablesDdl the value to * set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder schemaHistoryInternalStoreOnlyCapturedTablesDdl(boolean schemaHistoryInternalStoreOnlyCapturedTablesDdl) { doSetProperty("schemaHistoryInternalStoreOnlyCapturedTablesDdl", schemaHistoryInternalStoreOnlyCapturedTablesDdl); return this; } /** * Specify how schema names should be adjusted for compatibility with * the message converter used by the connector, including: 'avro' * replaces the characters that cannot be used in the Avro type name * with underscore; 'avro_unicode' replaces the underscore or characters * that cannot be used in the Avro type name with corresponding unicode * like _uxxxx. Note: _ is an escape sequence like backslash in * Java;'none' does not apply any adjustment (default). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: none * Group: sqlserver * * @param schemaNameAdjustmentMode the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder schemaNameAdjustmentMode(java.lang.String schemaNameAdjustmentMode) { doSetProperty("schemaNameAdjustmentMode", schemaNameAdjustmentMode); return this; } /** * The name of the data collection that is used to send signals/commands * to Debezium. Signaling is disabled when not set. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: sqlserver * * @param signalDataCollection the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder signalDataCollection(java.lang.String signalDataCollection) { doSetProperty("signalDataCollection", signalDataCollection); return this; } /** * List of channels names that are enabled. Source channel is enabled by * default. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: source * Group: sqlserver * * @param signalEnabledChannels the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder signalEnabledChannels(java.lang.String signalEnabledChannels) { doSetProperty("signalEnabledChannels", signalEnabledChannels); return this; } /** * Interval for looking for new signals in registered channels, given in * milliseconds. Defaults to 5 seconds. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 5s * Group: sqlserver * * @param signalPollIntervalMs the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder signalPollIntervalMs(long signalPollIntervalMs) { doSetProperty("signalPollIntervalMs", signalPollIntervalMs); return this; } /** * The comma-separated list of operations to skip during streaming, * defined as: 'c' for inserts/create; 'u' for updates; 'd' for deletes, * 't' for truncates, and 'none' to indicate nothing skipped. By * default, only truncate operations will be skipped. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: t * Group: sqlserver * * @param skippedOperations the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder skippedOperations(java.lang.String skippedOperations) { doSetProperty("skippedOperations", skippedOperations); return this; } /** * A delay period before a snapshot will begin, given in milliseconds. * Defaults to 0 ms. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 0ms * Group: sqlserver * * @param snapshotDelayMs the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotDelayMs(long snapshotDelayMs) { doSetProperty("snapshotDelayMs", snapshotDelayMs); return this; } /** * The maximum number of records that should be loaded into memory while * performing a snapshot. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: sqlserver * * @param snapshotFetchSize the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotFetchSize(int snapshotFetchSize) { doSetProperty("snapshotFetchSize", snapshotFetchSize); return this; } /** * This setting must be set to specify a list of tables/collections * whose snapshot must be taken on creating or restarting the connector. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: sqlserver * * @param snapshotIncludeCollectionList the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotIncludeCollectionList(java.lang.String snapshotIncludeCollectionList) { doSetProperty("snapshotIncludeCollectionList", snapshotIncludeCollectionList); return this; } /** * Controls which transaction isolation level is used and how long the * connector locks the captured tables. The default is * 'repeatable_read', which means that repeatable read isolation level * is used. In addition, type of acquired lock during schema snapshot * depends on snapshot.locking.mode property. Using a value of * 'exclusive' ensures that the connector holds the type of lock * specified with snapshot.locking.mode property (and thus prevents any * reads and updates) for all captured tables during the entire snapshot * duration. When 'snapshot' is specified, connector runs the initial * snapshot in SNAPSHOT isolation level, which guarantees snapshot * consistency. In addition, neither table nor row-level locks are held. * When 'read_committed' is specified, connector runs the initial * snapshot in READ COMMITTED isolation level. No long-running locks are * taken, so that initial snapshot does not prevent other transactions * from updating table rows. Snapshot consistency is not guaranteed.In * 'read_uncommitted' mode neither table nor row-level locks are * acquired, but connector does not guarantee snapshot consistency. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: repeatable_read * Group: sqlserver * * @param snapshotIsolationMode the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotIsolationMode(java.lang.String snapshotIsolationMode) { doSetProperty("snapshotIsolationMode", snapshotIsolationMode); return this; } /** * The maximum number of millis to wait for table locks at the beginning * of a snapshot. If locks cannot be acquired in this time frame, the * snapshot will be aborted. Defaults to 10 seconds. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 10s * Group: sqlserver * * @param snapshotLockTimeoutMs the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotLockTimeoutMs(long snapshotLockTimeoutMs) { doSetProperty("snapshotLockTimeoutMs", snapshotLockTimeoutMs); return this; } /** * The maximum number of threads used to perform the snapshot. Defaults * to 1. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: sqlserver * * @param snapshotMaxThreads the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotMaxThreads(int snapshotMaxThreads) { doSetProperty("snapshotMaxThreads", snapshotMaxThreads); return this; } /** * The criteria for running a snapshot upon startup of the connector. * Select one of the following snapshot options: 'initial' (default): If * the connector does not detect any offsets for the logical server * name, it runs a snapshot that captures the current full state of the * configured tables. After the snapshot completes, the connector begins * to stream changes from the transaction log.; 'initial_only': The * connector performs a snapshot as it does for the 'initial' option, * but after the connector completes the snapshot, it stops, and does * not stream changes from the transaction log.; 'schema_only': If the * connector does not detect any offsets for the logical server name, it * runs a snapshot that captures only the schema (table structures), but * not any table data. After the snapshot completes, the connector * begins to stream changes from the transaction log. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: initial * Group: sqlserver * * @param snapshotMode the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotMode(java.lang.String snapshotMode) { doSetProperty("snapshotMode", snapshotMode); return this; } /** * When 'snapshot.mode' is set as configuration_based, this setting * permits to specify whenever the data should be snapshotted or not. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param snapshotModeConfigurationBasedSnapshotData the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotModeConfigurationBasedSnapshotData(boolean snapshotModeConfigurationBasedSnapshotData) { doSetProperty("snapshotModeConfigurationBasedSnapshotData", snapshotModeConfigurationBasedSnapshotData); return this; } /** * When 'snapshot.mode' is set as configuration_based, this setting * permits to specify whenever the data should be snapshotted or not in * case of error. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param snapshotModeConfigurationBasedSnapshotOnDataError the value to * set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotModeConfigurationBasedSnapshotOnDataError(boolean snapshotModeConfigurationBasedSnapshotOnDataError) { doSetProperty("snapshotModeConfigurationBasedSnapshotOnDataError", snapshotModeConfigurationBasedSnapshotOnDataError); return this; } /** * When 'snapshot.mode' is set as configuration_based, this setting * permits to specify whenever the schema should be snapshotted or not * in case of error. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param snapshotModeConfigurationBasedSnapshotOnSchemaError the value * to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotModeConfigurationBasedSnapshotOnSchemaError(boolean snapshotModeConfigurationBasedSnapshotOnSchemaError) { doSetProperty("snapshotModeConfigurationBasedSnapshotOnSchemaError", snapshotModeConfigurationBasedSnapshotOnSchemaError); return this; } /** * When 'snapshot.mode' is set as configuration_based, this setting * permits to specify whenever the schema should be snapshotted or not. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param snapshotModeConfigurationBasedSnapshotSchema the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotModeConfigurationBasedSnapshotSchema(boolean snapshotModeConfigurationBasedSnapshotSchema) { doSetProperty("snapshotModeConfigurationBasedSnapshotSchema", snapshotModeConfigurationBasedSnapshotSchema); return this; } /** * When 'snapshot.mode' is set as configuration_based, this setting * permits to specify whenever the stream should start or not after * snapshot. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: sqlserver * * @param snapshotModeConfigurationBasedStartStream the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder snapshotModeConfigurationBasedStartStream(boolean snapshotModeConfigurationBasedStartStream) { doSetProperty("snapshotModeConfigurationBasedStartStream", snapshotModeConfigurationBasedStartStream); return this; } /** * When 'snapshot.mode' is set as custom, this setting must be set to * specify a the name of the custom implementation provided in the * 'name()' method. The implementations must implement the 'Snapshotter' *
that
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/ContextCustomizerFactories.java
{ "start": 4245, "end": 4352 }
class ____ does * <strong>not</strong> inherit factories from a superclass or enclosing * class. */
that
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/lucene/search/function/ScoreFunction.java
{ "start": 696, "end": 2019 }
class ____ { private final CombineFunction scoreCombiner; protected ScoreFunction(CombineFunction scoreCombiner) { this.scoreCombiner = scoreCombiner; } public CombineFunction getDefaultScoreCombiner() { return scoreCombiner; } public abstract LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException; /** * Indicates if document scores are needed by this function. * * @return {@code true} if scores are needed. */ public abstract boolean needsScores(); @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ScoreFunction other = (ScoreFunction) obj; return Objects.equals(scoreCombiner, other.scoreCombiner) && doEquals(other); } public float getWeight() { return 1.0f; } /** * Indicates whether some other {@link ScoreFunction} object of the same type is "equal to" this one. */ protected abstract boolean doEquals(ScoreFunction other); @Override public final int hashCode() { /* * Override hashCode here and forward to an abstract method to force extensions of this
ScoreFunction
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerSuspendAndResumeTest.java
{ "start": 1332, "end": 3076 }
class ____ extends ContextTestSupport { private final MyPolicy myPolicy = new MyPolicy(); @Test public void testConsumeSuspendAndResumeFile() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBodyAndHeader(fileUri(), "Bye World", Exchange.FILE_NAME, "bye.txt"); template.sendBodyAndHeader(fileUri(), "Hello World", Exchange.FILE_NAME, "hello.txt"); assertMockEndpointsSatisfied(); oneExchangeDone.matchesWaitTime(); // the route is suspended by the policy so we should only receive one try (Stream<Path> list = Files.list(testDirectory())) { long files = list.count(); assertEquals(1, files, "The file should exists"); } // reset mock oneExchangeDone.reset(); mock.reset(); mock.expectedMessageCount(1); // now resume it myPolicy.resumeConsumer(); assertMockEndpointsSatisfied(); oneExchangeDone.matchesWaitTime(); // and the file is now deleted try (Stream<Path> list = Files.list(testDirectory())) { long files = list.count(); assertEquals(0, files, "The file should exists"); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(fileUri("?maxMessagesPerPoll=1&delete=true&initialDelay=0&delay=10")) .routePolicy(myPolicy).id("myRoute").convertBodyTo(String.class) .to("mock:result"); } }; } private static
FileConsumerSuspendAndResumeTest
java
grpc__grpc-java
netty/src/test/java/io/grpc/netty/NettyAdaptiveCumulatorTest.java
{ "start": 7702, "end": 10054 }
class ____ { // Represent data as immutable ASCII Strings for easy and readable ByteBuf equality assertions. private static final String DATA_INITIAL = "0123"; private static final String DATA_INCOMING = "456789"; /** * Cartesian product of the test values. */ @Parameters(name = "composeMinSize={0}, tailData=\"{1}\", inData=\"{2}\"") public static Collection<Object[]> params() { List<?> composeMinSize = ImmutableList.of(0, 9, 10, 11, Integer.MAX_VALUE); List<?> tailData = ImmutableList.of("", DATA_INITIAL); List<?> inData = ImmutableList.of("", DATA_INCOMING); return cartesianProductParams(composeMinSize, tailData, inData); } @Parameter public int composeMinSize; @Parameter(1) public String tailData; @Parameter(2) public String inData; private CompositeByteBuf composite; private ByteBuf tail; private ByteBuf in; @Before public void setUp() { ByteBufAllocator alloc = new UnpooledByteBufAllocator(false); in = ByteBufUtil.writeAscii(alloc, inData); tail = ByteBufUtil.writeAscii(alloc, tailData); composite = alloc.compositeBuffer(Integer.MAX_VALUE); // Note that addFlattenedComponents() will not add a new component when tail is not readable. composite.addFlattenedComponents(true, tail); } @After public void tearDown() { in.release(); composite.release(); } @Test public void shouldCompose_emptyComposite() { assume().that(composite.numComponents()).isEqualTo(0); assertTrue(NettyAdaptiveCumulator.shouldCompose(composite, in, composeMinSize)); } @Test public void shouldCompose_composeMinSizeReached() { assume().that(composite.numComponents()).isGreaterThan(0); assume().that(tail.readableBytes() + in.readableBytes()).isAtLeast(composeMinSize); assertTrue(NettyAdaptiveCumulator.shouldCompose(composite, in, composeMinSize)); } @Test public void shouldCompose_composeMinSizeNotReached() { assume().that(composite.numComponents()).isGreaterThan(0); assume().that(tail.readableBytes() + in.readableBytes()).isLessThan(composeMinSize); assertFalse(NettyAdaptiveCumulator.shouldCompose(composite, in, composeMinSize)); } } @RunWith(Parameterized.class) public static
ShouldComposeTests
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SubsequenceInputTypeStrategy.java
{ "start": 5129, "end": 5599 }
class ____ { private final int startIndex; private final @Nullable Integer endIndex; private final InputTypeStrategy inputTypeStrategy; public ArgumentsSplit( int startIndex, Integer endIndex, InputTypeStrategy inputTypeStrategy) { this.startIndex = startIndex; this.endIndex = endIndex; this.inputTypeStrategy = inputTypeStrategy; } } private static final
ArgumentsSplit
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/convert/support/ArrayToObjectConverter.java
{ "start": 1177, "end": 2252 }
class ____ implements ConditionalGenericConverter { private final ConversionService conversionService; public ArrayToObjectConverter(ConversionService conversionService) { this.conversionService = conversionService; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(Object[].class, Object.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return ConversionUtils.canConvertElements(sourceType.getElementTypeDescriptor(), targetType, this.conversionService); } @Override public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } if (sourceType.isAssignableTo(targetType)) { return source; } if (Array.getLength(source) == 0) { return null; } Object firstElement = Array.get(source, 0); return this.conversionService.convert(firstElement, sourceType.elementTypeDescriptor(firstElement), targetType); } }
ArrayToObjectConverter
java
google__guava
guava/src/com/google/common/collect/Maps.java
{ "start": 6167, "end": 7260 }
enum ____ order, not encounter order. * * <p>If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when * the collection operation is performed. (This differs from the {@code Collector} returned by * {@link java.util.stream.Collectors#toMap(java.util.function.Function, * java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code * IllegalStateException}.) * * @since 21.0 */ public static <T extends @Nullable Object, K extends Enum<K>, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap( java.util.function.Function<? super T, ? extends K> keyFunction, java.util.function.Function<? super T, ? extends V> valueFunction) { return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction); } /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys * and values are the result of applying the provided mapping functions to the input elements. The * resulting implementation is specialized for
definition
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/ir/IfNode.java
{ "start": 616, "end": 1159 }
class ____ extends ConditionNode { /* ---- begin visitor ---- */ @Override public <Scope> void visit(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) { irTreeVisitor.visitIf(this, scope); } @Override public <Scope> void visitChildren(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) { getConditionNode().visit(irTreeVisitor, scope); getBlockNode().visit(irTreeVisitor, scope); } /* ---- end visitor ---- */ public IfNode(Location location) { super(location); } }
IfNode
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
{ "start": 42763, "end": 43572 }
class ____ { public void f(List<List<String>> lists) { lists.stream().collect(ArrayList::new, Collection::addAll, Collection::addAll); lists.stream().collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll); } } """) .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void simpleRecord() { helper .addSourceLines( "SimpleRecord.java", // """ // public record SimpleRecord(Integer foo, Long bar) {} //\ """) .expectNoDiagnostics() .doTest(); } @Test public void nestedRecord() { helper .addSourceLines( "SimpleClass.java", """ public
Test
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/tableperclass/ChildEntity.java
{ "start": 360, "end": 1342 }
class ____ extends ParentEntity { @Basic private Long numVal; public ChildEntity() { } public ChildEntity(Integer id, String data, Long numVal) { super( id, data ); this.numVal = numVal; } public Long getNumVal() { return numVal; } public void setNumVal(Long numVal) { this.numVal = numVal; } public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof ChildEntity) ) { return false; } if ( !super.equals( o ) ) { return false; } ChildEntity childEntity = (ChildEntity) o; if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { return false; } return true; } public int hashCode() { int result = super.hashCode(); result = 31 * result + (numVal != null ? numVal.hashCode() : 0); return result; } public String toString() { return "ChildPrimaryKeyJoinEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; } }
ChildEntity
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java
{ "start": 4729, "end": 6170 }
class ____ { private final Runnable onCapture; private final Object monitor = new Object(); private final PrintStreamCapture out; private final PrintStreamCapture err; private final List<CapturedString> capturedStrings = new ArrayList<>(); SystemCapture(Runnable onCapture) { this.onCapture = onCapture; this.out = new PrintStreamCapture(System.out, this::captureOut); this.err = new PrintStreamCapture(System.err, this::captureErr); System.setOut(this.out); System.setErr(this.err); } void release() { System.setOut(this.out.getParent()); System.setErr(this.err.getParent()); } private void captureOut(String string) { capture(new CapturedString(Type.OUT, string)); } private void captureErr(String string) { capture(new CapturedString(Type.ERR, string)); } private void capture(CapturedString e) { synchronized (this.monitor) { this.onCapture.run(); this.capturedStrings.add(e); } } void append(StringBuilder builder, Predicate<Type> filter) { synchronized (this.monitor) { for (CapturedString stringCapture : this.capturedStrings) { if (filter.test(stringCapture.getType())) { builder.append(stringCapture); } } } } void reset() { synchronized (this.monitor) { this.capturedStrings.clear(); } } } /** * A {@link PrintStream} implementation that captures written strings. */ private static
SystemCapture
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-toolchain/src/main/java/org/apache/maven/plugin/coreit/CoreItMojo.java
{ "start": 1688, "end": 5260 }
class ____ extends AbstractMojo { /** */ @Component private ToolchainManagerPrivate toolchainManager; /** * The current Maven session holding the selected toolchain. */ @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; /** * The path to the output file for the properties. */ @Parameter(property = "toolchain.outputFile", defaultValue = "${project.build.directory}/toolchains.properties") private File outputFile; /** * The type identifier of the toolchain, e.g. "jdk". */ @Parameter(property = "toolchain.type") private String type; /** * The name of the tool, e.g. "javac". */ @Parameter(property = "toolchain.tool") private String tool; /** * The zero-based index of the toolchain to select and store in the build context. */ @Parameter(property = "toolchain.selected") private int selected; public void execute() throws MojoExecutionException { ToolchainPrivate[] tcs = getToolchains(); getLog().info("[MAVEN-CORE-IT-LOG] Toolchains in plugin: " + Arrays.asList(tcs)); if (selected >= 0) { if (selected < tcs.length) { ToolchainPrivate toolchain = tcs[selected]; toolchainManager.storeToolchainToBuildContext(toolchain, session); } else { getLog().warn("[MAVEN-CORE-IT-LOG] Toolchain #" + selected + " can't be selected, found only " + tcs.length); } } Properties properties = new Properties(); int count = 1; for (Iterator<ToolchainPrivate> i = Arrays.<ToolchainPrivate>asList(tcs).iterator(); i.hasNext(); count++) { ToolchainPrivate toolchain = i.next(); String foundTool = toolchain.findTool(tool); if (foundTool != null) { properties.setProperty("tool." + count, foundTool); } } OutputStream out = null; try { outputFile.getParentFile().mkdirs(); out = new FileOutputStream(outputFile); properties.store(out, "MAVEN-CORE-IT-LOG"); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } private ToolchainPrivate[] getToolchains() throws MojoExecutionException { Class<? extends ToolchainManagerPrivate> managerClass = toolchainManager.getClass(); try { try { // try 2.x style API Method oldMethod = managerClass.getMethod("getToolchainsForType", new Class[] {String.class}); return (ToolchainPrivate[]) oldMethod.invoke(toolchainManager, new Object[] {type}); } catch (NoSuchMethodException e) { // try 3.x style API Method newMethod = managerClass.getMethod("getToolchainsForType", new Class[] {String.class, MavenSession.class}); return (ToolchainPrivate[]) newMethod.invoke(toolchainManager, new Object[] {type, session}); } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new MojoExecutionException("Incompatible toolchain API", e); } } }
CoreItMojo
java
apache__camel
tooling/camel-util-json/src/main/java/org/apache/camel/util/json/JsonArray.java
{ "start": 9235, "end": 9550 }
enum ____ couldn't be determined * with it. * @throws ClassCastException if the element at the index was not a String or if the fully qualified enum * name is of the wrong type. * @throws IllegalArgumentException if an
type
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/std/StdValueInstantiatorTest.java
{ "start": 756, "end": 2179 }
class ____ { final double value; Stuff(double value) { this.value = value; } } @Test public void testDoubleValidation_valid() { assertEquals(0d, StdValueInstantiator.tryConvertToDouble(BigDecimal.ZERO)); assertEquals(1d, StdValueInstantiator.tryConvertToDouble(BigDecimal.ONE)); assertEquals(10d, StdValueInstantiator.tryConvertToDouble(BigDecimal.TEN)); assertEquals(-1.5d, StdValueInstantiator.tryConvertToDouble(BigDecimal.valueOf(-1.5d))); } @Test public void testDoubleValidation_invalid() { BigDecimal value = BigDecimal.valueOf(Double.MAX_VALUE).add(BigDecimal.valueOf(Double.MAX_VALUE)); assertNull(StdValueInstantiator.tryConvertToDouble(value)); } @Test public void testJsonIntegerToDouble() throws Exception { Stuff a = MAPPER.readValue("5", Stuff.class); assertEquals(5, a.value); } @Test public void testJsonLongToDouble() throws Exception { assertTrue(LONG_TEST_VALUE > Integer.MAX_VALUE); Stuff a = MAPPER.readValue(String.valueOf(LONG_TEST_VALUE), Stuff.class); assertEquals(LONG_TEST_VALUE, a.value); } @Test public void testJsonIntegerDeserializationPrefersInt() throws Exception { A a = MAPPER.readValue("5", A.class); assertEquals(1, a.creatorType); } static
Stuff