language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsResourceCalculator.java
{ "start": 1345, "end": 1474 }
class ____ property. * Theoretically the ResourceCalculatorProcessTree can be configured using the * mapreduce.job.process-tree.
job
java
spring-projects__spring-boot
module/spring-boot-groovy-templates/src/main/java/org/springframework/boot/groovy/template/autoconfigure/GroovyTemplateAutoConfiguration.java
{ "start": 3133, "end": 6419 }
class ____ { private final ApplicationContext applicationContext; private final GroovyTemplateProperties properties; GroovyMarkupConfiguration(ApplicationContext applicationContext, GroovyTemplateProperties properties) { this.applicationContext = applicationContext; this.properties = properties; checkTemplateLocationExists(); } private void checkTemplateLocationExists() { if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) { TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath()); if (!location.exists(this.applicationContext)) { logger.warn(LogMessage.format( "Cannot find template location: %s (please add some templates, check your Groovy " + "configuration, or set spring.groovy.template.check-template-location=false)", location)); } } } /** * MarkupTemplateEngine could be loaded from groovy-templates or groovy-all. * Unfortunately it's quite common for people to use groovy-all and not actually * need templating support. This method attempts to check the source jar so that * we can skip the {@code /template} directory check for such cases. * @return true if the groovy-all jar is used */ private boolean isUsingGroovyAllJar() { try { ProtectionDomain domain = MarkupTemplateEngine.class.getProtectionDomain(); CodeSource codeSource = domain.getCodeSource(); return codeSource != null && codeSource.getLocation().toString().contains("-all"); } catch (Exception ex) { return false; } } @Bean @ConditionalOnMissingBean(GroovyMarkupConfig.class) GroovyMarkupConfigurer groovyMarkupConfigurer(ObjectProvider<MarkupTemplateEngine> templateEngine, Environment environment) { GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); PropertyMapper map = PropertyMapper.get(); map.from(this.properties::isAutoEscape).to(configurer::setAutoEscape); map.from(this.properties::isAutoIndent).to(configurer::setAutoIndent); map.from(this.properties::getAutoIndentString).to(configurer::setAutoIndentString); map.from(this.properties::isAutoNewLine).to(configurer::setAutoNewLine); map.from(this.properties::getBaseTemplateClass).to(configurer::setBaseTemplateClass); map.from(this.properties::isCache).to(configurer::setCacheTemplates); map.from(this.properties::getDeclarationEncoding).to(configurer::setDeclarationEncoding); map.from(this.properties::isExpandEmptyElements).to(configurer::setExpandEmptyElements); map.from(this.properties::getLocale).to(configurer::setLocale); map.from(this.properties::getNewLineString).to(configurer::setNewLineString); map.from(this.properties::getResourceLoaderPath).to(configurer::setResourceLoaderPath); map.from(this.properties::isUseDoubleQuotes).to(configurer::setUseDoubleQuotes); Binder.get(environment).bind("spring.groovy.template.configuration", Bindable.ofInstance(configurer)); templateEngine.ifAvailable(configurer::setTemplateEngine); return configurer; } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, UrlBasedViewResolver.class }) @ConditionalOnWebApplication(type = Type.SERVLET) static
GroovyMarkupConfiguration
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionFromChoiceUseOriginalBodyTest.java
{ "start": 1153, "end": 4241 }
class ____ extends ContextTestSupport { private MyServiceBean myServiceBean; @Test public void testNoErrorWhen() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(0); getMockEndpoint("mock:func").expectedMessageCount(0); getMockEndpoint("mock:tech").expectedMessageCount(0); getMockEndpoint("mock:otherwise").expectedMessageCount(0); MockEndpoint mock = getMockEndpoint("mock:when"); mock.expectedMessageCount(1); template.sendBody("direct:route", "<order><type>myType</type><user>James</user></order>"); assertMockEndpointsSatisfied(); } @Test public void testFunctionalError() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(0); getMockEndpoint("mock:tech").expectedMessageCount(0); getMockEndpoint("mock:when").expectedMessageCount(0); getMockEndpoint("mock:otherwise").expectedMessageCount(0); MockEndpoint mock = getMockEndpoint("mock:func"); mock.expectedBodiesReceived("Func"); template.sendBody("direct:func", "Func"); assertMockEndpointsSatisfied(); } @Test public void testTechnicalError() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(0); getMockEndpoint("mock:func").expectedMessageCount(0); getMockEndpoint("mock:when").expectedMessageCount(0); getMockEndpoint("mock:otherwise").expectedMessageCount(0); MockEndpoint mock = getMockEndpoint("mock:tech"); mock.expectedBodiesReceived("Tech"); template.sendBody("direct:tech", "Tech"); assertMockEndpointsSatisfied(); } @Override @BeforeEach public void setUp() throws Exception { myServiceBean = new MyServiceBean(); super.setUp(); } @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("myServiceBean", myServiceBean); return jndi; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { errorHandler(deadLetterChannel("mock:error")); onException(MyTechnicalException.class).useOriginalMessage().maximumRedeliveries(0).handled(true) .to("mock:tech"); onException(MyFunctionalException.class).useOriginalMessage().maximumRedeliveries(0).handled(true) .to("mock:func"); from("direct:tech").setBody(constant("<order><type>myType</type><user>Tech</user></order>")).to("direct:route"); from("direct:func").setBody(constant("<order><type>myType</type><user>Func</user></order>")).to("direct:route"); from("direct:route").choice().when(method("myServiceBean").isEqualTo("James")).to("mock:when").otherwise() .to("mock:otherwise"); } }; } }
OnExceptionFromChoiceUseOriginalBodyTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit4/StandardJUnit4FeaturesSpringRunnerTests.java
{ "start": 1421, "end": 1553 }
class ____ extends StandardJUnit4FeaturesTests { /* All tests are in the parent class... */ }
StandardJUnit4FeaturesSpringRunnerTests
java
qos-ch__slf4j
slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java
{ "start": 1396, "end": 5322 }
class ____ extends TestCase { /** * In this test we see that we can use more simple Pattern to do the * conversion * */ public void test() { MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern.compile("(.*)(Log)")); cr2.addReplacement(2, "LOGGER"); String s = "abcd Log"; Pattern pat = cr2.getPattern(); Matcher m = pat.matcher(s); assertTrue(m.matches()); String r = cr2.replace(m); assertEquals("abcd LOGGER", r); System.out.println(r); } /** * In this test we replace, using the simple Pattern (Log), the full Log * declaration and instantiation. This is not convenient because we will also * replace all String containing "Log". */ public void test2() { Pattern pat = Pattern.compile("(Log)"); String s = "abcd Log ="; Matcher m = pat.matcher(s); assertTrue(m.find()); String r = m.replaceAll("Logger"); assertEquals("abcd Logger =", r); String s1 = "Log l = LogFactory.getLog(MyClass.class);"; m = pat.matcher(s1); assertTrue(m.find()); r = m.replaceAll("Logger"); assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", r); String s2 = "Logabc "; m = pat.matcher(s2); assertTrue(m.find()); String s3 = "abcLog"; m = pat.matcher(s3); assertTrue(m.find()); } /** * In this test we use a simple Pattern to replace the log instantiation * without influence on Log declaration. * */ public void test3() { Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); String s = "Log log = LogFactory.getFactory().getInstance(\"x\");"; Matcher m = pat.matcher(s); assertTrue(m.find()); String r = m.replaceAll("LoggerFactory.getLogger("); assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r); String nonMatching = "Log log = xxx;"; pat.matcher(nonMatching); assertFalse(m.find()); } /** * In this test we try to replace keyword Log without influence on String * containing Log We see that we have to use two different Patterns */ public void test4() { Pattern pat = Pattern.compile("(\\sLog\\b)"); String s = "abcd Log ="; Matcher m = pat.matcher(s); assertTrue(m.find()); String r = m.replaceAll(" Logger"); assertEquals("abcd Logger =", r); String s2 = "Logabcd "; m = pat.matcher(s2); assertFalse(m.find()); String s3 = "abcdLogabcd "; m = pat.matcher(s3); assertFalse(m.find()); String s4 = "abcdLog"; m = pat.matcher(s4); assertFalse(m.find()); String s5 = "Log myLog"; m = pat.matcher(s5); assertFalse(m.find()); Pattern pat2 = Pattern.compile("^Log\\b"); Matcher m2 = pat2.matcher(s5); assertTrue(m2.find()); r = m2.replaceAll("Logger"); assertEquals("Logger myLog", r); } /** * In this test we combine two Pattern to achieve the intended conversion */ public void test5() { Pattern pat = Pattern.compile("(\\sLog\\b)"); String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);"; Matcher m = pat.matcher(s); assertTrue(m.find()); String r = m.replaceAll(" Logger"); assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r); Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); m = pat2.matcher(r); assertTrue(m.find()); r = m.replaceAll("LoggerFactory.getLogger("); assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r); } }
AternativeApproach
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/OutputCommitter.java
{ "start": 10168, "end": 10800 }
interface ____ calling the old method. Note * that the input types are different between the new and old apis and this * is a bridge between the two. * @deprecated Use {@link #commitJob(org.apache.hadoop.mapreduce.JobContext)} * or {@link #abortJob(org.apache.hadoop.mapreduce.JobContext, org.apache.hadoop.mapreduce.JobStatus.State)} * instead. */ @Override @Deprecated public final void cleanupJob(org.apache.hadoop.mapreduce.JobContext context ) throws IOException { cleanupJob((JobContext) context); } /** * This method implements the new
by
java
spring-projects__spring-boot
module/spring-boot-jackson/src/main/java/org/springframework/boot/jackson/JacksonMixin.java
{ "start": 1194, "end": 1751 }
interface ____ { /** * Alias for the {@link #type()} attribute. Allows for more concise annotation * declarations e.g.: {@code @JacksonMixin(MyType.class)} instead of * {@code @JacksonMixin(type=MyType.class)}. * @return the mixed-in classes */ @AliasFor("type") Class<?>[] value() default {}; /** * The types that are handled by the provided mixin class. {@link #value()} is an * alias for (and mutually exclusive with) this attribute. * @return the mixed-in classes */ @AliasFor("value") Class<?>[] type() default {}; }
JacksonMixin
java
spring-projects__spring-boot
module/spring-boot-data-couchbase-test/src/test/java/org/springframework/boot/data/couchbase/test/autoconfigure/DataCouchbaseTestPropertiesIntegrationTests.java
{ "start": 1399, "end": 1758 }
class ____ { @Autowired private Environment innerEnvironment; @Test void propertiesFromEnclosingClassAffectNestedTests() { assertThat(DataCouchbaseTestPropertiesIntegrationTests.this.environment.getActiveProfiles()) .containsExactly("test"); assertThat(this.innerEnvironment.getActiveProfiles()).containsExactly("test"); } } }
NestedTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/RenewerParam.java
{ "start": 887, "end": 1414 }
class ____ extends StringParam { /** Parameter name. */ public static final String NAME = "renewer"; /** Default parameter value. */ public static final String DEFAULT = NULL; private static final Domain DOMAIN = new Domain(NAME, null); /** * Constructor. * @param str a string representation of the parameter value. */ public RenewerParam(final String str) { super(DOMAIN, str == null || str.equals(DEFAULT)? null: str); } @Override public String getName() { return NAME; } }
RenewerParam
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java
{ "start": 6199, "end": 6539 }
enum ____ { /** * CONNECTED */ CONNECTED, /** * DISCONNECTED */ DISCONNECTED, /** * SENT */ SENT, /** * RECEIVED */ RECEIVED, /** * CAUGHT */ CAUGHT } }
ChannelState
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/netty4/SimpleSecurityNetty4ServerTransportTests.java
{ "start": 5539, "end": 58026 }
class ____ extends AbstractSimpleTransportTestCase { @Override protected Transport build(Settings settings, TransportVersion version, ClusterSettings clusterSettings, boolean doHandshake) { NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(Collections.emptyList()); Settings settings1 = Settings.builder().put(settings).put("xpack.security.transport.ssl.enabled", true).build(); return new TestSecurityNetty4ServerTransport( settings1, version, threadPool, networkService, PageCacheRecycler.NON_RECYCLING_INSTANCE, namedWriteableRegistry, new NoneCircuitBreakerService(), null, createSSLService(settings1), new SharedGroupFactory(settings1), doHandshake ); } private SSLService createSSLService() { return createSSLService(Settings.EMPTY); } protected SSLService createSSLService(Settings settings) { Path testnodeCert = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt"); Path testnodeKey = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.pem"); MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString("xpack.security.transport.ssl.secure_key_passphrase", "testnode"); // Some tests use a client profile. Put the passphrase in the secure settings for the profile (secure settings cannot be set twice) secureSettings.setString("transport.profiles.client.xpack.security.ssl.secure_key_passphrase", "testnode"); // For test that enables remote cluster port secureSettings.setString("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "testnode"); Settings settings1 = Settings.builder() .put("xpack.security.transport.ssl.enabled", true) .put("xpack.security.transport.ssl.key", testnodeKey) .put("xpack.security.transport.ssl.certificate", testnodeCert) .put("path.home", createTempDir()) .put(settings) .setSecureSettings(secureSettings) .build(); try { return new SSLService(TestEnvironment.newEnvironment(settings1)); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected Set<Setting<?>> getSupportedSettings() { HashSet<Setting<?>> availableSettings = new HashSet<>(super.getSupportedSettings()); availableSettings.addAll(XPackSettings.getAllSettings()); return availableSettings; } public void testConnectException() throws UnknownHostException { final ConnectTransportException e = connectToNodeExpectFailure( serviceA, DiscoveryNodeUtils.create("C", new TransportAddress(InetAddress.getByName("localhost"), 9876), emptyMap(), emptySet()), null ); assertThat(e.getMessage(), containsString("connect_exception")); assertThat(e.getMessage(), containsString("[127.0.0.1:9876]")); Throwable cause = ExceptionsHelper.unwrap(e, IOException.class); assertThat(cause, instanceOf(IOException.class)); } @Override public void testTcpHandshake() { assumeTrue("only tcp transport has a handshake method", serviceA.getOriginalTransport() instanceof TcpTransport); TcpTransport originalTransport = (TcpTransport) serviceA.getOriginalTransport(); ConnectionProfile connectionProfile = ConnectionProfile.buildDefaultConnectionProfile(Settings.EMPTY); try (TransportService service = buildService("TS_TPC", VersionInformation.CURRENT, TransportVersion.current(), Settings.EMPTY)) { DiscoveryNode node = DiscoveryNodeUtils.builder("TS_TPC") .name("TS_TPC") .address(service.boundAddress().publishAddress()) .roles(emptySet()) .version(version0) .build(); PlainActionFuture<Transport.Connection> future = new PlainActionFuture<>(); originalTransport.openConnection(node, connectionProfile, future); try (TcpTransport.NodeChannels connection = (TcpTransport.NodeChannels) future.actionGet()) { assertEquals(TransportVersion.current(), connection.getTransportVersion()); } } } @SuppressForbidden(reason = "Need to open socket connection") public void testRenegotiation() throws Exception { assumeFalse("BCTLS doesn't support renegotiation: https://github.com/bcgit/bc-java/issues/593#issuecomment-533518845", inFipsJvm()); // force TLSv1.2 since renegotiation is not supported by 1.3 SSLService sslService = createSSLService( Settings.builder().put("xpack.security.transport.ssl.supported_protocols", "TLSv1.2").build() ); final SslProfile sslProfile = sslService.profile("xpack.security.transport.ssl"); final SocketFactory factory = sslProfile.socketFactory(); try (SSLSocket socket = (SSLSocket) factory.createSocket()) { SocketAccess.doPrivileged(() -> socket.connect(serviceA.boundAddress().publishAddress().address())); CountDownLatch handshakeLatch = new CountDownLatch(1); HandshakeCompletedListener firstListener = event -> handshakeLatch.countDown(); socket.addHandshakeCompletedListener(firstListener); socket.startHandshake(); handshakeLatch.await(); socket.removeHandshakeCompletedListener(firstListener); OutputStreamStreamOutput stream = new OutputStreamStreamOutput(socket.getOutputStream()); stream.writeByte((byte) 'E'); stream.writeByte((byte) 'S'); stream.writeInt(-1); stream.flush(); CountDownLatch renegotiationLatch = new CountDownLatch(1); HandshakeCompletedListener secondListener = event -> renegotiationLatch.countDown(); socket.addHandshakeCompletedListener(secondListener); socket.startHandshake(); AtomicBoolean stopped = new AtomicBoolean(false); socket.setSoTimeout(10); Thread emptyReader = new Thread(() -> { while (stopped.get() == false) { try { socket.getInputStream().read(); } catch (SocketTimeoutException e) { // Ignore. We expect a timeout. } catch (IOException e) { throw new AssertionError(e); } } }); emptyReader.start(); renegotiationLatch.await(); stopped.set(true); emptyReader.join(); socket.removeHandshakeCompletedListener(secondListener); stream.writeByte((byte) 'E'); stream.writeByte((byte) 'S'); stream.writeInt(-1); stream.flush(); } } public void testSNIServerNameIsPropagated() throws Exception { assumeFalse("Can't run in a FIPS JVM, TrustAllConfig is not a SunJSSE TrustManagers", inFipsJvm()); SSLService sslService = createSSLService(); final SslProfile sslProfile = sslService.profile("xpack.security.transport.ssl"); final SSLContext sslContext = sslProfile.sslContext(); final SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory(); final String sniIp = "sni-hostname"; final SNIHostName sniHostName = new SNIHostName(sniIp); final CountDownLatch latch = new CountDownLatch(2); try (SSLServerSocket sslServerSocket = (SSLServerSocket) serverSocketFactory.createServerSocket()) { SSLParameters sslParameters = sslServerSocket.getSSLParameters(); sslParameters.setSNIMatchers(Collections.singletonList(new SNIMatcher(0) { @Override public boolean matches(SNIServerName sniServerName) { if (sniHostName.equals(sniServerName)) { latch.countDown(); return true; } else { return false; } } })); sslServerSocket.setSSLParameters(sslParameters); SocketAccess.doPrivileged(() -> sslServerSocket.bind(getLocalEphemeral())); new Thread(() -> { try { SSLSocket acceptedSocket = (SSLSocket) SocketAccess.doPrivileged(sslServerSocket::accept); // A read call will execute the handshake int byteRead = acceptedSocket.getInputStream().read(); assertEquals('E', byteRead); latch.countDown(); IOUtils.closeWhileHandlingException(acceptedSocket); } catch (IOException e) { throw new UncheckedIOException(e); } }).start(); InetSocketAddress serverAddress = (InetSocketAddress) SocketAccess.doPrivileged(sslServerSocket::getLocalSocketAddress); Settings settings = Settings.builder().put("xpack.security.transport.ssl.verification_mode", "none").build(); try (MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, settings)) { HashMap<String, String> attributes = new HashMap<>(); attributes.put("server_name", sniIp); DiscoveryNode node = DiscoveryNodeUtils.create( "server_node_id", new TransportAddress(serverAddress), attributes, DiscoveryNodeRole.roles() ); new Thread(() -> { // noinspection ThrowableNotThrown connectToNodeExpectFailure(serviceC, node, TestProfiles.LIGHT_PROFILE); }).start(); latch.await(); } } } public void testInvalidSNIServerName() throws Exception { assumeFalse("Can't run in a FIPS JVM, TrustAllConfig is not a SunJSSE TrustManagers", inFipsJvm()); SSLService sslService = createSSLService(); final SslProfile sslProfile = sslService.profile("xpack.security.transport.ssl"); final SSLContext sslContext = sslProfile.sslContext(); final SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory(); final String sniIp = "invalid_hostname"; try (SSLServerSocket sslServerSocket = (SSLServerSocket) serverSocketFactory.createServerSocket()) { SocketAccess.doPrivileged(() -> sslServerSocket.bind(getLocalEphemeral())); new Thread(() -> { try { SocketAccess.doPrivileged(sslServerSocket::accept); } catch (IOException e) { // We except an IOException from the `accept` call because the server socket will be // closed before the call returns. } }).start(); InetSocketAddress serverAddress = (InetSocketAddress) SocketAccess.doPrivileged(sslServerSocket::getLocalSocketAddress); Settings settings = Settings.builder().put("xpack.security.transport.ssl.verification_mode", "none").build(); try (MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, settings)) { HashMap<String, String> attributes = new HashMap<>(); attributes.put("server_name", sniIp); DiscoveryNode node = DiscoveryNodeUtils.create( "server_node_id", new TransportAddress(serverAddress), attributes, DiscoveryNodeRole.roles() ); assertThat( connectToNodeExpectFailure(serviceC, node, TestProfiles.LIGHT_PROFILE).getMessage(), containsString("invalid DiscoveryNode server_name [invalid_hostname]") ); } } } public void testSecurityClientAuthenticationConfigs() throws Exception { Path testnodeCert = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt"); Path testnodeKey = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.pem"); Transport.Connection connection1 = serviceA.getConnection(serviceB.getLocalNode()); SSLEngine sslEngine = getSSLEngine(connection1); assertThat(sslEngine, notNullValue()); // test client authentication is default assertThat(sslEngine.getNeedClientAuth(), is(true)); assertThat(sslEngine.getWantClientAuth(), is(false)); // test required client authentication String value = randomCapitalization(SslClientAuthenticationMode.REQUIRED); Settings settings = Settings.builder().put("xpack.security.transport.ssl.client_authentication", value).build(); try ( MockTransportService service = buildService( "TS_REQUIRED_CLIENT_AUTH", VersionInformation.CURRENT, TransportVersion.current(), settings ) ) { TcpTransport originalTransport = (TcpTransport) service.getOriginalTransport(); try (Transport.Connection connection2 = openConnection(serviceA, service.getLocalNode(), TestProfiles.LIGHT_PROFILE)) { sslEngine = getEngineFromAcceptedChannel(originalTransport, connection2); assertThat(sslEngine.getNeedClientAuth(), is(true)); assertThat(sslEngine.getWantClientAuth(), is(false)); } } // test no client authentication value = randomCapitalization(SslClientAuthenticationMode.NONE); settings = Settings.builder().put("xpack.security.transport.ssl.client_authentication", value).build(); try ( MockTransportService service = buildService( "TS_NO_CLIENT_AUTH", VersionInformation.CURRENT, TransportVersion.current(), settings ) ) { TcpTransport originalTransport = (TcpTransport) service.getOriginalTransport(); try (Transport.Connection connection2 = openConnection(serviceA, service.getLocalNode(), TestProfiles.LIGHT_PROFILE)) { sslEngine = getEngineFromAcceptedChannel(originalTransport, connection2); assertThat(sslEngine.getNeedClientAuth(), is(false)); assertThat(sslEngine.getWantClientAuth(), is(false)); } } // test optional client authentication value = randomCapitalization(SslClientAuthenticationMode.OPTIONAL); settings = Settings.builder().put("xpack.security.transport.ssl.client_authentication", value).build(); try ( MockTransportService service = buildService( "TS_OPTIONAL_CLIENT_AUTH", VersionInformation.CURRENT, TransportVersion.current(), settings ) ) { TcpTransport originalTransport = (TcpTransport) service.getOriginalTransport(); try (Transport.Connection connection2 = openConnection(serviceA, service.getLocalNode(), TestProfiles.LIGHT_PROFILE)) { sslEngine = getEngineFromAcceptedChannel(originalTransport, connection2); assertThat(sslEngine.getNeedClientAuth(), is(false)); assertThat(sslEngine.getWantClientAuth(), is(true)); } } // test profile required client authentication value = randomCapitalization(SslClientAuthenticationMode.REQUIRED); settings = Settings.builder() .put("transport.profiles.client.port", "8000-9000") .put("transport.profiles.client.xpack.security.ssl.enabled", true) .put("transport.profiles.client.xpack.security.ssl.certificate", testnodeCert) .put("transport.profiles.client.xpack.security.ssl.key", testnodeKey) .put("transport.profiles.client.xpack.security.ssl.client_authentication", value) .build(); try ( MockTransportService service = buildService( "TS_PROFILE_REQUIRE_CLIENT_AUTH", VersionInformation.CURRENT, TransportVersion.current(), settings ) ) { TcpTransport originalTransport = (TcpTransport) service.getOriginalTransport(); TransportAddress clientAddress = originalTransport.profileBoundAddresses().get("client").publishAddress(); DiscoveryNode node = DiscoveryNodeUtils.create( service.getLocalNode().getId(), clientAddress, service.getLocalNode().getVersionInformation() ); try (Transport.Connection connection2 = openConnection(serviceA, node, TestProfiles.LIGHT_PROFILE)) { sslEngine = getEngineFromAcceptedChannel(originalTransport, connection2); assertEquals("client", getAcceptedChannel(originalTransport, connection2).getProfile()); assertThat(sslEngine.getNeedClientAuth(), is(true)); assertThat(sslEngine.getWantClientAuth(), is(false)); } } // test profile no client authentication value = randomCapitalization(SslClientAuthenticationMode.NONE); settings = Settings.builder() .put("transport.profiles.client.port", "8000-9000") .put("transport.profiles.client.xpack.security.ssl.enabled", true) .put("transport.profiles.client.xpack.security.ssl.certificate", testnodeCert) .put("transport.profiles.client.xpack.security.ssl.key", testnodeKey) .put("transport.profiles.client.xpack.security.ssl.client_authentication", value) .build(); try ( MockTransportService service = buildService( "TS_PROFILE_NO_CLIENT_AUTH", VersionInformation.CURRENT, TransportVersion.current(), settings ) ) { TcpTransport originalTransport = (TcpTransport) service.getOriginalTransport(); TransportAddress clientAddress = originalTransport.profileBoundAddresses().get("client").publishAddress(); DiscoveryNode node = DiscoveryNodeUtils.create( service.getLocalNode().getId(), clientAddress, service.getLocalNode().getVersionInformation() ); try (Transport.Connection connection2 = openConnection(serviceA, node, TestProfiles.LIGHT_PROFILE)) { sslEngine = getEngineFromAcceptedChannel(originalTransport, connection2); assertEquals("client", getAcceptedChannel(originalTransport, connection2).getProfile()); assertThat(sslEngine.getNeedClientAuth(), is(false)); assertThat(sslEngine.getWantClientAuth(), is(false)); } } // test profile optional client authentication value = randomCapitalization(SslClientAuthenticationMode.OPTIONAL); settings = Settings.builder() .put("transport.profiles.client.port", "8000-9000") .put("transport.profiles.client.xpack.security.ssl.enabled", true) .put("transport.profiles.client.xpack.security.ssl.certificate", testnodeCert) .put("transport.profiles.client.xpack.security.ssl.key", testnodeKey) .put("transport.profiles.client.xpack.security.ssl.client_authentication", value) .build(); try ( MockTransportService service = buildService( "TS_PROFILE_OPTIONAL_CLIENT_AUTH", VersionInformation.CURRENT, TransportVersion.current(), settings ) ) { TcpTransport originalTransport = (TcpTransport) service.getOriginalTransport(); TransportAddress clientAddress = originalTransport.profileBoundAddresses().get("client").publishAddress(); DiscoveryNode node = DiscoveryNodeUtils.create( service.getLocalNode().getId(), clientAddress, service.getLocalNode().getVersionInformation() ); try (Transport.Connection connection2 = openConnection(serviceA, node, TestProfiles.LIGHT_PROFILE)) { sslEngine = getEngineFromAcceptedChannel(originalTransport, connection2); assertEquals("client", getAcceptedChannel(originalTransport, connection2).getProfile()); assertThat(sslEngine.getNeedClientAuth(), is(false)); assertThat(sslEngine.getWantClientAuth(), is(true)); } } } public void testClientChannelUsesSeparateSslConfigurationForRemoteCluster() throws Exception { final Path testnodeCert = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"); final Path testnodeKey = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.pem"); final ConnectionProfile connectionProfile = ConnectionProfile.resolveConnectionProfile( new ConnectionProfile.Builder().setTransportProfile("_remote_cluster") .addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ) .build(), TestProfiles.LIGHT_PROFILE ); final Settings fcSettings = Settings.builder() .put("remote_cluster_server.enabled", "true") .put("remote_cluster.port", "0") .put("xpack.security.remote_cluster_server.ssl.key", testnodeKey) .put("xpack.security.remote_cluster_server.ssl.certificate", testnodeCert) .put("xpack.security.remote_cluster_server.ssl.client_authentication", "none") .build(); try (MockTransportService fcService = buildService("FC", VersionInformation.CURRENT, TransportVersion.current(), fcSettings)) { final TcpTransport originalTransport = (TcpTransport) fcService.getOriginalTransport(); final TransportAddress remoteAccessAddress = originalTransport.profileBoundAddresses().get("_remote_cluster").publishAddress(); final DiscoveryNode node = DiscoveryNodeUtils.create( fcService.getLocalNode().getId(), remoteAccessAddress, fcService.getLocalNode().getVersionInformation() ); // 1. Connection will fail because FC server certificate is not trusted by default final Settings qcSettings1 = Settings.builder().build(); try (MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings1)) { final ConnectTransportException e = openConnectionExpectFailure(qcService, node, connectionProfile); assertThat( e.getRootCause().getMessage(), anyOf( containsString("unable to find valid certification path"), containsString("Unable to find certificate chain"), containsString("Unable to construct a valid chain") ) ); } // 2. Connection will success because QC does not verify FC server certificate final Settings qcSettings2 = Settings.builder() .put("xpack.security.remote_cluster_client.ssl.verification_mode", "none") .put("remote_cluster.tcp.keep_alive", "false") .build(); try ( MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings2); Transport.Connection connection = openConnection(qcService, node, connectionProfile) ) { assertThat(connection, instanceOf(StubbableTransport.WrappedConnection.class)); Transport.Connection conn = ((StubbableTransport.WrappedConnection) connection).getConnection(); assertThat(conn, instanceOf(TcpTransport.NodeChannels.class)); TcpTransport.NodeChannels nodeChannels = (TcpTransport.NodeChannels) conn; for (TcpChannel channel : nodeChannels.getChannels()) { assertFalse(channel.isServerChannel()); assertThat(channel.getProfile(), equalTo("_remote_cluster")); final SSLEngine sslEngine = SSLEngineUtils.getSSLEngine(channel); assertThat(sslEngine.getUseClientMode(), is(true)); assertThat(channel, instanceOf(Netty4TcpChannel.class)); final Map<String, Object> options = ((Netty4TcpChannel) channel).getNettyChannel() .config() .getOptions() .entrySet() .stream() .filter(entry -> entry.getKey() instanceof NioChannelOption<?>) .collect(Collectors.toUnmodifiableMap(entry -> entry.getKey().name(), Map.Entry::getValue)); assertThat(options.get(ChannelOption.SO_KEEPALIVE.name()), is(false)); } final TcpChannel acceptedChannel = getAcceptedChannel(originalTransport, connection); assertThat(acceptedChannel.getProfile(), equalTo("_remote_cluster")); } // 3. Connection will success because QC is explicitly configured to trust FC server certificate final Settings qcSettings3 = Settings.builder() .put("xpack.security.remote_cluster_client.ssl.certificate_authorities", testnodeCert) .put("xpack.security.remote_cluster_client.ssl.verification_mode", "full") .put("remote_cluster.tcp.keep_idle", 100) .put("remote_cluster.tcp.keep_interval", 101) .put("remote_cluster.tcp.keep_count", 102) .build(); try ( MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings3); Transport.Connection connection = openConnection(qcService, node, connectionProfile) ) { assertThat(connection, instanceOf(StubbableTransport.WrappedConnection.class)); Transport.Connection conn = ((StubbableTransport.WrappedConnection) connection).getConnection(); assertThat(conn, instanceOf(TcpTransport.NodeChannels.class)); TcpTransport.NodeChannels nodeChannels = (TcpTransport.NodeChannels) conn; for (TcpChannel channel : nodeChannels.getChannels()) { assertFalse(channel.isServerChannel()); assertThat(channel.getProfile(), equalTo("_remote_cluster")); final SSLEngine sslEngine = SSLEngineUtils.getSSLEngine(channel); assertThat(sslEngine.getUseClientMode(), is(true)); assertThat(channel, instanceOf(Netty4TcpChannel.class)); final Map<String, Object> options = ((Netty4TcpChannel) channel).getNettyChannel() .config() .getOptions() .entrySet() .stream() .filter(entry -> entry.getKey() instanceof NioChannelOption<?>) .collect(Collectors.toUnmodifiableMap(entry -> entry.getKey().name(), Map.Entry::getValue)); assertThat(options.get(ChannelOption.SO_KEEPALIVE.name()), is(true)); if (false == Constants.WINDOWS) { assertThat(options.get(OPTION_TCP_KEEP_IDLE.name()), equalTo(100)); assertThat(options.get(OPTION_TCP_KEEP_INTERVAL.name()), equalTo(101)); assertThat(options.get(OPTION_TCP_KEEP_COUNT.name()), equalTo(102)); } } final TcpChannel acceptedChannel = getAcceptedChannel(originalTransport, connection); assertThat(acceptedChannel.getProfile(), equalTo("_remote_cluster")); } } } public void testRemoteClusterCanWorkWithoutSSL() throws Exception { final ConnectionProfile connectionProfile = ConnectionProfile.resolveConnectionProfile( new ConnectionProfile.Builder().setTransportProfile("_remote_cluster") .addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ) .build(), TestProfiles.LIGHT_PROFILE ); final Settings fcSettings = Settings.builder() .put("remote_cluster_server.enabled", "true") .put("remote_cluster.port", "0") .put("xpack.security.remote_cluster_server.ssl.enabled", "false") .build(); try (MockTransportService fcService = buildService("FC", VersionInformation.CURRENT, TransportVersion.current(), fcSettings)) { final TcpTransport originalTransport = (TcpTransport) fcService.getOriginalTransport(); final TransportAddress remoteAccessAddress = originalTransport.profileBoundAddresses().get("_remote_cluster").publishAddress(); final DiscoveryNode node = DiscoveryNodeUtils.create( fcService.getLocalNode().getId(), remoteAccessAddress, fcService.getLocalNode().getVersionInformation() ); final Settings qcSettings = Settings.builder().put("xpack.security.remote_cluster_client.ssl.enabled", "false").build(); try ( MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings); Transport.Connection connection = openConnection(qcService, node, connectionProfile) ) { assertThat(connection, instanceOf(StubbableTransport.WrappedConnection.class)); Transport.Connection conn = ((StubbableTransport.WrappedConnection) connection).getConnection(); assertThat(conn, instanceOf(TcpTransport.NodeChannels.class)); TcpTransport.NodeChannels nodeChannels = (TcpTransport.NodeChannels) conn; for (TcpChannel channel : nodeChannels.getChannels()) { assertFalse(channel.isServerChannel()); assertThat(channel.getProfile(), equalTo("_remote_cluster")); } final TcpChannel acceptedChannel = getAcceptedChannel(originalTransport, connection); assertThat(acceptedChannel.getProfile(), equalTo("_remote_cluster")); } } } public void testGetClientBootstrap() { final ConnectionProfile connectionProfile = ConnectionProfile.resolveConnectionProfile( new ConnectionProfile.Builder().setTransportProfile("_remote_cluster") .addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ) .build(), TestProfiles.LIGHT_PROFILE ); // 1. Configuration for default profile only final Settings.Builder builder1 = Settings.builder(); if (randomBoolean()) { builder1.put(TransportSettings.TCP_NO_DELAY.getKey(), randomBoolean()) .put(TransportSettings.TCP_KEEP_ALIVE.getKey(), randomBoolean()) .put(TransportSettings.TCP_KEEP_IDLE.getKey(), randomIntBetween(-1, 300)) .put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), randomIntBetween(-1, 300)) .put(TransportSettings.TCP_KEEP_COUNT.getKey(), randomIntBetween(-1, 300)) .put(TransportSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(randomIntBetween(-1, 1000))) .put(TransportSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(randomIntBetween(-1, 1000))) .put(TransportSettings.TCP_REUSE_ADDRESS.getKey(), randomBoolean()); } final Settings qcSettings1 = builder1.build(); try (MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings1)) { final var transport = (TestSecurityNetty4ServerTransport) qcService.getOriginalTransport(); // RCS remote cluster client final Bootstrap rcsBootstrap = transport.getClientBootstrap(connectionProfile); // Legacy remote cluster client final Bootstrap legacyBootstrap = transport.getClientBootstrap(TestProfiles.LIGHT_PROFILE); // identical assertThat(rcsBootstrap.config().options(), equalTo(legacyBootstrap.config().options())); // The following attempts to ensure the super class's createClientBootstrap method does not change. // It does that by checking all configured options are known and expected, i.e. no option is added or removed. // The check is to approximately ensure SecurityNetty4Transport#getClientBootstrap does not become stale without notice final HashSet<ChannelOption<?>> expectedChannelOptions = new HashSet<>( Set.of( ChannelOption.ALLOCATOR, ChannelOption.TCP_NODELAY, ChannelOption.SO_KEEPALIVE, ChannelOption.RCVBUF_ALLOCATOR, ChannelOption.SO_REUSEADDR ) ); if (TransportSettings.TCP_KEEP_ALIVE.get(qcSettings1)) { if (TransportSettings.TCP_KEEP_IDLE.get(qcSettings1) >= 0) { expectedChannelOptions.add(OPTION_TCP_KEEP_IDLE); } if (TransportSettings.TCP_KEEP_INTERVAL.get(qcSettings1) >= 0) { expectedChannelOptions.add(OPTION_TCP_KEEP_INTERVAL); } if (TransportSettings.TCP_KEEP_COUNT.get(qcSettings1) >= 0) { expectedChannelOptions.add(OPTION_TCP_KEEP_COUNT); } } if (TransportSettings.TCP_SEND_BUFFER_SIZE.get(qcSettings1).getBytes() > 0) { expectedChannelOptions.add(ChannelOption.SO_SNDBUF); } if (TransportSettings.TCP_RECEIVE_BUFFER_SIZE.get(qcSettings1).getBytes() > 0) { expectedChannelOptions.add(ChannelOption.SO_RCVBUF); } // legacyBootstrap is the same as default clientBootstrap from the super class's createClientBootstrap method assertThat(legacyBootstrap.config().options().keySet(), equalTo(expectedChannelOptions)); } // 2. Different settings for _remote_cluster final Settings.Builder builder2 = Settings.builder(); if (randomBoolean()) { builder2.put(TransportSettings.TCP_NO_DELAY.getKey(), true).put(TransportSettings.TCP_KEEP_ALIVE.getKey(), true); } final Settings qcSettings2 = builder2.put(TransportSettings.TCP_KEEP_IDLE.getKey(), 200) .put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), 201) .put(TransportSettings.TCP_KEEP_COUNT.getKey(), 202) .put(TransportSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(1)) .put(TransportSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(1)) .put(TransportSettings.TCP_REUSE_ADDRESS.getKey(), true) .put(RemoteClusterPortSettings.TCP_NO_DELAY.getKey(), false) .put(RemoteClusterPortSettings.TCP_KEEP_ALIVE.getKey(), false) .put(RemoteClusterPortSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(42)) .put(RemoteClusterPortSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(99)) .put(RemoteClusterPortSettings.TCP_REUSE_ADDRESS.getKey(), false) .build(); try (MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings2)) { final var transport = (TestSecurityNetty4ServerTransport) qcService.getOriginalTransport(); // RCS remote cluster client final Map<ChannelOption<?>, Object> rcsOptions = transport.getClientBootstrap(connectionProfile).config().options(); assertThat(rcsOptions.get(ChannelOption.TCP_NODELAY), is(false)); assertThat(rcsOptions.get(ChannelOption.SO_KEEPALIVE), is(false)); assertThat(rcsOptions.get(OPTION_TCP_KEEP_IDLE), nullValue()); assertThat(rcsOptions.get(OPTION_TCP_KEEP_INTERVAL), nullValue()); assertThat(rcsOptions.get(OPTION_TCP_KEEP_COUNT), nullValue()); assertThat(rcsOptions.get(ChannelOption.SO_SNDBUF), equalTo(42)); assertThat(rcsOptions.get(ChannelOption.SO_RCVBUF), equalTo(99)); assertThat(rcsOptions.get(ChannelOption.SO_REUSEADDR), is(false)); // Legacy remote cluster client final Map<ChannelOption<?>, Object> legacyOptions = transport.getClientBootstrap(TestProfiles.LIGHT_PROFILE).config().options(); assertThat(legacyOptions.get(ChannelOption.TCP_NODELAY), is(true)); assertThat(legacyOptions.get(ChannelOption.SO_KEEPALIVE), is(true)); assertThat(legacyOptions.get(OPTION_TCP_KEEP_IDLE), equalTo(200)); assertThat(legacyOptions.get(OPTION_TCP_KEEP_INTERVAL), equalTo(201)); assertThat(legacyOptions.get(OPTION_TCP_KEEP_COUNT), equalTo(202)); assertThat(legacyOptions.get(ChannelOption.SO_SNDBUF), equalTo(1)); assertThat(legacyOptions.get(ChannelOption.SO_RCVBUF), equalTo(1)); assertThat(legacyOptions.get(ChannelOption.SO_REUSEADDR), is(true)); } // 3. Different keep_idle, keep_interval, keep_count final Settings.Builder builder3 = Settings.builder(); if (randomBoolean()) { builder3.put(TransportSettings.TCP_KEEP_ALIVE.getKey(), true).put(RemoteClusterPortSettings.TCP_KEEP_ALIVE.getKey(), true); } final Settings qcSettings3 = builder3.put(TransportSettings.TCP_KEEP_IDLE.getKey(), 200) .put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), 201) .put(TransportSettings.TCP_KEEP_COUNT.getKey(), 202) .put(RemoteClusterPortSettings.TCP_KEEP_IDLE.getKey(), 100) .put(RemoteClusterPortSettings.TCP_KEEP_INTERVAL.getKey(), 101) .put(RemoteClusterPortSettings.TCP_KEEP_COUNT.getKey(), 102) .build(); try (MockTransportService qcService = buildService("QC", VersionInformation.CURRENT, TransportVersion.current(), qcSettings3)) { final var transport = (TestSecurityNetty4ServerTransport) qcService.getOriginalTransport(); // RCS remote cluster client final Map<ChannelOption<?>, Object> rcsOptions = transport.getClientBootstrap(connectionProfile).config().options(); assertThat(rcsOptions.get(ChannelOption.SO_KEEPALIVE), is(true)); assertThat(rcsOptions.get(OPTION_TCP_KEEP_IDLE), equalTo(100)); assertThat(rcsOptions.get(OPTION_TCP_KEEP_INTERVAL), equalTo(101)); assertThat(rcsOptions.get(OPTION_TCP_KEEP_COUNT), equalTo(102)); // Legacy remote cluster client final Map<ChannelOption<?>, Object> legacyOptions = transport.getClientBootstrap(TestProfiles.LIGHT_PROFILE).config().options(); assertThat(legacyOptions.get(ChannelOption.SO_KEEPALIVE), is(true)); assertThat(legacyOptions.get(OPTION_TCP_KEEP_IDLE), equalTo(200)); assertThat(legacyOptions.get(OPTION_TCP_KEEP_INTERVAL), equalTo(201)); assertThat(legacyOptions.get(OPTION_TCP_KEEP_COUNT), equalTo(202)); } } public void testTcpHandshakeTimeout() throws IOException { assumeFalse("Can't run in a FIPS JVM, TrustAllConfig is not a SunJSSE TrustManagers", inFipsJvm()); SSLService sslService = createSSLService(); final SslProfile sslProfile = sslService.profile("xpack.security.transport.ssl"); final SSLContext sslContext = sslProfile.sslContext(); final SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory(); // use latch to to ensure that the accepted socket below isn't closed before the handshake times out final CountDownLatch doneLatch = new CountDownLatch(1); try (ServerSocket socket = serverSocketFactory.createServerSocket()) { socket.bind(getLocalEphemeral(), 1); socket.setReuseAddress(true); new Thread(() -> { SSLSocket acceptedSocket = null; try { acceptedSocket = (SSLSocket) SocketAccess.doPrivileged(socket::accept); // A read call will execute the ssl handshake int byteRead = acceptedSocket.getInputStream().read(); assertEquals('E', byteRead); safeAwait(doneLatch); } catch (Exception e) { throw new AssertionError(e); } finally { IOUtils.closeWhileHandlingException(acceptedSocket); } }).start(); DiscoveryNode dummy = DiscoveryNodeUtils.builder("TEST") .address(new TransportAddress(socket.getInetAddress(), socket.getLocalPort())) .roles(emptySet()) .version(version0) .build(); ConnectionProfile.Builder builder = new ConnectionProfile.Builder(); builder.addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ); builder.setHandshakeTimeout(TimeValue.timeValueMillis(1)); Settings settings = Settings.builder().put("xpack.security.transport.ssl.verification_mode", "none").build(); try (MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, settings)) { assertEquals( "[][" + dummy.getAddress() + "] handshake_timeout[1ms]", connectToNodeExpectFailure(serviceC, dummy, builder.build()).getMessage() ); } } finally { doneLatch.countDown(); } } @TestLogging(reason = "inbound timeout is reported at TRACE", value = "org.elasticsearch.transport.netty4.ESLoggingHandler:TRACE") public void testTlsHandshakeTimeout() throws IOException { runOutboundTlsHandshakeTimeoutTest(null); runOutboundTlsHandshakeTimeoutTest(randomLongBetween(1, 500)); runInboundTlsHandshakeTimeoutTest(null); runInboundTlsHandshakeTimeoutTest(randomLongBetween(1, 500)); } private void runOutboundTlsHandshakeTimeoutTest(@Nullable /* to use the default */ Long handshakeTimeoutMillis) throws IOException { final CountDownLatch doneLatch = new CountDownLatch(1); try (ServerSocket socket = new MockServerSocket()) { socket.bind(getLocalEphemeral(), 1); socket.setReuseAddress(true); new Thread(() -> { try (Socket ignored = socket.accept()) { doneLatch.await(); } catch (Exception e) { throw new AssertionError(e); } }).start(); DiscoveryNode dummy = DiscoveryNodeUtils.builder("TEST") .address(new TransportAddress(socket.getInetAddress(), socket.getLocalPort())) .roles(emptySet()) .version(version0) .build(); ConnectionProfile.Builder builder = new ConnectionProfile.Builder(); builder.addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ); final ConnectTransportException exception; final var transportSettings = Settings.builder(); if (handshakeTimeoutMillis == null) { handshakeTimeoutMillis = 10000L; // default } else { transportSettings.put("xpack.security.transport.ssl.handshake_timeout", TimeValue.timeValueMillis(handshakeTimeoutMillis)); } try (var service = buildService(getTestName(), version0, transportVersion0, transportSettings.build())) { final var future = new TestPlainActionFuture<Releasable>(); service.connectToNode(dummy, builder.build(), future); exception = expectThrows(ExecutionException.class, ConnectTransportException.class, future::get); // long wait assertEquals("[][" + dummy.getAddress() + "] connect_exception", exception.getMessage()); assertThat( asInstanceOf(SslHandshakeTimeoutException.class, exception.getCause()).getMessage(), equalTo("handshake timed out after " + handshakeTimeoutMillis + "ms") ); } } finally { doneLatch.countDown(); } } @SuppressForbidden(reason = "test needs a simple TCP connection") private void runInboundTlsHandshakeTimeoutTest(@Nullable /* to use the default */ Long handshakeTimeoutMillis) throws IOException { final var transportSettings = Settings.builder(); if (handshakeTimeoutMillis == null) { handshakeTimeoutMillis = 10000L; // default } else { transportSettings.put("xpack.security.transport.ssl.handshake_timeout", TimeValue.timeValueMillis(handshakeTimeoutMillis)); } try ( var service = buildService(getTestName(), version0, transportVersion0, transportSettings.build()); Socket clientSocket = new MockSocket(); MockLog mockLog = MockLog.capture("org.elasticsearch.transport.netty4.ESLoggingHandler") ) { mockLog.addExpectation( new MockLog.SeenEventExpectation( "timeout event message", "org.elasticsearch.transport.netty4.ESLoggingHandler", Level.TRACE, "SslHandshakeTimeoutException: handshake timed out after " + handshakeTimeoutMillis + "ms" ) ); clientSocket.connect(service.boundAddress().boundAddresses()[0].address()); expectThrows(EOFException.class, () -> clientSocket.getInputStream().skipNBytes(Long.MAX_VALUE)); mockLog.assertAllExpectationsMatched(); } } public void testTcpHandshakeConnectionReset() throws IOException, InterruptedException { assumeFalse("Can't run in a FIPS JVM, TrustAllConfig is not a SunJSSE TrustManagers", inFipsJvm()); SSLService sslService = createSSLService(); final SslProfile sslProfile = sslService.profile("xpack.security.transport.ssl"); final SSLContext sslContext = sslProfile.sslContext(); final SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory(); try (ServerSocket socket = serverSocketFactory.createServerSocket()) { socket.bind(getLocalEphemeral(), 1); socket.setReuseAddress(true); DiscoveryNode dummy = DiscoveryNodeUtils.builder("TEST") .address(new TransportAddress(socket.getInetAddress(), socket.getLocalPort())) .roles(emptySet()) .version(version0) .build(); Thread t = new Thread(() -> { try (Socket accept = SocketAccess.doPrivileged(socket::accept)) { // A read call will execute the ssl handshake int byteRead = accept.getInputStream().read(); assertEquals('E', byteRead); } catch (IOException e) { throw new UncheckedIOException(e); } }); t.start(); ConnectionProfile.Builder builder = new ConnectionProfile.Builder(); builder.addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ); builder.setHandshakeTimeout(TimeValue.timeValueHours(1)); Settings settings = Settings.builder().put("xpack.security.transport.ssl.verification_mode", "none").build(); try (MockTransportService serviceC = buildService("TS_C", version0, transportVersion0, settings)) { ConnectTransportException ex = connectToNodeExpectFailure(serviceC, dummy, builder.build()); assertEquals("[][" + dummy.getAddress() + "] general node connection failure", ex.getMessage()); assertThat(ex.getCause().getMessage(), startsWith("handshake failed")); } t.join(); } } public static String randomCapitalization(SslClientAuthenticationMode mode) { return randomFrom(mode.name(), mode.name().toLowerCase(Locale.ROOT)); } private SSLEngine getEngineFromAcceptedChannel(TcpTransport transport, Transport.Connection connection) throws Exception { return SSLEngineUtils.getSSLEngine(getAcceptedChannel(transport, connection)); } private TcpChannel getAcceptedChannel(TcpTransport transport, Transport.Connection connection) throws Exception { InetSocketAddress localAddress = getSingleChannel(connection).getLocalAddress(); AtomicReference<TcpChannel> accepted = new AtomicReference<>(); assertBusy(() -> { Optional<TcpChannel> maybeAccepted = getAcceptedChannels(transport).stream() .filter(c -> c.getRemoteAddress().equals(localAddress)) .findFirst(); assertTrue(maybeAccepted.isPresent()); accepted.set(maybeAccepted.get()); }); return accepted.get(); } private SSLEngine getSSLEngine(Transport.Connection connection) { return SSLEngineUtils.getSSLEngine(getSingleChannel(connection)); } private TcpChannel getSingleChannel(Transport.Connection connection) { StubbableTransport.WrappedConnection wrappedConnection = (StubbableTransport.WrappedConnection) connection; TcpTransport.NodeChannels nodeChannels = (TcpTransport.NodeChannels) wrappedConnection.getConnection(); return nodeChannels.getChannels().get(0); } static
SimpleSecurityNetty4ServerTransportTests
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/PojoSerializerUpgradeTestSpecifications.java
{ "start": 2034, "end": 3218 }
enum ____ { RED, BLUE, GREEN } public String name; public int age; public Color favoriteColor; public boolean married; public StaticSchemaPojo() {} public StaticSchemaPojo(String name, int age, Color favoriteColor, boolean married) { this.name = name; this.age = age; this.favoriteColor = favoriteColor; this.married = married; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof StaticSchemaPojo)) { return false; } StaticSchemaPojo other = (StaticSchemaPojo) obj; return Objects.equals(name, other.name) && age == other.age && favoriteColor == other.favoriteColor && married == other.married; } @Override public int hashCode() { return Objects.hash(name, age, favoriteColor, married); } } @SuppressWarnings("WeakerAccess") public static
Color
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/MappingTest_update.java
{ "start": 256, "end": 1975 }
class ____ extends TestCase { private String sql = "update user set f1 = 1 where id = 3"; Map<String, String> mapping = Collections.singletonMap("user", "user_01"); public void test_mapping() throws Exception { String result = SQLUtils.refactor(sql, null, mapping); assertEquals("UPDATE user_01\n" + "SET f1 = 1\n" + "WHERE id = 3", result); } public void test_mapping_mysql() throws Exception { String result = SQLUtils.refactor(sql, JdbcConstants.MYSQL, mapping); assertEquals("UPDATE user_01\n" + "SET f1 = 1\n" + "WHERE id = 3", result); } public void test_mapping_pg() throws Exception { String result = SQLUtils.refactor(sql, JdbcConstants.POSTGRESQL, mapping); assertEquals("UPDATE user_01\n" + "SET f1 = 1\n" + "WHERE id = 3", result); } public void test_mapping_oracle() throws Exception { String result = SQLUtils.refactor(sql, JdbcConstants.ORACLE, mapping); assertEquals("UPDATE user_01\n" + "SET f1 = 1\n" + "WHERE id = 3", result); } public void test_mapping_sqlserver() throws Exception { String result = SQLUtils.refactor(sql, JdbcConstants.SQL_SERVER, mapping); assertEquals("UPDATE user_01\n" + "SET f1 = 1\n" + "WHERE id = 3", result); } public void test_mapping_db2() throws Exception { String result = SQLUtils.refactor(sql, JdbcConstants.DB2, mapping); assertEquals("UPDATE user_01\n" + "SET f1 = 1\n" + "WHERE id = 3", result); } }
MappingTest_update
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java
{ "start": 1309, "end": 11352 }
class ____ { @Test void isEmpty() { assertThat(CollectionUtils.isEmpty((Set<Object>) null)).isTrue(); assertThat(CollectionUtils.isEmpty((Map<String, String>) null)).isTrue(); assertThat(CollectionUtils.isEmpty(new HashMap<>())).isTrue(); assertThat(CollectionUtils.isEmpty(new HashSet<>())).isTrue(); List<Object> list = new ArrayList<>(); list.add(new Object()); assertThat(CollectionUtils.isEmpty(list)).isFalse(); Map<String, String> map = new HashMap<>(); map.put("foo", "bar"); assertThat(CollectionUtils.isEmpty(map)).isFalse(); } @Test void mergeArrayIntoCollection() { Object[] arr = new Object[] {"value1", "value2"}; List<Comparable<?>> list = new ArrayList<>(); list.add("value3"); CollectionUtils.mergeArrayIntoCollection(arr, list); assertThat(list).containsExactly("value3", "value1", "value2"); } @Test void mergePrimitiveArrayIntoCollection() { int[] arr = new int[] {1, 2}; List<Comparable<?>> list = new ArrayList<>(); list.add(3); CollectionUtils.mergeArrayIntoCollection(arr, list); assertThat(list).containsExactly(3, 1, 2); } @Test void mergePropertiesIntoMap() { Properties defaults = new Properties(); defaults.setProperty("prop1", "value1"); Properties props = new Properties(defaults); props.setProperty("prop2", "value2"); props.put("prop3", 3); Map<String, Object> map = new HashMap<>(); map.put("prop4", "value4"); CollectionUtils.mergePropertiesIntoMap(props, map); assertThat(map.get("prop1")).isEqualTo("value1"); assertThat(map.get("prop2")).isEqualTo("value2"); assertThat(map.get("prop3")).isEqualTo(3); assertThat(map.get("prop4")).isEqualTo("value4"); } @Test void containsWithIterator() { assertThat(CollectionUtils.contains((Iterator<String>) null, "myElement")).isFalse(); assertThat(CollectionUtils.contains(List.of().iterator(), "myElement")).isFalse(); List<String> list = Arrays.asList("myElement", null); assertThat(CollectionUtils.contains(list.iterator(), "myElement")).isTrue(); assertThat(CollectionUtils.contains(list.iterator(), null)).isTrue(); } @Test void containsWithEnumeration() { assertThat(CollectionUtils.contains((Enumeration<String>) null, "myElement")).isFalse(); assertThat(CollectionUtils.contains(Collections.enumeration(List.of()), "myElement")).isFalse(); List<String> list = Arrays.asList("myElement", null); Enumeration<String> enumeration = Collections.enumeration(list); assertThat(CollectionUtils.contains(enumeration, "myElement")).isTrue(); assertThat(CollectionUtils.contains(enumeration, null)).isTrue(); } @Test void containsAny() { List<String> source = new ArrayList<>(); source.add("abc"); source.add("def"); source.add("ghi"); List<String> candidates = new ArrayList<>(); candidates.add("xyz"); candidates.add("def"); candidates.add("abc"); assertThat(CollectionUtils.containsAny(source, candidates)).isTrue(); candidates.remove("def"); assertThat(CollectionUtils.containsAny(source, candidates)).isTrue(); candidates.remove("abc"); assertThat(CollectionUtils.containsAny(source, candidates)).isFalse(); source.add(null); assertThat(CollectionUtils.containsAny(source, candidates)).isFalse(); candidates.add(null); assertThat(CollectionUtils.containsAny(source, candidates)).isTrue(); } @Test void containsInstanceWithNullCollection() { assertThat(CollectionUtils.containsInstance(null, this)).isFalse(); } @Test void containsInstanceWithInstancesThatAreEqualButDistinct() { List<Instance> list = List.of(new Instance("fiona")); assertThat(CollectionUtils.containsInstance(list, new Instance("fiona"))).isFalse(); } @Test void containsInstanceWithSameInstance() { Instance fiona = new Instance("fiona"); Instance apple = new Instance("apple"); List<Instance> list = List.of(fiona, apple); assertThat(CollectionUtils.containsInstance(list, fiona)).isTrue(); } @Test void containsInstanceWithNullInstance() { Instance fiona = new Instance("fiona"); List<Instance> list = List.of(fiona); assertThat(CollectionUtils.containsInstance(list, null)).isFalse(); list = Arrays.asList(fiona, null); assertThat(CollectionUtils.containsInstance(list, null)).isTrue(); } @Test void findFirstMatch() { List<String> source = new ArrayList<>(); source.add("abc"); source.add("def"); source.add("ghi"); List<String> candidates = new ArrayList<>(); candidates.add("xyz"); candidates.add("def"); candidates.add("abc"); assertThat(CollectionUtils.findFirstMatch(source, candidates)).isEqualTo("def"); source.clear(); source.add(null); assertThat(CollectionUtils.findFirstMatch(source, candidates)).isNull(); candidates.add(null); assertThat(CollectionUtils.findFirstMatch(source, candidates)).isNull(); } @Test void findValueOfType() { assertThat(CollectionUtils.findValueOfType(List.of(1), Integer.class)).isEqualTo(1); assertThat(CollectionUtils.findValueOfType(Set.of(2), Integer.class)).isEqualTo(2); } @Test void findValueOfTypeWithNullType() { assertThat(CollectionUtils.findValueOfType(List.of(1), (Class<?>) null)).isEqualTo(1); } @Test void findValueOfTypeWithNullCollection() { assertThat(CollectionUtils.findValueOfType(null, Integer.class)).isNull(); } @Test void findValueOfTypeWithEmptyCollection() { assertThat(CollectionUtils.findValueOfType(List.of(), Integer.class)).isNull(); } @Test void findValueOfTypeWithMoreThanOneValue() { assertThat(CollectionUtils.findValueOfType(List.of(1, 2), Integer.class)).isNull(); } @Test void hasUniqueObject() { List<String> list = new ArrayList<>(); list.add("myElement"); list.add("myOtherElement"); assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); list = new ArrayList<>(); list.add("myElement"); assertThat(CollectionUtils.hasUniqueObject(list)).isTrue(); list = new ArrayList<>(); list.add("myElement"); list.add(null); assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); list = new ArrayList<>(); list.add(null); list.add("myElement"); assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); list = new ArrayList<>(); list.add(null); list.add(null); assertThat(CollectionUtils.hasUniqueObject(list)).isTrue(); list = new ArrayList<>(); list.add(null); assertThat(CollectionUtils.hasUniqueObject(list)).isTrue(); list = new ArrayList<>(); assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); } @Test void findCommonElementType() { List<Integer> integerList = new ArrayList<>(); integerList.add(1); integerList.add(2); assertThat(CollectionUtils.findCommonElementType(integerList)).isEqualTo(Integer.class); } @Test void findCommonElementTypeWithEmptyCollection() { List<Integer> emptyList = new ArrayList<>(); assertThat(CollectionUtils.findCommonElementType(emptyList)).isNull(); } @Test void findCommonElementTypeWithDifferentElementType() { List<Object> list = new ArrayList<>(); list.add(1); list.add("foo"); assertThat(CollectionUtils.findCommonElementType(list)).isNull(); } @Test void firstElementWithSet() { Set<Integer> set = new HashSet<>(); set.add(17); set.add(3); set.add(2); set.add(1); assertThat(CollectionUtils.firstElement(set)).isEqualTo(17); } @Test void firstElementWithSortedSet() { SortedSet<Integer> sortedSet = new TreeSet<>(); sortedSet.add(17); sortedSet.add(3); sortedSet.add(2); sortedSet.add(1); assertThat(CollectionUtils.firstElement(sortedSet)).isEqualTo(1); } @Test void firstElementWithList() { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); assertThat(CollectionUtils.firstElement(list)).isEqualTo(1); } @Test void lastElementWithSet() { Set<Integer> set = new HashSet<>(); set.add(17); set.add(3); set.add(2); set.add(1); assertThat(CollectionUtils.lastElement(set)).isEqualTo(3); } @Test void lastElementWithSortedSet() { SortedSet<Integer> sortedSet = new TreeSet<>(); sortedSet.add(17); sortedSet.add(3); sortedSet.add(2); sortedSet.add(1); assertThat(CollectionUtils.lastElement(sortedSet)).isEqualTo(17); } @Test void lastElementWithList() { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); assertThat(CollectionUtils.lastElement(list)).isEqualTo(3); } @Test void toArray() { Vector<String> vector = new Vector<>(); vector.add("foo"); vector.add("bar"); Enumeration<String> enumeration = vector.elements(); assertThat(CollectionUtils.toArray(enumeration, new String[]{})).containsExactly("foo", "bar"); } @Test void conversionOfEmptyMap() { MultiValueMap<String, String> asMultiValueMap = CollectionUtils.toMultiValueMap(new HashMap<>()); assertThat(asMultiValueMap).isEmpty(); assertThat(asMultiValueMap).isEmpty(); } @Test void conversionOfNonEmptyMap() { Map<String, List<String>> wrapped = new HashMap<>(); wrapped.put("key", Arrays.asList("first", "second")); MultiValueMap<String, String> asMultiValueMap = CollectionUtils.toMultiValueMap(wrapped); assertThat(asMultiValueMap).containsAllEntriesOf(wrapped); } @Test void changesValueByReference() { Map<String, List<String>> wrapped = new HashMap<>(); MultiValueMap<String, String> asMultiValueMap = CollectionUtils.toMultiValueMap(wrapped); assertThat(asMultiValueMap).doesNotContainKeys("key"); wrapped.put("key", new ArrayList<>()); assertThat(asMultiValueMap).containsKey("key"); } @Test void compositeMap() { Map<String, String> first = new HashMap<>(); first.put("key1", "value1"); first.put("key2", "value2"); Map<String, String> second = new HashMap<>(); second.put("key3", "value3"); second.put("key4", "value4"); Map<String, String> compositeMap = CollectionUtils.compositeMap(first, second); assertThat(compositeMap).containsKeys("key1", "key2", "key3", "key4"); assertThat(compositeMap).containsValues("value1", "value2", "value3", "value4"); } private static final
CollectionUtilsTests
java
quarkusio__quarkus
integration-tests/grpc-test-random-port/src/test/java/io/quarkus/grpc/examples/hello/RandomPortVertxServerTlsTestBase.java
{ "start": 209, "end": 978 }
class ____ implements QuarkusTestProfile { @Override public Map<String, String> getConfigOverrides() { return Map.of( "quarkus.grpc.server.use-separate-server", "false", "quarkus.grpc.server.plain-text", "false", "quarkus.http.test-ssl-port", "0", "quarkus.http.ssl.certificate.files", "tls/server.pem", "quarkus.http.ssl.certificate.key-files", "tls/server.key", "quarkus.grpc.clients.hello.host", "localhost", "quarkus.grpc.clients.hello.ssl.trust-store", "tls/ca.pem"); } } @Override protected String serverPortProperty() { return "quarkus.https.test-port"; } }
Profile
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/identity/DB2zIdentityColumnSupport.java
{ "start": 176, "end": 494 }
class ____ extends DB2IdentityColumnSupport { public static final DB2zIdentityColumnSupport INSTANCE = new DB2zIdentityColumnSupport(); @Override public String getIdentitySelectString(String table, String column, int type) { return "select identity_val_local() from sysibm.sysdummy1"; } }
DB2zIdentityColumnSupport
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdTest.java
{ "start": 1472, "end": 2117 }
class ____ { @JsonTypeInfo(use=Id.NAME, include=As.EXTERNAL_PROPERTY, property="extType1") public Object value1; @JsonTypeInfo(use=Id.NAME, include=As.EXTERNAL_PROPERTY, property="extType2") public Object value2; public int foo; @JsonTypeInfo(use=Id.NAME, include=As.EXTERNAL_PROPERTY, property="extType3") public Object value3; public ExternalBean3() { } public ExternalBean3(int v) { value1 = new ValueBean(v); value2 = new ValueBean(v+1); value3 = new ValueBean(v+2); foo = v; } } static
ExternalBean3
java
reactor__reactor-core
reactor-test/src/main/java/reactor/test/DefaultStepVerifierBuilder.java
{ "start": 71862, "end": 72051 }
class ____<T> extends AbstractSignalEvent<T> { final long count; SignalCountEvent(long count, String desc) { super(desc); this.count = count; } } static final
SignalCountEvent
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeDatePartFunction.java
{ "start": 829, "end": 972 }
class ____ functions like {@link DateTrunc} and {@link DatePart} * which require an argument denoting a unit of date/time. */ public abstract
for
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesServiceAccountsEndpointBuilderFactory.java
{ "start": 1442, "end": 1604 }
interface ____ { /** * Builder for endpoint for the Kubernetes Service Account component. */ public
KubernetesServiceAccountsEndpointBuilderFactory
java
apache__flink
flink-core/src/main/java/org/apache/flink/types/FloatValue.java
{ "start": 1164, "end": 3835 }
class ____ implements Comparable<FloatValue>, ResettableValue<FloatValue>, CopyableValue<FloatValue> { private static final long serialVersionUID = 1L; private float value; /** Initializes the encapsulated float with 0.0. */ public FloatValue() { this.value = 0; } /** * Initializes the encapsulated float with the provided value. * * @param value Initial value of the encapsulated float. */ public FloatValue(float value) { this.value = value; } /** * Returns the value of the encapsulated primitive float. * * @return the value of the encapsulated primitive float. */ public float getValue() { return this.value; } /** * Sets the value of the encapsulated primitive float. * * @param value the new value of the encapsulated primitive float. */ public void setValue(float value) { this.value = value; } @Override public void setValue(FloatValue value) { this.value = value.value; } // -------------------------------------------------------------------------------------------- @Override public void read(DataInputView in) throws IOException { this.value = in.readFloat(); } @Override public void write(DataOutputView out) throws IOException { out.writeFloat(this.value); } // -------------------------------------------------------------------------------------------- @Override public String toString() { return String.valueOf(this.value); } @Override public int compareTo(FloatValue o) { final double other = o.value; return this.value < other ? -1 : this.value > other ? 1 : 0; } @Override public int hashCode() { return Float.floatToIntBits(this.value); } @Override public boolean equals(final Object obj) { if (obj instanceof FloatValue) { final FloatValue other = (FloatValue) obj; return Float.floatToIntBits(this.value) == Float.floatToIntBits(other.value); } return false; } // -------------------------------------------------------------------------------------------- @Override public int getBinaryLength() { return 4; } @Override public void copyTo(FloatValue target) { target.value = this.value; } @Override public FloatValue copy() { return new FloatValue(this.value); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { target.write(source, 4); } }
FloatValue
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/i18n/LocalizedFileDuplicateFoundTest.java
{ "start": 468, "end": 1823 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(root -> root.addAsResource(new StringAsset("hello=Ahoj!"), "messages/messages_cs.properties")) // there are multiple message files of the same priority .withAdditionalDependency( d -> d.addAsResource(new StringAsset("hello=Cau!"), "messages/messages_cs.properties")) .withAdditionalDependency( d -> d.addAsResource(new StringAsset("hello=Caucau!"), "messages/messages_cs.properties")) .assertException(t -> { Throwable e = t; MessageBundleException mbe = null; while (e != null) { if (e instanceof MessageBundleException) { mbe = (MessageBundleException) e; break; } e = e.getCause(); } assertNotNull(mbe); assertTrue(mbe.getMessage().contains("Duplicate localized files with priority 1 found:"), mbe.getMessage()); assertTrue(mbe.getMessage().contains("messages_cs.properties"), mbe.getMessage()); }); @Test public void testValidation() { fail(); } }
LocalizedFileDuplicateFoundTest
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/config/JpaRepositoryConfigDefinitionParserTests.java
{ "start": 1245, "end": 1953 }
class ____ { @Test void getsTransactionManagerSet() { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(new ClassPathResource("multiple-entity-manager-integration-context.xml")); BeanDefinition definition = factory.getBeanDefinition("auditableUserRepository"); assertThat(definition).isNotNull(); PropertyValue transactionManager = definition.getPropertyValues().getPropertyValue("transactionManager"); assertThat(transactionManager).isNotNull(); assertThat(transactionManager.getValue()).hasToString("transactionManager-2"); } }
JpaRepositoryConfigDefinitionParserTests
java
apache__flink
flink-core/src/test/java/org/apache/flink/types/StringSerializationTest.java
{ "start": 1375, "end": 13721 }
class ____ { private final Random rnd = new Random(2093486528937460234L); @Test void testNonNullValues() throws IOException { String[] testStrings = new String[] {"a", "", "bcd", "jbmbmner8 jhk hj \n \t üäßß@µ", "", "non-empty"}; testSerialization(testStrings); } @Test void testUnicodeValues() throws IOException { String[] testStrings = new String[] { StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2, (char) 1, (char) 127), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 128, (char) 16383), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 16384, (char) 65535), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 1, (char) 16383), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 1, (char) 65535), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 128, (char) 65535) }; testSerialization(testStrings); } @Test void testUnicodeSurrogatePairs() throws IOException { String[] symbols = new String[] { "\uD800\uDF30", "\uD800\uDF31", "\uD800\uDF32", "\uD834\uDF08", "\uD834\uDF56", "\uD834\uDD20", "\uD802\uDC01", "\uD800\uDC09", "\uD87E\uDC9E", "\uD864\uDDF8", "\uD840\uDC0E", "\uD801\uDC80", "\uD801\uDC56", "\uD801\uDC05", "\uD800\uDF01" }; String[] buffer = new String[100]; Random random = new Random(); for (int i = 0; i < 100; i++) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < 100; j++) { builder.append(symbols[random.nextInt(symbols.length)]); } buffer[i] = builder.toString(); } testSerialization(buffer); } @Test void testStringBinaryCompatibility() throws IOException { String[] testStrings = new String[] { StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2, (char) 1, (char) 127), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 128, (char) 16383), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 16384, (char) 65535), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 1, (char) 16383), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 1, (char) 65535), StringUtils.getRandomString( rnd, 10000, 1024 * 1024 * 2, (char) 128, (char) 65535) }; for (String testString : testStrings) { // new and old impl should produce the same binary result byte[] oldBytes = serializeBytes(testString, StringSerializationTest::oldWriteString); byte[] newBytes = serializeBytes(testString, StringSerializationTest::newWriteString); assertThat(newBytes).isEqualTo(oldBytes); // old impl should read bytes from new one String oldString = deserializeBytes(newBytes, StringSerializationTest::oldReadString); assertThat(testString).isEqualTo(oldString); // new impl should read bytes from old one String newString = deserializeBytes(oldBytes, StringSerializationTest::newReadString); assertThat(testString).isEqualTo(newString); // it should roundtrip over new impl String roundtrip = deserializeBytes(newBytes, StringSerializationTest::newReadString); assertThat(testString).isEqualTo(roundtrip); } } @Test void testNullValues() throws IOException { String[] testStrings = new String[] { "a", null, "", null, "bcd", null, "jbmbmner8 jhk hj \n \t üäßß@µ", null, "", null, "non-empty" }; testSerialization(testStrings); } @Test void testLongValues() throws IOException { String[] testStrings = new String[] { StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2) }; testSerialization(testStrings); } @Test void testMixedValues() throws IOException { String[] testStrings = new String[] { StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), "", StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), null, StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), null, "", StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), "", null }; testSerialization(testStrings); } @Test void testBinaryCopyOfLongStrings() throws IOException { String[] testStrings = new String[] { StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), "", StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), null, StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), null, "", StringUtils.getRandomString(rnd, 10000, 1024 * 1024 * 2), "", null }; testCopy(testStrings); } public static byte[] serializeBytes(String value, BiConsumer<String, DataOutput> writer) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DataOutputStream stream = new DataOutputStream(buffer); writer.accept(value, stream); stream.close(); return buffer.toByteArray(); } public static String deserializeBytes(byte[] value, Function<DataInput, String> reader) throws IOException { ByteArrayInputStream buffer = new ByteArrayInputStream(value); DataInputStream stream = new DataInputStream(buffer); String result = reader.apply(stream); stream.close(); return result; } public static void testSerialization(String[] values) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); DataOutputStream serializer = new DataOutputStream(baos); for (String value : values) { StringValue.writeString(value, serializer); } serializer.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DataInputStream deserializer = new DataInputStream(bais); int num = 0; while (deserializer.available() > 0) { String deser = StringValue.readString(deserializer); assertThat(values[num]).isEqualTo(deser); num++; } assertThat(values).hasSize(num); } public static void testCopy(String[] values) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); DataOutputStream serializer = new DataOutputStream(baos); for (String value : values) { StringValue.writeString(value, serializer); } serializer.close(); baos.close(); ByteArrayInputStream sourceInput = new ByteArrayInputStream(baos.toByteArray()); DataInputStream source = new DataInputStream(sourceInput); ByteArrayOutputStream targetOutput = new ByteArrayOutputStream(4096); DataOutputStream target = new DataOutputStream(targetOutput); for (int i = 0; i < values.length; i++) { StringValue.copyString(source, target); } ByteArrayInputStream validateInput = new ByteArrayInputStream(targetOutput.toByteArray()); DataInputStream validate = new DataInputStream(validateInput); int num = 0; while (validate.available() > 0) { String deser = StringValue.readString(validate); assertThat(values[num]).isEqualTo(deser); num++; } assertThat(values).hasSize(num); } // needed to test the binary compatibility for new/old string serialization code private static final int HIGH_BIT = 0x1 << 7; private static String oldReadString(DataInput in) { try { // the length we read is offset by one, because a length of zero indicates a null value int len = in.readUnsignedByte(); if (len == 0) { return null; } if (len >= HIGH_BIT) { int shift = 7; int curr; len = len & 0x7f; while ((curr = in.readUnsignedByte()) >= HIGH_BIT) { len |= (curr & 0x7f) << shift; shift += 7; } len |= curr << shift; } // subtract one for the null length len -= 1; final char[] data = new char[len]; for (int i = 0; i < len; i++) { int c = in.readUnsignedByte(); if (c < HIGH_BIT) { data[i] = (char) c; } else { int shift = 7; int curr; c = c & 0x7f; while ((curr = in.readUnsignedByte()) >= HIGH_BIT) { c |= (curr & 0x7f) << shift; shift += 7; } c |= curr << shift; data[i] = (char) c; } } return new String(data, 0, len); } catch (Exception e) { throw new RuntimeException(e); } } private static void oldWriteString(CharSequence cs, DataOutput out) { try { if (cs != null) { // the length we write is offset by one, because a length of zero indicates a null // value int lenToWrite = cs.length() + 1; if (lenToWrite < 0) { throw new IllegalArgumentException("CharSequence is too long."); } // write the length, variable-length encoded while (lenToWrite >= HIGH_BIT) { out.write(lenToWrite | HIGH_BIT); lenToWrite >>>= 7; } out.write(lenToWrite); // write the char data, variable length encoded for (int i = 0; i < cs.length(); i++) { int c = cs.charAt(i); while (c >= HIGH_BIT) { out.write(c | HIGH_BIT); c >>>= 7; } out.write(c); } } else { out.write(0); } } catch (Exception e) { throw new RuntimeException(e); } } public static String newReadString(DataInput in) { try { return StringValue.readString(in); } catch (Exception e) { throw new RuntimeException(e); } } public static void newWriteString(CharSequence cs, DataOutput out) { try { StringValue.writeString(cs, out); } catch (Exception e) { throw new RuntimeException(e); } } }
StringSerializationTest
java
google__guava
android/guava-tests/test/com/google/common/base/EnumsTest.java
{ "start": 8430, "end": 8508 }
class ____ entry: " + entry, e); } } return urls.build(); } }
path
java
grpc__grpc-java
binder/src/test/java/io/grpc/binder/SecurityPoliciesTest.java
{ "start": 21575, "end": 26672 }
class ____ extends SecurityPolicy { private final AtomicInteger numCalls = new AtomicInteger(0); @Override public Status checkAuthorization(int uid) { numCalls.incrementAndGet(); return Status.OK; } } @Test public void testHasSignatureSha256Hash_succeedsIfPackageNameAndSignatureHashMatch() throws Exception { PackageInfo info = newBuilder().setPackageName(OTHER_UID_PACKAGE_NAME).setSignatures(SIG2).build(); installPackages(OTHER_UID, info); policy = SecurityPolicies.hasSignatureSha256Hash( packageManager, OTHER_UID_PACKAGE_NAME, getSha256Hash(SIG2)); // THEN UID for package that has SIG2 will be authorized assertThat(policy.checkAuthorization(OTHER_UID).getCode()).isEqualTo(Status.OK.getCode()); } @Test public void testHasSignatureSha256Hash_failsIfPackageNameDoesNotMatch() throws Exception { PackageInfo info1 = newBuilder().setPackageName(appContext.getPackageName()).setSignatures(SIG1).build(); installPackages(MY_UID, info1); PackageInfo info2 = newBuilder() .setPackageName(OTHER_UID_SAME_SIGNATURE_PACKAGE_NAME) .setSignatures(SIG1) .build(); installPackages(OTHER_UID_SAME_SIGNATURE, info2); policy = SecurityPolicies.hasSignatureSha256Hash( packageManager, appContext.getPackageName(), getSha256Hash(SIG1)); // THEN UID for package that has SIG1 but different package name will not be authorized assertThat(policy.checkAuthorization(OTHER_UID_SAME_SIGNATURE).getCode()) .isEqualTo(Status.PERMISSION_DENIED.getCode()); } @Test public void testHasSignatureSha256Hash_failsIfSignatureHashDoesNotMatch() throws Exception { PackageInfo info = newBuilder().setPackageName(OTHER_UID_PACKAGE_NAME).setSignatures(SIG2).build(); installPackages(OTHER_UID, info); policy = SecurityPolicies.hasSignatureSha256Hash( packageManager, OTHER_UID_PACKAGE_NAME, getSha256Hash(SIG1)); // THEN UID for package that doesn't have SIG1 will not be authorized assertThat(policy.checkAuthorization(OTHER_UID).getCode()) .isEqualTo(Status.PERMISSION_DENIED.getCode()); } @Test public void testOneOfSignatureSha256Hash_succeedsIfPackageNameAndSignatureHashMatch() throws Exception { PackageInfo info = newBuilder().setPackageName(OTHER_UID_PACKAGE_NAME).setSignatures(SIG2).build(); installPackages(OTHER_UID, info); policy = SecurityPolicies.oneOfSignatureSha256Hash( packageManager, OTHER_UID_PACKAGE_NAME, ImmutableList.of(getSha256Hash(SIG2))); // THEN UID for package that has SIG2 will be authorized assertThat(policy.checkAuthorization(OTHER_UID).getCode()).isEqualTo(Status.OK.getCode()); } @Test public void testOneOfSignatureSha256Hash_succeedsIfPackageNameAndOneOfSignatureHashesMatch() throws Exception { PackageInfo info = newBuilder().setPackageName(OTHER_UID_PACKAGE_NAME).setSignatures(SIG2).build(); installPackages(OTHER_UID, info); policy = SecurityPolicies.oneOfSignatureSha256Hash( packageManager, OTHER_UID_PACKAGE_NAME, ImmutableList.of(getSha256Hash(SIG1), getSha256Hash(SIG2))); // THEN UID for package that has SIG2 will be authorized assertThat(policy.checkAuthorization(OTHER_UID).getCode()).isEqualTo(Status.OK.getCode()); } @Test public void testOneOfSignatureSha256Hash_failsIfPackageNameDoNotMatchAndOneOfSignatureHashesMatch() throws Exception { PackageInfo info = newBuilder().setPackageName(OTHER_UID_PACKAGE_NAME).setSignatures(SIG2).build(); installPackages(OTHER_UID, info); policy = SecurityPolicies.oneOfSignatureSha256Hash( packageManager, appContext.getPackageName(), ImmutableList.of(getSha256Hash(SIG1), getSha256Hash(SIG2))); // THEN UID for package that has SIG2 but different package name will not be authorized assertThat(policy.checkAuthorization(OTHER_UID).getCode()) .isEqualTo(Status.PERMISSION_DENIED.getCode()); } @Test public void testOneOfSignatureSha256Hash_failsIfPackageNameMatchAndOneOfSignatureHashesNotMatch() throws Exception { PackageInfo info = newBuilder() .setPackageName(OTHER_UID_PACKAGE_NAME) .setSignatures(new Signature("1234")) .build(); installPackages(OTHER_UID, info); policy = SecurityPolicies.oneOfSignatureSha256Hash( packageManager, appContext.getPackageName(), ImmutableList.of(getSha256Hash(SIG1), getSha256Hash(SIG2))); // THEN UID for package that doesn't have SIG1 or SIG2 will not be authorized assertThat(policy.checkAuthorization(OTHER_UID).getCode()) .isEqualTo(Status.PERMISSION_DENIED.getCode()); } private static byte[] getSha256Hash(Signature signature) { return Hashing.sha256().hashBytes(signature.toByteArray()).asBytes(); } }
RecordingPolicy
java
mockito__mockito
mockito-core/src/main/java/org/mockito/MockMakers.java
{ "start": 286, "end": 527 }
class ____ {@link MockSettings#mockMaker(String)} or {@link Mock#mockMaker()}. * The string values of these constants may also be used in the resource file <code>mockito-extensions/org.mockito.plugins.MockMaker</code> * as described in the
for
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistryTests.java
{ "start": 1459, "end": 7014 }
class ____ { @Test void addOneSessionId() { TestPrincipal user = new TestPrincipal("joe"); Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123"); SessionConnectedEvent event = new SessionConnectedEvent(this, message, user); DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry(); registry.onApplicationEvent(event); SimpUser simpUser = registry.getUser("joe"); assertThat(simpUser).isNotNull(); assertThat(registry.getUserCount()).isEqualTo(1); assertThat(simpUser.getSessions()).hasSize(1); assertThat(simpUser.getSession("123")).isNotNull(); } @Test void addMultipleSessionIds() { DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry(); TestPrincipal user = new TestPrincipal("joe"); Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123"); SessionConnectedEvent event = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(event); message = createMessage(SimpMessageType.CONNECT_ACK, "456"); event = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(event); message = createMessage(SimpMessageType.CONNECT_ACK, "789"); event = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(event); SimpUser simpUser = registry.getUser("joe"); assertThat(simpUser).isNotNull(); assertThat(registry.getUserCount()).isEqualTo(1); assertThat(simpUser.getSessions()).hasSize(3); assertThat(simpUser.getSession("123")).isNotNull(); assertThat(simpUser.getSession("456")).isNotNull(); assertThat(simpUser.getSession("789")).isNotNull(); } @Test void removeSessionIds() { DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry(); TestPrincipal user = new TestPrincipal("joe"); Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123"); SessionConnectedEvent connectedEvent = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(connectedEvent); message = createMessage(SimpMessageType.CONNECT_ACK, "456"); connectedEvent = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(connectedEvent); message = createMessage(SimpMessageType.CONNECT_ACK, "789"); connectedEvent = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(connectedEvent); SimpUser simpUser = registry.getUser("joe"); assertThat(simpUser).isNotNull(); assertThat(simpUser.getSessions()).hasSize(3); CloseStatus status = CloseStatus.GOING_AWAY; message = createMessage(SimpMessageType.DISCONNECT, "456"); SessionDisconnectEvent disconnectEvent = new SessionDisconnectEvent(this, message, "456", status, user); registry.onApplicationEvent(disconnectEvent); message = createMessage(SimpMessageType.DISCONNECT, "789"); disconnectEvent = new SessionDisconnectEvent(this, message, "789", status, user); registry.onApplicationEvent(disconnectEvent); assertThat(simpUser.getSessions()).hasSize(1); assertThat(simpUser.getSession("123")).isNotNull(); } @Test void findSubscriptions() { DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry(); TestPrincipal user = new TestPrincipal("joe"); Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123"); SessionConnectedEvent event = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(event); message = createMessage(SimpMessageType.SUBSCRIBE, "123", "sub1", "/match"); SessionSubscribeEvent subscribeEvent = new SessionSubscribeEvent(this, message, user); registry.onApplicationEvent(subscribeEvent); message = createMessage(SimpMessageType.SUBSCRIBE, "123", "sub2", "/match"); subscribeEvent = new SessionSubscribeEvent(this, message, user); registry.onApplicationEvent(subscribeEvent); message = createMessage(SimpMessageType.SUBSCRIBE, "123", "sub3", "/not-a-match"); subscribeEvent = new SessionSubscribeEvent(this, message, user); registry.onApplicationEvent(subscribeEvent); Set<SimpSubscription> matches = registry.findSubscriptions(subscription -> subscription.getDestination().equals("/match")); assertThat(matches).hasSize(2); Iterator<SimpSubscription> iterator = matches.iterator(); Set<String> sessionIds = new HashSet<>(2); sessionIds.add(iterator.next().getId()); sessionIds.add(iterator.next().getId()); assertThat(sessionIds).isEqualTo(new HashSet<>(Arrays.asList("sub1", "sub2"))); } @Test void nullSessionId() { DefaultSimpUserRegistry registry = new DefaultSimpUserRegistry(); TestPrincipal user = new TestPrincipal("joe"); Message<byte[]> message = createMessage(SimpMessageType.CONNECT_ACK, "123"); SessionConnectedEvent event = new SessionConnectedEvent(this, message, user); registry.onApplicationEvent(event); SimpUser simpUser = registry.getUser("joe"); assertThat(simpUser.getSession(null)).isNull(); } private Message<byte[]> createMessage(SimpMessageType type, String sessionId) { return createMessage(type, sessionId, null, null); } private Message<byte[]> createMessage(SimpMessageType type, String sessionId, String subscriptionId, String destination) { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(type); accessor.setSessionId(sessionId); if (destination != null) { accessor.setDestination(destination); } if (subscriptionId != null) { accessor.setSubscriptionId(subscriptionId); } return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); } }
DefaultSimpUserRegistryTests
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java
{ "start": 3933, "end": 12108 }
class ____ to load relative resources. * @return the resource load class */ protected final @Nullable Class<?> getResourceLoadClass() { return this.resourceLoadClass; } private Class<?> getResourceLoadClassNotNull() { Class<?> resourceLoadClass = getResourceLoadClass(); Assert.state(resourceLoadClass != null, "Instance has not been initialized"); return resourceLoadClass; } /** * Return {@link JsonContent} from writing the specific value. * @param value the value to write * @return the {@link JsonContent} * @throws IOException on write error */ public JsonContent<T> write(T value) throws IOException { verify(); Assert.notNull(value, "'value' must not be null"); String json = writeObject(value, getTypeNotNull()); return getJsonContent(json); } /** * Factory method used to get a {@link JsonContent} instance from a source JSON * string. * @param json the source JSON * @return a new {@link JsonContent} instance * @since 2.1.5 */ protected JsonContent<T> getJsonContent(String json) { return new JsonContent<>(getResourceLoadClassNotNull(), getType(), json); } /** * Return the object created from parsing the specific JSON bytes. * @param jsonBytes the source JSON bytes * @return the resulting object * @throws IOException on parse error */ public T parseObject(byte[] jsonBytes) throws IOException { verify(); return parse(jsonBytes).getObject(); } /** * Return {@link ObjectContent} from parsing the specific JSON bytes. * @param jsonBytes the source JSON bytes * @return the {@link ObjectContent} * @throws IOException on parse error */ public ObjectContent<T> parse(byte[] jsonBytes) throws IOException { verify(); Assert.notNull(jsonBytes, "'jsonBytes' must not be null"); return read(new ByteArrayResource(jsonBytes)); } /** * Return the object created from parsing the specific JSON String. * @param jsonString the source JSON string * @return the resulting object * @throws IOException on parse error */ public T parseObject(String jsonString) throws IOException { verify(); return parse(jsonString).getObject(); } /** * Return {@link ObjectContent} from parsing the specific JSON String. * @param jsonString the source JSON string * @return the {@link ObjectContent} * @throws IOException on parse error */ public ObjectContent<T> parse(String jsonString) throws IOException { verify(); Assert.notNull(jsonString, "'jsonString' must not be null"); return read(new StringReader(jsonString)); } /** * Return the object created from reading from the specified classpath resource. * @param resourcePath the source resource path. May be a full path or a path relative * to the {@code resourceLoadClass} passed to the constructor * @return the resulting object * @throws IOException on read error */ public T readObject(String resourcePath) throws IOException { verify(); return read(resourcePath).getObject(); } /** * Return {@link ObjectContent} from reading from the specified classpath resource. * @param resourcePath the source resource path. May be a full path or a path relative * to the {@code resourceLoadClass} passed to the constructor * @return the {@link ObjectContent} * @throws IOException on read error */ public ObjectContent<T> read(String resourcePath) throws IOException { verify(); Assert.notNull(resourcePath, "'resourcePath' must not be null"); return read(new ClassPathResource(resourcePath, this.resourceLoadClass)); } /** * Return the object created from reading from the specified file. * @param file the source file * @return the resulting object * @throws IOException on read error */ public T readObject(File file) throws IOException { verify(); return read(file).getObject(); } /** * Return {@link ObjectContent} from reading from the specified file. * @param file the source file * @return the {@link ObjectContent} * @throws IOException on read error */ public ObjectContent<T> read(File file) throws IOException { verify(); Assert.notNull(file, "'file' must not be null"); return read(new FileSystemResource(file)); } /** * Return the object created from reading from the specified input stream. * @param inputStream the source input stream * @return the resulting object * @throws IOException on read error */ public T readObject(InputStream inputStream) throws IOException { verify(); return read(inputStream).getObject(); } /** * Return {@link ObjectContent} from reading from the specified input stream. * @param inputStream the source input stream * @return the {@link ObjectContent} * @throws IOException on read error */ public ObjectContent<T> read(InputStream inputStream) throws IOException { verify(); Assert.notNull(inputStream, "'inputStream' must not be null"); return read(new InputStreamResource(inputStream)); } /** * Return the object created from reading from the specified resource. * @param resource the source resource * @return the resulting object * @throws IOException on read error */ public T readObject(Resource resource) throws IOException { verify(); return read(resource).getObject(); } /** * Return {@link ObjectContent} from reading from the specified resource. * @param resource the source resource * @return the {@link ObjectContent} * @throws IOException on read error */ public ObjectContent<T> read(Resource resource) throws IOException { verify(); Assert.notNull(resource, "'resource' must not be null"); InputStream inputStream = resource.getInputStream(); T object = readObject(inputStream, getTypeNotNull()); closeQuietly(inputStream); return new ObjectContent<>(this.type, object); } /** * Return the object created from reading from the specified reader. * @param reader the source reader * @return the resulting object * @throws IOException on read error */ public T readObject(Reader reader) throws IOException { verify(); return read(reader).getObject(); } /** * Return {@link ObjectContent} from reading from the specified reader. * @param reader the source reader * @return the {@link ObjectContent} * @throws IOException on read error */ public ObjectContent<T> read(Reader reader) throws IOException { verify(); Assert.notNull(reader, "'reader' must not be null"); T object = readObject(reader, getTypeNotNull()); closeQuietly(reader); return new ObjectContent<>(this.type, object); } private void closeQuietly(Closeable closeable) { try { closeable.close(); } catch (IOException ex) { // Ignore } } private void verify() { Assert.state(this.resourceLoadClass != null, "Uninitialized JsonMarshalTester (ResourceLoadClass is null)"); Assert.state(this.type != null, "Uninitialized JsonMarshalTester (Type is null)"); } /** * Write the specified object to a JSON string. * @param value the source value (never {@code null}) * @param type the resulting type (never {@code null}) * @return the JSON string * @throws IOException on write error */ protected abstract String writeObject(T value, ResolvableType type) throws IOException; /** * Read from the specified input stream to create an object of the specified type. The * default implementation delegates to {@link #readObject(Reader, ResolvableType)}. * @param inputStream the source input stream (never {@code null}) * @param type the resulting type (never {@code null}) * @return the resulting object * @throws IOException on read error */ protected T readObject(InputStream inputStream, ResolvableType type) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); return readObject(reader, type); } /** * Read from the specified reader to create an object of the specified type. * @param reader the source reader (never {@code null}) * @param type the resulting type (never {@code null}) * @return the resulting object * @throws IOException on read error */ protected abstract T readObject(Reader reader, ResolvableType type) throws IOException; /** * Utility
used
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/annotation/AnnotationTest.java
{ "start": 2094, "end": 2208 }
interface ____ { String name(); int age(); boolean sex(); } public static
PersonInfo
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/http/headers/CaseInsensitiveHeadersTest.java
{ "start": 665, "end": 2424 }
class ____ extends VertxHttpHeadersTest { public CaseInsensitiveHeadersTest() { sameHash1 = "AZ"; sameHash2 = "\u0080Y"; sameBucket1 = "A"; sameBucket2 = "R"; } @Override protected Http1xHeaders newMultiMap() { return (Http1xHeaders) MultiMap.caseInsensitiveMultiMap(); } @Test public void checkNameCollision() { assertEquals(hash(sameHash1), hash(sameHash2)); assertNotEquals(hash(sameBucket1), hash(sameBucket2)); assertEquals(index(hash(sameBucket1)), index(hash(sameBucket2))); } // hash function copied from method under test private static int hash(String name) { int h = 0; for (int i = name.length() - 1; i >= 0; i--) { char c = name.charAt(i); if (c >= 'A' && c <= 'Z') { c += 32; } h = 31 * h + c; } if (h > 0) { return h; } else if (h == Integer.MIN_VALUE) { return Integer.MAX_VALUE; } else { return -h; } } private static int index(int hash) { return hash % 17; } // construct a string with hash==MIN_VALUE // to get coverage of the if in hash() // we will calculate the representation of // MAX_VALUE+1 in base31, which wraps around to // MIN_VALUE in int representation @Test public void testHashMININT() { MultiMap mm = newMultiMap(); String name1 = ""; long value = Integer.MAX_VALUE; value++; int base = 31; long pow = 1; while (value > pow * base) { pow *= base; } while (pow != 0) { long mul = value / pow; name1 = ((char) mul) + name1; value -= pow * mul; pow /= base; } name1 = ((char) value) + name1; mm.add(name1, "value"); assertEquals("value", mm.get(name1)); } }
CaseInsensitiveHeadersTest
java
apache__camel
components/camel-olingo4/camel-olingo4-component/src/main/java/org/apache/camel/component/olingo4/Olingo4Configuration.java
{ "start": 1545, "end": 8793 }
class ____ { private static final String DEFAULT_CONTENT_TYPE = ContentType.APPLICATION_JSON.toString(); private static final int DEFAULT_TIMEOUT = 30 * 1000; @UriPath @Metadata(required = true) private Olingo4ApiName apiName; @UriPath @Metadata(required = true) private String methodName; @UriParam private String serviceUri; @UriParam(defaultValue = "application/json;charset=utf-8") private String contentType = DEFAULT_CONTENT_TYPE; @UriParam private Map<String, String> httpHeaders; @UriParam(defaultValue = "" + DEFAULT_TIMEOUT) private int connectTimeout = DEFAULT_TIMEOUT; @UriParam(defaultValue = "" + DEFAULT_TIMEOUT) private int socketTimeout = DEFAULT_TIMEOUT; @UriParam private HttpHost proxy; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "advanced") private HttpAsyncClientBuilder httpAsyncClientBuilder; @UriParam(label = "advanced") private HttpClientBuilder httpClientBuilder; @UriParam private boolean filterAlreadySeen; @UriParam(label = "consumer", defaultValue = "true") private boolean splitResult = true; public Olingo4ApiName getApiName() { return apiName; } /** * What kind of operation to perform */ public void setApiName(Olingo4ApiName apiName) { this.apiName = apiName; } public String getMethodName() { return methodName; } /** * What sub operation to use for the selected operation */ public void setMethodName(String methodName) { this.methodName = methodName; } public String getServiceUri() { return serviceUri; } /** * Target OData service base URI, e.g. http://services.odata.org/OData/OData.svc */ public void setServiceUri(String serviceUri) { this.serviceUri = serviceUri; } public String getContentType() { return contentType; } /** * Content-Type header value can be used to specify JSON or XML message format, defaults to * application/json;charset=utf-8 */ public void setContentType(String contentType) { this.contentType = contentType; } public Map<String, String> getHttpHeaders() { return httpHeaders; } /** * Custom HTTP headers to inject into every request, this could include OAuth tokens, etc. */ public void setHttpHeaders(Map<String, String> httpHeaders) { this.httpHeaders = httpHeaders; } public int getConnectTimeout() { return connectTimeout; } /** * HTTP connection creation timeout in milliseconds, defaults to 30,000 (30 seconds) */ public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getSocketTimeout() { return socketTimeout; } /** * HTTP request timeout in milliseconds, defaults to 30,000 (30 seconds) */ public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public HttpHost getProxy() { return proxy; } /** * HTTP proxy server configuration */ public void setProxy(HttpHost proxy) { this.proxy = proxy; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure security using SSLContextParameters */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public HttpAsyncClientBuilder getHttpAsyncClientBuilder() { return httpAsyncClientBuilder; } /** * Custom HTTP async client builder for more complex HTTP client configuration, overrides connectionTimeout, * socketTimeout, proxy and sslContext. Note that a socketTimeout MUST be specified in the builder, otherwise OData * requests could block indefinitely */ public void setHttpAsyncClientBuilder(HttpAsyncClientBuilder httpAsyncClientBuilder) { this.httpAsyncClientBuilder = httpAsyncClientBuilder; } public HttpClientBuilder getHttpClientBuilder() { return httpClientBuilder; } /** * Custom HTTP client builder for more complex HTTP client configuration, overrides connectionTimeout, * socketTimeout, proxy and sslContext. Note that a socketTimeout MUST be specified in the builder, otherwise OData * requests could block indefinitely */ public void setHttpClientBuilder(HttpClientBuilder httpClientBuilder) { this.httpClientBuilder = httpClientBuilder; } /** * Filter flag for filtering out already seen results */ public boolean isFilterAlreadySeen() { return filterAlreadySeen; } /** * Set this to true to filter out results that have already been communicated by this component. * * @param filterAlreadySeen */ public void setFilterAlreadySeen(boolean filterAlreadySeen) { this.filterAlreadySeen = filterAlreadySeen; } public boolean isSplitResult() { return splitResult; } /** * For endpoints that return an array or collection, a consumer endpoint will map every element to distinct * messages, unless splitResult is set to false. */ public void setSplitResult(boolean splitResult) { this.splitResult = splitResult; } @Override public int hashCode() { return new HashCodeBuilder().append(serviceUri).append(contentType).append(httpHeaders).append(connectTimeout) .append(socketTimeout).append(proxy) .append(sslContextParameters).append(httpAsyncClientBuilder).append(httpClientBuilder).hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof Olingo4Configuration) { Olingo4Configuration other = (Olingo4Configuration) obj; return serviceUri == null ? other.serviceUri == null : serviceUri.equals(other.serviceUri) && contentType == null ? other.contentType == null : contentType.equals(other.contentType) && httpHeaders == null ? other.httpHeaders == null : httpHeaders.equals(other.httpHeaders) && connectTimeout == other.connectTimeout && socketTimeout == other.socketTimeout && proxy == null ? other.proxy == null : proxy.equals(other.proxy) && sslContextParameters == null ? other.sslContextParameters == null : sslContextParameters.equals(other.sslContextParameters) && httpAsyncClientBuilder == null ? other.httpAsyncClientBuilder == null : httpAsyncClientBuilder.equals(other.httpAsyncClientBuilder) && httpClientBuilder == null ? other.httpClientBuilder == null : httpClientBuilder.equals(other.httpClientBuilder); } return false; } }
Olingo4Configuration
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java
{ "start": 6205, "end": 6536 }
class ____ { @Bean WebFilter webFilter() { return (exchange, chain) -> chain.filter(exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken( "Alice", "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR"))))); } } }
AuthenticatedConfiguration
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java
{ "start": 5496, "end": 5577 }
class ____ { } @MetaImport static
TestWithImportAndComponentScanOfAnotherPackage
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java
{ "start": 6234, "end": 6630 }
class ____ * be loaded or if an error occurs while instantiating any factory * @since 6.0 */ public <T> List<T> load(Class<T> factoryType, @Nullable ArgumentResolver argumentResolver) { return load(factoryType, argumentResolver, null); } /** * Load and instantiate the factory implementations of the given type from * {@value #FACTORIES_RESOURCE_LOCATION}, using the configured
cannot
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EnumComparisonTest.java
{ "start": 2539, "end": 2598 }
enum ____ { X, Y, Z } @Entity(name = "WithEnum") static
Enum
java
google__guava
android/guava-tests/test/com/google/common/base/ToStringHelperTest.java
{ "start": 4146, "end": 4505 }
class ____ {} } String toTest = MoreObjects.toStringHelper(new LocalInnerClass().new LocalInnerNestedClass()).toString(); assertTrue(toTest, toTest.matches(".*\\{\\}")); } @GwtIncompatible // Class names are obfuscated in GWT public void testToStringHelper_moreThanNineAnonymousClasses() { // The nth anonymous
LocalInnerNestedClass
java
quarkusio__quarkus
extensions/reactive-oracle-client/deployment/src/test/java/io/quarkus/reactive/oracle/client/OraclePoolProducerTest.java
{ "start": 348, "end": 1097 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withConfigurationResource("application-default-datasource.properties") .withApplicationRoot((jar) -> jar .addClasses(BeanUsingBareOracleClient.class) .addClasses(BeanUsingMutinyOracleClient.class)); @Inject BeanUsingBareOracleClient beanUsingBare; @Inject BeanUsingMutinyOracleClient beanUsingMutiny; @Test public void testVertxInjection() { beanUsingBare.verify() .thenCompose(v -> beanUsingMutiny.verify()) .toCompletableFuture() .join(); } @ApplicationScoped static
OraclePoolProducerTest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/HttpMediaTypeNotAcceptableException.java
{ "start": 1138, "end": 2395 }
class ____ extends HttpMediaTypeException { private static final String PARSE_ERROR_DETAIL_CODE = ErrorResponse.getDefaultDetailMessageCode(HttpMediaTypeNotAcceptableException.class, "parseError"); /** * Constructor for when the {@code Accept} header cannot be parsed. * @param message the parse error message */ public HttpMediaTypeNotAcceptableException(String message) { super(message, Collections.emptyList(), PARSE_ERROR_DETAIL_CODE, null); getBody().setDetail("Could not parse Accept header."); } /** * Create a new HttpMediaTypeNotSupportedException. * @param mediaTypes the list of supported media types */ public HttpMediaTypeNotAcceptableException(List<MediaType> mediaTypes) { super("No acceptable representation", mediaTypes, null, new Object[] {mediaTypes}); getBody().setDetail("Acceptable representations: " + mediaTypes + "."); } @Override public HttpStatusCode getStatusCode() { return HttpStatus.NOT_ACCEPTABLE; } @Override public HttpHeaders getHeaders() { if (CollectionUtils.isEmpty(getSupportedMediaTypes())) { return HttpHeaders.EMPTY; } HttpHeaders headers = new HttpHeaders(); headers.setAccept(getSupportedMediaTypes()); return headers; } }
HttpMediaTypeNotAcceptableException
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/ZKFailoverController.java
{ "start": 33639, "end": 34450 }
class ____ implements ActiveStandbyElectorCallback { @Override public void becomeActive() throws ServiceFailedException { ZKFailoverController.this.becomeActive(); } @Override public void becomeStandby() { ZKFailoverController.this.becomeStandby(); } @Override public void enterNeutralMode() { } @Override public void notifyFatalError(String errorMessage) { fatalError(errorMessage); } @Override public void fenceOldActive(byte[] data) { ZKFailoverController.this.fenceOldActive(data); } @Override public String toString() { synchronized (ZKFailoverController.this) { return "Elector callbacks for " + localTarget; } } } /** * Callbacks from HealthMonitor */
ElectorCallbacks
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanOverrideHandlerTests.java
{ "start": 8870, "end": 8980 }
class ____ { } @MockitoBean(name = "otherBeanToMock", types = String.class) static
ClassLevelStringMockByName2
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/InvokerGenerator.java
{ "start": 40924, "end": 44567 }
class ____ { private final AssignabilityCheck assignabilityCheck; Assignability(IndexView index) { this.assignabilityCheck = new AssignabilityCheck(index, null); } boolean isSubtype(Type a, Type b) { Objects.requireNonNull(a); Objects.requireNonNull(b); switch (a.kind()) { case VOID: return b.kind() == Type.Kind.VOID || b.kind() == Type.Kind.CLASS && b.asClassType().name().equals(DotName.createSimple(Void.class)); case PRIMITIVE: return b.kind() == Type.Kind.PRIMITIVE && a.asPrimitiveType().primitive() == b.asPrimitiveType().primitive(); case ARRAY: return b.kind() == Type.Kind.ARRAY && a.asArrayType().deepDimensions() == b.asArrayType().deepDimensions() && isSubtype(a.asArrayType().elementType(), b.asArrayType().elementType()); case CLASS: if (b.kind() == Type.Kind.VOID) { return a.asClassType().name().equals(DotName.createSimple(Void.class)); } else if (b.kind() == Type.Kind.CLASS) { return isClassSubtype(a.asClassType(), b.asClassType()); } else if (b.kind() == Type.Kind.PARAMETERIZED_TYPE) { return isClassSubtype(a.asClassType(), ClassType.create(b.name())); } else if (b.kind() == Type.Kind.TYPE_VARIABLE) { Type firstBound = b.asTypeVariable().bounds().isEmpty() ? ClassType.OBJECT_TYPE : b.asTypeVariable().bounds().get(0); return isSubtype(a, firstBound); } else { return false; } case PARAMETERIZED_TYPE: if (b.kind() == Type.Kind.CLASS) { return isClassSubtype(ClassType.create(a.name()), b.asClassType()); } else if (b.kind() == Type.Kind.PARAMETERIZED_TYPE) { return isClassSubtype(ClassType.create(a.name()), ClassType.create(b.name())); } else if (b.kind() == Type.Kind.TYPE_VARIABLE) { Type firstBound = b.asTypeVariable().bounds().isEmpty() ? ClassType.OBJECT_TYPE : b.asTypeVariable().bounds().get(0); return isSubtype(a, firstBound); } else { return false; } case TYPE_VARIABLE: if (b.kind() == Type.Kind.CLASS || b.kind() == Type.Kind.PARAMETERIZED_TYPE) { Type firstBound = a.asTypeVariable().bounds().isEmpty() ? ClassType.OBJECT_TYPE : a.asTypeVariable().bounds().get(0); return isSubtype(firstBound, b); } else { return false; } default: throw new IllegalArgumentException("Cannot determine assignability between " + a + " and " + b); } } boolean isSupertype(Type a, Type b) { return isSubtype(b, a); } private boolean isClassSubtype(ClassType a, ClassType b) { return assignabilityCheck.isAssignableFrom(b, a); } } }
Assignability
java
google__dagger
javatests/dagger/hilt/processor/internal/root/RootFileFormatterTest.java
{ "start": 6681, "end": 7748 }
class ____ implements" + " HiltWrapper_ActivityRetainedComponentManager" + "_ActivityRetainedComponentBuilderEntryPoint,", " ServiceComponentManager.ServiceComponentBuilderEntryPoint,", " SingletonComponent,", " TestSingletonComponent,", " EntryPoint1,", " MyTest_GeneratedInjector {")); }); } private static Source entryPoint(String component, String name) { return HiltCompilerTests.javaSource( "test." + name, "package test;", "", "import dagger.hilt.EntryPoint;", "import dagger.hilt.InstallIn;", component.equals("SingletonComponent") ? "import dagger.hilt.components.SingletonComponent;" : "import dagger.hilt.android.components." + component + ";", "", "@EntryPoint", "@InstallIn(" + component + ".class)", "public interface " + name + " {}"); } }
SingletonC
java
apache__hadoop
hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/client/api/RegistryOperationsFactory.java
{ "start": 1543, "end": 6489 }
class ____ { private RegistryOperationsFactory() { } /** * Create and initialize a registry operations instance. * Access writes will be determined from the configuration * @param conf configuration * @return a registry operations instance * @throws ServiceStateException on any failure to initialize */ public static RegistryOperations createInstance(Configuration conf) { return createInstance("RegistryOperations", conf); } /** * Create and initialize a registry operations instance. * Access rights will be determined from the configuration * @param name name of the instance * @param conf configuration * @return a registry operations instance * @throws ServiceStateException on any failure to initialize */ public static RegistryOperations createInstance(String name, Configuration conf) { Preconditions.checkArgument(conf != null, "Null configuration"); RegistryOperationsClient operations = new RegistryOperationsClient(name); operations.init(conf); return operations; } public static RegistryOperationsClient createClient(String name, Configuration conf) { Preconditions.checkArgument(conf != null, "Null configuration"); RegistryOperationsClient operations = new RegistryOperationsClient(name); operations.init(conf); return operations; } /** * Create and initialize an anonymous read/write registry operations instance. * In a secure cluster, this instance will only have read access to the * registry. * @param conf configuration * @return an anonymous registry operations instance * * @throws ServiceStateException on any failure to initialize */ public static RegistryOperations createAnonymousInstance(Configuration conf) { Preconditions.checkArgument(conf != null, "Null configuration"); conf.set(KEY_REGISTRY_CLIENT_AUTH, REGISTRY_CLIENT_AUTH_ANONYMOUS); return createInstance("AnonymousRegistryOperations", conf); } /** * Create and initialize an secure, Kerberos-authenticated instance. * * The user identity will be inferred from the current user * * The authentication of this instance will expire when any kerberos * tokens needed to authenticate with the registry infrastructure expire. * @param conf configuration * @param jaasContext the JAAS context of the account. * @return a registry operations instance * @throws ServiceStateException on any failure to initialize */ public static RegistryOperations createKerberosInstance(Configuration conf, String jaasContext) { Preconditions.checkArgument(conf != null, "Null configuration"); conf.set(KEY_REGISTRY_CLIENT_AUTH, REGISTRY_CLIENT_AUTH_KERBEROS); conf.set(KEY_REGISTRY_CLIENT_JAAS_CONTEXT, jaasContext); return createInstance("KerberosRegistryOperations", conf); } /** * Create a kerberos registry service client * @param conf configuration * @param jaasClientEntry the name of the login config entry * @param principal principal of the client. * @param keytab location to the keytab file * @return a registry service client instance */ public static RegistryOperations createKerberosInstance(Configuration conf, String jaasClientEntry, String principal, String keytab) { Preconditions.checkArgument(conf != null, "Null configuration"); conf.set(KEY_REGISTRY_CLIENT_AUTH, REGISTRY_CLIENT_AUTH_KERBEROS); conf.set(KEY_REGISTRY_CLIENT_JAAS_CONTEXT, jaasClientEntry); RegistryOperationsClient operations = new RegistryOperationsClient("KerberosRegistryOperations"); operations.setKerberosPrincipalAndKeytab(principal, keytab); operations.init(conf); return operations; } /** * Create and initialize an operations instance authenticated with write * access via an <code>id:password</code> pair. * * The instance will have the read access * across the registry, but write access only to that part of the registry * to which it has been give the relevant permissions. * @param conf configuration * @param id user ID * @param password password * @return a registry operations instance * @throws ServiceStateException on any failure to initialize * @throws IllegalArgumentException if an argument is invalid */ public static RegistryOperations createAuthenticatedInstance(Configuration conf, String id, String password) { Preconditions.checkArgument(!StringUtils.isEmpty(id), "empty Id"); Preconditions.checkArgument(!StringUtils.isEmpty(password), "empty Password"); Preconditions.checkArgument(conf != null, "Null configuration"); conf.set(KEY_REGISTRY_CLIENT_AUTH, REGISTRY_CLIENT_AUTH_DIGEST); conf.set(KEY_REGISTRY_CLIENT_AUTHENTICATION_ID, id); conf.set(KEY_REGISTRY_CLIENT_AUTHENTICATION_PASSWORD, password); return createInstance("DigestRegistryOperations", conf); } }
RegistryOperationsFactory
java
hibernate__hibernate-orm
hibernate-jcache/src/main/java/org/hibernate/cache/jcache/internal/JCacheDomainDataRegionImpl.java
{ "start": 1034, "end": 2585 }
class ____ extends DomainDataRegionImpl { public JCacheDomainDataRegionImpl( DomainDataRegionConfig regionConfig, RegionFactoryTemplate regionFactory, DomainDataStorageAccess domainDataStorageAccess, CacheKeysFactory defaultKeysFactory, DomainDataRegionBuildingContext buildingContext) { super( regionConfig, regionFactory, domainDataStorageAccess, defaultKeysFactory, buildingContext ); } @Override protected EntityDataAccess generateTransactionalEntityDataAccess(EntityDataCachingConfig entityAccessConfig) { L2CACHE_LOGGER.nonStandardSupportForAccessType( getName(), AccessType.TRANSACTIONAL.getExternalName(), getRegionFactory().getClass().getSimpleName() ); return super.generateTransactionalEntityDataAccess( entityAccessConfig ); } @Override protected NaturalIdDataAccess generateTransactionalNaturalIdDataAccess(NaturalIdDataCachingConfig accessConfig) { L2CACHE_LOGGER.nonStandardSupportForAccessType( getName(), AccessType.TRANSACTIONAL.getExternalName(), getRegionFactory().getClass().getSimpleName() ); return super.generateTransactionalNaturalIdDataAccess( accessConfig ); } @Override protected CollectionDataAccess generateTransactionalCollectionDataAccess(CollectionDataCachingConfig accessConfig) { L2CACHE_LOGGER.nonStandardSupportForAccessType( getName(), AccessType.TRANSACTIONAL.getExternalName(), getRegionFactory().getClass().getSimpleName() ); return super.generateTransactionalCollectionDataAccess( accessConfig ); } }
JCacheDomainDataRegionImpl
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/relationship/JoinedInheritancePropertyNameConflictTest.java
{ "start": 2044, "end": 2423 }
class ____ { @Id @Column(name = "PLACE_ID") private Long id; @Column(name = "PLACE_NAME") private String name; protected Place() { } protected Place(Long id, String name) { super(); this.id = id; this.name = name; } } @Entity @Table(name = "COUNTRY") @PrimaryKeyJoinColumn(name = "PLACE_ID", referencedColumnName = "PLACE_ID") public static
Place
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/resource/basic/DefaultMediaTypeTest.java
{ "start": 1446, "end": 10245 }
class ____ { private final Logger LOG = Logger.getLogger(DefaultMediaTypeResource.class.getName()); static Client client; @RegisterExtension static ResteasyReactiveUnitTest testExtension = new ResteasyReactiveUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { JavaArchive war = ShrinkWrap.create(JavaArchive.class); war.addClass(DefaultMediaTypeCustomObject.class); war.addClasses(PortProviderUtil.class, DefaultMediaTypeResource.class); return war; } }); @BeforeEach public void init() { client = ClientBuilder.newClient(); } @AfterEach public void after() throws Exception { client.close(); client = null; } private String generateURL(String path) { return PortProviderUtil.generateURL(path, DefaultMediaTypeResource.class.getSimpleName()); } /** * @tpTestDetails Test Date object with produce annotation * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Date Produce") public void postDateProduce() throws Exception { WebTarget target = client.target(generateURL("/postDateProduce")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test Date object without produce annotation * https://issues.jboss.org/browse/RESTEASY-1403 * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Date") public void postDate() throws Exception { WebTarget target = client.target(generateURL("/postDate")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test Foo object with produce annotation * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Foo Produce") public void postFooProduce() throws Exception { WebTarget target = client.target(generateURL("/postFooProduce")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test Foo object without produce annotation * https://issues.jboss.org/browse/RESTEASY-1403 * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Foo") public void postFoo() throws Exception { WebTarget target = client.target(generateURL("/postFoo")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test int primitive with produce annotation * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Int Produce") public void postIntProduce() throws Exception { WebTarget target = client.target(generateURL("/postIntProduce")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test int primitive without produce annotation * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Int") public void postInt() throws Exception { WebTarget target = client.target(generateURL("/postInt")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test Integer object with produce annotation * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Integer Produce") public void postIntegerProduce() throws Exception { WebTarget target = client.target(generateURL("/postIntegerProduce")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } /** * @tpTestDetails Test Integer object without produce annotation * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Post Integer") public void postInteger() throws Exception { WebTarget target = client.target(generateURL("/postInteger")); ByteArrayOutputStream baos = new ByteArrayOutputStream(5000); for (int i = 0; i < 5000; i++) { baos.write(i); } Response response = target.request().post(Entity.entity(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String responseContent = response.readEntity(String.class); LOG.debug(String.format("Response: %s", responseContent)); } @Test @DisplayName("Post Multi Media Type Consumer") public void testConsumesMultiMediaType() { WebTarget target = client.target(generateURL("/postMultiMediaTypeConsumer")); Response response = target.request().post(Entity.entity("payload", "application/soap+xml")); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals("postMultiMediaTypeConsumer", response.readEntity(String.class)); response = target.request().post(Entity.entity("payload", MediaType.TEXT_XML)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals("postMultiMediaTypeConsumer", response.readEntity(String.class)); response = target.request().post(Entity.entity("payload", "any/media-type")); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals("any/media-type", response.readEntity(String.class)); response = target.request().post(Entity.entity("payload", "unexpected/media-type")); Assertions.assertEquals(Response.Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatus()); } }
DefaultMediaTypeTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-actuator/src/main/java/smoketest/actuator/SampleActuatorApplication.java
{ "start": 1385, "end": 2539 }
class ____ { @Bean public HealthIndicator helloHealthIndicator() { return createHealthIndicator("world"); } @Bean public HealthContributor compositeHelloHealthContributor() { Map<String, HealthContributor> map = new LinkedHashMap<>(); map.put("spring", createNestedHealthContributor("spring")); map.put("boot", createNestedHealthContributor("boot")); return CompositeHealthContributor.fromMap(map); } private HealthContributor createNestedHealthContributor(String name) { Map<String, HealthContributor> map = new LinkedHashMap<>(); map.put("a", createHealthIndicator(name + "-a")); map.put("b", createHealthIndicator(name + "-b")); map.put("c", createHealthIndicator(name + "-c")); return CompositeHealthContributor.fromMap(map); } private HealthIndicator createHealthIndicator(String value) { return () -> Health.up().withDetail("hello", value).build(); } public static void main(String[] args) { SpringApplication application = new SpringApplication(SampleActuatorApplication.class); application.setApplicationStartup(new BufferingApplicationStartup(1024)); application.run(args); } }
SampleActuatorApplication
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/api/dto/composite/SObjectCompositeTest.java
{ "start": 2710, "end": 2854 }
class ____ extends Account { // just for property order } @JsonPropertyOrder({ "LastName", "Phone" }) public static
TestAccount
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanOverrideProcessorTests.java
{ "start": 3874, "end": 6568 }
class ____ { @Test void missingTypes() { Class<?> testClass = MissingTypesTestCase.class; MockitoBean annotation = testClass.getAnnotation(MockitoBean.class); assertThatIllegalStateException() .isThrownBy(() -> processor.createHandlers(annotation, testClass)) .withMessage("The @MockitoBean 'types' attribute must not be empty when declared on a class"); } @Test void nameNotSupportedWithMultipleTypes() { Class<?> testClass = NameNotSupportedWithMultipleTypesTestCase.class; MockitoBean annotation = testClass.getAnnotation(MockitoBean.class); assertThatIllegalStateException() .isThrownBy(() -> processor.createHandlers(annotation, testClass)) .withMessage("The @MockitoBean 'name' attribute cannot be used when mocking multiple types"); } @Test void singleMockByType() { Class<?> testClass = SingleMockByTypeTestCase.class; MockitoBean annotation = testClass.getAnnotation(MockitoBean.class); List<BeanOverrideHandler> handlers = processor.createHandlers(annotation, testClass); assertThat(handlers).singleElement().isInstanceOfSatisfying(MockitoBeanOverrideHandler.class, handler -> { assertThat(handler.getField()).isNull(); assertThat(handler.getBeanName()).isNull(); assertThat(handler.getBeanType().resolve()).isEqualTo(Integer.class); }); } @Test void singleMockByName() { Class<?> testClass = SingleMockByNameTestCase.class; MockitoBean annotation = testClass.getAnnotation(MockitoBean.class); List<BeanOverrideHandler> handlers = processor.createHandlers(annotation, testClass); assertThat(handlers).singleElement().isInstanceOfSatisfying(MockitoBeanOverrideHandler.class, handler -> { assertThat(handler.getField()).isNull(); assertThat(handler.getBeanName()).isEqualTo("enigma"); assertThat(handler.getBeanType().resolve()).isEqualTo(Integer.class); }); } @Test void multipleMocks() { Class<?> testClass = MultipleMocksTestCase.class; MockitoBean annotation = testClass.getAnnotation(MockitoBean.class); List<BeanOverrideHandler> handlers = processor.createHandlers(annotation, testClass); assertThat(handlers).satisfiesExactly( handler1 -> { assertThat(handler1.getField()).isNull(); assertThat(handler1.getBeanName()).isNull(); assertThat(handler1.getBeanType().resolve()).isEqualTo(Integer.class); }, handler2 -> { assertThat(handler2.getField()).isNull(); assertThat(handler2.getBeanName()).isNull(); assertThat(handler2.getBeanType().resolve()).isEqualTo(Float.class); } ); } @MockitoBean static
MockitoBeanTests
java
apache__kafka
connect/transforms/src/test/java/org/apache/kafka/connect/transforms/DropHeadersTest.java
{ "start": 1344, "end": 4805 }
class ____ { private final DropHeaders<SourceRecord> xform = new DropHeaders<>(); private Map<String, ?> config(String... headers) { Map<String, Object> result = new HashMap<>(); result.put(DropHeaders.HEADERS_FIELD, List.of(headers)); return result; } @Test public void dropExistingHeader() { xform.configure(config("to-drop")); ConnectHeaders expected = new ConnectHeaders(); expected.addString("existing", "existing-value"); ConnectHeaders headers = expected.duplicate(); headers.addString("to-drop", "existing-value"); SourceRecord original = sourceRecord(headers); SourceRecord xformed = xform.apply(original); assertNonHeaders(original, xformed); assertEquals(expected, xformed.headers()); } @Test public void dropExistingHeaderWithMultipleValues() { xform.configure(config("to-drop")); ConnectHeaders expected = new ConnectHeaders(); expected.addString("existing", "existing-value"); ConnectHeaders headers = expected.duplicate(); headers.addString("to-drop", "existing-value"); headers.addString("to-drop", "existing-other-value"); SourceRecord original = sourceRecord(headers); SourceRecord xformed = xform.apply(original); assertNonHeaders(original, xformed); assertEquals(expected, xformed.headers()); } @Test public void dropNonExistingHeader() { xform.configure(config("to-drop")); ConnectHeaders expected = new ConnectHeaders(); expected.addString("existing", "existing-value"); ConnectHeaders headers = expected.duplicate(); SourceRecord original = sourceRecord(headers); SourceRecord xformed = xform.apply(original); assertNonHeaders(original, xformed); assertEquals(expected, xformed.headers()); } @Test public void configRejectsEmptyList() { assertThrows(ConfigException.class, () -> xform.configure(config())); } @Test public void testDropHeadersVersionRetrievedFromAppInfoParser() { assertEquals(AppInfoParser.getVersion(), xform.version()); } private void assertNonHeaders(SourceRecord original, SourceRecord xformed) { assertEquals(original.sourcePartition(), xformed.sourcePartition()); assertEquals(original.sourceOffset(), xformed.sourceOffset()); assertEquals(original.topic(), xformed.topic()); assertEquals(original.kafkaPartition(), xformed.kafkaPartition()); assertEquals(original.keySchema(), xformed.keySchema()); assertEquals(original.key(), xformed.key()); assertEquals(original.valueSchema(), xformed.valueSchema()); assertEquals(original.value(), xformed.value()); assertEquals(original.timestamp(), xformed.timestamp()); } private SourceRecord sourceRecord(ConnectHeaders headers) { Map<String, ?> sourcePartition = Map.of("foo", "bar"); Map<String, ?> sourceOffset = Map.of("baz", "quxx"); String topic = "topic"; Integer partition = 0; Schema keySchema = null; Object key = "key"; Schema valueSchema = null; Object value = "value"; Long timestamp = 0L; return new SourceRecord(sourcePartition, sourceOffset, topic, partition, keySchema, key, valueSchema, value, timestamp, headers); } }
DropHeadersTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/bigquery/BigQueryCommentTest.java
{ "start": 375, "end": 2253 }
class ____ { @Test public void test_0() throws Exception { String sql = "SELECT id\n" + " , updatedTimestamp as updated_timestamp\n" + " , event_timestamp\n" + "\n" + " -- comment1 --\n" + " , current_timestamp() as last_modified_timestamp\n" + " , execution_time as load_timestamp\n" + "\n" + " -- comment2 \n" + " -- comment3\n" + " , row_number() over(partition by pid, orderId, status order by event_timestamp desc) rn\n" + "FROM t1\n" + "WHERE\n" + " -- comment4\n" + " et >= TIMESTAMP(date_sub(fact_start_date, interval 2 day))\n" + "AND\n" + " et < TIMESTAMP(fact_end_date)"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseSingleStatement( sql, DbType.bigquery, SQLParserFeature.KeepComments ); SQLSelectQueryBlock queryBlock = stmt.getSelect().getQueryBlock(); assertEquals(6, queryBlock.getSelectList().size()); assertEquals("SELECT id, updatedTimestamp AS updated_timestamp, event_timestamp -- comment1 --\n" + "\t, current_timestamp() AS last_modified_timestamp, execution_time AS load_timestamp -- comment2\n" + "\t-- comment3\n" + "\t, row_number() OVER (PARTITION BY pid, orderId, status ORDER BY event_timestamp DESC) AS rn\n" + "FROM t1\n" + "WHERE -- comment4\n" + "et >= TIMESTAMP(date_sub(fact_start_date, INTERVAL 2 DAY))\n" + "\tAND et < TIMESTAMP(fact_end_date)", SQLUtils.toSQLString(stmt, DbType.bigquery)); } }
BigQueryCommentTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/config/DefaultLoaderExplicitConfigClassesBaseTests.java
{ "start": 1342, "end": 1642 }
class ____ { @Autowired Employee employee; @Test void verifyEmployeeSetFromBaseContextConfig() { assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); assertThat(this.employee.getName()).isEqualTo("John Smith"); } }
DefaultLoaderExplicitConfigClassesBaseTests
java
apache__camel
test-infra/camel-test-infra-openai-mock/src/main/java/org/apache/camel/test/infra/openai/mock/OpenAIMock.java
{ "start": 1485, "end": 3063 }
class ____ implements BeforeEachCallback, AfterEachCallback { private static final Logger LOG = LoggerFactory.getLogger(OpenAIMock.class); private HttpServer server; private final List<MockExpectation> expectations; private final OpenAIMockBuilder builder; private final ObjectMapper objectMapper; private ExecutorService executor; public OpenAIMock() { this.expectations = new ArrayList<>(); this.objectMapper = new ObjectMapper(); this.builder = new OpenAIMockBuilder(this, this.expectations); } public OpenAIMockBuilder builder() { return this.builder; } public String getBaseUrl() { if (server == null) { throw new IllegalStateException("Mock server not started. Call beforeEach() first."); } return "http://localhost:" + server.getAddress().getPort(); } @Override public void beforeEach(ExtensionContext context) throws Exception { server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/", new OpenAIMockServerHandler(expectations, objectMapper)); executor = Executors.newSingleThreadExecutor(); server.setExecutor(executor); server.start(); LOG.info("Mock web server started on {}", server.getAddress()); } @Override public void afterEach(ExtensionContext context) throws IOException { if (server != null) { server.stop(0); executor.shutdownNow(); LOG.info("Mock web server shut down"); } } }
OpenAIMock
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/TestPropertyConflicts.java
{ "start": 1797, "end": 2129 }
class ____ { public String _name() { return "foo"; } public String getName() { return "Bob"; } public void setStuff(String value) { ; // ok } public void _stuff(String value) { throw new UnsupportedOperationException(); } } // For [databind#541] static
Infernal
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/support/CancellableFanOut.java
{ "start": 10140, "end": 10389 }
class ____ implementing this method, and that will prevent the * early release of any accumulated results. Beware of lambdas, and test carefully. */ protected abstract FinalResponse onCompletion() throws Exception; private static
when
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/module/SimpleModuleTest.java
{ "start": 2756, "end": 2824 }
interface ____ { public String getText(); } static
Base
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue1036.java
{ "start": 946, "end": 1619 }
class ____<T> { private T data; private Throwable exception; public Result() { } public T getData() { return data; } public void setData(T data) { this.data = data; } public Throwable getException() { return exception; } public void setException(Throwable exception) { this.exception = exception; } @Override public String toString() { return "Result{" + "data='" + data + '\'' + ", exception=" + exception + '}'; } } }
Result
java
spring-projects__spring-framework
spring-orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaDialect.java
{ "start": 2910, "end": 7830 }
class ____ extends DefaultJpaDialect { private boolean lazyDatabaseTransaction = false; private final Lock transactionIsolationLock = new ReentrantLock(); /** * Set whether to lazily start a database resource transaction within a * Spring-managed EclipseLink transaction. * <p>By default, read-only transactions are started lazily but regular * non-read-only transactions are started early. This allows for reusing the * same JDBC Connection throughout an entire EclipseLink transaction, for * enforced isolation and consistent visibility with JDBC access code working * on the same DataSource. * <p>Switch this flag to "true" to enforce a lazy database transaction begin * even for non-read-only transactions, allowing access to EclipseLink's * shared cache and following EclipseLink's connection mode configuration, * assuming that isolation and visibility at the JDBC level are less important. * <p><b>NOTE: Lazy database transactions are not guaranteed to work reliably * in combination with custom isolation levels. Use read-only as well as this * lazy flag with care. If other transactions use custom isolation levels, * it is not recommended to use read-only and lazy transactions at all.</b> * Otherwise, you may see non-default isolation levels used during read-only * or lazy access. If this is not acceptable, don't use read-only and lazy * next to custom isolation levels in potentially concurrent transactions. * @see org.eclipse.persistence.sessions.UnitOfWork#beginEarlyTransaction() * @see TransactionDefinition#isReadOnly() * @see TransactionDefinition#getIsolationLevel() */ public void setLazyDatabaseTransaction(boolean lazyDatabaseTransaction) { this.lazyDatabaseTransaction = lazyDatabaseTransaction; } @Override public @Nullable Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { entityManager.getTransaction().setTimeout(definition.getTimeout()); } int currentIsolationLevel = definition.getIsolationLevel(); if (currentIsolationLevel != TransactionDefinition.ISOLATION_DEFAULT) { // Pass custom isolation level on to EclipseLink's DatabaseLogin configuration. UnitOfWork uow = entityManager.unwrap(UnitOfWork.class); DatabaseLogin databaseLogin = uow.getLogin(); // Lock around shared DatabaseLogin instance for consistent isolation level // set and reset in case of concurrent transactions with different isolation. this.transactionIsolationLock.lock(); try { int originalIsolationLevel = databaseLogin.getTransactionIsolation(); // Apply current isolation level value, if necessary. if (currentIsolationLevel != originalIsolationLevel) { databaseLogin.setTransactionIsolation(currentIsolationLevel); } // Transaction begin including enforced JDBC Connection access // (picking up current isolation level from DatabaseLogin) entityManager.getTransaction().begin(); uow.beginEarlyTransaction(); entityManager.unwrap(Connection.class); // Restore original isolation level value, if necessary. if (currentIsolationLevel != originalIsolationLevel) { databaseLogin.setTransactionIsolation(originalIsolationLevel); } } finally { this.transactionIsolationLock.unlock(); } } else if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) { // Begin an early transaction to force EclipseLink to get a JDBC Connection // so that Spring can manage transactions with JDBC as well as EclipseLink. UnitOfWork uow = entityManager.unwrap(UnitOfWork.class); // Lock around shared DatabaseLogin instance for consistently picking up // the default isolation level even in case of concurrent transactions with // a custom isolation level (see above). this.transactionIsolationLock.lock(); try { entityManager.getTransaction().begin(); uow.beginEarlyTransaction(); entityManager.unwrap(Connection.class); } finally { this.transactionIsolationLock.unlock(); } } else { // Regular transaction begin with lazy database transaction. entityManager.getTransaction().begin(); } return null; } @Override public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly) throws PersistenceException, SQLException { return new EclipseLinkConnectionHandle(entityManager); } /** * {@link ConnectionHandle} implementation that lazily fetches an * EclipseLink-provided Connection on the first {@code getConnection} call - * which may never come if no application code requests a JDBC Connection. * This is useful to defer the early transaction begin that obtaining a * JDBC Connection implies within an EclipseLink EntityManager. */ private static
EclipseLinkJpaDialect
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/rest/action/search/RestSearchAction.java
{ "start": 2730, "end": 22677 }
class ____ extends BaseRestHandler { /** * Indicates whether hits.total should be rendered as an integer or an object * in the rest search response. */ public static final String TOTAL_HITS_AS_INT_PARAM = "rest_total_hits_as_int"; public static final String TYPED_KEYS_PARAM = "typed_keys"; public static final String INCLUDE_NAMED_QUERIES_SCORE_PARAM = "include_named_queries_score"; public static final Set<String> RESPONSE_PARAMS = Set.of(TYPED_KEYS_PARAM, TOTAL_HITS_AS_INT_PARAM, INCLUDE_NAMED_QUERIES_SCORE_PARAM); private final SearchUsageHolder searchUsageHolder; private final Predicate<NodeFeature> clusterSupportsFeature; private final CrossProjectModeDecider crossProjectModeDecider; public RestSearchAction(SearchUsageHolder searchUsageHolder, Predicate<NodeFeature> clusterSupportsFeature, Settings settings) { this.searchUsageHolder = searchUsageHolder; this.clusterSupportsFeature = clusterSupportsFeature; this.crossProjectModeDecider = new CrossProjectModeDecider(settings); } @Override public String getName() { return "search_action"; } @Override public List<Route> routes() { return List.of( new Route(GET, "/_search"), new Route(POST, "/_search"), new Route(GET, "/{index}/_search"), new Route(POST, "/{index}/_search") ); } @Override public Set<String> supportedCapabilities() { return SearchCapabilities.CAPABILITIES; } @Override public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException { if (client.threadPool() != null && client.threadPool().getThreadContext() != null) { client.threadPool().getThreadContext().setErrorTraceTransportHeader(request); } SearchRequest searchRequest = new SearchRequest(); // access the BwC param, but just drop it // this might be set by old clients request.param("min_compatible_shard_node"); final boolean crossProjectEnabled = crossProjectModeDecider.crossProjectEnabled(); if (crossProjectEnabled) { searchRequest.setProjectRouting(request.param("project_routing")); } /* * We have to pull out the call to `source().size(size)` because * _update_by_query and _delete_by_query uses this same parsing * path but sets a different variable when it sees the `size` * url parameter. * * Note that we can't use `searchRequest.source()::size` because * `searchRequest.source()` is null right now. We don't have to * guard against it being null in the IntConsumer because it can't * be null later. If that is confusing to you then you are in good * company. */ IntConsumer setSize = size -> searchRequest.source().size(size); request.withContentOrSourceParamParserOrNull( parser -> parseSearchRequest( searchRequest, request, parser, clusterSupportsFeature, setSize, searchUsageHolder, Optional.of(crossProjectEnabled) ) ); return channel -> { RestCancellableNodeClient cancelClient = new RestCancellableNodeClient(client, request.getHttpChannel()); cancelClient.execute(TransportSearchAction.TYPE, searchRequest, new RestRefCountedChunkedToXContentListener<>(channel)); }; } /** * Parses the rest request on top of the SearchRequest, preserving values that are not overridden by the rest request. * The endpoint calling this method is treated as if it does not support Cross Project Search (CPS). In case it supports * CPS, it should call in the other appropriate overload and pass in the CPS state explicitly either via Optional.of(true) * or Optional.of(false). * @param searchRequest the search request that will hold what gets parsed * @param request the rest request to read from * @param requestContentParser body of the request to read. This method does not attempt to read the body from the {@code request} * parameter * @param clusterSupportsFeature used to check if certain features are available in this cluster * @param setSize how the size url parameter is handled. {@code udpate_by_query} and regular search differ here. */ public static void parseSearchRequest( SearchRequest searchRequest, RestRequest request, XContentParser requestContentParser, Predicate<NodeFeature> clusterSupportsFeature, IntConsumer setSize ) throws IOException { parseSearchRequest(searchRequest, request, requestContentParser, clusterSupportsFeature, setSize, null); } public static void parseSearchRequest( SearchRequest searchRequest, RestRequest request, @Nullable XContentParser requestContentParser, Predicate<NodeFeature> clusterSupportsFeature, IntConsumer setSize, @Nullable SearchUsageHolder searchUsageHolder ) throws IOException { parseSearchRequest( searchRequest, request, requestContentParser, clusterSupportsFeature, setSize, searchUsageHolder, Optional.empty() ); } /** * Parses the rest request on top of the SearchRequest, preserving values that are not overridden by the rest request. * * @param searchRequest the search request that will hold what gets parsed * @param request the rest request to read from * @param requestContentParser body of the request to read. This method does not attempt to read the body from the {@code request} * parameter, will be null when there is no request body to parse * @param clusterSupportsFeature used to check if certain features are available in this cluster * @param setSize how the size url parameter is handled. {@code udpate_by_query} and regular search differ here. * @param searchUsageHolder the holder of search usage stats * @param crossProjectEnabled Specifies the state of Cross Project Search (CPS) for the endpoint that's calling this method. * Optional.of(true) - signifies that the endpoint supports CPS, * Optional.of(false) - signifies that the endpoint supports CPS but CPS is disabled, and, * Optional.empty() - signifies that the endpoint does not support CPS. */ public static void parseSearchRequest( SearchRequest searchRequest, RestRequest request, @Nullable XContentParser requestContentParser, Predicate<NodeFeature> clusterSupportsFeature, IntConsumer setSize, @Nullable SearchUsageHolder searchUsageHolder, Optional<Boolean> crossProjectEnabled ) throws IOException { if (searchRequest.source() == null) { searchRequest.source(new SearchSourceBuilder()); } searchRequest.indices(Strings.splitStringByCommaToArray(request.param("index"))); /* * We pass this object to the request body parser so that we can extract info such as project_routing. * We only do it if in a Cross Project Environment, though, because outside it, such details are not * expected and valid. */ SearchRequest searchRequestForParsing = crossProjectEnabled.orElse(false) ? searchRequest : null; if (requestContentParser != null) { if (searchUsageHolder == null) { searchRequest.source().parseXContent(searchRequestForParsing, requestContentParser, true, clusterSupportsFeature); } else { searchRequest.source() .parseXContent(searchRequestForParsing, requestContentParser, true, searchUsageHolder, clusterSupportsFeature); } } final int batchedReduceSize = request.paramAsInt("batched_reduce_size", searchRequest.getBatchedReduceSize()); searchRequest.setBatchedReduceSize(batchedReduceSize); if (request.hasParam("pre_filter_shard_size")) { searchRequest.setPreFilterShardSize(request.paramAsInt("pre_filter_shard_size", SearchRequest.DEFAULT_PRE_FILTER_SHARD_SIZE)); } if (request.hasParam("enable_fields_emulation")) { // this flag is a no-op from 8.0 on, we only want to consume it so its presence doesn't cause errors request.paramAsBoolean("enable_fields_emulation", false); } if (request.hasParam("max_concurrent_shard_requests")) { // only set if we have the parameter since we auto adjust the max concurrency on the coordinator // based on the number of nodes in the cluster final int maxConcurrentShardRequests = request.paramAsInt( "max_concurrent_shard_requests", searchRequest.getMaxConcurrentShardRequests() ); searchRequest.setMaxConcurrentShardRequests(maxConcurrentShardRequests); } if (request.hasParam("allow_partial_search_results")) { // only set if we have the parameter passed to override the cluster-level default searchRequest.allowPartialSearchResults(request.paramAsBoolean("allow_partial_search_results", null)); } searchRequest.searchType(request.param("search_type")); parseSearchSource(searchRequest.source(), request, setSize); searchRequest.requestCache(request.paramAsBoolean("request_cache", searchRequest.requestCache())); String scroll = request.param("scroll"); if (scroll != null) { searchRequest.scroll(parseTimeValue(scroll, null, "scroll")); } searchRequest.routing(request.param("routing")); searchRequest.preference(request.param("preference")); IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, searchRequest.indicesOptions()); if (crossProjectEnabled.orElse(false) && searchRequest.allowsCrossProject()) { indicesOptions = IndicesOptions.builder(indicesOptions) .crossProjectModeOptions(new IndicesOptions.CrossProjectModeOptions(true)) .build(); } searchRequest.indicesOptions(indicesOptions); validateSearchRequest(request, searchRequest); if (searchRequest.pointInTimeBuilder() != null) { preparePointInTime(searchRequest, request); } else { searchRequest.setCcsMinimizeRoundtrips( SearchParamsParser.parseCcsMinimizeRoundtrips(crossProjectEnabled, request, searchRequest.isCcsMinimizeRoundtrips()) ); } if (request.paramAsBoolean("force_synthetic_source", false)) { searchRequest.setForceSyntheticSource(true); } } /** * Parses the rest request on top of the SearchSourceBuilder, preserving * values that are not overridden by the rest request. */ private static void parseSearchSource(final SearchSourceBuilder searchSourceBuilder, RestRequest request, IntConsumer setSize) { QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request); if (queryBuilder != null) { searchSourceBuilder.query(queryBuilder); } if (request.hasParam("from")) { searchSourceBuilder.from(request.paramAsInt("from", 0)); } if (request.hasParam("size")) { setSize.accept(request.paramAsInt("size", SearchService.DEFAULT_SIZE)); } if (request.hasParam("explain")) { searchSourceBuilder.explain(request.paramAsBoolean("explain", null)); } if (request.hasParam("version")) { searchSourceBuilder.version(request.paramAsBoolean("version", null)); } if (request.hasParam("seq_no_primary_term")) { searchSourceBuilder.seqNoAndPrimaryTerm(request.paramAsBoolean("seq_no_primary_term", null)); } if (request.hasParam("timeout")) { searchSourceBuilder.timeout(request.paramAsTime("timeout", null)); } if (request.hasParam("terminate_after")) { int terminateAfter = request.paramAsInt("terminate_after", SearchContext.DEFAULT_TERMINATE_AFTER); searchSourceBuilder.terminateAfter(terminateAfter); } StoredFieldsContext storedFieldsContext = StoredFieldsContext.fromRestRequest( SearchSourceBuilder.STORED_FIELDS_FIELD.getPreferredName(), request ); if (storedFieldsContext != null) { searchSourceBuilder.storedFields(storedFieldsContext); } String sDocValueFields = request.param("docvalue_fields"); if (sDocValueFields != null) { if (Strings.hasText(sDocValueFields)) { String[] sFields = Strings.splitStringByCommaToArray(sDocValueFields); for (String field : sFields) { searchSourceBuilder.docValueField(field, null); } } } FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request); if (fetchSourceContext != null) { searchSourceBuilder.fetchSource(fetchSourceContext); } if (request.hasParam("track_scores")) { searchSourceBuilder.trackScores(request.paramAsBoolean("track_scores", false)); } if (request.hasParam("track_total_hits")) { if (Booleans.isBoolean(request.param("track_total_hits"))) { searchSourceBuilder.trackTotalHits(request.paramAsBoolean("track_total_hits", true)); } else { searchSourceBuilder.trackTotalHitsUpTo( request.paramAsInt("track_total_hits", SearchContext.DEFAULT_TRACK_TOTAL_HITS_UP_TO) ); } } String sSorts = request.param("sort"); if (sSorts != null) { String[] sorts = Strings.splitStringByCommaToArray(sSorts); for (String sort : sorts) { int delimiter = sort.lastIndexOf(':'); if (delimiter != -1) { String sortField = sort.substring(0, delimiter); String reverse = sort.substring(delimiter + 1); if ("asc".equals(reverse)) { searchSourceBuilder.sort(sortField, SortOrder.ASC); } else if ("desc".equals(reverse)) { searchSourceBuilder.sort(sortField, SortOrder.DESC); } } else { searchSourceBuilder.sort(sort); } } } String sStats = request.param("stats"); if (sStats != null) { searchSourceBuilder.stats(Arrays.asList(Strings.splitStringByCommaToArray(sStats))); } SuggestBuilder suggestBuilder = parseSuggestUrlParameters(request); if (suggestBuilder != null) { searchSourceBuilder.suggest(suggestBuilder); } } private static final String[] suggestQueryStringParams = new String[] { "suggest_text", "suggest_size", "suggest_mode" }; /** * package private for testing */ static SuggestBuilder parseSuggestUrlParameters(RestRequest request) { String suggestField = request.param("suggest_field"); if (suggestField != null) { String suggestText = request.param("suggest_text", request.param("q")); int suggestSize = request.paramAsInt("suggest_size", 5); String suggestMode = request.param("suggest_mode"); return new SuggestBuilder().addSuggestion( suggestField, termSuggestion(suggestField).text(suggestText) .size(suggestSize) .suggestMode(TermSuggestionBuilder.SuggestMode.resolve(suggestMode)) ); } else { List<String> unconsumedParams = Arrays.stream(suggestQueryStringParams).filter(key -> request.param(key) != null).toList(); if (unconsumedParams.isEmpty() == false) { // this would lead to a non-descriptive error from RestBaseHandler#unrecognized later, so throw a better IAE here throw new IllegalArgumentException( String.format( Locale.ROOT, "request [%s] contains parameters %s but missing 'suggest_field' parameter.", request.path(), unconsumedParams.toString() ) ); } } return null; } static void preparePointInTime(SearchRequest request, RestRequest restRequest) { assert request.pointInTimeBuilder() != null; ActionRequestValidationException validationException = null; if (restRequest.paramAsBoolean("ccs_minimize_roundtrips", false)) { validationException = addValidationError("[ccs_minimize_roundtrips] cannot be used with point in time", validationException); request.setCcsMinimizeRoundtrips(false); } ExceptionsHelper.reThrowIfNotNull(validationException); } /** * Validates that no search request parameters conflict. This method * might modify the search request to align certain parameters. */ public static void validateSearchRequest(RestRequest restRequest, SearchRequest searchRequest) { checkRestTotalHits(restRequest, searchRequest); checkSearchType(restRequest, searchRequest); // ensures that the rest param is consumed restRequest.paramAsBoolean(INCLUDE_NAMED_QUERIES_SCORE_PARAM, false); } /** * Modify the search request to accurately count the total hits that match the query * if {@link #TOTAL_HITS_AS_INT_PARAM} is set. * * @throws IllegalArgumentException if {@link #TOTAL_HITS_AS_INT_PARAM} * is used in conjunction with a lower bound value (other than {@link SearchContext#DEFAULT_TRACK_TOTAL_HITS_UP_TO}) * for the track_total_hits option. */ private static void checkRestTotalHits(RestRequest restRequest, SearchRequest searchRequest) { boolean totalHitsAsInt = restRequest.paramAsBoolean(TOTAL_HITS_AS_INT_PARAM, false); if (totalHitsAsInt == false) { return; } if (searchRequest.source() == null) { searchRequest.source(new SearchSourceBuilder()); } Integer trackTotalHitsUpTo = searchRequest.source().trackTotalHitsUpTo(); if (trackTotalHitsUpTo == null) { searchRequest.source().trackTotalHits(true); } else if (trackTotalHitsUpTo != SearchContext.TRACK_TOTAL_HITS_ACCURATE && trackTotalHitsUpTo != SearchContext.TRACK_TOTAL_HITS_DISABLED) { throw new IllegalArgumentException( "[" + TOTAL_HITS_AS_INT_PARAM + "] cannot be used " + "if the tracking of total hits is not accurate, got " + trackTotalHitsUpTo ); } } private static void checkSearchType(RestRequest restRequest, SearchRequest searchRequest) { if (restRequest.hasParam("search_type") && searchRequest.hasKnnSearch()) { throw new IllegalArgumentException( "cannot set [search_type] when using [knn] search, since the search type is determined automatically" ); } } @Override protected Set<String> responseParams() { return RESPONSE_PARAMS; } }
RestSearchAction
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/common/ExpandTestPrograms.java
{ "start": 1377, "end": 4269 }
class ____ { public static final TableTestProgram EXPAND = TableTestProgram.of("expand", "validates expand node") .setupConfig( OptimizerConfigOptions.TABLE_OPTIMIZER_AGG_PHASE_STRATEGY, AggregatePhaseStrategy.ONE_PHASE) .setupConfig( OptimizerConfigOptions.TABLE_OPTIMIZER_DISTINCT_AGG_SPLIT_ENABLED, true) .setupConfig( OptimizerConfigOptions.TABLE_OPTIMIZER_INCREMENTAL_AGG_ENABLED, false) .setupTableSource( SourceTestStep.newBuilder("MyTable") .addSchema("a int", "b bigint", "c varchar") .producedBeforeRestore( Row.of(1, 1L, "Hi"), Row.of(2, 2L, "Hello"), Row.of(2, 3L, "Hello world")) .producedAfterRestore(Row.of(5, 6L, "Hello there")) .build()) .setupTableSink( SinkTestStep.newBuilder("MySink") .addSchema( "b bigint", "a bigint", "c varchar", "primary key (b) not enforced") .consumedBeforeRestore( Row.of(1, 1L, null), Row.ofKind(RowKind.UPDATE_AFTER, 1, 1L, "Hi"), Row.of(2, 1L, null), Row.ofKind(RowKind.UPDATE_AFTER, 2, 1L, "Hello"), Row.ofKind(RowKind.UPDATE_AFTER, 2, 2L, "Hello")) .consumedAfterRestore( Row.of(5, 1L, null), Row.ofKind(RowKind.UPDATE_AFTER, 5, 1L, "Hello there")) .expectedMaterializedRows( Row.of(1, 1L, "Hi"), Row.of(2, 2L, "Hello"), Row.of(5, 1L, "Hello there")) .build()) .runSql( "insert into MySink select a, " + "count(distinct b) as b, " + "first_value(c) c " + "from MyTable group by a") .build(); }
ExpandTestPrograms
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractPeer.java
{ "start": 1131, "end": 4068 }
class ____ implements Endpoint, ChannelHandler { private final ChannelHandler handler; private volatile URL url; // closing closed means the process is being closed and close is finished private volatile boolean closing; private volatile boolean closed; public AbstractPeer(URL url, ChannelHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.url = url; this.handler = handler; } protected AbstractPeer() { handler = null; } @Override public void send(Object message) throws RemotingException { send(message, url.getParameter(Constants.SENT_KEY, false)); } @Override public void close() { closed = true; } @Override public void close(int timeout) { close(); } @Override public void startClose() { if (isClosed()) { return; } closing = true; } @Override public URL getUrl() { return url; } protected void setUrl(URL url) { if (url == null) { throw new IllegalArgumentException("url == null"); } this.url = url; } @Override public ChannelHandler getChannelHandler() { if (handler instanceof ChannelHandlerDelegate) { return ((ChannelHandlerDelegate) handler).getHandler(); } else { return handler; } } /** * @return ChannelHandler */ @Deprecated public ChannelHandler getHandler() { return getDelegateHandler(); } /** * Return the final handler (which may have been wrapped). This method should be distinguished with getChannelHandler() method * * @return ChannelHandler */ public ChannelHandler getDelegateHandler() { return handler; } @Override public boolean isClosed() { return closed; } public boolean isClosing() { return closing && !closed; } @Override public void connected(Channel ch) throws RemotingException { if (closed) { return; } handler.connected(ch); } @Override public void disconnected(Channel ch) throws RemotingException { handler.disconnected(ch); } @Override public void sent(Channel ch, Object msg) throws RemotingException { if (closed) { return; } handler.sent(ch, msg); } @Override public void received(Channel ch, Object msg) throws RemotingException { if (closed) { return; } handler.received(ch, msg); } @Override public void caught(Channel ch, Throwable ex) throws RemotingException { handler.caught(ch, ex); } }
AbstractPeer
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallLimitTest.java
{ "start": 797, "end": 1057 }
class ____ extends TestCase { public void test_permitTable() throws Exception { assertFalse(WallUtils.isValidateMySql("SELECT * FROM T LIMIT 0")); assertFalse(WallUtils.isValidateMySql("SELECT * FROM T LIMIT 10, 0")); } }
MySqlWallLimitTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/IdentifierLoadAccess.java
{ "start": 374, "end": 1333 }
interface ____ especially useful when customizing association /// fetching using an [jakarta.persistence.EntityGraph]. /// ```java /// var graph = session.createEntityGraph(Book.class); /// graph.addSubgraph(Book_.publisher); /// graph.addPluralSubgraph(Book_.authors) /// .addSubgraph(Author_.person); /// Book book = session.byId(Book.class) /// .withFetchGraph(graph) /// .load(bookId); /// ``` /// /// It's also useful for loading entity instances with a specific /// [cache interaction mode][CacheMode] in effect, or in /// [read-only mode][Session#setReadOnly(Object, boolean)]. /// /// ```java /// Book book = session.byId(Book.class) /// .with(CacheMode.GET) /// .withReadOnly(true) /// .load(bookId); /// ``` /// /// @author Eric Dalquist /// @author Steve Ebersole /// /// @see Session#byId /// /// @deprecated Use forms of [Session#find] accepting [jakarta.persistence.FindOption]} instead. @Deprecated(since = "7.1", forRemoval = true) public
is
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/TestJsonSerialize2.java
{ "start": 758, "end": 932 }
class ____ { public final String value; public SimpleValue(String str) { value = str; } } @JsonPropertyOrder({"value", "value2"}) static
SimpleValue
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/optimizer/OptimizerRules.java
{ "start": 65329, "end": 65886 }
class ____ extends OptimizerExpressionRule<Expression> { public ReplaceSurrogateFunction() { super(TransformDirection.DOWN); } @Override protected Expression rule(Expression e) { if (e instanceof SurrogateFunction) { e = ((SurrogateFunction) e).substitute(); } return e; } } // Simplifies arithmetic expressions with BinaryComparisons and fixed point fields, such as: (int + 2) / 3 > 4 => int > 10 public static final
ReplaceSurrogateFunction
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/delegation/AbstractDelegationTokenSelector.java
{ "start": 1408, "end": 2113 }
class ____<TokenIdent extends AbstractDelegationTokenIdentifier> implements TokenSelector<TokenIdent> { private Text kindName; protected AbstractDelegationTokenSelector(Text kindName) { this.kindName = kindName; } @SuppressWarnings("unchecked") @Override public Token<TokenIdent> selectToken(Text service, Collection<Token<? extends TokenIdentifier>> tokens) { if (service == null) { return null; } for (Token<? extends TokenIdentifier> token : tokens) { if (kindName.equals(token.getKind()) && service.equals(token.getService())) { return (Token<TokenIdent>) token; } } return null; } }
AbstractDelegationTokenSelector
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/object/Status.java
{ "start": 259, "end": 942 }
class ____ { public static Status ONE = new Status( 1 ); public static Status TWO = new Status( 2 ); private final int value; public Status(int value) { this.value = value; } public int getValue() { return value; } public static Status from(int value) { return new Status( value ); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } final Status status = (Status) o; return value == status.value; } @Override public int hashCode() { return value; } @Override public String toString() { return "Status{" + "value=" + value + '}'; } }
Status
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/Spr15275Tests.java
{ "start": 6268, "end": 6377 }
class ____ { public final FooInterface foo; public Bar(FooInterface foo) { this.foo = foo; } } }
Bar
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/index/mapper/OffsetDocValuesLoaderTestCase.java
{ "start": 1039, "end": 8144 }
class ____ extends MapperServiceTestCase { @Override protected Settings getIndexSettings() { return Settings.builder() .put("index.mapping.source.mode", "synthetic") .put("index.mapping.synthetic_source_keep", "arrays") .build(); } public void testOffsetArrayNoDocValues() throws Exception { XContentBuilder mapping = jsonBuilder().startObject().startObject("_doc").startObject("properties").startObject("field"); minimalMapping(mapping); mapping.field("doc_values", false); mapping.endObject().endObject().endObject().endObject(); try (var mapperService = createMapperService(mapping)) { var fieldMapper = mapperService.mappingLookup().getMapper("field"); assertThat(fieldMapper.getOffsetFieldName(), nullValue()); } } public void testOffsetArrayStored() throws Exception { XContentBuilder mapping = jsonBuilder().startObject().startObject("_doc").startObject("properties").startObject("field"); minimalMapping(mapping); mapping.field("store", true); mapping.endObject().endObject().endObject().endObject(); try (var mapperService = createMapperService(mapping)) { var fieldMapper = mapperService.mappingLookup().getMapper("field"); assertThat(fieldMapper.getOffsetFieldName(), nullValue()); } } public void testOffsetMultiFields() throws Exception { XContentBuilder mapping = jsonBuilder().startObject().startObject("_doc").startObject("properties").startObject("field"); minimalMapping(mapping); mapping.startObject("fields").startObject("sub").field("type", "text").endObject().endObject(); mapping.endObject().endObject().endObject().endObject(); try (var mapperService = createMapperService(mapping)) { var fieldMapper = mapperService.mappingLookup().getMapper("field"); assertThat(fieldMapper.getOffsetFieldName(), nullValue()); } } public void testOffsetArrayNoSyntheticSource() throws Exception { XContentBuilder mapping = jsonBuilder().startObject().startObject("_doc").startObject("properties").startObject("field"); minimalMapping(mapping); mapping.endObject().endObject().endObject().endObject(); try (var mapperService = createMapperService(Settings.EMPTY, mapping)) { var fieldMapper = mapperService.mappingLookup().getMapper("field"); assertThat(fieldMapper.getOffsetFieldName(), nullValue()); } } public void testOffsetArrayNoSourceArrayKeep() throws Exception { var settingsBuilder = Settings.builder().put("index.mapping.source.mode", "synthetic"); XContentBuilder mapping = jsonBuilder().startObject().startObject("_doc").startObject("properties").startObject("field"); minimalMapping(mapping); if (randomBoolean()) { mapping.field("synthetic_source_keep", randomBoolean() ? "none" : "all"); } else if (randomBoolean()) { settingsBuilder.put("index.mapping.synthetic_source_keep", "none"); } mapping.endObject().endObject().endObject().endObject(); try (var mapperService = createMapperService(settingsBuilder.build(), mapping)) { var fieldMapper = mapperService.mappingLookup().getMapper("field"); assertThat(fieldMapper.getOffsetFieldName(), nullValue()); } } public void testOffsetEmptyArray() throws Exception { verifyOffsets("{\"field\":[]}"); } public void testOffsetArrayWithNulls() throws Exception { verifyOffsets("{\"field\":[null,null,null]}"); verifyOffsets("{\"field\":[null,[null],null]}", "{\"field\":[null,null,null]}"); } public void testOffsetArrayRandom() throws Exception { String values; int numValues = randomIntBetween(0, 256); var previousValues = new HashSet<>(); try (XContentBuilder b = XContentBuilder.builder(XContentType.JSON.xContent());) { b.startArray(); for (int i = 0; i < numValues; i++) { if (randomInt(10) == 1) { b.nullValue(); } else if (randomInt(10) == 1 && previousValues.size() > 0) { b.value(randomFrom(previousValues)); } else { Object value = randomValue(); previousValues.add(value); b.value(value); } } b.endArray(); values = Strings.toString(b); } verifyOffsets("{\"field\":" + values + "}"); } protected void minimalMapping(XContentBuilder b) throws IOException { String fieldTypeName = getFieldTypeName(); assertThat(fieldTypeName, notNullValue()); b.field("type", fieldTypeName); } protected abstract String getFieldTypeName(); protected abstract Object randomValue(); protected void verifyOffsets(String source) throws IOException { verifyOffsets(source, source); } protected void verifyOffsets(String source, String expectedSource) throws IOException { XContentBuilder mapping = jsonBuilder().startObject().startObject("_doc").startObject("properties").startObject("field"); minimalMapping(mapping); mapping.endObject().endObject().endObject().endObject(); verifyOffsets(mapping, source, expectedSource); } private void verifyOffsets(XContentBuilder mapping, String source, String expectedSource) throws IOException { try (var mapperService = createMapperService(mapping)) { var mapper = mapperService.documentMapper(); try (var directory = newDirectory()) { var iw = indexWriterForSyntheticSource(directory); var doc = mapper.parse(new SourceToParse("_id", new BytesArray(source), XContentType.JSON)); doc.updateSeqID(0, 0); doc.version().setLongValue(0); iw.addDocuments(doc.docs()); iw.close(); try (var indexReader = wrapInMockESDirectoryReader(DirectoryReader.open(directory))) { FieldMapper fieldMapper = (FieldMapper) mapper.mappers().getMapper("field"); var syntheticSourceLoader = fieldMapper.syntheticFieldLoader(); var leafReader = indexReader.leaves().getFirst().reader(); var docValueLoader = syntheticSourceLoader.docValuesLoader(leafReader, new int[] { 0 }); assertTrue(docValueLoader.advanceToDoc(0)); assertTrue(syntheticSourceLoader.hasValue()); XContentBuilder builder = jsonBuilder().startObject(); syntheticSourceLoader.write(builder); builder.endObject(); var actual = Strings.toString(builder); assertEquals(expectedSource, actual); } } } } }
OffsetDocValuesLoaderTestCase
java
apache__dubbo
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
{ "start": 6702, "end": 6832 }
class ____ extends RuntimeException { private static final long serialVersionUID = -7541893754900723624L; } }
BizException
java
grpc__grpc-java
testing/src/main/java/io/grpc/testing/GrpcCleanupRule.java
{ "start": 7752, "end": 8313 }
class ____ implements Resource { final Server server; ServerResource(Server server) { this.server = server; } @Override public void cleanUp() { server.shutdown(); } @Override public void forceCleanUp() { server.shutdownNow(); } @Override public boolean awaitReleased(long duration, TimeUnit timeUnit) throws InterruptedException { return server.awaitTermination(duration, timeUnit); } @Override public String toString() { return server.toString(); } } }
ServerResource
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java
{ "start": 2592, "end": 3379 }
interface ____(logAdvice.getCountThrows()).isEqualTo(0); assertThat(logAdvice.getCountBefore()).isEqualTo(0); } @Test void groovyBeanProxyTargetClass() { context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName() + "-groovy-proxy-target-class-context.xml"); TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatRuntimeException() .isThrownBy(bean::sayHello) .withMessage("GroovyServiceImpl"); assertThat(logAdvice.getCountBefore()).isEqualTo(1); assertThat(logAdvice.getCountThrows()).isEqualTo(1); } @AfterEach void close() { if (context != null) { context.close(); } } }
assertThat
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/ComponentImplementation.java
{ "start": 8176, "end": 8289 }
class ____ the component creator (only used by the root component.) */ COMPONENT_CREATOR, /** A provider
for
java
apache__dubbo
dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataProxyDescriberRegistrar.java
{ "start": 1210, "end": 1966 }
class ____ implements ProxyDescriberRegistrar { @Override public List<JdkProxyDescriber> getJdkProxyDescribers() { List<JdkProxyDescriber> describers = new ArrayList<>(); describers.add(buildJdkProxyDescriber(MetadataService.class)); describers.add(buildJdkProxyDescriber(MetadataServiceV2.class)); return describers; } private JdkProxyDescriber buildJdkProxyDescriber(Class<?> cl) { List<String> proxiedInterfaces = new ArrayList<>(); proxiedInterfaces.add(cl.getName()); proxiedInterfaces.add(EchoService.class.getName()); proxiedInterfaces.add(Destroyable.class.getName()); return new JdkProxyDescriber(proxiedInterfaces, null); } }
MetadataProxyDescriberRegistrar
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/ondeletecascade/OnDeleteCascadeRemoveTest.java
{ "start": 3978, "end": 4285 }
class ____ { @Id long id; @OneToMany(mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) @OnDelete(action = OnDeleteAction.CASCADE) Set<Child> children = new HashSet<>(); } @Entity(name="CascadeChild") @Cacheable // @SQLDelete( sql = "should never happen" ) static
Parent
java
redisson__redisson
redisson/src/main/java/org/redisson/cache/LRUCacheMap.java
{ "start": 806, "end": 1847 }
class ____<K, V> extends AbstractCacheMap<K, V> { private final FastRemovalQueue<CachedValue<K, V>> queue = new FastRemovalQueue<>(); public LRUCacheMap(int size, long timeToLiveInMillis, long maxIdleInMillis) { super(size, timeToLiveInMillis, maxIdleInMillis); } @Override protected void onValueCreate(CachedValue<K, V> value) { queue.add(value); } @Override protected void onValueRemove(CachedValue<K, V> value) { queue.remove(value); super.onValueRemove(value); } @Override protected void onValueRead(CachedValue<K, V> value) { queue.moveToTail(value); } @Override protected void onMapFull() { CachedValue<K, V> removedValue = queue.poll(); if (removedValue != null) { if (map.remove(removedValue.getKey(), removedValue)) { super.onValueRemove(removedValue); } } } @Override public void clear() { queue.clear(); super.clear(); } }
LRUCacheMap
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java
{ "start": 112074, "end": 112233 }
class ____ extends AsyncScalarFunction { public void eval(CompletableFuture<String> f, int i, int... more) {} } private static
VarArgFunctionAsync
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java
{ "start": 4209, "end": 4986 }
class ____ ctClass = pool.makeClass(className, pool.get(superClassName)); // add imported packages imports.forEach(pool::importPackage); // add implemented interfaces for (String iface : ifaces) { ctClass.addInterface(pool.get(iface)); } // add constructors for (String constructor : constructors) { ctClass.addConstructor(CtNewConstructor.make(constructor, ctClass)); } // add fields for (String field : fields) { ctClass.addField(CtField.make(field, ctClass)); } // add methods for (String method : methods) { ctClass.addMethod(CtNewMethod.make(method, ctClass)); } return ctClass; } }
CtClass
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/JdkConscryptSslEngineInteropTest.java
{ "start": 1017, "end": 3970 }
class ____ extends SSLEngineTest { static boolean checkConscryptDisabled() { return !Conscrypt.isAvailable(); } public JdkConscryptSslEngineInteropTest() { super(false); } @Override protected SslProvider sslClientProvider() { return SslProvider.JDK; } @Override protected SslProvider sslServerProvider() { return SslProvider.JDK; } @Override protected Provider serverSslContextProvider() { return Java8SslTestUtils.conscryptProvider(); } @MethodSource("newTestParams") @ParameterizedTest @Disabled("TODO: Make this work with Conscrypt") @Override public void testMutualAuthValidClientCertChainTooLongFailOptionalClientAuth(SSLEngineTestParam param) throws Exception { super.testMutualAuthValidClientCertChainTooLongFailOptionalClientAuth(param); } @MethodSource("newTestParams") @ParameterizedTest @Disabled("TODO: Make this work with Conscrypt") @Override public void testMutualAuthValidClientCertChainTooLongFailRequireClientAuth(SSLEngineTestParam param) throws Exception { super.testMutualAuthValidClientCertChainTooLongFailRequireClientAuth(param); } @Override protected boolean mySetupMutualAuthServerIsValidClientException(Throwable cause) { // TODO(scott): work around for a JDK issue. The exception should be SSLHandshakeException. return super.mySetupMutualAuthServerIsValidClientException(cause) || causedBySSLException(cause); } @MethodSource("newTestParams") @ParameterizedTest @Disabled("Ignore due bug in Conscrypt") @Override public void testHandshakeSession(SSLEngineTestParam param) throws Exception { // Ignore as Conscrypt does not correctly return the local certificates while the TrustManager is invoked. // See https://github.com/google/conscrypt/issues/634 } @Override protected void invalidateSessionsAndAssert(SSLSessionContext context) { // Not supported by conscrypt } @MethodSource("newTestParams") @ParameterizedTest @Disabled("Possible Conscrypt bug") @Override public void testSessionCacheTimeout(SSLEngineTestParam param) { // Skip // https://github.com/google/conscrypt/issues/851 } @Disabled("Not supported") @Override public void testRSASSAPSS(SSLEngineTestParam param) { // skip } @Test @Disabled("Disabled due a conscrypt bug") @Override public void testTLSv13DisabledIfNoValidCipherSuiteConfigured() throws Exception { super.testTLSv13DisabledIfNoValidCipherSuiteConfigured(); } @Disabled("Disabled due a conscrypt bug") @Override public void mustCallResumeTrustedOnSessionResumption(SSLEngineTestParam param) throws Exception { super.mustCallResumeTrustedOnSessionResumption(param); } }
JdkConscryptSslEngineInteropTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/AllFirstLongByTimestampAggregator.java
{ "start": 2043, "end": 5897 }
class ____ { public static String describe() { return "all_first_long_by_timestamp"; } public static AllLongLongState initSingle(DriverContext driverContext) { return new AllLongLongState(0, 0); } private static void first(AllLongLongState current, long timestamp, long value, boolean v2Seen) { current.seen(true); current.v1(timestamp); current.v2(v2Seen ? value : 0); current.v2Seen(v2Seen); } public static void combine(AllLongLongState current, @Position int position, LongBlock value, LongBlock timestamp) { if (current.seen() == false) { // We never observed a value before so we'll take this right in, no questions asked. first(current, timestamp.getLong(position), value.getLong(position), value.isNull(position) == false); return; } long ts = timestamp.getLong(position); if (ts < current.v1()) { // timestamp and seen flag are updated in all cases current.v1(ts); current.seen(true); if (value.isNull(position) == false) { // non-null value current.v2(value.getLong(position)); current.v2Seen(true); } else { // null value current.v2Seen(false); } } } public static void combineIntermediate(AllLongLongState current, long timestamp, long value, boolean seen, boolean v2Seen) { if (seen) { if (current.seen()) { if (timestamp < current.v1()) { // A newer timestamp has been observed in the reporting shard so we must update internal state current.v1(timestamp); current.v2(value); current.v2Seen(v2Seen); } } else { current.v1(timestamp); current.v2(value); current.seen(true); current.v2Seen(v2Seen); } } } public static Block evaluateFinal(AllLongLongState current, DriverContext ctx) { if (current.v2Seen()) { return ctx.blockFactory().newConstantLongBlockWith(current.v2(), 1); } else { return ctx.blockFactory().newConstantNullBlock(1); } } public static GroupingState initGrouping(DriverContext driverContext) { return new GroupingState(driverContext.bigArrays()); } public static void combine(GroupingState current, int groupId, @Position int position, LongBlock value, LongBlock timestamp) { boolean hasValue = value.isNull(position) == false; current.collectValue(groupId, timestamp.getLong(position), value.getLong(position), hasValue); } public static void combineIntermediate( GroupingState current, int groupId, LongBlock timestamps, LongBlock values, BooleanBlock hasValues, int otherPosition ) { // TODO seen should probably be part of the intermediate representation int valueCount = values.getValueCount(otherPosition); if (valueCount > 0) { long timestamp = timestamps.getLong(timestamps.getFirstValueIndex(otherPosition)); int firstIndex = values.getFirstValueIndex(otherPosition); boolean hasValueFlag = hasValues.getBoolean(otherPosition); for (int i = 0; i < valueCount; i++) { current.collectValue(groupId, timestamp, values.getLong(firstIndex + i), hasValueFlag); } } } public static Block evaluateFinal(GroupingState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) { return state.evaluateFinal(selected, ctx); } public static final
AllFirstLongByTimestampAggregator
java
apache__camel
components/camel-servlet/src/test/java/org/apache/camel/component/servlet/ServletCamelRouterTestSupport.java
{ "start": 5879, "end": 6158 }
class ____ extends WebRequest { public GetMethodWebRequest(String url) { super(url); headers.put("Content-Length", "0"); } public String getMethod() { return "GET"; } } protected static
GetMethodWebRequest
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/service/connection/DockerComposeConnectionDetailsFactory.java
{ "start": 4929, "end": 5045 }
class ____ {@link ConnectionDetails} results that are backed by a * {@link RunningService}. */ protected static
for
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
{ "start": 3643, "end": 3799 }
class ____ extends NestedRuntimeException { public MockMvcBuildException(String msg, Throwable cause) { super(msg, cause); } } }
MockMvcBuildException
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/AppChecker.java
{ "start": 1381, "end": 2227 }
class ____ extends CompositeService { public AppChecker() { super("AppChecker"); } public AppChecker(String name) { super(name); } /** * Returns whether the app is in an active state. * * @return true if the app is found and is not in one of the completed states; * false otherwise * @throws YarnException if there is an error in determining the app state */ @Private public abstract boolean isApplicationActive(ApplicationId id) throws YarnException; /** * Returns the list of all active apps at the given time. * * @return the list of active apps, or an empty list if there is none * @throws YarnException if there is an error in obtaining the list */ @Private public abstract Collection<ApplicationId> getActiveApplications() throws YarnException; }
AppChecker
java
spring-projects__spring-security
rsocket/src/main/java/org/springframework/security/rsocket/metadata/BasicAuthenticationDecoder.java
{ "start": 1304, "end": 2854 }
class ____ extends AbstractDecoder<UsernamePasswordMetadata> { public BasicAuthenticationDecoder() { super(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE); } @Override public Flux<UsernamePasswordMetadata> decode(Publisher<DataBuffer> input, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { return Flux.from(input).map(DataBuffer::asByteBuffer).map((byteBuffer) -> { byte[] sizeBytes = new byte[4]; byteBuffer.get(sizeBytes); int usernameSize = 4; byte[] usernameBytes = new byte[usernameSize]; byteBuffer.get(usernameBytes); byte[] passwordBytes = new byte[byteBuffer.remaining()]; byteBuffer.get(passwordBytes); String username = new String(usernameBytes); String password = new String(passwordBytes); return new UsernamePasswordMetadata(username, password); }); } @Override public Mono<UsernamePasswordMetadata> decodeToMono(Publisher<DataBuffer> input, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { return Mono.from(input).map(DataBuffer::asByteBuffer).map((byteBuffer) -> { int usernameSize = byteBuffer.getInt(); byte[] usernameBytes = new byte[usernameSize]; byteBuffer.get(usernameBytes); byte[] passwordBytes = new byte[byteBuffer.remaining()]; byteBuffer.get(passwordBytes); String username = new String(usernameBytes); String password = new String(passwordBytes); return new UsernamePasswordMetadata(username, password); }); } }
BasicAuthenticationDecoder
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/parsing/DefaultsDefinition.java
{ "start": 1191, "end": 1253 }
interface ____ extends BeanMetadataElement { }
DefaultsDefinition
java
spring-projects__spring-boot
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/AnsiString.java
{ "start": 806, "end": 907 }
class ____ build an ANSI string when supported by the {@link Terminal}. * * @author Phillip Webb */
to
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/aot/samples/jdbc/SqlScriptsSpringJupiterTests.java
{ "start": 1752, "end": 2037 }
class ____ { @Test @Sql // default script --> org/springframework/test/context/aot/samples/jdbc/SqlScriptsSpringJupiterTests.test.sql void test(@Autowired JdbcTemplate jdbcTemplate) { assertThat(countRowsInTable(jdbcTemplate, "user")).isEqualTo(1); } }
SqlScriptsSpringJupiterTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/notfound/CompositeForeignKeyNotFoundTest.java
{ "start": 1387, "end": 2996 }
class ____ { @Test void hhh18891TestWithNotFoundIgnore(SessionFactoryScope scope) { // prepare document scope.inTransaction( session -> { Query nativeQuery = session.createNativeQuery( "insert into DocumentIgnore (id,owner) values (123,42)" ); nativeQuery.executeUpdate(); } ); // assert document scope.inTransaction( session -> { final DocumentIgnore document = session.find( DocumentIgnore.class, 123 ); assertNotNull( document ); assertEquals( 123, document.id ); assertNull( document.owner ); } ); } @Test void hhh18891TestWithNotFoundException(SessionFactoryScope scope) { // prepare document scope.inTransaction( session -> { Query nativeQuery = session.createNativeQuery( "insert into DocumentException (id,owner) values (123,42)" ); nativeQuery.executeUpdate(); } ); // assert document scope.inTransaction( session -> { assertThrows( FetchNotFoundException.class, () -> session.find( DocumentException.class, 123 ) ); } ); } @Test void hhh18891TestWithoutNotFoundAnnotation(SessionFactoryScope scope) { // prepare document scope.inTransaction( session -> { Query nativeQuery = session.createNativeQuery( "insert into Document (id,owner) values (123,42)" ); nativeQuery.executeUpdate(); } ); // assert document scope.inTransaction( session -> { final Document document = session.find( Document.class, 123 ); assertNotNull( document ); assertEquals( 123, document.id ); assertNull( document.owner ); } ); } @Entity(name = "DocumentIgnore") public static
CompositeForeignKeyNotFoundTest
java
apache__flink
flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/operator/window/ProcessEvictingWindowReader.java
{ "start": 1250, "end": 1811 }
class ____<IN, OUT, KEY, W extends Window> extends EvictingWindowReaderFunction<IN, IN, OUT, KEY, W> { public ProcessEvictingWindowReader(WindowReaderFunction<IN, OUT, KEY, W> wrappedFunction) { super(wrappedFunction); } @Override public Iterable<IN> transform(Iterable<StreamRecord<IN>> elements) throws Exception { return () -> StreamSupport.stream(elements.spliterator(), false) .map(StreamRecord::getValue) .iterator(); } }
ProcessEvictingWindowReader
java
elastic__elasticsearch
x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/test/integration/WatchMetadataTests.java
{ "start": 2324, "end": 5631 }
class ____ extends AbstractWatcherIntegrationTestCase { public void testWatchMetadata() throws Exception { Map<String, Object> metadata = new HashMap<>(); metadata.put("foo", "bar"); List<String> metaList = new ArrayList<>(); metaList.add("this"); metaList.add("is"); metaList.add("a"); metaList.add("test"); metadata.put("baz", metaList); new PutWatchRequestBuilder(client()).setId("_name") .setSource( watchBuilder().trigger(schedule(cron("0/5 * * * * ? *"))) .input(noneInput()) .condition(new CompareCondition("ctx.payload.hits.total.value", CompareCondition.Op.EQ, 1L)) .metadata(metadata) ) .get(); timeWarp().trigger("_name"); assertBusy(() -> { refresh(); SearchResponse searchResponse; try { searchResponse = prepareSearch(HistoryStoreField.DATA_STREAM + "*").setQuery(termQuery("metadata.foo", "bar")).get(); } catch (SearchPhaseExecutionException e) { if (e.getCause() instanceof NoShardAvailableActionException) { // Nothing has created the index yet searchResponse = null; } else { throw e; } } assertNotNull(searchResponse); try { assertThat(searchResponse.getHits().getTotalHits().value(), greaterThan(0L)); } finally { searchResponse.decRef(); } }); } public void testWatchMetadataAvailableAtExecution() throws Exception { Map<String, Object> metadata = new HashMap<>(); metadata.put("foo", "bar"); metadata.put("logtext", "This is a test"); LoggingAction.Builder loggingAction = loggingAction(new TextTemplate("_logging")).setLevel(LoggingLevel.DEBUG).setCategory("test"); new PutWatchRequestBuilder(client()).setId("_name") .setSource( watchBuilder().trigger(schedule(cron("0 0 0 1 1 ? 2050"))) .input(noneInput()) .condition(InternalAlwaysCondition.INSTANCE) .addAction("testLogger", loggingAction) .defaultThrottlePeriod(TimeValue.timeValueSeconds(0)) .metadata(metadata) ) .get(); TriggerEvent triggerEvent = new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeWatchResponse = new ExecuteWatchRequestBuilder(client()).setId("_name") .setTriggerEvent(triggerEvent) .setActionMode("_all", ActionExecutionMode.SIMULATE) .get(); Map<String, Object> result = executeWatchResponse.getRecordSource().getAsMap(); logger.info("result=\n{}", result); assertThat(ObjectPath.<String>eval("metadata.foo", result), equalTo("bar")); assertThat(ObjectPath.<String>eval("result.actions.0.id", result), equalTo("testLogger")); assertThat(ObjectPath.<String>eval("result.actions.0.logging.logged_text", result), equalTo("_logging")); } }
WatchMetadataTests
java
apache__flink
flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarHandlerTest.java
{ "start": 1648, "end": 4595 }
class ____ { private static final String JAR_NAME = "output-test-program.jar"; @RegisterExtension private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_EXTENSION = TestingUtils.defaultExecutorExtension(); @Test void testPlanJar(@TempDir File tmp1, @TempDir File tmp2) throws Exception { final TestingDispatcherGateway restfulGateway = TestingDispatcherGateway.newBuilder().build(); final JarHandlers handlers = new JarHandlers(tmp1.toPath(), restfulGateway, EXECUTOR_EXTENSION.getExecutor()); final Path originalJar = Paths.get(System.getProperty("targetDir")).resolve(JAR_NAME); final Path jar = Files.copy(originalJar, tmp2.toPath().resolve(JAR_NAME)); final String storedJarPath = JarHandlers.uploadJar(handlers.uploadHandler, jar, restfulGateway); final String storedJarName = Paths.get(storedJarPath).getFileName().toString(); assertThatThrownBy( () -> JarHandlers.showPlan( handlers.planHandler, storedJarName, restfulGateway)) .satisfies( e -> { assertThat( ExceptionUtils.findThrowable( e, ProgramInvocationException.class)) .map(Exception::getMessage) .hasValueSatisfying( message -> { assertThat(message) // original cause is preserved in stack // trace .contains( "The program plan could not be fetched - the program aborted pre-maturely") // implies the jar was registered for the // job graph // (otherwise the jar name would // not occur in the exception) .contains(JAR_NAME) // ensure that no stdout/stderr has been // captured .contains("System.out: " + "hello out!") .contains("System.err: " + "hello err!"); }); }); } }
JarHandlerTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/entrypoint/ClusterEntrypointTest.java
{ "start": 18265, "end": 19865 }
class ____ { private HighAvailabilityServices haService = new TestingHighAvailabilityServicesBuilder().build(); private ResourceManagerFactory<ResourceID> resourceManagerFactory = StandaloneResourceManagerFactory.getInstance(); private DispatcherRunnerFactory dispatcherRunnerFactory = new TestingDispatcherRunnerFactory.Builder().build(); private Configuration configuration = new Configuration(); public Builder setHighAvailabilityServices(HighAvailabilityServices haService) { this.haService = haService; return this; } public Builder setResourceManagerFactory( ResourceManagerFactory<ResourceID> resourceManagerFactory) { this.resourceManagerFactory = resourceManagerFactory; return this; } public Builder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public Builder setDispatcherRunnerFactory( DispatcherRunnerFactory dispatcherRunnerFactory) { this.dispatcherRunnerFactory = dispatcherRunnerFactory; return this; } public TestingEntryPoint build() { return new TestingEntryPoint( configuration, haService, resourceManagerFactory, dispatcherRunnerFactory); } } } private static
Builder
java
google__truth
core/src/test/java/com/google/common/truth/PathSubjectTest.java
{ "start": 873, "end": 1005 }
class ____ { @Test public void basicEquality() { assertThat(Paths.get("foo")).isEqualTo(Paths.get("foo")); } }
PathSubjectTest
java
quarkusio__quarkus
extensions/jackson/deployment/src/test/java/io/quarkus/jackson/deployment/JacksonMixinsWithCustomizerTest.java
{ "start": 1870, "end": 2163 }
class ____ { private final String description; public Message(String description) { this.description = description; } public String getDescription() { return description; } } @JacksonMixin(Message.class) public
Message
java
apache__camel
components/camel-servicenow/camel-servicenow-component/src/main/java/org/apache/camel/component/servicenow/ServiceNowProducerSupplier.java
{ "start": 858, "end": 973 }
interface ____ { ServiceNowProducer get(ServiceNowEndpoint endpoint) throws Exception; }
ServiceNowProducerSupplier
java
google__dagger
javatests/dagger/internal/codegen/ComponentValidationTest.java
{ "start": 9723, "end": 10374 }
interface ____ {}"); Compilation compilation = daggerCompiler().compile(testComponent); assertThat(compilation).failed(); assertThat(compilation).hadErrorContaining("int is not a valid component dependency type"); } // TODO(b/245954367): Migrate test to XProcessing Testing after this bug has been fixed. @Test public void invalidComponentModules() { JavaFileObject testComponent = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component(modules = int.class)", "
TestComponent
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-jpa/src/main/java/smoketest/data/jpa/service/CitySearchCriteria.java
{ "start": 741, "end": 1043 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; private final String name; public CitySearchCriteria(String name) { Assert.notNull(name, "'name' must not be null"); this.name = name; } public String getName() { return this.name; } }
CitySearchCriteria
java
apache__maven
compat/maven-embedder/src/main/java/org/apache/maven/cli/internal/BootstrapCoreExtensionManager.java
{ "start": 4093, "end": 8809 }
class ____ { public static final String STRATEGY_PARENT_FIRST = "parent-first"; public static final String STRATEGY_PLUGIN = "plugin"; public static final String STRATEGY_SELF_FIRST = "self-first"; private final Logger log = LoggerFactory.getLogger(getClass()); private final DefaultPluginDependenciesResolver pluginDependenciesResolver; private final RepositorySystemSessionFactory repositorySystemSessionFactory; private final CoreExports coreExports; private final ClassWorld classWorld; private final ClassRealm parentRealm; private final WorkspaceReader ideWorkspaceReader; private final RepositorySystem repoSystem; @Inject public BootstrapCoreExtensionManager( DefaultPluginDependenciesResolver pluginDependenciesResolver, RepositorySystemSessionFactory repositorySystemSessionFactory, CoreExports coreExports, PlexusContainer container, @Nullable @Named("ide") WorkspaceReader ideWorkspaceReader, RepositorySystem repoSystem) { this.pluginDependenciesResolver = pluginDependenciesResolver; this.repositorySystemSessionFactory = repositorySystemSessionFactory; this.coreExports = coreExports; this.classWorld = ((DefaultPlexusContainer) container).getClassWorld(); this.parentRealm = container.getContainerRealm(); this.ideWorkspaceReader = ideWorkspaceReader; this.repoSystem = repoSystem; } public List<CoreExtensionEntry> loadCoreExtensions( MavenExecutionRequest request, Set<String> providedArtifacts, List<CoreExtension> extensions) throws Exception { try (CloseableSession repoSession = repositorySystemSessionFactory .newRepositorySessionBuilder(request) .setWorkspaceReader(new MavenChainedWorkspaceReader(request.getWorkspaceReader(), ideWorkspaceReader)) .build()) { MavenSession mSession = new MavenSession(repoSession, request, new DefaultMavenExecutionResult()); InternalSession iSession = new SimpleSession(mSession, repoSystem, null); InternalSession.associate(repoSession, iSession); List<RemoteRepository> repositories = RepositoryUtils.toRepos(request.getPluginArtifactRepositories()); UnaryOperator<String> interpolator = createInterpolator(request); return resolveCoreExtensions(repoSession, repositories, providedArtifacts, extensions, interpolator); } } private List<CoreExtensionEntry> resolveCoreExtensions( RepositorySystemSession repoSession, List<RemoteRepository> repositories, Set<String> providedArtifacts, List<CoreExtension> configuration, UnaryOperator<String> interpolator) throws Exception { List<CoreExtensionEntry> extensions = new ArrayList<>(); DependencyFilter dependencyFilter = new ExclusionsDependencyFilter(providedArtifacts); for (CoreExtension extension : configuration) { List<Artifact> artifacts = resolveExtension(extension, repoSession, repositories, dependencyFilter, interpolator); if (!artifacts.isEmpty()) { extensions.add(createExtension(extension, artifacts)); } } return Collections.unmodifiableList(extensions); } private CoreExtensionEntry createExtension(CoreExtension extension, List<Artifact> artifacts) throws Exception { String realmId = "coreExtension>" + extension.getGroupId() + ":" + extension.getArtifactId() + ":" + extension.getVersion(); final ClassRealm realm = classWorld.newRealm(realmId, null); Set<String> providedArtifacts = Collections.emptySet(); String classLoadingStrategy = extension.getClassLoadingStrategy(); if (STRATEGY_PARENT_FIRST.equals(classLoadingStrategy)) { realm.importFrom(parentRealm, ""); } else if (STRATEGY_PLUGIN.equals(classLoadingStrategy)) { coreExports.getExportedPackages().forEach((p, cl) -> realm.importFrom(cl, p)); providedArtifacts = coreExports.getExportedArtifacts(); } else if (STRATEGY_SELF_FIRST.equals(classLoadingStrategy)) { realm.setParentRealm(parentRealm); } else { throw new IllegalArgumentException("Unsupported class-loading strategy '" + classLoadingStrategy + "'. Supported values are: " + STRATEGY_PARENT_FIRST + ", " + STRATEGY_PLUGIN + " and " + STRATEGY_SELF_FIRST); } log.debug("Populating
BootstrapCoreExtensionManager