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
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cache/EntityUpdateCacheModeIgnoreTest.java
{ "start": 3889, "end": 4786 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; @Id private Long purchaseOrderId; private Long customerId; private Long totalAmount; public PurchaseOrder() { } public PurchaseOrder(Long purchaseOrderId, Long customerId, Long totalAmount) { this.purchaseOrderId = purchaseOrderId; this.customerId = customerId; this.totalAmount = totalAmount; } public Long getPurchaseOrderId() { return purchaseOrderId; } public void setPurchaseOrderId(Long purchaseOrderId) { this.purchaseOrderId = purchaseOrderId; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public Long getTotalAmount() { return totalAmount; } public void setTotalAmount(Long totalAmount) { this.totalAmount = totalAmount; } } }
PurchaseOrder
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermarkDeclaration.java
{ "start": 1232, "end": 3314 }
class ____ implements WatermarkDeclaration { private final String identifier; private final WatermarkCombinationPolicy combinationPolicy; private final WatermarkHandlingStrategy defaultHandlingStrategy; public BoolWatermarkDeclaration( String identifier, WatermarkCombinationPolicy combinationPolicy, WatermarkHandlingStrategy defaultHandlingStrategy) { this.identifier = identifier; this.combinationPolicy = combinationPolicy; this.defaultHandlingStrategy = defaultHandlingStrategy; } @Override public String getIdentifier() { return identifier; } /** Creates a new {@link BoolWatermark} with the specified boolean value. */ public BoolWatermark newWatermark(boolean val) { return new BoolWatermark(val, identifier); } public WatermarkCombinationPolicy getCombinationPolicy() { return combinationPolicy; } public WatermarkHandlingStrategy getDefaultHandlingStrategy() { return defaultHandlingStrategy; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BoolWatermarkDeclaration that = (BoolWatermarkDeclaration) o; return Objects.equals(identifier, that.identifier) && Objects.equals(combinationPolicy, that.combinationPolicy) && defaultHandlingStrategy == that.defaultHandlingStrategy; } @Override public int hashCode() { return Objects.hash(identifier, combinationPolicy, defaultHandlingStrategy); } @Override public String toString() { return "BoolWatermarkDeclaration{" + "identifier='" + identifier + '\'' + ", combinationPolicy=" + combinationPolicy + ", defaultHandlingStrategy=" + defaultHandlingStrategy + '}'; } }
BoolWatermarkDeclaration
java
resilience4j__resilience4j
resilience4j-rxjava3/src/test/java/io/github/resilience4j/rxjava3/bulkhead/operator/ObserverBulkheadTest.java
{ "start": 507, "end": 1799 }
class ____ { private Bulkhead bulkhead; @Before public void setUp() { bulkhead = mock(Bulkhead.class, RETURNS_DEEP_STUBS); } @Test public void shouldEmitAllEvents() { given(bulkhead.tryAcquirePermission()).willReturn(true); Observable.fromArray("Event 1", "Event 2") .compose(BulkheadOperator.of(bulkhead)) .test() .assertResult("Event 1", "Event 2"); then(bulkhead).should().onComplete(); } @Test public void shouldPropagateError() { given(bulkhead.tryAcquirePermission()).willReturn(true); Observable.error(new IOException("BAM!")) .compose(BulkheadOperator.of(bulkhead)) .test() .assertError(IOException.class) .assertNotComplete(); then(bulkhead).should().onComplete(); } @Test public void shouldEmitErrorWithBulkheadFullException() { given(bulkhead.tryAcquirePermission()).willReturn(false); Observable.fromArray("Event 1", "Event 2") .compose(BulkheadOperator.of(bulkhead)) .test() .assertError(BulkheadFullException.class) .assertNotComplete(); then(bulkhead).should(never()).onComplete(); } }
ObserverBulkheadTest
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/jira/JiraAccountTests.java
{ "start": 1761, "end": 12426 }
class ____ extends ESTestCase { private HttpClient httpClient; private ClusterSettings clusterSettings; @Before public void init() throws Exception { httpClient = mock(HttpClient.class); clusterSettings = new ClusterSettings(Settings.EMPTY, new HashSet<>(JiraService.getSettings())); } public void testJiraAccountSettings() { final String url = "https://internal-jira.elastic.co:443"; final MockSecureSettings secureSettings = new MockSecureSettings(); SettingsException e = expectThrows(SettingsException.class, () -> new JiraAccount(null, Settings.EMPTY, null)); assertThat(e.getMessage(), containsString("invalid jira [null] account settings. missing required [secure_url] setting")); secureSettings.setString("secure_url", url); Settings settings1 = Settings.builder().setSecureSettings(secureSettings).build(); e = expectThrows(SettingsException.class, () -> new JiraAccount("test", settings1, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. missing required [secure_user] setting")); secureSettings.setString("secure_user", ""); Settings settings2 = Settings.builder().setSecureSettings(secureSettings).build(); e = expectThrows(SettingsException.class, () -> new JiraAccount("test", settings2, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. missing required [secure_user] setting")); secureSettings.setString("secure_user", "foo"); Settings settings3 = Settings.builder().setSecureSettings(secureSettings).build(); e = expectThrows(SettingsException.class, () -> new JiraAccount("test", settings3, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. missing required [secure_password] setting")); secureSettings.setString("secure_password", ""); Settings settings4 = Settings.builder().setSecureSettings(secureSettings).build(); e = expectThrows(SettingsException.class, () -> new JiraAccount("test", settings4, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. missing required [secure_password] setting")); } public void testInvalidSchemeUrl() throws Exception { MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString(JiraAccount.SECURE_URL_SETTING.getKey(), "test"); // Setting test as invalid scheme url secureSettings.setString(JiraAccount.SECURE_USER_SETTING.getKey(), "foo"); secureSettings.setString(JiraAccount.SECURE_PASSWORD_SETTING.getKey(), "password"); Settings settings = Settings.builder().setSecureSettings(secureSettings).build(); SettingsException e = expectThrows(SettingsException.class, () -> new JiraAccount("test", settings, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. invalid [secure_url] setting")); } public void testUnsecureAccountUrl() throws Exception { final MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString(JiraAccount.SECURE_USER_SETTING.getKey(), "foo"); secureSettings.setString(JiraAccount.SECURE_PASSWORD_SETTING.getKey(), "password"); secureSettings.setString(JiraAccount.SECURE_URL_SETTING.getKey(), "http://localhost"); Settings settings = Settings.builder().setSecureSettings(secureSettings).build(); SettingsException e = expectThrows(SettingsException.class, () -> new JiraAccount("test", settings, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. unsecure scheme [HTTP]")); Settings disallowHttp = Settings.builder().put(settings).put("allow_http", false).build(); e = expectThrows(SettingsException.class, () -> new JiraAccount("test", disallowHttp, null)); assertThat(e.getMessage(), containsString("invalid jira [test] account settings. unsecure scheme [HTTP]")); Settings allowHttp = Settings.builder().put(settings).put("allow_http", true).build(); assertNotNull(new JiraAccount("test", allowHttp, null)); } public void testCreateIssueWithError() throws Exception { Settings.Builder builder = Settings.builder(); addAccountSettings("account1", builder); JiraService service = new JiraService(builder.build(), httpClient, clusterSettings); JiraAccount account = service.getAccount("account1"); Tuple<Integer, String> error = randomHttpError(); when(httpClient.execute(any(HttpRequest.class))).thenReturn(new HttpResponse(error.v1())); JiraIssue issue = account.createIssue(emptyMap(), null); assertFalse(issue.successful()); assertThat(issue.getFailureReason(), equalTo(error.v2())); } public void testCreateIssue() throws Exception { Settings.Builder builder = Settings.builder(); addAccountSettings("account1", builder); JiraService service = new JiraService(builder.build(), httpClient, clusterSettings); JiraAccount account = service.getAccount("account1"); ArgumentCaptor<HttpRequest> argumentCaptor = ArgumentCaptor.forClass(HttpRequest.class); when(httpClient.execute(argumentCaptor.capture())).thenReturn(new HttpResponse(HttpStatus.SC_CREATED)); Map<String, Object> fields = singletonMap("key", "value"); JiraIssue issue = account.createIssue(fields, null); assertTrue(issue.successful()); assertNull(issue.getFailureReason()); HttpRequest sentRequest = argumentCaptor.getValue(); assertThat(sentRequest.host(), equalTo("internal-jira.elastic.co")); assertThat(sentRequest.port(), equalTo(443)); assertThat(sentRequest.scheme(), equalTo(Scheme.HTTPS)); assertThat(sentRequest.path(), equalTo(JiraAccount.DEFAULT_PATH)); assertThat(sentRequest.auth(), notNullValue()); assertThat(sentRequest.body(), notNullValue()); } public void testCustomUrls() throws Exception { assertCustomUrl("https://localhost/foo", "/foo"); assertCustomUrl("https://localhost/foo/", "/foo/"); // this ensures we retain backwards compatibility assertCustomUrl("https://localhost/", JiraAccount.DEFAULT_PATH); assertCustomUrl("https://localhost", JiraAccount.DEFAULT_PATH); } private void assertCustomUrl(String urlSettings, String expectedPath) throws IOException { final MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString("secure_url", urlSettings); secureSettings.setString("secure_user", "foo"); secureSettings.setString("secure_password", "bar"); Settings settings = Settings.builder().setSecureSettings(secureSettings).build(); HttpClient client = mock(HttpClient.class); HttpResponse response = new HttpResponse(200); when(client.execute(any())).thenReturn(response); JiraAccount jiraAccount = new JiraAccount("test", settings, client); jiraAccount.createIssue(Collections.emptyMap(), HttpProxy.NO_PROXY); ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class); verify(client, times(1)).execute(captor.capture()); assertThat(captor.getAllValues(), hasSize(1)); HttpRequest request = captor.getValue(); assertThat(request.path(), is(expectedPath)); } @SuppressWarnings("unchecked") private void addAccountSettings(String name, Settings.Builder builder) { final MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString( "xpack.notification.jira.account." + name + "." + JiraAccount.SECURE_URL_SETTING.getKey(), "https://internal-jira.elastic.co:443" ); secureSettings.setString( "xpack.notification.jira.account." + name + "." + JiraAccount.SECURE_USER_SETTING.getKey(), randomAlphaOfLength(10) ); secureSettings.setString( "xpack.notification.jira.account." + name + "." + JiraAccount.SECURE_PASSWORD_SETTING.getKey(), randomAlphaOfLength(10) ); builder.setSecureSettings(secureSettings); Map<String, Object> defaults = randomIssueDefaults(); for (Map.Entry<String, Object> setting : defaults.entrySet()) { String key = "xpack.notification.jira.account." + name + "." + JiraAccount.ISSUE_DEFAULTS_SETTING + "." + setting.getKey(); if (setting.getValue() instanceof String) { builder.put(key, setting.getValue().toString()); } else if (setting.getValue() instanceof Map) { builder.putProperties((Map) setting.getValue(), s -> key + "." + s); } } } public static Map<String, Object> randomIssueDefaults() { Map<String, Object> builder = new HashMap<>(); if (randomBoolean()) { Map<String, Object> project = new HashMap<>(); project.put("project", singletonMap("id", randomAlphaOfLength(10))); builder.putAll(project); } if (randomBoolean()) { Map<String, Object> project = new HashMap<>(); project.put("issuetype", singletonMap("name", randomAlphaOfLength(5))); builder.putAll(project); } if (randomBoolean()) { builder.put("summary", randomAlphaOfLength(10)); } if (randomBoolean()) { builder.put("description", randomAlphaOfLength(50)); } if (randomBoolean()) { int count = randomIntBetween(0, 5); for (int i = 0; i < count; i++) { builder.put("customfield_" + i, randomAlphaOfLengthBetween(5, 10)); } } return Collections.unmodifiableMap(builder); } static Tuple<Integer, String> randomHttpError() { Tuple<Integer, String> error = randomFrom( tuple(400, "Bad Request"), tuple(401, "Unauthorized (authentication credentials are invalid)"), tuple(403, "Forbidden (account doesn't have permission to create this issue)"), tuple(404, "Not Found (account uses invalid JIRA REST APIs)"), tuple(408, "Request Timeout (request took too long to process)"), tuple(500, "JIRA Server Error (internal error occurred while processing request)"), tuple(666, "Unknown Error") ); return error; } }
JiraAccountTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/util/asyncprocessing/AsyncKeyedMultiInputStreamOperatorTestHarness.java
{ "start": 2648, "end": 8408 }
class ____<K, OUT> extends MultiInputStreamOperatorTestHarness<OUT> { /** The executor service for async state processing. */ private final ExecutorService executor; /** Create an instance of the subclass of this class. */ public static <K, OUT, OP extends AsyncKeyedMultiInputStreamOperatorTestHarness<K, OUT>> OP create(FunctionWithException<ExecutorService, OP, Exception> constructor) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<OP> future = new CompletableFuture<>(); executor.execute( () -> { try { future.complete(constructor.apply(executor)); } catch (Exception e) { throw new RuntimeException(e); } }); return future.get(); } public static <K, OUT> AsyncKeyedMultiInputStreamOperatorTestHarness<K, OUT> create( StreamOperatorFactory<OUT> operatorFactory, TypeInformation<K> keyType, List<KeySelector<?, K>> keySelectors, int maxParallelism, int numSubtasks, int subtaskIndex) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<AsyncKeyedMultiInputStreamOperatorTestHarness<K, OUT>> future = new CompletableFuture<>(); executor.execute( () -> { try { future.complete( new AsyncKeyedMultiInputStreamOperatorTestHarness<>( executor, operatorFactory, keyType, keySelectors, maxParallelism, numSubtasks, subtaskIndex)); } catch (Exception e) { throw new RuntimeException(e); } }); return future.get(); } private AsyncKeyedMultiInputStreamOperatorTestHarness( ExecutorService executor, StreamOperatorFactory<OUT> operatorFactory, TypeInformation<K> keyType, List<KeySelector<?, K>> keySelectors, int maxParallelism, int numSubtasks, int subtaskIndex) throws Exception { super(operatorFactory, maxParallelism, numSubtasks, subtaskIndex); config.setStateKeySerializer( keyType.createSerializer(executionConfig.getSerializerConfig())); config.serializeAllConfigs(); for (int i = 0; i < keySelectors.size(); i++) { setKeySelector(i, keySelectors.get(i)); } this.executor = executor; // Make environment record any failure getEnvironment().setExpectedExternalFailureCause(Throwable.class); } public void setKeySelector(int idx, KeySelector<?, K> keySelector) { ClosureCleaner.clean(keySelector, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, false); config.setStatePartitioner(idx, keySelector); config.serializeAllConfigs(); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void processElement(int idx, StreamRecord<?> element) throws Exception { Input input = getCastedOperator().getInputs().get(idx); ThrowingConsumer<StreamRecord<?>, Exception> inputProcessor = RecordProcessorUtils.getRecordProcessor(input); executeAndGet(() -> inputProcessor.accept(element)); } @Override @SuppressWarnings("rawtypes") public void processWatermark(int idx, Watermark mark) throws Exception { Input input = getCastedOperator().getInputs().get(idx); executeAndGet(() -> input.processWatermark(mark)); } @Override @SuppressWarnings("rawtypes") public void processWatermarkStatus(int idx, WatermarkStatus watermarkStatus) throws Exception { Input input = getCastedOperator().getInputs().get(idx); executeAndGet(() -> input.processWatermarkStatus(watermarkStatus)); } @Override @SuppressWarnings("rawtypes") public void processRecordAttributes(int idx, RecordAttributes recordAttributes) throws Exception { Input input = getCastedOperator().getInputs().get(idx); executeAndGet(() -> input.processRecordAttributes(recordAttributes)); } public void drainStateRequests() throws Exception { executeAndGet(() -> drain(operator)); } @Override public void close() throws Exception { executeAndGet(super::close); executor.shutdown(); } private void executeAndGet(RunnableWithException runnable) throws Exception { try { execute( executor, () -> { checkEnvState(); runnable.run(); }) .get(); checkEnvState(); } catch (Exception e) { execute(executor, () -> mockTask.cleanUp(e)).get(); throw unwrapAsyncException(e); } } private void checkEnvState() { if (getEnvironment().getActualExternalFailureCause().isPresent()) { fail( "There is an error on other threads", getEnvironment().getActualExternalFailureCause().get()); } } }
AsyncKeyedMultiInputStreamOperatorTestHarness
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractComparableAssert.java
{ "start": 872, "end": 1327 }
class ____ all implementations of <code>{@link ComparableAssert}</code>. * * @param <SELF> the "self" type of this assertion class. Please read &quot;<a href="http://bit.ly/1IZIRcY" * target="_blank">Emulating * 'self types' using Java Generics to simplify fluent API implementation</a>&quot; for more details. * @param <ACTUAL> the type of the "actual" value. * * @author Alex Ruiz * @author Mikhail Mazursky */ public abstract
for
java
google__dagger
javatests/dagger/internal/codegen/ModuleFactoryGeneratorTest.java
{ "start": 57970, "end": 58608 }
interface ____ {}"); daggerCompiler(module, nonScope) .compile( subject -> { subject.hasErrorCount(0); assertSourceMatchesGolden(subject, "test/MyModule_ProvideStringFactory"); }); } @Test public void testScopedMetadataOnNonStaticProvides() throws Exception { Source module = CompilerTests.javaSource( "test.MyModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Singleton;", "", "@Module", "
NonScope
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestServiceLifecycle.java
{ "start": 14847, "end": 15114 }
class ____ extends AbstractService { private StopInInitService() { super("StopInInitService"); } @Override protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); stop(); } } }
StopInInitService
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/expression/MapExpression.java
{ "start": 1135, "end": 4810 }
class ____ extends Expression { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Expression.class, "MapExpression", MapExpression::readFrom ); private final List<EntryExpression> entryExpressions; private final Map<Expression, Expression> map; private final Map<String, Expression> keyFoldedMap; public MapExpression(Source source, List<Expression> entries) { super(source, entries); int entryCount = entries.size() / 2; this.entryExpressions = new ArrayList<>(entryCount); this.map = new LinkedHashMap<>(entryCount); // create a map with key folded and source removed to make the retrieval of value easier this.keyFoldedMap = new LinkedHashMap<>(entryCount); for (int i = 0; i < entryCount; i++) { Expression key = entries.get(i * 2); Expression value = entries.get(i * 2 + 1); entryExpressions.add(new EntryExpression(key.source(), key, value)); map.put(key, value); if (key instanceof Literal l) { this.keyFoldedMap.put(BytesRefs.toString(l.value()), value); } } } private static MapExpression readFrom(StreamInput in) throws IOException { return new MapExpression( Source.readFrom((StreamInput & PlanStreamInput) in), in.readNamedWriteableCollectionAsList(Expression.class) ); } @Override public void writeTo(StreamOutput out) throws IOException { source().writeTo(out); out.writeNamedWriteableCollection(children()); } @Override public String getWriteableName() { return ENTRY.name; } @Override public MapExpression replaceChildren(List<Expression> newChildren) { return new MapExpression(source(), newChildren); } @Override protected NodeInfo<MapExpression> info() { return NodeInfo.create(this, MapExpression::new, children()); } public List<EntryExpression> entryExpressions() { return entryExpressions; } public Map<Expression, Expression> map() { return map; } public Map<String, Expression> keyFoldedMap() { return keyFoldedMap; } @Override public Nullability nullable() { return Nullability.FALSE; } @Override public DataType dataType() { return UNSUPPORTED; } @Override public int hashCode() { return Objects.hash(entryExpressions); } public Expression get(Object key) { if (key instanceof Expression) { return map.get(key); } else { // the key(literal) could be converted to BytesRef by ConvertStringToByteRef return keyFoldedMap.containsKey(key) ? keyFoldedMap.get(key) : keyFoldedMap.get(foldKey(key)); } } public boolean containsKey(Object key) { return keyFoldedMap.containsKey(key) || keyFoldedMap.containsKey(foldKey(key)); } private BytesRef foldKey(Object key) { return new BytesRef(key.toString()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } MapExpression other = (MapExpression) obj; return Objects.equals(entryExpressions, other.entryExpressions); } @Override public String toString() { String str = entryExpressions.stream().map(String::valueOf).collect(Collectors.joining(", ")); return "{ " + str + " }"; } }
MapExpression
java
mockito__mockito
mockito-core/src/main/java/org/mockito/plugins/MockitoPlugins.java
{ "start": 579, "end": 682 }
interface ____ introduced to help framework integrations. * * @since 2.10.0 */ @NotExtensible public
was
java
apache__camel
components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/producer/KubernetesNodesProducerTest.java
{ "start": 1951, "end": 6555 }
class ____ extends KubernetesTestSupport { KubernetesMockServer server; NamespacedKubernetesClient client; @BindToRegistry("kubernetesClient") public KubernetesClient getClient() { return client; } @Test void listTest() { server.expect().withPath("/api/v1/nodes").andReturn(200, new NodeListBuilder().addNewItem().and().build()).once(); List<?> result = template.requestBody("direct:list", "", List.class); assertEquals(1, result.size()); } @Test void listByLabelsTest() throws Exception { server.expect().withPath("/api/v1/nodes?labelSelector=" + toUrlEncoded("key1=value1,key2=value2")) .andReturn(200, new NodeListBuilder().addNewItem().and().addNewItem().and().addNewItem().and().build()).once(); Exchange ex = template.request("direct:listByLabels", exchange -> { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODES_LABELS, labels); }); List<?> result = ex.getMessage().getBody(List.class); assertEquals(3, result.size()); } @Test void createNodeTest() { ObjectMeta meta = new ObjectMeta(); meta.setName("test"); server.expect().withPath("/api/v1/nodes").andReturn(200, new NodeBuilder().withMetadata(meta).build()).once(); Exchange ex = template.request("direct:createNode", exchange -> { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODES_LABELS, labels); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODE_NAME, "test"); NodeSpec spec = new NodeSpecBuilder().build(); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODE_SPEC, spec); }); Node result = ex.getMessage().getBody(Node.class); assertEquals("test", result.getMetadata().getName()); } @Test void updateNodeTest() { ObjectMeta meta = new ObjectMeta(); meta.setName("test"); server.expect().get().withPath("/api/v1/nodes/test").andReturn(200, new NodeBuilder().build()).once(); server.expect().put().withPath("/api/v1/nodes/test").andReturn(200, new NodeBuilder().withMetadata(meta).build()) .once(); Exchange ex = template.request("direct:updateNode", exchange -> { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODES_LABELS, labels); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODE_NAME, "test"); NodeSpec spec = new NodeSpecBuilder().build(); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODE_SPEC, spec); }); Node result = ex.getMessage().getBody(Node.class); assertEquals("test", result.getMetadata().getName()); } @Test void deleteNode() { Node node1 = new NodeBuilder().withNewMetadata().withName("node1").withNamespace("test").and().build(); server.expect().withPath("/api/v1/nodes/node1").andReturn(200, node1).once(); Exchange ex = template.request("direct:deleteNode", exchange -> exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODE_NAME, "node1")); boolean nodeDeleted = ex.getMessage().getBody(Boolean.class); assertTrue(nodeDeleted); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:list").toF("kubernetes-nodes:///?kubernetesClient=#kubernetesClient&operation=listNodes"); from("direct:listByLabels") .toF("kubernetes-nodes:///?kubernetesClient=#kubernetesClient&operation=listNodesByLabels"); from("direct:createNode").toF("kubernetes-nodes:///?kubernetesClient=#kubernetesClient&operation=createNode"); from("direct:updateNode").toF("kubernetes-nodes:///?kubernetesClient=#kubernetesClient&operation=updateNode"); from("direct:deleteNode").toF("kubernetes-nodes:///?kubernetesClient=#kubernetesClient&operation=deleteNode"); } }; } }
KubernetesNodesProducerTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/SubtypeSensitiveMatchingTests.java
{ "start": 2312, "end": 2377 }
interface ____ extends Serializable { void foo(); }
SerializableFoo
java
quarkusio__quarkus
integration-tests/hibernate-orm-panache/src/main/java/io/quarkus/it/panache/defaultpu/DuplicateEntity.java
{ "start": 272, "end": 741 }
class ____ extends PanacheEntityBase { @Id @GeneratedValue public Integer id; public static <T extends PanacheEntityBase> T findById(Object id) { DuplicateEntity duplicate = new DuplicateEntity(); duplicate.id = (Integer) id; return (T) duplicate; } @Override public void persist() { // Do nothing } public static int update(String query, Parameters params) { return 0; } }
DuplicateEntity
java
google__guice
extensions/dagger-adapter/test/com/google/inject/daggeradapter/IntoMapTest.java
{ "start": 5721, "end": 5808 }
interface ____ { String value() default ""; } @dagger.Module static
CustomMapKey
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/transaction/SessionWithinRequestScopeDisabledTest.java
{ "start": 586, "end": 1880 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyEntity.class, PrefixPhysicalNamingStrategy.class) .addAsResource(EmptyAsset.INSTANCE, "import.sql")) .overrideConfigKey("quarkus.hibernate-orm.request-scoped.enabled", "false"); @Inject Session session; @BeforeEach public void activateRequestContext() { Arc.container().requestContext().activate(); } @Test public void read() { assertThatThrownBy(() -> session .createSelectionQuery("SELECT entity FROM MyEntity entity WHERE name IS NULL", MyEntity.class).getResultCount()) .hasMessageContaining( "Cannot use the EntityManager/Session because no transaction is active"); } @Test public void write() { assertThatThrownBy(() -> session.persist(new MyEntity("john"))) .hasMessageContaining( "Cannot use the EntityManager/Session because no transaction is active"); } @AfterEach public void terminateRequestContext() { Arc.container().requestContext().terminate(); } }
SessionWithinRequestScopeDisabledTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/DeltaFloatAggregatorFunctionSupplier.java
{ "start": 649, "end": 1629 }
class ____ implements AggregatorFunctionSupplier { public DeltaFloatAggregatorFunctionSupplier() { } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { throw new UnsupportedOperationException("non-grouping aggregator is not supported"); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return DeltaFloatGroupingAggregatorFunction.intermediateStateDesc(); } @Override public AggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { throw new UnsupportedOperationException("non-grouping aggregator is not supported"); } @Override public DeltaFloatGroupingAggregatorFunction groupingAggregator(DriverContext driverContext, List<Integer> channels) { return DeltaFloatGroupingAggregatorFunction.create(channels, driverContext); } @Override public String describe() { return "delta of floats"; } }
DeltaFloatAggregatorFunctionSupplier
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java
{ "start": 958, "end": 1649 }
class ____ { private final PercentStyleFormatter formatter = new PercentStyleFormatter(); @Test void formatValue() { assertThat(formatter.print(new BigDecimal(".23"), Locale.US)).isEqualTo("23%"); } @Test void parseValue() throws ParseException { assertThat(formatter.parse("23.56%", Locale.US)).isEqualTo(new BigDecimal(".2356")); } @Test void parseBogusValue() { assertThatExceptionOfType(ParseException.class).isThrownBy(() -> formatter.parse("bogus", Locale.US)); } @Test void parsePercentValueNotLenientFailure() { assertThatExceptionOfType(ParseException.class).isThrownBy(() -> formatter.parse("23.56%bogus", Locale.US)); } }
PercentStyleFormatterTests
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/BuiltInAggregateFunctionTestBase.java
{ "start": 17790, "end": 18843 }
class ____ extends SuccessItem { private final List<Expression> selectExpr; private final List<Expression> groupByExpr; public TableApiTestItem( List<Expression> selectExpr, @Nullable List<Expression> groupByExpr, @Nullable DataType expectedRowType, @Nullable List<Row> expectedRows) { super(expectedRowType, expectedRows); this.selectExpr = selectExpr; this.groupByExpr = groupByExpr; } @Override protected TableResult getResult(TableEnvironment tEnv, Table sourceTable) { if (groupByExpr != null) { return sourceTable .groupBy(groupByExpr.toArray(new Expression[0])) .select(selectExpr.toArray(new Expression[0])) .execute(); } else { return sourceTable.select(selectExpr.toArray(new Expression[0])).execute(); } } } private static
TableApiTestItem
java
quarkusio__quarkus
integration-tests/hibernate-validator-resteasy-reactive/src/main/java/io/quarkus/it/hibernate/validator/HibernateValidatorTestResource.java
{ "start": 6110, "end": 6225 }
class ____ { @SuppressWarnings("unused") private String property; } }
NestedBeanWithoutConstraints
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/co/CoStreamMapTest.java
{ "start": 1898, "end": 5699 }
class ____ implements CoMapFunction<Double, Integer, String> { private static final long serialVersionUID = 1L; @Override public String map1(Double value) { return value.toString(); } @Override public String map2(Integer value) { return value.toString(); } } @Test void testCoMap() throws Exception { CoStreamMap<Double, Integer, String> operator = new CoStreamMap<Double, Integer, String>(new MyCoMap()); TwoInputStreamOperatorTestHarness<Double, Integer, String> testHarness = new TwoInputStreamOperatorTestHarness<Double, Integer, String>(operator); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<Object>(); testHarness.open(); testHarness.processElement1(new StreamRecord<Double>(1.1d, initialTime + 1)); testHarness.processElement1(new StreamRecord<Double>(1.2d, initialTime + 2)); testHarness.processElement1(new StreamRecord<Double>(1.3d, initialTime + 3)); testHarness.processWatermark1(new Watermark(initialTime + 3)); testHarness.processElement1(new StreamRecord<Double>(1.4d, initialTime + 4)); testHarness.processElement1(new StreamRecord<Double>(1.5d, initialTime + 5)); testHarness.processElement2(new StreamRecord<Integer>(1, initialTime + 1)); testHarness.processElement2(new StreamRecord<Integer>(2, initialTime + 2)); testHarness.processWatermark2(new Watermark(initialTime + 2)); testHarness.processElement2(new StreamRecord<Integer>(3, initialTime + 3)); testHarness.processElement2(new StreamRecord<Integer>(4, initialTime + 4)); testHarness.processElement2(new StreamRecord<Integer>(5, initialTime + 5)); expectedOutput.add(new StreamRecord<String>("1.1", initialTime + 1)); expectedOutput.add(new StreamRecord<String>("1.2", initialTime + 2)); expectedOutput.add(new StreamRecord<String>("1.3", initialTime + 3)); expectedOutput.add(new StreamRecord<String>("1.4", initialTime + 4)); expectedOutput.add(new StreamRecord<String>("1.5", initialTime + 5)); expectedOutput.add(new StreamRecord<String>("1", initialTime + 1)); expectedOutput.add(new StreamRecord<String>("2", initialTime + 2)); expectedOutput.add(new Watermark(initialTime + 2)); expectedOutput.add(new StreamRecord<String>("3", initialTime + 3)); expectedOutput.add(new StreamRecord<String>("4", initialTime + 4)); expectedOutput.add(new StreamRecord<String>("5", initialTime + 5)); TestHarnessUtil.assertOutputEquals( "Output was not correct.", expectedOutput, testHarness.getOutput()); } @Test void testOpenClose() throws Exception { CoStreamMap<Double, Integer, String> operator = new CoStreamMap<Double, Integer, String>(new TestOpenCloseCoMapFunction()); TwoInputStreamOperatorTestHarness<Double, Integer, String> testHarness = new TwoInputStreamOperatorTestHarness<Double, Integer, String>(operator); long initialTime = 0L; testHarness.open(); testHarness.processElement1(new StreamRecord<Double>(74d, initialTime)); testHarness.processElement2(new StreamRecord<Integer>(42, initialTime)); testHarness.close(); assertThat(TestOpenCloseCoMapFunction.closeCalled) .as("RichFunction methods where not called.") .isTrue(); assertThat(testHarness.getOutput()).isNotEmpty(); } // This must only be used in one test, otherwise the static fields will be changed // by several tests concurrently private static
MyCoMap
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java
{ "start": 27254, "end": 27615 }
class ____ extends WebSocketHandlerDecorator { public TestWebSocketHandlerDecorator(WebSocketHandler delegate) { super(delegate); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { session.getAttributes().put("decorated", true); super.afterConnectionEstablished(session); } }
TestWebSocketHandlerDecorator
java
spring-projects__spring-boot
module/spring-boot-pulsar/src/dockerTest/java/org/springframework/boot/pulsar/testcontainers/DeprecatedPulsarContainerConnectionDetailsFactoryIntegrationTests.java
{ "start": 3034, "end": 3239 }
class ____ { private final List<String> messages = new ArrayList<>(); @PulsarListener(topics = "test-topic") void processMessage(String message) { this.messages.add(message); } } }
TestListener
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/CustomerInventory.java
{ "start": 159, "end": 585 }
class ____ { private Long id; private String name; private Customer customer; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
CustomerInventory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsInLazyFetchGroupTest.java
{ "start": 2074, "end": 2286 }
class ____ { @Id Long id; String text; @ElementCollection(fetch = FetchType.EAGER) List<String> someStrings; @ElementCollection(fetch = FetchType.EAGER) List<String> someStrings2; } }
StringsEntity
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/xml/XMLEventStreamReader.java
{ "start": 1313, "end": 1631 }
interface ____ wraps a * {@link XMLEventReader}. Useful because the StAX {@link javax.xml.stream.XMLInputFactory} * allows one to create an event reader from a stream reader, but not vice-versa. * * @author Arjen Poutsma * @since 3.0 * @see StaxUtils#createEventStreamReader(javax.xml.stream.XMLEventReader) */
that
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/routing/allocation/MaxRetryAllocationDeciderTests.java
{ "start": 2515, "end": 19235 }
class ____ extends ESAllocationTestCase { private final MaxRetryAllocationDecider decider = new MaxRetryAllocationDecider(); private final AllocationService strategy = new AllocationService( new AllocationDeciders(List.of(decider)), new TestGatewayAllocator(), new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE, EmptySnapshotsInfoService.INSTANCE, TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY ); private ClusterState createInitialClusterState() { Metadata metadata = Metadata.builder() .put(IndexMetadata.builder("idx").settings(settings(IndexVersion.current())).numberOfShards(1).numberOfReplicas(0)) .build(); RoutingTable routingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY) .addAsNew(metadata.getProject().index("idx")) .build(); ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT) .metadata(metadata) .routingTable(routingTable) .nodes(DiscoveryNodes.builder().add(newNode("node1")).add(newNode("node2"))) .build(); assertEquals(clusterState.routingTable().index("idx").size(), 1); assertEquals(clusterState.routingTable().index("idx").shard(0).shard(0).state(), UNASSIGNED); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); assertEquals(clusterState.routingTable().index("idx").size(), 1); assertEquals(clusterState.routingTable().index("idx").shard(0).shard(0).state(), INITIALIZING); return clusterState; } public void testSingleRetryOnIgnore() { ClusterState clusterState = createInitialClusterState(); RoutingTable routingTable = clusterState.routingTable(); final int retries = MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY.get(Settings.EMPTY); // now fail it N-1 times for (int i = 0; i < retries - 1; i++) { ClusterState newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "boom" + i); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); assertEquals(routingTable.index("idx").shard(0).shard(0).state(), INITIALIZING); assertEquals(routingTable.index("idx").shard(0).shard(0).unassignedInfo().failedAllocations(), i + 1); assertThat(routingTable.index("idx").shard(0).shard(0).unassignedInfo().message(), containsString("boom" + i)); } // now we go and check that we are actually stick to unassigned on the next failure ClusterState newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "boom"); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); assertEquals(routingTable.index("idx").shard(0).shard(0).unassignedInfo().failedAllocations(), retries); assertEquals(routingTable.index("idx").shard(0).shard(0).state(), UNASSIGNED); assertThat(routingTable.index("idx").shard(0).shard(0).unassignedInfo().message(), containsString("boom")); // manual resetting of retry count newState = strategy.reroute(clusterState, new AllocationCommands(), false, true, false, ActionListener.noop()).clusterState(); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertEquals(routingTable.index("idx").size(), 1); assertEquals(0, routingTable.index("idx").shard(0).shard(0).unassignedInfo().failedAllocations()); assertEquals(INITIALIZING, routingTable.index("idx").shard(0).shard(0).state()); assertThat(routingTable.index("idx").shard(0).shard(0).unassignedInfo().message(), containsString("boom")); // again fail it N-1 times for (int i = 0; i < retries - 1; i++) { newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "boom"); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); assertEquals(i + 1, routingTable.index("idx").shard(0).shard(0).unassignedInfo().failedAllocations()); assertEquals(INITIALIZING, routingTable.index("idx").shard(0).shard(0).state()); assertThat(routingTable.index("idx").shard(0).shard(0).unassignedInfo().message(), containsString("boom")); } // now we go and check that we are actually stick to unassigned on the next failure newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "boom"); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); assertEquals(retries, routingTable.index("idx").shard(0).shard(0).unassignedInfo().failedAllocations()); assertEquals(UNASSIGNED, routingTable.index("idx").shard(0).shard(0).state()); assertThat(routingTable.index("idx").shard(0).shard(0).unassignedInfo().message(), containsString("boom")); } public void testFailedAllocation() { ClusterState clusterState = createInitialClusterState(); RoutingTable routingTable = clusterState.routingTable(); final int retries = MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY.get(Settings.EMPTY); // now fail it N-1 times for (int i = 0; i < retries - 1; i++) { ClusterState newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "boom" + i); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); ShardRouting unassignedPrimary = routingTable.index("idx").shard(0).shard(0); assertEquals(unassignedPrimary.state(), INITIALIZING); assertEquals(unassignedPrimary.unassignedInfo().failedAllocations(), i + 1); assertThat(unassignedPrimary.unassignedInfo().message(), containsString("boom" + i)); // MaxRetryAllocationDecider#canForceAllocatePrimary should return YES decisions because canAllocate returns YES here assertEquals( Decision.Type.YES, decider.canForceAllocatePrimary(unassignedPrimary, null, newRoutingAllocation(clusterState)).type() ); } // now we go and check that we are actually stick to unassigned on the next failure { ClusterState newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "boom"); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); ShardRouting unassignedPrimary = routingTable.index("idx").shard(0).shard(0); assertEquals(unassignedPrimary.unassignedInfo().failedAllocations(), retries); assertEquals(unassignedPrimary.state(), UNASSIGNED); assertThat(unassignedPrimary.unassignedInfo().message(), containsString("boom")); // MaxRetryAllocationDecider#canForceAllocatePrimary should return a NO decision because canAllocate returns NO here final var allocation = newRoutingAllocation(clusterState); allocation.debugDecision(true); final var decision = decider.canForceAllocatePrimary(unassignedPrimary, null, allocation); assertEquals(Decision.Type.NO, decision.type()); assertThat( decision.getExplanation(), allOf( containsString("shard has exceeded the maximum number of retries"), containsString("POST /_cluster/reroute?retry_failed") ) ); } // change the settings and ensure we can do another round of allocation for that index. clusterState = ClusterState.builder(clusterState) .routingTable(routingTable) .metadata( Metadata.builder(clusterState.metadata()) .put( IndexMetadata.builder(clusterState.metadata().getProject().index("idx")) .settings( Settings.builder() .put(clusterState.metadata().getProject().index("idx").getSettings()) .put("index.allocation.max_retries", retries + 1) .build() ) .build(), true ) .build() ) .build(); ClusterState newState = strategy.reroute(clusterState, "settings changed", ActionListener.noop()); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); // good we are initializing and we are maintaining failure information assertEquals(routingTable.index("idx").size(), 1); ShardRouting unassignedPrimary = routingTable.index("idx").shard(0).shard(0); assertEquals(unassignedPrimary.unassignedInfo().failedAllocations(), retries); assertEquals(unassignedPrimary.state(), INITIALIZING); assertThat(unassignedPrimary.unassignedInfo().message(), containsString("boom")); // bumped up the max retry count, so canForceAllocatePrimary should return a YES decision assertEquals( Decision.Type.YES, decider.canForceAllocatePrimary(routingTable.index("idx").shard(0).shard(0), null, newRoutingAllocation(clusterState)).type() ); // now we start the shard clusterState = startShardsAndReroute(strategy, clusterState, routingTable.index("idx").shard(0).shard(0)); routingTable = clusterState.routingTable(); // all counters have been reset to 0 ie. no unassigned info assertEquals(routingTable.index("idx").size(), 1); assertNull(routingTable.index("idx").shard(0).shard(0).unassignedInfo()); assertEquals(routingTable.index("idx").shard(0).shard(0).state(), STARTED); // now fail again and see if it has a new counter newState = applyShardFailure(clusterState, routingTable.index("idx").shard(0).shard(0), "ZOOOMG"); assertThat(newState, not(equalTo(clusterState))); clusterState = newState; routingTable = newState.routingTable(); assertEquals(routingTable.index("idx").size(), 1); unassignedPrimary = routingTable.index("idx").shard(0).shard(0); assertEquals(unassignedPrimary.unassignedInfo().failedAllocations(), 1); assertEquals(unassignedPrimary.state(), UNASSIGNED); assertThat(unassignedPrimary.unassignedInfo().message(), containsString("ZOOOMG")); // Counter reset, so MaxRetryAllocationDecider#canForceAllocatePrimary should return a YES decision assertEquals( Decision.Type.YES, decider.canForceAllocatePrimary(unassignedPrimary, null, newRoutingAllocation(clusterState)).type() ); } public void testFailedRelocation() { ClusterState clusterState = createInitialClusterState(); assertThat(clusterState.metadata().projects().size(), equalTo(1)); final ProjectId projectId = clusterState.metadata().projects().keySet().iterator().next(); clusterState = startInitializingShardsAndReroute(strategy, clusterState); int retries = MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY.get(Settings.EMPTY); // shard could be relocated while retries are not exhausted for (int i = 0; i < retries; i++) { clusterState = withRoutingAllocation(clusterState, allocation -> { var source = allocation.routingTable(projectId).index("idx").shard(0).shard(0); var targetNodeId = Objects.equals(source.currentNodeId(), "node1") ? "node2" : "node1"; assertThat(decider.canAllocate(source, allocation).type(), equalTo(Decision.Type.YES)); allocation.routingNodes().relocateShard(source, targetNodeId, 0, "test", allocation.changes()); }); clusterState = applyShardFailure( clusterState, clusterState.getRoutingTable().index("idx").shard(0).shard(0).getTargetRelocatingShard(), "boom" + i ); var relocationFailureInfo = clusterState.globalRoutingTable() .routingTable(projectId) .index("idx") .shard(0) .shard(0) .relocationFailureInfo(); assertThat(relocationFailureInfo.failedRelocations(), equalTo(i + 1)); } // shard could not be relocated when retries are exhausted withRoutingAllocation(clusterState, allocation -> { allocation.debugDecision(true); final var decision = decider.canAllocate( allocation.globalRoutingTable().routingTable(projectId).index("idx").shard(0).shard(0), allocation ); assertThat(decision.type(), equalTo(Decision.Type.NO)); assertThat( decision.getExplanation(), allOf( containsString("shard has exceeded the maximum number of retries"), containsString("POST /_cluster/reroute?retry_failed") ) ); }); // manually reset retry count clusterState = strategy.reroute(clusterState, new AllocationCommands(), false, true, false, ActionListener.noop()).clusterState(); // shard could be relocated again withRoutingAllocation(clusterState, allocation -> { var source = allocation.globalRoutingTable().routingTable(projectId).index("idx").shard(0).shard(0); assertThat(decider.canAllocate(source, allocation).type(), equalTo(Decision.Type.YES)); }); } private ClusterState applyShardFailure(ClusterState clusterState, ShardRouting shardRouting, String message) { return strategy.applyFailedShards( clusterState, List.of(new FailedShard(shardRouting, message, new RuntimeException("test"), randomBoolean())), List.of() ); } private static ClusterState withRoutingAllocation(ClusterState clusterState, Consumer<RoutingAllocation> block) { RoutingAllocation allocation = new RoutingAllocation( null, clusterState.mutableRoutingNodes(), clusterState, ClusterInfo.EMPTY, SnapshotShardSizeInfo.EMPTY, 0L ); block.accept(allocation); return updateClusterState(clusterState, allocation); } private static ClusterState updateClusterState(ClusterState state, RoutingAllocation allocation) { assert allocation.metadata() == state.metadata(); if (allocation.routingNodesChanged() == false) { return state; } assertThat(state.metadata().projects(), aMapWithSize(1)); final GlobalRoutingTable newRoutingTable = state.globalRoutingTable().rebuild(allocation.routingNodes(), allocation.metadata()); final Metadata newMetadata = allocation.updateMetadataWithRoutingChanges(newRoutingTable); assert newRoutingTable.validate(newMetadata); return state.copyAndUpdate(builder -> builder.routingTable(newRoutingTable).metadata(newMetadata)); } private RoutingAllocation newRoutingAllocation(ClusterState clusterState) { final var routingAllocation = new RoutingAllocation(null, clusterState, null, null, 0); if (randomBoolean()) { routingAllocation.setDebugMode(randomFrom(RoutingAllocation.DebugMode.values())); } return routingAllocation; } }
MaxRetryAllocationDeciderTests
java
elastic__elasticsearch
x-pack/plugin/sql/sql-client/src/main/java/org/elasticsearch/xpack/sql/client/ObjectUtils.java
{ "start": 448, "end": 1008 }
class ____ { public static boolean isEmpty(int[] array) { return (array == null || array.length == 0); } public static boolean isEmpty(byte[] array) { return (array == null || array.length == 0); } public static boolean isEmpty(Object[] array) { return (array == null || array.length == 0); } public static <K, E extends Enum<E>> Map<K, E> mapEnum(Class<E> clazz, Function<E, K> mapper) { return Arrays.stream(clazz.getEnumConstants()).collect(toMap(mapper, Function.identity())); } }
ObjectUtils
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/JiraActionTests.java
{ "start": 12922, "end": 13511 }
class ____ extends TextTemplateEngine { private final Map<String, Object> model; ModelTextTemplateEngine(Map<String, Object> model) { super(mock(ScriptService.class)); this.model = model; } @Override public String render(TextTemplate textTemplate, Map<String, Object> ignoredModel) { String template = textTemplate.getTemplate(); if (model.containsKey(template)) { return (String) model.get(template); } return template; } } }
ModelTextTemplateEngine
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
{ "start": 37989, "end": 38332 }
class ____ implements Runnable { @Override public void run() { long now = System.currentTimeMillis(); for (RelayConnectionHandler handler : connectionHandlers.values()) { handler.updateClientSendMessageCount(now); } } } /** * Contract for access to session counters. * @since 5.2 */ public
ClientSendMessageCountTask
java
apache__camel
components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java
{ "start": 28415, "end": 29172 }
class ____ implements AsyncCallback { private final ChannelFuture channelFuture; private final AsyncCallback callback; private NettyProducerCallback(ChannelFuture channelFuture, AsyncCallback callback) { this.channelFuture = channelFuture; this.callback = callback; } @Override public void done(boolean doneSync) { // put back in pool try { releaseChannel(channelFuture); } finally { // ensure we call the delegated callback callback.done(doneSync); } } } /** * Object factory to create {@link Channel} used by the pool. */ private final
NettyProducerCallback
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingRefasterAnnotationTest.java
{ "start": 2395, "end": 2818 }
class ____ { @BeforeTemplate boolean before(String string) { return string.equals(""); } // @AfterTemplate is missing boolean after(String string) { return string.isEmpty(); } } // BUG: Diagnostic matches: X abstract
MethodLacksAfterTemplateAnnotation
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/plugin/DataNodeRequestTests.java
{ "start": 938, "end": 2320 }
class ____ extends ESTestCase { public void testNoIndexPlaceholder() { var sessionId = randomAlphaOfLength(10); List<DataNodeRequest.Shard> shards = randomList( 1, 10, () -> new DataNodeRequest.Shard( new ShardId("index-" + between(1, 10), "n/a", between(1, 10)), SplitShardCountSummary.fromInt(randomIntBetween(0, 1024)) ) ); DataNodeRequest request = new DataNodeRequest( sessionId, randomConfiguration(""" from test | where round(emp_no) > 10 | eval c = salary | stats x = avg(c) """, randomTables()), randomAlphaOfLength(10), shards, Collections.emptyMap(), null, generateRandomStringArray(10, 10, false, false), IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()), randomBoolean(), randomBoolean() ); assertThat(request.shards(), equalTo(shards)); request.indices(generateRandomStringArray(10, 10, false, false)); assertThat(request.shards(), equalTo(shards)); request.indices(NO_INDEX_PLACEHOLDER); assertThat(request.shards(), empty()); } }
DataNodeRequestTests
java
apache__maven
compat/maven-compat/src/test/java/org/apache/maven/project/inheritance/t10/ProjectInheritanceTest.java
{ "start": 1813, "end": 3839 }
class ____ extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 // p0 inherits from super model // // or we can show it graphically as: // // p1 ---> p0 --> super model // // ---------------------------------------------------------------------- @Test void testDependencyManagementOverridesTransitiveDependencyVersion() throws Exception { File localRepo = getLocalRepositoryPath(); File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load the child project, which inherits from p0... MavenProject project0 = getProjectWithDependencies(pom0); MavenProject project1 = getProjectWithDependencies(pom1); assertEquals(pom0Basedir, project1.getParent().getBasedir()); System.out.println("Project " + project1.getId() + " " + project1); Map map = project1.getArtifactMap(); assertNotNull(map, "No artifacts"); assertFalse(map.isEmpty(), "No Artifacts"); assertTrue(map.size() == 3, "Set size should be 3, is " + map.size()); Artifact a = (Artifact) map.get("maven-test:t10-a"); Artifact b = (Artifact) map.get("maven-test:t10-b"); Artifact c = (Artifact) map.get("maven-test:t10-c"); assertNotNull(a); assertNotNull(b); assertNotNull(c); // inherited from depMgmt System.out.println(a.getScope()); assertTrue(a.getScope().equals("test"), "Incorrect scope for " + a.getDependencyConflictId()); // transitive dep, overridden b depMgmt assertTrue(b.getScope().equals("runtime"), "Incorrect scope for " + b.getDependencyConflictId()); // direct dep, overrides depMgmt assertTrue(c.getScope().equals("runtime"), "Incorrect scope for " + c.getDependencyConflictId()); } }
ProjectInheritanceTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/FloatArraysBaseTest.java
{ "start": 1046, "end": 1388 }
class ____ testing <code>{@link FloatArrays}</code>, set up an instance with {@link StandardComparisonStrategy} and another * with {@link ComparatorBasedComparisonStrategy}. * <p> * Is in <code>org.assertj.core.internal</code> package to be able to set {@link FloatArrays#failures} appropriately. * * @author Joel Costigliola */ public
for
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/io/buffer/support/DataBufferTestUtilsTests.java
{ "start": 1117, "end": 1969 }
class ____ extends AbstractDataBufferAllocatingTests { @ParameterizedDataBufferAllocatingTest void dumpBytes(DataBufferFactory bufferFactory) { this.bufferFactory = bufferFactory; DataBuffer buffer = this.bufferFactory.allocateBuffer(4); byte[] source = {'a', 'b', 'c', 'd'}; buffer.write(source); byte[] result = DataBufferTestUtils.dumpBytes(buffer); assertThat(result).isEqualTo(source); release(buffer); } @ParameterizedDataBufferAllocatingTest void dumpString(DataBufferFactory bufferFactory) { this.bufferFactory = bufferFactory; DataBuffer buffer = this.bufferFactory.allocateBuffer(4); String source = "abcd"; buffer.write(source.getBytes(StandardCharsets.UTF_8)); String result = buffer.toString(StandardCharsets.UTF_8); release(buffer); assertThat(result).isEqualTo(source); } }
DataBufferTestUtilsTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest90_isof.java
{ "start": 1039, "end": 2608 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "select * from persons p\n" + " where value(p) is of type(only employee_t)"; System.out.println(sql); OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); System.out.println(stmt.toString()); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); { String text = SQLUtils.toOracleString(stmt); assertEquals("SELECT *\n" + "FROM persons p\n" + "WHERE value(p) IS OF TYPE (ONLY employee_t)", text); } 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()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); assertEquals(0, visitor.getOrderByColumns().size()); } }
OracleSelectTest90_isof
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jChatEndpointBuilderFactory.java
{ "start": 16088, "end": 18042 }
interface ____ extends LangChain4jChatEndpointConsumerBuilder, LangChain4jChatEndpointProducerBuilder { default AdvancedLangChain4jChatEndpointBuilder advanced() { return (AdvancedLangChain4jChatEndpointBuilder) this; } /** * Operation in case of Endpoint of type CHAT. The value is one of the * values of * org.apache.camel.component.langchain4j.chat.LangChain4jChatOperations. * * The option is a: * <code>org.apache.camel.component.langchain4j.chat.LangChain4jChatOperations</code> type. * * Required: true * Default: CHAT_SINGLE_MESSAGE * Group: common * * @param chatOperation the value to set * @return the dsl builder */ default LangChain4jChatEndpointBuilder chatOperation(org.apache.camel.component.langchain4j.chat.LangChain4jChatOperations chatOperation) { doSetProperty("chatOperation", chatOperation); return this; } /** * Operation in case of Endpoint of type CHAT. The value is one of the * values of * org.apache.camel.component.langchain4j.chat.LangChain4jChatOperations. * * The option will be converted to a * <code>org.apache.camel.component.langchain4j.chat.LangChain4jChatOperations</code> type. * * Required: true * Default: CHAT_SINGLE_MESSAGE * Group: common * * @param chatOperation the value to set * @return the dsl builder */ default LangChain4jChatEndpointBuilder chatOperation(String chatOperation) { doSetProperty("chatOperation", chatOperation); return this; } } /** * Advanced builder for endpoint for the LangChain4j Chat component. */ public
LangChain4jChatEndpointBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/JavaxInjectOnAbstractMethodTest.java
{ "start": 2646, "end": 2815 }
class ____ implements TestInterface { // BUG: Diagnostic contains: remove @javax.inject.Inject public abstract void abstractMethod(); }
AbstractImplementing
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestResourceVector.java
{ "start": 1570, "end": 5082 }
class ____ { private final static String CUSTOM_RESOURCE = "custom"; private final YarnConfiguration conf = new YarnConfiguration(); @BeforeEach public void setUp() { conf.set(YarnConfiguration.RESOURCE_TYPES, CUSTOM_RESOURCE); ResourceUtils.resetResourceTypes(conf); } @Test public void testCreation() { ResourceVector zeroResourceVector = ResourceVector.newInstance(); assertEquals(0, zeroResourceVector.getValue(MEMORY_URI), EPSILON); assertEquals(0, zeroResourceVector.getValue(VCORES_URI), EPSILON); assertEquals(0, zeroResourceVector.getValue(CUSTOM_RESOURCE), EPSILON); ResourceVector uniformResourceVector = ResourceVector.of(10); assertEquals(10, uniformResourceVector.getValue(MEMORY_URI), EPSILON); assertEquals(10, uniformResourceVector.getValue(VCORES_URI), EPSILON); assertEquals(10, uniformResourceVector.getValue(CUSTOM_RESOURCE), EPSILON); Map<String, Long> customResources = new HashMap<>(); customResources.put(CUSTOM_RESOURCE, 2L); Resource resource = Resource.newInstance(10, 5, customResources); ResourceVector resourceVectorFromResource = ResourceVector.of(resource); assertEquals(10, resourceVectorFromResource.getValue(MEMORY_URI), EPSILON); assertEquals(5, resourceVectorFromResource.getValue(VCORES_URI), EPSILON); assertEquals(2, resourceVectorFromResource.getValue(CUSTOM_RESOURCE), EPSILON); } @Test public void testSubtract() { ResourceVector lhsResourceVector = ResourceVector.of(13); ResourceVector rhsResourceVector = ResourceVector.of(5); lhsResourceVector.decrement(rhsResourceVector); assertEquals(8, lhsResourceVector.getValue(MEMORY_URI), EPSILON); assertEquals(8, lhsResourceVector.getValue(VCORES_URI), EPSILON); assertEquals(8, lhsResourceVector.getValue(CUSTOM_RESOURCE), EPSILON); ResourceVector negativeResourceVector = ResourceVector.of(-100); // Check whether overflow causes any issues negativeResourceVector.decrement(ResourceVector.of(Float.MAX_VALUE)); assertEquals(-Float.MAX_VALUE, negativeResourceVector.getValue(MEMORY_URI), EPSILON); assertEquals(-Float.MAX_VALUE, negativeResourceVector.getValue(VCORES_URI), EPSILON); assertEquals(-Float.MAX_VALUE, negativeResourceVector.getValue(CUSTOM_RESOURCE), EPSILON); } @Test public void testIncrement() { ResourceVector resourceVector = ResourceVector.of(13); resourceVector.increment(MEMORY_URI, 5); assertEquals(18, resourceVector.getValue(MEMORY_URI), EPSILON); assertEquals(13, resourceVector.getValue(VCORES_URI), EPSILON); assertEquals(13, resourceVector.getValue(CUSTOM_RESOURCE), EPSILON); // Check whether overflow causes any issues ResourceVector maxFloatResourceVector = ResourceVector.of(Float.MAX_VALUE); maxFloatResourceVector.increment(MEMORY_URI, 100); assertEquals(Float.MAX_VALUE, maxFloatResourceVector.getValue(MEMORY_URI), EPSILON); } @Test public void testEquals() { ResourceVector resourceVector = ResourceVector.of(13); ResourceVector resourceVectorOther = ResourceVector.of(14); Resource resource = Resource.newInstance(13, 13); assertNotEquals(null, resourceVector); assertNotEquals(resourceVectorOther, resourceVector); assertNotEquals(resource, resourceVector); ResourceVector resourceVectorOne = ResourceVector.of(1); resourceVectorOther.decrement(resourceVectorOne); assertEquals(resourceVectorOther, resourceVector); } }
TestResourceVector
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/memory/ByteStreamStateHandleTest.java
{ "start": 1267, "end": 6441 }
class ____ { @Test void testStreamSeekAndPos() throws IOException { final byte[] data = {34, 25, 22, 66, 88, 54}; final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", data); // read backwards, one byte at a time for (int i = data.length; i >= 0; i--) { FSDataInputStream in = handle.openInputStream(); in.seek(i); assertThat(in.getPos()).isEqualTo(i); if (i < data.length) { assertThat(in.read()).isEqualTo(data[i]); assertThat(in.getPos()).isEqualTo(i + 1); } else { assertThat(in.read()).isEqualTo(-1); assertThat(in.getPos()).isEqualTo(i); } } // reading past the end makes no difference FSDataInputStream in = handle.openInputStream(); in.seek(data.length); // read multiple times, should not affect anything assertThat(in.read()).isEqualTo(-1); assertThat(in.read()).isEqualTo(-1); assertThat(in.read()).isEqualTo(-1); assertThat(in.getPos()).isEqualTo(data.length); } @Test void testStreamSeekOutOfBounds() { final int len = 10; final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", new byte[len]); // check negative offset assertThatThrownBy(() -> handle.openInputStream().seek(-2)).isInstanceOf(IOException.class); // check integer overflow assertThatThrownBy(() -> handle.openInputStream().seek(len + 1)) .isInstanceOf(IOException.class); // check integer overflow assertThatThrownBy(() -> handle.openInputStream().seek(((long) Integer.MAX_VALUE) + 100L)) .isInstanceOf(IOException.class); } @Test void testBulkRead() throws IOException { final byte[] data = {34, 25, 22, 66}; final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", data); final int targetLen = 8; for (int start = 0; start < data.length; start++) { for (int num = 0; num < targetLen; num++) { FSDataInputStream in = handle.openInputStream(); in.seek(start); final byte[] target = new byte[targetLen]; final int read = in.read(target, targetLen - num, num); assertThat(read).isEqualTo(Math.min(num, data.length - start)); for (int i = 0; i < read; i++) { assertThat(target[targetLen - num + i]).isEqualTo(data[start + i]); } int newPos = start + read; assertThat(in.getPos()).isEqualTo(newPos); assertThat(in.read()).isEqualTo(newPos < data.length ? data[newPos] : -1); } } } @SuppressWarnings("ResultOfMethodCallIgnored") @Test void testBulkReadINdexOutOfBounds() throws IOException { final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", new byte[10]); // check negative offset assertThatThrownBy(() -> handle.openInputStream().read(new byte[10], -1, 5)) .isInstanceOf(IndexOutOfBoundsException.class); // check offset overflow assertThatThrownBy(() -> handle.openInputStream().read(new byte[10], 10, 5)) .isInstanceOf(IndexOutOfBoundsException.class); // check negative length assertThatThrownBy(() -> handle.openInputStream().read(new byte[10], 0, -2)) .isInstanceOf(IndexOutOfBoundsException.class); // check length too large assertThatThrownBy(() -> handle.openInputStream().read(new byte[10], 5, 6)) .isInstanceOf(IndexOutOfBoundsException.class); // check length integer overflow assertThatThrownBy(() -> handle.openInputStream().read(new byte[10], 5, Integer.MAX_VALUE)) .isInstanceOf(IndexOutOfBoundsException.class); } @Test void testStreamWithEmptyByteArray() throws IOException { final byte[] data = new byte[0]; final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", data); try (FSDataInputStream in = handle.openInputStream()) { byte[] dataGot = new byte[1]; assertThat(in.read(dataGot, 0, 0)).isZero(); // got return 0 because len == 0. assertThat(in.read()).isEqualTo(-1); // got -1 because of EOF. } } @Test void testCollectSizeStats() { final byte[] data = new byte[5]; final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", data); StateObject.StateObjectSizeStatsCollector statsCollector = StateObject.StateObjectSizeStatsCollector.create(); handle.collectSizeStats(statsCollector); Assertions.assertEquals( new HashMap<StateObject.StateObjectLocation, Long>() { { put(StateObject.StateObjectLocation.LOCAL_MEMORY, (long) data.length); } }, statsCollector.getStats()); } }
ByteStreamStateHandleTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/RemoteConnectionStrategy.java
{ "start": 1869, "end": 2907 }
enum ____ { SNIFF(SniffConnectionStrategy.CHANNELS_PER_CONNECTION, SniffConnectionStrategy::infoReader) { @Override public String toString() { return "sniff"; } }, PROXY(ProxyConnectionStrategy.CHANNELS_PER_CONNECTION, ProxyConnectionStrategy::infoReader) { @Override public String toString() { return "proxy"; } }; private final int numberOfChannels; private final Supplier<Writeable.Reader<RemoteConnectionInfo.ModeInfo>> reader; ConnectionStrategy(int numberOfChannels, Supplier<Writeable.Reader<RemoteConnectionInfo.ModeInfo>> reader) { this.numberOfChannels = numberOfChannels; this.reader = reader; } public int getNumberOfChannels() { return numberOfChannels; } public Writeable.Reader<RemoteConnectionInfo.ModeInfo> getReader() { return reader.get(); } }
ConnectionStrategy
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/RepeatedTest.java
{ "start": 3622, "end": 7691 }
interface ____ { /** * Placeholder for the {@linkplain TestInfo#getDisplayName display name} of * a {@code @RepeatedTest} method: <code>{displayName}</code> */ String DISPLAY_NAME_PLACEHOLDER = "{displayName}"; /** * Placeholder for the current repetition count of a {@code @RepeatedTest} * method: <code>{currentRepetition}</code> */ String CURRENT_REPETITION_PLACEHOLDER = "{currentRepetition}"; /** * Placeholder for the total number of repetitions of a {@code @RepeatedTest} * method: <code>{totalRepetitions}</code> */ String TOTAL_REPETITIONS_PLACEHOLDER = "{totalRepetitions}"; /** * <em>Short</em> display name pattern for a repeated test: {@value} * * @see #CURRENT_REPETITION_PLACEHOLDER * @see #TOTAL_REPETITIONS_PLACEHOLDER * @see #LONG_DISPLAY_NAME */ String SHORT_DISPLAY_NAME = "repetition " + CURRENT_REPETITION_PLACEHOLDER + " of " + TOTAL_REPETITIONS_PLACEHOLDER; /** * <em>Long</em> display name pattern for a repeated test: {@value} * * @see #DISPLAY_NAME_PLACEHOLDER * @see #SHORT_DISPLAY_NAME */ String LONG_DISPLAY_NAME = DISPLAY_NAME_PLACEHOLDER + " :: " + SHORT_DISPLAY_NAME; /** * The number of repetitions. * * @return the number of repetitions; must be greater than zero */ int value(); /** * The display name for each repetition of the repeated test. * * <h4>Supported placeholders</h4> * <ul> * <li>{@link #DISPLAY_NAME_PLACEHOLDER}</li> * <li>{@link #CURRENT_REPETITION_PLACEHOLDER}</li> * <li>{@link #TOTAL_REPETITIONS_PLACEHOLDER}</li> * </ul> * * <p>Defaults to {@link #SHORT_DISPLAY_NAME}, resulting in * names such as {@code "repetition 1 of 2"}, {@code "repetition 2 of 2"}, * etc. * * <p>Can be set to <code>{@link #LONG_DISPLAY_NAME}</code>, resulting in * names such as {@code "myRepeatedTest() :: repetition 1 of 2"}, * {@code "myRepeatedTest() :: repetition 2 of 2"}, etc. * * <p>Alternatively, you can provide a custom display name, optionally * using the aforementioned placeholders. * * @return a custom display name; never blank or consisting solely of * whitespace * @see #SHORT_DISPLAY_NAME * @see #LONG_DISPLAY_NAME * @see #DISPLAY_NAME_PLACEHOLDER * @see #CURRENT_REPETITION_PLACEHOLDER * @see #TOTAL_REPETITIONS_PLACEHOLDER * @see TestInfo#getDisplayName() */ String name() default SHORT_DISPLAY_NAME; /** * Configures the number of failures after which remaining repetitions will * be automatically skipped. * * <p>Set this to a positive number less than the total {@linkplain #value() * number of repetitions} in order to skip the invocations of remaining * repetitions after the specified number of failures has been encountered. * * <p>For example, if you are using {@code @RepeatedTest} to repeatedly invoke * a test that you suspect to be <em>flaky</em>, a single failure is sufficient * to demonstrate that the test is flaky, and there is no need to invoke the * remaining repetitions. To support that specific use case, set * {@code failureThreshold = 1}. You can alternatively set the threshold to * a number greater than {@code 1} depending on your use case. * * <p>Defaults to {@link Integer#MAX_VALUE}, signaling that no failure * threshold will be applied, which effectively means that the specified * {@linkplain #value() number of repetitions} will be invoked regardless of * whether any repetitions fail. * * <p><strong>WARNING</strong>: if the repetitions of a {@code @RepeatedTest} * method are executed in parallel, no guarantees can be made regarding the * failure threshold. It is therefore recommended that a {@code @RepeatedTest} * method be annotated with * {@link org.junit.jupiter.api.parallel.Execution @Execution(SAME_THREAD)} * when parallel execution is configured. * * @since 5.10 * @return the failure threshold; must be greater than zero and less than the * total number of repetitions */ @API(status = MAINTAINED, since = "5.13.3") int failureThreshold() default Integer.MAX_VALUE; }
RepeatedTest
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/localizer/sharedcache/TestSharedCacheUploadService.java
{ "start": 1085, "end": 1587 }
class ____ { @Test public void testInitDisabled() { testInit(false); } @Test public void testInitEnabled() { testInit(true); } public void testInit(boolean enabled) { Configuration conf = new Configuration(); conf.setBoolean(YarnConfiguration.SHARED_CACHE_ENABLED, enabled); SharedCacheUploadService service = new SharedCacheUploadService(); service.init(conf); assertSame(enabled, service.isEnabled()); service.stop(); } }
TestSharedCacheUploadService
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLWhoamiStatement.java
{ "start": 157, "end": 326 }
class ____ extends SQLStatementImpl { @Override protected void accept0(SQLASTVisitor v) { v.visit(this); v.endVisit(this); } }
SQLWhoamiStatement
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/AbstractYarnClusterITest.java
{ "start": 3061, "end": 3173 }
class ____ instantiated in the same JVM, in order, * they are guaranteed to be isolated. * */ public abstract
are
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/script/CtxMapTests.java
{ "start": 892, "end": 5059 }
class ____ extends ESTestCase { CtxMap<?> map; @Override @Before public void setUp() throws Exception { super.setUp(); map = new CtxMap<>(new HashMap<>(), new Metadata(Map.of(), Map.of())); } @SuppressWarnings("unchecked") public void testGetOrDefault() { { map = new CtxMap<>(Map.of("foo", "bar"), new Metadata(Map.of("_version", 5L), Map.of(VERSION, LongField.withWritable()))); // it does the expected thing for fields that are present assertThat(map.getOrDefault("_version", -1L), equalTo(5L)); assertThat(((Map<String, Object>) map.getOrDefault("_source", Map.of())).getOrDefault("foo", "wat"), equalTo("bar")); // it does the expected thing for fields that are not present assertThat(map.getOrDefault("_version_type", "something"), equalTo("something")); assertThat(map.getOrDefault("baz", "quux"), equalTo("quux")); } { map = new CtxMap<>(Map.of("foo", "bar"), new Metadata(Map.of("_version", 5L), Map.of(VERSION, LongField.withWritable()))) { @Override protected boolean directSourceAccess() { return true; } }; // it does the expected thing for fields that are present assertThat(map.getOrDefault("_version", -1L), equalTo(5L)); assertThat(map.getOrDefault("foo", "wat"), equalTo("bar")); // it does the expected thing for fields that are not present assertThat(map.getOrDefault("_version_type", "something"), equalTo("something")); assertThat(map.getOrDefault("baz", "quux"), equalTo("quux")); } } public void testAddingJunkToCtx() { IllegalArgumentException err = expectThrows(IllegalArgumentException.class, () -> map.put("junk", "stuff")); assertEquals("Cannot put key [junk] with value [stuff] into ctx", err.getMessage()); } public void testRemovingSource() { UnsupportedOperationException err = expectThrows(UnsupportedOperationException.class, () -> map.remove("_source")); assertEquals("Cannot remove key _source from ctx", err.getMessage()); err = expectThrows(UnsupportedOperationException.class, () -> iteratorAtSource().remove()); assertEquals("Cannot remove key [_source] from ctx", err.getMessage()); } @SuppressWarnings("unchecked") public void testReplacingSource() { map.put("_source", Map.of("abc", 123)); assertEquals(123, ((Map<String, Object>) map.get("_source")).get("abc")); sourceEntry().setValue(Map.of("def", 456)); assertEquals(456, ((Map<String, Object>) map.get("_source")).get("def")); } public void testInvalidReplacementOfSource() { IllegalArgumentException err = expectThrows( IllegalArgumentException.class, () -> map.put("_source", List.of(1, 2, "buckle my shoe")) ); assertThat( err.getMessage(), containsString("Expected [_source] to be a Map, not [[1, 2, buckle my shoe]] with type [java.util.ImmutableCollections$ListN]") ); err = expectThrows(IllegalArgumentException.class, () -> sourceEntry().setValue(List.of(1, 2, "buckle my shoe"))); assertThat( err.getMessage(), containsString("Expected [_source] to be a Map, not [[1, 2, buckle my shoe]] with type [java.util.ImmutableCollections$ListN]") ); } protected Map.Entry<String, Object> sourceEntry() { for (Map.Entry<String, Object> entry : map.entrySet()) { if ("_source".equals(entry.getKey())) { return entry; } } fail("no _source"); return null; } protected Iterator<Map.Entry<String, Object>> iteratorAtSource() { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { if ("_source".equals(it.next().getKey())) { return it; } } fail("no _source"); return null; } }
CtxMapTests
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/AsyncStateTableStreamOperator.java
{ "start": 1645, "end": 1833 }
class ____ nearly identical with {@link TableStreamOperator}, but extending from {@link * AbstractAsyncStateStreamOperator} to integrate with asynchronous state access. */ public abstract
is
java
apache__camel
components/camel-google/camel-google-calendar/src/main/java/org/apache/camel/component/google/calendar/stream/GoogleCalendarStreamEndpoint.java
{ "start": 1839, "end": 4499 }
class ____ extends ScheduledPollEndpoint implements EndpointServiceLocation { @UriParam private GoogleCalendarStreamConfiguration configuration; public GoogleCalendarStreamEndpoint(String uri, GoogleCalendarStreamComponent component, GoogleCalendarStreamConfiguration endpointConfiguration) { super(uri, component); this.configuration = endpointConfiguration; } @Override public Producer createProducer() throws Exception { throw new UnsupportedOperationException("The camel google calendar stream component doesn't support producer"); } @Override public Consumer createConsumer(Processor processor) throws Exception { // check for incompatible configuration options if (configuration.isSyncFlow()) { if (ObjectHelper.isNotEmpty(configuration.getQuery())) { throw new IllegalArgumentException("'query' parameter is incompatible with sync flow."); } if (configuration.isConsiderLastUpdate()) { throw new IllegalArgumentException("'considerLastUpdate' is incompatible with sync flow."); } } final GoogleCalendarStreamConsumer consumer = new GoogleCalendarStreamConsumer(this, processor); configureConsumer(consumer); return consumer; } public Calendar getClient() { return ((GoogleCalendarStreamComponent) getComponent()).getClient(configuration); } public GoogleCalendarStreamConfiguration getConfiguration() { return configuration; } public Exchange createExchange(ExchangePattern pattern, Event event) { Exchange exchange = super.createExchange(pattern); Message message = exchange.getIn(); message.setBody(event); message.setHeader(GoogleCalendarStreamConstants.EVENT_ID, event.getId()); return exchange; } @Override public String getServiceUrl() { if (ObjectHelper.isNotEmpty( ObjectHelper.isNotEmpty(configuration.getCalendarId()) && ObjectHelper.isNotEmpty(configuration.getUser()))) { return getServiceProtocol() + ":" + configuration.getUser() + ":" + configuration.getCalendarId(); } return null; } @Override public String getServiceProtocol() { return "calendar-stream"; } @Override public Map<String, String> getServiceMetadata() { if (configuration.getApplicationName() != null) { return Map.of("applicationName", configuration.getApplicationName()); } return null; } }
GoogleCalendarStreamEndpoint
java
spring-projects__spring-boot
loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java
{ "start": 10721, "end": 11053 }
class ____ implements MainClassCallback<Object> { private final List<String> classNames = new ArrayList<>(); @Override public @Nullable Object doWith(MainClass mainClass) { this.classNames.add(mainClass.getName()); return null; } List<String> getClassNames() { return this.classNames; } } }
ClassNameCollector
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_515/Issue515Mapper.java
{ "start": 312, "end": 546 }
class ____ { public static final Issue515Mapper INSTANCE = Mappers.getMapper( Issue515Mapper.class ); @Mapping( target = "id", expression = "java(\"blah)\\\"\")" ) public abstract Target map(Source source); }
Issue515Mapper
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java
{ "start": 4933, "end": 21769 }
class ____ extends Realm implements Releasable { public static final String CONTEXT_TOKEN_DATA = "_oidc_tokendata"; private final OpenIdConnectProviderConfiguration opConfiguration; private final RelyingPartyConfiguration rpConfiguration; private final OpenIdConnectAuthenticator openIdConnectAuthenticator; private final ClaimParser principalAttribute; private final ClaimParser groupsAttribute; private final ClaimParser dnAttribute; private final ClaimParser nameAttribute; private final ClaimParser mailAttribute; private final Boolean populateUserMetadata; private final UserRoleMapper roleMapper; private DelegatedAuthorizationSupport delegatedRealms; public OpenIdConnectRealm(RealmConfig config, SSLService sslService, UserRoleMapper roleMapper, ResourceWatcherService watcherService) { super(config); this.roleMapper = roleMapper; this.rpConfiguration = buildRelyingPartyConfiguration(config); this.opConfiguration = buildOpenIdConnectProviderConfiguration(config); this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); if (TokenService.isTokenServiceEnabled(config.settings()) == false) { throw new IllegalStateException( "OpenID Connect Realm requires that the token service be enabled (" + XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey() + ")" ); } this.openIdConnectAuthenticator = new OpenIdConnectAuthenticator( config, opConfiguration, rpConfiguration, sslService, watcherService ); } // For testing OpenIdConnectRealm(RealmConfig config, OpenIdConnectAuthenticator authenticator, UserRoleMapper roleMapper) { super(config); this.roleMapper = roleMapper; this.rpConfiguration = buildRelyingPartyConfiguration(config); this.opConfiguration = buildOpenIdConnectProviderConfiguration(config); this.openIdConnectAuthenticator = authenticator; this.principalAttribute = ClaimParser.forSetting(logger, PRINCIPAL_CLAIM, config, true); this.groupsAttribute = ClaimParser.forSetting(logger, GROUPS_CLAIM, config, false); this.dnAttribute = ClaimParser.forSetting(logger, DN_CLAIM, config, false); this.nameAttribute = ClaimParser.forSetting(logger, NAME_CLAIM, config, false); this.mailAttribute = ClaimParser.forSetting(logger, MAIL_CLAIM, config, false); this.populateUserMetadata = config.getSetting(POPULATE_USER_METADATA); } @Override public void initialize(Iterable<Realm> realms, XPackLicenseState licenseState) { if (delegatedRealms != null) { throw new IllegalStateException("Realm has already been initialized"); } delegatedRealms = new DelegatedAuthorizationSupport(realms, config, licenseState); } @Override public boolean supports(AuthenticationToken token) { return token instanceof OpenIdConnectToken; } private boolean isTokenForRealm(OpenIdConnectToken oidcToken) { if (oidcToken.getAuthenticatingRealm() == null) { return true; } else { return oidcToken.getAuthenticatingRealm().equals(this.name()); } } @Override public AuthenticationToken token(ThreadContext context) { return null; } @Override public void authenticate(AuthenticationToken token, ActionListener<AuthenticationResult<User>> listener) { if (token instanceof OpenIdConnectToken oidcToken && isTokenForRealm(oidcToken)) { openIdConnectAuthenticator.authenticate( oidcToken, ActionListener.wrap(jwtClaimsSet -> { buildUserFromClaims(jwtClaimsSet, listener); }, e -> { logger.debug("Failed to consume the OpenIdConnectToken ", e); if (e instanceof ElasticsearchSecurityException) { listener.onResponse(AuthenticationResult.unsuccessful("Failed to authenticate user with OpenID Connect", e)); } else { listener.onFailure(e); } }) ); } else { listener.onResponse(AuthenticationResult.notHandled()); } } @Override public void lookupUser(String username, ActionListener<User> listener) { listener.onResponse(null); } private void buildUserFromClaims(JWTClaimsSet claims, ActionListener<AuthenticationResult<User>> authResultListener) { final String principal = principalAttribute.getClaimValue(claims); if (Strings.isNullOrEmpty(principal)) { authResultListener.onResponse( AuthenticationResult.unsuccessful(principalAttribute + "not found in " + claims.toJSONObject(), null) ); return; } final Map<String, Object> tokenMetadata = new HashMap<>(); tokenMetadata.put("id_token_hint", claims.getClaim("id_token_hint")); ActionListener<AuthenticationResult<User>> wrappedAuthResultListener = ActionListener.wrap(auth -> { if (auth.isAuthenticated()) { // Add the ID Token as metadata on the authentication, so that it can be used for logout requests Map<String, Object> metadata = new HashMap<>(auth.getMetadata()); metadata.put(CONTEXT_TOKEN_DATA, tokenMetadata); auth = AuthenticationResult.success(auth.getValue(), metadata); } authResultListener.onResponse(auth); }, authResultListener::onFailure); if (delegatedRealms.hasDelegation()) { delegatedRealms.resolve(principal, wrappedAuthResultListener); return; } final Map<String, Object> userMetadata; if (populateUserMetadata) { userMetadata = claims.getClaims() .entrySet() .stream() .filter(entry -> isAllowedTypeForClaim(entry.getValue())) .collect(Collectors.toUnmodifiableMap(entry -> "oidc(" + entry.getKey() + ")", Map.Entry::getValue)); } else { userMetadata = Map.of(); } final List<String> groups = groupsAttribute.getClaimValues(claims); final String dn = dnAttribute.getClaimValue(claims); final String mail = mailAttribute.getClaimValue(claims); final String name = nameAttribute.getClaimValue(claims); UserRoleMapper.UserData userData = new UserRoleMapper.UserData(principal, dn, groups, userMetadata, config); roleMapper.resolveRoles(userData, ActionListener.wrap(roles -> { final User user = new User(principal, roles.toArray(Strings.EMPTY_ARRAY), name, mail, userMetadata, true); wrappedAuthResultListener.onResponse(AuthenticationResult.success(user)); }, wrappedAuthResultListener::onFailure)); } private static RelyingPartyConfiguration buildRelyingPartyConfiguration(RealmConfig config) { final String redirectUriString = require(config, RP_REDIRECT_URI); final URI redirectUri; try { redirectUri = new URI(redirectUriString); } catch (URISyntaxException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid URI:" + RP_REDIRECT_URI.getKey(), e); } final String postLogoutRedirectUriString = config.getSetting(RP_POST_LOGOUT_REDIRECT_URI); final URI postLogoutRedirectUri; try { postLogoutRedirectUri = new URI(postLogoutRedirectUriString); } catch (URISyntaxException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid URI:" + RP_POST_LOGOUT_REDIRECT_URI.getKey(), e); } final ClientID clientId = new ClientID(require(config, RP_CLIENT_ID)); final SecureString clientSecret = config.getSetting(RP_CLIENT_SECRET); if (clientSecret.length() == 0) { throw new SettingsException( "The configuration setting [" + RealmSettings.getFullSettingKey(config, RP_CLIENT_SECRET) + "] is required" ); } final ResponseType responseType; try { responseType = ResponseType.parse(require(config, RP_RESPONSE_TYPE)); } catch (ParseException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid value for " + RP_RESPONSE_TYPE.getKey(), e); } final Scope requestedScope = new Scope(config.getSetting(RP_REQUESTED_SCOPES).toArray(Strings.EMPTY_ARRAY)); if (requestedScope.contains("openid") == false) { requestedScope.add("openid"); } final JWSAlgorithm signatureAlgorithm = JWSAlgorithm.parse(require(config, RP_SIGNATURE_ALGORITHM)); final ClientAuthenticationMethod clientAuthenticationMethod = ClientAuthenticationMethod.parse( require(config, RP_CLIENT_AUTH_METHOD) ); final JWSAlgorithm clientAuthJwtAlgorithm = JWSAlgorithm.parse(require(config, RP_CLIENT_AUTH_JWT_SIGNATURE_ALGORITHM)); return new RelyingPartyConfiguration( clientId, clientSecret, redirectUri, responseType, requestedScope, signatureAlgorithm, clientAuthenticationMethod, clientAuthJwtAlgorithm, postLogoutRedirectUri ); } private OpenIdConnectProviderConfiguration buildOpenIdConnectProviderConfiguration(RealmConfig config) { Issuer issuer = new Issuer(require(config, OP_ISSUER)); String jwkSetUrl = require(config, OP_JWKSET_PATH); URI authorizationEndpoint; try { authorizationEndpoint = new URI(require(config, OP_AUTHORIZATION_ENDPOINT)); } catch (URISyntaxException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid URI: " + OP_AUTHORIZATION_ENDPOINT.getKey(), e); } String responseType = require(config, RP_RESPONSE_TYPE); String tokenEndpointString = config.getSetting(OP_TOKEN_ENDPOINT); if (responseType.equals("code") && tokenEndpointString.isEmpty()) { throw new SettingsException( "The configuration setting [" + OP_TOKEN_ENDPOINT.getConcreteSettingForNamespace(name()).getKey() + "] is required when [" + RP_RESPONSE_TYPE.getConcreteSettingForNamespace(name()).getKey() + "] is set to \"code\"" ); } URI tokenEndpoint; try { tokenEndpoint = tokenEndpointString.isEmpty() ? null : new URI(tokenEndpointString); } catch (URISyntaxException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid URL: " + OP_TOKEN_ENDPOINT.getKey(), e); } URI userinfoEndpoint; try { userinfoEndpoint = (config.getSetting(OP_USERINFO_ENDPOINT).isEmpty()) ? null : new URI(config.getSetting(OP_USERINFO_ENDPOINT)); } catch (URISyntaxException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid URI: " + OP_USERINFO_ENDPOINT.getKey(), e); } URI endsessionEndpoint; try { endsessionEndpoint = (config.getSetting(OP_ENDSESSION_ENDPOINT).isEmpty()) ? null : new URI(config.getSetting(OP_ENDSESSION_ENDPOINT)); } catch (URISyntaxException e) { // This should never happen as it's already validated in the settings throw new SettingsException("Invalid URI: " + OP_ENDSESSION_ENDPOINT.getKey(), e); } return new OpenIdConnectProviderConfiguration( issuer, jwkSetUrl, authorizationEndpoint, tokenEndpoint, userinfoEndpoint, endsessionEndpoint ); } private static String require(RealmConfig config, Setting.AffixSetting<String> setting) { final String value = config.getSetting(setting); if (value.isEmpty()) { throw new SettingsException("The configuration setting [" + RealmSettings.getFullSettingKey(config, setting) + "] is required"); } return value; } /** * Creates the URI for an OIDC Authentication Request from the realm configuration using URI Query String Serialization and * possibly generates a state parameter and a nonce. It then returns the URI, state and nonce encapsulated in a * {@link OpenIdConnectPrepareAuthenticationResponse}. A facilitator can provide a state and a nonce parameter in two cases: * <ul> * <li>In case of Kibana, it allows for a better UX by ensuring that all requests to an OpenID Connect Provider within * the same browser context (even across tabs) will use the same state and nonce values.</li> * <li>In case of custom facilitators, the implementer might require/support generating the state parameter in order * to tie this to an anti-XSRF token.</li> * </ul> * * * @param existingState An existing state that can be reused or null if we need to generate one * @param existingNonce An existing nonce that can be reused or null if we need to generate one * @param loginHint A String with a login hint to add to the authentication request in case of a 3rd party initiated login * * @return an {@link OpenIdConnectPrepareAuthenticationResponse} */ public OpenIdConnectPrepareAuthenticationResponse buildAuthenticationRequestUri( @Nullable String existingState, @Nullable String existingNonce, @Nullable String loginHint ) { final State state = existingState != null ? new State(existingState) : new State(); final Nonce nonce = existingNonce != null ? new Nonce(existingNonce) : new Nonce(); final AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder( rpConfiguration.getResponseType(), rpConfiguration.getRequestedScope(), rpConfiguration.getClientId(), rpConfiguration.getRedirectUri() ).endpointURI(opConfiguration.getAuthorizationEndpoint()).state(state).nonce(nonce); if (Strings.hasText(loginHint)) { builder.loginHint(loginHint); } return new OpenIdConnectPrepareAuthenticationResponse( builder.build().toURI().toString(), state.getValue(), nonce.getValue(), this.name() ); } public boolean isIssuerValid(String issuer) { return this.opConfiguration.getIssuer().getValue().equals(issuer); } public OpenIdConnectLogoutResponse buildLogoutResponse(JWT idTokenHint) { if (opConfiguration.getEndsessionEndpoint() != null) { final State state = new State(); final LogoutRequest logoutRequest = new LogoutRequest( opConfiguration.getEndsessionEndpoint(), idTokenHint, rpConfiguration.getPostLogoutRedirectUri(), state ); return new OpenIdConnectLogoutResponse(logoutRequest.toURI().toString()); } else { return new OpenIdConnectLogoutResponse((String) null); } } @Override public void close() { openIdConnectAuthenticator.close(); } /* * We only map claims that are of Type String, Boolean, or Number, or arrays that contain only these types */ private static boolean isAllowedTypeForClaim(Object o) { return (o instanceof String || o instanceof Boolean || o instanceof Number || (o instanceof Collection && ((Collection<?>) o).stream().allMatch(c -> c instanceof String || c instanceof Boolean || c instanceof Number))); } }
OpenIdConnectRealm
java
apache__camel
components/camel-workday/src/main/java/org/apache/camel/component/workday/auth/AuthenticationClient.java
{ "start": 1024, "end": 1156 }
interface ____ { void configure(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException; }
AuthenticationClient
java
spring-projects__spring-framework
spring-r2dbc/src/main/java/org/springframework/r2dbc/core/binding/Bindings.java
{ "start": 4356, "end": 5402 }
class ____ { private final BindMarker marker; protected Binding(BindMarker marker) { this.marker = marker; } /** * Return the associated {@link BindMarker}. */ public BindMarker getBindMarker() { return this.marker; } /** * Return whether the binding has a value associated with it. * @return {@code true} if there is a value present, * otherwise {@code false} for a {@code NULL} binding */ public abstract boolean hasValue(); /** * Return whether the binding is empty. * @return {@code true} if this is a {@code NULL} binding */ public boolean isNull() { return !hasValue(); } /** * Return the binding value. * @return the value of this binding * (can be {@code null} if this is a {@code NULL} binding) */ public abstract @Nullable Object getValue(); /** * Apply the binding to a {@link BindTarget}. * @param bindTarget the target to apply bindings to */ public abstract void apply(BindTarget bindTarget); } /** * Value binding. */ static
Binding
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/ExtendedRevisionListener.java
{ "start": 303, "end": 548 }
class ____ implements RevisionListener { public static final String COMMENT_VALUE = "Comment"; public void newRevision(Object revisionEntity) { ((ExtendedRevisionEntity) revisionEntity).setComment( COMMENT_VALUE ); } }
ExtendedRevisionListener
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/constraint/api/PlacedSchedulingRequest.java
{ "start": 1498, "end": 2851 }
class ____ { // The number of times the Algorithm tried to place the SchedulingRequest // after it was rejected by the commit phase of the Scheduler (due to some // transient state of the cluster. For eg: no space on Node / user limit etc.) // The Algorithm can then try to probably place on a different node. private int placementAttempt = 0; private final SchedulingRequest request; // One Node per numContainers in the SchedulingRequest; private final List<SchedulerNode> nodes = new ArrayList<>(); public PlacedSchedulingRequest(SchedulingRequest request) { this.request = request; } public SchedulingRequest getSchedulingRequest() { return request; } /** * List of Node locations on which this Scheduling Request can be placed. * The size of this list = schedulingRequest.resourceSizing.numAllocations. * @return List of Scheduler nodes. */ public List<SchedulerNode> getNodes() { return nodes; } public int getPlacementAttempt() { return placementAttempt; } public void setPlacementAttempt(int attempt) { this.placementAttempt = attempt; } @Override public String toString() { return "PlacedSchedulingRequest{" + "placementAttempt=" + placementAttempt + ", request=" + request + ", nodes=" + nodes + '}'; } }
PlacedSchedulingRequest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/HtmlTextRenderer.java
{ "start": 913, "end": 1378 }
class ____ implements TextRenderer { public HtmlTextRenderer(final String[] formats) { // TODO Auto-generated constructor stub } @Override public void render(final String input, final StringBuilder output, final String styleName) { // TODO Auto-generated method stub } @Override public void render(final StringBuilder input, final StringBuilder output) { // TODO Auto-generated method stub } }
HtmlTextRenderer
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/joda/JodaTest_7_DateTimeZone.java
{ "start": 555, "end": 611 }
class ____ { public DateTimeZone zone; } }
Model
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/annotations/BuildProducer.java
{ "start": 437, "end": 606 }
interface ____<T extends BuildItem> { void produce(T item); default void produce(Collection<T> items) { items.forEach(this::produce); } }
BuildProducer
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java
{ "start": 19074, "end": 19209 }
class ____ { ConsumingConfiguration(String testBean) { } } @Configuration(proxyBeanMethods = false) static
ConsumingConfiguration
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/FileEndpointBuilderFactory.java
{ "start": 167112, "end": 174311 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final FileHeaderNameBuilder INSTANCE = new FileHeaderNameBuilder(); /** * A long value containing the file size. * * The option is a: {@code long} type. * * Group: consumer * * @return the name of the header {@code FileLength}. */ public String fileLength() { return "CamelFileLength"; } /** * A Long value containing the last modified timestamp of the file. * * The option is a: {@code long} type. * * Group: consumer * * @return the name of the header {@code FileLastModified}. */ public String fileLastModified() { return "CamelFileLastModified"; } /** * The local work path. * * The option is a: {@code File} type. * * Group: producer * * @return the name of the header {@code FileLocalWorkPath}. */ public String fileLocalWorkPath() { return "CamelFileLocalWorkPath"; } /** * Only the file name (the name with no leading paths). * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileNameOnly}. */ public String fileNameOnly() { return "CamelFileNameOnly"; } /** * (producer) Specifies the name of the file to write (relative to the * endpoint directory). This name can be a String; a String with a file * or simple Language expression; or an Expression object. If it's null * then Camel will auto-generate a filename based on the message unique * ID. (consumer) Name of the consumed file as a relative file path with * offset from the starting directory configured on the endpoint. * * The option is a: {@code String} type. * * Group: common * * @return the name of the header {@code FileName}. */ public String fileName() { return "CamelFileName"; } /** * The name of the file that has been consumed. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileNameConsumed}. */ public String fileNameConsumed() { return "CamelFileNameConsumed"; } /** * A boolean option specifying whether the consumed file denotes an * absolute path or not. Should normally be false for relative paths. * Absolute paths should normally not be used but we added to the move * option to allow moving files to absolute paths. But can be used * elsewhere as well. * * The option is a: {@code Boolean} type. * * Group: consumer * * @return the name of the header {@code FileAbsolute}. */ public String fileAbsolute() { return "CamelFileAbsolute"; } /** * The absolute path to the file. For relative files this path holds the * relative path instead. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileAbsolutePath}. */ public String fileAbsolutePath() { return "CamelFileAbsolutePath"; } /** * The extended attributes of the file. * * The option is a: {@code Map<String, Object>} type. * * Group: consumer * * @return the name of the header {@code FileExtendedAttributes}. */ public String fileExtendedAttributes() { return "CamelFileExtendedAttributes"; } /** * The content type of the file. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileContentType}. */ public String fileContentType() { return "CamelFileContentType"; } /** * The file path. For relative files this is the starting directory. For * absolute files this is the absolute path. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FilePath}. */ public String filePath() { return "CamelFilePath"; } /** * The relative path. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code FileRelativePath}. */ public String fileRelativePath() { return "CamelFileRelativePath"; } /** * The parent path. * * The option is a: {@code String} type. * * Group: common * * @return the name of the header {@code FileParent}. */ public String fileParent() { return "CamelFileParent"; } /** * The actual absolute filepath (path name) for the output file that was * written. This header is set by Camel and its purpose is providing * end-users with the name of the file that was written. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code FileNameProduced}. */ public String fileNameProduced() { return "CamelFileNameProduced"; } /** * Is used for overruling CamelFileName header and use the value instead * (but only once, as the producer will remove this header after writing * the file). The value can be only be a String. Notice that if the * option fileName has been configured, then this is still being * evaluated. * * The option is a: {@code Object} type. * * Group: producer * * @return the name of the header {@code OverruleFileName}. */ public String overruleFileName() { return "CamelOverruleFileName"; } /** * A long value containing the initial offset. * * The option is a: {@code long} type. * * Group: consumer * * @return the name of the header {@code FileInitialOffset}. */ public String fileInitialOffset() { return "CamelFileInitialOffset"; } } static FileEndpointBuilder endpointBuilder(String componentName, String path) {
FileHeaderNameBuilder
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/api/ServerBuilderCustomizer.java
{ "start": 413, "end": 1172 }
interface ____<T extends ServerBuilder<T>> { /** * Customize a ServerBuilder instance. * * @param config server's configuration * @param builder Server builder instance */ default void customize(GrpcServerConfiguration config, T builder) { } /** * Customize a GrpcServerOptions instance. * * @param config server's configuration * @param options GrpcServerOptions instance */ default void customize(GrpcServerConfiguration config, GrpcServerOptions options) { } /** * Priority by which the customizers are applied. * Higher priority is applied later. * * @return the priority */ default int priority() { return 0; } }
ServerBuilderCustomizer
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/qualifiers/AnyQualifier.java
{ "start": 1018, "end": 2244 }
class ____<T> extends FilteringQualifier<T> { @SuppressWarnings("rawtypes") public static final AnyQualifier INSTANCE = new AnyQualifier(); private AnyQualifier() { } @Override public boolean doesQualify(Class<T> beanType, BeanType<T> candidate) { return true; } @Override public boolean doesQualify(Class<T> beanType, QualifiedBeanType<T> candidate) { return true; } @Override public <BT extends BeanType<T>> Stream<BT> reduce(Class<T> beanType, Stream<BT> candidates) { return candidates; } @Override public boolean contains(Qualifier<T> qualifier) { return true; } @Override public <BT extends BeanType<T>> Optional<BT> qualify(Class<T> beanType, Stream<BT> candidates) { return candidates.findFirst(); } @Override public boolean doesQualify(Class<T> beanType, Collection<? extends BeanType<T>> candidates) { return !candidates.isEmpty(); } @Override public <BT extends BeanType<T>> Collection<BT> filter(Class<T> beanType, Collection<BT> candidates) { return candidates; } @Override public String toString() { return "@Any"; } }
AnyQualifier
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/output/NumberListOutput.java
{ "start": 600, "end": 1829 }
class ____<K, V> extends CommandOutput<K, V, List<Number>> { private static final InternalLogger LOG = InternalLoggerFactory.getInstance(NumberListOutput.class); private boolean initialized; public NumberListOutput(RedisCodec<K, V> codec) { super(codec, new ArrayList<>()); } @Override public void set(ByteBuffer bytes) { output.add(bytes != null ? parseNumber(bytes) : null); } @Override public void set(double number) { output.add(number); } @Override public void set(long integer) { output.add(integer); } @Override public void setBigNumber(ByteBuffer bytes) { output.add(bytes != null ? parseNumber(bytes) : null); } @Override public void multi(int count) { if (!initialized) { output = OutputFactory.newList(count); initialized = true; } } private Number parseNumber(ByteBuffer bytes) { Number result = 0; try { result = NumberFormat.getNumberInstance().parse(decodeString(bytes)); } catch (ParseException e) { LOG.warn("Failed to parse " + bytes, e); } return result; } }
NumberListOutput
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/retry/RetryPolicy.java
{ "start": 994, "end": 1073 }
interface ____ be immutable. * </p> */ @InterfaceStability.Evolving public
should
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/strings/Strings_assertStartsWithIgnoringCase_Test.java
{ "start": 1513, "end": 4272 }
class ____ extends StringsBaseTest { @Test void should_pass_if_actual_starts_with_prefix() { strings.assertStartsWithIgnoringCase(INFO, "Yoda", "YODA"); strings.assertStartsWithIgnoringCase(INFO, "Yoda", "YO"); strings.assertStartsWithIgnoringCase(INFO, "Yoda", "Yo"); strings.assertStartsWithIgnoringCase(INFO, "Yoda", "yo"); strings.assertStartsWithIgnoringCase(INFO, "Yoda", "Y"); strings.assertStartsWithIgnoringCase(INFO, "Yoda", "y"); } @Test void should_fail_if_actual_does_not_start_with_prefix() { // WHEN var assertionError = expectAssertionError(() -> strings.assertStartsWithIgnoringCase(INFO, "Yoda", "Luke")); // THEN then(assertionError).hasMessage(shouldStartWithIgnoringCase("Yoda", "Luke", StandardComparisonStrategy.instance()).create()); } @Test void should_throw_error_if_prefix_is_null() { assertThatNullPointerException().isThrownBy(() -> strings.assertStartsWithIgnoringCase(INFO, "Yoda", null)) .withMessage("The given prefix should not be null"); } @Test void should_fail_if_actual_is_null() { // WHEN var assertionError = expectAssertionError(() -> strings.assertStartsWithIgnoringCase(INFO, null, "Yoda")); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_pass_if_actual_starts_with_prefix_according_to_custom_comparison_strategy() { // GIVEN ComparisonStrategy hashCodeComparisonStrategy = new ComparatorBasedComparisonStrategy(new StringHashCodeTestComparator()); Strings stringsWithHashCodeComparisonStrategy = new Strings(hashCodeComparisonStrategy); // WHEN/THEN stringsWithHashCodeComparisonStrategy.assertStartsWithIgnoringCase(INFO, "Yoda", "yod"); } @Test void should_fail_if_actual_does_not_start_with_prefix_according_to_custom_comparison_strategy() { // GIVEN ComparisonStrategy hashCodeComparisonStrategy = new ComparatorBasedComparisonStrategy(new StringHashCodeTestComparator()); // WHEN var assertionError = expectAssertionError(() -> new Strings(hashCodeComparisonStrategy).assertStartsWithIgnoringCase(INFO, "Yoda", "Luke")); // THEN then(assertionError).hasMessage(shouldStartWithIgnoringCase("Yoda", "Luke", hashCodeComparisonStrategy).create()); } @Test @DefaultLocale("tr-TR") void should_pass_with_Turkish_default_locale() { // WHEN/THEN strings.assertStartsWithIgnoringCase(INFO, "Leia", "LEI"); } }
Strings_assertStartsWithIgnoringCase_Test
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java
{ "start": 1819, "end": 2026 }
class ____. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?> dc, ClassLoader cl) { return mixin(ics, new Class[] {dc}, cl); } /** * mixin
loader
java
alibaba__nacos
maintainer-client/src/test/java/com/alibaba/nacos/maintainer/client/model/HttpRequestTest.java
{ "start": 860, "end": 2473 }
class ____ { @Test void testBuild() { HttpRequest.Builder builder = new HttpRequest.Builder(); builder.setHttpMethod("GET"); builder.setPath("/nacos/v3/admin/ns/instance"); builder.setParamValue(Collections.singletonMap("test", "value")); builder.addHeader(Collections.singletonMap("testH", "value")); builder.setBody("testBody"); HttpRequest httpRequest = builder.build(); assertNotNull(httpRequest); assertEquals("GET", httpRequest.getHttpMethod()); assertEquals("/nacos/v3/admin/ns/instance", httpRequest.getPath()); assertEquals("value", httpRequest.getParamValues().get("test")); assertEquals("value", httpRequest.getHeaders().get("testH")); assertEquals("testBody", httpRequest.getBody()); } @Test void testSetter() { HttpRequest httpRequest = new HttpRequest.Builder().build(); httpRequest.setHttpMethod("GET"); httpRequest.setPath("/nacos/v3/admin/ns/instance"); httpRequest.setParamValues(Collections.singletonMap("test", "value")); httpRequest.setHeaders(Collections.singletonMap("testH", "value")); httpRequest.setBody("testBody"); assertNotNull(httpRequest); assertEquals("GET", httpRequest.getHttpMethod()); assertEquals("/nacos/v3/admin/ns/instance", httpRequest.getPath()); assertEquals("value", httpRequest.getParamValues().get("test")); assertEquals("value", httpRequest.getHeaders().get("testH")); assertEquals("testBody", httpRequest.getBody()); } }
HttpRequestTest
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/resequencer/SequenceSender.java
{ "start": 862, "end": 1019 }
interface ____ by the {@link ResequencerEngine#deliver()} and {@link ResequencerEngine#deliverNext()} methods to * send out re-ordered elements. */ public
used
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/DefaultMethodTests.java
{ "start": 1675, "end": 7814 }
class ____ extends AbstractJupiterTestEngineTests { private static boolean beforeAllInvoked; private static boolean afterAllInvoked; private static boolean defaultMethodInvoked; private static boolean overriddenDefaultMethodInvoked; private static boolean localMethodInvoked; @BeforeEach void resetFlags() { beforeAllInvoked = false; afterAllInvoked = false; defaultMethodInvoked = false; overriddenDefaultMethodInvoked = false; localMethodInvoked = false; } @Test void executeTestCaseWithDefaultMethodFromInterfaceSelectedByFullyQualifedMethodName() { String fqmn = TestCaseWithDefaultMethod.class.getName() + "#test"; LauncherDiscoveryRequest request = request().selectors(selectMethod(fqmn)).build(); EngineExecutionResults executionResults = executeTests(request); // @formatter:off assertAll( () -> assertTrue(beforeAllInvoked, "@BeforeAll static method invoked from interface"), () -> assertTrue(afterAllInvoked, "@AfterAll static method invoked from interface"), () -> assertTrue(defaultMethodInvoked, "default @Test method invoked from interface"), () -> assertEquals(1, executionResults.testEvents().started().count(), "# tests started"), () -> assertEquals(1, executionResults.testEvents().succeeded().count(), "# tests succeeded"), () -> assertEquals(0, executionResults.testEvents().failed().count(), "# tests failed") ); // @formatter:on } @Test void executeTestCaseWithDefaultMethodFromGenericInterfaceSelectedByFullyQualifedMethodName() { String fqmn = GenericTestCaseWithDefaultMethod.class.getName() + "#test(" + Long.class.getName() + ")"; LauncherDiscoveryRequest request = request().selectors(selectMethod(fqmn)).build(); EngineExecutionResults executionResults = executeTests(request); // @formatter:off assertAll( () -> assertTrue(beforeAllInvoked, "@BeforeAll default method invoked from interface"), () -> assertTrue(afterAllInvoked, "@AfterAll default method invoked from interface"), () -> assertTrue(defaultMethodInvoked, "default @Test method invoked from interface"), () -> assertFalse(localMethodInvoked, "local @Test method should not have been invoked from class"), () -> assertEquals(1, executionResults.testEvents().started().count(), "# tests started"), () -> assertEquals(1, executionResults.testEvents().succeeded().count(), "# tests succeeded"), () -> assertEquals(0, executionResults.testEvents().failed().count(), "# tests failed") ); // @formatter:on } @Test void executeTestCaseWithOverloadedMethodNextToGenericDefaultMethodSelectedByFullyQualifedMethodName() { String fqmn = GenericTestCaseWithDefaultMethod.class.getName() + "#test(" + Double.class.getName() + ")"; LauncherDiscoveryRequest request = request().selectors(selectMethod(fqmn)).build(); EngineExecutionResults executionResults = executeTests(request); // @formatter:off assertAll( () -> assertTrue(beforeAllInvoked, "@BeforeAll default method invoked from interface"), () -> assertTrue(afterAllInvoked, "@AfterAll default method invoked from interface"), () -> assertFalse(defaultMethodInvoked, "default @Test method should not have been invoked from interface"), () -> assertTrue(localMethodInvoked, "local @Test method invoked from class"), () -> assertEquals(1, executionResults.testEvents().started().count(), "# tests started"), () -> assertEquals(1, executionResults.testEvents().succeeded().count(), "# tests succeeded"), () -> assertEquals(0, executionResults.testEvents().failed().count(), "# tests failed") ); // @formatter:on } @Test void executeTestCaseWithOverloadedMethodNextToGenericDefaultMethodSelectedByClass() { Class<?> clazz = GenericTestCaseWithDefaultMethod.class; LauncherDiscoveryRequest request = request().selectors(selectClass(clazz)).build(); EngineExecutionResults executionResults = executeTests(request); // @formatter:off assertAll( () -> assertTrue(beforeAllInvoked, "@BeforeAll default method invoked from interface"), () -> assertTrue(afterAllInvoked, "@AfterAll default method invoked from interface"), () -> assertTrue(defaultMethodInvoked, "default @Test method invoked from interface"), () -> assertTrue(localMethodInvoked, "local @Test method invoked from class"), () -> assertEquals(2, executionResults.testEvents().started().count(), "# tests started"), () -> assertEquals(2, executionResults.testEvents().succeeded().count(), "# tests succeeded"), () -> assertEquals(0, executionResults.testEvents().failed().count(), "# tests failed") ); // @formatter:on } @Test void executeTestCaseWithOverriddenGenericDefaultMethodSelectedByClass() { Class<?> clazz = GenericTestCaseWithOverriddenDefaultMethod.class; LauncherDiscoveryRequest request = request().selectors(selectClass(clazz)).build(); EngineExecutionResults executionResults = executeTests(request); // @formatter:off assertAll( () -> assertTrue(beforeAllInvoked, "@BeforeAll default method invoked from interface"), () -> assertTrue(afterAllInvoked, "@AfterAll default method invoked from interface"), () -> assertFalse(defaultMethodInvoked, "default @Test method should not have been invoked from interface"), () -> assertTrue(overriddenDefaultMethodInvoked, "overridden default @Test method invoked from interface"), () -> assertTrue(localMethodInvoked, "local @Test method invoked from class"), // If defaultMethodInvoked is false and the following ends up being // 3 instead of 2, that means that the overriding method gets invoked // twice: once as itself and a second time "as" the default method which // should not have been "discovered" since it is overridden. () -> assertEquals(2, executionResults.testEvents().started().count(), "# tests started"), () -> assertEquals(2, executionResults.testEvents().succeeded().count(), "# tests succeeded"), () -> assertEquals(0, executionResults.testEvents().failed().count(), "# tests failed") ); // @formatter:on } // -------------------------------------------------------------------------
DefaultMethodTests
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1665/Issue1665Test.java
{ "start": 576, "end": 1059 }
class ____ { @ProcessorTest public void shouldBoxIntPrimitive() { Source source = new Source(); List<Integer> values = new ArrayList<>(); values.add( 10 ); source.setValue( values ); Target target = Issue1665Mapper.INSTANCE.map( source ); assertThat( target.getValue().size() ).isEqualTo( source.getValue().size() ); assertThat( target.getValue().get( 0 ) ).isEqualTo( source.getValue().get( 0 ) ); } }
Issue1665Test
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/InternalWatchExecutor.java
{ "start": 555, "end": 1369 }
class ____ implements WatchExecutor { public static final String THREAD_POOL_NAME = XPackField.WATCHER; private final ThreadPool threadPool; public InternalWatchExecutor(ThreadPool threadPool) { this.threadPool = threadPool; } @Override public BlockingQueue<Runnable> queue() { return executor().getQueue(); } @Override public Stream<Runnable> tasks() { return executor().getTasks(); } @Override public long largestPoolSize() { return executor().getLargestPoolSize(); } @Override public void execute(Runnable runnable) { executor().execute(runnable); } private EsThreadPoolExecutor executor() { return (EsThreadPoolExecutor) threadPool.executor(THREAD_POOL_NAME); } }
InternalWatchExecutor
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/syncjob/action/RestPostConnectorSyncJobAction.java
{ "start": 925, "end": 1798 }
class ____ extends BaseRestHandler { @Override public String getName() { return "connector_sync_job_post_action"; } @Override public List<Route> routes() { return List.of(new Route(POST, "/" + EnterpriseSearch.CONNECTOR_SYNC_JOB_API_ENDPOINT)); } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { try (XContentParser parser = restRequest.contentParser()) { PostConnectorSyncJobAction.Request request = PostConnectorSyncJobAction.Request.fromXContent(parser); return channel -> client.execute( PostConnectorSyncJobAction.INSTANCE, request, new RestToXContentListener<>(channel, r -> RestStatus.CREATED, r -> null) ); } } }
RestPostConnectorSyncJobAction
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingWhenString.java
{ "start": 1037, "end": 1122 }
class ____ { public String value; } public static
ModelWithOutJsonField
java
apache__camel
tooling/openapi-rest-dsl-generator/src/main/java/org/apache/camel/generator/openapi/RestDslXmlGenerator.java
{ "start": 1599, "end": 5084 }
class ____ extends RestDslGenerator<RestDslXmlGenerator> { RestDslXmlGenerator(final OpenAPI document) { super(document); } public String generate(final CamelContext context) throws Exception { final RestDefinitionEmitter emitter = new RestDefinitionEmitter(); final String basePath = RestDslGenerator.determineBasePathFrom(this.basePath, document); final PathVisitor<RestsDefinition> restDslStatement = new PathVisitor<>( basePath, emitter, filter, destinationGenerator(), dtoPackageName); for (String name : document.getPaths().keySet()) { PathItem item = document.getPaths().get(name); restDslStatement.visit(document, name, item); } final RestsDefinition rests = emitter.result(); final String xml = new LwModelToXMLDumper().dumpModelAsXml(context, rests); final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); builderFactory.setNamespaceAware(true); final DocumentBuilder builder = builderFactory.newDocumentBuilder(); final Document document = builder.parse(new InputSource(new StringReader(xml))); final Element root = document.getDocumentElement(); // remove all customId attributes as we do not want them in the output final NodeList elements = document.getElementsByTagName("*"); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); element.removeAttribute("customId"); } boolean restConfig = restComponent != null || restContextPath != null || clientRequestValidation; if (restConfig) { final Element configuration = document.createElement("restConfiguration"); if (ObjectHelper.isNotEmpty(restComponent)) { configuration.setAttribute("component", restComponent); } if (ObjectHelper.isNotEmpty(restContextPath)) { configuration.setAttribute("contextPath", restContextPath); } if (ObjectHelper.isNotEmpty(apiContextPath)) { configuration.setAttribute("apiContextPath", apiContextPath); } if (clientRequestValidation) { configuration.setAttribute("clientRequestValidation", "true"); } root.insertBefore(configuration, root.getFirstChild()); } final TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); try { transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); } catch (IllegalArgumentException e) { // ignore } try { transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); } catch (IllegalArgumentException e) { // ignore } final Transformer transformer = transformerFactory.newTransformer(); final StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.toString(); } }
RestDslXmlGenerator
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/constructornoinject/ObservesParamConstructorTest.java
{ "start": 1042, "end": 1141 }
class ____ { @Inject public MyBean(@Observes String ignored) { } } }
MyBean
java
apache__camel
components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringExcludeRoutesTest.java
{ "start": 1042, "end": 1247 }
class ____ extends CamelSpringPlainTest { @Override @Test public void testExcludedRoute() { assertNull(camelContext.getRoute("excludedRoute")); } }
CamelSpringExcludeRoutesTest
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/converter/ByteArrayMessageConverter.java
{ "start": 1060, "end": 1672 }
class ____ extends AbstractMessageConverter { public ByteArrayMessageConverter() { super(MimeTypeUtils.APPLICATION_OCTET_STREAM); } @Override protected boolean supports(Class<?> clazz) { return (byte[].class == clazz); } @Override protected @Nullable Object convertFromInternal( Message<?> message, @Nullable Class<?> targetClass, @Nullable Object conversionHint) { return message.getPayload(); } @Override protected @Nullable Object convertToInternal( Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) { return payload; } }
ByteArrayMessageConverter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 11876, "end": 12188 }
class ____ { public void doTest() { Client client = new Client(); client.something(); } } """) .addOutputLines( "out/Caller.java", """ import com.google.A; public final
Caller
java
google__error-prone
check_api/src/main/java/com/google/errorprone/scanner/InstanceReturningScannerSupplierImpl.java
{ "start": 1158, "end": 2078 }
class ____ extends ScannerSupplier { private final Scanner scanner; InstanceReturningScannerSupplierImpl(Scanner scanner) { this.scanner = scanner; } @Override public Scanner get() { return scanner; } @Override public ImmutableBiMap<String, BugCheckerInfo> getAllChecks() { // TODO(cushon): migrate users off Scanner-based ScannerSuppliers, and throw UOE here return ImmutableBiMap.of(); } @Override public ImmutableMap<String, SeverityLevel> severities() { throw new UnsupportedOperationException(); } @Override protected ImmutableSet<String> disabled() { throw new UnsupportedOperationException(); } @Override public ErrorProneFlags getFlags() { throw new UnsupportedOperationException(); } @Override public ImmutableSet<BugCheckerInfo> getEnabledChecks() { throw new UnsupportedOperationException(); } }
InstanceReturningScannerSupplierImpl
java
reactor__reactor-core
reactor-core/src/test/java/reactor/test/MockUtils.java
{ "start": 963, "end": 1003 }
class ____ { /** * An abstract
MockUtils
java
greenrobot__EventBus
EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusBuilderTest.java
{ "start": 2926, "end": 3092 }
class ____ { @Subscribe public void onEvent(NoSubscriberEvent event) { trackEvent(event); } } public
NoSubscriberEventTracker
java
apache__dubbo
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java
{ "start": 1640, "end": 5789 }
class ____ { private static final Logger logger = LoggerFactory.getLogger(TraceFilterTest.class); private MockChannel mockChannel; private static final String TRACE_MAX = "trace.max"; private static final String TRACE_COUNT = "trace.count"; private static final String TRACERS_FIELD_NAME = "TRACERS"; @BeforeEach public void setUp() { URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo"); mockChannel = new MockChannel(url); } @AfterEach public void tearDown() { mockChannel.close(); } @Test void testAddAndRemoveTracer() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 100); Assertions.assertEquals(100, mockChannel.getAttribute(TRACE_MAX)); Assertions.assertTrue(mockChannel.getAttribute(TRACE_COUNT) instanceof AtomicInteger); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> o = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Assertions.assertTrue(o.containsKey(key)); Set<Channel> channels = o.get(key); Assertions.assertNotNull(channels); Assertions.assertTrue(channels.contains(mockChannel)); // remove tracer TraceFilter.removeTracer(type, method, mockChannel); Assertions.assertNull(mockChannel.getAttribute(TRACE_MAX)); Assertions.assertNull(mockChannel.getAttribute(TRACE_COUNT)); Assertions.assertFalse(channels.contains(mockChannel)); } @Test void testInvoke() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 2); Invoker<DemoService> mockInvoker = mock(Invoker.class); Invocation mockInvocation = mock(Invocation.class); Result mockResult = mock(Result.class); TraceFilter filter = new TraceFilter(); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvocation.getMethodName()).willReturn(method); given(mockInvocation.getArguments()).willReturn(new Object[0]); given(mockInvoker.invoke(mockInvocation)).willReturn(mockResult); given(mockResult.getValue()).willReturn("result"); // test invoke filter.invoke(mockInvoker, mockInvocation); String message = listToString(mockChannel.getReceivedObjects()); String expectMessage = "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.sayHello([]) -> \"result\""; logger.info("actual message: {}", message); Assertions.assertTrue(message.contains(expectMessage)); Assertions.assertTrue(message.contains("elapsed:")); AtomicInteger traceCount = (AtomicInteger) mockChannel.getAttribute(TRACE_COUNT); Assertions.assertEquals(1, traceCount.get()); // test remove channel when count >= max - 1 filter.invoke(mockInvoker, mockInvocation); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> o = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Assertions.assertTrue(o.containsKey(key)); Set<Channel> channels = o.get(key); Assertions.assertNotNull(channels); Assertions.assertFalse(channels.contains(mockChannel)); } private static String listToString(List<Object> objectList) { StringBuilder sb = new StringBuilder(); if (CollectionUtils.isEmpty(objectList)) { return ""; } objectList.forEach(o -> { sb.append(o.toString()); }); return sb.toString(); } }
TraceFilterTest
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/UninterruptiblesTest.java
{ "start": 26418, "end": 26840 }
class ____ extends DelayedActionRunnable { private final BlockingQueue<String> queue; EnableWrites(BlockingQueue<String> queue, long tMinus) { super(tMinus); assertFalse(queue.isEmpty()); assertFalse(queue.offer("shouldBeRejected")); this.queue = queue; } @Override protected void doAction() { assertThat(queue.remove()).isNotNull(); } } private static
EnableWrites
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java
{ "start": 9010, "end": 9613 }
class ____ implements EventHandler<RMAppAttemptEvent> { @Override public void handle(RMAppAttemptEvent event) { ApplicationAttemptId appID = event.getApplicationAttemptId(); assertEquals(applicationAttempt.getAppAttemptId(), appID); try { applicationAttempt.handle(event); } catch (Throwable t) { LOG.error("Error in handling event type " + event.getType() + " for application " + appID, t); } } } // handle all the RM application events - same as in ResourceManager.java private final
TestApplicationAttemptEventDispatcher
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/UnionTableReference.java
{ "start": 345, "end": 2299 }
class ____ extends NamedTableReference { private final String[] subclassTableSpaceExpressions; public UnionTableReference( String unionTableExpression, String[] subclassTableSpaceExpressions, String identificationVariable) { this( unionTableExpression, subclassTableSpaceExpressions, identificationVariable, false ); } public UnionTableReference( String unionTableExpression, String[] subclassTableSpaceExpressions, String identificationVariable, boolean isOptional) { super( unionTableExpression, identificationVariable, isOptional ); this.subclassTableSpaceExpressions = subclassTableSpaceExpressions; } @Override public TableReference resolveTableReference( NavigablePath navigablePath, String tableExpression) { if ( hasTableExpression( tableExpression ) ) { return this; } throw new UnknownTableReferenceException( tableExpression, String.format( Locale.ROOT, "Unable to determine TableReference (`%s`) for `%s`", tableExpression, navigablePath ) ); } @Override public TableReference getTableReference( NavigablePath navigablePath, String tableExpression, boolean resolve) { if ( hasTableExpression( tableExpression ) ) { return this; } return null; } private boolean hasTableExpression(String tableExpression) { for ( String expression : subclassTableSpaceExpressions ) { if ( tableExpression.equals( expression ) ) { return true; } } return false; } @Override public boolean containsAffectedTableName(String requestedName) { return isEmpty( requestedName ) || hasTableExpression( requestedName ); } @Override public Boolean visitAffectedTableNames(Function<String, Boolean> nameCollector) { for ( String expression : subclassTableSpaceExpressions ) { final Boolean result = nameCollector.apply( expression ); if ( result != null ) { return result; } } return null; } }
UnionTableReference
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MemoizeConstantVisitorStateLookupsTest.java
{ "start": 4000, "end": 4616 }
class ____ { public Test(VisitorState state) { Name className = state.getName("java.lang.Class"); Type classType = state.getTypeFromString("java.lang.Class"); Name lookupAgain = state.getName("java.lang.Class"); } } """) .addOutputLines( "Test.java", """ import com.google.errorprone.VisitorState; import com.google.errorprone.suppliers.Supplier; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.Name;
Test
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/JSONPath.java
{ "start": 111544, "end": 114274 }
class ____ extends PropertyFilter { private final Segment refSgement; private final Operator op; public RefOpSegement(String propertyName, boolean function, Segment refSgement, Operator op){ super(propertyName, function); this.refSgement = refSgement; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } Object refValue = refSgement.eval(path, rootObject, rootObject); if (refValue instanceof Integer || refValue instanceof Long || refValue instanceof Short || refValue instanceof Byte) { long value = TypeUtils.longExtractValue((Number) refValue); if (propertyValue instanceof Integer || propertyValue instanceof Long || propertyValue instanceof Short || propertyValue instanceof Byte) { long longValue = TypeUtils.longExtractValue((Number) propertyValue); switch (op) { case EQ: return longValue == value; case NE: return longValue != value; case GE: return longValue >= value; case GT: return longValue > value; case LE: return longValue <= value; case LT: return longValue < value; } } else if (propertyValue instanceof BigDecimal) { BigDecimal valueDecimal = BigDecimal.valueOf(value); int result = valueDecimal.compareTo((BigDecimal) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } } throw new UnsupportedOperationException(); } } static
RefOpSegement
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotations.java
{ "start": 1775, "end": 5237 }
interface ____ { * * &#064;AliasFor(attribute = "path") * String[] value() default {}; * * &#064;AliasFor(attribute = "value") * String[] path() default {}; * } * </pre> * * <p>If a method is annotated with {@code @PostMapping("/home")} it will contain * merged annotations for both {@code @PostMapping} and the meta-annotation * {@code @RequestMapping}. The merged view of the {@code @RequestMapping} * annotation will contain the following attributes: * * <p><table border="1"> * <tr> * <th>Name</th> * <th>Value</th> * <th>Source</th> * </tr> * <tr> * <td>value</td> * <td>"/home"</td> * <td>Declared in {@code @PostMapping}</td> * </tr> * <tr> * <td>path</td> * <td>"/home"</td> * <td>Explicit {@code @AliasFor}</td> * </tr> * <tr> * <td>method</td> * <td>RequestMethod.POST</td> * <td>Declared in meta-annotation</td> * </tr> * </table> * * <p>{@code MergedAnnotations} can be obtained {@linkplain #from(AnnotatedElement) * from} any Java {@link AnnotatedElement}. They may also be used for sources that * don't use reflection (such as those that directly parse bytecode). * * <p>Different {@linkplain SearchStrategy search strategies} can be used to locate * related source elements that contain the annotations to be aggregated. For * example, the following code uses {@link SearchStrategy#TYPE_HIERARCHY} to * search for annotations on {@code MyClass} as well as in superclasses and implemented * interfaces. * * <pre class="code"> * MergedAnnotations mergedAnnotations = * MergedAnnotations.search(TYPE_HIERARCHY).from(MyClass.class); * </pre> * * <p>From a {@code MergedAnnotations} instance you can either * {@linkplain #get(String) get} a single annotation, or {@linkplain #stream() * stream all annotations} or just those that match {@linkplain #stream(String) * a specific type}. You can also quickly tell if an annotation * {@linkplain #isPresent(String) is present}. * * <p>Here are some typical examples: * * <pre class="code"> * // is an annotation present or meta-present? * mergedAnnotations.isPresent(ExampleAnnotation.class); * * // get the merged "value" attribute of ExampleAnnotation (either directly or * // meta-present) * mergedAnnotations.get(ExampleAnnotation.class).getString("value"); * * // get all meta-annotations but no directly present annotations * mergedAnnotations.stream().filter(MergedAnnotation::isMetaPresent); * * // get all ExampleAnnotation declarations (including any meta-annotations) and * // print the merged "value" attributes * mergedAnnotations.stream(ExampleAnnotation.class) * .map(mergedAnnotation -&gt; mergedAnnotation.getString("value")) * .forEach(System.out::println); * </pre> * * <p><b>NOTE: The {@code MergedAnnotations} API and its underlying model have * been designed for composable annotations in Spring's common component model, * with a focus on attribute aliasing and meta-annotation relationships.</b> * There is no support for retrieving plain Java annotations with this API; * please use standard Java reflection or Spring's {@link AnnotationUtils} * for simple annotation retrieval purposes. * * @author Phillip Webb * @author Sam Brannen * @since 5.2 * @see MergedAnnotation * @see MergedAnnotationCollectors * @see MergedAnnotationPredicates * @see MergedAnnotationSelectors * @see AliasFor * @see AnnotationUtils * @see AnnotatedElementUtils */ public
PostMapping
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpMoveFileRecursiveNotStepwiseIT.java
{ "start": 939, "end": 1283 }
class ____ extends FromFtpMoveFileRecursiveIT { @Override protected String getFtpUrl() { return "ftp://admin@localhost:{{ftp.server.port}}/movefile?password=admin&recursive=true&binary=false" + "&move=.done/${file:name}.old&initialDelay=2500&delay=5000&stepwise=false"; } }
FromFtpMoveFileRecursiveNotStepwiseIT
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/datastreams/autosharding/DataStreamAutoShardingService.java
{ "start": 2162, "end": 4919 }
class ____ { private static final Logger logger = LogManager.getLogger(DataStreamAutoShardingService.class); public static final String DATA_STREAMS_AUTO_SHARDING_ENABLED = "data_streams.auto_sharding.enabled"; public static final Setting<List<String>> DATA_STREAMS_AUTO_SHARDING_EXCLUDES_SETTING = Setting.listSetting( "data_streams.auto_sharding.excludes", List.of(), Function.identity(), Setting.Property.Dynamic, Setting.Property.NodeScope ); /** * Represents the minimum amount of time between two scaling events if the next event will increase the number of shards. * We've chosen a value of 4.5minutes by default, just lower than the data stream lifecycle poll interval so we can increase shards with * every DSL run, but we don't want it to be lower/0 as data stream lifecycle might run more often than the poll interval in case of * a master failover. */ public static final Setting<TimeValue> DATA_STREAMS_AUTO_SHARDING_INCREASE_SHARDS_COOLDOWN = Setting.timeSetting( "data_streams.auto_sharding.increase_shards.cooldown", TimeValue.timeValueSeconds(270), TimeValue.timeValueSeconds(0), Setting.Property.Dynamic, Setting.Property.NodeScope ); /** * Represents the minimum amount of time between two scaling events if the next event will reduce the number of shards. */ public static final Setting<TimeValue> DATA_STREAMS_AUTO_SHARDING_DECREASE_SHARDS_COOLDOWN = Setting.timeSetting( "data_streams.auto_sharding.decrease_shards.cooldown", TimeValue.timeValueDays(3), TimeValue.timeValueSeconds(0), Setting.Property.Dynamic, Setting.Property.NodeScope ); /** * Represents the minimum number of write threads we expect a node to have in the environments where auto sharding will be enabled. */ public static final Setting<Integer> CLUSTER_AUTO_SHARDING_MIN_WRITE_THREADS = Setting.intSetting( "cluster.auto_sharding.min_write_threads", 2, 1, Setting.Property.Dynamic, Setting.Property.NodeScope ); /** * Represents the maximum number of write threads we expect a node to have in the environments where auto sharding will be enabled. */ public static final Setting<Integer> CLUSTER_AUTO_SHARDING_MAX_WRITE_THREADS = Setting.intSetting( "cluster.auto_sharding.max_write_threads", 32, 1, Setting.Property.Dynamic, Setting.Property.NodeScope ); /** * Enumerates the different ways of measuring write load which we can choose between to use in the auto-sharding calculations. */ public
DataStreamAutoShardingService
java
quarkusio__quarkus
extensions/panache/hibernate-orm-rest-data-panache/deployment/src/main/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/HibernateOrmPanacheRestProcessor.java
{ "start": 1894, "end": 8780 }
class ____ { private static final DotName PANACHE_ENTITY_RESOURCE_INTERFACE = DotName .createSimple(PanacheEntityResource.class.getName()); private static final DotName PANACHE_REPOSITORY_RESOURCE_INTERFACE = DotName .createSimple(PanacheRepositoryResource.class.getName()); private static final DotName REST_DATA_RESOURCE_METHOD_LISTENER_INTERFACE = DotName .createSimple(RestDataResourceMethodListener.class.getName()); @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(HIBERNATE_ORM_REST_DATA_PANACHE); } @BuildStep void findResourceMethodListeners(CombinedIndexBuildItem index, BuildProducer<ResourceMethodListenerBuildItem> resourceMethodListeners) { for (ClassInfo classInfo : index.getIndex().getKnownDirectImplementors(REST_DATA_RESOURCE_METHOD_LISTENER_INTERFACE)) { List<Type> generics = getGenericTypes(classInfo); Type entityType = generics.get(0); resourceMethodListeners.produce(new ResourceMethodListenerBuildItem(classInfo, entityType)); } } @BuildStep void registerRestDataPanacheExceptionMapper( BuildProducer<ResteasyJaxrsProviderBuildItem> resteasyJaxrsProviderBuildItemBuildProducer, BuildProducer<ExceptionMapperBuildItem> exceptionMapperBuildItemBuildProducer) { resteasyJaxrsProviderBuildItemBuildProducer .produce(new ResteasyJaxrsProviderBuildItem(RestDataPanacheExceptionMapper.class.getName())); exceptionMapperBuildItemBuildProducer .produce(new ExceptionMapperBuildItem(RestDataPanacheExceptionMapper.class.getName(), RestDataPanacheException.class.getName(), Priorities.USER + 100, false)); } @BuildStep AdditionalBeanBuildItem registerTransactionalExecutor() { return AdditionalBeanBuildItem.unremovableOf(TransactionalUpdateExecutor.class); } /** * Find Panache entity resources and generate their implementations. */ @BuildStep void findEntityResources(CombinedIndexBuildItem index, List<ResourceMethodListenerBuildItem> resourceMethodListeners, BuildProducer<GeneratedBeanBuildItem> implementationsProducer, BuildProducer<RestDataResourceBuildItem> restDataResourceProducer) { ResourceImplementor resourceImplementor = new ResourceImplementor(new EntityClassHelper(index.getComputingIndex())); ClassOutput classOutput = new GeneratedBeanGizmoAdaptor(implementationsProducer); for (ClassInfo resourceInterface : index.getComputingIndex() .getKnownDirectImplementors(PANACHE_ENTITY_RESOURCE_INTERFACE)) { validateResource(index.getComputingIndex(), resourceInterface); List<Type> generics = getGenericTypes(resourceInterface); String entityType = generics.get(0).name().toString(); String idType = generics.get(1).name().toString(); List<ClassInfo> listenersForEntityType = getListenersByEntityType(index.getIndex(), resourceMethodListeners, entityType); DataAccessImplementor dataAccessImplementor = new EntityDataAccessImplementor(entityType); String resourceClass = resourceImplementor.implement( classOutput, dataAccessImplementor, resourceInterface, entityType, listenersForEntityType); restDataResourceProducer.produce(new RestDataResourceBuildItem( new ResourceMetadata(resourceClass, resourceInterface, entityType, idType, getEntityFields(index.getIndex(), entityType)))); } } /** * Find Panache repository resources and generate their implementations. */ @BuildStep void findRepositoryResources(CombinedIndexBuildItem index, List<ResourceMethodListenerBuildItem> resourceMethodListeners, BuildProducer<GeneratedBeanBuildItem> implementationsProducer, BuildProducer<RestDataResourceBuildItem> restDataResourceProducer, BuildProducer<UnremovableBeanBuildItem> unremovableBeansProducer) { ResourceImplementor resourceImplementor = new ResourceImplementor(new EntityClassHelper(index.getComputingIndex())); ClassOutput classOutput = new GeneratedBeanGizmoAdaptor(implementationsProducer); for (ClassInfo resourceInterface : index.getComputingIndex() .getKnownDirectImplementors(PANACHE_REPOSITORY_RESOURCE_INTERFACE)) { validateResource(index.getComputingIndex(), resourceInterface); List<Type> generics = getGenericTypes(resourceInterface); String repositoryClassName = generics.get(0).name().toString(); String entityType = generics.get(1).name().toString(); String idType = generics.get(2).name().toString(); List<ClassInfo> listenersForEntityType = getListenersByEntityType(index.getIndex(), resourceMethodListeners, entityType); DataAccessImplementor dataAccessImplementor = new RepositoryDataAccessImplementor(repositoryClassName); String resourceClass = resourceImplementor.implement( classOutput, dataAccessImplementor, resourceInterface, entityType, listenersForEntityType); // Make sure that repository bean is not removed and will be injected to the generated resource unremovableBeansProducer.produce(new UnremovableBeanBuildItem( new UnremovableBeanBuildItem.BeanClassNameExclusion(repositoryClassName))); restDataResourceProducer.produce(new RestDataResourceBuildItem( new ResourceMetadata(resourceClass, resourceInterface, entityType, idType, getEntityFields(index.getIndex(), entityType)))); } } private void validateResource(IndexView index, ClassInfo classInfo) { if (!Modifier.isInterface(classInfo.flags())) { throw new RuntimeException(classInfo.name() + " has to be an interface"); } if (classInfo.interfaceNames().size() > 1) { throw new RuntimeException(classInfo.name() + " should only extend REST Data Panache interface"); } if (!index.getKnownDirectImplementors(classInfo.name()).isEmpty()) { throw new RuntimeException(classInfo.name() + " should not be extended or implemented"); } } private List<Type> getGenericTypes(ClassInfo classInfo) { return classInfo.interfaceTypes() .stream() .findFirst() .orElseThrow(() -> new RuntimeException(classInfo.toString() + " does not have generic types")) .asParameterizedType() .arguments(); } }
HibernateOrmPanacheRestProcessor
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AEncryptionSSES3.java
{ "start": 1005, "end": 1520 }
class ____ extends AbstractTestS3AEncryption { @Override protected Configuration createConfiguration() { Configuration conf = super.createConfiguration(); S3ATestUtils.disableFilesystemCaching(conf); //must specify encryption key as empty because SSE-S3 does not allow it, //nor can it be null. conf.set(Constants.S3_ENCRYPTION_KEY, ""); return conf; } @Override protected S3AEncryptionMethods getSSEAlgorithm() { return S3AEncryptionMethods.SSE_S3; } }
ITestS3AEncryptionSSES3
java
alibaba__nacos
maintainer-client/src/test/java/com/alibaba/nacos/maintainer/client/remote/HttpClientManagerTest.java
{ "start": 952, "end": 1677 }
class ____ { @BeforeEach void setUp() throws IllegalAccessException, NoSuchFieldException { Field instanceField = HttpClientManager.class.getDeclaredField("httpClientManager"); instanceField.setAccessible(true); instanceField.set(null, null); } @AfterEach void tearDown() throws NacosException { HttpClientManager.getInstance().shutdown(); } @Test public void testGetNacosRestTemplate() { HttpClientManager httpClientManager = HttpClientManager.getInstance(); NacosRestTemplate template = httpClientManager.getNacosRestTemplate(); assert template != null : "NacosRestTemplate should not be null."; } }
HttpClientManagerTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/data/BytesRefBlockEqualityTests.java
{ "start": 804, "end": 21213 }
class ____ extends ComputeTestCase { final BigArrays bigArrays = new MockBigArrays(PageCacheRecycler.NON_RECYCLING_INSTANCE, new NoneCircuitBreakerService()); final BlockFactory blockFactory = TestBlockFactory.getNonBreakingInstance(); public void testEmptyVector() { // all these "empty" vectors should be equivalent try (var bytesRefArray1 = new BytesRefArray(0, bigArrays); var bytesRefArray2 = new BytesRefArray(1, bigArrays)) { List<BytesRefVector> vectors = List.of( new BytesRefArrayVector(bytesRefArray1, 0, blockFactory), new BytesRefArrayVector(bytesRefArray2, 0, blockFactory), blockFactory.newConstantBytesRefBlockWith(new BytesRef(), 0).asVector(), blockFactory.newConstantBytesRefBlockWith(new BytesRef(), 0).filter().asVector(), blockFactory.newBytesRefBlockBuilder(0).build().asVector(), blockFactory.newBytesRefBlockBuilder(0).appendBytesRef(new BytesRef()).build().asVector().filter() ); assertAllEquals(vectors); } } public void testEmptyBlock() { // all these "empty" vectors should be equivalent try (var bytesRefArray1 = new BytesRefArray(0, bigArrays); var bytesRefArray2 = new BytesRefArray(1, bigArrays)) { List<BytesRefBlock> blocks = List.of( new BytesRefArrayBlock( bytesRefArray1, 0, new int[] { 0 }, BitSet.valueOf(new byte[] { 0b00 }), randomFrom(Block.MvOrdering.values()), blockFactory ), new BytesRefArrayBlock( bytesRefArray2, 0, new int[] { 0 }, BitSet.valueOf(new byte[] { 0b00 }), randomFrom(Block.MvOrdering.values()), blockFactory ), blockFactory.newConstantBytesRefBlockWith(new BytesRef(), 0), blockFactory.newBytesRefBlockBuilder(0).build(), blockFactory.newBytesRefBlockBuilder(0).appendBytesRef(new BytesRef()).build().filter(), blockFactory.newBytesRefBlockBuilder(0).appendNull().build().filter(), (ConstantNullBlock) blockFactory.newConstantNullBlock(0) ); assertAllEquals(blocks); } } public void testVectorEquality() { // all these vectors should be equivalent try (var bytesRefArray1 = arrayOf("1", "2", "3"); var bytesRefArray2 = arrayOf("1", "2", "3", "4")) { List<BytesRefVector> vectors = List.of( new BytesRefArrayVector(bytesRefArray1, 3, blockFactory), new BytesRefArrayVector(bytesRefArray1, 3, blockFactory).asBlock().asVector(), new BytesRefArrayVector(bytesRefArray2, 3, blockFactory), new BytesRefArrayVector(bytesRefArray1, 3, blockFactory).filter(0, 1, 2), new BytesRefArrayVector(bytesRefArray2, 4, blockFactory).filter(0, 1, 2), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .asVector(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .asVector() .filter(0, 1, 2), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("4")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .filter(0, 2, 3) .asVector(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("4")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .asVector() .filter(0, 2, 3) ); assertAllEquals(vectors); } // all these constant-like vectors should be equivalent try (var bytesRefArray1 = arrayOf("1", "1", "1"); var bytesRefArray2 = arrayOf("1", "1", "1", "4")) { List<BytesRefVector> moreVectors = List.of( new BytesRefArrayVector(bytesRefArray1, 3, blockFactory), new BytesRefArrayVector(bytesRefArray1, 3, blockFactory).asBlock().asVector(), new BytesRefArrayVector(bytesRefArray2, 3, blockFactory), new BytesRefArrayVector(bytesRefArray1, 3, blockFactory).filter(0, 1, 2), new BytesRefArrayVector(bytesRefArray2, 4, blockFactory).filter(0, 1, 2), blockFactory.newConstantBytesRefBlockWith(new BytesRef("1"), 3).asVector(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("1")) .build() .asVector(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("1")) .build() .asVector() .filter(0, 1, 2), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("4")) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("1")) .build() .filter(0, 2, 3) .asVector(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("4")) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("1")) .build() .asVector() .filter(0, 2, 3) ); assertAllEquals(moreVectors); } } public void testBlockEquality() { // all these blocks should be equivalent try (var bytesRefArray1 = arrayOf("1", "2", "3"); var bytesRefArray2 = arrayOf("1", "2", "3", "4")) { List<BytesRefBlock> blocks = List.of( new BytesRefArrayVector(bytesRefArray1, 3, blockFactory).asBlock(), new BytesRefArrayBlock( bytesRefArray1, 3, new int[] { 0, 1, 2, 3 }, BitSet.valueOf(new byte[] { 0b000 }), randomFrom(Block.MvOrdering.values()), blockFactory ), new BytesRefArrayBlock( bytesRefArray2, 3, new int[] { 0, 1, 2, 3 }, BitSet.valueOf(new byte[] { 0b1000 }), randomFrom(Block.MvOrdering.values()), blockFactory ), new BytesRefArrayVector(bytesRefArray1, 3, blockFactory).filter(0, 1, 2).asBlock(), new BytesRefArrayVector(bytesRefArray2, 3, blockFactory).filter(0, 1, 2).asBlock(), new BytesRefArrayVector(bytesRefArray2, 4, blockFactory).filter(0, 1, 2).asBlock(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build(), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .filter(0, 1, 2), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("4")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .filter(0, 2, 3), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendNull() .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .build() .filter(0, 2, 3) ); assertAllEquals(blocks); } // all these constant-like blocks should be equivalent try (var bytesRefArray1 = arrayOf("9", "9"); var bytesRefArray2 = arrayOf("9", "9", "4")) { List<BytesRefBlock> moreBlocks = List.of( new BytesRefArrayVector(bytesRefArray1, 2, blockFactory).asBlock(), new BytesRefArrayBlock( bytesRefArray1, 2, new int[] { 0, 1, 2 }, BitSet.valueOf(new byte[] { 0b000 }), randomFrom(Block.MvOrdering.values()), blockFactory ), new BytesRefArrayBlock( bytesRefArray2, 2, new int[] { 0, 1, 2 }, BitSet.valueOf(new byte[] { 0b100 }), randomFrom(Block.MvOrdering.values()), blockFactory ), new BytesRefArrayVector(bytesRefArray1, 2, blockFactory).filter(0, 1).asBlock(), new BytesRefArrayVector(bytesRefArray2, 2, blockFactory).filter(0, 1).asBlock(), new BytesRefArrayVector(bytesRefArray2, 3, blockFactory).filter(0, 1).asBlock(), blockFactory.newConstantBytesRefBlockWith(new BytesRef("9"), 2), blockFactory.newBytesRefBlockBuilder(2).appendBytesRef(new BytesRef("9")).appendBytesRef(new BytesRef("9")).build(), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("9")) .appendBytesRef(new BytesRef("9")) .build() .filter(0, 1), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("9")) .appendBytesRef(new BytesRef("4")) .appendBytesRef(new BytesRef("9")) .build() .filter(0, 2), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("9")) .appendNull() .appendBytesRef(new BytesRef("9")) .build() .filter(0, 2) ); assertAllEquals(moreBlocks); } } public void testVectorInequality() { // all these vectors should NOT be equivalent try ( var bytesRefArray1 = arrayOf("1"); var bytesRefArray2 = arrayOf("9"); var bytesRefArray3 = arrayOf("1", "2"); var bytesRefArray4 = arrayOf("1", "2", "3"); var bytesRefArray5 = arrayOf("1", "2", "4") ) { List<BytesRefVector> notEqualVectors = List.of( new BytesRefArrayVector(bytesRefArray1, 1, blockFactory), new BytesRefArrayVector(bytesRefArray2, 1, blockFactory), new BytesRefArrayVector(bytesRefArray3, 2, blockFactory), new BytesRefArrayVector(bytesRefArray4, 3, blockFactory), new BytesRefArrayVector(bytesRefArray5, 3, blockFactory), blockFactory.newConstantBytesRefBlockWith(new BytesRef("9"), 2).asVector(), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .build() .asVector() .filter(1), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("5")) .build() .asVector(), blockFactory.newBytesRefBlockBuilder(1) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .appendBytesRef(new BytesRef("4")) .build() .asVector() ); assertAllNotEquals(notEqualVectors); } } public void testBlockInequality() { // all these blocks should NOT be equivalent try ( var bytesRefArray1 = arrayOf("1"); var bytesRefArray2 = arrayOf("9"); var bytesRefArray3 = arrayOf("1", "2"); var bytesRefArray4 = arrayOf("1", "2", "3"); var bytesRefArray5 = arrayOf("1", "2", "4") ) { List<BytesRefBlock> notEqualBlocks = List.of( new BytesRefArrayVector(bytesRefArray1, 1, blockFactory).asBlock(), new BytesRefArrayVector(bytesRefArray2, 1, blockFactory).asBlock(), new BytesRefArrayVector(bytesRefArray3, 2, blockFactory).asBlock(), new BytesRefArrayVector(bytesRefArray4, 3, blockFactory).asBlock(), new BytesRefArrayVector(bytesRefArray5, 3, blockFactory).asBlock(), blockFactory.newConstantBytesRefBlockWith(new BytesRef("9"), 2), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .build() .filter(1), blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("5")) .build(), blockFactory.newBytesRefBlockBuilder(1) .appendBytesRef(new BytesRef("1")) .appendBytesRef(new BytesRef("2")) .appendBytesRef(new BytesRef("3")) .appendBytesRef(new BytesRef("4")) .build(), blockFactory.newBytesRefBlockBuilder(1).appendBytesRef(new BytesRef("1")).appendNull().build(), blockFactory.newBytesRefBlockBuilder(1) .appendBytesRef(new BytesRef("1")) .appendNull() .appendBytesRef(new BytesRef("3")) .build(), blockFactory.newBytesRefBlockBuilder(1).appendBytesRef(new BytesRef("1")).appendBytesRef(new BytesRef("3")).build() ); assertAllNotEquals(notEqualBlocks); } } public void testSimpleBlockWithSingleNull() { List<BytesRefBlock> blocks = List.of( blockFactory.newBytesRefBlockBuilder(3) .appendBytesRef(new BytesRef("1")) .appendNull() .appendBytesRef(new BytesRef("3")) .build(), blockFactory.newBytesRefBlockBuilder(3).appendBytesRef(new BytesRef("1")).appendNull().appendBytesRef(new BytesRef("3")).build() ); assertEquals(3, blocks.get(0).getPositionCount()); assertTrue(blocks.get(0).isNull(1)); assertAllEquals(blocks); } public void testSimpleBlockWithManyNulls() { int positions = randomIntBetween(1, 256); boolean grow = randomBoolean(); BytesRefBlock.Builder builder1 = blockFactory.newBytesRefBlockBuilder(grow ? 0 : positions); BytesRefBlock.Builder builder2 = blockFactory.newBytesRefBlockBuilder(grow ? 0 : positions); ConstantNullBlock.Builder builder3 = new ConstantNullBlock.Builder(blockFactory); for (int p = 0; p < positions; p++) { builder1.appendNull(); builder2.appendNull(); builder3.appendNull(); } BytesRefBlock block1 = builder1.build(); BytesRefBlock block2 = builder2.build(); Block block3 = builder3.build(); assertEquals(positions, block1.getPositionCount()); assertTrue(block1.mayHaveNulls()); assertTrue(block1.isNull(0)); List<Block> blocks = List.of(block1, block2, block3); assertAllEquals(blocks); } public void testSimpleBlockWithSingleMultiValue() { List<BytesRefBlock> blocks = List.of( blockFactory.newBytesRefBlockBuilder(1) .beginPositionEntry() .appendBytesRef(new BytesRef("1a")) .appendBytesRef(new BytesRef("2b")) .build(), blockFactory.newBytesRefBlockBuilder(1) .beginPositionEntry() .appendBytesRef(new BytesRef("1a")) .appendBytesRef(new BytesRef("2b")) .build() ); assertEquals(1, blocks.get(0).getPositionCount()); assertEquals(2, blocks.get(0).getValueCount(0)); assertAllEquals(blocks); } public void testSimpleBlockWithManyMultiValues() { int positions = randomIntBetween(1, 256); boolean grow = randomBoolean(); BytesRefBlock.Builder builder1 = blockFactory.newBytesRefBlockBuilder(grow ? 0 : positions); BytesRefBlock.Builder builder2 = blockFactory.newBytesRefBlockBuilder(grow ? 0 : positions); BytesRefBlock.Builder builder3 = blockFactory.newBytesRefBlockBuilder(grow ? 0 : positions); for (int pos = 0; pos < positions; pos++) { builder1.beginPositionEntry(); builder2.beginPositionEntry(); builder3.beginPositionEntry(); int values = randomIntBetween(1, 16); for (int i = 0; i < values; i++) { BytesRef value = new BytesRef(Integer.toHexString(randomInt())); builder1.appendBytesRef(value); builder2.appendBytesRef(value); builder3.appendBytesRef(value); } builder1.endPositionEntry(); builder2.endPositionEntry(); builder3.endPositionEntry(); } BytesRefBlock block1 = builder1.build(); BytesRefBlock block2 = builder2.build(); BytesRefBlock block3 = builder3.build(); assertEquals(positions, block1.getPositionCount()); assertAllEquals(List.of(block1, block2, block3)); } BytesRefArray arrayOf(String... values) { var array = new BytesRefArray(values.length, bigArrays); Arrays.stream(values).map(BytesRef::new).forEach(array::append); return array; } static void assertAllEquals(List<?> objs) { for (Object obj1 : objs) { for (Object obj2 : objs) { assertEquals(obj1, obj2); assertEquals(obj2, obj1); // equal objects must generate the same hash code assertEquals(obj1.hashCode(), obj2.hashCode()); } } } static void assertAllNotEquals(List<?> objs) { for (Object obj1 : objs) { for (Object obj2 : objs) { if (obj1 == obj2) { continue; // skip self } assertNotEquals(obj1, obj2); assertNotEquals(obj2, obj1); // unequal objects SHOULD generate the different hash code assertNotEquals(obj1.hashCode(), obj2.hashCode()); } } } }
BytesRefBlockEqualityTests
java
quarkusio__quarkus
extensions/scheduler/deployment/src/test/java/SimpleScheduledMethodDefaultPackageTest.java
{ "start": 336, "end": 983 }
class ____ { @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(SimpleJobsDefaultPackage.class) .addAsResource(new StringAsset("simpleJobs.cron=0/1 * * * * ?\nsimpleJobs.every=1s"), "application.properties")); @Test public void testSimpleScheduledJobs() throws InterruptedException { for (CountDownLatch latch : SimpleJobsDefaultPackage.LATCHES.values()) { assertTrue(latch.await(5, TimeUnit.SECONDS)); } } }
SimpleScheduledMethodDefaultPackageTest
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/conversion/URLToStringConversion.java
{ "start": 661, "end": 1488 }
class ____ extends SimpleConversion { @Override protected String getToExpression(ConversionContext conversionContext) { return "<SOURCE>.toString()"; } @Override protected String getFromExpression(ConversionContext conversionContext) { return "new " + url( conversionContext ) + "( <SOURCE> )"; } @Override protected Set<Type> getFromConversionImportTypes(final ConversionContext conversionContext) { return asSet( conversionContext.getTypeFactory().getType( URL.class ) ); } @Override protected List<Type> getFromConversionExceptionTypes(ConversionContext conversionContext) { return java.util.Collections.singletonList( conversionContext.getTypeFactory().getType( MalformedURLException.class ) ); } }
URLToStringConversion
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java
{ "start": 1308, "end": 4713 }
class ____ extends AbstractMessage {} @Test public void can_create_mock_with_constructor() { Message mock = mock( Message.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); // the message is a part of state of the mocked type that gets initialized in constructor assertEquals("hey!", mock.getMessage()); } @Test public void can_mock_abstract_classes() { AbstractMessage mock = mock( AbstractMessage.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); assertEquals("hey!", mock.getMessage()); } @Test public void can_spy_abstract_classes() { AbstractMessage mock = spy(AbstractMessage.class); assertEquals("hey!", mock.getMessage()); } @Test public void can_spy_abstract_classes_with_constructor_args() { AbstractMessage mock = mock( AbstractMessage.class, withSettings().useConstructor("hello!").defaultAnswer(CALLS_REAL_METHODS)); assertEquals("hello!", mock.getMessage()); } @Test public void can_spy_abstract_classes_with_constructor_primitive_args() { AbstractMessage mock = mock( AbstractMessage.class, withSettings().useConstructor(7).defaultAnswer(CALLS_REAL_METHODS)); assertEquals("7", mock.getMessage()); } @Test public void can_spy_abstract_classes_with_constructor_array_of_nulls() { AbstractMessage mock = mock( AbstractMessage.class, withSettings() .useConstructor(new Object[] {null}) .defaultAnswer(CALLS_REAL_METHODS)); assertNull(mock.getMessage()); } @Test public void can_spy_abstract_classes_with_casted_null() { AbstractMessage mock = mock( AbstractMessage.class, withSettings() .useConstructor((String) null) .defaultAnswer(CALLS_REAL_METHODS)); assertNull(mock.getMessage()); } @Test public void can_spy_abstract_classes_with_null_varargs() { try { mock( AbstractMessage.class, withSettings().useConstructor(null).defaultAnswer(CALLS_REAL_METHODS)); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessageContaining( "constructorArgs should not be null. " + "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)"); } } @Test public void can_mock_inner_classes() { InnerClass mock = mock( InnerClass.class, withSettings() .useConstructor() .outerInstance(this) .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("hey!", mock.getMessage()); } public static
InnerClass
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oscar/visitor/OscarPermissionOutputVisitor.java
{ "start": 1083, "end": 3054 }
class ____ extends OscarOutputVisitor { public OscarPermissionOutputVisitor(StringBuilder appender) { super(appender); this.dbType = DbType.oscar; } public OscarPermissionOutputVisitor(StringBuilder appender, boolean parameterized) { super(appender, parameterized); this.dbType = DbType.oscar; } @Override public boolean visit(SQLExprTableSource x) { String catalog = x.getCatalog(); String schema = x.getSchema(); String tableName = x.getTableName(); List<SQLName> columns1 = x.getColumns(); int sourceColumn = x.getSourceColumn(); //SQLExpr sqlExpr = SQLUtils.toSQLExpr("id=3", dbType); print(" ("); print0(ucase ? "SELECT " : "select "); print('*'); print0(ucase ? " FROM " : " from "); printTableSourceExpr(x.getExpr()); //print0(ucase ? " WHERE " : " where "); //printExpr(sqlExpr); print(')'); final SQLTableSampling sampling = x.getSampling(); if (sampling != null) { print(' '); sampling.accept(this); } String alias = x.getAlias(); List<SQLName> columns = x.getColumnsDirect(); if (alias != null) { print(' '); if (columns != null && columns.size() > 0) { print0(ucase ? " AS " : " as "); } print0(alias); } if (columns != null && columns.size() > 0) { print(" ("); printAndAccept(columns, ", "); print(')'); } for (int i = 0; i < x.getHintsSize(); ++i) { print(' '); x.getHints().get(i).accept(this); } if (x.getPartitionSize() > 0) { print0(ucase ? " PARTITION (" : " partition ("); printlnAndAccept(x.getPartitions(), ", "); print(')'); } return false; } }
OscarPermissionOutputVisitor
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/jdbc/MergedSqlConfigTests.java
{ "start": 16411, "end": 16501 }
class ____ { } @SqlConfig public static
GlobalConfigWithWithDuplicatedCommentPrefixesClass
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/producer/ProducerWithClassLevelInterceptorsAndBindingsSourceTest.java
{ "start": 2430, "end": 2579 }
class ____ { @NoClassInterceptors String hello2() { return null; } } @Dependent static
MyNonbeanBindings