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
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/tofix/BuilderAdvanced2580Test.java
{ "start": 1048, "end": 1110 }
class ____ { } @JsonTypeName("vbean") static
BaseBean
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/server/WebFilterChainProxyTests.java
{ "start": 2752, "end": 11658 }
class ____ { // gh-4668 @Test public void filterWhenNoMatchThenContinuesChainAnd404() { List<WebFilter> filters = Arrays.asList(new Http200WebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy filter = new WebFilterChainProxy(chain); WebTestClient.bindToController(new Object()) .webFilter(filter) .build() .get() .exchange() .expectStatus() .isNotFound(); } @Test public void doFilterWhenMatchesThenObservationRegistryObserves() { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter()); ServerWebExchangeMatcher match = (exchange) -> MatchResult.match(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters); WebFilterChainProxy fcp = new WebFilterChainProxy(chain); fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry)); WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp); WebFilterChain mockChain = mock(WebFilterChain.class); given(mockChain.filter(any())).willReturn(Mono.empty()); filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block(); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(4)).onStart(captor.capture()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getName()).isEqualTo("wrap"); assertFilterChainObservation(contexts.next(), "before", 1); assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.SECURED_OBSERVATION_NAME); assertFilterChainObservation(contexts.next(), "after", 1); } @Test public void doFilterWhenMismatchesThenObservationRegistryObserves() { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy fcp = new WebFilterChainProxy(chain); fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry)); WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp); WebFilterChain mockChain = mock(WebFilterChain.class); given(mockChain.filter(any())).willReturn(Mono.empty()); filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block(); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(2)).onStart(captor.capture()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getName()).isEqualTo("wrap"); assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.UNSECURED_OBSERVATION_NAME); } @Test public void doFilterWhenFilterExceptionThenObservationRegistryObserves() { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); WebFilter error = mock(WebFilter.class); given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException())); List<WebFilter> filters = Arrays.asList(error); ServerWebExchangeMatcher match = (exchange) -> MatchResult.match(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters); WebFilterChainProxy fcp = new WebFilterChainProxy(chain); fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry)); WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp); WebFilterChain mockChain = mock(WebFilterChain.class); given(mockChain.filter(any())).willReturn(Mono.empty()); assertThatExceptionOfType(IllegalStateException.class).isThrownBy( () -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block()); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(2)).onStart(captor.capture()); verify(handler, atLeastOnce()).onError(any()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getName()).isEqualTo("wrap"); assertFilterChainObservation(contexts.next(), "before", 1); } @Test void doFilterWhenFirewallThenBadRequest() { List<WebFilter> filters = Arrays.asList(new Http200WebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy filter = new WebFilterChainProxy(chain); WebTestClient.bindToController(new Object()) .webFilter(filter) .build() .method(HttpMethod.valueOf("INVALID")) .exchange() .expectStatus() .isBadRequest(); } @Test void doFilterWhenCustomFirewallThenInvoked() { List<WebFilter> filters = Arrays.asList(new Http200WebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy filter = new WebFilterChainProxy(chain); ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class); ServerWebExchangeFirewall firewall = mock(ServerWebExchangeFirewall.class); filter.setFirewall(firewall); filter.setExchangeRejectedHandler(handler); WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange(); verify(firewall).getFirewalledExchange(any()); verifyNoInteractions(handler); } @Test void doFilterWhenCustomExchangeRejectedHandlerThenInvoked() { List<WebFilter> filters = Arrays.asList(new Http200WebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy filter = new WebFilterChainProxy(chain); ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class); ServerWebExchangeFirewall firewall = mock(ServerWebExchangeFirewall.class); given(firewall.getFirewalledExchange(any())) .willReturn(Mono.error(new ServerExchangeRejectedException("Oops"))); filter.setFirewall(firewall); filter.setExchangeRejectedHandler(handler); WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange(); verify(firewall).getFirewalledExchange(any()); verify(handler).handle(any(), any()); } @Test void doFilterWhenDelayedServerExchangeRejectedException() { List<WebFilter> filters = Arrays.asList(new WebFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { // simulate a delayed error (e.g. reading parameters) return Mono.error(new ServerExchangeRejectedException("Ooops")); } }); ServerWebExchangeMatcher match = (exchange) -> MatchResult.match(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters); WebFilterChainProxy filter = new WebFilterChainProxy(chain); ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class); filter.setExchangeRejectedHandler(handler); // @formatter:off WebTestClient.bindToController(new Object()) .webFilter(filter) .build() .get() .exchange(); // @formatter:on verify(handler).handle(any(), any()); } static void assertFilterChainObservation(Observation.Context context, String filterSection, int chainPosition) { assertThat(context).isInstanceOf(WebFilterChainObservationContext.class); WebFilterChainObservationContext filterChainObservationContext = (WebFilterChainObservationContext) context; assertThat(context.getName()).isEqualTo(WebFilterChainObservationConvention.CHAIN_OBSERVATION_NAME); assertThat(context.getContextualName()).endsWith(filterSection); assertThat(filterChainObservationContext.getChainPosition()).isEqualTo(chainPosition); } static
WebFilterChainProxyTests
java
apache__camel
components/camel-aws/camel-aws2-transcribe/src/generated/java/org/apache/camel/component/aws2/transcribe/Transcribe2EndpointConfigurer.java
{ "start": 742, "end": 9657 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { Transcribe2Endpoint target = (Transcribe2Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": target.getConfiguration().setAccessKey(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.aws2.transcribe.Transcribe2Operations.class, value)); return true; case "overrideendpoint": case "overrideEndpoint": target.getConfiguration().setOverrideEndpoint(property(camelContext, boolean.class, value)); return true; case "pojorequest": case "pojoRequest": target.getConfiguration().setPojoRequest(property(camelContext, boolean.class, value)); return true; case "profilecredentialsname": case "profileCredentialsName": target.getConfiguration().setProfileCredentialsName(property(camelContext, java.lang.String.class, value)); return true; case "protocol": target.getConfiguration().setProtocol(property(camelContext, software.amazon.awssdk.core.Protocol.class, value)); return true; case "proxyhost": case "proxyHost": target.getConfiguration().setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxypassword": case "proxyPassword": target.getConfiguration().setProxyPassword(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "proxyPort": target.getConfiguration().setProxyPort(property(camelContext, java.lang.Integer.class, value)); return true; case "proxyprotocol": case "proxyProtocol": target.getConfiguration().setProxyProtocol(property(camelContext, java.lang.String.class, value)); return true; case "proxyusername": case "proxyUsername": target.getConfiguration().setProxyUsername(property(camelContext, java.lang.String.class, value)); return true; case "region": target.getConfiguration().setRegion(property(camelContext, java.lang.String.class, value)); return true; case "secretkey": case "secretKey": target.getConfiguration().setSecretKey(property(camelContext, java.lang.String.class, value)); return true; case "sessiontoken": case "sessionToken": target.getConfiguration().setSessionToken(property(camelContext, java.lang.String.class, value)); return true; case "transcribeclient": case "transcribeClient": target.getConfiguration().setTranscribeClient(property(camelContext, software.amazon.awssdk.services.transcribe.TranscribeClient.class, value)); return true; case "trustallcertificates": case "trustAllCertificates": target.getConfiguration().setTrustAllCertificates(property(camelContext, boolean.class, value)); return true; case "uriendpointoverride": case "uriEndpointOverride": target.getConfiguration().setUriEndpointOverride(property(camelContext, java.lang.String.class, value)); return true; case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": target.getConfiguration().setUseDefaultCredentialsProvider(property(camelContext, boolean.class, value)); return true; case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": target.getConfiguration().setUseProfileCredentialsProvider(property(camelContext, boolean.class, value)); return true; case "usesessioncredentials": case "useSessionCredentials": target.getConfiguration().setUseSessionCredentials(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "operation": return org.apache.camel.component.aws2.transcribe.Transcribe2Operations.class; case "overrideendpoint": case "overrideEndpoint": return boolean.class; case "pojorequest": case "pojoRequest": return boolean.class; case "profilecredentialsname": case "profileCredentialsName": return java.lang.String.class; case "protocol": return software.amazon.awssdk.core.Protocol.class; case "proxyhost": case "proxyHost": return java.lang.String.class; case "proxypassword": case "proxyPassword": return java.lang.String.class; case "proxyport": case "proxyPort": return java.lang.Integer.class; case "proxyprotocol": case "proxyProtocol": return java.lang.String.class; case "proxyusername": case "proxyUsername": return java.lang.String.class; case "region": return java.lang.String.class; case "secretkey": case "secretKey": return java.lang.String.class; case "sessiontoken": case "sessionToken": return java.lang.String.class; case "transcribeclient": case "transcribeClient": return software.amazon.awssdk.services.transcribe.TranscribeClient.class; case "trustallcertificates": case "trustAllCertificates": return boolean.class; case "uriendpointoverride": case "uriEndpointOverride": return java.lang.String.class; case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": return boolean.class; case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": return boolean.class; case "usesessioncredentials": case "useSessionCredentials": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { Transcribe2Endpoint target = (Transcribe2Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return target.getConfiguration().getAccessKey(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "operation": return target.getConfiguration().getOperation(); case "overrideendpoint": case "overrideEndpoint": return target.getConfiguration().isOverrideEndpoint(); case "pojorequest": case "pojoRequest": return target.getConfiguration().isPojoRequest(); case "profilecredentialsname": case "profileCredentialsName": return target.getConfiguration().getProfileCredentialsName(); case "protocol": return target.getConfiguration().getProtocol(); case "proxyhost": case "proxyHost": return target.getConfiguration().getProxyHost(); case "proxypassword": case "proxyPassword": return target.getConfiguration().getProxyPassword(); case "proxyport": case "proxyPort": return target.getConfiguration().getProxyPort(); case "proxyprotocol": case "proxyProtocol": return target.getConfiguration().getProxyProtocol(); case "proxyusername": case "proxyUsername": return target.getConfiguration().getProxyUsername(); case "region": return target.getConfiguration().getRegion(); case "secretkey": case "secretKey": return target.getConfiguration().getSecretKey(); case "sessiontoken": case "sessionToken": return target.getConfiguration().getSessionToken(); case "transcribeclient": case "transcribeClient": return target.getConfiguration().getTranscribeClient(); case "trustallcertificates": case "trustAllCertificates": return target.getConfiguration().isTrustAllCertificates(); case "uriendpointoverride": case "uriEndpointOverride": return target.getConfiguration().getUriEndpointOverride(); case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": return target.getConfiguration().isUseDefaultCredentialsProvider(); case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": return target.getConfiguration().isUseProfileCredentialsProvider(); case "usesessioncredentials": case "useSessionCredentials": return target.getConfiguration().isUseSessionCredentials(); default: return null; } } }
Transcribe2EndpointConfigurer
java
apache__dubbo
dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java
{ "start": 1140, "end": 5452 }
class ____ { @Test void testOverrideApplication() { AbsentConfigurator configurator = new AbsentConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("1000", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11)); Assertions.assertNull(url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11)); Assertions.assertEquals("1000", url.getParameter("timeout")); } @Test void testOverrideHost() { AbsentConfigurator configurator = new AbsentConfigurator( URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("1000", url.getParameter("timeout")); AbsentConfigurator configurator1 = new AbsentConfigurator(URL.valueOf(UrlConstant.SERVICE_TIMEOUT_200)); url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10)); Assertions.assertNull(url.getParameter("timeout")); url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10)); Assertions.assertEquals("1000", url.getParameter("timeout")); } // Test the version after 2.7 @Test void testAbsentForVersion27() { { String consumerUrlV27 = "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("absent://0.0.0.0/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "consumer"); params.put("configVersion", "2.7"); params.put("application", "foo"); params.put("timeout", "10000"); params.put("weight", "200"); consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params); AbsentConfigurator configurator = new AbsentConfigurator(consumerConfiguratorUrl); // Meet the configured conditions: // same side // The port of configuratorUrl is 0 // The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27 // same appName URL url = configurator.configure(URL.valueOf(consumerUrlV27)); Assertions.assertEquals("100", url.getParameter("timeout")); Assertions.assertEquals("200", url.getParameter("weight")); } { String providerUrlV27 = "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; URL providerConfiguratorUrl = URL.valueOf("absent://172.24.160.179:21880/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "provider"); params.put("configVersion", "2.7"); params.put("application", "foo"); params.put("timeout", "20000"); params.put("weight", "200"); providerConfiguratorUrl = providerConfiguratorUrl.addParameters(params); // Meet the configured conditions: // same side // same port // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as // consumerUrlV27 // same appName AbsentConfigurator configurator = new AbsentConfigurator(providerConfiguratorUrl); URL url = configurator.configure(URL.valueOf(providerUrlV27)); Assertions.assertEquals("20000", url.getParameter("timeout")); Assertions.assertEquals("100", url.getParameter("weight")); } } }
AbsentConfiguratorTest
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/load/engine/EngineKeyTest.java
{ "start": 972, "end": 6186 }
class ____ { @Mock private Transformation<Object> transformation; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void updateDiskCacheKey_throwsException() throws NoSuchAlgorithmException { // If this test fails, update testEqualsAndHashcode to use KeyTester including regression tests. final EngineKey key = new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options()); assertThrows( UnsupportedOperationException.class, new ThrowingRunnable() { @Override public void run() throws NoSuchAlgorithmException { key.updateDiskCacheKey(MessageDigest.getInstance("SHA-1")); } }); } @Test public void testEqualsAndHashCode() { Options memoryOptions = new Options(); memoryOptions.set(Option.memory("key", new Object()), new Object()); Options diskOptions = new Options(); diskOptions.set( Option.disk( "key", new CacheKeyUpdater<String>() { @Override public void update( @NonNull byte[] keyBytes, @NonNull String value, @NonNull MessageDigest messageDigest) { messageDigest.update(keyBytes); messageDigest.update(value.getBytes(Key.CHARSET)); } }), "value"); new EqualsTester() .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options()), new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "otherId", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("otherSignature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 200, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 200, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>singletonMap(Object.class, transformation), Object.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Integer.class, Object.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Integer.class, new Options())) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, memoryOptions)) .addEqualityGroup( new EngineKey( "id", new ObjectKey("signature"), 100, 100, Collections.<Class<?>, Transformation<?>>emptyMap(), Object.class, Object.class, diskOptions)) .testEquals(); } }
EngineKeyTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/DeltaIntAggregator.java
{ "start": 2686, "end": 3320 }
class ____ { static final long BASE_RAM_USAGE = RamUsageEstimator.sizeOfObject(IntDeltaState.class); long lastTimestamp = -1; long firstTimestamp = Long.MAX_VALUE; int lastValue; int firstValue; long valuesSeen; IntDeltaState(long seenTs, int seenValue) { this.lastTimestamp = seenTs; this.lastValue = seenValue; this.firstTimestamp = seenTs; this.firstValue = seenValue; this.valuesSeen = 1L; } long bytesUsed() { return BASE_RAM_USAGE; } } public static final
IntDeltaState
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/rest/ConnectRestServer.java
{ "start": 1466, "end": 2542 }
class ____ extends RestServer { private final RestClient restClient; private Herder herder; public ConnectRestServer(Integer rebalanceTimeoutMs, RestClient restClient, Map<?, ?> props) { super(RestServerConfig.forPublic(rebalanceTimeoutMs, props)); this.restClient = restClient; } public void initializeResources(Herder herder) { this.herder = herder; super.initializeResources(); } @Override protected Collection<Class<?>> regularResources() { return List.of( RootResource.class, ConnectorsResource.class, InternalConnectResource.class, ConnectorPluginsResource.class ); } @Override protected Collection<Class<?>> adminResources() { return List.of(LoggingResource.class); } @Override protected void configureRegularResources(ResourceConfig resourceConfig) { registerRestExtensions(herder, resourceConfig); resourceConfig.register(new Binder()); } private
ConnectRestServer
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/ChainedCxfConfigurer.java
{ "start": 2146, "end": 2476 }
class ____ implements CxfConfigurer { @Override public void configure(AbstractWSDLBasedEndpointFactory factoryBean) { } @Override public void configureClient(Client client) { } @Override public void configureServer(Server server) { } } }
NullCxfConfigurer
java
apache__camel
components/camel-json-patch/src/main/java/org/apache/camel/component/jsonpatch/JsonPatchConstants.java
{ "start": 902, "end": 1149 }
class ____ { @Metadata(label = "producer", description = "The resource URI", javaType = "String") public static final String JSON_PATCH_RESOURCE_URI = "CamelJsonPatchResourceUri"; private JsonPatchConstants() { } }
JsonPatchConstants
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/recall/RecallWithTraceIT.java
{ "start": 2324, "end": 4834 }
class ____ extends BaseConf { private static String topic; private static String group; private static DefaultMQProducer producer; private static RMQPopConsumer popConsumer; @BeforeClass public static void init() throws MQClientException { System.setProperty("com.rocketmq.recall.default.trace.enable", Boolean.TRUE.toString()); topic = MQRandomUtils.getRandomTopic(); IntegrationTestBase.initTopic(topic, NAMESRV_ADDR, BROKER1_NAME, 1, CQType.SimpleCQ, TopicMessageType.NORMAL); group = initConsumerGroup(); producer = new DefaultMQProducer(group, true, topic); producer.setNamesrvAddr(NAMESRV_ADDR); producer.start(); popConsumer = ConsumerFactory.getRMQPopConsumer(NAMESRV_ADDR, group, topic, "*", new RMQNormalListener()); mqClients.add(popConsumer); mqClients.add(producer); } @AfterClass public static void tearDown() { shutdown(); } @Test public void testRecallTrace() throws MQBrokerException, RemotingException, InterruptedException, MQClientException { String msgId = MessageClientIDSetter.createUniqID(); String recallHandle = RecallMessageHandle.HandleV1.buildHandle(topic, BROKER1_NAME, String.valueOf(System.currentTimeMillis() + 30000), msgId); producer.recallMessage(topic, recallHandle); MessageQueue messageQueue = new MessageQueue(topic, BROKER1_NAME, 0); String brokerAddress = brokerController1.getBrokerAddr(); AtomicReference<MessageExt> traceMessage = new AtomicReference(); await() .pollInterval(1, TimeUnit.SECONDS) .atMost(15, TimeUnit.SECONDS) .until(() -> { PopResult popResult = popConsumer.pop(brokerAddress, messageQueue, 60 * 1000, -1); boolean found = popResult.getPopStatus().equals(PopStatus.FOUND); traceMessage.set(found ? popResult.getMsgFoundList().get(0) : null); return found; }); Assert.assertNotNull(traceMessage.get()); TraceContext context = TraceDataEncoder.decoderFromTraceDataString(new String(traceMessage.get().getBody())).get(0); Assert.assertEquals(TraceType.Recall, context.getTraceType()); Assert.assertEquals(group, context.getGroupName()); Assert.assertTrue(context.isSuccess()); Assert.assertEquals(msgId, context.getTraceBeans().get(0).getMsgId()); } }
RecallWithTraceIT
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdTest.java
{ "start": 5208, "end": 5281 }
class ____ implements Pet { public String name; } static
Dog
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/custom/CustomServiceSettings.java
{ "start": 7028, "end": 20844 }
class ____ implements ToXContentFragment, Writeable { // This specifies float for the element type but null for all other settings public static final TextEmbeddingSettings DEFAULT_FLOAT = new TextEmbeddingSettings(null, null, null); // This refers to settings that are not related to the text embedding task type (all the settings should be null) public static final TextEmbeddingSettings NON_TEXT_EMBEDDING_TASK_TYPE_SETTINGS = new TextEmbeddingSettings(null, null, null); private static final TransportVersion ML_INFERENCE_CUSTOM_SERVICE_EMBEDDING_TYPE = TransportVersion.fromName( "ml_inference_custom_service_embedding_type" ); public static TextEmbeddingSettings fromMap(Map<String, Object> map, TaskType taskType, ValidationException validationException) { if (taskType != TaskType.TEXT_EMBEDDING) { return NON_TEXT_EMBEDDING_TASK_TYPE_SETTINGS; } SimilarityMeasure similarity = extractSimilarity(map, ModelConfigurations.SERVICE_SETTINGS, validationException); Integer dims = removeAsType(map, DIMENSIONS, Integer.class); Integer maxInputTokens = removeAsType(map, MAX_INPUT_TOKENS, Integer.class); return new TextEmbeddingSettings(similarity, dims, maxInputTokens); } private final SimilarityMeasure similarityMeasure; private final Integer dimensions; private final Integer maxInputTokens; public TextEmbeddingSettings( @Nullable SimilarityMeasure similarityMeasure, @Nullable Integer dimensions, @Nullable Integer maxInputTokens ) { this.similarityMeasure = similarityMeasure; this.dimensions = dimensions; this.maxInputTokens = maxInputTokens; } public TextEmbeddingSettings(StreamInput in) throws IOException { this.similarityMeasure = in.readOptionalEnum(SimilarityMeasure.class); this.dimensions = in.readOptionalVInt(); this.maxInputTokens = in.readOptionalVInt(); if (in.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_EMBEDDING_TYPE) == false) { in.readOptionalEnum(DenseVectorFieldMapper.ElementType.class); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalEnum(similarityMeasure); out.writeOptionalVInt(dimensions); out.writeOptionalVInt(maxInputTokens); if (out.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_EMBEDDING_TYPE) == false) { out.writeOptionalEnum(null); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (similarityMeasure != null) { builder.field(SIMILARITY, similarityMeasure); } if (dimensions != null) { builder.field(DIMENSIONS, dimensions); } if (maxInputTokens != null) { builder.field(MAX_INPUT_TOKENS, maxInputTokens); } return builder; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; TextEmbeddingSettings that = (TextEmbeddingSettings) o; return similarityMeasure == that.similarityMeasure && Objects.equals(dimensions, that.dimensions) && Objects.equals(maxInputTokens, that.maxInputTokens); } @Override public int hashCode() { return Objects.hash(similarityMeasure, dimensions, maxInputTokens); } } private final TextEmbeddingSettings textEmbeddingSettings; private final String url; private final Map<String, String> headers; private final QueryParameters queryParameters; private final String requestContentString; private final CustomResponseParser responseJsonParser; private final RateLimitSettings rateLimitSettings; private final int batchSize; private final InputTypeTranslator inputTypeTranslator; public CustomServiceSettings( TextEmbeddingSettings textEmbeddingSettings, String url, @Nullable Map<String, String> headers, @Nullable QueryParameters queryParameters, String requestContentString, CustomResponseParser responseJsonParser, @Nullable RateLimitSettings rateLimitSettings ) { this( textEmbeddingSettings, url, headers, queryParameters, requestContentString, responseJsonParser, rateLimitSettings, null, InputTypeTranslator.EMPTY_TRANSLATOR ); } public CustomServiceSettings( TextEmbeddingSettings textEmbeddingSettings, String url, @Nullable Map<String, String> headers, @Nullable QueryParameters queryParameters, String requestContentString, CustomResponseParser responseJsonParser, @Nullable RateLimitSettings rateLimitSettings, @Nullable Integer batchSize, InputTypeTranslator inputTypeTranslator ) { this.textEmbeddingSettings = Objects.requireNonNull(textEmbeddingSettings); this.url = Objects.requireNonNull(url); this.headers = Collections.unmodifiableMap(Objects.requireNonNullElse(headers, Map.of())); this.queryParameters = Objects.requireNonNullElse(queryParameters, QueryParameters.EMPTY); this.requestContentString = Objects.requireNonNull(requestContentString); this.responseJsonParser = Objects.requireNonNull(responseJsonParser); this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS); this.batchSize = Objects.requireNonNullElse(batchSize, DEFAULT_EMBEDDING_BATCH_SIZE); this.inputTypeTranslator = Objects.requireNonNull(inputTypeTranslator); } public CustomServiceSettings(StreamInput in) throws IOException { textEmbeddingSettings = new TextEmbeddingSettings(in); url = in.readString(); headers = in.readImmutableMap(StreamInput::readString); queryParameters = new QueryParameters(in); requestContentString = in.readString(); responseJsonParser = in.readNamedWriteable(CustomResponseParser.class); rateLimitSettings = new RateLimitSettings(in); if (in.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_REMOVE_ERROR_PARSING) == false) { // Read the error parsing fields for backwards compatibility in.readString(); in.readString(); } if (in.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_EMBEDDING_BATCH_SIZE)) { batchSize = in.readVInt(); } else { batchSize = DEFAULT_EMBEDDING_BATCH_SIZE; } if (in.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_INPUT_TYPE)) { inputTypeTranslator = new InputTypeTranslator(in); } else { inputTypeTranslator = InputTypeTranslator.EMPTY_TRANSLATOR; } } @Override public String modelId() { // returning null because the model id is embedded in the url or the request body return null; } @Override public SimilarityMeasure similarity() { return textEmbeddingSettings.similarityMeasure; } @Override public Integer dimensions() { return textEmbeddingSettings.dimensions; } @Override public DenseVectorFieldMapper.ElementType elementType() { var embeddingType = responseJsonParser.getEmbeddingType(); if (embeddingType != null) { return embeddingType.toElementType(); } return null; } public Integer getMaxInputTokens() { return textEmbeddingSettings.maxInputTokens; } TextEmbeddingSettings getTextEmbeddingSettings() { return textEmbeddingSettings; } public String getUrl() { return url; } public Map<String, String> getHeaders() { return headers; } public QueryParameters getQueryParameters() { return queryParameters; } public String getRequestContentString() { return requestContentString; } public CustomResponseParser getResponseJsonParser() { return responseJsonParser; } public InputTypeTranslator getInputTypeTranslator() { return inputTypeTranslator; } public int getBatchSize() { return batchSize; } @Override public RateLimitSettings rateLimitSettings() { return rateLimitSettings; } @Override public String getWriteableName() { return NAME; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); toXContentFragment(builder, params); builder.endObject(); return builder; } public XContentBuilder toXContentFragment(XContentBuilder builder, Params params) throws IOException { return toXContentFragmentOfExposedFields(builder, params); } @Override public XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException { textEmbeddingSettings.toXContent(builder, params); builder.field(URL, url); if (headers.isEmpty() == false) { builder.field(HEADERS, headers); } queryParameters.toXContent(builder, params); builder.field(REQUEST, requestContentString); builder.startObject(RESPONSE); { responseJsonParser.toXContent(builder, params); } builder.endObject(); inputTypeTranslator.toXContent(builder, params); rateLimitSettings.toXContent(builder, params); builder.field(BATCH_SIZE, batchSize); return builder; } @Override public ToXContentObject getFilteredXContentObject() { return this; } @Override public TransportVersion getMinimalSupportedVersion() { assert false : "should never be called when supportsVersion is used"; return INFERENCE_CUSTOM_SERVICE_ADDED; } @Override public boolean supportsVersion(TransportVersion version) { return version.supports(INFERENCE_CUSTOM_SERVICE_ADDED); } @Override public void writeTo(StreamOutput out) throws IOException { textEmbeddingSettings.writeTo(out); out.writeString(url); out.writeMap(headers, StreamOutput::writeString, StreamOutput::writeString); queryParameters.writeTo(out); out.writeString(requestContentString); out.writeNamedWriteable(responseJsonParser); rateLimitSettings.writeTo(out); if (out.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_REMOVE_ERROR_PARSING) == false) { // Write empty strings for backwards compatibility for the error parsing fields out.writeString(""); out.writeString(""); } if (out.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_EMBEDDING_BATCH_SIZE)) { out.writeVInt(batchSize); } if (out.getTransportVersion().supports(ML_INFERENCE_CUSTOM_SERVICE_INPUT_TYPE)) { inputTypeTranslator.writeTo(out); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomServiceSettings that = (CustomServiceSettings) o; return Objects.equals(textEmbeddingSettings, that.textEmbeddingSettings) && Objects.equals(url, that.url) && Objects.equals(headers, that.headers) && Objects.equals(queryParameters, that.queryParameters) && Objects.equals(requestContentString, that.requestContentString) && Objects.equals(responseJsonParser, that.responseJsonParser) && Objects.equals(rateLimitSettings, that.rateLimitSettings) && Objects.equals(batchSize, that.batchSize) && Objects.equals(inputTypeTranslator, that.inputTypeTranslator); } @Override public int hashCode() { return Objects.hash( textEmbeddingSettings, url, headers, queryParameters, requestContentString, responseJsonParser, rateLimitSettings, batchSize, inputTypeTranslator ); } private static CustomResponseParser extractResponseParser( TaskType taskType, Map<String, Object> responseParserMap, ValidationException validationException ) { if (responseParserMap == null) { return NoopResponseParser.INSTANCE; } return switch (taskType) { case TEXT_EMBEDDING -> DenseEmbeddingResponseParser.fromMap(responseParserMap, RESPONSE_SCOPE, validationException); case SPARSE_EMBEDDING -> SparseEmbeddingResponseParser.fromMap(responseParserMap, RESPONSE_SCOPE, validationException); case RERANK -> RerankResponseParser.fromMap(responseParserMap, RESPONSE_SCOPE, validationException); case COMPLETION -> CompletionResponseParser.fromMap(responseParserMap, RESPONSE_SCOPE, validationException); default -> throw new IllegalArgumentException( Strings.format("Invalid task type received [%s] while constructing response parser", taskType) ); }; } }
TextEmbeddingSettings
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/ref/RefTest23.java
{ "start": 192, "end": 1101 }
class ____ extends TestCase { public void test_ref() throws Exception { String json = "{\"$ref\":\"tmall/item\",\"id\":123}"; JSONObject root = JSON.parseObject(json); assertEquals("tmall/item", root.get("$ref")); assertEquals(123, root.get("id")); } public void test_ref_1() throws Exception { String json = "{\"$ref\":123}"; JSONObject root = JSON.parseObject(json); assertEquals(123, root.get("$ref")); } public void test_ref_2() throws Exception { String json = "{\n" + "\t\"bbbb\\\"\":{\n" + "\t\t\"x\":\"x\"\n" + "\t},\n" + "\t\"aaaa\\\"\":{\"$ref\":\"$.bbbb\\\\\\\"\"}\n" + "}"; System.out.println(json); JSONObject root = JSON.parseObject(json); assertSame(root.get("bbbb\\"), root.get("aaaa\\")); } }
RefTest23
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/testdata/input/MayOptionallyUseTemplateExample.java
{ "start": 821, "end": 1199 }
class ____ { public void example1() { try { System.out.println(new String(new byte[0], "UTF-8")); } catch (UnsupportedEncodingException e) { } } public void example2() { try { System.out.println(new String(new byte[0], "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
MayOptionallyUseTemplateExample
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DistributionArchiveCheckExtension.java
{ "start": 609, "end": 846 }
class ____ { ListProperty<String> expectedMlLicenses; public DistributionArchiveCheckExtension(ObjectFactory factory) { this.expectedMlLicenses = factory.listProperty(String.class); } }
DistributionArchiveCheckExtension
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/SchemaUtil.java
{ "start": 441, "end": 2207 }
class ____ { private SchemaUtil() { } public static Set<String> getColumnNames( Class<?> entityType, MappingMetamodel metamodel) { Set<String> result = new HashSet<>(); var persister = metamodel.getEntityDescriptor(entityType); if (persister == null) { return result; } for (String propertyName : persister.getPropertyNames()) { Collections.addAll(result, persister.getPropertyColumnNames(propertyName)); } return result; } public static String getColumnTypeName( Class<?> entityType, String columnName, MappingMetamodel mappingMetaModel) { EntityPersister entityDescriptor = mappingMetaModel.findEntityDescriptor(entityType); var columnFinder = new SelectableConsumer() { private SelectableMapping found; @Override public void accept(int selectionIndex, SelectableMapping selectableMapping) { if (found == null && selectableMapping.getSelectableName().equals(columnName)) { found = selectableMapping; } } }; entityDescriptor.forEachSelectable(columnFinder); return columnFinder.found.getJdbcMapping().getJdbcType().getFriendlyName(); } public static Generator getGenerator(Class<?> entityType, MappingMetamodel mappingMetamodel) { EntityPersister entityDescriptor = mappingMetamodel.findEntityDescriptor(entityType); return entityDescriptor.getGenerator(); } public static MappingMetamodel mappingMetamodel(Mutiny.SessionFactory sessionFactory) { return (MappingMetamodel) sessionFactory.getMetamodel(); } }
SchemaUtil
java
spring-projects__spring-framework
spring-expression/src/main/java/org/springframework/expression/spel/ast/LongLiteral.java
{ "start": 954, "end": 1516 }
class ____ extends Literal { private final TypedValue value; public LongLiteral(String payload, int startPos, int endPos, long value) { super(payload, startPos, endPos); this.value = new TypedValue(value); this.exitTypeDescriptor = "J"; } @Override public TypedValue getLiteralValue() { return this.value; } @Override public boolean isCompilable() { return true; } @Override public void generateCode(MethodVisitor mv, CodeFlow cf) { mv.visitLdcInsn(this.value.getValue()); cf.pushDescriptor(this.exitTypeDescriptor); } }
LongLiteral
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/cdi/QualifiedCustomizedUserRepository.java
{ "start": 834, "end": 979 }
interface ____ extends Repository<User, Integer>, QualifiedCustomizedUserRepositoryCustom, QualifiedFragment { }
QualifiedCustomizedUserRepository
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2400/Issue2428.java
{ "start": 395, "end": 545 }
class ____ extends TestCase { private String myName; private NestedBean nestedBean; @AllArgsConstructor @Data public static
Issue2428
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/fuseable/HasUpstreamSingleSource.java
{ "start": 922, "end": 1176 }
interface ____<@NonNull T> { /** * Returns the upstream source of this Single. * <p>Allows discovering the chain of observables. * @return the source SingleSource */ @NonNull SingleSource<T> source(); }
HasUpstreamSingleSource
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/cache/ContextCache.java
{ "start": 10598, "end": 13588 }
class ____ is no longer using the application context(s) * @since 7.0 * @see #registerContextUsage(MergedContextConfiguration, Class) * @see #getContextUsageCount() */ default void unregisterContextUsage(MergedContextConfiguration key, Class<?> testClass) { /* no-op */ } /** * Determine the number of contexts within the cache that are currently in use. * <p>The default implementation of this method always returns {@code 0}. * Concrete implementations are therefore highly encouraged to override this * method, {@link #registerContextUsage(MergedContextConfiguration, Class)}, * and {@link #unregisterContextUsage(MergedContextConfiguration, Class)} with * appropriate behavior. Note that the standard {@code ContextContext} * implementation in Spring overrides these methods appropriately. * @since 7.0 * @see #registerContextUsage(MergedContextConfiguration, Class) * @see #unregisterContextUsage(MergedContextConfiguration, Class) */ default int getContextUsageCount() { return 0; } /** * Determine the number of contexts currently stored in the cache. * <p>If the cache contains more than {@code Integer.MAX_VALUE} elements, * this method must return {@code Integer.MAX_VALUE}. */ int size(); /** * Determine the number of parent contexts currently tracked within the cache. */ int getParentContextCount(); /** * Get the overall hit count for this cache. * <p>A <em>hit</em> is any access to the cache that returns a non-null * context for the queried key. */ int getHitCount(); /** * Get the overall miss count for this cache. * <p>A <em>miss</em> is any access to the cache that returns a {@code null} * context for the queried key. */ int getMissCount(); /** * Reset all state maintained by this cache including statistics. * @see #clear() * @see #clearStatistics() */ void reset(); /** * Clear all contexts from the cache, clearing context hierarchy information as well. */ void clear(); /** * Clear {@linkplain #getHitCount() hit count} and {@linkplain #getMissCount() * miss count} statistics for the cache (i.e., reset counters to zero). */ void clearStatistics(); /** * Log the statistics for this {@code ContextCache} at {@code DEBUG} level * using the {@value #CONTEXT_CACHE_LOGGING_CATEGORY} logging category. * <p>The following information should be logged. * <ul> * <li>name of the concrete {@code ContextCache} implementation</li> * <li>{@linkplain #size}</li> * <li>{@linkplain #getContextUsageCount() context usage count}</li> * <li>{@linkplain #getParentContextCount() parent context count}</li> * <li>{@linkplain #getHitCount() hit count}</li> * <li>{@linkplain #getMissCount() miss count}</li> * <li>any other information useful for monitoring the state of this cache</li> * </ul> */ void logStatistics(); /** * Represents a function that loads an {@link ApplicationContext}. * * @since 7.0 */ @FunctionalInterface
that
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/TransactionalStringCommands.java
{ "start": 151, "end": 8096 }
interface ____<K, V> extends TransactionalRedisCommands { /** * Execute the command <a href="https://redis.io/commands/append">APPEND</a>. * Summary: Append a value to a key * Group: string * Requires Redis 2.0.0 * * @param key the key * @param value the value */ void append(K key, V value); /** * Execute the command <a href="https://redis.io/commands/decr">DECR</a>. * Summary: Decrement the integer value of a key by one * Group: string * Requires Redis 1.0.0 * * @param key the key */ void decr(K key); /** * Execute the command <a href="https://redis.io/commands/decrby">DECRBY</a>. * Summary: Decrement the integer value of a key by the given number * Group: string * Requires Redis 1.0.0 * * @param key the key * @param amount the amount, can be negative */ void decrby(K key, long amount); /** * Execute the command <a href="https://redis.io/commands/get">GET</a>. * Summary: Get the value of a key * Group: string * Requires Redis 1.0.0 * * @param key the key */ void get(K key); /** * Execute the command <a href="https://redis.io/commands/getdel">GETDEL</a>. * Summary: Get the value of a key and delete the key * Group: string * Requires Redis 6.2.0 * * @param key the key */ void getdel(K key); /** * Execute the command <a href="https://redis.io/commands/getex">GETEX</a>. * Summary: Get the value of a key and optionally set its expiration * Group: string * Requires Redis 6.2.0 * * @param key the key * @param args the getex command extra-arguments */ void getex(K key, GetExArgs args); /** * Execute the command <a href="https://redis.io/commands/getrange">GETRANGE</a>. * Summary: Get a substring of the string stored at a key * Group: string * Requires Redis 2.4.0 * * @param key the key * @param start the start offset * @param end the end offset */ void getrange(K key, long start, long end); /** * Execute the command <a href="https://redis.io/commands/getset">GETSET</a>. * Summary: Set the string value of a key and return its old value * Group: string * Requires Redis 1.0.0 * * @param key the key * @param value the value * @deprecated See https://redis.io/commands/getset */ void getset(K key, V value); /** * Execute the command <a href="https://redis.io/commands/incr">INCR</a>. * Summary: Increment the integer value of a key by one * Group: string * Requires Redis 1.0.0 * * @param key the key */ void incr(K key); /** * Execute the command <a href="https://redis.io/commands/incrby">INCRBY</a>. * Summary: Increment the integer value of a key by the given amount * Group: string * Requires Redis 1.0.0 * * @param key the key * @param amount the amount, can be negative */ void incrby(K key, long amount); /** * Execute the command <a href="https://redis.io/commands/incrbyfloat">INCRBYFLOAT</a>. * Summary: Increment the float value of a key by the given amount * Group: string * Requires Redis 2.6.0 * * @param key the key * @param amount the amount, can be negative */ void incrbyfloat(K key, double amount); /** * Execute the command <a href="https://redis.io/commands/lcs">LCS</a>. * Summary: Find longest common substring * Group: string * Requires Redis 7.0.0 * * @param key1 the key * @param key2 the key */ void lcs(K key1, K key2); /** * Execute the command <a href="https://redis.io/commands/lcs">LCS</a>. * Summary: Find longest common substring and return the length (using {@code LEN}) * Group: string * Requires Redis 7.0.0 * * @param key1 the key * @param key2 the key */ void lcsLength(K key1, K key2); /** * Execute the command <a href="https://redis.io/commands/mget">MGET</a>. * Summary: Get the values of all the given keys * Group: string * Requires Redis 1.0.0 * * @param keys the keys */ void mget(K... keys); /** * Execute the command <a href="https://redis.io/commands/mset">MSET</a>. * Summary: Set multiple keys to multiple values * Group: string * Requires Redis 1.0.1 * * @param map the key/value map containing the items to store */ void mset(Map<K, V> map); /** * Execute the command <a href="https://redis.io/commands/msetnx">MSETNX</a>. * Summary: Set multiple keys to multiple values, only if none of the keys exist * Group: string * Requires Redis 1.0.1 * * @param map the key/value map containing the items to store */ void msetnx(Map<K, V> map); /** * Execute the command <a href="https://redis.io/commands/psetex">PSETEX</a>. * Summary: Set the value and expiration in milliseconds of a key * Group: string * Requires Redis 2.6.0 * * @param key the key * @param milliseconds the duration in ms * @param value the value */ void psetex(K key, long milliseconds, V value); /** * Execute the command <a href="https://redis.io/commands/set">SET</a>. * Summary: Set the string value of a key * Group: string * Requires Redis 1.0.0 * * @param key the key * @param value the value */ void set(K key, V value); /** * Execute the command <a href="https://redis.io/commands/set">SET</a>. * Summary: Set the string value of a key * Group: string * Requires Redis 1.0.0 * * @param key the key * @param value the value * @param setArgs the set command extra-arguments */ void set(K key, V value, SetArgs setArgs); /** * Execute the command <a href="https://redis.io/commands/set">SET</a>. * Summary: Set the string value of a key, and return the previous value * Group: string * Requires Redis 1.0.0 * * @param key the key * @param value the value */ void setGet(K key, V value); /** * Execute the command <a href="https://redis.io/commands/set">SET</a>. * Summary: Set the string value of a key, and return the previous value * Group: string * Requires Redis 1.0.0 * * @param key the key * @param value the value * @param setArgs the set command extra-arguments */ void setGet(K key, V value, SetArgs setArgs); /** * Execute the command <a href="https://redis.io/commands/setex">SETEX</a>. * Summary: Set the value and expiration of a key * Group: string * Requires Redis 2.0.0 * * @param key the key * @param value the value */ void setex(K key, long seconds, V value); /** * Execute the command <a href="https://redis.io/commands/setnx">SETNX</a>. * Summary: Set the value of a key, only if the key does not exist * Group: string * Requires Redis 1.0.0 * * @param key the key * @param value the value */ void setnx(K key, V value); /** * Execute the command <a href="https://redis.io/commands/setrange">SETRANGE</a>. * Summary: Overwrite part of a string at key starting at the specified offset * Group: string * Requires Redis 2.2.0 * * @param key the key * @param value the value */ void setrange(K key, long offset, V value); /** * Execute the command <a href="https://redis.io/commands/strlen">STRLEN</a>. * Summary: Get the length of the value stored in a key * Group: string * Requires Redis 2.2.0 * * @param key the key */ void strlen(K key); }
TransactionalStringCommands
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/VertxHandler.java
{ "start": 867, "end": 5314 }
class ____<C extends VertxConnection> extends ChannelDuplexHandler { public static <C extends VertxConnection> VertxHandler<C> create(Function<ChannelHandlerContext, C> connectionFactory) { return new VertxHandler<>(connectionFactory); } private final Function<ChannelHandlerContext, C> connectionFactory; private C conn; private Handler<C> addHandler; private Handler<C> removeHandler; private VertxHandler(Function<ChannelHandlerContext, C> connectionFactory) { this.connectionFactory = connectionFactory; } public static ByteBuf copyBuffer(ByteBuf byteBuf) { Class<?> allocClass; if (byteBuf != Unpooled.EMPTY_BUFFER && ((allocClass = byteBuf.alloc().getClass()) == AdaptiveByteBufAllocator.class || allocClass == PooledByteBufAllocator.class || byteBuf instanceof CompositeByteBuf)) { if (byteBuf.isReadable()) { ByteBuf buffer = VertxByteBufAllocator.DEFAULT.heapBuffer(byteBuf.readableBytes()); buffer.writeBytes(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes()); return buffer; } else { return Unpooled.EMPTY_BUFFER; } } return byteBuf; } /** * Pooled {@code byteBuf} are copied and released, otherwise it is returned as is. * * @param byteBuf the buffer * @return a buffer safe */ public static ByteBuf safeBuffer(ByteBuf byteBuf) { Class<?> allocClass; if (byteBuf != Unpooled.EMPTY_BUFFER && ((allocClass = byteBuf.alloc().getClass()) == AdaptiveByteBufAllocator.class || allocClass == PooledByteBufAllocator.class || byteBuf instanceof CompositeByteBuf)) { try { if (byteBuf.isReadable()) { ByteBuf buffer = VertxByteBufAllocator.DEFAULT.heapBuffer(byteBuf.readableBytes()); buffer.writeBytes(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes()); return buffer; } else { return Unpooled.EMPTY_BUFFER; } } finally { byteBuf.release(); } } return byteBuf; } /** * Set the connection, this is called when the channel is added to the pipeline. * * @param connection the connection */ private void setConnection(C connection) { conn = connection; if (addHandler != null) { addHandler.handle(connection); } } @Override public void handlerAdded(ChannelHandlerContext ctx) { setConnection(connectionFactory.apply(ctx)); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { if (removeHandler != null) { Handler<C> handler = removeHandler; removeHandler = null; handler.handle(conn); } } /** * Set an handler to be called when the connection is set on this handler. * * @param handler the handler to be notified * @return this */ public VertxHandler<C> addHandler(Handler<C> handler) { this.addHandler = handler; return this; } /** * Set an handler to be called when the connection is unset from this handler. * * @param handler the handler to be notified * @return this */ public VertxHandler<C> removeHandler(Handler<C> handler) { this.removeHandler = handler; return this; } public C getConnection() { return conn; } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) { C conn = getConnection(); conn.channelWritabilityChanged(); } @Override public void exceptionCaught(ChannelHandlerContext chctx, final Throwable t) { C connection = getConnection(); boolean close; if (connection != null) { close = connection.handleException(t); } else { close = true; } if (close) { chctx.close(); } } @Override public void channelInactive(ChannelHandlerContext chctx) { conn.handleClosed(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { conn.readComplete(); } @Override public void channelRead(ChannelHandlerContext chctx, Object msg) { conn.read(msg); } @Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { conn.handleClose(promise); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { conn.handleIdle((IdleStateEvent) evt); } conn.handleEvent(evt); } }
VertxHandler
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/HANAServerConfiguration.java
{ "start": 752, "end": 6590 }
class ____ { private static final Pattern CLOUD_VERSION_PATTERN = Pattern.compile( "\\(fa/CE(\\d+)\\.(\\d+)\\)" ); public static final int MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE = 1024; private final DatabaseVersion fullVersion; private final int maxLobPrefetchSize; public HANAServerConfiguration(DatabaseVersion fullVersion) { this( fullVersion, MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE ); } public HANAServerConfiguration(DatabaseVersion fullVersion, int maxLobPrefetchSize) { this.fullVersion = fullVersion; this.maxLobPrefetchSize = maxLobPrefetchSize; } public DatabaseVersion getFullVersion() { return fullVersion; } public int getMaxLobPrefetchSize() { return maxLobPrefetchSize; } public static HANAServerConfiguration fromDialectResolutionInfo(DialectResolutionInfo info) { Integer maxLobPrefetchSize = null; final DatabaseMetaData databaseMetaData = info.getDatabaseMetadata(); DatabaseVersion databaseVersion = null; if ( databaseMetaData != null ) { int databaseMajorVersion = -1; try { databaseMajorVersion = databaseMetaData.getDatabaseMajorVersion(); } catch (SQLException e) { // Ignore Logger.getLogger( HANAServerConfiguration.class ) .debug( "An error occurred while trying to determine the database version.", e ); } if (databaseMajorVersion > 0 && databaseMajorVersion < 4) { try (final Statement statement = databaseMetaData.getConnection().createStatement()) { try ( ResultSet rs = statement.executeQuery( "SELECT TOP 1 VALUE,MAP(LAYER_NAME,'DEFAULT',1,'SYSTEM',2,'DATABASE',3,4) AS LAYER FROM SYS.M_CONFIGURATION_PARAMETER_VALUES WHERE FILE_NAME='indexserver.ini' AND SECTION='session' AND KEY='max_lob_prefetch_size' ORDER BY LAYER DESC" ) ) { // This only works if the current user has the privilege INIFILE ADMIN if ( rs.next() ) { maxLobPrefetchSize = rs.getInt( 1 ); } } } catch (SQLException e) { // Ignore Logger.getLogger( HANAServerConfiguration.class ) .debug( "An error occurred while trying to determine the value of the HANA parameter indexserver.ini / session / max_lob_prefetch_size", e ); } } else { databaseVersion = determineDatabaseVersion( info ); } } // default to the dialect-specific configuration settings if ( maxLobPrefetchSize == null ) { maxLobPrefetchSize = ConfigurationHelper.getInt( HANA_MAX_LOB_PREFETCH_SIZE, info.getConfigurationValues(), MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE ); } if ( databaseVersion == null ) { databaseVersion = staticDetermineDatabaseVersion( info ); } return new HANAServerConfiguration( databaseVersion, maxLobPrefetchSize ); } public static DatabaseVersion determineDatabaseVersion(DialectResolutionInfo info) { final DatabaseMetaData databaseMetaData = info.getDatabaseMetadata(); String databaseVersion = null; if ( databaseMetaData != null ) { try (final Statement statement = databaseMetaData.getConnection().createStatement()) { try (ResultSet rs = statement.executeQuery( "SELECT VALUE FROM M_SYSTEM_OVERVIEW WHERE NAME='Version'" )) { // This only works if the current user has the privilege INIFILE ADMIN if ( rs.next() ) { databaseVersion = rs.getString( 1 ); } } } catch (SQLException e) { // Ignore Logger.getLogger( HANAServerConfiguration.class ) .debug( "An error occurred while trying to determine the HANA Cloud version.", e ); } } return databaseVersion == null ? staticDetermineDatabaseVersion( info ) : determineDatabaseVersion( databaseVersion ); } public static DatabaseVersion determineDatabaseVersion(String versionString) { if ( versionString == null ) { return HANADialect.MINIMUM_VERSION; } final String[] components = StringHelper.split( " ", versionString ); final DatabaseVersion databaseVersion = staticDetermineDatabaseVersion( components[0] ); if ( components.length == 1 || databaseVersion.isBefore( 4 ) ) { return databaseVersion; } else { // Parse the HANA Cloud version final Matcher matcher = CLOUD_VERSION_PATTERN.matcher( components[1] ); if ( matcher.matches() ) { final int year = Integer.parseInt( matcher.group( 1 ) ); final int week = Integer.parseInt( matcher.group( 2 ) ); return new SimpleDatabaseVersion( databaseVersion.getDatabaseMajorVersion(), getHanaCloudVersion( LocalDate.of( year, 1, 1 ).plusWeeks( week ) ), databaseVersion.getDatabaseMicroVersion() ); } else { return databaseVersion; } } } private static int getHanaCloudVersion(LocalDate date) { final int quarter = switch (date.getMonth()) { case JANUARY, FEBRUARY, MARCH -> 1; case APRIL, MAY, JUNE -> 2; case JULY, AUGUST, SEPTEMBER -> 3; case OCTOBER, NOVEMBER, DECEMBER -> 4; }; return date.getYear() * 10 + quarter; } public static DatabaseVersion staticDetermineDatabaseVersion(DialectResolutionInfo info) { return staticDetermineDatabaseVersion( info.getDatabaseVersion() ); } public static DatabaseVersion staticDetermineDatabaseVersion(String versionString) { // Parse the version according to https://answers.sap.com/questions/9760991/hana-sps-version-check.html int majorVersion = 1; int minorVersion = 0; int patchLevel = 0; if ( versionString == null ) { return HANADialect.MINIMUM_VERSION; } final String[] components = StringHelper.split( ".", versionString ); if ( components.length >= 3 ) { try { majorVersion = Integer.parseInt( components[0] ); minorVersion = Integer.parseInt( components[1] ); patchLevel = Integer.parseInt( components[2] ); } catch (NumberFormatException ex) { // Ignore } } return DatabaseVersion.make( majorVersion, minorVersion, patchLevel ); } }
HANAServerConfiguration
java
apache__flink
flink-python/src/main/java/org/apache/flink/table/runtime/typeutils/PythonTypeUtils.java
{ "start": 22160, "end": 22819 }
class ____ extends DataConverter<Byte, Byte, Long> { public static final ByteDataConverter INSTANCE = new ByteDataConverter(); private ByteDataConverter() { super(DataFormatConverters.ByteConverter.INSTANCE); } @Override Byte toInternalImpl(Long value) { return value.byteValue(); } @Override Long toExternalImpl(Byte value) { return value.longValue(); } } /** * Python Long will be converted to Long in PemJa, so we need ShortDataConverter to convert Java * Long to internal Short. */ public static final
ByteDataConverter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/System.java
{ "start": 305, "end": 540 }
class ____ extends Principal { private String code; public System() { } public System(String uid) { super( uid ); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
System
java
quarkusio__quarkus
extensions/kubernetes-client/runtime/src/main/java/io/quarkus/kubernetes/client/KubernetesClientObjectMapper.java
{ "start": 1028, "end": 1355 }
class ____ extends AnnotationLiteral<KubernetesClientObjectMapper> implements KubernetesClientObjectMapper { @SuppressWarnings("unused") public static final Literal INSTANCE = new Literal(); private static final long serialVersionUID = 1L; private Literal() { } } }
Literal
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/method/configuration/issue14637/domain/Entry.java
{ "start": 923, "end": 1108 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } }
Entry
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/MountVolumeInfo.java
{ "start": 1356, "end": 4935 }
class ____ { private final EnumMap<StorageType, FsVolumeImpl> storageTypeVolumeMap; private final EnumMap<StorageType, Double> capacityRatioMap; private double reservedForArchiveDefault; MountVolumeInfo(Configuration conf) { storageTypeVolumeMap = new EnumMap<>(StorageType.class); capacityRatioMap = new EnumMap<>(StorageType.class); reservedForArchiveDefault = conf.getDouble( DFSConfigKeys.DFS_DATANODE_RESERVE_FOR_ARCHIVE_DEFAULT_PERCENTAGE, DFSConfigKeys .DFS_DATANODE_RESERVE_FOR_ARCHIVE_DEFAULT_PERCENTAGE_DEFAULT); if (reservedForArchiveDefault > 1) { FsDatasetImpl.LOG.warn("Value of reserve-for-archival is > 100%." + " Setting it to 100%."); reservedForArchiveDefault = 1; } if (reservedForArchiveDefault < 0) { FsDatasetImpl.LOG.warn("Value of reserve-for-archival is < 0." + " Setting it to 0.0"); reservedForArchiveDefault = 0; } } FsVolumeReference getVolumeRef(StorageType storageType) { try { FsVolumeImpl volumeImpl = storageTypeVolumeMap .getOrDefault(storageType, null); if (volumeImpl != null) { return volumeImpl.obtainReference(); } } catch (ClosedChannelException e) { FsDatasetImpl.LOG.warn("Volume closed when getting volume" + " by storage type: " + storageType); } return null; } /** * Return configured capacity ratio. */ double getCapacityRatio(StorageType storageType) { // If capacity ratio is set, return the val. if (capacityRatioMap.containsKey(storageType)) { return capacityRatioMap.get(storageType); } // If capacity ratio is set for counterpart, // use the rest of capacity of the mount for it. if (!capacityRatioMap.isEmpty()) { double leftOver = 1; for (Map.Entry<StorageType, Double> e : capacityRatioMap.entrySet()) { leftOver -= e.getValue(); } return leftOver; } // Use reservedForArchiveDefault by default. if (storageTypeVolumeMap.containsKey(storageType) && storageTypeVolumeMap.size() > 1) { if (storageType == StorageType.ARCHIVE) { return reservedForArchiveDefault; } else if (storageType == StorageType.DISK) { return 1 - reservedForArchiveDefault; } } return 1; } /** * Add a volume to the mapping. * If there is already storage type exists on same mount, skip this volume. */ boolean addVolume(FsVolumeImpl volume) { if (storageTypeVolumeMap.containsKey(volume.getStorageType())) { FsDatasetImpl.LOG.error("Found storage type already exist." + " Skipping for now. Please check disk configuration"); return false; } storageTypeVolumeMap.put(volume.getStorageType(), volume); return true; } void removeVolume(FsVolumeImpl target) { storageTypeVolumeMap.remove(target.getStorageType()); capacityRatioMap.remove(target.getStorageType()); } /** * Set customize capacity ratio for a storage type. * Return false if the value is too big. */ boolean setCapacityRatio(StorageType storageType, double capacityRatio) { double leftover = 1; for (Map.Entry<StorageType, Double> e : capacityRatioMap.entrySet()) { if (e.getKey() != storageType) { leftover -= e.getValue(); } } if (leftover < capacityRatio) { return false; } capacityRatioMap.put(storageType, capacityRatio); return true; } int size() { return storageTypeVolumeMap.size(); } }
MountVolumeInfo
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/InputDemuxer.java
{ "start": 1114, "end": 2050 }
interface ____ extends Closeable { /** * Bind the {@link InputDemuxer} to a particular file. * * @param path * The path to the file it should bind to. * @param conf * Configuration * @throws IOException * * Returns true when the binding succeeds. If the file can be read * but is in the wrong format, returns false. IOException is * reserved for read errors. */ public void bindTo(Path path, Configuration conf) throws IOException; /** * Get the next &lt;name, input&gt; pair. The name should preserve the original job * history file or job conf file name. The input object should be closed * before calling getNext() again. The old input object would be invalid after * calling getNext() again. * * @return the next &lt;name, input&gt; pair. */ public Pair<String, InputStream> getNext() throws IOException; }
InputDemuxer
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/test/java/org/apache/hadoop/hdfs/protocol/TestReadOnly.java
{ "start": 1128, "end": 1204 }
class ____ {@link ReadOnly} annotation on {@link ClientProtocol}. */ public
for
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/web/server/SessionManagementSpecTests.java
{ "start": 15760, "end": 16517 }
class ____ { static SessionLimit sessionLimit = SessionLimit.of(1); @Bean SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { // @formatter:off http .authorizeExchange((authorize) -> authorize.anyExchange().authenticated()) .formLogin(Customizer.withDefaults()) .sessionManagement((sessionManagement) -> sessionManagement .concurrentSessions((concurrentSessions) -> concurrentSessions .maximumSessions(sessionLimit) .maximumSessionsExceededHandler(new PreventLoginServerMaximumSessionsExceededHandler()) ) ); // @formatter:on return http.build(); } } @Configuration @EnableWebFlux @EnableWebFluxSecurity @Import(Config.class) static
ConcurrentSessionsMaxSessionPreventsLoginConfig
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 12805, "end": 13022 }
class ____ resolvable but there * was a readability mismatch in the inheritance hierarchy of the class (typically a * missing dependency declaration in a Java Module System module definition for a * superclass or
is
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/unproxyable/ProducerFailedToAddMissingNoargsConstructorTest.java
{ "start": 1286, "end": 1358 }
class ____ { public MyBase(String foo) { } } }
MyBase
java
apache__camel
components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/pojos/CalculatorTool.java
{ "start": 977, "end": 1409 }
class ____ { @Tool("Adds two numbers") public int add(@P("First number") int a, @P("Second number") int b) { return a + b; } @Tool("Multiplies two numbers") public int multiply(@P("First number") int a, @P("Second number") int b) { return a * b; } @Tool("Gets the square root of a number") public double sqrt(@P("Number") double x) { return Math.sqrt(x); } }
CalculatorTool
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java
{ "start": 54164, "end": 76720 }
interface ____ provides access. * @param delegation Represents delegation token used for authentication. * @param username User parameter. * @param doAsUser DoAs parameter for proxy user. * @param op Http DELETE operation parameter. * @param offset Offset parameter. * @param length Length parameter. * @param renewer Renewer parameter. * @param bufferSize Buffer size parameter. * @param xattrNames XAttr Name parameter. * @param xattrEncoding Xattr Encoding parameter. * @param excludeDatanodes Exclude datanodes param. * @param fsAction FsAction Parameter. * @param snapshotName * The snapshot name parameter for createSnapshot and deleteSnapshot operation. * @param oldSnapshotName * The old snapshot name parameter for renameSnapshot operation. * @param snapshotDiffStartPath * The snapshot startPath parameter used by snapshotDiffReportListing. * @param snapshotDiffIndex * resuming index of snapshotDiffReportListing operation. * @param tokenKind tokenKind Parameter. * @param tokenService tokenService Parameter. * @param noredirect overwrite parameter. * @param startAfter used during batched ListStatus operations. * @param allUsers AllUsers parameter. * @return Represents an HTTP response. * @throws IOException any IOE raised, or translated exception. * @throws InterruptedException if the current thread was interrupted * before or during the call. */ @GET @Path("{" + UriFsPathParam.NAME + ":.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get( @Context final UserGroupInformation ugi, @Context final UriInfo uriInfo, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT) final GetOpParam op, @QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT) final OffsetParam offset, @QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT) final LengthParam length, @QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT) final RenewerParam renewer, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT) final List<XAttrNameParam> xattrNames, @QueryParam(XAttrEncodingParam.NAME) @DefaultValue(XAttrEncodingParam.DEFAULT) final XAttrEncodingParam xattrEncoding, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes, @QueryParam(FsActionParam.NAME) @DefaultValue(FsActionParam.DEFAULT) final FsActionParam fsAction, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName, @QueryParam(OldSnapshotNameParam.NAME) @DefaultValue(OldSnapshotNameParam.DEFAULT) final OldSnapshotNameParam oldSnapshotName, @QueryParam(SnapshotDiffStartPathParam.NAME) @DefaultValue(SnapshotDiffStartPathParam.DEFAULT) final SnapshotDiffStartPathParam snapshotDiffStartPath, @QueryParam(SnapshotDiffIndexParam.NAME) @DefaultValue(SnapshotDiffIndexParam.DEFAULT) final SnapshotDiffIndexParam snapshotDiffIndex, @QueryParam(TokenKindParam.NAME) @DefaultValue(TokenKindParam.DEFAULT) final TokenKindParam tokenKind, @QueryParam(TokenServiceParam.NAME) @DefaultValue(TokenServiceParam.DEFAULT) final TokenServiceParam tokenService, @QueryParam(NoRedirectParam.NAME) @DefaultValue(NoRedirectParam.DEFAULT) final NoRedirectParam noredirect, @QueryParam(StartAfterParam.NAME) @DefaultValue(StartAfterParam.DEFAULT) final StartAfterParam startAfter, @QueryParam(AllUsersParam.NAME) @DefaultValue(AllUsersParam.DEFAULT) final AllUsersParam allUsers ) throws IOException, InterruptedException { final UriFsPathParam path = new UriFsPathParam(uriInfo.getPath()); init(ugi, delegation, username, doAsUser, path, op, offset, length, renewer, bufferSize, xattrEncoding, excludeDatanodes, fsAction, snapshotName, oldSnapshotName, tokenKind, tokenService, startAfter, allUsers); return doAs(ugi, () -> get(ugi, delegation, username, doAsUser, path.getAbsolutePath(), op, offset, length, renewer, bufferSize, xattrNames, xattrEncoding, excludeDatanodes, fsAction, snapshotName, oldSnapshotName, snapshotDiffStartPath, snapshotDiffIndex, tokenKind, tokenService, noredirect, startAfter, allUsers)); } private static String encodeFeInfo(FileEncryptionInfo feInfo) { Encoder encoder = Base64.getEncoder(); String encodedValue = encoder .encodeToString(PBHelperClient.convert(feInfo).toByteArray()); return encodedValue; } protected Response get( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final GetOpParam op, final OffsetParam offset, final LengthParam length, final RenewerParam renewer, final BufferSizeParam bufferSize, final List<XAttrNameParam> xattrNames, final XAttrEncodingParam xattrEncoding, final ExcludeDatanodesParam excludeDatanodes, final FsActionParam fsAction, final SnapshotNameParam snapshotName, final OldSnapshotNameParam oldSnapshotName, final SnapshotDiffStartPathParam snapshotDiffStartPath, final SnapshotDiffIndexParam snapshotDiffIndex, final TokenKindParam tokenKind, final TokenServiceParam tokenService, final NoRedirectParam noredirectParam, final StartAfterParam startAfter, final AllUsersParam allUsers ) throws IOException, URISyntaxException { final Configuration conf = (Configuration) context .getAttribute(JspHelper.CURRENT_CONF); final ClientProtocol cp = getRpcClientProtocol(); switch(op.getValue()) { case OPEN: { final NameNode namenode = (NameNode)context.getAttribute("name.node"); ResponseBuilder rb = Response.noContent(); final URI uri = redirectURI(rb, namenode, ugi, delegation, username, doAsUser, fullpath, op.getValue(), offset.getValue(), -1L, excludeDatanodes.getValue(), offset, length, bufferSize); if(!noredirectParam.getValue()) { return rb.status(Status.TEMPORARY_REDIRECT).location(uri) .type(MediaType.APPLICATION_OCTET_STREAM).build(); } else { final String js = JsonUtil.toJsonString("Location", uri); return rb.status(Status.OK).entity(js).type(MediaType.APPLICATION_JSON) .build(); } } case GETFILEBLOCKLOCATIONS: { final long offsetValue = offset.getValue(); final Long lengthValue = length.getValue(); LocatedBlocks locatedBlocks = getRpcClientProtocol() .getBlockLocations(fullpath, offsetValue, lengthValue != null ? lengthValue : Long.MAX_VALUE); BlockLocation[] locations = DFSUtilClient.locatedBlocks2Locations(locatedBlocks); final String js = JsonUtil.toJsonString(locations); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GET_BLOCK_LOCATIONS: { final long offsetValue = offset.getValue(); final Long lengthValue = length.getValue(); final LocatedBlocks locatedblocks = cp.getBlockLocations(fullpath, offsetValue, lengthValue != null? lengthValue: Long.MAX_VALUE); final String js = JsonUtil.toJsonString(locatedblocks); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETFILESTATUS: { final HdfsFileStatus status = cp.getFileInfo(fullpath); if (status == null) { throw new FileNotFoundException("File does not exist: " + fullpath); } final String js = JsonUtil.toJsonString(status, true); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case LISTSTATUS: { final StreamingOutput streaming = getListingStream(cp, fullpath); return Response.ok(streaming).type(MediaType.APPLICATION_JSON).build(); } case GETCONTENTSUMMARY: { final ContentSummary contentsummary = cp.getContentSummary(fullpath); final String js = JsonUtil.toJsonString(contentsummary); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETQUOTAUSAGE: { final QuotaUsage quotaUsage = cp.getQuotaUsage(fullpath); final String js = JsonUtil.toJsonString(quotaUsage); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETFILECHECKSUM: { final NameNode namenode = (NameNode)context.getAttribute("name.node"); final URI uri = redirectURI(null, namenode, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, -1L, null); if(!noredirectParam.getValue()) { return Response.temporaryRedirect(uri) .type(MediaType.APPLICATION_OCTET_STREAM).build(); } else { final String js = JsonUtil.toJsonString("Location", uri); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } } case GETDELEGATIONTOKEN: { if (delegation.getValue() != null) { throw new IllegalArgumentException(delegation.getName() + " parameter is not null."); } final Token<? extends TokenIdentifier> token = generateDelegationToken( ugi, renewer.getValue()); final String setServiceName = tokenService.getValue(); final String setKind = tokenKind.getValue(); if (setServiceName != null) { token.setService(new Text(setServiceName)); } if (setKind != null) { token.setKind(new Text(setKind)); } final String js = JsonUtil.toJsonString(token); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETHOMEDIRECTORY: { String userHome = DFSUtilClient.getHomeDirectory(conf, ugi); final String js = JsonUtil.toJsonString("Path", userHome); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETACLSTATUS: { AclStatus status = cp.getAclStatus(fullpath); if (status == null) { throw new FileNotFoundException("File does not exist: " + fullpath); } final String js = JsonUtil.toJsonString(status); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETXATTRS: { validateOpParams(op, xattrEncoding); List<String> names = null; if (xattrNames != null) { names = Lists.newArrayListWithCapacity(xattrNames.size()); for (XAttrNameParam xattrName : xattrNames) { if (xattrName.getXAttrName() != null) { names.add(xattrName.getXAttrName()); } } } List<XAttr> xAttrs = cp.getXAttrs(fullpath, (names != null && !names.isEmpty()) ? XAttrHelper.buildXAttrs(names) : null); final String js = JsonUtil.toJsonString(xAttrs, xattrEncoding.getEncoding()); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case LISTXATTRS: { final List<XAttr> xAttrs = cp.listXAttrs(fullpath); final String js = JsonUtil.toJsonString(xAttrs); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case CHECKACCESS: { validateOpParams(op, fsAction); cp.checkAccess(fullpath, FsAction.getFsAction(fsAction.getValue())); return Response.ok().build(); } case GETTRASHROOT: { final String trashPath = getTrashRoot(conf, fullpath); final String jsonStr = JsonUtil.toJsonString("Path", trashPath); return Response.ok(jsonStr).type(MediaType.APPLICATION_JSON).build(); } case GETTRASHROOTS: { Boolean value = allUsers.getValue(); final Collection<FileStatus> trashPaths = getTrashRoots(conf, value); final String js = JsonUtil.toJsonString(trashPaths); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case LISTSTATUS_BATCH: { byte[] start = HdfsFileStatus.EMPTY_NAME; if (startAfter != null && startAfter.getValue() != null) { start = startAfter.getValue().getBytes(StandardCharsets.UTF_8); } final DirectoryListing listing = getDirectoryListing(cp, fullpath, start); final String js = JsonUtil.toJsonString(listing); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETALLSTORAGEPOLICY: { BlockStoragePolicy[] storagePolicies = cp.getStoragePolicies(); final String js = JsonUtil.toJsonString(storagePolicies); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETSTORAGEPOLICY: { BlockStoragePolicy storagePolicy = cp.getStoragePolicy(fullpath); final String js = JsonUtil.toJsonString(storagePolicy); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETECPOLICY: { ErasureCodingPolicy ecpolicy = cp.getErasureCodingPolicy(fullpath); final String js = JsonUtil.toJsonString(ecpolicy); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETSERVERDEFAULTS: { // Since none of the server defaults values are hot reloaded, we can // cache the output of serverDefaults. String serverDefaultsResponse = (String) context.getAttribute("serverDefaults"); if (serverDefaultsResponse == null) { FsServerDefaults serverDefaults = cp.getServerDefaults(); serverDefaultsResponse = JsonUtil.toJsonString(serverDefaults); context.setAttribute("serverDefaults", serverDefaultsResponse); } return Response.ok(serverDefaultsResponse) .type(MediaType.APPLICATION_JSON).build(); } case GETSNAPSHOTDIFF: { SnapshotDiffReport diffReport = cp.getSnapshotDiffReport(fullpath, oldSnapshotName.getValue(), snapshotName.getValue()); final String js = JsonUtil.toJsonString(diffReport); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETSNAPSHOTDIFFLISTING: { SnapshotDiffReportListing diffReport = cp.getSnapshotDiffReportListing( fullpath, oldSnapshotName.getValue(), snapshotName.getValue(), DFSUtilClient.string2Bytes(snapshotDiffStartPath.getValue()), snapshotDiffIndex.getValue()); final String js = JsonUtil.toJsonString(diffReport); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETSNAPSHOTTABLEDIRECTORYLIST: { SnapshottableDirectoryStatus[] snapshottableDirectoryList = cp.getSnapshottableDirListing(); final String js = JsonUtil.toJsonString(snapshottableDirectoryList); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETSNAPSHOTLIST: { SnapshotStatus[] snapshotList = cp.getSnapshotListing(fullpath); final String js = JsonUtil.toJsonString(snapshotList); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETLINKTARGET: { String target = cp.getLinkTarget(fullpath); final String js = JsonUtil.toJsonString("Path", target); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETFILELINKSTATUS: { HdfsFileStatus status = cp.getFileLinkInfo(fullpath); if (status == null) { throw new FileNotFoundException("File does not exist: " + fullpath); } final String js = JsonUtil.toJsonString(status, true); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETSTATUS: { long[] states = cp.getStats(); FsStatus status = new FsStatus( DFSClient.getStateAtIndex(states, 0), DFSClient.getStateAtIndex(states, 1), DFSClient.getStateAtIndex(states, 2)); final String js = JsonUtil.toJsonString(status); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETECPOLICIES: { ErasureCodingPolicyInfo[] ecPolicyInfos = cp.getErasureCodingPolicies(); final String js = JsonUtil.toJsonString(ecPolicyInfos); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETECCODECS: { Map<String, String> ecCodecs = cp.getErasureCodingCodecs(); final String js = JsonUtil.toJsonString("ErasureCodingCodecs", ecCodecs); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } default: throw new UnsupportedOperationException(op + " is not supported"); } } /** * Get the snapshot root of a given file or directory if it exists. * e.g. if /snapdir1 is a snapshottable directory and path given is * /snapdir1/path/to/file, this method would return /snapdir1 * @param pathStr String of path to a file or a directory. * @return Not null if found in a snapshot root directory. * @throws IOException any IOE raised, or translated exception. */ String getSnapshotRoot(String pathStr) throws IOException { SnapshottableDirectoryStatus[] dirStatusList = getRpcClientProtocol().getSnapshottableDirListing(); if (dirStatusList == null) { return null; } for (SnapshottableDirectoryStatus dirStatus : dirStatusList) { String currDir = dirStatus.getFullPath().toString(); if (pathStr.startsWith(currDir)) { return currDir; } } return null; } private String getTrashRoot(Configuration conf, String fullPath) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); String parentSrc = getParent(fullPath); String ssTrashRoot = ""; boolean isSnapshotTrashRootEnabled = getRpcClientProtocol() .getServerDefaults().getSnapshotTrashRootEnabled(); if (isSnapshotTrashRootEnabled) { String ssRoot = getSnapshotRoot(fullPath); if (ssRoot != null) { ssTrashRoot = DFSUtilClient.getSnapshotTrashRoot(ssRoot, ugi); } } EncryptionZone ez = getRpcClientProtocol().getEZForPath( parentSrc != null ? parentSrc : fullPath); String ezTrashRoot = ""; if (ez != null) { ezTrashRoot = DFSUtilClient.getEZTrashRoot(ez, ugi); } // Choose the longest path if (ssTrashRoot.isEmpty() && ezTrashRoot.isEmpty()) { return DFSUtilClient.getTrashRoot(conf, ugi); } else { return ssTrashRoot.length() > ezTrashRoot.length() ? ssTrashRoot : ezTrashRoot; } } /** * Returns the parent of a path in the same way as Path#getParent. * @return the parent of a path or null if at root */ public String getParent(String path) { int lastSlash = path.lastIndexOf('/'); int start = 0; if ((path.length() == start) || // empty path (lastSlash == start && path.length() == start + 1)) { // at root return null; } String parent; if (lastSlash == -1) { parent = org.apache.hadoop.fs.Path.CUR_DIR; } else { parent = path.substring(0, lastSlash == start ? start + 1 : lastSlash); } return parent; } private static DirectoryListing getDirectoryListing(final ClientProtocol cp, final String p, byte[] startAfter) throws IOException { final DirectoryListing listing = cp.getListing(p, startAfter, false); if (listing == null) { // the directory does not exist throw new FileNotFoundException("File " + p + " does not exist."); } return listing; } private static StreamingOutput getListingStream(final ClientProtocol cp, final String p) throws IOException { // allows exceptions like FNF or ACE to prevent http response of 200 for // a failure since we can't (currently) return error responses in the // middle of a streaming operation final DirectoryListing firstDirList = getDirectoryListing(cp, p, HdfsFileStatus.EMPTY_NAME); // must save ugi because the streaming object will be executed outside // the remote user's ugi final UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); return new StreamingOutput() { @Override public void write(final OutputStream outstream) throws IOException { final PrintWriter out = new PrintWriter(new OutputStreamWriter( outstream, StandardCharsets.UTF_8)); out.println("{\"" + FileStatus.class.getSimpleName() + "es\":{\"" + FileStatus.class.getSimpleName() + "\":["); try { // restore remote user's ugi ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws IOException { long n = 0; for (DirectoryListing dirList = firstDirList; ; dirList = getDirectoryListing(cp, p, dirList.getLastName()) ) { // send each segment of the directory listing for (HdfsFileStatus s : dirList.getPartialListing()) { if (n++ > 0) { out.println(','); } out.print(JsonUtil.toJsonString(s, false)); } // stop if last segment if (!dirList.hasMore()) { break; } } return null; } }); } catch (InterruptedException e) { throw new IOException(e); } out.println(); out.println("]}}"); out.flush(); } }; } private Collection<FileStatus> getTrashRoots(Configuration conf, boolean allUsers) throws IOException { FileSystem fs = FileSystem.get(conf != null ? conf : new Configuration()); return fs.getTrashRoots(allUsers); } /** * Handle HTTP DELETE request for the root. * * @param ugi User and group information for Hadoop. * @param uriInfo An injectable
that
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldContainAnyOf_create_Test.java
{ "start": 1196, "end": 2900 }
class ____ { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldContainAnyOf(list("Yoda", "Han", "Han"), list("Vador", "Leia")); // WHEN String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting actual:%n" + " [\"Yoda\", \"Han\", \"Han\"]%n" + "to contain at least one of the following elements:%n" + " [\"Vador\", \"Leia\"]%n" + "but none were found")); } @Test void should_create_error_message_with_custom_comparison_strategy() { // GIVEN ErrorMessageFactory factory = shouldContainAnyOf(list("Yoda", "Han", "Han"), list("Vador", "Leia"), new ComparatorBasedComparisonStrategy(CaseInsensitiveStringComparator.INSTANCE)); // WHEN String message = factory.create(new TextDescription("Test"), CONFIGURATION_PROVIDER.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting actual:%n" + " [\"Yoda\", \"Han\", \"Han\"]%n" + "to contain at least one of the following elements:%n" + " [\"Vador\", \"Leia\"]%n" + "but none were found " + "when comparing values using CaseInsensitiveStringComparator")); } }
ShouldContainAnyOf_create_Test
java
elastic__elasticsearch
x-pack/plugin/security/qa/security-basic/src/javaRestTest/java/org/elasticsearch/xpack/security/ApiKeyAggsIT.java
{ "start": 1167, "end": 29626 }
class ____ extends SecurityInBasicRestTestCase { @SuppressWarnings("unchecked") public void testFiltersAggs() throws IOException { // admin keys createApiKey( "key1", Map.of("tags", List.of("prod", "est"), "label", "value1", "environment", Map.of("system", false, "hostname", "my-org-host-1")), API_KEY_ADMIN_AUTH_HEADER ); createApiKey( "key2", Map.of("tags", List.of("prod", "west"), "label", "value2", "environment", Map.of("system", false, "hostname", "my-org-host-2")), API_KEY_ADMIN_AUTH_HEADER ); createApiKey( "key3", Map.of("tags", List.of("prod", "south"), "label", "value3", "environment", Map.of("system", true, "hostname", "my-org-host-2")), API_KEY_ADMIN_AUTH_HEADER ); // user keys createApiKey( "key4", Map.of("tags", List.of("prod", "north"), "label", "value4", "environment", Map.of("system", true, "hostname", "my-org-host-1")), API_KEY_USER_AUTH_HEADER ); createApiKey( "wild", Map.of( "tags", List.of("staging", "west"), "label", "value5", "environment", Map.of("system", true, "hostname", "my-org-host-3") ), API_KEY_USER_AUTH_HEADER ); final boolean typedAggs = randomBoolean(); assertAggs(API_KEY_ADMIN_AUTH_HEADER, typedAggs, """ { "aggs": { "hostnames": { "filters": { "filters": { "my-org-host-1": { "term": {"metadata.environment.hostname": "my-org-host-1"}}, "my-org-host-2": { "match": {"metadata": "my-org-host-2"}} } } } } } """, aggs -> { String aggName = typedAggs ? "filters#hostnames" : "hostnames"; assertThat(((Map<String, Object>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).size(), is(2)); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get( "my-org-host-1" )).get("doc_count"), is(2) ); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get( "my-org-host-2" )).get("doc_count"), is(2) ); }); // other bucket assertAggs(API_KEY_USER_AUTH_HEADER, typedAggs, """ { "aggregations": { "only_user_keys": { "filters": { "other_bucket_key": "other_user_keys", "filters": { "only_key4_match": { "bool": { "should": [{"prefix": {"name": "key"}}, {"match": {"metadata.tags": "prod"}}]}} } } } } } """, aggs -> { String aggName = typedAggs ? "filters#only_user_keys" : "only_user_keys"; assertThat(((Map<String, Object>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).size(), is(2)); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get( "only_key4_match" )).get("doc_count"), is(1) ); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get( "other_user_keys" )).get("doc_count"), is(1) ); }); // anonymous filters assertAggs(API_KEY_USER_AUTH_HEADER, typedAggs, """ { "aggs": { "all_user_keys": { "filters": { "other_bucket_key": "other_user_keys", "filters": [ {"match_all": {}}, {"exists": {"field": "username"}}, {"wildcard": {"name": {"value": "*"}}} ] } } } } """, aggs -> { String aggName = typedAggs ? "filters#all_user_keys" : "all_user_keys"; assertThat(((List<Map<String, Object>>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).size(), is(4)); assertThat( ((List<Map<String, Object>>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get(0).get("doc_count"), is(2) ); assertThat( ((List<Map<String, Object>>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get(1).get("doc_count"), is(2) ); assertThat( ((List<Map<String, Object>>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get(2).get("doc_count"), is(2) ); // the "other" bucket assertThat( ((List<Map<String, Object>>) ((Map<String, Object>) aggs.get(aggName)).get("buckets")).get(3).get("doc_count"), is(0) ); }); // nested filters assertAggs(API_KEY_USER_AUTH_HEADER, typedAggs, """ { "aggs": { "level1": { "filters": { "keyed": false, "filters": { "rest-filter": {"term": {"type": "rest"}}, "user-filter": {"wildcard": {"username": "api_*_user"}} } }, "aggs": { "level2": { "filters": { "filters": { "invalidated": {"term": {"invalidated": true}}, "not-invalidated": {"term": {"invalidated": false}} } } } } } } } """, aggs -> { String level1AggName = typedAggs ? "filters#level1" : "level1"; List<Map<String, Object>> level1Buckets = (List<Map<String, Object>>) ((Map<String, Object>) aggs.get(level1AggName)).get( "buckets" ); assertThat(level1Buckets.size(), is(2)); assertThat(level1Buckets.get(0).get("doc_count"), is(2)); assertThat(level1Buckets.get(0).get("key"), is("rest-filter")); String level2AggName = typedAggs ? "filters#level2" : "level2"; assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) level1Buckets.get(0).get(level2AggName)).get( "buckets" )).get("invalidated")).get("doc_count"), is(0) ); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) level1Buckets.get(0).get(level2AggName)).get( "buckets" )).get("not-invalidated")).get("doc_count"), is(2) ); assertThat(level1Buckets.get(1).get("doc_count"), is(2)); assertThat(level1Buckets.get(1).get("key"), is("user-filter")); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) level1Buckets.get(1).get(level2AggName)).get( "buckets" )).get("invalidated")).get("doc_count"), is(0) ); assertThat( ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) level1Buckets.get(1).get(level2AggName)).get( "buckets" )).get("not-invalidated")).get("doc_count"), is(2) ); }); // filter on disallowed fields { Request request = new Request("GET", "/_security/_query/api_key" + (randomBoolean() ? "?typed_keys" : "")); request.setOptions( request.getOptions() .toBuilder() .addHeader(HttpHeaders.AUTHORIZATION, randomFrom(API_KEY_ADMIN_AUTH_HEADER, API_KEY_USER_AUTH_HEADER)) ); request.setJsonEntity(""" { "aggs": { "wrong-field": { "filters": { "filters": { "wrong-api-key-invalidated": { "term": {"api_key_invalidated": false}} } } } } } """); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(exception.getResponse().toString(), exception.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat(exception.getMessage(), containsString("Field [api_key_invalidated] is not allowed for querying or aggregation")); } { Request request = new Request("GET", "/_security/_query/api_key" + (randomBoolean() ? "?typed_keys" : "")); request.setOptions( request.getOptions() .toBuilder() .addHeader(HttpHeaders.AUTHORIZATION, randomFrom(API_KEY_ADMIN_AUTH_HEADER, API_KEY_USER_AUTH_HEADER)) ); request.setJsonEntity(""" { "aggs": { "good-field": { "filters": { "filters": { "good-api-key-invalidated": { "term": {"invalidated": false}} } }, "aggregations": { "wrong-field": { "filters": { "filters": { "wrong-creator-realm": {"wildcard": {"creator.realm": "whatever"}} } } } } } } } """); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(exception.getResponse().toString(), exception.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat(exception.getMessage(), containsString("Field [creator.realm] is not allowed for querying or aggregation")); } } @SuppressWarnings("unchecked") public void testAggsForType() throws IOException { List<String> crossApiKeyIds = new ArrayList<>(); List<String> oldApiKeyIds = new ArrayList<>(); List<String> otherApiKeyIds = new ArrayList<>(); createApiKey("admin-rest-key", Map.of("tags", List.of("prod", "admin", "rest")), API_KEY_ADMIN_AUTH_HEADER); // this is to be mutated to look almost like a cross-cluster API key crossApiKeyIds.add( createApiKey("admin-cross-key", Map.of("tags", List.of("prod", "admin", "cross")), API_KEY_ADMIN_AUTH_HEADER).v1() ); // this is to be mutated to look like an old API key with no type oldApiKeyIds.add(createApiKey("admin-old-key", Map.of("tags", List.of("prod", "admin", "old")), API_KEY_ADMIN_AUTH_HEADER).v1()); // this is to be mutated to look like an unknown type of key otherApiKeyIds.add( createApiKey("admin-other-key", Map.of("tags", List.of("prod", "admin", "other")), API_KEY_ADMIN_AUTH_HEADER).v1() ); createApiKey("user-rest-key", Map.of("tags", List.of("prod", "user", "rest")), API_KEY_USER_AUTH_HEADER); // this is to be mutated to look almost like a cross-cluster API key crossApiKeyIds.add(createApiKey("user-cross-key", Map.of("tags", List.of("prod", "user", "cross")), API_KEY_USER_AUTH_HEADER).v1()); // this is to be mutated to look like an old API key with no type oldApiKeyIds.add(createApiKey("user-old-key", Map.of("tags", List.of("prod", "user", "old")), API_KEY_USER_AUTH_HEADER).v1()); // this is to be mutated to look like an unknown type of key otherApiKeyIds.add(createApiKey("user-other-key", Map.of("tags", List.of("prod", "user", "other")), API_KEY_USER_AUTH_HEADER).v1()); createSystemWriteRole("system_write"); String systemWriteCreds = createUser("superuser_with_system_write", new String[] { "superuser", "system_write" }); // test keys with no "type" field are still considered of type "rest" // this is so in order to accommodate pre-8.9 API keys which where all of type "rest" implicitly updateApiKeys(systemWriteCreds, "ctx._source.remove('type');", oldApiKeyIds); updateApiKeys(systemWriteCreds, "ctx._source['type']='other';", otherApiKeyIds); // hack to make these look like cross_cluster keys, because really creating those requires special setup and different license level updateApiKeys(systemWriteCreds, "ctx._source['type']='cross_cluster';", crossApiKeyIds); boolean isAdmin = randomBoolean(); final boolean typedAggs = randomBoolean(); assertAggs(isAdmin ? API_KEY_ADMIN_AUTH_HEADER : API_KEY_USER_AUTH_HEADER, typedAggs, """ { "size": 0, "aggs": { "all_keys_by_type": { "composite": { "sources": [ { "type": { "terms": { "field": "type" } } } ] } } } } """, aggs -> { String aggName = typedAggs ? "composite#all_keys_by_type" : "all_keys_by_type"; List<Map<String, Object>> buckets = (List<Map<String, Object>>) ((Map<String, Object>) aggs.get(aggName)).get("buckets"); assertThat(buckets.size(), is(3)); assertThat(((Map<String, Object>) buckets.get(0).get("key")).get("type"), is("cross_cluster")); assertThat(((Map<String, Object>) buckets.get(1).get("key")).get("type"), is("other")); assertThat(((Map<String, Object>) buckets.get(2).get("key")).get("type"), is("rest")); if (isAdmin) { assertThat(buckets.get(0).get("doc_count"), is(2)); assertThat(buckets.get(1).get("doc_count"), is(2)); assertThat(buckets.get(2).get("doc_count"), is(4)); // 2 + 2 old ones with no explicit type set } else { assertThat(buckets.get(0).get("doc_count"), is(1)); assertThat(buckets.get(1).get("doc_count"), is(1)); assertThat(buckets.get(2).get("doc_count"), is(2)); // 1 + 1 old ones with no explicit type set } }); assertAggs(isAdmin ? API_KEY_ADMIN_AUTH_HEADER : API_KEY_USER_AUTH_HEADER, typedAggs, """ { "size": 0, "aggs": { "type_cardinality": { "cardinality": { "field": "type" } }, "type_value_count": { "value_count": { "field": "type" } }, "missing_type_count": { "missing": { "field": "type" } }, "type_terms": { "terms": { "field": "type" } } } } """, aggs -> { assertThat(aggs.size(), is(4)); // 3 types assertThat(((Map<String, Object>) aggs.get((typedAggs ? "cardinality#" : "") + "type_cardinality")).get("value"), is(3)); if (isAdmin) { // 8 keys assertThat(((Map<String, Object>) aggs.get((typedAggs ? "value_count#" : "") + "type_value_count")).get("value"), is(8)); } else { // 4 keys assertThat(((Map<String, Object>) aggs.get((typedAggs ? "value_count#" : "") + "type_value_count")).get("value"), is(4)); } assertThat(((Map<String, Object>) aggs.get((typedAggs ? "missing#" : "") + "missing_type_count")).get("doc_count"), is(0)); List<Map<String, Object>> typeTermsBuckets = (List<Map<String, Object>>) ((Map<String, Object>) aggs.get( (typedAggs ? "sterms#" : "") + "type_terms" )).get("buckets"); assertThat(typeTermsBuckets.size(), is(3)); }); // runtime type field is disallowed { Request request = new Request("GET", "/_security/_query/api_key" + (typedAggs ? "?typed_keys" : "")); request.setOptions( request.getOptions() .toBuilder() .addHeader(HttpHeaders.AUTHORIZATION, randomFrom(API_KEY_ADMIN_AUTH_HEADER, API_KEY_USER_AUTH_HEADER)) ); request.setJsonEntity(""" { "aggs": { "type_value_count": { "value_count": { "field": "runtime_key_type" } } } } """); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(exception.getResponse().toString(), exception.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat(exception.getMessage(), containsString("Field [runtime_key_type] is not allowed for querying or aggregation")); } } @SuppressWarnings("unchecked") public void testFilterAggs() throws IOException { String user1Creds = createUser("test-user-1", new String[] { "api_key_user_role" }); String user2Creds = createUser("test-user-2", new String[] { "api_key_user_role" }); String user3Creds = createUser("test-user-3", new String[] { "api_key_user_role" }); // create 6 keys for 3 users (2 keys each, one granted) grantApiKey("key-1-user-1", "10d", Map.of("labels", List.of("grant", "1", "10d")), API_KEY_ADMIN_AUTH_HEADER, "test-user-1").v1(); String key2User1KeyId = createApiKey("key-2-user-1", "20d", null, Map.of("labels", List.of("2", "20d")), user1Creds).v1(); grantApiKey("key-1-user-2", "30d", Map.of("labels", List.of("grant", "1", "30d")), API_KEY_ADMIN_AUTH_HEADER, "test-user-2").v1(); createApiKey("key-2-user-2", "40d", null, Map.of("labels", List.of("2", "40d")), user2Creds).v1(); String key1User3KeyId = grantApiKey( "key-1-user-3", "50d", Map.of("labels", List.of("grant", "1", "50d")), API_KEY_ADMIN_AUTH_HEADER, "test-user-3" ).v1(); createApiKey("key-2-user-3", "60d", null, Map.of("labels", List.of("2", "60d")), user3Creds).v1(); // invalidate some two keys invalidateApiKey(key2User1KeyId, false, API_KEY_ADMIN_AUTH_HEADER); invalidateApiKey(key1User3KeyId, false, API_KEY_ADMIN_AUTH_HEADER); final boolean typedAggs = randomBoolean(); assertAggs(API_KEY_ADMIN_AUTH_HEADER, typedAggs, """ { "size": 0, "aggs": { "not_invalidated": { "filter": { "term": { "invalidated": false } }, "aggs": { "keys_by_username": { "composite": { "sources": [ { "usernames": { "terms": { "field": "username" } } } ] } } } } } } """, aggs -> { // 6 - 2 (invalidated) assertThat(((Map<String, Object>) aggs.get(typedAggs ? "filter#not_invalidated" : "not_invalidated")).get("doc_count"), is(4)); List<Map<String, Object>> buckets = (List<Map<String, Object>>) ((Map<String, Object>) ((Map<String, Object>) aggs.get( typedAggs ? "filter#not_invalidated" : "not_invalidated" )).get(typedAggs ? "composite#keys_by_username" : "keys_by_username")).get("buckets"); assertThat(buckets.size(), is(3)); assertThat(((Map<String, Object>) buckets.get(0).get("key")).get("usernames"), is("test-user-1")); assertThat(buckets.get(0).get("doc_count"), is(1)); assertThat(((Map<String, Object>) buckets.get(1).get("key")).get("usernames"), is("test-user-2")); assertThat(buckets.get(1).get("doc_count"), is(2)); assertThat(((Map<String, Object>) buckets.get(2).get("key")).get("usernames"), is("test-user-3")); assertThat(buckets.get(2).get("doc_count"), is(1)); }); assertAggs(API_KEY_ADMIN_AUTH_HEADER, typedAggs, """ { "aggs": { "keys_by_username": { "composite": { "sources": [ { "usernames": { "terms": { "field": "username" } } } ] }, "aggregations": { "not_expired": { "filter": { "range": { "expiration": { "gte": "now+35d/d" } } } } } } } } """, aggs -> { List<Map<String, Object>> buckets = (List<Map<String, Object>>) ((Map<String, Object>) aggs.get( typedAggs ? "composite#keys_by_username" : "keys_by_username" )).get("buckets"); assertThat(buckets.size(), is(3)); assertThat(buckets.get(0).get("doc_count"), is(2)); assertThat(((Map<String, Object>) buckets.get(0).get("key")).get("usernames"), is("test-user-1")); assertThat( ((Map<String, Object>) buckets.get(0).get(typedAggs ? "filter#not_expired" : "not_expired")).get("doc_count"), is(0) ); assertThat(buckets.get(1).get("doc_count"), is(2)); assertThat(((Map<String, Object>) buckets.get(1).get("key")).get("usernames"), is("test-user-2")); assertThat( ((Map<String, Object>) buckets.get(1).get(typedAggs ? "filter#not_expired" : "not_expired")).get("doc_count"), is(1) ); assertThat(buckets.get(2).get("doc_count"), is(2)); assertThat(((Map<String, Object>) buckets.get(2).get("key")).get("usernames"), is("test-user-3")); assertThat( ((Map<String, Object>) buckets.get(2).get(typedAggs ? "filter#not_expired" : "not_expired")).get("doc_count"), is(2) ); }); // "creator" field is disallowed { Request request = new Request("GET", "/_security/_query/api_key" + (typedAggs ? "?typed_keys" : "?typed_keys=false")); request.setOptions( request.getOptions() .toBuilder() .addHeader(HttpHeaders.AUTHORIZATION, randomFrom(API_KEY_ADMIN_AUTH_HEADER, API_KEY_USER_AUTH_HEADER)) ); request.setJsonEntity(""" { "aggs": { "keys_by_username": { "composite": { "sources": [ { "usernames": { "terms": { "field": "username" } } }, { "histo": { "histogram": { "field": "creator", "interval": 5 } } } ] } } } } """); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(exception.getResponse().toString(), exception.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat(exception.getMessage(), containsString("Field [creator] is not allowed for querying or aggregation")); } } public void testDisallowedAggTypes() { // global aggregation type MUST never be allowed in order to not expose non-owned non-API key docs { Request request = new Request("GET", "/_security/_query/api_key" + (randomBoolean() ? "?typed_keys=true" : "")); request.setOptions( request.getOptions() .toBuilder() .addHeader(HttpHeaders.AUTHORIZATION, randomFrom(API_KEY_ADMIN_AUTH_HEADER, API_KEY_USER_AUTH_HEADER)) ); request.setJsonEntity(""" { "aggregations": { "all_.security_docs": { "global": {}, "aggs": { "key_names": { "terms": { "field": "name" } } } } } } """); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(exception.getResponse().toString(), exception.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat(exception.getMessage(), containsString("Unsupported API Keys agg [all_.security_docs] of type [global]")); } // pipeline aggs are not allowed but could be if there's an identified use-case { Request request = new Request("GET", "/_security/_query/api_key" + (randomBoolean() ? "?typed_keys=true" : "")); request.setOptions( request.getOptions() .toBuilder() .addHeader(HttpHeaders.AUTHORIZATION, randomFrom(API_KEY_ADMIN_AUTH_HEADER, API_KEY_USER_AUTH_HEADER)) ); request.setJsonEntity(""" { "aggs": { "type_cardinality": { "cardinality": { "field": "type" } }, "total_type_cardinality": { "cumulative_cardinality": { "buckets_path": "type_cardinality" } } } } """); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(exception.getResponse().toString(), exception.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat(exception.getMessage(), containsString("Unsupported aggregation of type [cumulative_cardinality]")); } } void assertAggs(String authHeader, boolean typedAggs, String body, Consumer<Map<String, Object>> aggsVerifier) throws IOException { final Request request = new Request( "GET", "/_security/_query/api_key" + (typedAggs ? randomFrom("?typed_keys", "?typed_keys=true") : randomFrom("", "?typed_keys=false")) ); request.setJsonEntity(body); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, authHeader)); final Response response = client().performRequest(request); assertOK(response); final Map<String, Object> responseMap = responseAsMap(response); @SuppressWarnings("unchecked") final Map<String, Object> aggs = (Map<String, Object>) responseMap.get("aggregations"); aggsVerifier.accept(aggs); } }
ApiKeyAggsIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/boot/cfgXml/CfgXmlResourceNameClosingTest.java
{ "start": 2573, "end": 3044 }
class ____ extends InputStream { private final InputStream wrapped; private boolean wasClosed = false; public InputStreamWrapper(InputStream wrapped) { this.wrapped = wrapped; } @Override public int read() throws IOException { return wrapped.read(); } @Override public void close() throws IOException { wrapped.close(); wasClosed = true; super.close(); } public boolean wasClosed() { return wasClosed; } } }
InputStreamWrapper
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/hint/AbstractTypeReference.java
{ "start": 1015, "end": 2664 }
class ____ implements TypeReference { private final String packageName; private final String simpleName; private final @Nullable TypeReference enclosingType; protected AbstractTypeReference(String packageName, String simpleName, @Nullable TypeReference enclosingType) { this.packageName = packageName; this.simpleName = simpleName; this.enclosingType = enclosingType; } @Override public String getName() { TypeReference enclosingType = getEnclosingType(); String simpleName = getSimpleName(); return (enclosingType != null ? (enclosingType.getName() + '$' + simpleName) : addPackageIfNecessary(simpleName)); } @Override public String getPackageName() { return this.packageName; } @Override public String getSimpleName() { return this.simpleName; } @Override public @Nullable TypeReference getEnclosingType() { return this.enclosingType; } protected String addPackageIfNecessary(String part) { if (this.packageName.isEmpty() || (this.packageName.equals("java.lang") && isPrimitive())) { return part; } return this.packageName + '.' + part; } protected abstract boolean isPrimitive(); @Override public int compareTo(TypeReference other) { return getCanonicalName().compareToIgnoreCase(other.getCanonicalName()); } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof TypeReference that && getCanonicalName().equals(that.getCanonicalName()))); } @Override public int hashCode() { return Objects.hash(getCanonicalName()); } @Override public String toString() { return getCanonicalName(); } }
AbstractTypeReference
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1665/Target.java
{ "start": 280, "end": 483 }
class ____ { private List<Integer> value = new ArrayList<>(); public void addValue(int v) { value.add( v ); } public List<Integer> getValue() { return value; } }
Target
java
google__gson
gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java
{ "start": 1023, "end": 4310 }
class ____ { private static TimeZone utcTimeZone() { return TimeZone.getTimeZone("UTC"); } private static GregorianCalendar createUtcCalendar() { TimeZone utc = utcTimeZone(); GregorianCalendar calendar = new GregorianCalendar(utc); // Calendar was created with current time, must clear it calendar.clear(); return calendar; } @Test public void testDateFormatString() { GregorianCalendar calendar = new GregorianCalendar(utcTimeZone(), Locale.US); // Calendar was created with current time, must clear it calendar.clear(); calendar.set(2018, Calendar.JUNE, 25); Date date = calendar.getTime(); String dateStr = ISO8601Utils.format(date); String expectedDate = "2018-06-25T00:00:00Z"; assertThat(dateStr).isEqualTo(expectedDate); } @Test @SuppressWarnings("JavaUtilDate") public void testDateFormatWithMilliseconds() { long time = 1530209176870L; Date date = new Date(time); String dateStr = ISO8601Utils.format(date, true); String expectedDate = "2018-06-28T18:06:16.870Z"; assertThat(dateStr).isEqualTo(expectedDate); } @Test @SuppressWarnings("JavaUtilDate") public void testDateFormatWithTimezone() { long time = 1530209176870L; Date date = new Date(time); String dateStr = ISO8601Utils.format(date, true, TimeZone.getTimeZone("Brazil/East")); String expectedDate = "2018-06-28T15:06:16.870-03:00"; assertThat(dateStr).isEqualTo(expectedDate); } @Test @SuppressWarnings("UndefinedEquals") public void testDateParseWithDefaultTimezone() throws ParseException { String dateStr = "2018-06-25"; Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0)); Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime(); assertThat(date).isEqualTo(expectedDate); } @Test public void testDateParseInvalidDay() { String dateStr = "2022-12-33"; assertThrows(ParseException.class, () -> ISO8601Utils.parse(dateStr, new ParsePosition(0))); } @Test public void testDateParseInvalidMonth() { String dateStr = "2022-14-30"; assertThrows(ParseException.class, () -> ISO8601Utils.parse(dateStr, new ParsePosition(0))); } @Test @SuppressWarnings("UndefinedEquals") public void testDateParseWithTimezone() throws ParseException { String dateStr = "2018-06-25T00:00:00-03:00"; Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0)); GregorianCalendar calendar = createUtcCalendar(); calendar.set(2018, Calendar.JUNE, 25, 3, 0); Date expectedDate = calendar.getTime(); assertThat(date).isEqualTo(expectedDate); } @Test @SuppressWarnings("UndefinedEquals") public void testDateParseSpecialTimezone() throws ParseException { String dateStr = "2018-06-25T00:02:00-02:58"; Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0)); GregorianCalendar calendar = createUtcCalendar(); calendar.set(2018, Calendar.JUNE, 25, 3, 0); Date expectedDate = calendar.getTime(); assertThat(date).isEqualTo(expectedDate); } @Test public void testDateParseInvalidTime() { String dateStr = "2018-06-25T61:60:62-03:00"; assertThrows(ParseException.class, () -> ISO8601Utils.parse(dateStr, new ParsePosition(0))); } }
ISO8601UtilsTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/api/records/TestTaskAttemptReport.java
{ "start": 3066, "end": 3419 }
class ____ report = Records.newRecord(TaskAttemptReport.class); // Set raw counters to null report.setRawCounters(null); // Verify properties still null assertThat(report.getCounters()).isNull(); assertThat(report.getRawCounters()).isNull(); } @Test public void testSetCountersToNull() { // Create basic
TaskAttemptReport
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java
{ "start": 23309, "end": 23596 }
class ____ { @Bean VoidDeleteResponseEndpoint voidDeleteResponseEndpoint(EndpointDelegate delegate) { return new VoidDeleteResponseEndpoint(delegate); } } @Configuration(proxyBeanMethods = false) @Import(BaseConfiguration.class) static
VoidDeleteResponseEndpointConfiguration
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/persistence/RetrievableStateStorageHelper.java
{ "start": 1190, "end": 1567 }
interface ____<T extends Serializable> { /** * Stores the given state and returns a state handle to it. * * @param state State to be stored * @return State handle to the stored state * @throws Exception if an error occurred while storing the state. */ RetrievableStateHandle<T> store(T state) throws Exception; }
RetrievableStateStorageHelper
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/util/TopicCreation.java
{ "start": 1284, "end": 5680 }
class ____ { private static final TopicCreation EMPTY = new TopicCreation(false, null, Map.of(), Set.of()); private final boolean isTopicCreationEnabled; private final TopicCreationGroup defaultTopicGroup; private final Map<String, TopicCreationGroup> topicGroups; private final Set<String> topicCache; protected TopicCreation(boolean isTopicCreationEnabled, TopicCreationGroup defaultTopicGroup, Map<String, TopicCreationGroup> topicGroups, Set<String> topicCache) { this.isTopicCreationEnabled = isTopicCreationEnabled; this.defaultTopicGroup = defaultTopicGroup; this.topicGroups = topicGroups; this.topicCache = topicCache; } public static TopicCreation newTopicCreation(WorkerConfig workerConfig, Map<String, TopicCreationGroup> topicGroups) { if (!workerConfig.topicCreationEnable() || topicGroups == null) { return EMPTY; } Map<String, TopicCreationGroup> groups = new LinkedHashMap<>(topicGroups); groups.remove(DEFAULT_TOPIC_CREATION_GROUP); return new TopicCreation(true, topicGroups.get(DEFAULT_TOPIC_CREATION_GROUP), groups, new HashSet<>()); } /** * Return an instance of this utility that represents what the state of the internal data * structures should be when topic creation is disabled. * * @return the utility when topic creation is disabled */ public static TopicCreation empty() { return EMPTY; } /** * Check whether topic creation is enabled for this utility instance. This state is set at * instantiation time and remains unchanged for the lifetime of every {@link TopicCreation} * object. * * @return true if topic creation is enabled; false otherwise */ public boolean isTopicCreationEnabled() { return isTopicCreationEnabled; } /** * Check whether topic creation may be required for a specific topic name. * * @return true if topic creation is enabled and the topic name is not in the topic cache; * false otherwise */ public boolean isTopicCreationRequired(String topic) { return isTopicCreationEnabled && !topicCache.contains(topic); } /** * Return the default topic creation group. This group is always defined when topic creation is * enabled but is {@code null} if topic creation is disabled. * * @return the default topic creation group if topic creation is enabled; {@code null} otherwise */ public TopicCreationGroup defaultTopicGroup() { return defaultTopicGroup; } /** * Return the topic creation groups defined for a source connector as a map of topic creation * group name to topic creation group instance. This map maintains all the optionally defined * groups besides the default group which is defined for any connector when topic creation is * enabled. * * @return the map of all the topic creation groups besides the default group; may be empty * but not {@code null} */ public Map<String, TopicCreationGroup> topicGroups() { return topicGroups; } /** * Inform this utility instance that a topic has been created and its creation will no * longer be required. After this method is called for a given {@code topic}, * any subsequent calls to {@link #isTopicCreationRequired} will return {@code false} for the * same topic. * * @param topic the topic name to mark as created */ public void addTopic(String topic) { if (isTopicCreationEnabled) { topicCache.add(topic); } } /** * Get the first topic creation group that is configured to match the given {@code topic} * name. If topic creation is enabled, any topic should match at least the default topic * creation group. * * @param topic the topic name to match against group configurations * * @return the first group that matches the given topic */ public TopicCreationGroup findFirstGroup(String topic) { return topicGroups.values().stream() .filter(group -> group.matches(topic)) .findFirst() .orElse(defaultTopicGroup); } }
TopicCreation
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/blink/parser/BlinkLexer.java
{ "start": 329, "end": 1344 }
class ____ extends Lexer { static final Keywords BLINK_KEYWORDS; static { Map<String, Token> map = new HashMap<>(); map.putAll(Keywords.DEFAULT_KEYWORDS.getKeywords()); map.put("OF", Token.OF); map.put("CONCAT", Token.CONCAT); map.put("CONTINUE", Token.CONTINUE); map.put("MERGE", Token.MERGE); map.put("USING", Token.USING); map.put("ROW", Token.ROW); map.put("LIMIT", Token.LIMIT); map.put("IF", Token.IF); map.put("PERIOD", Token.PERIOD); BLINK_KEYWORDS = new Keywords(map); } @Override protected Keywords loadKeywords() { return BLINK_KEYWORDS; } public BlinkLexer(String input) { super(input); dbType = DbType.blink; } public BlinkLexer(String input, SQLParserFeature... features) { super(input); dbType = DbType.blink; for (SQLParserFeature feature : features) { config(feature, true); } } }
BlinkLexer
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KTableAggregateTest.java
{ "start": 2951, "end": 19041 }
class ____ { private final Serde<String> stringSerde = Serdes.String(); private final Consumed<String, String> consumed = Consumed.with(stringSerde, stringSerde); private final Grouped<String, String> stringSerialized = Grouped.with(stringSerde, stringSerde); private final MockApiProcessorSupplier<String, Object, Void, Void> supplier = new MockApiProcessorSupplier<>(); private static final Properties CONFIG = mkProperties(mkMap( mkEntry(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory("kafka-test").getAbsolutePath()))); @Test public void testAggBasic() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; final KTable<String, String> table1 = builder.table(topic1, consumed); final KTable<String, String> table2 = table1 .groupBy( MockMapper.noOpKeyValueMapper(), stringSerialized) .aggregate( MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, MockAggregator.TOSTRING_REMOVER, Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("topic1-Canonized") .withValueSerde(stringSerde)); table2.toStream().process(supplier); try ( final TopologyTestDriver driver = new TopologyTestDriver( builder.build(), CONFIG, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(topic1, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); inputTopic.pipeInput("A", "1", 10L); inputTopic.pipeInput("B", "2", 15L); inputTopic.pipeInput("A", "3", 20L); inputTopic.pipeInput("B", "4", 18L); inputTopic.pipeInput("C", "5", 5L); inputTopic.pipeInput("D", "6", 25L); inputTopic.pipeInput("B", "7", 15L); inputTopic.pipeInput("C", "8", 10L); assertEquals( asList( new KeyValueTimestamp<>("A", "0+1", 10L), new KeyValueTimestamp<>("B", "0+2", 15L), new KeyValueTimestamp<>("A", "0+1-1+3", 20L), new KeyValueTimestamp<>("B", "0+2-2+4", 18L), new KeyValueTimestamp<>("C", "0+5", 5L), new KeyValueTimestamp<>("D", "0+6", 25L), new KeyValueTimestamp<>("B", "0+2-2+4-4+7", 18L), new KeyValueTimestamp<>("C", "0+5-5+8", 10L)), supplier.theCapturedProcessor().processed()); } } @Test public void testAggRepartition() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; final KTable<String, String> table1 = builder.table(topic1, consumed); final KTable<String, String> table2 = table1 .groupBy( (key, value) -> { switch (key) { case "null": return KeyValue.pair(null, value); case "NULL": return null; default: return KeyValue.pair(value, value); } }, stringSerialized) .aggregate( MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, MockAggregator.TOSTRING_REMOVER, Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("topic1-Canonized") .withValueSerde(stringSerde)); table2.toStream().process(supplier); try ( final TopologyTestDriver driver = new TopologyTestDriver( builder.build(), CONFIG, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(topic1, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); inputTopic.pipeInput("A", "1", 10L); inputTopic.pipeInput("A", (String) null, 15L); inputTopic.pipeInput("A", "1", 12L); inputTopic.pipeInput("B", "2", 20L); inputTopic.pipeInput("null", "3", 25L); inputTopic.pipeInput("B", "4", 23L); inputTopic.pipeInput("NULL", "5", 24L); inputTopic.pipeInput("B", "7", 22L); assertEquals( asList( new KeyValueTimestamp<>("1", "0+1", 10), new KeyValueTimestamp<>("1", "0+1-1", 15), new KeyValueTimestamp<>("1", "0+1-1+1", 15), new KeyValueTimestamp<>("2", "0+2", 20), new KeyValueTimestamp<>("2", "0+2-2", 23), new KeyValueTimestamp<>("4", "0+4", 23), new KeyValueTimestamp<>("4", "0+4-4", 23), new KeyValueTimestamp<>("7", "0+7", 22)), supplier.theCapturedProcessor().processed()); } } @Test public void testAggOfVersionedStore() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; final Materialized<String, String, KeyValueStore<Bytes, byte[]>> versionedMaterialize = Materialized.as(Stores.persistentVersionedKeyValueStore("versioned", Duration.ofMinutes(5))); final KTable<String, String> table1 = builder.table(topic1, consumed, versionedMaterialize); final KTable<String, String> table2 = table1 .groupBy( (key, value) -> { switch (key) { case "null": return KeyValue.pair(null, value); case "NULL": return null; default: return KeyValue.pair(value, value); } }, stringSerialized) .aggregate( MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, MockAggregator.TOSTRING_REMOVER, Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("topic1-Canonized") .withValueSerde(stringSerde)); table2.toStream().process(supplier); try ( final TopologyTestDriver driver = new TopologyTestDriver( builder.build(), CONFIG, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(topic1, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); inputTopic.pipeInput("A", "1", 10L); inputTopic.pipeInput("A", (String) null, 15L); inputTopic.pipeInput("A", "1", 12L); // out-of-order record will be ignored inputTopic.pipeInput("B", "2", 20L); inputTopic.pipeInput("null", "3", 25L); inputTopic.pipeInput("B", "4", 23L); inputTopic.pipeInput("NULL", "5", 24L); inputTopic.pipeInput("B", "7", 22L); // out-of-order record will be ignored assertEquals( asList( new KeyValueTimestamp<>("1", "0+1", 10), new KeyValueTimestamp<>("1", "0+1-1", 15), new KeyValueTimestamp<>("2", "0+2", 20), new KeyValueTimestamp<>("2", "0+2-2", 23), new KeyValueTimestamp<>("4", "0+4", 23)), supplier.theCapturedProcessor().processed()); } } private static void testCountHelper(final StreamsBuilder builder, final String input, final MockApiProcessorSupplier<String, Object, Void, Void> supplier) { try ( final TopologyTestDriver driver = new TopologyTestDriver( builder.build(), CONFIG, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(input, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); inputTopic.pipeInput("A", "green", 10L); inputTopic.pipeInput("B", "green", 9L); inputTopic.pipeInput("A", "blue", 12L); inputTopic.pipeInput("C", "yellow", 15L); inputTopic.pipeInput("D", "green", 11L); assertEquals( asList( new KeyValueTimestamp<>("green", 1L, 10), new KeyValueTimestamp<>("green", 2L, 10), new KeyValueTimestamp<>("green", 1L, 12), new KeyValueTimestamp<>("blue", 1L, 12), new KeyValueTimestamp<>("yellow", 1L, 15), new KeyValueTimestamp<>("green", 2L, 12)), supplier.theCapturedProcessor().processed()); } } @Test public void testCount() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; builder .table(input, consumed) .groupBy(MockMapper.selectValueKeyValueMapper(), stringSerialized) .count(Materialized.as("count")) .toStream() .process(supplier); testCountHelper(builder, input, supplier); } @Test public void testCountWithInternalStore() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; builder .table(input, consumed) .groupBy(MockMapper.selectValueKeyValueMapper(), stringSerialized) .count() .toStream() .process(supplier); testCountHelper(builder, input, supplier); } @Test public void testCountOfVersionedStore() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; final Materialized<String, String, KeyValueStore<Bytes, byte[]>> versionedMaterialize = Materialized.as(Stores.persistentVersionedKeyValueStore("versioned", Duration.ofMinutes(5))); builder .table(input, consumed, versionedMaterialize) .groupBy(MockMapper.selectValueKeyValueMapper(), stringSerialized) .count() .toStream() .process(supplier); try ( final TopologyTestDriver driver = new TopologyTestDriver( builder.build(), CONFIG, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(input, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); inputTopic.pipeInput("A", "green", 10L); inputTopic.pipeInput("B", "green", 9L); inputTopic.pipeInput("A", "blue", 12L); inputTopic.pipeInput("A", "blue", 11L); // out-of-order record will be ignored inputTopic.pipeInput("C", "yellow", 15L); inputTopic.pipeInput("D", "green", 11L); assertEquals( asList( new KeyValueTimestamp<>("green", 1L, 10), new KeyValueTimestamp<>("green", 2L, 10), new KeyValueTimestamp<>("green", 1L, 12), new KeyValueTimestamp<>("blue", 1L, 12), new KeyValueTimestamp<>("yellow", 1L, 15), new KeyValueTimestamp<>("green", 2L, 12)), supplier.theCapturedProcessor().processed()); } } @Test public void testRemoveOldBeforeAddNew() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; final MockApiProcessorSupplier<String, String, Void, Void> supplier = new MockApiProcessorSupplier<>(); builder .table(input, consumed) .groupBy( (key, value) -> KeyValue.pair( String.valueOf(key.charAt(0)), String.valueOf(key.charAt(1))), stringSerialized) .aggregate( () -> "", (aggKey, value, aggregate) -> aggregate + value, (key, value, aggregate) -> aggregate.replaceAll(value, ""), Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("someStore") .withValueSerde(Serdes.String())) .toStream() .process(supplier); try ( final TopologyTestDriver driver = new TopologyTestDriver( builder.build(), CONFIG, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(input, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); final MockApiProcessor<String, String, Void, Void> proc = supplier.theCapturedProcessor(); inputTopic.pipeInput("11", "A", 10L); inputTopic.pipeInput("12", "B", 8L); inputTopic.pipeInput("11", (String) null, 12L); inputTopic.pipeInput("12", "C", 6L); assertEquals( asList( new KeyValueTimestamp<>("1", "1", 10), new KeyValueTimestamp<>("1", "12", 10), new KeyValueTimestamp<>("1", "2", 12), new KeyValueTimestamp<>("1", "2", 12L) ), proc.processed() ); } } private void testUpgradeFromConfig(final Properties config, final List<KeyValueTimestamp<String, Long>> expected) { final StreamsBuilder builder = new StreamsBuilder(); final String input = "input-topic"; final String output = "output-topic"; final Serde<String> stringSerde = Serdes.String(); builder .table(input, Consumed.with(stringSerde, stringSerde)) // key is not changed .groupBy(KeyValue::pair, Grouped.with(stringSerde, stringSerde)) .count() .toStream() .to(output); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), config, Instant.ofEpochMilli(0L))) { final TestInputTopic<String, String> inputTopic = driver.createInputTopic(input, new StringSerializer(), new StringSerializer(), Instant.ofEpochMilli(0L), Duration.ZERO); final TestOutputTopic<String, Long> outputTopic = driver.createOutputTopic(output, new StringDeserializer(), new LongDeserializer()); inputTopic.pipeInput("1", "", 8L); inputTopic.pipeInput("1", "", 9L); final List<KeyValueTimestamp<String, Long>> actual = new ArrayList<>(); outputTopic.readRecordsToList().forEach(tr -> actual.add(new KeyValueTimestamp<>(tr.key(), tr.value(), tr.timestamp()))); assertEquals(expected, actual); } } @Test public void testShouldSendTransientStateWhenUpgrading() { final Properties upgradingConfig = new Properties(); upgradingConfig.putAll(CONFIG); upgradingConfig.put(StreamsConfig.UPGRADE_FROM_CONFIG, StreamsConfig.UPGRADE_FROM_33); testUpgradeFromConfig(upgradingConfig, asList( new KeyValueTimestamp<>("1", 1L, 8), new KeyValueTimestamp<>("1", 0L, 9), // transient inconsistent state new KeyValueTimestamp<>("1", 1L, 9) )); } @Test public void testShouldNotSendTransientStateIfNotUpgrading() { testUpgradeFromConfig(CONFIG, asList( new KeyValueTimestamp<>("1", 1L, 8), new KeyValueTimestamp<>("1", 1L, 9) )); } private static
KTableAggregateTest
java
apache__camel
components/camel-pgevent/src/main/java/org/apache/camel/component/pgevent/PgEventConstants.java
{ "start": 900, "end": 1125 }
class ____ { @Metadata(label = "consumer", description = "The name of the channel.", javaType = "String") public static final String HEADER_CHANNEL = "channel"; private PgEventConstants() { } }
PgEventConstants
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/resourceplugin/com/nvidia/TestNvidiaGPUPluginForRuntimeV2.java
{ "start": 2343, "end": 29465 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestNvidiaGPUPluginForRuntimeV2.class); @Test public void testGetNvidiaDevices() throws Exception { NvidiaGPUPluginForRuntimeV2.NvidiaCommandExecutor mockShell = mock(NvidiaGPUPluginForRuntimeV2.NvidiaCommandExecutor.class); String deviceInfoShellOutput = "0, 00000000:04:00.0\n" + "1, 00000000:82:00.0"; String majorMinorNumber0 = "c3:0"; String majorMinorNumber1 = "c3:1"; when(mockShell.getDeviceInfo()).thenReturn(deviceInfoShellOutput); when(mockShell.getMajorMinorInfo("nvidia0")) .thenReturn(majorMinorNumber0); when(mockShell.getMajorMinorInfo("nvidia1")) .thenReturn(majorMinorNumber1); NvidiaGPUPluginForRuntimeV2 plugin = new NvidiaGPUPluginForRuntimeV2(); plugin.setShellExecutor(mockShell); plugin.setPathOfGpuBinary("/fake/nvidia-smi"); Set<Device> expectedDevices = new TreeSet<>(); expectedDevices.add(Device.Builder.newInstance() .setId(0).setHealthy(true) .setBusID("00000000:04:00.0") .setDevPath("/dev/nvidia0") .setMajorNumber(195) .setMinorNumber(0).build()); expectedDevices.add(Device.Builder.newInstance() .setId(1).setHealthy(true) .setBusID("00000000:82:00.0") .setDevPath("/dev/nvidia1") .setMajorNumber(195) .setMinorNumber(1).build()); Set<Device> devices = plugin.getDevices(); assertEquals(expectedDevices, devices); } @Test public void testOnDeviceAllocated() throws Exception { NvidiaGPUPluginForRuntimeV2 plugin = new NvidiaGPUPluginForRuntimeV2(); Set<Device> allocatedDevices = new TreeSet<>(); DeviceRuntimeSpec spec = plugin.onDevicesAllocated(allocatedDevices, YarnRuntimeType.RUNTIME_DEFAULT); assertNull(spec); // allocate one device allocatedDevices.add(Device.Builder.newInstance() .setId(0).setHealthy(true) .setBusID("00000000:04:00.0") .setDevPath("/dev/nvidia0") .setMajorNumber(195) .setMinorNumber(0).build()); spec = plugin.onDevicesAllocated(allocatedDevices, YarnRuntimeType.RUNTIME_DOCKER); assertEquals("nvidia", spec.getContainerRuntime()); assertEquals("0", spec.getEnvs().get("NVIDIA_VISIBLE_DEVICES")); // two device allowed allocatedDevices.add(Device.Builder.newInstance() .setId(0).setHealthy(true) .setBusID("00000000:82:00.0") .setDevPath("/dev/nvidia1") .setMajorNumber(195) .setMinorNumber(1).build()); spec = plugin.onDevicesAllocated(allocatedDevices, YarnRuntimeType.RUNTIME_DOCKER); assertEquals("nvidia", spec.getContainerRuntime()); assertEquals("0,1", spec.getEnvs().get("NVIDIA_VISIBLE_DEVICES")); } private NvidiaGPUPluginForRuntimeV2 mockEightGPUPlugin() throws IOException { String topoInfo = "\tGPU0\tGPU1\tGPU2\tGPU3\tGPU4\tGPU5\tGPU6\tGPU7\tCPU Affinity\n" + "GPU0\t X \tNV1\tNV1\tNV2\tNV2\tPHB\tPHB\tPHB\t0-63\n" + "GPU1\tNV1\t X \tNV2\tNV1\tPHB\tNV2\tPHB\tPHB\t0-63\n" + "GPU2\tNV1\tNV2\t X \tNV2\tPHB\tPHB\tNV1\tPHB\t0-63\n" + "GPU3\tNV2\tNV1\tNV2\t X \tPHB\tPHB\tPHB\tNV1\t0-63\n" + "GPU4\tNV2\tPHB\tPHB\tPHB\t X \tNV1\tNV1\tNV2\t0-63\n" + "GPU5\tPHB\tNV2\tPHB\tPHB\tNV1\t X \tNV2\tNV1\t0-63\n" + "GPU6\tPHB\tPHB\tNV1\tPHB\tNV1\tNV2\t X \tNV2\t0-63\n" + "GPU7\tPHB\tPHB\tPHB\tNV1\tNV2\tNV1\tNV2\t X \t0-63\n" + "\n" + "Legend:\n" + "\n" + " X = Self\n" + " SYS = Connection traversing PCIe as well as the SMP interconnect" + " between NUMA nodes (e.g., QPI/UPI)\n" + " NODE = Connection traversing PCIe as well as the interconnect" + " between PCIe Host Bridges within a NUMA node\n" + " PHB = Connection traversing PCIe as well as a PCIe Host Bridge" + " (typically the CPU)\n" + " PXB = Connection traversing multiple PCIe switches" + " (without traversing the PCIe Host Bridge)\n" + " PIX = Connection traversing a single PCIe switch\n" + " NV# = Connection traversing a bonded set of # NVLinks\n"; String deviceInfoShellOutput = "0, 00000000:04:00.0\n" + "1, 00000000:82:00.0\n" + "2, 00000000:83:00.0\n" + "3, 00000000:84:00.0\n" + "4, 00000000:85:00.0\n" + "5, 00000000:86:00.0\n" + "6, 00000000:87:00.0\n" + "7, 00000000:88:00.0"; String majorMinorNumber0 = "c3:0"; String majorMinorNumber1 = "c3:1"; String majorMinorNumber2 = "c3:2"; String majorMinorNumber3 = "c3:3"; String majorMinorNumber4 = "c3:4"; String majorMinorNumber5 = "c3:5"; String majorMinorNumber6 = "c3:6"; String majorMinorNumber7 = "c3:7"; NvidiaGPUPluginForRuntimeV2.NvidiaCommandExecutor mockShell = mock(NvidiaGPUPluginForRuntimeV2.NvidiaCommandExecutor.class); when(mockShell.getDeviceInfo()).thenReturn(deviceInfoShellOutput); when(mockShell.getMajorMinorInfo("nvidia0")) .thenReturn(majorMinorNumber0); when(mockShell.getMajorMinorInfo("nvidia1")) .thenReturn(majorMinorNumber1); when(mockShell.getMajorMinorInfo("nvidia2")) .thenReturn(majorMinorNumber2); when(mockShell.getMajorMinorInfo("nvidia3")) .thenReturn(majorMinorNumber3); when(mockShell.getMajorMinorInfo("nvidia4")) .thenReturn(majorMinorNumber4); when(mockShell.getMajorMinorInfo("nvidia5")) .thenReturn(majorMinorNumber5); when(mockShell.getMajorMinorInfo("nvidia6")) .thenReturn(majorMinorNumber6); when(mockShell.getMajorMinorInfo("nvidia7")) .thenReturn(majorMinorNumber7); when(mockShell.getTopologyInfo()).thenReturn(topoInfo); when(mockShell.getDeviceInfo()).thenReturn(deviceInfoShellOutput); NvidiaGPUPluginForRuntimeV2 plugin = new NvidiaGPUPluginForRuntimeV2(); plugin.setShellExecutor(mockShell); plugin.setPathOfGpuBinary("/fake/nvidia-smi"); return plugin; } private NvidiaGPUPluginForRuntimeV2 mockFourGPUPlugin() throws IOException { String topoInfo = "\tGPU0\tGPU1\tGPU2\tGPU3\tCPU Affinity\n" + "GPU0\t X \tPHB\tSOC\tSOC\t0-31\n" + "GPU1\tPHB\t X \tSOC\tSOC\t0-31\n" + "GPU2\tSOC\tSOC\t X \tPHB\t0-31\n" + "GPU3\tSOC\tSOC\tPHB\t X \t0-31\n" + "\n" + "\n" + " Legend:\n" + "\n" + " X = Self\n" + " SOC = Connection traversing PCIe as well as the SMP link between\n" + " CPU sockets(e.g. QPI)\n" + " PHB = Connection traversing PCIe as well as a PCIe Host Bridge\n" + " (typically the CPU)\n" + " PXB = Connection traversing multiple PCIe switches\n" + " (without traversing the PCIe Host Bridge)\n" + " PIX = Connection traversing a single PCIe switch\n" + " NV# = Connection traversing a bonded set of # NVLinks"; String deviceInfoShellOutput = "0, 00000000:04:00.0\n" + "1, 00000000:82:00.0\n" + "2, 00000000:83:00.0\n" + "3, 00000000:84:00.0"; String majorMinorNumber0 = "c3:0"; String majorMinorNumber1 = "c3:1"; String majorMinorNumber2 = "c3:2"; String majorMinorNumber3 = "c3:3"; NvidiaGPUPluginForRuntimeV2.NvidiaCommandExecutor mockShell = mock(NvidiaGPUPluginForRuntimeV2.NvidiaCommandExecutor.class); when(mockShell.getDeviceInfo()).thenReturn(deviceInfoShellOutput); when(mockShell.getMajorMinorInfo("nvidia0")) .thenReturn(majorMinorNumber0); when(mockShell.getMajorMinorInfo("nvidia1")) .thenReturn(majorMinorNumber1); when(mockShell.getMajorMinorInfo("nvidia2")) .thenReturn(majorMinorNumber2); when(mockShell.getMajorMinorInfo("nvidia3")) .thenReturn(majorMinorNumber3); when(mockShell.getTopologyInfo()).thenReturn(topoInfo); when(mockShell.getDeviceInfo()).thenReturn(deviceInfoShellOutput); NvidiaGPUPluginForRuntimeV2 plugin = new NvidiaGPUPluginForRuntimeV2(); plugin.setShellExecutor(mockShell); plugin.setPathOfGpuBinary("/fake/nvidia-smi"); return plugin; } @Test public void testTopologySchedulingWithPackPolicy() throws Exception { NvidiaGPUPluginForRuntimeV2 plugin = mockFourGPUPlugin(); NvidiaGPUPluginForRuntimeV2 spyPlugin = spy(plugin); // cache the total devices Set<Device> allDevices = spyPlugin.getDevices(); // environment variable to use PACK policy Map<String, String> env = new HashMap<>(); env.put(NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_ENV_KEY, NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_PACK); // Case 0. if available devices is less than 3, no topo scheduling needed Set<Device> copyAvailableDevices = new TreeSet<>(allDevices); Iterator<Device> iterator0 = copyAvailableDevices.iterator(); iterator0.next(); iterator0.remove(); iterator0.next(); iterator0.remove(); // Case 0. allocate 1 device reset(spyPlugin); Set<Device> allocation = spyPlugin.allocateDevices(copyAvailableDevices, 1, env); assertThat(allocation).hasSize(1); verify(spyPlugin).basicSchedule(anySet(), anyInt(), anySet()); assertFalse(spyPlugin.isTopoInitialized()); // Case 1. allocate 1 device reset(spyPlugin); allocation = spyPlugin.allocateDevices(allDevices, 1, env); // ensure no topology scheduling needed assertThat(allocation).hasSize(1); verify(spyPlugin).basicSchedule(anySet(), anyInt(), anySet()); reset(spyPlugin); // Case 2. allocate all available allocation = spyPlugin.allocateDevices(allDevices, allDevices.size(), env); assertEquals(allocation.size(), allDevices.size()); verify(spyPlugin).basicSchedule(anySet(), anyInt(), anySet()); // Case 3. allocate 2 devices reset(spyPlugin); int count = 2; Map<String, Integer> pairToWeight = spyPlugin.getDevicePairToWeight(); allocation = spyPlugin.allocateDevices(allDevices, count, env); assertThat(allocation).hasSize(count); // the costTable should be init and used topology scheduling verify(spyPlugin).initCostTable(); assertTrue(spyPlugin.isTopoInitialized()); verify(spyPlugin).topologyAwareSchedule(anySet(), anyInt(), anyMap(), anySet(), anyMap()); assertThat(allocation).hasSize(count); Device[] allocatedDevices = allocation.toArray(new Device[count]); // Check weights assertEquals(NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkSameCPUSocket.getWeight(), spyPlugin.computeCostOfDevices(allocatedDevices)); // Case 4. allocate 3 devices reset(spyPlugin); count = 3; allocation = spyPlugin.allocateDevices(allDevices, count, env); assertThat(allocation).hasSize(count); // the costTable should be init and used topology scheduling verify(spyPlugin, times(0)).initCostTable(); assertTrue(spyPlugin.isTopoInitialized()); verify(spyPlugin).topologyAwareSchedule(anySet(), anyInt(), anyMap(), anySet(), anyMap()); assertThat(allocation).hasSize(count); allocatedDevices = allocation.toArray(new Device[count]); // check weights int expectedWeight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkSameCPUSocket.getWeight() + 2 * NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkCrossCPUSocket.getWeight(); assertEquals(expectedWeight, spyPlugin.computeCostOfDevices(allocatedDevices)); // Case 5. allocate 2 GPUs from three available devices reset(spyPlugin); Iterator<Device> iterator = allDevices.iterator(); iterator.next(); // remove GPU0 iterator.remove(); count = 2; allocation = spyPlugin.allocateDevices(allDevices, count, env); assertThat(allocation).hasSize(count); // the costTable should be init and used topology scheduling verify(spyPlugin, times(0)).initCostTable(); assertTrue(spyPlugin.isTopoInitialized()); verify(spyPlugin).topologyAwareSchedule(anySet(), anyInt(), anyMap(), anySet(), anyMap()); assertThat(allocation).hasSize(count); allocatedDevices = allocation.toArray(new Device[count]); // check weights assertEquals(NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkSameCPUSocket.getWeight(), spyPlugin.computeCostOfDevices(allocatedDevices)); // it should allocate GPU 2 and 3 for (Device device : allocation) { if (device.getMinorNumber() == 2) { assertTrue(true); } else if (device.getMinorNumber() == 3) { assertTrue(true); } else { assertTrue(false, "Should allocate GPU 2 and 3"); } } } @Test public void testTopologySchedulingWithSpreadPolicy() throws Exception { NvidiaGPUPluginForRuntimeV2 plugin = mockFourGPUPlugin(); NvidiaGPUPluginForRuntimeV2 spyPlugin = spy(plugin); // cache the total devices Set<Device> allDevices = spyPlugin.getDevices(); // environment variable to use PACK policy Map<String, String> env = new HashMap<>(); env.put(NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_ENV_KEY, NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_SPREAD); // Case 1. allocate 1 device Set<Device> allocation = spyPlugin.allocateDevices(allDevices, 1, env); // ensure no topology scheduling needed assertEquals(allocation.size(), 1); verify(spyPlugin).basicSchedule(anySet(), anyInt(), anySet()); reset(spyPlugin); // Case 2. allocate all available allocation = spyPlugin.allocateDevices(allDevices, allDevices.size(), env); assertEquals(allocation.size(), allDevices.size()); verify(spyPlugin).basicSchedule(anySet(), anyInt(), anySet()); // Case 3. allocate 2 devices reset(spyPlugin); int count = 2; Map<String, Integer> pairToWeight = spyPlugin.getDevicePairToWeight(); allocation = spyPlugin.allocateDevices(allDevices, count, env); assertThat(allocation).hasSize(count); // the costTable should be init and used topology scheduling verify(spyPlugin).initCostTable(); assertTrue(spyPlugin.isTopoInitialized()); verify(spyPlugin).topologyAwareSchedule(anySet(), anyInt(), anyMap(), anySet(), anyMap()); assertThat(allocation).hasSize(count); Device[] allocatedDevices = allocation.toArray(new Device[count]); // Check weights assertEquals(NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkCrossCPUSocket.getWeight(), spyPlugin.computeCostOfDevices(allocatedDevices)); // Case 4. allocate 3 devices reset(spyPlugin); count = 3; allocation = spyPlugin.allocateDevices(allDevices, count, env); assertThat(allocation).hasSize(count); // the costTable should be init and used topology scheduling verify(spyPlugin, times(0)).initCostTable(); assertTrue(spyPlugin.isTopoInitialized()); verify(spyPlugin).topologyAwareSchedule(anySet(), anyInt(), anyMap(), anySet(), anyMap()); assertThat(allocation).hasSize(count); allocatedDevices = allocation.toArray(new Device[count]); // check weights int expectedWeight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkSameCPUSocket.getWeight() + 2 * NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkCrossCPUSocket.getWeight(); assertEquals(expectedWeight, spyPlugin.computeCostOfDevices(allocatedDevices)); // Case 5. allocate 2 GPUs from three available devices reset(spyPlugin); Iterator<Device> iterator = allDevices.iterator(); iterator.next(); // remove GPU0 iterator.remove(); count = 2; allocation = spyPlugin.allocateDevices(allDevices, count, env); assertThat(allocation).hasSize(count); // the costTable should be init and used topology scheduling verify(spyPlugin, times(0)).initCostTable(); assertTrue(spyPlugin.isTopoInitialized()); verify(spyPlugin).topologyAwareSchedule(anySet(), anyInt(), anyMap(), anySet(), anyMap()); assertThat(allocation).hasSize(count); allocatedDevices = allocation.toArray(new Device[count]); // check weights assertEquals(NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkCrossCPUSocket.getWeight(), spyPlugin.computeCostOfDevices(allocatedDevices)); // it should allocate GPU 1 and 2 for (Device device : allocation) { if (device.getMinorNumber() == 0) { assertTrue(false, "Shouldn't allocate GPU 0"); } } } @Test public void testCostTableWithNVlink() throws Exception { NvidiaGPUPluginForRuntimeV2 plugin = mockEightGPUPlugin(); NvidiaGPUPluginForRuntimeV2 spyPlugin = spy(plugin); // verify the device pair to weight map spyPlugin.initCostTable(); Map<String, Integer> devicePairToWeight = spyPlugin.getDevicePairToWeight(); // 12 combinations when choose 2 GPUs from 8 respect the order. 8!/6! assertEquals(56, devicePairToWeight.size()); int sameCPUWeight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkSameCPUSocket.getWeight(); int nv1Weight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkNVLink1.getWeight(); int nv2Weight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkNVLink2.getWeight(); assertEquals(nv1Weight, (int)devicePairToWeight.get("0-1")); assertEquals(nv1Weight, (int)devicePairToWeight.get("1-0")); assertEquals(nv2Weight, (int)devicePairToWeight.get("0-4")); assertEquals(nv2Weight, (int)devicePairToWeight.get("4-0")); assertEquals(nv2Weight, (int)devicePairToWeight.get("0-3")); assertEquals(nv2Weight, (int)devicePairToWeight.get("3-0")); assertEquals(sameCPUWeight, (int)devicePairToWeight.get("6-3")); assertEquals(sameCPUWeight, (int)devicePairToWeight.get("3-6")); assertEquals(nv2Weight, (int)devicePairToWeight.get("6-7")); assertEquals(nv2Weight, (int)devicePairToWeight.get("7-6")); assertEquals(nv1Weight, (int)devicePairToWeight.get("1-3")); assertEquals(nv1Weight, (int)devicePairToWeight.get("3-1")); // verify cost Table Map<Integer, List<Map.Entry<Set<Device>, Integer>>> costTable = spyPlugin.getCostTable(); assertNull(costTable.get(1)); // C8:2 = 8!/2!/6! = 28 assertEquals(28, costTable.get(2).size()); // C8:4 = 8!/4!/4! = 70 assertEquals(70, costTable.get(4).size()); assertNull(costTable.get(8)); Set<Device> allDevices = spyPlugin.getDevices(); Map<String, String> env = new HashMap<>(); env.put(NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_ENV_KEY, NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_PACK); spyPlugin.allocateDevices(allDevices, 3, env); spyPlugin.allocateDevices(allDevices, 2, env); } /** * Test the key cost table used for topology scheduling. * */ @Test public void testCostTable() throws IOException { NvidiaGPUPluginForRuntimeV2 plugin = mockFourGPUPlugin(); NvidiaGPUPluginForRuntimeV2 spyPlugin = spy(plugin); // verify the device pair to weight map spyPlugin.initCostTable(); Map<String, Integer> devicePairToWeight = spyPlugin.getDevicePairToWeight(); // 12 combinations when choose 2 GPUs from 4 respect the order. 4!/2! assertEquals(12, devicePairToWeight.size()); int sameCPUWeight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkSameCPUSocket.getWeight(); int crossCPUWeight = NvidiaGPUPluginForRuntimeV2.DeviceLinkType .P2PLinkCrossCPUSocket.getWeight(); assertEquals(sameCPUWeight, (int)devicePairToWeight.get("0-1")); assertEquals(sameCPUWeight, (int)devicePairToWeight.get("1-0")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("0-2")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("2-0")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("0-3")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("3-0")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("1-2")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("2-1")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("1-3")); assertEquals(crossCPUWeight, (int)devicePairToWeight.get("3-1")); assertEquals(sameCPUWeight, (int)devicePairToWeight.get("2-3")); assertEquals(sameCPUWeight, (int)devicePairToWeight.get("3-2")); // verify cost Table Map<Integer, List<Map.Entry<Set<Device>, Integer>>> costTable = spyPlugin.getCostTable(); assertNull(costTable.get(1)); assertEquals(6, costTable.get(2).size()); assertEquals(4, costTable.get(3).size()); assertNull(costTable.get(4)); } /** * Test GPU topology allocation. * And analysis the GPU allocation's performance against the actual * performance data using tensorflow benchmarks. * https://github.com/tensorflow/benchmarks * */ @Test public void testTopologySchedulingPerformanceWithPackPolicyWithNVLink() throws Exception { NvidiaGPUPluginForRuntimeV2 plugin = mockEightGPUPlugin(); NvidiaGPUPluginForRuntimeV2 spyPlugin = spy(plugin); Set<Device> allDevices = spyPlugin.getDevices(); Map<String, String> env = new HashMap<>(); env.put(NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_ENV_KEY, NvidiaGPUPluginForRuntimeV2.TOPOLOGY_POLICY_PACK); /** * Analyze performance against the real data. * Get the topology scheduling algorithm's allocation's * average performance boost against median imagePerSecond and minimum * imagePerSecond in certain model and batch size combinations. * And then calculate the average performance boost. * The average performance boost against * median value means topology scheduler's allocation can stably * outperforms 50% of possible allocations. * The average performance boost against min value means the average boost * comparing to the worst allocations in various scenarios. Which is more * beautiful number for public promotion. * And also the analysis shows the best performance boost against median * and min value. * */ ActualPerformanceReport report = new ActualPerformanceReport(); report.readFromFile(); ArrayList<ActualPerformanceReport.DataRecord> dataSet = report.getDataSet(); assertThat(dataSet).hasSize(2952); String[] allModels = {"alexnet", "resnet50", "vgg16", "inception3"}; int[] batchSizes = {32, 64, 128}; int[] gpuCounts = {2, 3, 4, 5, 6, 7}; float totalBoostAgainstMedian = 0; int count = 0; float maxBoostAgainstMedian = 0; float totalBoostAgainstMin = 0; float maxBoostAgainstMin = 0; for (String model : allModels) { float totalBoostAgainstMinCertainModel = 0; float totalBoostAgainstMedianCertainModel = 0; float maxBoostAgainstMinCertainModel = 0; float maxBoostAgainstMedianCertainModel = 0; int countOfEachModel = 0; for (int bs : batchSizes) { for (int gpuCount: gpuCounts) { float bstAgainstMedian = calculatePerformanceBoostAgainstMedian( report, model, bs, gpuCount, plugin, allDevices, env); float bstAgainstMinimum = calculatePerformanceBoostAgainstMinimum( report, model, bs, gpuCount, plugin, allDevices, env); totalBoostAgainstMedian += bstAgainstMedian; totalBoostAgainstMin += bstAgainstMinimum; count++; if (maxBoostAgainstMedian < bstAgainstMedian) { maxBoostAgainstMedian = bstAgainstMedian; } if (maxBoostAgainstMin < bstAgainstMinimum) { maxBoostAgainstMin = bstAgainstMinimum; } totalBoostAgainstMinCertainModel += bstAgainstMinimum; totalBoostAgainstMedianCertainModel += bstAgainstMedian; if (maxBoostAgainstMinCertainModel < bstAgainstMinimum) { maxBoostAgainstMinCertainModel = bstAgainstMinimum; } if (maxBoostAgainstMedianCertainModel < bstAgainstMedian) { maxBoostAgainstMedianCertainModel = bstAgainstMedian; } countOfEachModel++; } } LOG.info("Model:{}, The best performance boost against median value is " + "{}", model, maxBoostAgainstMedianCertainModel); LOG.info("Model:{}, The aggregated average performance boost against " + "median value is {}", model, totalBoostAgainstMedianCertainModel/countOfEachModel); LOG.info("Model:{}, The best performance boost against min value is {}", model, maxBoostAgainstMinCertainModel); LOG.info("Model:{}, The aggregated average performance boost against " + "min value is {}", model, totalBoostAgainstMinCertainModel/countOfEachModel); } LOG.info("For all, the best performance boost against median value is " + maxBoostAgainstMedian); LOG.info("For all, the aggregated average performance boost against median " + "value is " + totalBoostAgainstMedian/count); LOG.info("For all, the best performance boost against min value is " + maxBoostAgainstMin); LOG.info("For all, the aggregated average performance boost against min " + "value is " + totalBoostAgainstMin/count); } /** * For <code>gpuCount</code> GPUs allocated by the topology algorithm, return * its performance boost against the median value. * * */ private float calculatePerformanceBoostAgainstMedian( ActualPerformanceReport report, String model, int bs, int gpuCount, NvidiaGPUPluginForRuntimeV2 plugin, Set<Device> allDevice, Map<String, String> env) { Set<Device> allocation = plugin.allocateDevices(allDevice, gpuCount, env); String gpuAllocationString = convertAllocationToGpuString(allocation); float[] metrics = report.getVariousImagePerSecond(model, bs, gpuCount, gpuAllocationString); return metrics[7]; } /** * For <code>gpuCount</code> GPUs allocated by the topology algorithm, return * its performance boost against the minimum value. * * */ private float calculatePerformanceBoostAgainstMinimum( ActualPerformanceReport report, String model, int bs, int gpuCount, NvidiaGPUPluginForRuntimeV2 plugin, Set<Device> allDevice, Map<String, String> env) { Set<Device> allocation = plugin.allocateDevices(allDevice, gpuCount, env); String gpuAllocationString = convertAllocationToGpuString(allocation); float[] metrics = report.getVariousImagePerSecond(model, bs, gpuCount, gpuAllocationString); return metrics[5]; } private String convertAllocationToGpuString(Set<Device> allocation) { StringBuilder sb = new StringBuilder(); for (Device device : allocation) { sb.append(device.getMinorNumber() + "_"); } return sb.toString().substring(0, sb.lastIndexOf("_")); } /** * Representation of the performance data report. * */ private
TestNvidiaGPUPluginForRuntimeV2
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ConstantPatternCompile.java
{ "start": 3376, "end": 15063 }
class ____ extends BugChecker implements ClassTreeMatcher { private static final ImmutableList<String> PATTERN_CLASSES = ImmutableList.of("java.util.regex.Pattern", "com.google.re2j.Pattern"); private static final Matcher<ExpressionTree> PATTERN_COMPILE_CHECK = staticMethod().onClassAny(PATTERN_CLASSES).named("compile"); private static final Matcher<ExpressionTree> MATCHER_MATCHER = instanceMethod().onExactClassAny(PATTERN_CLASSES).named("matcher"); @Override public Description matchClass(ClassTree classTree, VisitorState state) { NameUniquifier nameUniquifier = new NameUniquifier(); SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); Tree[] firstHit = new Tree[1]; for (Tree member : classTree.getMembers()) { new SuppressibleTreePathScanner<Void, Void>(state) { @Override public Void visitClass(ClassTree node, Void unused) { // Don't descend into nested classes - we'll visit them later return null; } @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { tryFix(tree, state.withPath(getCurrentPath()), nameUniquifier) .ifPresent( other -> { fixBuilder.merge(other); if (firstHit[0] == null) { firstHit[0] = tree; } }); return super.visitMethodInvocation(tree, null); } private Optional<SuggestedFix> tryFix( MethodInvocationTree tree, VisitorState state, NameUniquifier nameUniquifier) { if (!PATTERN_COMPILE_CHECK.matches(tree, state)) { return Optional.empty(); } if (!tree.getArguments().stream() .allMatch(ConstantPatternCompile::isArgStaticAndConstant)) { return Optional.empty(); } if (state.errorProneOptions().isTestOnlyTarget()) { return Optional.empty(); } if (isInStaticInitializer(state)) { return Optional.empty(); } Tree parent = state.getPath().getParentPath().getLeaf(); if (parent instanceof VariableTree variableTree) { return handleVariable(variableTree, state); } return Optional.of(handleInlineExpression(tree, state, nameUniquifier)); } }.scan(new TreePath(state.getPath(), member), null); } if (firstHit[0] == null) { return NO_MATCH; } return describeMatch(firstHit[0], fixBuilder.build()); } private static SuggestedFix handleInlineExpression( MethodInvocationTree tree, VisitorState state, NameUniquifier nameUniquifier) { String nameSuggestion = nameUniquifier.uniquify( Optional.ofNullable(findNameFromMatcherArgument(state, state.getPath())) .orElse("PATTERN")); SuggestedFix.Builder fix = SuggestedFix.builder(); return fix.replace(tree, nameSuggestion) .merge( SuggestedFixes.addMembers( state.findEnclosing(ClassTree.class), state, format( "private static final %s %s = %s;", SuggestedFixes.qualifyType(state, fix, getSymbol(tree).getReturnType().tsym), nameSuggestion, state.getSourceForNode(tree)))) .build(); } private static Optional<SuggestedFix> handleVariable(VariableTree tree, VisitorState state) { MethodTree outerMethodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); if (outerMethodTree == null) { return Optional.empty(); } VarSymbol sym = getSymbol(tree); return switch (sym.getKind()) { case RESOURCE_VARIABLE -> Optional.of(SuggestedFix.emptyFix()); case LOCAL_VARIABLE -> Optional.of(fixLocal(tree, outerMethodTree, state)); default -> Optional.empty(); }; } private static SuggestedFix fixLocal( VariableTree tree, MethodTree outerMethodTree, VisitorState state) { SuggestedFix fix = replaceRegexConstant(tree, state); if (!fix.isEmpty()) { return fix; } String name = inferName(tree, state); if (name == null) { return SuggestedFix.emptyFix(); } MethodSymbol methodSymbol = getSymbol(outerMethodTree); boolean canUseStatic = enclosingClass(methodSymbol).getNestingKind() == NestingKind.TOP_LEVEL || outerMethodTree.getModifiers().getFlags().contains(Modifier.STATIC); String replacement = String.format( "private %s final %s %s = %s;", canUseStatic ? "static " : "", state.getSourceForNode(tree.getType()), name, state.getSourceForNode(tree.getInitializer())); return renameVariableUsages(tree, name, state).toBuilder() .postfixWith(outerMethodTree, replacement) .delete(tree) .build(); } /** * If the pattern variable is initialized with a regex from a {@code private static final String} * constant, and the constant is only used once, store the {@code Pattern} in the existing * constant. * * <p>Before: * * <pre>{@code * private static final String MY_REGEX = "a+"; * ... * Pattern p = Pattern.compile(MY_REGEX); * p.matcher(...); * }</pre> * * <p>After: * * <pre>{@code * private static final Pattern MY_REGEX = Pattern.compile("a+"); * ... * MY_REGEX.matcher(...); * }</pre> */ private static SuggestedFix replaceRegexConstant(VariableTree tree, VisitorState state) { ExpressionTree regex = ((MethodInvocationTree) tree.getInitializer()).getArguments().getFirst(); Symbol regexSym = getSymbol(regex); if (regexSym == null || !regexSym.getKind().equals(ElementKind.FIELD) || !isStatic(regexSym) || !regexSym.getModifiers().contains(Modifier.FINAL) || !canBeRemoved((VarSymbol) regexSym)) { return SuggestedFix.emptyFix(); } VariableTree[] defs = {null}; int[] uses = {0}; new TreeScanner<Void, Void>() { @Override public Void visitVariable(VariableTree tree, Void unused) { if (regexSym.equals(getSymbol(tree))) { defs[0] = tree; } return super.visitVariable(tree, null); } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (regexSym.equals(getSymbol(tree))) { uses[0]++; } return super.visitIdentifier(tree, null); } @Override public Void visitMemberSelect(MemberSelectTree tree, Void unused) { if (regexSym.equals(getSymbol(tree))) { uses[0]++; } return super.visitMemberSelect(tree, null); } }.scan(state.getPath().getCompilationUnit(), null); if (uses[0] != 1) { return SuggestedFix.emptyFix(); } VariableTree def = defs[0]; return SuggestedFix.builder() .replace(def.getType(), state.getSourceForNode(tree.getType())) .prefixWith( def.getInitializer(), state .getSourceCode() .subSequence(getStartPosition(tree.getInitializer()), getStartPosition(regex)) .toString()) .postfixWith(def.getInitializer(), ")") .merge(renameVariableUsages(tree, def.getName().toString(), state)) .delete(tree) .build(); } /** Infer a name when upgrading the {@code Pattern} local to a constant. */ private static @Nullable String inferName(VariableTree tree, VisitorState state) { String name; if ((name = fromName(tree)) != null) { return name; } if ((name = fromInitializer(tree)) != null) { return name; } if ((name = fromUse(tree, state)) != null) { return name; } return null; } /** Use the existing local variable's name, unless it's terrible. */ private static @Nullable String fromName(VariableTree tree) { String name = LOWER_CAMEL.to(UPPER_UNDERSCORE, tree.getName().toString()); if (name.length() > 1 && !name.equals("PATTERN")) { return name; } return null; } /** * If the pattern is initialized from an existing constant, re-use its name. * * <p>e.g. use {@code FOO_PATTERN} for {@code Pattern.compile(FOO)} and {@code * Pattern.compile(FOO_REGEX)}. */ private static @Nullable String fromInitializer(VariableTree tree) { ExpressionTree regex = ((MethodInvocationTree) tree.getInitializer()).getArguments().getFirst(); if (!(regex instanceof IdentifierTree identifierTree)) { return null; } String name = identifierTree.getName().toString(); if (name.endsWith("_REGEX")) { name = name.substring(0, name.length() - "_REGEX".length()); } if (name.endsWith("_PATTERN")) { // Give up if we have something like Pattern.compile(FOO_PATTERN), // we don't want to name the regex FOO_PATTERN_PATTERN. return null; } return name + "_PATTERN"; } /** * If the pattern is only used once in a call to {@code matcher}, and the argument is a variable, * use that variable's name. For example, infer {@code FOO_PATTERN} from {@code * pattern.matcher(foo)}. If the argument to the call is a method call, use the method's name. */ private static @Nullable String fromUse(VariableTree tree, VisitorState state) { VarSymbol sym = getSymbol(tree); ImmutableList.Builder<TreePath> usesBuilder = ImmutableList.builder(); new TreePathScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (sym.equals(getSymbol(tree))) { usesBuilder.add(getCurrentPath()); } return null; } }.scan(state.getPath().getCompilationUnit(), null); ImmutableList<TreePath> uses = usesBuilder.build(); if (uses.size() != 1) { return null; } TreePath use = getOnlyElement(uses); return findNameFromMatcherArgument(state, use); } /** * If the path at {@code use} is a Pattern object whose .matcher method is being called on a * variable CharSequence, returns the name of that variable. */ private static @Nullable String findNameFromMatcherArgument(VisitorState state, TreePath use) { Tree grandParent = use.getParentPath().getParentPath().getLeaf(); if (!(grandParent instanceof ExpressionTree expressionTree)) { return null; } if (!MATCHER_MATCHER.matches(expressionTree, state)) { return null; } ExpressionTree matchTree = ((MethodInvocationTree) grandParent).getArguments().getFirst(); if (matchTree instanceof IdentifierTree identifierTree) { return convertToConstantName(identifierTree.getName().toString()); } if (matchTree instanceof MethodInvocationTree methodInvocationTree) { return convertToConstantName(getSymbol(methodInvocationTree).getSimpleName().toString()); } return null; } private static String convertToConstantName(String variableName) { String root = variableName.equals(Ascii.toUpperCase(variableName)) ? variableName : LOWER_CAMEL.to(UPPER_UNDERSCORE, variableName); return root + "_PATTERN"; } private static boolean isArgStaticAndConstant(ExpressionTree arg) { if (ASTHelpers.constValue(arg) == null) { return false; } Symbol argSymbol = getSymbol(arg); if (argSymbol == null) { return true; } return (argSymbol.flags() & Flags.STATIC) != 0; } // TODO(b/250568455): Make this more widely available. private static final
ConstantPatternCompile
java
apache__kafka
raft/src/main/java/org/apache/kafka/raft/internals/FuturePurgatory.java
{ "start": 913, "end": 2026 }
interface ____ supports waiting with expiration for a given threshold * to be reached. The threshold is specified through {@link #await(Comparable, long)}. * The returned future can be completed in the following ways: * * 1) The future is completed successfully if the threshold value is reached * in a call to {@link #maybeComplete(Comparable, long)}. * 2) The future is completed successfully if {@link #completeAll(long)} is called. * 3) The future is completed exceptionally if {@link #completeAllExceptionally(Throwable)} * is called. * 4) If none of the above happens before the expiration of the timeout passed to * {@link #await(Comparable, long)}, then the future will be completed exceptionally * with a {@link org.apache.kafka.common.errors.TimeoutException}. * * It is also possible for the future to be completed externally, but this should * generally be avoided. * * Note that the future objects should be organized in order so that completing awaiting * futures would stop early and not traverse all awaiting futures. * * @param <T> threshold value type */ public
which
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/external-reloadable-artifacts/external-lib/src/main/java/org/acme/lib/Greeting.java
{ "start": 30, "end": 186 }
class ____ { public static String hello() { return "Hello"; } /* public static String bonjour() { return "Bonjour"; } */ }
Greeting
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/regression/RegressionTests.java
{ "start": 1553, "end": 5375 }
class ____ extends AbstractXContentSerializingTestCase<Regression> { private static final EvaluationParameters EVALUATION_PARAMETERS = new EvaluationParameters(100); @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { return new NamedWriteableRegistry(MlEvaluationNamedXContentProvider.getNamedWriteables()); } @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(new MlEvaluationNamedXContentProvider().getNamedXContentParsers()); } public static Regression createRandom() { List<EvaluationMetric> metrics = new ArrayList<>(); if (randomBoolean()) { metrics.add(MeanSquaredErrorTests.createRandom()); } if (randomBoolean()) { metrics.add(RSquaredTests.createRandom()); } return new Regression(randomAlphaOfLength(10), randomAlphaOfLength(10), metrics.isEmpty() ? null : metrics); } @Override protected Regression doParseInstance(XContentParser parser) throws IOException { return Regression.fromXContent(parser); } @Override protected Regression createTestInstance() { return createRandom(); } @Override protected Regression mutateInstance(Regression instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Regression> instanceReader() { return Regression::new; } public void testConstructor_GivenEmptyMetrics() { ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new Regression("foo", "bar", Collections.emptyList()) ); assertThat(e.getMessage(), equalTo("[regression] must have one or more metrics")); } public void testConstructor_GivenDefaultMetrics() { Regression regression = new Regression("actual", "predicted", null); List<EvaluationMetric> metrics = regression.getMetrics(); assertThat(metrics, containsInAnyOrder(new Huber(), new MeanSquaredError(), new RSquared())); } public void testGetFields() { Regression evaluation = new Regression("foo", "bar", null); EvaluationFields fields = evaluation.getFields(); assertThat(fields.getActualField(), is(equalTo("foo"))); assertThat(fields.getPredictedField(), is(equalTo("bar"))); assertThat(fields.getTopClassesField(), is(nullValue())); assertThat(fields.getPredictedClassField(), is(nullValue())); assertThat(fields.getPredictedProbabilityField(), is(nullValue())); assertThat(fields.isPredictedProbabilityFieldNested(), is(false)); } public void testBuildSearch() { QueryBuilder userProvidedQuery = QueryBuilders.boolQuery() .filter(QueryBuilders.termQuery("field_A", "some-value")) .filter(QueryBuilders.termQuery("field_B", "some-other-value")); QueryBuilder expectedSearchQuery = QueryBuilders.boolQuery() .filter(QueryBuilders.existsQuery("act")) .filter(QueryBuilders.existsQuery("pred")) .filter( QueryBuilders.boolQuery() .filter(QueryBuilders.termQuery("field_A", "some-value")) .filter(QueryBuilders.termQuery("field_B", "some-other-value")) ); Regression evaluation = new Regression("act", "pred", Arrays.asList(new MeanSquaredError())); SearchSourceBuilder searchSourceBuilder = evaluation.buildSearch(EVALUATION_PARAMETERS, userProvidedQuery); assertThat(searchSourceBuilder.query(), equalTo(expectedSearchQuery)); assertThat(searchSourceBuilder.aggregations().count(), greaterThan(0)); } }
RegressionTests
java
elastic__elasticsearch
plugins/store-smb/src/main/java/org/elasticsearch/index/store/smb/SmbDirectoryWrapper.java
{ "start": 928, "end": 1305 }
class ____ used to wrap an existing {@link org.apache.lucene.store.FSDirectory} so that * the new shard segment files will be opened for Read and Write access. * <p> * When storing index files on an SMB share like Azure File Service, opening the file for Read * access can save a lot of roundtrips to the storage server and thus offering better performance. */ public final
is
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0985NonExecutedPluginMgmtGoalsTest.java
{ "start": 1034, "end": 1821 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that plugins in pluginManagement aren't included in the build * unless they are referenced by groupId/artifactId within the plugins * section of a pom. * * @throws Exception in case of failure */ @Test public void testitMNG0985() throws Exception { File testDir = extractResources("/mng-0985"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("initialize"); verifier.execute(); verifier.verifyFileNotPresent("target/unexpected.txt"); verifier.verifyErrorFreeLog(); } }
MavenITmng0985NonExecutedPluginMgmtGoalsTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeRpcServer.java
{ "start": 2654, "end": 10678 }
class ____ { @Test public void testNamenodeRpcBindAny() throws IOException { Configuration conf = new HdfsConfiguration(); // The name node in MiniDFSCluster only binds to 127.0.0.1. // We can set the bind address to 0.0.0.0 to make it listen // to all interfaces. conf.set(DFS_NAMENODE_RPC_BIND_HOST_KEY, "0.0.0.0"); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitActive(); assertEquals("0.0.0.0", ((NameNodeRpcServer) cluster.getNameNodeRpc()).getClientRpcServer() .getListenerAddress().getHostName()); } finally { if (cluster != null) { cluster.shutdown(); } // Reset the config conf.unset(DFS_NAMENODE_RPC_BIND_HOST_KEY); } } /** * Get the preferred DataNode location for the first block of the * given file. * @param fs The file system to use * @param p The path to use * @return the preferred host to get the data */ private static String getPreferredLocation(DistributedFileSystem fs, Path p) throws IOException{ // Use getLocatedBlocks because it is the basis for HDFS open, // but provides visibility into which host will be used. LocatedBlocks blocks = fs.getClient() .getLocatedBlocks(p.toUri().getPath(), 0); return blocks.get(0).getLocations()[0].getHostName(); } // Because of the randomness of the NN assigning DN, we run multiple // trials. 1/3^20=3e-10, so that should be good enough. static final int ITERATIONS_TO_USE = 20; @Test @Timeout(30000) public void testNamenodeRpcClientIpProxyWithFailBack() throws Exception { // Make 3 nodes & racks so that we have a decent shot of detecting when // our change overrides the random choice of datanode. Configuration conf = new HdfsConfiguration(); conf.set(DFS_NAMENODE_IP_PROXY_USERS, "fake_joe"); final CallerContext original = CallerContext.getCurrent(); MiniQJMHACluster qjmhaCluster = null; try { String baseDir = GenericTestUtils.getRandomizedTempPath(); MiniQJMHACluster.Builder builder = new MiniQJMHACluster.Builder(conf); builder.getDfsBuilder().numDataNodes(3); qjmhaCluster = builder.baseDir(baseDir).build(); MiniDFSCluster dfsCluster = qjmhaCluster.getDfsCluster(); dfsCluster.waitActive(); dfsCluster.transitionToActive(0); // Set the caller context to set the ip address CallerContext.setCurrent( new CallerContext.Builder("test", conf) .build()); dfsCluster.getFileSystem(0).setPermission( new Path("/"), FsPermission.getDirDefault()); // Run as fake joe to authorize the test UserGroupInformation joe = UserGroupInformation.createUserForTesting("fake_joe", new String[]{"fake_group"}); FileSystem joeFs = joe.doAs((PrivilegedExceptionAction<FileSystem>) () -> FileSystem.get(dfsCluster.getURI(0), conf)); Path testPath = new Path("/foo"); // Write a sample file FSDataOutputStream stream = joeFs.create(testPath); stream.write("Hello world!\n".getBytes(StandardCharsets.UTF_8)); stream.close(); qjmhaCluster.getDfsCluster().transitionToStandby(0); qjmhaCluster.getDfsCluster().transitionToActive(1); DistributedFileSystem nn1 = dfsCluster.getFileSystem(1); assertNotNull(nn1.getFileStatus(testPath)); } finally { CallerContext.setCurrent(original); if (qjmhaCluster != null) { try { qjmhaCluster.shutdown(); } catch (IOException e) { e.printStackTrace(); } } // Reset the config conf.unset(DFS_NAMENODE_IP_PROXY_USERS); } } @Test @Timeout(30000) public void testObserverHandleAddBlock() throws Exception { String baseDir = GenericTestUtils.getRandomizedTempPath(); Configuration conf = new HdfsConfiguration(); MiniQJMHACluster.Builder builder = new MiniQJMHACluster.Builder(conf).setNumNameNodes(3); builder.getDfsBuilder().numDataNodes(3); try (MiniQJMHACluster qjmhaCluster = builder.baseDir(baseDir).build()) { MiniDFSCluster dfsCluster = qjmhaCluster.getDfsCluster(); dfsCluster.waitActive(); dfsCluster.transitionToActive(0); dfsCluster.transitionToObserver(2); NameNode activeNN = dfsCluster.getNameNode(0); NameNode observerNN = dfsCluster.getNameNode(2); // Stop the editLogTailer of Observer NameNode observerNN.getNamesystem().getEditLogTailer().stop(); DistributedFileSystem dfs = dfsCluster.getFileSystem(0); Path testPath = new Path("/testObserverHandleAddBlock/file.txt"); try (FSDataOutputStream ignore = dfs.create(testPath)) { HdfsFileStatus fileStatus = activeNN.getRpcServer().getFileInfo(testPath.toUri().getPath()); assertNotNull(fileStatus); assertNull(observerNN.getRpcServer().getFileInfo(testPath.toUri().getPath())); LambdaTestUtils.intercept(ObserverRetryOnActiveException.class, () -> { observerNN.getRpcServer().addBlock(testPath.toUri().getPath(), dfs.getClient().getClientName(), null, null, fileStatus.getFileId(), null, EnumSet.noneOf(AddBlockFlag.class)); }); } finally { dfs.delete(testPath, true); } } } /** * A test to make sure that if an authorized user adds "clientIp:" to their * caller context, it will be used to make locality decisions on the NN. */ @Test public void testNamenodeRpcClientIpProxy() throws IOException { Configuration conf = new HdfsConfiguration(); conf.set(DFS_NAMENODE_IP_PROXY_USERS, "fake_joe"); // Make 3 nodes & racks so that we have a decent shot of detecting when // our change overrides the random choice of datanode. final String[] racks = new String[]{"/rack1", "/rack2", "/rack3"}; final String[] hosts = new String[]{"node1", "node2", "node3"}; MiniDFSCluster cluster = null; final CallerContext original = CallerContext.getCurrent(); try { cluster = new MiniDFSCluster.Builder(conf) .racks(racks).hosts(hosts).numDataNodes(hosts.length) .build(); cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); // Write a sample file final Path fooName = fs.makeQualified(new Path("/foo")); FSDataOutputStream stream = fs.create(fooName); stream.write("Hello world!\n".getBytes(StandardCharsets.UTF_8)); stream.close(); // Set the caller context to set the ip address CallerContext.setCurrent( new CallerContext.Builder("test", conf) .append(CallerContext.CLIENT_IP_STR, hosts[0]) .build()); // Should get a random mix of DataNodes since we aren't joe. for (int trial = 0; trial < ITERATIONS_TO_USE; ++trial) { String host = getPreferredLocation(fs, fooName); if (!hosts[0].equals(host)) { // found some other host, so things are good break; } else if (trial == ITERATIONS_TO_USE - 1) { assertNotEquals(hosts[0], host, "Failed to get non-node1"); } } // Run as fake joe to authorize the test UserGroupInformation joe = UserGroupInformation.createUserForTesting("fake_joe", new String[]{"fake_group"}); DistributedFileSystem joeFs = (DistributedFileSystem) DFSTestUtil.getFileSystemAs(joe, conf); // As joe, we should get all node1. for (int trial = 0; trial < ITERATIONS_TO_USE; ++trial) { String host = getPreferredLocation(joeFs, fooName); assertEquals(hosts[0], host, "Trial " + trial + " failed"); } } finally { CallerContext.setCurrent(original); if (cluster != null) { cluster.shutdown(); } // Reset the config conf.unset(DFS_NAMENODE_IP_PROXY_USERS); } } }
TestNameNodeRpcServer
java
netty__netty
codec-compression/src/test/java/io/netty/handler/codec/compression/Bzip2EncoderTest.java
{ "start": 1086, "end": 2050 }
class ____ extends AbstractEncoderTest { @Override protected EmbeddedChannel createChannel() { return new EmbeddedChannel(new Bzip2Encoder(MIN_BLOCK_SIZE)); } @Override protected ByteBuf decompress(ByteBuf compressed, int originalLength) throws Exception { byte[] decompressed = new byte[originalLength]; try (InputStream is = new ByteBufInputStream(compressed, true); BZip2CompressorInputStream bzip2Is = new BZip2CompressorInputStream(is)) { int remaining = originalLength; while (remaining > 0) { int read = bzip2Is.read(decompressed, originalLength - remaining, remaining); if (read > 0) { remaining -= read; } else { break; } } assertEquals(-1, bzip2Is.read()); } return Unpooled.wrappedBuffer(decompressed); } }
Bzip2EncoderTest
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/basic/BasicPlatform.java
{ "start": 1679, "end": 4041 }
class ____ implements CommandRunner { @Override public String run(Node curNode, String[] command) throws IOException { try { String result = Shell.execCommand(command); log.info("RUN: {}. RESULT: [{}]", String.join(" ", command), result); return result; } catch (RuntimeException | IOException e) { log.info("RUN: {}. ERROR: [{}]", String.join(" ", command), e.getMessage()); throw e; } } } public BasicPlatform(String curNodeName, BasicTopology topology, Scheduler scheduler, CommandRunner commandRunner) { this.curNode = topology.node(curNodeName); if (this.curNode == null) { throw new RuntimeException(String.format("No node named %s found " + "in the cluster! Cluster nodes are: %s", curNodeName, String.join(",", topology.nodes().keySet()))); } this.topology = topology; this.scheduler = scheduler; this.commandRunner = commandRunner; } public BasicPlatform(String curNodeName, Scheduler scheduler, JsonNode configRoot) { JsonNode nodes = configRoot.get("nodes"); if (nodes == null) { throw new RuntimeException("Expected to find a 'nodes' field " + "in the root JSON configuration object"); } this.topology = new BasicTopology(nodes); this.scheduler = scheduler; this.curNode = topology.node(curNodeName); if (this.curNode == null) { throw new RuntimeException(String.format("No node named %s found " + "in the cluster! Cluster nodes are: %s", curNodeName, String.join(",", topology.nodes().keySet()))); } this.commandRunner = new ShellCommandRunner(); } @Override public String name() { return "BasicPlatform"; } @Override public Node curNode() { return curNode; } @Override public Topology topology() { return topology; } @Override public Scheduler scheduler() { return scheduler; } @Override public String runCommand(String[] command) throws IOException { return commandRunner.run(curNode, command); } }
ShellCommandRunner
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParser.java
{ "start": 10933, "end": 13497 }
class ____ extends ExpressionContext { public ExpressionContext left; public Token op; public ExpressionContext right; public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public TerminalNode CARET() { return getToken(PromqlBaseParser.CARET, 0); } public ModifierContext modifier() { return getRuleContext(ModifierContext.class,0); } public TerminalNode ASTERISK() { return getToken(PromqlBaseParser.ASTERISK, 0); } public TerminalNode PERCENT() { return getToken(PromqlBaseParser.PERCENT, 0); } public TerminalNode SLASH() { return getToken(PromqlBaseParser.SLASH, 0); } public TerminalNode MINUS() { return getToken(PromqlBaseParser.MINUS, 0); } public TerminalNode PLUS() { return getToken(PromqlBaseParser.PLUS, 0); } public TerminalNode EQ() { return getToken(PromqlBaseParser.EQ, 0); } public TerminalNode NEQ() { return getToken(PromqlBaseParser.NEQ, 0); } public TerminalNode GT() { return getToken(PromqlBaseParser.GT, 0); } public TerminalNode GTE() { return getToken(PromqlBaseParser.GTE, 0); } public TerminalNode LT() { return getToken(PromqlBaseParser.LT, 0); } public TerminalNode LTE() { return getToken(PromqlBaseParser.LTE, 0); } public TerminalNode BOOL() { return getToken(PromqlBaseParser.BOOL, 0); } public TerminalNode AND() { return getToken(PromqlBaseParser.AND, 0); } public TerminalNode UNLESS() { return getToken(PromqlBaseParser.UNLESS, 0); } public TerminalNode OR() { return getToken(PromqlBaseParser.OR, 0); } @SuppressWarnings("this-escape") public ArithmeticBinaryContext(ExpressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).enterArithmeticBinary(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).exitArithmeticBinary(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PromqlBaseParserVisitor ) return ((PromqlBaseParserVisitor<? extends T>)visitor).visitArithmeticBinary(this); else return visitor.visitChildren(this); } } @SuppressWarnings("CheckReturnValue") public static
ArithmeticBinaryContext
java
spring-projects__spring-boot
module/spring-boot-artemis/src/main/java/org/springframework/boot/artemis/autoconfigure/ArtemisConnectionFactoryConfiguration.java
{ "start": 1983, "end": 2973 }
class ____ { @Bean(name = "jmsConnectionFactory") @ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", havingValue = false) ActiveMQConnectionFactory jmsConnectionFactory(ArtemisProperties properties, ListableBeanFactory beanFactory, ArtemisConnectionDetails connectionDetails) { return createJmsConnectionFactory(properties, connectionDetails, beanFactory); } private static ActiveMQConnectionFactory createJmsConnectionFactory(ArtemisProperties properties, ArtemisConnectionDetails connectionDetails, ListableBeanFactory beanFactory) { return new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails) .createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CachingConnectionFactory.class) @ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", matchIfMissing = true) static
SimpleConnectionFactoryConfiguration
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/ast/UnresolvedTypeKind.java
{ "start": 1129, "end": 1173 }
enum ____ { /** * An
UnresolvedTypeKind
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationTest.java
{ "start": 1784, "end": 2146 }
class ____ { @Id Long id; @Column String name; @ManyToMany( mappedBy = "groups" ) Set<User> users = new HashSet<>(); Set<User> getUsers() { return Collections.unmodifiableSet( users ); } void resetUsers() { // this wouldn't trigger association management: users.clear(); users = new HashSet<>(); } } @Entity private static
Group
java
apache__camel
components/camel-jmx/src/main/java/org/apache/camel/component/jmx/JMXUriBuilder.java
{ "start": 1058, "end": 6981 }
class ____ { private Map<String, String> mQueryProps = new LinkedHashMap<>(); private String mServerName = "platform"; public JMXUriBuilder() { } public JMXUriBuilder(String aServerName) { setServerName(aServerName); } public JMXUriBuilder withFormat(String aFormat) { addProperty("format", aFormat); return this; } public JMXUriBuilder withUser(String aFormat) { addProperty("user", aFormat); return this; } public JMXUriBuilder withPassword(String aFormat) { addProperty("password", aFormat); return this; } public JMXUriBuilder withObjectDomain(String aFormat) { addProperty("objectDomain", aFormat); return this; } public JMXUriBuilder withObjectName(String aFormat) { addProperty("objectName", aFormat); return this; } public JMXUriBuilder withNotificationFilter(String aFilter) { addProperty("notificationFilter", aFilter); return this; } public JMXUriBuilder withHandback(String aHandback) { addProperty("handback", aHandback); return this; } public JMXUriBuilder withMonitorType(String aMonitorType) { addProperty("monitorType", aMonitorType); return this; } public JMXUriBuilder withInitThreshold(int aInitThreshold) { addProperty("initThreshold", String.valueOf(aInitThreshold)); return this; } public JMXUriBuilder withOffset(int aOffset) { addProperty("offset", String.valueOf(aOffset)); return this; } public JMXUriBuilder withModulus(int aModulus) { addProperty("modulus", String.valueOf(aModulus)); return this; } public JMXUriBuilder withDifferenceMode(boolean aDifferenceMode) { addProperty("differenceMode", String.valueOf(aDifferenceMode)); return this; } public JMXUriBuilder withGranularityPeriod(long aPeriod) { addProperty("granularityPeriod", String.valueOf(aPeriod)); return this; } public JMXUriBuilder withObservedAttribute(String aObservedAttribute) { addProperty("observedAttribute", aObservedAttribute); return this; } public JMXUriBuilder withNotifyHigh(boolean aNotifyHigh) { addProperty("notifyHigh", String.valueOf(aNotifyHigh)); return this; } public JMXUriBuilder withNotifyLow(boolean aNotifyLow) { addProperty("notifyLow", String.valueOf(aNotifyLow)); return this; } public JMXUriBuilder withThresholdHigh(Number aThresholdHigh) { addProperty("thresholdHigh", String.valueOf(aThresholdHigh)); return this; } public JMXUriBuilder withThresholdLow(Number aThresholdLow) { addProperty("thresholdLow", String.valueOf(aThresholdLow)); return this; } public JMXUriBuilder withNotifyDiffer(boolean aNotifyDiffer) { addProperty("notifyDiffer", String.valueOf(aNotifyDiffer)); return this; } public JMXUriBuilder withNotifyMatch(boolean aNotifyMatch) { addProperty("notifyMatch", String.valueOf(aNotifyMatch)); return this; } public JMXUriBuilder withStringToCompare(String aStringToCompare) { addProperty("stringToCompare", aStringToCompare); return this; } public JMXUriBuilder withTestConnectionOnStartup(boolean aTestConnectionOnStartup) { addProperty("testConnectionOnStartup", String.valueOf(aTestConnectionOnStartup)); return this; } public JMXUriBuilder withReconnectOnConnectionFailure(boolean aReconnectOnConnectionFailure) { addProperty("reconnectOnConnectionFailure", String.valueOf(aReconnectOnConnectionFailure)); return this; } public JMXUriBuilder withReconnectDelay(int aReconnectDelay) { addProperty("reconnectDelay", String.valueOf(aReconnectDelay)); return this; } /** * Converts all of the values to params with the "key." prefix so the component will pick up on them and set them on * the endpoint. Alternatively, you can pass in a reference to a Hashtable using the version of this method that * takes a single string. */ public JMXUriBuilder withObjectProperties(Map<String, String> aPropertiesSansKeyPrefix) { for (Entry<String, String> entry : aPropertiesSansKeyPrefix.entrySet()) { addProperty("key." + entry.getKey(), entry.getValue()); } return this; } /** * Your value should start with a hash mark since it's a reference to a value. This method will add the hash mark if * it's not present. */ public JMXUriBuilder withObjectPropertiesReference(String aReferenceToHashtable) { if (aReferenceToHashtable.startsWith("#")) { addProperty("objectProperties", aReferenceToHashtable); } else { addProperty("objectProperties", "#" + aReferenceToHashtable); } return this; } protected void addProperty(String aName, String aValue) { mQueryProps.put(aName, aValue); } public String getServerName() { return mServerName; } public void setServerName(String aServerName) { mServerName = aServerName; } public JMXUriBuilder withServerName(String aServerName) { setServerName(aServerName); return this; } @Override public String toString() { StringBuilder sb = new StringBuilder("jmx:").append(getServerName()); if (!mQueryProps.isEmpty()) { sb.append('?'); String delim = ""; for (Entry<String, String> entry : mQueryProps.entrySet()) { sb.append(delim); sb.append(entry.getKey()).append('=').append(entry.getValue()); delim = "&"; } } return sb.toString(); } }
JMXUriBuilder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/javatime/deser/InstantDeser291Test.java
{ "start": 521, "end": 1829 }
class ____ extends DateTimeTestBase { private final JsonMapper MAPPER = JsonMapper.builder() .defaultLocale(Locale.ENGLISH) .enable(DateTimeFeature.ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS) .build(); private final ObjectReader READER = MAPPER.readerFor(Instant.class); private static final Instant INSTANT_3_SEC_AFTER_EPOC = Instant.ofEpochSecond(3); private static final Instant INSTANT_3_SEC_BEFORE_EPOC = Instant.ofEpochSecond(-3); private static final String STR_3_SEC = "\"3.000000000\""; private static final String STR_POSITIVE_3 = "\"+3.000000000\""; private static final String STR_NEGATIVE_3 = "\"-3.000000000\""; /** * Baseline that always succeeds, even before resolution of issue 291 * @throws Exception */ @Test public void testNormalNumericalString() throws Exception { assertEquals(INSTANT_3_SEC_AFTER_EPOC, READER.readValue(STR_3_SEC)); } @Test public void testNegativeNumericalString() throws Exception { assertEquals(INSTANT_3_SEC_BEFORE_EPOC, READER.readValue(STR_NEGATIVE_3)); } @Test public void testAllowedPlusSignNumericalString() throws Exception { assertEquals(INSTANT_3_SEC_AFTER_EPOC, READER.readValue(STR_POSITIVE_3)); } }
InstantDeser291Test
java
google__dagger
javatests/dagger/internal/codegen/MapMultibindingValidationTest.java
{ "start": 16404, "end": 17840 }
class ____ {", "", " @Binds", " @IntoMap", " @StringKey(\"foo\")", " abstract Provider<String> provideProvider(Provider<String> provider);", "}"); // Entry points aren't needed because the check we care about here is a module validation Source bindsComponent = component(""); CompilerTests.daggerCompiler(bindsModule, bindsComponent) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(2); subject.hasErrorContaining( "@Binds methods with @IntoMap must not return framework types"); subject.hasErrorContaining("test.MapModule has errors") .onSource(bindsComponent) .onLineContaining("@Component(modules = {MapModule.class})"); }); } private static Source component(String... entryPoints) { return CompilerTests.javaSource( "test.TestComponent", ImmutableList.<String>builder() .add( "package test;", "", "import dagger.Component;", "import dagger.producers.Producer;", "import java.util.Map;", "import javax.inject.Provider;", "", "@Component(modules = {MapModule.class})", "
MapModule
java
assertj__assertj-core
assertj-tests/assertj-performance-tests/src/test/java/org/assertj/tests/core/perf/TypeComparatorsPerfTest.java
{ "start": 1023, "end": 1600 }
class ____ Comparator.comparing(Class::getName) : ~160ms @Disabled @Test void run_100_000_object_assertions() { long start = System.currentTimeMillis(); // GIVEN int total = 1_000_000; Object object = "test"; // WHEN for (int i = 0; i < total; i++) { assertThat(object).isNotNull(); } // THEN long end = System.currentTimeMillis(); long duration = ChronoUnit.MILLIS.between(Instant.ofEpochMilli(start), Instant.ofEpochMilli(end)); System.out.println("execution time for " + total + " -> " + duration + "ms"); } }
replacing
java
apache__flink
flink-python/src/test/java/org/apache/flink/table/runtime/operators/python/aggregate/PythonStreamGroupTableAggregateOperatorTest.java
{ "start": 2227, "end": 11400 }
class ____ extends AbstractPythonStreamAggregateOperatorTest { @Test void testFlushDataOnClose() throws Exception { OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(new Configuration()); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.open(); testHarness.processElement(new StreamRecord<>(newRow(true, "c1", 0L), initialTime + 1)); testHarness.processElement(new StreamRecord<>(newRow(false, "c2", 1L), initialTime + 2)); testHarness.close(); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(false, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(false, "c2", 1L))); assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); } @Test void testFinishBundleTriggeredOnCheckpoint() throws Exception { Configuration conf = new Configuration(); conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.open(); testHarness.processElement(new StreamRecord<>(newRow(true, "c1", 0L), initialTime + 1)); testHarness.processElement(new StreamRecord<>(newRow(true, "c2", 1L), initialTime + 2)); testHarness.processElement(new StreamRecord<>(newRow(true, "c3", 2L), initialTime + 3)); // checkpoint trigger finishBundle testHarness.prepareSnapshotPreBarrier(0L); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c3", 2L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c3", 2L))); assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.close(); } @Test void testFinishBundleTriggeredByCount() throws Exception { Configuration conf = new Configuration(); conf.set(PythonOptions.MAX_BUNDLE_SIZE, 3); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.open(); testHarness.processElement(new StreamRecord<>(newRow(true, "c1", 0L), initialTime + 1)); testHarness.processElement(new StreamRecord<>(newRow(true, "c2", 1L), initialTime + 2)); assertOutputEquals( "FinishBundle should not be triggered.", expectedOutput, testHarness.getOutput()); testHarness.processElement(new StreamRecord<>(newRow(true, "c3", 2L), initialTime + 2)); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c3", 2L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c3", 2L))); assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.close(); } @Test void testFinishBundleTriggeredByTime() throws Exception { Configuration conf = new Configuration(); conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10); conf.set(PythonOptions.MAX_BUNDLE_TIME_MILLS, 1000L); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.open(); testHarness.processElement(new StreamRecord<>(newRow(true, "c1", 0L), initialTime + 1)); testHarness.processElement(new StreamRecord<>(newRow(true, "c2", 1L), initialTime + 2)); testHarness.processElement(new StreamRecord<>(newRow(true, "c3", 2L), initialTime + 3)); assertOutputEquals( "FinishBundle should not be triggered.", expectedOutput, testHarness.getOutput()); testHarness.setProcessingTime(1000L); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c3", 2L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c3", 2L))); assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.close(); } @Test void testWatermarkProcessedOnFinishBundle() throws Exception { Configuration conf = new Configuration(); conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.open(); testHarness.processElement(new StreamRecord<>(newRow(true, "c1", 0L), initialTime + 1)); testHarness.processElement(new StreamRecord<>(newRow(true, "c2", 1L), initialTime + 2)); testHarness.processWatermark(initialTime + 2); assertOutputEquals("Watermark has been processed", expectedOutput, testHarness.getOutput()); // checkpoint trigger finishBundle testHarness.prepareSnapshotPreBarrier(0L); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new Watermark(initialTime + 2)); assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.close(); } @Test void testStateCleanupTimer() throws Exception { Configuration conf = new Configuration(); conf.setString("table.exec.state.ttl", "100"); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>(); testHarness.open(); testHarness.setProcessingTime(0L); testHarness.processElement(new StreamRecord<>(newRow(true, "c1", 0L), initialTime + 1)); testHarness.setProcessingTime(500L); testHarness.processElement(new StreamRecord<>(newRow(true, "c2", 1L), initialTime + 2)); testHarness.setProcessingTime(599L); testHarness.processElement(new StreamRecord<>(newRow(true, "c2", 2L), initialTime + 3)); testHarness.setProcessingTime(1000L); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L))); expectedOutput.add(new StreamRecord<>(newRow(true, "state_cleanup_triggered: c1", 100L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 1L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 2L))); expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 2L))); expectedOutput.add(new StreamRecord<>(newRow(true, "state_cleanup_triggered: c2", 699L))); assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.close(); } @Override public OneInputStreamOperator getTestOperator(Configuration config) { long stateTtl = Long.valueOf(config.getString("table.exec.state.ttl", "0")); return new PassThroughPythonStreamGroupTableAggregateOperator( config, getInputType(), getOutputType(), new PythonAggregateFunctionInfo[] { new PythonAggregateFunctionInfo( PythonScalarFunctionOperatorTestBase.DummyPythonFunction.INSTANCE, new Integer[] {0}, -1, false) }, getGrouping(), -1, false, stateTtl, stateTtl); } private static
PythonStreamGroupTableAggregateOperatorTest
java
netty__netty
transport-sctp/src/main/java/com/sun/nio/sctp/UnsupportedOperatingSystemException.java
{ "start": 668, "end": 1277 }
class ____ extends RuntimeException { private static final long serialVersionUID = -221782446524784377L; public static void raise() { throw new UnsupportedOperatingSystemException(); } public UnsupportedOperatingSystemException() { } public UnsupportedOperatingSystemException(String message) { super(message); } public UnsupportedOperatingSystemException(String message, Throwable cause) { super(message, cause); } public UnsupportedOperatingSystemException(Throwable cause) { super(cause); } }
UnsupportedOperatingSystemException
java
grpc__grpc-java
authz/src/test/java/io/grpc/authz/AuthorizationServerInterceptorTest.java
{ "start": 914, "end": 2011 }
class ____ { @Test public void invalidPolicyFailsStaticAuthzInterceptorCreation() throws Exception { String policy = "{ \"name\": \"abc\",, }"; try { AuthorizationServerInterceptor.create(policy); fail("exception expected"); } catch (IOException ioe) { assertThat(ioe).hasMessageThat().contains("malformed JSON"); assertThat(ioe).hasMessageThat().contains("at line 1 column 18 path $.name"); } } @Test public void validPolicyCreatesStaticAuthzInterceptor() throws Exception { String policy = "{" + " \"name\" : \"authz\"," + " \"deny_rules\": [" + " {" + " \"name\": \"deny_foo\"," + " \"source\": {" + " \"principals\": [" + " \"spiffe://foo.com\"" + " ]" + " }" + " }" + " ]," + " \"allow_rules\": [" + " {" + " \"name\": \"allow_all\"" + " }" + " ]" + "}"; assertNotNull(AuthorizationServerInterceptor.create(policy)); } }
AuthorizationServerInterceptorTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/CompositeArgumentTypeStrategy.java
{ "start": 1394, "end": 2088 }
class ____ implements ArgumentTypeStrategy { @Override public Optional<DataType> inferArgumentType( CallContext callContext, int argumentPos, boolean throwOnFailure) { DataType dataType = callContext.getArgumentDataTypes().get(argumentPos); if (!LogicalTypeChecks.isCompositeType(dataType.getLogicalType())) { return callContext.fail(throwOnFailure, "A composite type expected. Got: %s", dataType); } return Optional.of(dataType); } @Override public Argument getExpectedArgument(FunctionDefinition functionDefinition, int argumentPos) { return Argument.ofGroup("COMPOSITE"); } }
CompositeArgumentTypeStrategy
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/main/java/org/apache/hadoop/mapred/YARNRunner.java
{ "start": 4890, "end": 4998 }
class ____ the current JobClient (0.22 hadoop) to run on YARN. */ @SuppressWarnings("unchecked") public
enables
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/legacy/sources/tsextractors/ExistingField.java
{ "start": 2277, "end": 5182 }
class ____ extends TimestampExtractor { private static final long serialVersionUID = 1L; private String field; /** * @param field The field to convert into a rowtime attribute. */ public ExistingField(String field) { this.field = checkNotNull(field); } @Override public String[] getArgumentFields() { return new String[] {field}; } @Override public void validateArgumentFields(TypeInformation<?>[] argumentFieldTypes) { DataType fieldType = fromLegacyInfoToDataType(argumentFieldTypes[0]); switch (fieldType.getLogicalType().getTypeRoot()) { case BIGINT: case TIMESTAMP_WITHOUT_TIME_ZONE: case VARCHAR: break; default: throw new ValidationException( String.format( "Field '%s' must be of type Long or Timestamp or String but is of type %s.", field, fieldType)); } } /** * Returns an {@link Expression} that casts a {@link Long}, {@link Timestamp}, or timestamp * formatted {@link String} field (e.g., "2018-05-28 12:34:56.000") into a rowtime attribute. */ @Override public Expression getExpression(ResolvedFieldReference[] fieldAccesses) { ResolvedFieldReference fieldAccess = fieldAccesses[0]; DataType type = fromLegacyInfoToDataType(fieldAccess.resultType()); FieldReferenceExpression fieldReferenceExpr = new FieldReferenceExpression(fieldAccess.name(), type, 0, fieldAccess.fieldIndex()); switch (type.getLogicalType().getTypeRoot()) { case BIGINT: case TIMESTAMP_WITHOUT_TIME_ZONE: return fieldReferenceExpr; case VARCHAR: DataType outputType = TIMESTAMP(3).bridgedTo(Timestamp.class); return CallExpression.permanent( CAST, Arrays.asList(fieldReferenceExpr, typeLiteral(outputType)), outputType); default: throw new RuntimeException("Unsupport type: " + type); } } @Override public Map<String, String> toProperties() { Map<String, String> map = new HashMap<>(); map.put(Rowtime.ROWTIME_TIMESTAMPS_TYPE, Rowtime.ROWTIME_TIMESTAMPS_TYPE_VALUE_FROM_FIELD); map.put(Rowtime.ROWTIME_TIMESTAMPS_FROM, field); return map; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExistingField that = (ExistingField) o; return field.equals(that.field); } @Override public int hashCode() { return field.hashCode(); } }
ExistingField
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NameAbbreviatorTest.java
{ "start": 1197, "end": 3682 }
class ____ { public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { // { pattern, expected } {"0", "NameAbbreviatorTest"}, {"1", "NameAbbreviatorTest"}, {"2", "pattern.NameAbbreviatorTest"}, {"3", "core.pattern.NameAbbreviatorTest"}, {"1.", "o.a.l.l.c.p.NameAbbreviatorTest"}, {"1.1.~", "o.a.~.~.~.~.NameAbbreviatorTest"}, {"1.1.1.*", "o.a.l.log4j.core.pattern.NameAbbreviatorTest"}, {".", "......NameAbbreviatorTest"}, {"1.2*", "o.a.l.l.c.pattern.NameAbbreviatorTest"}, {"1.3*", "o.a.l.l.core.pattern.NameAbbreviatorTest"}, {"1.8*", "org.apache.logging.log4j.core.pattern.NameAbbreviatorTest"} }); } @MethodSource("data") @ParameterizedTest(name = "pattern=\"{0}\", expected={1}") void testAbbreviatorPatterns(final String pattern, final String expected) { final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(pattern); final StringBuilder destination = new StringBuilder(); abbreviator.abbreviate(this.getClass().getName(), destination); final String actual = destination.toString(); assertEquals(expected, actual); } @MethodSource("data") @ParameterizedTest(name = "pattern=\"{0}\", expected={1}") void testAbbreviatorPatternsAppendLongPrefix(final String pattern, final String expected) { final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(pattern); final String PREFIX = "some random text big enough to be larger than abbreviated string "; final StringBuilder destination = new StringBuilder(PREFIX); abbreviator.abbreviate(this.getClass().getName(), destination); final String actual = destination.toString(); assertEquals(PREFIX + expected, actual); } @MethodSource("data") @ParameterizedTest(name = "pattern=\"{0}\", expected={1}") void testAbbreviatorPatternsAppend(final String pattern, final String expected) { final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(pattern); final String PREFIX = "some random text"; final StringBuilder destination = new StringBuilder(PREFIX); abbreviator.abbreviate(this.getClass().getName(), destination); final String actual = destination.toString(); assertEquals(PREFIX + expected, actual); } }
NameAbbreviatorTest
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapServerDebugLogging.java
{ "start": 771, "end": 2140 }
class ____ { private final MemoryHandler logHandler; private final Logger targetLogger; private final AtomicBoolean hasLogMessage = new AtomicBoolean(false); public LdapServerDebugLogging(Logger targetLogger) { this.logHandler = new MemoryHandler(new InfoLoggingHandler(targetLogger), 1000, Level.WARNING) { @Override public void publish(LogRecord record) { hasLogMessage.set(true); super.publish(record); } }; this.targetLogger = targetLogger; } public TestRule getTestWatcher() { return new TestWatcher() { @Override protected void failed(Throwable e, Description description) { if (hasLogMessage.get()) { targetLogger.info("Test [{}] failed, printing debug output from LDAP server", description); logHandler.push(); } else { targetLogger.info("Test [{}] failed, but no debug output was received from LDAP server", description); } } }; } public void configure(InMemoryDirectoryServerConfig config) { targetLogger.info("Configuring debug logging for LDAP server [{}]", config); config.setLDAPDebugLogHandler(logHandler); } private static
LdapServerDebugLogging
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/qualifiers/CompositeQualifier.java
{ "start": 1077, "end": 3713 }
class ____<T> implements Qualifier<T> { private final Qualifier<T>[] qualifiers; /** * @param qualifiers The qualifiers */ CompositeQualifier(Qualifier<T>[] qualifiers) { this.qualifiers = qualifiers; } @Override public <BT extends BeanType<T>> Stream<BT> reduce(Class<T> beanType, Stream<BT> candidates) { Stream<BT> reduced = candidates; for (Qualifier<T> qualifier : qualifiers) { reduced = qualifier.reduce(beanType, reduced); } return reduced; } @Override public <BT extends BeanType<T>> Collection<BT> filter(Class<T> beanType, Collection<BT> candidates) { for (Qualifier<T> qualifier : qualifiers) { candidates = qualifier.filter(beanType, candidates); } return candidates; } @Override public <BT extends QualifiedBeanType<T>> Collection<BT> filterQualified(Class<T> beanType, Collection<BT> candidates) { for (Qualifier<T> qualifier : qualifiers) { candidates = qualifier.filterQualified(beanType, candidates); } return candidates; } public Qualifier<T>[] getQualifiers() { return qualifiers; } @Override public boolean contains(Qualifier<T> qualifier) { if (qualifier instanceof CompositeQualifier<T> compositeQualifier) { for (Qualifier<T> q : compositeQualifier.qualifiers) { if (!contains(q)) { return false; } } return true; } if (qualifier instanceof FilteringCompositeQualifier<T> filteringCompositeQualifier) { for (Qualifier<T> q : filteringCompositeQualifier.getQualifiers()) { if (!contains(q)) { return false; } } return true; } for (Qualifier<T> q : qualifiers) { if (q.contains(qualifier)) { return true; } } return false; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompositeQualifier<?> that = (CompositeQualifier<?>) o; return Arrays.equals(qualifiers, that.qualifiers); } @Override public int hashCode() { return Arrays.hashCode(qualifiers); } @Override public String toString() { return Arrays.stream(qualifiers).map(Object::toString).collect(Collectors.joining(" and ")); } }
CompositeQualifier
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/checkpointing/AlternatingCollectingBarriers.java
{ "start": 1365, "end": 3534 }
class ____ extends AbstractAlternatingAlignedBarrierHandlerState { AlternatingCollectingBarriers(ChannelState context) { super(context); } @Override public BarrierHandlerState alignedCheckpointTimeout( Controller controller, CheckpointBarrier checkpointBarrier) throws IOException, CheckpointException { state.prioritizeAllAnnouncements(); CheckpointBarrier unalignedBarrier = checkpointBarrier.asUnaligned(); controller.initInputsCheckpoint(unalignedBarrier); for (CheckpointableInput input : state.getInputs()) { input.checkpointStarted(unalignedBarrier); } controller.triggerGlobalCheckpoint(unalignedBarrier); return new AlternatingCollectingBarriersUnaligned(true, state); } @Override public BarrierHandlerState endOfPartitionReceived( Controller controller, InputChannelInfo channelInfo) throws IOException, CheckpointException { state.channelFinished(channelInfo); CheckpointBarrier pendingCheckpointBarrier = controller.getPendingCheckpointBarrier(); checkState( pendingCheckpointBarrier != null, "At least one barrier received in collecting barrier state."); checkState( !pendingCheckpointBarrier.getCheckpointOptions().isUnalignedCheckpoint(), "Pending checkpoint barrier should be aligned in " + "collecting aligned barrier state"); if (controller.allBarriersReceived()) { controller.initInputsCheckpoint(pendingCheckpointBarrier); controller.triggerGlobalCheckpoint(pendingCheckpointBarrier); return finishCheckpoint(); } else if (controller.isTimedOut(pendingCheckpointBarrier)) { return alignedCheckpointTimeout(controller, pendingCheckpointBarrier) .endOfPartitionReceived(controller, channelInfo); } return this; } @Override protected BarrierHandlerState transitionAfterBarrierReceived(ChannelState state) { return this; } }
AlternatingCollectingBarriers
java
elastic__elasticsearch
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java
{ "start": 5272, "end": 6200 }
class ____ * for the equivalent Java parameter types (these must be whitelisted as well), a closing * parenthesis, and a newline. </li> * <li>A field may be specified starting with a Painless type name for the equivalent Java type * of the field, followed by the Java name of the field (which all be the Painless name * for the field), and a newline. </li> * </ul> * <li> Annotations may be added starting with an at, followed by a name, optionally an opening brace, * a parameter name, an equals, an opening quote, an argument value, a closing quote, (possibly repeated * for multiple arguments,) and a closing brace. Multiple annotations may be added after a class (before * the opening bracket), after a method, or after field. </li> * </ul> * * Note there must be a one-to-one correspondence of Painless type names to Java type/
names
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/propagation/MdcLegacyFilter.java
{ "start": 682, "end": 1320 }
class ____ implements HttpServerFilter { @Override public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) { try { String trackingId = request.getHeaders().get("X-TrackingId"); MDC.put("trackingId", trackingId); try (PropagatedContext.Scope ignore = PropagatedContext.get().plus(new MdcPropagationContext()).propagate()) { return chain.proceed(request); } } finally { MDC.remove("trackingId"); } } } // end::class[]
MdcLegacyFilter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/access/PropertyAccessMemberTest.java
{ "start": 948, "end": 1972 }
class ____ { @Test public void testPropertyAccessMember(SessionFactoryScope scope) { scope.inTransaction( entityManager -> { final Metamodel metaModel = entityManager.getMetamodel(); final ManagedType<PropertyEntity> managedType = metaModel.managedType( PropertyEntity.class ); final Attribute<PropertyEntity, ?> attribute = managedType.getDeclaredAttribute( "total" ); final Member member = attribute.getJavaMember(); assertEquals( "getTotal", member.getName() ); } ); } @Test public void testFieldAccessMember(SessionFactoryScope scope) { scope.inTransaction( entityManager -> { final Metamodel metaModel = entityManager.getMetamodel(); final ManagedType<FieldEntity> managedType = metaModel.managedType( FieldEntity.class ); final Attribute<FieldEntity, ?> attribute = managedType.getDeclaredAttribute( "total" ); final Member member = attribute.getJavaMember(); assertEquals( "total", member.getName() ); } ); } @Entity(name = "PropertyEntity") static
PropertyAccessMemberTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/BaseMappedSuperclass.java
{ "start": 257, "end": 540 }
class ____ { @Id protected Long id; protected String value; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
BaseMappedSuperclass
java
elastic__elasticsearch
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/direct/GetDatabaseConfigurationAction.java
{ "start": 1792, "end": 2141 }
class ____ extends ActionType<Response> { public static final GetDatabaseConfigurationAction INSTANCE = new GetDatabaseConfigurationAction(); public static final String NAME = "cluster:admin/ingest/geoip/database/get"; protected GetDatabaseConfigurationAction() { super(NAME); } public static
GetDatabaseConfigurationAction
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TearDownNotRunTest.java
{ "start": 3949, "end": 4478 }
interface ____ {}\ """) .doTest(); } @Test public void positiveCase_customAnnotationDifferentName() { compilationHelper .addSourceLines( "JUnit4TearDownNotRunPositiveCaseCustomAfter2.java", """ package com.google.errorprone.bugpatterns.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test case with a custom After annotation. */ @RunWith(JUnit4.class) public
After
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/internal/OrmAnnotationHelper.java
{ "start": 945, "end": 3413 }
class ____ { public static void forEachOrmAnnotation(Consumer<AnnotationDescriptor<?>> consumer) { JpaAnnotations.forEachAnnotation( consumer ); HibernateAnnotations.forEachAnnotation( consumer ); DialectOverrideAnnotations.forEachAnnotation( consumer ); XmlAnnotations.forEachAnnotation( consumer ); } public static void forEachOrmAnnotation(Class<?> declarer, Consumer<AnnotationDescriptor<?>> consumer) { for ( Field field : declarer.getFields() ) { if ( AnnotationDescriptor.class.isAssignableFrom( field.getType() ) ) { try { consumer.accept( (AnnotationDescriptor<?>) field.get( null ) ); } catch (IllegalAccessException e) { throw new AnnotationAccessException( String.format( Locale.ROOT, "Unable to access standard annotation descriptor field - %s", field.getName() ), e ); } } } } public static <V, A extends Annotation> V extractJdkValue(A jdkAnnotation, AttributeDescriptor<V> attributeDescriptor, ModelsContext modelContext) { return attributeDescriptor .getTypeDescriptor() .createJdkValueExtractor( modelContext ) .extractValue( jdkAnnotation, attributeDescriptor, modelContext ); } public static <V, A extends Annotation> V extractJdkValue(A jdkAnnotation, AnnotationDescriptor<A> annotationDescriptor, String attributeName, ModelsContext modelContext) { final AttributeDescriptor<V> attributeDescriptor = annotationDescriptor.getAttribute( attributeName ); return extractJdkValue( jdkAnnotation, attributeDescriptor, modelContext ); } public static List<Annotation> extractAnnotationTypeAnnotations(Class<? extends Annotation> annotationType) { final ArrayList<Annotation> result = new ArrayList<>(); final Annotation[] annotationTypeAnnotations = annotationType.getAnnotations(); for ( int i = 0; i < annotationTypeAnnotations.length; i++ ) { final Annotation annotationTypeAnnotation = annotationTypeAnnotations[i]; final Class<? extends Annotation> annotationTypeAnnotationType = annotationTypeAnnotation.annotationType(); // skip a few well-know ones that are irrelevant if ( annotationTypeAnnotationType == Repeatable.class || annotationTypeAnnotationType == Target.class || annotationTypeAnnotationType == Retention.class || annotationTypeAnnotationType == Documented.class ) { continue; } result.add( annotationTypeAnnotation ); } return result; } }
OrmAnnotationHelper
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/support/AbstractPlatformTransactionManager.java
{ "start": 1815, "end": 2034 }
class ____ implements Spring's standard transaction workflow, * serving as basis for concrete platform transaction managers like * {@link org.springframework.transaction.jta.JtaTransactionManager}. * * <p>This base
that
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/tests/StreamsUpgradeTest.java
{ "start": 3509, "end": 6716 }
class ____ { public static void main(final String[] args) throws Exception { if (args.length < 1) { System.err.println("StreamsUpgradeTest requires one argument (properties-file) but no provided: "); } final String propFileName = args.length > 0 ? args[0] : null; final Properties streamsProperties = Utils.loadProps(propFileName); System.out.println("StreamsTest instance started (StreamsUpgradeTest trunk)"); System.out.println("props=" + streamsProperties); final KafkaStreams streams = buildStreams(streamsProperties); streams.start(); Exit.addShutdownHook("streams-shutdown-hook", () -> { System.out.println("closing Kafka Streams instance"); System.out.flush(); streams.close(); System.out.println("UPGRADE-TEST-CLIENT-CLOSED"); System.out.flush(); }); } public static KafkaStreams buildStreams(final Properties streamsProperties) { final StreamsBuilder builder = new StreamsBuilder(); final KTable<String, Integer> dataTable = builder.table( "data", Consumed.with(stringSerde, intSerde)); final KStream<String, Integer> dataStream = dataTable.toStream(); dataStream.process(SmokeTestUtil.printProcessorSupplier("data")); dataStream.to("echo"); final boolean runFkJoin = Boolean.parseBoolean(streamsProperties.getProperty( "test.run_fk_join", "false")); if (runFkJoin) { try { final KTable<Integer, String> fkTable = builder.table( "fk", Consumed.with(intSerde, stringSerde)); buildFKTable(dataStream, fkTable); } catch (final Exception e) { System.err.println("Caught " + e.getMessage()); } } final Properties config = new Properties(); config.setProperty(StreamsConfig.APPLICATION_ID_CONFIG, "StreamsUpgradeTest"); config.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000L); config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.ByteArraySerde.class.getName()); config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.ByteArraySerde.class.getName()); final KafkaClientSupplier kafkaClientSupplier; if (streamsProperties.containsKey("test.future.metadata")) { kafkaClientSupplier = new FutureKafkaClientSupplier(); } else { kafkaClientSupplier = new DefaultKafkaClientSupplier(); } config.putAll(streamsProperties); return new KafkaStreams(builder.build(), config, kafkaClientSupplier); } private static void buildFKTable(final KStream<String, Integer> primaryTable, final KTable<Integer, String> otherTable) { final KStream<String, String> kStream = primaryTable.toTable() .join(otherTable, v -> v, (k0, v0) -> v0) .toStream(); kStream.process(SmokeTestUtil.printProcessorSupplier("fk")); kStream.to("fk-result", Produced.with(stringSerde, stringSerde)); } private static
StreamsUpgradeTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/OnDeleteAction.java
{ "start": 457, "end": 1918 }
enum ____ { /** * No action. The default. An error is raised if rows still reference * the parent when the constraint is checked, possibly later in the * transaction. */ NO_ACTION, /** * Cascade deletion of the parent to the child. * <p> * Produces a foreign key constraint with {@code on delete cascade}. */ CASCADE, /** * Prevents deletion of the parent by raising an error immediately. * <p> * Produces a foreign key constraint with {@code on delete restrict}. * * @since 6.2 */ RESTRICT, /** * Set the referencing foreign key to null. * <p> * Produces a foreign key constraint with {@code on delete set null}. * * @since 6.2 */ SET_NULL, /** * Set the referencing foreign key to its default value. * <p> * Produces a foreign key constraint with {@code on delete set default}. * * @since 6.2 */ SET_DEFAULT; public String getAlternativeName() { return toString().toLowerCase(ROOT).replace('_', '-'); } public String toSqlString() { return toString().toLowerCase(ROOT).replace('_', ' '); } public static OnDeleteAction fromExternalForm(Object value) { if ( value == null ) { return null; } else if ( value instanceof OnDeleteAction onDeleteAction ) { return onDeleteAction; } else { final String valueString = value.toString(); try { return valueOf( valueString ); } catch (IllegalArgumentException e) { // the name did not match the
OnDeleteAction
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/common/state/ValueState.java
{ "start": 1573, "end": 2923 }
interface ____<T> extends State { /** * Returns the current value for the state. When the state is not partitioned the returned value * is the same for all inputs in a given operator instance. If state partitioning is applied, * the value returned depends on the current operator input, as the operator maintains an * independent state for each partition. * * <p>If you didn't specify a default value when creating the ValueStateDescriptor this will * return {@code null} when no value was previously set using {@link #update(Object)}. * * @return The state value corresponding to the current input. * @throws IOException Thrown if the system cannot access the state. */ T value() throws IOException; /** * Updates the operator state accessible by {@link #value()} to the given value. The next time * {@link #value()} is called (for the same state partition) the returned state will represent * the updated value. When a partitioned state is updated with {@code null}, the state for the * current key will be removed and the default value is returned on the next access. * * @param value The new value for the state. * @throws IOException Thrown if the system cannot access the state. */ void update(T value) throws IOException; }
ValueState
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/parser/EvaluatedExpressionParser.java
{ "start": 992, "end": 1356 }
interface ____ permits SingleEvaluatedExpressionParser, CompoundEvaluatedExpressionParser { /** * Parse expression into AST. * * @return expression AST * @throws ExpressionParsingException when expression violates syntactic rules */ @NonNull ExpressionNode parse() throws ExpressionParsingException; }
EvaluatedExpressionParser
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/hive/visitor/HiveSchemaStatVisitor.java
{ "start": 1632, "end": 4268 }
class ____ extends SchemaStatVisitor implements HiveASTVisitor { public HiveSchemaStatVisitor() { super(DbType.hive); } public HiveSchemaStatVisitor(DbType dbType) { super(dbType); } public HiveSchemaStatVisitor(SchemaRepository repository) { super(repository); } @Override public boolean visit(HiveInsert x) { setMode(x, TableStat.Mode.Insert); SQLExprTableSource tableSource = x.getTableSource(); SQLExpr tableName = tableSource != null ? tableSource.getExpr() : null; if (tableName instanceof SQLName) { TableStat stat = getTableStat((SQLName) tableName); stat.incrementInsertCount(); } for (SQLAssignItem partition : x.getPartitions()) { partition.accept(this); } accept(x.getQuery()); return false; } @Override public boolean visit(HiveMultiInsertStatement x) { if (repository != null && x.getParent() == null) { repository.resolve(x); } return true; } @Override public boolean visit(HiveInsertStatement x) { if (repository != null && x.getParent() == null) { repository.resolve(x); } SQLWithSubqueryClause with = x.getWith(); if (with != null) { with.accept(this); } setMode(x, TableStat.Mode.Insert); SQLExprTableSource tableSource = x.getTableSource(); SQLExpr tableName = tableSource.getExpr(); if (tableName instanceof SQLName) { TableStat stat = getTableStat((SQLName) tableName); stat.incrementInsertCount(); List<SQLExpr> columns = x.getColumns(); for (SQLExpr column : columns) { if (column instanceof SQLIdentifierExpr) { addColumn((SQLName) tableName, ((SQLIdentifierExpr) column).normalizedName()); } } } for (SQLAssignItem partition : x.getPartitions()) { partition.accept(this); } accept(x.getQuery()); return false; } @Override public boolean visit(HiveCreateFunctionStatement x) { return false; } @Override public boolean visit(HiveLoadDataStatement x) { TableStat tableStat = getTableStat(x.getInto()); if (tableStat != null) { tableStat.incrementInsertCount(); } return false; } @Override public boolean visit(HiveMsckRepairStatement x) { return false; } }
HiveSchemaStatVisitor
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/access/MBeanProxyFactoryBean.java
{ "start": 1609, "end": 1774 }
interface ____ matched by a * corresponding property or method in the proxy interface. * * <p>Attempting to invoke or access any method or property on the proxy *
is
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
{ "start": 1858, "end": 2168 }
class ____ to test StringUtils#equals(CharSequence, CharSequence) // with a CharSequence implementation whose equals(Object) override requires that the // other object be an instance of CustomCharSequence, even though, as char sequences, // `seq` may equal the other object. private static final
is
java
quarkusio__quarkus
core/builder/src/main/java/io/quarkus/builder/item/SimpleBuildItem.java
{ "start": 121, "end": 254 }
class ____ extends BuildItem { /** * Construct a new instance. */ protected SimpleBuildItem() { } }
SimpleBuildItem
java
apache__thrift
lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java
{ "start": 236, "end": 716 }
class ____ { @Test public void testRaisesExceptionWhenUsedConcurrently() throws Exception { TAsyncClientManager mockClientManager = new TAsyncClientManager() { @Override public void call(TAsyncMethodCall method) throws TException { // do nothing } }; Srv.AsyncClient c = new AsyncClient(null, mockClientManager, null); c.Janky(0, null); assertThrows(Exception.class, c::checkReady); } }
TestTAsyncClient
java
apache__flink
flink-yarn/src/test/java/org/apache/flink/yarn/YarnClusterDescriptorTest.java
{ "start": 4141, "end": 51347 }
class ____ { private static final int YARN_MAX_VCORES = 16; private static YarnConfiguration yarnConfiguration; private static YarnClient yarnClient; private final ClusterSpecification clusterSpecification = new ClusterSpecification.ClusterSpecificationBuilder() .setSlotsPerTaskManager(Integer.MAX_VALUE) .createClusterSpecification(); private final ApplicationConfiguration appConfig = new ApplicationConfiguration(new String[0], null); @TempDir java.nio.file.Path temporaryFolder; private File flinkJar; @BeforeAll static void setupClass() { yarnConfiguration = new YarnConfiguration(); yarnClient = YarnClient.createYarnClient(); yarnClient.init(yarnConfiguration); yarnClient.start(); } @BeforeEach void beforeTest() throws IOException { flinkJar = Files.createTempFile(temporaryFolder, "flink", ".jar").toFile(); } @AfterAll static void tearDownClass() { yarnClient.stop(); } @Test void testFailIfTaskSlotsHigherThanMaxVcores() throws ClusterDeploymentException { final Configuration flinkConfiguration = new Configuration(); YarnClusterDescriptor clusterDescriptor = createYarnClusterDescriptor(flinkConfiguration); clusterDescriptor.setLocalJarPath(new Path(flinkJar.getPath())); try { clusterDescriptor.deploySessionCluster(clusterSpecification); fail("The deploy call should have failed."); } catch (ClusterDeploymentException e) { // we expect the cause to be an IllegalConfigurationException if (!(e.getCause() instanceof IllegalConfigurationException)) { throw e; } } finally { clusterDescriptor.close(); } } @Test void testConfigOverwrite() throws ClusterDeploymentException { Configuration configuration = new Configuration(); // overwrite vcores in config configuration.set(YarnConfigOptions.VCORES, Integer.MAX_VALUE); YarnClusterDescriptor clusterDescriptor = createYarnClusterDescriptor(configuration); clusterDescriptor.setLocalJarPath(new Path(flinkJar.getPath())); // configure slots ClusterSpecification clusterSpecification = new ClusterSpecification.ClusterSpecificationBuilder().createClusterSpecification(); try { clusterDescriptor.deploySessionCluster(clusterSpecification); fail("The deploy call should have failed."); } catch (ClusterDeploymentException e) { // we expect the cause to be an IllegalConfigurationException if (!(e.getCause() instanceof IllegalConfigurationException)) { throw e; } } finally { clusterDescriptor.close(); } } @Test void testSetupApplicationMasterContainer() { Configuration cfg = new Configuration(); YarnClusterDescriptor clusterDescriptor = createYarnClusterDescriptor(cfg); final JobManagerProcessSpec jobManagerProcessSpec = createDefaultJobManagerProcessSpec(1024); final String java = "$JAVA_HOME/bin/java"; final String jvmmem = JobManagerProcessUtils.generateJvmParametersStr(jobManagerProcessSpec, cfg); final String dynamicParameters = JobManagerProcessUtils.generateDynamicConfigsStr(jobManagerProcessSpec); final String defaultJvmOpts = "-DdefaultJvm"; // if set final String jvmOpts = "-Djvm"; // if set final String defaultJmJvmOpts = "-DdefaultJmJvm"; // if set final String jmJvmOpts = "-DjmJvm"; // if set final String krb5 = "-Djava.security.krb5.conf=krb5.conf"; final String logfile = "-Dlog.file=\"" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/jobmanager.log\""; // if set final String logback = "-Dlogback.configurationFile=file:" + YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME; // if set final String log4j = "-Dlog4j.configuration=file:" + YarnLogConfigUtil.CONFIG_FILE_LOG4J_NAME + " -Dlog4j.configurationFile=file:" + YarnLogConfigUtil.CONFIG_FILE_LOG4J_NAME; // if set final String mainClass = clusterDescriptor.getYarnSessionClusterEntrypoint(); final String redirects = "1> " + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/jobmanager.out " + "2> " + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/jobmanager.err"; try { // no logging, with/out krb5 assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, false, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, mainClass, dynamicParameters, redirects)); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, mainClass, dynamicParameters, redirects)); // logback only, with/out krb5 cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, false, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, logfile, logback, mainClass, dynamicParameters, redirects)); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, logfile, logback, mainClass, dynamicParameters, redirects)); // log4j, with/out krb5 cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOG4J_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, false, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, logfile, log4j, mainClass, dynamicParameters, redirects)); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOG4J_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, logfile, log4j, mainClass, dynamicParameters, redirects)); // logback, with/out krb5 cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, false, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, logfile, logback, mainClass, dynamicParameters, redirects)); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, logfile, logback, mainClass, dynamicParameters, redirects)); // logback, with/out krb5, different JVM opts // IMPORTANT: Be aware that we are using side effects here to modify the created // YarnClusterDescriptor, // because we have a reference to the ClusterDescriptor's configuration which we modify // continuously cfg.set(CoreOptions.FLINK_DEFAULT_JVM_OPTIONS, defaultJvmOpts); cfg.set(CoreOptions.FLINK_JVM_OPTIONS, jvmOpts); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, false, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, defaultJvmOpts, jvmOpts, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, logfile, logback, mainClass, dynamicParameters, redirects)); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, defaultJvmOpts, jvmOpts, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, logfile, logback, mainClass, dynamicParameters, redirects)); // log4j, with/out krb5, different JVM opts // IMPORTANT: Be aware that we are using side effects here to modify the created // YarnClusterDescriptor cfg.set(CoreOptions.FLINK_DEFAULT_JM_JVM_OPTIONS, defaultJmJvmOpts); cfg.set(CoreOptions.FLINK_JM_JVM_OPTIONS, jmJvmOpts); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOG4J_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, false, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, defaultJvmOpts, jvmOpts, defaultJmJvmOpts, jmJvmOpts, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, logfile, log4j, mainClass, dynamicParameters, redirects)); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOG4J_NAME); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, jvmmem, defaultJvmOpts, jvmOpts, defaultJmJvmOpts, jmJvmOpts, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, logfile, log4j, mainClass, dynamicParameters, redirects)); // now try some configurations with different yarn.container-start-command-template // IMPORTANT: Be aware that we are using side effects here to modify the created // YarnClusterDescriptor cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); cfg.set( YARN_CONTAINER_START_COMMAND_TEMPLATE, "%java% 1 %jvmmem% 2 %jvmopts% 3 %logging% 4 %class% 5 %args% 6 %redirects%"); assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, "1", jvmmem, "2", defaultJvmOpts, jvmOpts, defaultJmJvmOpts, jmJvmOpts, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, "3", logfile, logback, "4", mainClass, "5", dynamicParameters, "6", redirects)); cfg.set( YarnConfigOptionsInternal.APPLICATION_LOG_CONFIG_FILE, YarnLogConfigUtil.CONFIG_FILE_LOGBACK_NAME); cfg.set( YARN_CONTAINER_START_COMMAND_TEMPLATE, "%java% %logging% %jvmopts% %jvmmem% %class% %args% %redirects%"); // IMPORTANT: Be aware that we are using side effects here to modify the created // YarnClusterDescriptor assertThat( clusterDescriptor .setupApplicationMasterContainer( mainClass, true, jobManagerProcessSpec) .getCommands() .get(0)) .isEqualTo( String.join( " ", java, logfile, logback, defaultJvmOpts, jvmOpts, defaultJmJvmOpts, jmJvmOpts, YarnClusterDescriptor.IGNORE_UNRECOGNIZED_VM_OPTIONS, krb5, jvmmem, mainClass, dynamicParameters, redirects)); } finally { clusterDescriptor.close(); } } /** Tests to ship files through the {@code YarnClusterDescriptor.addShipFiles}. */ @Test void testExplicitFileShipping() throws Exception { try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) { descriptor.setLocalJarPath(new Path("/path/to/flink.jar")); File libFile = Files.createTempFile(temporaryFolder, "libFile", ".jar").toFile(); File libFolder = Files.createTempDirectory(temporaryFolder, UUID.randomUUID().toString()) .toFile(); assertThat(descriptor.getShipFiles()) .doesNotContain(getPathFromLocalFile(libFile), getPathFromLocalFile(libFolder)); List<Path> shipFiles = new ArrayList<>(); shipFiles.add(getPathFromLocalFile(libFile)); shipFiles.add(getPathFromLocalFile(libFolder)); descriptor.addShipFiles(shipFiles); assertThat(descriptor.getShipFiles()) .contains(getPathFromLocalFile(libFile), getPathFromLocalFile(libFolder)); // only execute part of the deployment to test for shipped files Set<Path> effectiveShipFiles = new HashSet<>(); descriptor.addLibFoldersToShipFiles(effectiveShipFiles); assertThat(effectiveShipFiles).isEmpty(); assertThat(descriptor.getShipFiles()) .hasSize(2) .contains(getPathFromLocalFile(libFile), getPathFromLocalFile(libFolder)); } } /** Tests to ship files through the {@link YarnConfigOptions#SHIP_FILES}. */ @Test void testShipFiles() throws IOException { String hdfsDir = "hdfs:///flink/hdfs_dir"; String hdfsFile = "hdfs:///flink/hdfs_file"; File libFile = Files.createTempFile(temporaryFolder, "libFile", ".jar").toFile(); File libFolder = Files.createTempDirectory(temporaryFolder, UUID.randomUUID().toString()).toFile(); final org.apache.hadoop.conf.Configuration hdConf = new org.apache.hadoop.conf.Configuration(); hdConf.set( MiniDFSCluster.HDFS_MINIDFS_BASEDIR, temporaryFolder.toAbsolutePath().toString()); try (final MiniDFSCluster hdfsCluster = new MiniDFSCluster.Builder(hdConf).build()) { final org.apache.hadoop.fs.Path hdfsRootPath = new org.apache.hadoop.fs.Path(hdfsCluster.getURI()); hdfsCluster.getFileSystem().mkdirs(new org.apache.hadoop.fs.Path(hdfsDir)); hdfsCluster.getFileSystem().createNewFile(new org.apache.hadoop.fs.Path(hdfsFile)); Configuration flinkConfiguration = new Configuration(); flinkConfiguration.set( YarnConfigOptions.SHIP_FILES, Arrays.asList( libFile.getAbsolutePath(), libFolder.getAbsolutePath(), hdfsDir, hdfsFile)); final YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.set( CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, hdfsRootPath.toString()); YarnClusterDescriptor descriptor = createYarnClusterDescriptor(flinkConfiguration, yarnConfig); assertThat(descriptor.getShipFiles()) .containsExactly( getPathFromLocalFile(libFile), getPathFromLocalFile(libFolder), new Path(hdfsDir), new Path(hdfsFile)); } } @Test void testEnvironmentLibShipping() throws Exception { testEnvironmentDirectoryShipping(ConfigConstants.ENV_FLINK_LIB_DIR, false); } @Test void testEnvironmentPluginsShipping() throws Exception { testEnvironmentDirectoryShipping(ConfigConstants.ENV_FLINK_PLUGINS_DIR, true); } private void testEnvironmentDirectoryShipping(String environmentVariable, boolean onlyShip) throws Exception { try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) { File libFolder = Files.createTempDirectory(temporaryFolder, UUID.randomUUID().toString()) .toFile(); File libFile = new File(libFolder, "libFile.jar"); assertThat(libFile.createNewFile()).isTrue(); Set<Path> effectiveShipFiles = new HashSet<>(); final Map<String, String> oldEnv = System.getenv(); try { Map<String, String> env = new HashMap<>(1); env.put(environmentVariable, libFolder.getAbsolutePath()); CommonTestUtils.setEnv(env); // only execute part of the deployment to test for shipped files if (onlyShip) { descriptor.addPluginsFoldersToShipFiles(effectiveShipFiles); } else { descriptor.addLibFoldersToShipFiles(effectiveShipFiles); } } finally { CommonTestUtils.setEnv(oldEnv); } // only add the ship the folder, not the contents assertThat(effectiveShipFiles) .doesNotContain(getPathFromLocalFile(libFile)) .contains(getPathFromLocalFile(libFolder)); assertThat(descriptor.getShipFiles()) .doesNotContain(getPathFromLocalFile(libFile), getPathFromLocalFile(libFolder)); } } @Test void testEnvironmentEmptyPluginsShipping() { try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) { File pluginsFolder = Paths.get( temporaryFolder.toFile().getAbsolutePath(), "s0m3_p4th_th4t_sh0uld_n0t_3x1sts") .toFile(); Set<Path> effectiveShipFiles = new HashSet<>(); final Map<String, String> oldEnv = System.getenv(); try { Map<String, String> env = new HashMap<>(1); env.put(ConfigConstants.ENV_FLINK_PLUGINS_DIR, pluginsFolder.getAbsolutePath()); CommonTestUtils.setEnv(env); // only execute part of the deployment to test for shipped files descriptor.addPluginsFoldersToShipFiles(effectiveShipFiles); } finally { CommonTestUtils.setEnv(oldEnv); } assertThat(effectiveShipFiles).isEmpty(); } } @Test void testDisableSystemClassPathIncludeUserJarAndWithIllegalShipDirectoryName() { final Configuration configuration = new Configuration(); configuration.set(CLASSPATH_INCLUDE_USER_JAR, YarnConfigOptions.UserJarInclusion.DISABLED); final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(configuration); java.nio.file.Path p = temporaryFolder.resolve(ConfigConstants.DEFAULT_FLINK_USR_LIB_DIR); p.toFile().mkdir(); assertThatThrownBy( () -> yarnClusterDescriptor.addShipFiles( Collections.singletonList(new Path(p.toString())))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("User-shipped directories configured via :"); } /** Tests that the usrlib will be automatically shipped. */ @Test void testShipUsrLib() throws IOException { final Map<String, String> oldEnv = System.getenv(); final Map<String, String> env = new HashMap<>(1); final File homeFolder = Files.createTempDirectory(temporaryFolder, UUID.randomUUID().toString()).toFile(); final File libFolder = new File(homeFolder.getAbsolutePath(), "lib"); assertThat(libFolder.createNewFile()).isTrue(); final File usrLibFolder = new File(homeFolder.getAbsolutePath(), ConfigConstants.DEFAULT_FLINK_USR_LIB_DIR); assertThat(usrLibFolder.mkdirs()).isTrue(); final File usrLibFile = new File(usrLibFolder, "usrLibFile.jar"); assertThat(usrLibFile.createNewFile()).isTrue(); env.put(ConfigConstants.ENV_FLINK_LIB_DIR, libFolder.getAbsolutePath()); CommonTestUtils.setEnv(env); try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) { final Set<File> effectiveShipFiles = new HashSet<>(); descriptor.addUsrLibFolderToShipFiles(effectiveShipFiles); assertThat(effectiveShipFiles).containsExactlyInAnyOrder(usrLibFolder); } finally { CommonTestUtils.setEnv(oldEnv); } } /** Tests that the {@code YarnConfigOptions.SHIP_ARCHIVES} only supports archive files. */ @Test void testShipArchives() throws IOException { final File homeFolder = Files.createTempDirectory(temporaryFolder, UUID.randomUUID().toString()).toFile(); File dir1 = new File(homeFolder.getPath(), "dir1"); File file1 = new File(homeFolder.getPath(), "file1"); File archive1 = new File(homeFolder.getPath(), "archive1.zip"); File archive2 = new File(homeFolder.getPath(), "archive2.zip"); assertThat(dir1.mkdirs()).isTrue(); assertThat(file1.createNewFile()).isTrue(); assertThat(archive1.createNewFile()).isTrue(); assertThat(archive2.createNewFile()).isTrue(); Configuration flinkConfiguration = new Configuration(); flinkConfiguration.set( YarnConfigOptions.SHIP_ARCHIVES, Arrays.asList(dir1.getAbsolutePath(), archive1.getAbsolutePath())); assertThrows( "Directories or non-archive files are included.", IllegalArgumentException.class, () -> createYarnClusterDescriptor(flinkConfiguration)); flinkConfiguration.set( YarnConfigOptions.SHIP_ARCHIVES, Arrays.asList(file1.getAbsolutePath(), archive1.getAbsolutePath())); assertThrows( "Directories or non-archive files are included.", IllegalArgumentException.class, () -> createYarnClusterDescriptor(flinkConfiguration)); flinkConfiguration.set( YarnConfigOptions.SHIP_ARCHIVES, Arrays.asList(archive1.getAbsolutePath(), archive2.getAbsolutePath())); createYarnClusterDescriptor(flinkConfiguration); String archive3 = "hdfs:///flink/archive3.zip"; final org.apache.hadoop.conf.Configuration hdConf = new org.apache.hadoop.conf.Configuration(); hdConf.set( MiniDFSCluster.HDFS_MINIDFS_BASEDIR, temporaryFolder.toAbsolutePath().toString()); try (final MiniDFSCluster hdfsCluster = new MiniDFSCluster.Builder(hdConf).build()) { final org.apache.hadoop.fs.Path hdfsRootPath = new org.apache.hadoop.fs.Path(hdfsCluster.getURI()); hdfsCluster.getFileSystem().createNewFile(new org.apache.hadoop.fs.Path(archive3)); flinkConfiguration.set( YarnConfigOptions.SHIP_ARCHIVES, Arrays.asList(archive1.getAbsolutePath(), archive3)); final YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.set( CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, hdfsRootPath.toString()); YarnClusterDescriptor descriptor = createYarnClusterDescriptor(flinkConfiguration, yarnConfig); assertThat(descriptor.getShipArchives()) .containsExactly(getPathFromLocalFile(archive1), new Path(archive3)); } } /** Tests that the YarnClient is only shut down if it is not shared. */ @Test void testYarnClientShutDown() { YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(); yarnClusterDescriptor.close(); assertThat(yarnClient.isInState(Service.STATE.STARTED)).isTrue(); final YarnClient closableYarnClient = YarnClient.createYarnClient(); closableYarnClient.init(yarnConfiguration); closableYarnClient.start(); yarnClusterDescriptor = YarnTestUtils.createClusterDescriptorWithLogging( temporaryFolder.toFile().getAbsolutePath(), new Configuration(), yarnConfiguration, closableYarnClient, false); yarnClusterDescriptor.close(); assertThat(closableYarnClient.isInState(Service.STATE.STOPPED)).isTrue(); } @Test void testDeployApplicationClusterWithDeploymentTargetNotCorrectlySet() { final Configuration flinkConfig = new Configuration(); flinkConfig.set( PipelineOptions.JARS, Collections.singletonList("file:///path/of/user.jar")); flinkConfig.set(DeploymentOptions.TARGET, YarnDeploymentTarget.SESSION.getName()); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { assertThrows( "Expected deployment.target=yarn-application", ClusterDeploymentException.class, () -> yarnClusterDescriptor.deployApplicationCluster( clusterSpecification, appConfig)); } } @Test void testGetStagingDirWithoutSpecifyingStagingDir() throws IOException { try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor()) { YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.set("fs.defaultFS", "file://tmp"); FileSystem defaultFileSystem = FileSystem.get(yarnConfig); Path stagingDir = yarnClusterDescriptor.getStagingDir(defaultFileSystem); assertThat(defaultFileSystem.getScheme()).isEqualTo("file"); assertThat(stagingDir.getFileSystem(yarnConfig).getScheme()).isEqualTo("file"); } } @Test void testGetStagingDirWithSpecifyingStagingDir() throws IOException { final Configuration flinkConfig = new Configuration(); flinkConfig.set(YarnConfigOptions.STAGING_DIRECTORY, "file:///tmp/path1"); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.set("fs.defaultFS", "viewfs://hadoop-ns01"); yarnConfig.set("fs.viewfs.mounttable.hadoop-ns01.link./tmp", "file://tmp"); FileSystem defaultFileSystem = FileSystem.get(yarnConfig); Path stagingDir = yarnClusterDescriptor.getStagingDir(defaultFileSystem); assertThat(defaultFileSystem.getScheme()).isEqualTo("viewfs"); assertThat(stagingDir.getFileSystem(yarnConfig).getScheme()).isEqualTo("file"); } } @Test void testDeployApplicationClusterWithMultipleJarsSet() { final Configuration flinkConfig = new Configuration(); flinkConfig.set( PipelineOptions.JARS, Arrays.asList("local:///path/of/user.jar", "local:///user2.jar")); flinkConfig.set(DeploymentOptions.TARGET, YarnDeploymentTarget.APPLICATION.getName()); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { assertThrows( "Should only have at most one jar", IllegalArgumentException.class, () -> yarnClusterDescriptor.deployApplicationCluster( clusterSpecification, appConfig)); } } private YarnClusterDescriptor createYarnClusterDescriptor() { return createYarnClusterDescriptor(new Configuration()); } private YarnClusterDescriptor createYarnClusterDescriptor(Configuration configuration) { YarnTestUtils.configureLogFile(configuration, temporaryFolder.toFile().getAbsolutePath()); return this.createYarnClusterDescriptor(configuration, yarnConfiguration); } private YarnClusterDescriptor createYarnClusterDescriptor( Configuration configuration, YarnConfiguration yarnConfiguration) { YarnTestUtils.configureLogFile(configuration, temporaryFolder.toFile().getAbsolutePath()); return YarnClusterDescriptorBuilder.newBuilder(yarnClient, true) .setFlinkConfiguration(configuration) .setYarnConfiguration(yarnConfiguration) .setYarnClusterInformationRetriever(() -> YARN_MAX_VCORES) .build(); } @Test public void testGenerateApplicationMasterEnv(@TempDir File flinkHomeDir) throws IOException { final String fakeLocalFlinkJar = "./lib/flink_dist.jar"; final String fakeClassPath = fakeLocalFlinkJar + ":./usrlib/user.jar"; final ApplicationId appId = ApplicationId.newInstance(0, 0); final Configuration flinkConfig = new Configuration(); flinkConfig.set(CoreOptions.FLINK_JAVA_HOME, "/opt/jdk"); final Map<String, String> masterEnv = getTestMasterEnv( flinkConfig, flinkHomeDir, fakeClassPath, fakeLocalFlinkJar, appId); assertThat(masterEnv) .containsEntry(ConfigConstants.ENV_JAVA_HOME, "/opt/jdk") .containsEntry(ConfigConstants.ENV_FLINK_LIB_DIR, "./lib") .containsEntry(YarnConfigKeys.ENV_APP_ID, appId.toString()) .containsEntry( YarnConfigKeys.FLINK_YARN_FILES, YarnApplicationFileUploader.getApplicationDirPath( new Path(flinkHomeDir.getPath()), appId) .toString()) .containsEntry(YarnConfigKeys.ENV_FLINK_CLASSPATH, fakeClassPath); assertThat(masterEnv.get(YarnConfigKeys.ENV_CLIENT_SHIP_FILES)).isEmpty(); assertThat(masterEnv) .containsEntry(YarnConfigKeys.FLINK_DIST_JAR, fakeLocalFlinkJar) .containsEntry(YarnConfigKeys.ENV_CLIENT_HOME_DIR, flinkHomeDir.getPath()); } @Test public void testContainerEnvJavaHomeNotOverriddenByDefault(@TempDir File flinkHomeDir) throws IOException { final Configuration flinkConfig = new Configuration(); final Map<String, String> masterEnv = getTestMasterEnv( flinkConfig, flinkHomeDir, "", "./lib/flink_dist.jar", ApplicationId.newInstance(0, 0)); assertThat(masterEnv).doesNotContainKey(ConfigConstants.ENV_JAVA_HOME); } @Test public void testEnvFlinkLibDirVarNotOverriddenByContainerEnv(@TempDir File tmpDir) throws IOException { final Configuration flinkConfig = new Configuration(); flinkConfig.setString( ResourceManagerOptions.CONTAINERIZED_MASTER_ENV_PREFIX + ConfigConstants.ENV_FLINK_LIB_DIR, "fake_path"); final Map<String, String> masterEnv = getTestMasterEnv( flinkConfig, tmpDir, "", "./lib/flink_dist.jar", ApplicationId.newInstance(0, 0)); assertThat(masterEnv).containsEntry(ConfigConstants.ENV_FLINK_LIB_DIR, "./lib"); } private Map<String, String> getTestMasterEnv( Configuration flinkConfig, File flinkHomeDir, String fakeClassPath, String fakeLocalFlinkJar, ApplicationId appId) throws IOException { try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { final YarnApplicationFileUploader yarnApplicationFileUploader = YarnApplicationFileUploader.from( FileSystem.get(new YarnConfiguration()), new Path(flinkHomeDir.getPath()), new ArrayList<>(), appId, DFSConfigKeys.DFS_REPLICATION_DEFAULT); return yarnClusterDescriptor.generateApplicationMasterEnv( yarnApplicationFileUploader, fakeClassPath, fakeLocalFlinkJar, appId.toString()); } } @Test public void testSetTokensForYarnAppMaster() { final Configuration flinkConfig = new Configuration(); flinkConfig.set( APP_MASTER_TOKEN_SERVICES, Arrays.asList(TestYarnAMDelegationTokenProvider.SERVICE_NAME)); YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig); ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); try { yarnClusterDescriptor.setTokensFor(amContainer, true); Credentials credentials = new Credentials(); try (DataInputStream dis = new DataInputStream( new ByteArrayInputStream(amContainer.getTokens().array()))) { credentials.readTokenStorageStream(dis); } assertThat(credentials.getAllTokens()) .hasSize(1) .contains(TestYarnAMDelegationTokenProvider.TEST_YARN_AM_TOKEN); } catch (Exception e) { fail("Should not throw exception when setting tokens for AM container."); } } @Test void testSetRolledLogConfigs() { final String includePattern = "(jobmanager|taskmanager).*"; final String excludePattern = "(jobmanager|taskmanager)\\.(out|err)"; // Both include and exclude patterns are given. Configuration flinkConfig = new Configuration(); flinkConfig.set(YarnConfigOptions.ROLLED_LOGS_INCLUDE_PATTERN, includePattern); flinkConfig.set(YarnConfigOptions.ROLLED_LOGS_EXCLUDE_PATTERN, excludePattern); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { final TestApplicationSubmissionContext testAppCtx = new TestApplicationSubmissionContext(); yarnClusterDescriptor.setRolledLogConfigs(testAppCtx); assertThat(testAppCtx.logAggregationContext.getRolledLogsIncludePattern()) .isEqualTo(includePattern); assertThat(testAppCtx.logAggregationContext.getRolledLogsExcludePattern()) .isEqualTo(excludePattern); } // Only include pattern is given. flinkConfig = new Configuration(); flinkConfig.set(YarnConfigOptions.ROLLED_LOGS_INCLUDE_PATTERN, includePattern); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { final TestApplicationSubmissionContext testAppCtx = new TestApplicationSubmissionContext(); yarnClusterDescriptor.setRolledLogConfigs(testAppCtx); assertThat(testAppCtx.logAggregationContext.getRolledLogsIncludePattern()) .isEqualTo(includePattern); assertThat(testAppCtx.logAggregationContext.getRolledLogsExcludePattern()).isNull(); } // Only exclude pattern is given. flinkConfig = new Configuration(); flinkConfig.set(YarnConfigOptions.ROLLED_LOGS_EXCLUDE_PATTERN, excludePattern); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { final TestApplicationSubmissionContext testAppCtx = new TestApplicationSubmissionContext(); yarnClusterDescriptor.setRolledLogConfigs(testAppCtx); assertThat(testAppCtx.logAggregationContext.getRolledLogsIncludePattern()).isNull(); assertThat(testAppCtx.logAggregationContext.getRolledLogsExcludePattern()) .isEqualTo(excludePattern); } // Blank values are ignored. flinkConfig = new Configuration(); flinkConfig.set(YarnConfigOptions.ROLLED_LOGS_INCLUDE_PATTERN, " "); flinkConfig.set(YarnConfigOptions.ROLLED_LOGS_EXCLUDE_PATTERN, " "); try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(flinkConfig)) { final TestApplicationSubmissionContext testAppCtx = new TestApplicationSubmissionContext(); yarnClusterDescriptor.setRolledLogConfigs(testAppCtx); assertThat(testAppCtx.logAggregationContext).isNull(); } } private static
YarnClusterDescriptorTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AnnotationMirrorToStringTest.java
{ "start": 879, "end": 1267 }
class ____ { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(AnnotationMirrorToString.class, getClass()); @Test public void refactoring() { testHelper .addInputLines( "Test.java", """ import javax.lang.model.element.AnnotationMirror;
AnnotationMirrorToStringTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MissingParameterNamesFailureAnalyzerTests.java
{ "start": 1254, "end": 4962 }
class ____ { @Test void analyzeWhenMissingParametersExceptionReturnsFailure() throws Exception { MissingParameterNamesFailureAnalyzer analyzer = new MissingParameterNamesFailureAnalyzer(); FailureAnalysis analysis = analyzer.analyze(getSpringFrameworkMissingParameterException()); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) .isEqualTo(String.format("Name for argument of type [java.lang.String] not specified, and parameter name " + "information not available via reflection. Ensure that the compiler uses the '-parameters' flag.:%n")); assertThat(analysis.getAction()).isEqualTo(MissingParameterNamesFailureAnalyzer.ACTION); } @Test void analyzeForMissingParametersWhenMissingParametersExceptionReturnsFailure() throws Exception { FailureAnalysis analysis = MissingParameterNamesFailureAnalyzer .analyzeForMissingParameters(getSpringFrameworkMissingParameterException()); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) .isEqualTo(String.format("Name for argument of type [java.lang.String] not specified, and parameter name " + "information not available via reflection. Ensure that the compiler uses the '-parameters' flag.:%n")); assertThat(analysis.getAction()).isEqualTo(MissingParameterNamesFailureAnalyzer.ACTION); } @Test void analyzeForMissingParametersWhenInCauseReturnsFailure() throws Exception { RuntimeException exception = new RuntimeException("Badness", getSpringFrameworkMissingParameterException()); FailureAnalysis analysis = MissingParameterNamesFailureAnalyzer.analyzeForMissingParameters(exception); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) .isEqualTo(String.format("Name for argument of type [java.lang.String] not specified, and parameter name " + "information not available via reflection. Ensure that the compiler uses the '-parameters' flag.:%n%n" + " Resulting Failure: java.lang.RuntimeException: Badness")); assertThat(analysis.getAction()).isEqualTo(MissingParameterNamesFailureAnalyzer.ACTION); } @Test void analyzeForMissingParametersWhenInSuppressedReturnsFailure() throws Exception { RuntimeException exception = new RuntimeException("Badness"); exception.addSuppressed(getSpringFrameworkMissingParameterException()); FailureAnalysis analysis = MissingParameterNamesFailureAnalyzer.analyzeForMissingParameters(exception); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) .isEqualTo(String.format("Name for argument of type [java.lang.String] not specified, and parameter name " + "information not available via reflection. Ensure that the compiler uses the '-parameters' flag.:%n%n" + " Resulting Failure: java.lang.RuntimeException: Badness")); assertThat(analysis.getAction()).isEqualTo(MissingParameterNamesFailureAnalyzer.ACTION); } @Test void analyzeForMissingParametersWhenNotPresentReturnsNull() { RuntimeException exception = new RuntimeException("Badness"); FailureAnalysis analysis = MissingParameterNamesFailureAnalyzer.analyzeForMissingParameters(exception); assertThat(analysis).isNull(); } private RuntimeException getSpringFrameworkMissingParameterException() throws Exception { MockResolver resolver = new MockResolver(); Method method = getClass().getDeclaredMethod("example", String.class); MethodParameter parameter = new MethodParameter(method, 0); try { resolver.resolveArgument(parameter, null, mock(NativeWebRequest.class), null); } catch (RuntimeException ex) { return ex; } throw new AssertionError("Did not throw"); } void example(String name) { } static
MissingParameterNamesFailureAnalyzerTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateIndexTest1.java
{ "start": 978, "end": 2457 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "create index PFS_PACKAGE_SAMPLE_PID_IND on PFS_PACKAGE_SAMPLE(PACKAGE_ID) tablespace appindx1m"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("PFS_PACKAGE_SAMPLE"))); assertEquals(1, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleCreateIndexTest1
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/DiffableUtils.java
{ "start": 18461, "end": 19091 }
class ____<K, T> implements MapBuilder<K, T, Map<K, T>> { private final Map<K, T> map; JdkMapBuilder(Map<K, T> map) { this.map = new HashMap<>(map); } @Override public void remove(K key) { map.remove(key); } @Override public T get(K key) { return map.get(key); } @Override public void put(K key, T value) { map.put(key, value); } @Override public Map<K, T> build() { return Collections.unmodifiableMap(map); } } private static
JdkMapBuilder
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java
{ "start": 23600, "end": 24358 }
class ____ { } // @formatter:off var configuration = new ParentConfigurationParameters("parent", "parent parameters were used"); var request = builder.applyConfigurationParametersFromSuite(Suite.class) .parentConfigurationParameters(configuration) .build(); // @formatter:on var configurationParameters = request.getConfigurationParameters(); assertEquals(Optional.empty(), configurationParameters.get("parent")); } @Test void selectByIdentifier() { // @formatter:off @Select({ "class:org.junit.platform.suite.engine.SuiteLauncherDiscoveryRequestBuilderTests$NonLocalTestCase", "method:org.junit.platform.suite.engine.SuiteLauncherDiscoveryRequestBuilderTests$NoParameterTestCase#testMethod" }) // @formatter:on
Suite