language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/PartitionConnectionException.java
{ "start": 1125, "end": 1497 }
class ____ extends PartitionException { private static final long serialVersionUID = 0L; public PartitionConnectionException(ResultPartitionID partitionId, Throwable throwable) { super( "Connection for partition " + partitionId + " not reachable.", partitionId, throwable); } }
PartitionConnectionException
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java
{ "start": 74786, "end": 75409 }
class ____ { @Value("${mockwebserver.url:https://example.org}") String jwkSetUri; @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((authorize) -> authorize .requestMatchers("/requires-read-scope").hasAuthority("SCOPE_message:read") .anyRequest().authenticated() ) .oauth2ResourceServer((oauth2) -> oauth2 .jwt((jwt) -> jwt .jwkSetUri(this.jwkSetUri) ) ); return http.build(); // @formatter:on } } @Configuration @EnableWebSecurity @EnableWebMvc static
JwkSetUriInLambdaConfig
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java
{ "start": 4893, "end": 5064 }
class ____ { private String name = "654321"; public String getName() { return this.name; } public void setName(String name) { this.name = name; } } }
Bar
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/CamelTop.java
{ "start": 1235, "end": 1752 }
class ____ extends CamelCommand { @CommandLine.Option(names = { "--watch" }, description = "Execute periodically and showing output fullscreen") boolean watch; public CamelTop(CamelJBangMain main) { super(main); } @Override public Integer doCall() throws Exception { // default to top the integrations CamelContextTop cmd = new CamelContextTop(getMain()); cmd.watch = watch; return new CommandLine(cmd).execute(); } }
CamelTop
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractObjectArrayAssert.java
{ "start": 172761, "end": 176666 }
class ____ { * String name; * boolean hasPhd; * } * * Doctor drSheldon = new Doctor("Sheldon Cooper", true); * Doctor drLeonard = new Doctor("Leonard Hofstadter", true); * Doctor drRaj = new Doctor("Raj Koothrappali", true); * * Person sheldon = new Person("Sheldon Cooper", true); * Person leonard = new Person("Leonard Hofstadter", true); * Person raj = new Person("Raj Koothrappali", true); * Person howard = new Person("Howard Wolowitz", false); * * Doctor[] doctors = { drSheldon, drLeonard, drRaj }; * Person[] people = { sheldon, leonard, raj }; * * // assertion succeeds as both lists contains equivalent items in order. * assertThat(doctors).usingRecursiveComparison() * .isEqualTo(people); * * // assertion fails because leonard names are different. * leonard.setName("Leonard Ofstater"); * assertThat(doctors).usingRecursiveComparison() * .isEqualTo(people); * * // assertion fails because howard is missing and leonard is not expected. * Person[] otherPeople = { howard, sheldon, raj }; * assertThat(doctors).usingRecursiveComparison() * .isEqualTo(otherPeople);</code></pre> * <p> * A detailed documentation for the recursive comparison is available here: <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison">https://assertj.github.io/doc/#assertj-core-recursive-comparison</a>. * <p> * The default recursive comparison behavior is {@link RecursiveComparisonConfiguration configured} as follows: * <ul> * <li> different types of iterable can be compared by default, this allows to compare for example an {@code Person[]} and a {@code PersonDto[]}.<br> * This behavior can be turned off by calling {@link RecursiveComparisonAssert#withStrictTypeChecking() withStrictTypeChecking}.</li> * <li>overridden equals methods are used in the comparison (unless stated otherwise - see <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals">https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals</a>)</li> * <li>the following types are compared with these comparators: * <ul> * <li>{@code java.lang.Double}: {@code DoubleComparator} with precision of 1.0E-15</li> * <li>{@code java.lang.Float}: {@code FloatComparator }with precision of 1.0E-6</li> * <li>any comparators previously registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} </li> * </ul> * </li> * </ul> * * @return a new {@link RecursiveComparisonAssert} instance * @see RecursiveComparisonConfiguration RecursiveComparisonConfiguration */ @Override @Beta public RecursiveComparisonAssert<?> usingRecursiveComparison() { // overridden for javadoc and to make this method public return super.usingRecursiveComparison(); } /** * Same as {@link #usingRecursiveComparison()} but allows to specify your own {@link RecursiveComparisonConfiguration}. * * @param recursiveComparisonConfiguration the {@link RecursiveComparisonConfiguration} used in the chained {@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo} assertion. * @return a new {@link RecursiveComparisonAssert} instance built with the given {@link RecursiveComparisonConfiguration}. */ @Override @Beta public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) { return super.usingRecursiveComparison(recursiveComparisonConfiguration).withTypeComparators(comparatorsByType); } /** * <p>Asserts that the given predicate is met for all fields of the object under test <b>recursively</b> (but not the object itself).</p> * * <p>For example if the object under test is an instance of
Doctor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/AbstractMutationStrategyGeneratedIdTest.java
{ "start": 1009, "end": 4051 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { Doctor doctor = new Doctor(); doctor.setName( "Doctor John" ); doctor.setEmployed( true ); session.persist( doctor ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test public void testInsertStatic(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "insert into Engineer(id, name, employed, fellow) values (0, :name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.find( Engineer.class, 0 ); assertThat( engineer.getName() ).isEqualTo( "John Doe" ); assertThat( engineer.isEmployed() ).isTrue(); assertThat( engineer.isFellow() ).isFalse(); } ); } @Test public void testInsertGenerated(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "insert into Engineer(name, employed, fellow) values (:name, :employed, false)" ) .setParameter( "name", "John Doe" ) .setParameter( "employed", true ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); assertThat( engineer.getName() ).isEqualTo( "John Doe" ); assertThat( engineer.isEmployed() ).isTrue(); assertThat( engineer.isFellow() ).isFalse(); } ); } @Test public void testInsertSelectStatic(SessionFactoryScope scope) { scope.inTransaction( session -> { final int insertCount = session.createMutationQuery( "insert into Engineer(id, name, employed, fellow) " + "select d.id + 1, 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); assertThat( insertCount ).isEqualTo( 1 ); assertThat( engineer.getName() ).isEqualTo( "John Doe" ); assertThat( engineer.isEmployed() ).isTrue(); assertThat( engineer.isFellow() ).isFalse(); } ); } @Test public void testInsertSelectGenerated(SessionFactoryScope scope) { scope.inTransaction( session -> { final int insertCount = session.createMutationQuery( "insert into Engineer(name, employed, fellow) " + "select 'John Doe', true, false from Doctor d" ) .executeUpdate(); final Engineer engineer = session.createQuery( "from Engineer e where e.name = 'John Doe'", Engineer.class ) .getSingleResult(); assertThat( insertCount ).isEqualTo( 1 ); assertThat( engineer.getName() ).isEqualTo( "John Doe" ); assertThat( engineer.isEmployed() ).isTrue(); assertThat( engineer.isFellow() ).isFalse(); } ); } @Entity(name = "Person") @Inheritance(strategy = InheritanceType.JOINED) public static
AbstractMutationStrategyGeneratedIdTest
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/task/engine/NacosTaskExecuteEngine.java
{ "start": 922, "end": 2884 }
interface ____<T extends NacosTask> extends Closeable { /** * Get Task size in execute engine. * * @return size of task */ int size(); /** * Whether the execute engine is empty. * * @return true if the execute engine has no task to do, otherwise false */ boolean isEmpty(); /** * Add task processor {@link NacosTaskProcessor} for execute engine. * * @param key key of task * @param taskProcessor task processor */ void addProcessor(Object key, NacosTaskProcessor taskProcessor); /** * Remove task processor {@link NacosTaskProcessor} form execute engine for key. * * @param key key of task */ void removeProcessor(Object key); /** * Try to get {@link NacosTaskProcessor} by key, if non-exist, will return default processor. * * @param key key of task * @return task processor for task key or default processor if task processor for task key non-exist */ NacosTaskProcessor getProcessor(Object key); /** * Get all processor key. * * @return collection of processors */ Collection<Object> getAllProcessorKey(); /** * Set default task processor. If do not find task processor by task key, use this default processor to process * task. * * @param defaultTaskProcessor default task processor */ void setDefaultTaskProcessor(NacosTaskProcessor defaultTaskProcessor); /** * Add task into execute pool. * * @param key key of task * @param task task */ void addTask(Object key, T task); /** * Remove task. * * @param key key of task * @return nacos task */ T removeTask(Object key); /** * Get all task keys. * * @return collection of task keys. */ Collection<Object> getAllTaskKeys(); }
NacosTaskExecuteEngine
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/saml/SamlInvalidateSessionRequest.java
{ "start": 779, "end": 2677 }
class ____ extends LegacyActionRequest { @Nullable private String realmName; @Nullable private String assertionConsumerServiceURL; private String queryString; public SamlInvalidateSessionRequest(StreamInput in) throws IOException { super(in); } public SamlInvalidateSessionRequest() {} @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (Strings.isNullOrEmpty(queryString)) { validationException = addValidationError("query_string is missing", validationException); } return validationException; } public String getQueryString() { return queryString; } public void setQueryString(String queryString) { if (this.queryString == null) { this.queryString = queryString; } else { throw new IllegalArgumentException("Must use either [query_string] or [queryString], not both at the same time"); } } public String getRealmName() { return realmName; } public void setRealmName(String realmName) { this.realmName = realmName; } public String getAssertionConsumerServiceURL() { return assertionConsumerServiceURL; } public void setAssertionConsumerServiceURL(String assertionConsumerServiceURL) { this.assertionConsumerServiceURL = assertionConsumerServiceURL; } @Override public String toString() { return getClass().getSimpleName() + "{" + "realmName='" + realmName + '\'' + ", assertionConsumerServiceURL='" + assertionConsumerServiceURL + '\'' + ", url-query=" + queryString.length() + " chars" + '}'; } }
SamlInvalidateSessionRequest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java
{ "start": 1041, "end": 4226 }
class ____ { // original stdout stream private final PrintStream out; // original stderr stream private final PrintStream err; // arguments from the CLI process private final ServerArgs args; // controller for spawning component subprocesses private final Spawner spawner = new Spawner(); // the loaded keystore, not valid until after phase 2 of initialization private final SetOnce<SecureSettings> secureSettings = new SetOnce<>(); // the loaded settings for the node, not valid until after phase 2 of initialization private final SetOnce<Environment> nodeEnv = new SetOnce<>(); // loads information about plugins required for entitlements in phase 2, used by plugins service in phase 3 private final SetOnce<PluginsLoader> pluginsLoader = new SetOnce<>(); Bootstrap(PrintStream out, PrintStream err, ServerArgs args) { this.out = out; this.err = err; this.args = args; } ServerArgs args() { return args; } Spawner spawner() { return spawner; } void setSecureSettings(SecureSettings secureSettings) { this.secureSettings.set(secureSettings); } SecureSettings secureSettings() { return secureSettings.get(); } void setEnvironment(Environment environment) { this.nodeEnv.set(environment); } Environment environment() { return nodeEnv.get(); } void setPluginsLoader(PluginsLoader pluginsLoader) { this.pluginsLoader.set(pluginsLoader); } PluginsLoader pluginsLoader() { return pluginsLoader.get(); } void exitWithNodeValidationException(NodeValidationException e) { Logger logger = LogManager.getLogger(Elasticsearch.class); logger.error("node validation exception\n{}", e.getMessage()); gracefullyExit(ExitCodes.CONFIG); } void exitWithUnknownException(Throwable e) { Logger logger = LogManager.getLogger(Elasticsearch.class); logger.error("fatal exception while booting Elasticsearch", e); gracefullyExit(1); // mimic JDK exit code on exception } private void gracefullyExit(int exitCode) { printLogsSuggestion(); err.flush(); exit(exitCode); } @SuppressForbidden(reason = "main exit path") static void exit(int exitCode) { System.exit(exitCode); } /** * Prints a message directing the user to look at the logs. A message is only printed if * logging has been configured. */ private void printLogsSuggestion() { final String basePath = System.getProperty("es.logs.base_path"); assert basePath != null : "logging wasn't initialized"; err.println( "ERROR: Elasticsearch did not exit normally - check the logs at " + basePath + System.getProperty("file.separator") + System.getProperty("es.logs.cluster_name") + ".log" ); } void sendCliMarker(char marker) { err.println(marker); err.flush(); } void closeStreams() { out.close(); err.close(); } }
Bootstrap
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/IndexBalanceAllocationDeciderTests.java
{ "start": 2846, "end": 17217 }
class ____ extends ESAllocationTestCase { private DiscoveryNode indexNodeOne; private DiscoveryNode indexNodeTwo; private DiscoveryNode searchNodeOne; private DiscoveryNode searchNodeTwo; private DiscoveryNode masterNode; private DiscoveryNode machineLearningNode; private RoutingNode routingIndexNodeOne; private RoutingNode routingIndexNodeTwo; private RoutingNode routingSearchNodeOne; private RoutingNode routingSearchNodeTwo; private RoutingNode routingMachineLearningNode; private List<DiscoveryNode> allNodes; private int numberOfPrimaryShards; private int replicationFactor; private ClusterState clusterState; private IndexMetadata indexMetadata; private RoutingAllocation routingAllocation; private IndexBalanceAllocationDecider indexBalanceAllocationDecider; private ShardRouting indexTierShardRouting; private ShardRouting searchTierShardRouting; private List<RoutingNode> indexTier; private List<RoutingNode> searchIier; private void setup(Settings settings) { final String indexName = "IndexBalanceAllocationDeciderIndex"; final Map<DiscoveryNode, List<ShardRouting>> nodeToShardRoutings = new HashMap<>(); Settings.Builder builder = Settings.builder() .put(settings) .put("stateless.enabled", "true") .put(IndexBalanceConstraintSettings.INDEX_BALANCE_DECIDER_ENABLED_SETTING.getKey(), "true"); numberOfPrimaryShards = randomIntBetween(2, 10) * 2; replicationFactor = 2; indexNodeOne = DiscoveryNodeUtils.builder("indexNodeOne").roles(Collections.singleton(DiscoveryNodeRole.INDEX_ROLE)).build(); indexNodeTwo = DiscoveryNodeUtils.builder("indexNodeTwo").roles(Collections.singleton(DiscoveryNodeRole.INDEX_ROLE)).build(); searchNodeOne = DiscoveryNodeUtils.builder("searchNodeOne").roles(Collections.singleton(DiscoveryNodeRole.SEARCH_ROLE)).build(); searchNodeTwo = DiscoveryNodeUtils.builder("searchNodeTwo").roles(Collections.singleton(DiscoveryNodeRole.SEARCH_ROLE)).build(); masterNode = DiscoveryNodeUtils.builder("masterNode").roles(Collections.singleton(DiscoveryNodeRole.MASTER_ROLE)).build(); machineLearningNode = DiscoveryNodeUtils.builder("machineLearningNode") .roles(Collections.singleton(DiscoveryNodeRole.ML_ROLE)) .build(); allNodes = List.of(indexNodeOne, indexNodeTwo, searchNodeOne, searchNodeTwo, masterNode, machineLearningNode); DiscoveryNodes.Builder discoveryNodeBuilder = DiscoveryNodes.builder(); for (DiscoveryNode node : allNodes) { discoveryNodeBuilder.add(node); } ProjectId projectId = ProjectId.fromId("test-IndexBalanceAllocationDecider"); ClusterState.Builder state = ClusterState.builder(new ClusterName("test-IndexBalanceAllocationDecider")); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(projectId); indexMetadata = IndexMetadata.builder(indexName) .settings( indexSettings(IndexVersion.current(), numberOfPrimaryShards, replicationFactor).put( SETTING_CREATION_DATE, System.currentTimeMillis() ).build() ) .timestampRange(IndexLongFieldRange.UNKNOWN) .eventIngestedRange(IndexLongFieldRange.UNKNOWN) .build(); projectBuilder.put(indexMetadata, false); IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(indexMetadata.getIndex()); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); Metadata.Builder metadataBuilder = Metadata.builder(); ShardId[] shardIds = new ShardId[numberOfPrimaryShards]; for (int i = 0; i < numberOfPrimaryShards; i++) { shardIds[i] = new ShardId(indexMetadata.getIndex(), i); IndexShardRoutingTable.Builder indexShardRoutingBuilder = IndexShardRoutingTable.builder(shardIds[i]); DiscoveryNode indexNode = i % 2 == 0 ? indexNodeOne : indexNodeTwo; ShardRouting primaryShardRouting = TestShardRouting.newShardRouting( shardIds[i], indexNode.getId(), null, true, ShardRoutingState.STARTED ); indexShardRoutingBuilder.addShard(primaryShardRouting); nodeToShardRoutings.putIfAbsent(indexNode, new ArrayList<>()); nodeToShardRoutings.get(indexNode).add(primaryShardRouting); for (int j = 1; j <= replicationFactor; j++) { DiscoveryNode searchNode = j % 2 == 0 ? searchNodeOne : searchNodeTwo; ShardRouting replicaShardRouting = shardRoutingBuilder(shardIds[i], searchNode.getId(), false, ShardRoutingState.STARTED) .withRole(ShardRouting.Role.DEFAULT) .build(); indexShardRoutingBuilder.addShard(replicaShardRouting); nodeToShardRoutings.putIfAbsent(searchNode, new ArrayList<>()); nodeToShardRoutings.get(searchNode).add(replicaShardRouting); } indexRoutingTableBuilder.addIndexShard(indexShardRoutingBuilder); routingTableBuilder.add(indexRoutingTableBuilder.build()); } routingMachineLearningNode = RoutingNodesHelper.routingNode(machineLearningNode.getId(), machineLearningNode); metadataBuilder.put(projectBuilder).generateClusterUuidIfNeeded(); state.nodes(discoveryNodeBuilder); state.metadata(metadataBuilder); state.routingTable(GlobalRoutingTable.builder().put(projectId, routingTableBuilder).build()); clusterState = state.build(); routingIndexNodeOne = RoutingNodesHelper.routingNode( indexNodeOne.getId(), indexNodeOne, nodeToShardRoutings.get(indexNodeOne).toArray(new ShardRouting[0]) ); routingIndexNodeTwo = RoutingNodesHelper.routingNode( indexNodeTwo.getId(), indexNodeTwo, nodeToShardRoutings.get(indexNodeTwo).toArray(new ShardRouting[0]) ); routingSearchNodeOne = RoutingNodesHelper.routingNode( searchNodeOne.getId(), searchNodeOne, nodeToShardRoutings.get(searchNodeOne).toArray(new ShardRouting[0]) ); routingSearchNodeTwo = RoutingNodesHelper.routingNode( searchNodeTwo.getId(), searchNodeTwo, nodeToShardRoutings.get(searchNodeTwo).toArray(new ShardRouting[0]) ); ClusterInfo clusterInfo = ClusterInfo.builder().build(); routingAllocation = new RoutingAllocation(null, clusterState.getRoutingNodes(), clusterState, clusterInfo, null, System.nanoTime()); routingAllocation.setDebugMode(RoutingAllocation.DebugMode.ON); indexBalanceAllocationDecider = new IndexBalanceAllocationDecider(builder.build(), createBuiltInClusterSettings(builder.build())); indexTierShardRouting = TestShardRouting.newShardRouting( new ShardId(indexMetadata.getIndex(), 1), randomFrom(indexNodeOne, indexNodeTwo).getId(), null, true, ShardRoutingState.STARTED ); searchTierShardRouting = TestShardRouting.newShardRouting( new ShardId(indexMetadata.getIndex(), 1), randomFrom(searchNodeOne, searchNodeTwo).getId(), null, false, ShardRoutingState.STARTED ); indexTier = List.of(routingIndexNodeOne, routingIndexNodeTwo); searchIier = List.of(routingSearchNodeOne, routingSearchNodeTwo); } public void testCanAllocateUnderThresholdWithExcessShards() { Settings settings = allowExcessShards(Settings.EMPTY); setup(settings); ShardRouting newIndexShardRouting = TestShardRouting.newShardRouting( new ShardId("newIndex", "uuid", 1), indexNodeTwo.getId(), null, true, ShardRoutingState.STARTED ); for (RoutingNode routingNode : List.of( routingIndexNodeOne, routingIndexNodeTwo, routingSearchNodeOne, routingSearchNodeTwo, routingMachineLearningNode )) { assertDecisionMatches( "Assigning a new index to a node should succeed", indexBalanceAllocationDecider.canAllocate(newIndexShardRouting, routingNode, routingAllocation), Decision.Type.YES, "Node does not currently host this index." ); } for (RoutingNode routingNode : searchIier) { assertDecisionMatches( "Assigning a new primary shard to a search tier node should succeed", indexBalanceAllocationDecider.canAllocate(indexTierShardRouting, routingNode, routingAllocation), Decision.Type.YES, "A search node cannot own primary shards. Decider inactive." ); } for (RoutingNode routingNode : indexTier) { assertDecisionMatches( "Assigning a replica shard to a index tier node should succeed", indexBalanceAllocationDecider.canAllocate(searchTierShardRouting, routingNode, routingAllocation), Decision.Type.YES, "An index node cannot own search shards. Decider inactive." ); } verifyCanAllocate(); } private void verifyCanAllocate() { for (RoutingNode routingNode : indexTier) { assertDecisionMatches( "Assigning an additional primary shard to an index node has capacity should succeed", indexBalanceAllocationDecider.canAllocate(indexTierShardRouting, routingNode, routingAllocation), Decision.Type.YES, "Node index shard allocation is under the threshold." ); } for (RoutingNode routingNode : searchIier) { assertDecisionMatches( "Assigning an additional replica shard to an search node has capacity should succeed", indexBalanceAllocationDecider.canAllocate(searchTierShardRouting, routingNode, routingAllocation), Decision.Type.YES, "Node index shard allocation is under the threshold." ); } } public void testCanAllocateExceedThreshold() { setup(Settings.EMPTY); int ideal = numberOfPrimaryShards / 2; int current = numberOfPrimaryShards / 2; assertDecisionMatches( "Assigning an additional primary shard to an index node at capacity should fail", indexBalanceAllocationDecider.canAllocate(indexTierShardRouting, routingIndexNodeOne, routingAllocation), Decision.Type.NOT_PREFERRED, "There are [2] eligible nodes in the [index] tier for assignment of [" + numberOfPrimaryShards + "] shards in index [[IndexBalanceAllocationDeciderIndex]]. Ideally no more than [" + ideal + "] shard would be assigned per node (the index balance excess shards setting is [0]). This node is already assigned [" + current + "] shards of the index." ); int total = numberOfPrimaryShards * replicationFactor; ideal = numberOfPrimaryShards * replicationFactor / 2; current = numberOfPrimaryShards * replicationFactor / 2; assertDecisionMatches( "Assigning an additional replica shard to an replica node at capacity should fail", indexBalanceAllocationDecider.canAllocate(searchTierShardRouting, routingSearchNodeOne, routingAllocation), Decision.Type.NOT_PREFERRED, "There are [2] eligible nodes in the [search] tier for assignment of [" + total + "] shards in index [[IndexBalanceAllocationDeciderIndex]]. Ideally no more than [" + ideal + "] shard would be assigned per node (the index balance excess shards setting is [0]). This node is already assigned [" + current + "] shards of the index." ); } public void testCanAllocateHasDiscoveryNodeFilters() { Settings settings = addRandomFilterSetting(Settings.EMPTY); if (randomBoolean()) { settings = allowExcessShards(settings); } setup(settings); for (RoutingNode routingNode : indexTier) { assertDecisionMatches( "Having DiscoveryNodeFilters disables this decider", indexBalanceAllocationDecider.canAllocate(indexTierShardRouting, routingNode, routingAllocation), Decision.Type.YES, "Decider is disabled." ); } for (RoutingNode routingNode : searchIier) { assertDecisionMatches( "Having DiscoveryNodeFilters disables this decider", indexBalanceAllocationDecider.canAllocate(searchTierShardRouting, routingNode, routingAllocation), Decision.Type.YES, "Decider is disabled." ); } } public Settings addRandomFilterSetting(Settings settings) { String setting = randomFrom( CLUSTER_ROUTING_REQUIRE_GROUP_PREFIX, CLUSTER_ROUTING_INCLUDE_GROUP_PREFIX, CLUSTER_ROUTING_EXCLUDE_GROUP_PREFIX ); String attribute = randomFrom("_value", "name"); String name = randomFrom("indexNodeOne", "indexNodeTwo", "searchNodeOne", "searchNodeTwo"); String ip = randomFrom("192.168.0.1", "192.168.0.2", "192.168.7.1", "10.17.0.1"); return Settings.builder().put(settings).put(setting + "." + attribute, attribute.equals("name") ? name : ip).build(); } public Settings allowExcessShards(Settings settings) { int excessShards = randomIntBetween(1, 5); return Settings.builder() .put(settings) .put(IndexBalanceConstraintSettings.INDEX_BALANCE_DECIDER_EXCESS_SHARDS.getKey(), excessShards) .build(); } }
IndexBalanceAllocationDeciderTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/NamenodeHeartbeatResponse.java
{ "start": 1211, "end": 1752 }
class ____ { public static NamenodeHeartbeatResponse newInstance() throws IOException { return StateStoreSerializer.newRecord(NamenodeHeartbeatResponse.class); } public static NamenodeHeartbeatResponse newInstance(boolean status) throws IOException { NamenodeHeartbeatResponse response = newInstance(); response.setResult(status); return response; } @Private @Unstable public abstract boolean getResult(); @Private @Unstable public abstract void setResult(boolean result); }
NamenodeHeartbeatResponse
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java
{ "start": 15935, "end": 17665 }
class ____ extends MockNodeStatusUpdater { public TestNodeStatusUpdaterResync(Context context, Dispatcher dispatcher, NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics) { super(context, dispatcher, healthChecker, metrics); } @Override protected void rebootNodeStatusUpdaterAndRegisterWithRM() { try { // Wait here so as to sync with the main test thread. super.rebootNodeStatusUpdaterAndRegisterWithRM(); syncBarrier.await(); } catch (InterruptedException e) { } catch (BrokenBarrierException e) { } catch (AssertionError ae) { ae.printStackTrace(); assertionFailedInThread.set(true); } } } private YarnConfiguration createNMConfig(int port) throws IOException { YarnConfiguration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.NM_PMEM_MB, 5*1024); // 5GB conf.set(YarnConfiguration.NM_ADDRESS, "127.0.0.1:" + port); conf.set(YarnConfiguration.NM_LOCALIZER_ADDRESS, "127.0.0.1:" + ServerSocketUtil.getPort(49155, 10)); conf.set(YarnConfiguration.NM_WEBAPP_ADDRESS, "127.0.0.1:" + ServerSocketUtil .getPort(YarnConfiguration.DEFAULT_NM_WEBAPP_PORT, 10)); conf.set(YarnConfiguration.NM_LOG_DIRS, logsDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogsDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_LOCAL_DIRS, nmLocalDir.getAbsolutePath()); conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1); return conf; } private YarnConfiguration createNMConfig() throws IOException { return createNMConfig(ServerSocketUtil.getPort(49156, 10)); }
TestNodeStatusUpdaterResync
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/file/FileAssert_usingCharset_default_Test.java
{ "start": 942, "end": 1257 }
class ____ extends FileAssertBaseTest { @Override protected FileAssert invoke_api_method() { // do nothing return assertions; } @Override protected void verify_internal_effects() { assertThat(Charset.defaultCharset()).isEqualTo(getCharset(assertions)); } }
FileAssert_usingCharset_default_Test
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/util/CompilationExtension.java
{ "start": 6777, "end": 8905 }
class ____ { private final Class<?> testClass; private final List<Class<?>> testEntities; private final List<Class<?>> preCompileEntities; private final List<String> sources; private final List<String> mappingFiles; private final Map<String, String> processorOptions; private final String packageName; private final boolean ignoreCompilationErrors; private CompilationTestInfo(Class<?> testClass, List<Class<?>> testEntities, List<Class<?>> preCompileEntities, List<String> sources, List<String> mappingFiles, Map<String, String> processorOptions, String packageName, boolean ignoreCompilationErrors) { this.testClass = testClass; this.testEntities = testEntities; this.preCompileEntities = preCompileEntities; this.sources = sources; this.mappingFiles = mappingFiles; this.processorOptions = processorOptions; this.packageName = packageName; this.ignoreCompilationErrors = ignoreCompilationErrors; } private CompilationTestInfo(Class<?> testClass) { this.testClass = testClass; this.testEntities = new ArrayList<>(); this.preCompileEntities = new ArrayList<>(); this.sources = new ArrayList<>(); this.mappingFiles = new ArrayList<>(); this.processorOptions = new HashMap<>(); Package pkg = testClass.getPackage(); this.packageName = pkg != null ? pkg.getName() : null; processWithClasses( testClass.getAnnotation( WithClasses.class ) ); processWithMappingFiles( testClass.getAnnotation( WithMappingFiles.class ) ); processOptions( testClass.getAnnotation( WithProcessorOption.class ), testClass.getAnnotation( WithProcessorOption.List.class ) ); ignoreCompilationErrors = testClass.getAnnotation( IgnoreCompilationErrors.class ) != null; } protected CompilationTestInfo forMethod(Method method) { CompilationTestInfo copy = new CompilationTestInfo( testClass, new ArrayList<>( testEntities ), new ArrayList<>( preCompileEntities ), new ArrayList<>( sources ), new ArrayList<>( mappingFiles ), new HashMap<>( processorOptions ), packageName, // overrides potential
CompilationTestInfo
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/eventtime/TimestampAssignerSupplier.java
{ "start": 1401, "end": 1965 }
interface ____<T> extends Serializable { /** Instantiates a {@link TimestampAssigner}. */ TimestampAssigner<T> createTimestampAssigner(Context context); static <T> TimestampAssignerSupplier<T> of(SerializableTimestampAssigner<T> assigner) { return new SupplierFromSerializableTimestampAssigner<>(assigner); } /** * Additional information available to {@link #createTimestampAssigner(Context)}. This can be * access to {@link org.apache.flink.metrics.MetricGroup MetricGroups}, for example. */
TimestampAssignerSupplier
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/CSES3AFileSystemOperations.java
{ "start": 4026, "end": 5018 }
class ____ configuration. * * @param conf The Hadoop configuration object. * @return null */ @Override public S3ClientFactory getUnencryptedS3ClientFactory(Configuration conf) { return null; } /** * Retrieves the unencrypted length of an object in the S3 bucket. * * @param key The key (path) of the object in the S3 bucket. * @param length The length of the object. * @param store The S3AStore object representing the S3 bucket. * @param response The HeadObjectResponse containing the metadata of the object. * @return The unencrypted size of the object in bytes. * @throws IOException If an error occurs while retrieving the object size. */ @Override public long getS3ObjectSize(String key, long length, S3AStore store, HeadObjectResponse response) throws IOException { long unencryptedLength = length - CSE_PADDING_LENGTH; if (unencryptedLength >= 0) { return unencryptedLength; } return length; } }
and
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/MlMetadata.java
{ "start": 3888, "end": 5943 }
class ____ implements NamedDiff<Metadata.ProjectCustom> { final boolean upgradeMode; final boolean resetMode; MlMetadataDiff(MlMetadata before, MlMetadata after) { this.upgradeMode = after.upgradeMode; this.resetMode = after.resetMode; } public MlMetadataDiff(StreamInput in) throws IOException { upgradeMode = in.readBoolean(); resetMode = in.readBoolean(); } /** * Merge the diff with the ML metadata. * @param part The current ML metadata. * @return The new ML metadata. */ @Override public Metadata.ProjectCustom apply(Metadata.ProjectCustom part) { return new MlMetadata(upgradeMode, resetMode); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(upgradeMode); out.writeBoolean(resetMode); } @Override public String getWriteableName() { return TYPE; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.minimumCompatible(); } static Diff<Job> readJobDiffFrom(StreamInput in) throws IOException { return SimpleDiffable.readDiffFrom(Job::new, in); } static Diff<DatafeedConfig> readDatafeedDiffFrom(StreamInput in) throws IOException { return SimpleDiffable.readDiffFrom(DatafeedConfig::new, in); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MlMetadata that = (MlMetadata) o; return upgradeMode == that.upgradeMode && resetMode == that.resetMode; } @Override public final String toString() { return Strings.toString(this); } @Override public int hashCode() { return Objects.hash(upgradeMode, resetMode); } public static
MlMetadataDiff
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/expression/AttributeMap.java
{ "start": 1768, "end": 1841 }
class ____<E> implements Map<Attribute, E> { private static
AttributeMap
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/WaitForActiveShardsStep.java
{ "start": 7557, "end": 10292 }
class ____ implements ToXContentObject { private final long currentActiveShardsCount; private final String targetActiveShardsCount; private final boolean enoughShardsActive; private final String message; static final ParseField CURRENT_ACTIVE_SHARDS_COUNT = new ParseField("current_active_shards_count"); static final ParseField TARGET_ACTIVE_SHARDS_COUNT = new ParseField("target_active_shards_count"); static final ParseField ENOUGH_SHARDS_ACTIVE = new ParseField("enough_shards_active"); static final ParseField MESSAGE = new ParseField("message"); ActiveShardsInfo(long currentActiveShardsCount, String targetActiveShardsCount, boolean enoughShardsActive) { this.currentActiveShardsCount = currentActiveShardsCount; this.targetActiveShardsCount = targetActiveShardsCount; this.enoughShardsActive = enoughShardsActive; if (enoughShardsActive) { message = "the target of [" + targetActiveShardsCount + "] are active. Don't need to wait anymore"; } else { message = "waiting for [" + targetActiveShardsCount + "] shards to become active, but only [" + currentActiveShardsCount + "] are active"; } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(MESSAGE.getPreferredName(), message); builder.field(CURRENT_ACTIVE_SHARDS_COUNT.getPreferredName(), currentActiveShardsCount); builder.field(TARGET_ACTIVE_SHARDS_COUNT.getPreferredName(), targetActiveShardsCount); builder.field(ENOUGH_SHARDS_ACTIVE.getPreferredName(), enoughShardsActive); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ActiveShardsInfo info = (ActiveShardsInfo) o; return currentActiveShardsCount == info.currentActiveShardsCount && enoughShardsActive == info.enoughShardsActive && Objects.equals(targetActiveShardsCount, info.targetActiveShardsCount) && Objects.equals(message, info.message); } @Override public int hashCode() { return Objects.hash(currentActiveShardsCount, targetActiveShardsCount, enoughShardsActive, message); } } }
ActiveShardsInfo
java
elastic__elasticsearch
plugins/discovery-azure-classic/src/internalClusterTest/java/org/elasticsearch/cloud/azure/classic/AbstractAzureComputeServiceTestCase.java
{ "start": 4606, "end": 8203 }
class ____ extends AzureDiscoveryPlugin { public TestPlugin(Settings settings) { super(settings); } @Override protected AzureComputeService createComputeService() { return () -> { final List<RoleInstance> instances = new ArrayList<>(); for (Map.Entry<String, DiscoveryNode> node : nodes.entrySet()) { final String name = node.getKey(); final DiscoveryNode discoveryNode = node.getValue(); RoleInstance instance = new RoleInstance(); instance.setInstanceName(name); instance.setHostName(discoveryNode.getHostName()); instance.setPowerState(RoleInstancePowerState.Started); // Set the private IP address final TransportAddress transportAddress = discoveryNode.getAddress(); instance.setIPAddress(transportAddress.address().getAddress()); // Set the public IP address final InstanceEndpoint endpoint = new InstanceEndpoint(); endpoint.setName(Discovery.ENDPOINT_NAME_SETTING.getDefault(Settings.EMPTY)); endpoint.setVirtualIPAddress(transportAddress.address().getAddress()); endpoint.setPort(transportAddress.address().getPort()); instance.setInstanceEndpoints(new ArrayList<>(Collections.singletonList(endpoint))); instances.add(instance); } final HostedServiceGetDetailedResponse.Deployment deployment = new HostedServiceGetDetailedResponse.Deployment(); deployment.setName("dummy"); deployment.setDeploymentSlot(DeploymentSlot.Production); deployment.setStatus(DeploymentStatus.Running); deployment.setRoleInstances(new ArrayList<>(Collections.unmodifiableList(instances))); final HostedServiceGetDetailedResponse response = new HostedServiceGetDetailedResponse(); response.setDeployments(newSingletonArrayList(deployment)); return response; }; } /** * Defines a {@link AzureSeedHostsProvider} for testing purpose that is able to resolve * network addresses for Azure instances running on the same host but different ports. */ @Override protected AzureSeedHostsProvider createSeedHostsProvider( final Settings settingsToUse, final AzureComputeService azureComputeService, final TransportService transportService, final NetworkService networkService ) { return new AzureSeedHostsProvider(settingsToUse, azureComputeService, transportService, networkService) { @Override protected String resolveInstanceAddress(final HostType hostTypeValue, final RoleInstance instance) { if (hostTypeValue == HostType.PRIVATE_IP) { DiscoveryNode discoveryNode = nodes.get(instance.getInstanceName()); if (discoveryNode != null) { // Format the InetSocketAddress to a format that contains the port number return NetworkAddress.format(discoveryNode.getAddress().address()); } } return super.resolveInstanceAddress(hostTypeValue, instance); } }; } } }
TestPlugin
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/scripting/LanguageDriver.java
{ "start": 1107, "end": 1939 }
interface ____ { /** * Creates a {@link ParameterHandler} that passes the actual parameters to the the JDBC statement. * * @author Frank D. Martinez [mnesarco] * * @param mappedStatement * The mapped statement that is being executed * @param parameterObject * The input parameter object (can be null) * @param boundSql * The resulting SQL once the dynamic language has been executed. * * @return the parameter handler * * @see DefaultParameterHandler */ ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql); /** * Creates an {@link SqlSource} that will hold the statement read from a mapper xml file. It is called during startup, * when the mapped statement is read from a
LanguageDriver
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/config/CorsBeanDefinitionParser.java
{ "start": 1590, "end": 3962 }
class ____ implements BeanDefinitionParser { @Override public @Nullable BeanDefinition parse(Element element, ParserContext parserContext) { Map<String, CorsConfiguration> corsConfigurations = new LinkedHashMap<>(); List<Element> mappings = DomUtils.getChildElementsByTagName(element, "mapping"); if (mappings.isEmpty()) { CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); corsConfigurations.put("/**", config); } else { for (Element mapping : mappings) { CorsConfiguration config = new CorsConfiguration(); if (mapping.hasAttribute("allowed-origins")) { String[] allowedOrigins = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-origins"), ","); config.setAllowedOrigins(Arrays.asList(allowedOrigins)); } if (mapping.hasAttribute("allowed-origin-patterns")) { String[] patterns = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-origin-patterns"), ","); config.setAllowedOriginPatterns(Arrays.asList(patterns)); } if (mapping.hasAttribute("allowed-methods")) { String[] allowedMethods = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-methods"), ","); config.setAllowedMethods(Arrays.asList(allowedMethods)); } if (mapping.hasAttribute("allowed-headers")) { String[] allowedHeaders = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-headers"), ","); config.setAllowedHeaders(Arrays.asList(allowedHeaders)); } if (mapping.hasAttribute("exposed-headers")) { String[] exposedHeaders = StringUtils.tokenizeToStringArray(mapping.getAttribute("exposed-headers"), ","); config.setExposedHeaders(Arrays.asList(exposedHeaders)); } if (mapping.hasAttribute("allow-credentials")) { config.setAllowCredentials(Boolean.parseBoolean(mapping.getAttribute("allow-credentials"))); } if (mapping.hasAttribute("max-age")) { config.setMaxAge(Long.parseLong(mapping.getAttribute("max-age"))); } config.applyPermitDefaultValues(); config.validateAllowCredentials(); config.validateAllowPrivateNetwork(); corsConfigurations.put(mapping.getAttribute("path"), config); } } MvcNamespaceUtils.registerCorsConfigurations( corsConfigurations, parserContext, parserContext.extractSource(element)); return null; } }
CorsBeanDefinitionParser
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketFrameDecoder.java
{ "start": 788, "end": 955 }
interface ____ all WebSocketFrame decoders need to implement. * * This makes it easier to access the added encoder later in the {@link ChannelPipeline}. */ public
which
java
apache__spark
sql/api/src/main/scala/org/apache/spark/sql/internal/types/SpatialReferenceSystemMapper.java
{ "start": 1005, "end": 1157 }
class ____ { protected static final SpatialReferenceSystemCache srsCache = SpatialReferenceSystemCache.getInstance(); }
SpatialReferenceSystemMapper
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/cli/TestErasureCodingCLI.java
{ "start": 2880, "end": 3758 }
class ____ extends CLITestHelper.TestConfigFileParser { @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("ec-admin-command")) { if (testCommands != null) { testCommands.add(new CLITestCmdErasureCoding(charString, new CLICommandErasureCodingCli())); } else if (cleanupCommands != null) { cleanupCommands.add(new CLITestCmdErasureCoding(charString, new CLICommandErasureCodingCli())); } } else { super.endElement(uri, localName, qName); } } } @Override protected Result execute(CLICommand cmd) throws Exception { return cmd.getExecutor(namenode, conf).executeCommand(cmd.getCmd()); } @Test @Override public void testAll() { super.testAll(); } }
TestErasureCodingAdmin
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/KafkaStreams.java
{ "start": 19902, "end": 29713 }
interface ____ { /** * Called when state changes. * * @param newState new state * @param oldState previous state */ void onChange(final State newState, final State oldState); } /** * An app can set a single {@link KafkaStreams.StateListener} so that the app is notified when state changes. * * @param listener a new state listener * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setStateListener(final KafkaStreams.StateListener listener) { synchronized (stateLock) { if (state.hasNotStarted()) { stateListener = listener; } else { throw new IllegalStateException("Can only set StateListener before calling start(). Current state is: " + state); } } } /** * Set the handler invoked when an internal {@link StreamsConfig#NUM_STREAM_THREADS_CONFIG stream thread} * throws an unexpected exception. * These might be exceptions indicating rare bugs in Kafka Streams, or they * might be exceptions thrown by your code, for example a NullPointerException thrown from your processor logic. * The handler will execute on the thread that produced the exception. * In order to get the thread that threw the exception, use {@code Thread.currentThread()}. * <p> * Note, this handler must be thread safe, since it will be shared among all threads, and invoked from any * thread that encounters such an exception. * * @param userStreamsUncaughtExceptionHandler the uncaught exception handler of type {@link StreamsUncaughtExceptionHandler} for all internal threads * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. * @throws NullPointerException if userStreamsUncaughtExceptionHandler is null. */ public void setUncaughtExceptionHandler(final StreamsUncaughtExceptionHandler userStreamsUncaughtExceptionHandler) { synchronized (stateLock) { if (state.hasNotStarted()) { Objects.requireNonNull(userStreamsUncaughtExceptionHandler); streamsUncaughtExceptionHandler = (exception, skipThreadReplacement) -> handleStreamsUncaughtException(exception, userStreamsUncaughtExceptionHandler, skipThreadReplacement); processStreamThread(thread -> thread.setStreamsUncaughtExceptionHandler(streamsUncaughtExceptionHandler)); if (globalStreamThread != null) { globalStreamThread.setUncaughtExceptionHandler( exception -> handleStreamsUncaughtException(exception, userStreamsUncaughtExceptionHandler, false) ); } processStreamThread(thread -> thread.setUncaughtExceptionHandler((t, e) -> { } )); } else { throw new IllegalStateException("Can only set UncaughtExceptionHandler before calling start(). " + "Current state is: " + state); } } } private void replaceStreamThread(final Throwable throwable) { if (globalStreamThread != null && Thread.currentThread().getName().equals(globalStreamThread.getName())) { log.warn("The global thread cannot be replaced. Reverting to shutting down the client."); log.error("Encountered the following exception during processing " + " The streams client is going to shut down now. ", throwable); closeToError(); } final StreamThread deadThread = (StreamThread) Thread.currentThread(); deadThread.shutdown(org.apache.kafka.streams.CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP); addStreamThread(); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException("Unexpected checked exception caught in the uncaught exception handler", throwable); } } private void handleStreamsUncaughtException(final Throwable throwable, final StreamsUncaughtExceptionHandler streamsUncaughtExceptionHandler, final boolean skipThreadReplacement) { final StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse action = streamsUncaughtExceptionHandler.handle(throwable); switch (action) { case REPLACE_THREAD: if (!skipThreadReplacement) { log.error("Replacing thread in the streams uncaught exception handler", throwable); replaceStreamThread(throwable); } else { log.debug("Skipping thread replacement for recoverable error"); } break; case SHUTDOWN_CLIENT: log.error( "Encountered the following exception during processing and the registered exception handler " + "opted to {}. The streams client is going to shut down now.", action, throwable ); closeToError(); break; case SHUTDOWN_APPLICATION: if (numLiveStreamThreads() == 1) { log.warn("Attempt to shut down the application requires adding a thread to communicate the shutdown. No processing will be done on this thread"); addStreamThread(); } if (throwable instanceof Error) { log.error("This option requires running threads to shut down the application." + "but the uncaught exception was an Error, which means this runtime is no " + "longer in a well-defined state. Attempting to send the shutdown command anyway.", throwable); } if (Thread.currentThread().equals(globalStreamThread) && numLiveStreamThreads() == 0) { log.error("Exception in global thread caused the application to attempt to shutdown." + " This action will succeed only if there is at least one StreamThread running on this client." + " Currently there are no running threads so will now close the client."); closeToError(); break; } processStreamThread(StreamThread::sendShutdownRequest); log.error("Encountered the following exception during processing " + "and sent shutdown request for the entire application.", throwable); break; } } /** * Set the listener which is triggered whenever a {@link StateStore} is being restored in order to resume * processing. * * @param globalStateRestoreListener The listener triggered when {@link StateStore} is being restored. * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setGlobalStateRestoreListener(final StateRestoreListener globalStateRestoreListener) { synchronized (stateLock) { if (state.hasNotStarted()) { delegatingStateRestoreListener.setUserStateRestoreListener(globalStateRestoreListener); } else { throw new IllegalStateException("Can only set GlobalStateRestoreListener before calling start(). " + "Current state is: " + state); } } } /** * Set the listener which is triggered whenever a standby task is updated * * @param standbyListener The listener triggered when a standby task is updated. * @throws IllegalStateException if this {@code KafkaStreams} instance has already been started. */ public void setStandbyUpdateListener(final StandbyUpdateListener standbyListener) { synchronized (stateLock) { if (state.hasNotStarted()) { this.delegatingStandbyUpdateListener.setUserStandbyListener(standbyListener); } else { throw new IllegalStateException("Can only set StandbyUpdateListener before calling start(). " + "Current state is: " + state); } } } /** * Get read-only handle on global metrics registry, including streams client's own metrics plus * its embedded producer, consumer and admin clients' metrics. * * @return Map of all metrics. */ public Map<MetricName, ? extends Metric> metrics() { final Map<MetricName, Metric> result = new LinkedHashMap<>(); // producer and consumer clients are per-thread processStreamThread(thread -> { result.putAll(thread.producerMetrics()); result.putAll(thread.consumerMetrics()); // admin client is shared, so we can actually move it // to result.putAll(adminClient.metrics()). // we did it intentionally just for flexibility. result.putAll(thread.adminClientMetrics()); }); // global thread's consumer client if (globalStreamThread != null) { result.putAll(globalStreamThread.consumerMetrics()); } // self streams metrics result.putAll(metrics.metrics()); return Collections.unmodifiableMap(result); } /** * Class that handles stream thread transitions */ private final
StateListener
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/MaterializedStoreFactory.java
{ "start": 1153, "end": 1263 }
class ____ any {@link StoreFactory} that * wraps a {@link MaterializedInternal} instance. */ public abstract
for
java
apache__camel
components/camel-stitch/src/main/java/org/apache/camel/component/stitch/client/JsonUtils.java
{ "start": 1056, "end": 1849 }
class ____ { static final ObjectMapper MAPPER = new ObjectMapper(); private JsonUtils() { } public static String convertMapToJson(final Map<String, Object> inputMap) { try { return MAPPER.writeValueAsString(inputMap); } catch (JsonProcessingException exception) { throw new RuntimeException("Error occurred writing data map to JSON.", exception); } } public static Map<String, Object> convertJsonToMap(final String jsonString) { try { return MAPPER.readValue(jsonString, new TypeReference<Map<String, Object>>() { }); } catch (JsonProcessingException exception) { throw new RuntimeException("Error occurred writing JSON to Map.", exception); } } }
JsonUtils
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RedirectionErrorPage.java
{ "start": 966, "end": 1077 }
class ____ used to display a message that the proxy request failed * because of a redirection issue. */ public
is
java
playframework__playframework
documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java
{ "start": 1501, "end": 1635 }
class ____ { static Find find = new Find(); Item(String id) { this.id = id; } public String id; } static
Item
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java
{ "start": 8074, "end": 8323 }
class ____ extends RequestPartTestConfig { @Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } } @Controller @SuppressWarnings("unused") private static
StandardMultipartResolverTestConfig
java
google__dagger
javatests/dagger/functional/subcomponent/multibindings/MultibindingSubcomponents.java
{ "start": 3964, "end": 4739 }
class ____ { @Provides static BoundInParentAndChild provideBoundInParentAndChildForBinds() { return BoundInParentAndChild.IN_CHILD; } @Binds @IntoSet abstract BoundInParentAndChild bindsLocalContribution(BoundInParentAndChild instance); @Binds @IntoMap @StringKey("child key") abstract BoundInParentAndChild inParentAndChildEntry(BoundInParentAndChild instance); @Provides static BoundInChild provideBoundInChildForBinds() { return BoundInChild.INSTANCE; } @Binds @IntoSet abstract BoundInChild inChild(BoundInChild instance); @Binds @IntoMap @StringKey("child key") abstract BoundInChild inChildEntry(BoundInChild instance); }
ChildMultibindingModuleWithOnlyBindsMultibindings
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/cors/reactive/PreFlightRequestHandler.java
{ "start": 907, "end": 1374 }
interface ____ { /** * Handle a pre-flight request by finding and applying the CORS configuration * that matches the expected actual request. As a result of handling, the * response should be updated with CORS headers or rejected with * {@link org.springframework.http.HttpStatus#FORBIDDEN}. * @param exchange the exchange for the request * @return a completion handle */ Mono<Void> handlePreFlight(ServerWebExchange exchange); }
PreFlightRequestHandler
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/compatible/TypeUtilsComputeGettersTest.java
{ "start": 240, "end": 549 }
class ____ extends TestCase { public void test_for_computeGetters() { List<FieldInfo> fieldInfoList = TypeUtils.computeGetters(Model.class, null); assertEquals(1, fieldInfoList.size()); assertEquals("id", fieldInfoList.get(0).name); } public static
TypeUtilsComputeGettersTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/ResourceManager.java
{ "start": 69441, "end": 71150 }
class ____ implements BlocklistContext { @Override public void blockResources(Collection<BlockedNode> blockedNodes) {} @Override public void unblockResources(Collection<BlockedNode> unBlockedNodes) { // when a node is unblocked, we should trigger the resource requirements because the // slots on this node become available again. slotManager.triggerResourceRequirementsCheck(); } } // ------------------------------------------------------------------------ // Resource Management // ------------------------------------------------------------------------ @Override public void onNewTokensObtained(byte[] tokens) throws Exception { latestTokens.set(tokens); log.info("Updating delegation tokens for {} task manager(s).", taskExecutors.size()); if (!taskExecutors.isEmpty()) { final List<CompletableFuture<Acknowledge>> futures = new ArrayList<>(taskExecutors.size()); for (Map.Entry<ResourceID, WorkerRegistration<WorkerType>> workerRegistrationEntry : taskExecutors.entrySet()) { WorkerRegistration<WorkerType> registration = workerRegistrationEntry.getValue(); log.info("Updating delegation tokens for node {}.", registration.getNodeId()); final TaskExecutorGateway taskExecutorGateway = registration.getTaskExecutorGateway(); futures.add(taskExecutorGateway.updateDelegationTokens(getFencingToken(), tokens)); } FutureUtils.combineAll(futures).get(); } } }
ResourceManagerBlocklistContext
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestSnapshotManager.java
{ "start": 2074, "end": 7787 }
class ____ { private static final int testMaxSnapshotIDLimit = 7; /** * Test that the global limit on snapshot Ids is honored. */ @Test @Timeout(value = 10) public void testSnapshotIDLimits() throws Exception { testMaxSnapshotLimit(testMaxSnapshotIDLimit, "rollover", new Configuration(), testMaxSnapshotIDLimit); } /** * Tests that the global limit on snapshots is honored. */ @Test @Timeout(value = 10) public void testMaxSnapshotLimit() throws Exception { Configuration conf = new Configuration(); conf.setInt(DFSConfigKeys.DFS_NAMENODE_SNAPSHOT_FILESYSTEM_LIMIT, testMaxSnapshotIDLimit); conf.setInt(DFSConfigKeys. DFS_NAMENODE_SNAPSHOT_MAX_LIMIT, testMaxSnapshotIDLimit); testMaxSnapshotLimit(testMaxSnapshotIDLimit,"file system snapshot limit" , conf, testMaxSnapshotIDLimit * 2); } private void testMaxSnapshotLimit(int maxSnapshotLimit, String errMsg, Configuration conf, int maxSnapID) throws IOException { LeaseManager leaseManager = mock(LeaseManager.class); INodeDirectory ids = mock(INodeDirectory.class); FSDirectory fsdir = mock(FSDirectory.class); INodesInPath iip = mock(INodesInPath.class); SnapshotManager sm = spy(new SnapshotManager(conf, fsdir)); doReturn(ids).when(sm).getSnapshottableRoot(any()); doReturn(maxSnapID).when(sm).getMaxSnapshotID(); doReturn(true).when(fsdir).isImageLoaded(); // Create testMaxSnapshotLimit snapshots. These should all succeed. // for (Integer i = 0; i < maxSnapshotLimit; ++i) { sm.createSnapshot(leaseManager, iip, "dummy", i.toString(), Time.now()); } // Attempt to create one more snapshot. This should fail due to snapshot // ID rollover. // try { sm.createSnapshot(leaseManager, iip, "dummy", "shouldFailSnapshot", Time.now()); fail("Expected SnapshotException not thrown"); } catch (SnapshotException se) { assertTrue( StringUtils.toLowerCase(se.getMessage()).contains(errMsg)); } // Delete a snapshot to free up a slot. // sm.deleteSnapshot(iip, "", mock(INode.ReclaimContext.class), Time.now()); // Attempt to create a snapshot again. It should still fail due // to snapshot ID rollover. // try { sm.createSnapshot(leaseManager, iip, "dummy", "shouldFailSnapshot2", Time.now()); // in case the snapshot ID limit is hit, further creation of snapshots // even post deletions of snapshots won't succeed if (maxSnapID < maxSnapshotLimit) { fail("CreateSnapshot should succeed"); } } catch (SnapshotException se) { assertTrue( StringUtils.toLowerCase(se.getMessage()).contains(errMsg)); } } /** * Snapshot is identified by INODE CURRENT_STATE_ID. * So maximum allowable snapshotID should be less than CURRENT_STATE_ID */ @Test public void testValidateSnapshotIDWidth() throws Exception { FSDirectory fsdir = mock(FSDirectory.class); SnapshotManager snapshotManager = new SnapshotManager(new Configuration(), fsdir); assertTrue(snapshotManager. getMaxSnapshotID() < Snapshot.CURRENT_STATE_ID); } @Test public void testSnapshotLimitOnRestart() throws Exception { final Configuration conf = new Configuration(); final Path snapshottableDir = new Path("/" + getClass().getSimpleName()); int numSnapshots = 5; conf.setInt(DFSConfigKeys. DFS_NAMENODE_SNAPSHOT_MAX_LIMIT, numSnapshots); conf.setInt(DFSConfigKeys.DFS_NAMENODE_SNAPSHOT_FILESYSTEM_LIMIT, numSnapshots * 2); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf). numDataNodes(0).build(); cluster.waitActive(); DistributedFileSystem hdfs = cluster.getFileSystem(); hdfs.mkdirs(snapshottableDir); hdfs.allowSnapshot(snapshottableDir); for (int i = 0; i < numSnapshots; i++) { hdfs.createSnapshot(snapshottableDir, "s" + i); } LambdaTestUtils.intercept(SnapshotException.class, "snapshot limit", () -> hdfs.createSnapshot(snapshottableDir, "s5")); // now change max snapshot directory limit to 2 and restart namenode cluster.getNameNode().getConf().setInt(DFSConfigKeys. DFS_NAMENODE_SNAPSHOT_MAX_LIMIT, 2); cluster.restartNameNodes(); SnapshotManager snapshotManager = cluster.getNamesystem(). getSnapshotManager(); // make sure edits of all previous 5 create snapshots are replayed assertEquals(numSnapshots, snapshotManager.getNumSnapshots()); // make sure namenode has the new snapshot limit configured as 2 assertEquals(2, snapshotManager.getMaxSnapshotLimit()); // Any new snapshot creation should still fail LambdaTestUtils.intercept(SnapshotException.class, "snapshot limit", () -> hdfs.createSnapshot(snapshottableDir, "s5")); // now change max snapshot FS limit to 2 and restart namenode cluster.getNameNode().getConf().setInt(DFSConfigKeys. DFS_NAMENODE_SNAPSHOT_FILESYSTEM_LIMIT, 2); cluster.restartNameNodes(); snapshotManager = cluster.getNamesystem(). getSnapshotManager(); // make sure edits of all previous 5 create snapshots are replayed assertEquals(numSnapshots, snapshotManager.getNumSnapshots()); // make sure namenode has the new snapshot limit configured as 2 assertEquals(2, snapshotManager.getMaxSnapshotLimit()); } finally { if (cluster != null) { cluster.shutdown(); } } } }
TestSnapshotManager
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PgReplicationSlotEndpointBuilderFactory.java
{ "start": 21180, "end": 32317 }
interface ____ extends EndpointConsumerBuilder { default PgReplicationSlotEndpointBuilder basic() { return (PgReplicationSlotEndpointBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder pollStrategy(String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * Auto create slot if it does not exist. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: true * Group: advanced * * @param autoCreateSlot the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder autoCreateSlot(Boolean autoCreateSlot) { doSetProperty("autoCreateSlot", autoCreateSlot); return this; } /** * Auto create slot if it does not exist. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: true * Group: advanced * * @param autoCreateSlot the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder autoCreateSlot(String autoCreateSlot) { doSetProperty("autoCreateSlot", autoCreateSlot); return this; } /** * Slot options to be passed to the output plugin. This is a multi-value * option with prefix: slotOptions. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the slotOptions(String, * Object) method to add a value (call the method multiple times to set * more values). * * Group: advanced * * @param key the option key * @param value the option value * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder slotOptions(String key, Object value) { doSetMultiValueProperty("slotOptions", "slotOptions." + key, value); return this; } /** * Slot options to be passed to the output plugin. This is a multi-value * option with prefix: slotOptions. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the slotOptions(String, * Object) method to add a value (call the method multiple times to set * more values). * * Group: advanced * * @param values the values * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder slotOptions(Map values) { doSetMultiValueProperties("slotOptions", "slotOptions.", values); return this; } /** * Specifies the number of seconds between status packets sent back to * Postgres server. * * The option is a: <code>java.lang.Integer</code> type. * * Default: 10 * Group: advanced * * @param statusInterval the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder statusInterval(Integer statusInterval) { doSetProperty("statusInterval", statusInterval); return this; } /** * Specifies the number of seconds between status packets sent back to * Postgres server. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 10 * Group: advanced * * @param statusInterval the value to set * @return the dsl builder */ default AdvancedPgReplicationSlotEndpointBuilder statusInterval(String statusInterval) { doSetProperty("statusInterval", statusInterval); return this; } } public
AdvancedPgReplicationSlotEndpointBuilder
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/over/frame/UnboundedPrecedingOverFrame.java
{ "start": 1478, "end": 2789 }
class ____ implements OverWindowFrame { private GeneratedAggsHandleFunction aggsHandleFunction; AggsHandleFunction processor; RowData accValue; /** An iterator over the input. */ ResettableExternalBuffer.BufferIterator inputIterator; /** The next row from `input`. */ BinaryRowData nextRow; public UnboundedPrecedingOverFrame(GeneratedAggsHandleFunction aggsHandleFunction) { this.aggsHandleFunction = aggsHandleFunction; } @Override public void open(ExecutionContext ctx) throws Exception { ClassLoader cl = ctx.getRuntimeContext().getUserCodeClassLoader(); processor = aggsHandleFunction.newInstance(cl); processor.open(new PerKeyStateDataViewStore(ctx.getRuntimeContext())); this.aggsHandleFunction = null; } @Override public void prepare(ResettableExternalBuffer rows) throws Exception { if (inputIterator != null) { inputIterator.close(); } inputIterator = rows.newIterator(); if (inputIterator.advanceNext()) { nextRow = inputIterator.getRow().copy(); } processor.setWindowSize(rows.size()); // reset the accumulators value processor.setAccumulators(processor.createAccumulators()); } }
UnboundedPrecedingOverFrame
java
quarkusio__quarkus
test-framework/junit5-internal/src/main/java/io/quarkus/test/DisabledOnSemeruCondition.java
{ "start": 406, "end": 2161 }
class ____ implements ExecutionCondition { @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { Optional<AnnotatedElement> element = context.getElement(); Optional<DisabledOnSemeru> optional = findAnnotation(element, DisabledOnSemeru.class); if (optional.isEmpty()) { return ConditionEvaluationResult.enabled("@DisabledOnSemeru was not found"); } if (!JdkUtil.isSemeru()) { return ConditionEvaluationResult.enabled("JVM is not identified as Semeru"); } DisabledOnSemeru disabledOnSemeru = optional.get(); if (disabledOnSemeru.versionGreaterThanOrEqualTo() > 0 || disabledOnSemeru.versionLessThanOrEqualTo() > 0) { if (disabledOnSemeru.versionGreaterThanOrEqualTo() > 0) { if (Runtime.version().feature() < disabledOnSemeru.versionGreaterThanOrEqualTo()) { return ConditionEvaluationResult.disabled( "JVM identified as Semeru and JVM version < " + disabledOnSemeru.versionGreaterThanOrEqualTo()); } } if (disabledOnSemeru.versionLessThanOrEqualTo() > 0) { if (Runtime.version().feature() > disabledOnSemeru.versionLessThanOrEqualTo()) { return ConditionEvaluationResult.disabled( "JVM identified as Semeru and JVM version > " + disabledOnSemeru.versionLessThanOrEqualTo()); } } return ConditionEvaluationResult.enabled("JVM is identified as Semeru but version matches"); } return ConditionEvaluationResult.disabled("JVM is identified as Semeru"); } }
DisabledOnSemeruCondition
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/TestLogicalType.java
{ "start": 13929, "end": 14723 }
class ____ the Runnable should throw * @param containedInMessage A String that should be contained by the thrown * exception's message * @param callable A Callable that is expected to throw the exception */ public static void assertThrows(String message, Class<? extends Exception> expected, String containedInMessage, Callable<?> callable) { try { callable.call(); fail("No exception was thrown (" + message + "), expected: " + expected.getName()); } catch (Exception actual) { assertEquals(expected, actual.getClass(), message); assertTrue(actual.getMessage().contains(containedInMessage), "Expected exception message (" + containedInMessage + ") missing: " + actual.getMessage()); } } }
that
java
alibaba__nacos
client-basic/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java
{ "start": 840, "end": 1225 }
class ____ { @Test void testNormalizeContextPath() { assertEquals("/nacos", ContextPathUtil.normalizeContextPath("/nacos")); assertEquals("/nacos", ContextPathUtil.normalizeContextPath("nacos")); assertEquals("", ContextPathUtil.normalizeContextPath("/")); assertEquals("", ContextPathUtil.normalizeContextPath("")); } }
ContextPathUtilTest
java
quarkusio__quarkus
extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/exception/SmallRyeAuthSecurityIdentityAlreadyAssignedException.java
{ "start": 299, "end": 824 }
class ____ extends Exception { private final Map<String, Object> connectionInitPayload; public SmallRyeAuthSecurityIdentityAlreadyAssignedException(Map<String, Object> connectionInitPayload) { super("Security identity already assigned to this WebSocket."); this.connectionInitPayload = Collections.unmodifiableMap(connectionInitPayload); } public Map<String, Object> getConnectionInitPayload() { return connectionInitPayload; } }
SmallRyeAuthSecurityIdentityAlreadyAssignedException
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/CamelUpdateException.java
{ "start": 868, "end": 1183 }
class ____ extends Exception { public CamelUpdateException(String message) { super(message); } public CamelUpdateException(String message, Throwable cause) { super(message, cause); } public CamelUpdateException(Throwable cause) { super(cause); } }
CamelUpdateException
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/testing/springbootapplications/autoconfiguredwebservices/client/MyWebServiceClientTests.java
{ "start": 1297, "end": 1766 }
class ____ { @Autowired private MockWebServiceServer server; @Autowired private SomeWebService someWebService; @Test void mockServerCall() { // @formatter:off this.server .expect(payload(new StringSource("<request/>"))) .andRespond(withPayload(new StringSource("<response><status>200</status></response>"))); assertThat(this.someWebService.test()) .extracting(Response::getStatus) .isEqualTo(200); // @formatter:on } }
MyWebServiceClientTests
java
quarkusio__quarkus
extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/FooResource.java
{ "start": 166, "end": 299 }
class ____ implements FooAPI { @Override public Response getFoo() { return Response.ok("ok").build(); } }
FooResource
java
apache__kafka
metadata/src/test/java/org/apache/kafka/metadata/placement/StripedReplicaPlacerTest.java
{ "start": 1646, "end": 1719 }
class ____ { /** * Test that the BrokerList
StripedReplicaPlacerTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/client/samples/JsonContentTests.java
{ "start": 3822, "end": 4440 }
class ____ { @GetMapping List<Person> getPersons() { return List.of(new Person("Jane", "Williams"), new Person("Jason", "Johnson"), new Person("John", "Smith")); } @GetMapping("/{firstName}/{lastName}") Person getPerson(@PathVariable String firstName, @PathVariable String lastName) { return new Person(firstName, lastName); } @PostMapping ResponseEntity<String> savePerson(@RequestBody Person person) { URI location = URI.create(String.format("/persons/%s/%s", person.getFirstName(), person.getLastName())); return ResponseEntity.created(location).build(); } } static
PersonController
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 112578, "end": 112767 }
class ____ extends ImmutableAbstractClass { // BUG: Diagnostic contains: has non-final field Object unsafe; } """) .doTest(); } }
H
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/datageneration/datasource/DefaultMappingParametersHandler.java
{ "start": 1211, "end": 12747 }
class ____ implements DataSourceHandler { @Override public DataSourceResponse.LeafMappingParametersGenerator handle(DataSourceRequest.LeafMappingParametersGenerator request) { var fieldType = FieldType.tryParse(request.fieldType()); if (fieldType == null) { // This is a custom field type return null; } return new DataSourceResponse.LeafMappingParametersGenerator(switch (fieldType) { case KEYWORD -> keywordMapping(request); case LONG, INTEGER, SHORT, BYTE, DOUBLE, FLOAT, HALF_FLOAT, UNSIGNED_LONG -> numberMapping(fieldType); case SCALED_FLOAT -> scaledFloatMapping(); case COUNTED_KEYWORD -> countedKeywordMapping(); case BOOLEAN -> booleanMapping(); case DATE -> dateMapping(); case GEO_POINT -> geoPointMapping(); case TEXT -> textMapping(); case IP -> ipMapping(); case CONSTANT_KEYWORD -> constantKeywordMapping(); case WILDCARD -> wildcardMapping(); case MATCH_ONLY_TEXT -> matchOnlyTextMapping(); case PASSTHROUGH -> throw new IllegalArgumentException("Unsupported field type: " + fieldType); }); } private Supplier<Map<String, Object>> numberMapping(FieldType fieldType) { return () -> { var mapping = commonMappingParameters(); if (ESTestCase.randomBoolean()) { mapping.put("ignore_malformed", ESTestCase.randomBoolean()); } if (ESTestCase.randomDouble() <= 0.2) { Number value = switch (fieldType) { case LONG -> ESTestCase.randomLong(); case UNSIGNED_LONG -> ESTestCase.randomNonNegativeLong(); case INTEGER -> ESTestCase.randomInt(); case SHORT -> ESTestCase.randomShort(); case BYTE -> ESTestCase.randomByte(); case DOUBLE -> ESTestCase.randomDouble(); case FLOAT, HALF_FLOAT -> ESTestCase.randomFloat(); default -> throw new IllegalStateException("Unexpected field type"); }; mapping.put("null_value", value); } return mapping; }; } private Supplier<Map<String, Object>> keywordMapping(DataSourceRequest.LeafMappingParametersGenerator request) { return () -> { var mapping = commonMappingParameters(); // Inject copy_to sometimes but reflect that it is not widely used in reality. // We only add copy_to to keywords because we get into trouble with numeric fields that are copied to dynamic fields. // If first copied value is numeric, dynamic field is created with numeric field type and then copy of text values fail. // Actual value being copied does not influence the core logic of copy_to anyway. if (ESTestCase.randomDouble() <= 0.05) { var options = request.eligibleCopyToFields() .stream() .filter(f -> f.equals(request.fieldName()) == false) .collect(Collectors.toSet()); if (options.isEmpty() == false) { mapping.put("copy_to", randomFrom(options)); } } if (ESTestCase.randomDouble() <= 0.3) { mapping.put("ignore_above", ESTestCase.randomIntBetween(1, 50)); } if (ESTestCase.randomDouble() <= 0.2) { mapping.put("null_value", ESTestCase.randomAlphaOfLengthBetween(0, 10)); } return mapping; }; } private Supplier<Map<String, Object>> scaledFloatMapping() { return () -> { var mapping = commonMappingParameters(); mapping.put("scaling_factor", randomFrom(10, 1000, 100000, 100.5)); if (ESTestCase.randomDouble() <= 0.2) { mapping.put("null_value", ESTestCase.randomDouble()); } if (ESTestCase.randomBoolean()) { mapping.put("ignore_malformed", ESTestCase.randomBoolean()); } return mapping; }; } private Supplier<Map<String, Object>> countedKeywordMapping() { return () -> Map.of("index", ESTestCase.randomBoolean()); } private Supplier<Map<String, Object>> booleanMapping() { return () -> { var mapping = commonMappingParameters(); if (ESTestCase.randomDouble() <= 0.2) { mapping.put("null_value", randomFrom(true, false, "true", "false")); } if (ESTestCase.randomBoolean()) { mapping.put("ignore_malformed", ESTestCase.randomBoolean()); } return mapping; }; } // just a custom format, specific format does not matter private static final String FORMAT = "yyyy_MM_dd_HH_mm_ss_n"; private Supplier<Map<String, Object>> dateMapping() { return () -> { var mapping = commonMappingParameters(); String format = null; if (ESTestCase.randomBoolean()) { format = FORMAT; mapping.put("format", format); } if (ESTestCase.randomDouble() <= 0.2) { var instant = ESTestCase.randomInstantBetween(Instant.parse("2300-01-01T00:00:00Z"), Instant.parse("2350-01-01T00:00:00Z")); if (format == null) { mapping.put("null_value", instant.toEpochMilli()); } else { mapping.put( "null_value", DateTimeFormatter.ofPattern(format, Locale.ROOT).withZone(ZoneId.from(ZoneOffset.UTC)).format(instant) ); } } if (ESTestCase.randomBoolean()) { mapping.put("ignore_malformed", ESTestCase.randomBoolean()); } return mapping; }; } private Supplier<Map<String, Object>> geoPointMapping() { return () -> { var mapping = commonMappingParameters(); if (ESTestCase.randomDouble() <= 0.2) { var point = GeometryTestUtils.randomPoint(false); mapping.put("null_value", WellKnownText.toWKT(point)); } if (ESTestCase.randomBoolean()) { mapping.put("ignore_malformed", ESTestCase.randomBoolean()); } return mapping; }; } private Supplier<Map<String, Object>> textMapping() { return () -> { var mapping = new HashMap<String, Object>(); mapping.put("store", ESTestCase.randomBoolean()); mapping.put("index", ESTestCase.randomBoolean()); return mapping; }; } private Supplier<Map<String, Object>> ipMapping() { return () -> { var mapping = commonMappingParameters(); if (ESTestCase.randomDouble() <= 0.2) { mapping.put("null_value", NetworkAddress.format(ESTestCase.randomIp(ESTestCase.randomBoolean()))); } if (ESTestCase.randomBoolean()) { mapping.put("ignore_malformed", ESTestCase.randomBoolean()); } return mapping; }; } private Supplier<Map<String, Object>> constantKeywordMapping() { return () -> { var mapping = new HashMap<String, Object>(); // value is optional and can be set from the first document // we don't cover this case here mapping.put("value", ESTestCase.randomAlphaOfLengthBetween(0, 10)); return mapping; }; } private Supplier<Map<String, Object>> wildcardMapping() { return () -> { var mapping = new HashMap<String, Object>(); if (ESTestCase.randomDouble() <= 0.3) { mapping.put("ignore_above", ESTestCase.randomIntBetween(1, 50)); } if (ESTestCase.randomDouble() <= 0.2) { mapping.put("null_value", ESTestCase.randomAlphaOfLengthBetween(0, 10)); } return mapping; }; } private Supplier<Map<String, Object>> matchOnlyTextMapping() { return HashMap::new; } public static HashMap<String, Object> commonMappingParameters() { var map = new HashMap<String, Object>(); map.put("store", ESTestCase.randomBoolean()); map.put("index", ESTestCase.randomBoolean()); map.put("doc_values", ESTestCase.randomBoolean()); if (ESTestCase.randomBoolean()) { map.put(Mapper.SYNTHETIC_SOURCE_KEEP_PARAM, randomFrom("none", "arrays", "all")); } return map; } @Override public DataSourceResponse.ObjectMappingParametersGenerator handle(DataSourceRequest.ObjectMappingParametersGenerator request) { if (request.isNested()) { assert request.parentSubobjects() != ObjectMapper.Subobjects.DISABLED; return new DataSourceResponse.ObjectMappingParametersGenerator(() -> { var parameters = new HashMap<String, Object>(); if (ESTestCase.randomBoolean()) { parameters.put("dynamic", randomFrom("true", "false", "strict")); } if (ESTestCase.randomBoolean()) { parameters.put(Mapper.SYNTHETIC_SOURCE_KEEP_PARAM, "all"); // [arrays] doesn't apply to nested objects } return parameters; }); } return new DataSourceResponse.ObjectMappingParametersGenerator(() -> { var parameters = new HashMap<String, Object>(); // Changing subobjects from subobjects: false is not supported, but we can f.e. go from "true" to "false". // TODO enable subobjects: auto // It is disabled because it currently does not have auto flattening and that results in asserts being triggered when using // copy_to. var subobjects = randomFrom(ObjectMapper.Subobjects.values()); if (request.parentSubobjects() == ObjectMapper.Subobjects.DISABLED || subobjects == ObjectMapper.Subobjects.DISABLED) { // "enabled: false" is not compatible with subobjects: false // changing "dynamic" from parent context is not compatible with subobjects: false // changing subobjects value is not compatible with subobjects: false if (ESTestCase.randomBoolean()) { parameters.put("enabled", "true"); } return parameters; } if (ESTestCase.randomBoolean()) { parameters.put("subobjects", subobjects.toString()); } if (ESTestCase.randomBoolean()) { parameters.put("dynamic", randomFrom("true", "false", "strict", "runtime")); } if (ESTestCase.randomBoolean()) { parameters.put("enabled", randomFrom("true", "false")); } if (ESTestCase.randomBoolean()) { var value = request.isRoot() ? randomFrom("none", "arrays") : randomFrom("none", "arrays", "all"); parameters.put(Mapper.SYNTHETIC_SOURCE_KEEP_PARAM, value); } return parameters; }); } }
DefaultMappingParametersHandler
java
elastic__elasticsearch
x-pack/plugin/inference/qa/rolling-upgrade/src/javaRestTest/java/org/elasticsearch/xpack/application/HuggingFaceServiceUpgradeIT.java
{ "start": 955, "end": 7864 }
class ____ extends InferenceUpgradeTestCase { // TODO: replace with proper test features private static final String HF_EMBEDDINGS_TEST_FEATURE = "gte_v8.12.0"; private static final String HF_ELSER_TEST_FEATURE = "gte_v8.12.0"; private static MockWebServer embeddingsServer; private static MockWebServer elserServer; public HuggingFaceServiceUpgradeIT(@Name("upgradedNodes") int upgradedNodes) { super(upgradedNodes); } @BeforeClass public static void startWebServer() throws IOException { embeddingsServer = new MockWebServer(); embeddingsServer.start(); elserServer = new MockWebServer(); elserServer.start(); } @AfterClass public static void shutdown() { embeddingsServer.close(); elserServer.close(); } @SuppressWarnings("unchecked") public void testHFEmbeddings() throws IOException { var embeddingsSupported = oldClusterHasFeature(HF_EMBEDDINGS_TEST_FEATURE); String oldClusterEndpointIdentifier = oldClusterHasFeature(MODELS_RENAMED_TO_ENDPOINTS_FEATURE) ? "endpoints" : "models"; assumeTrue("Hugging Face embedding service supported", embeddingsSupported); final String oldClusterId = "old-cluster-embeddings"; final String upgradedClusterId = "upgraded-cluster-embeddings"; var testTaskType = TaskType.TEXT_EMBEDDING; if (isOldCluster()) { // queue a response as PUT will call the service embeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponse())); put(oldClusterId, embeddingConfig(getUrl(embeddingsServer)), testTaskType); var configs = (List<Map<String, Object>>) get(testTaskType, oldClusterId).get(oldClusterEndpointIdentifier); assertThat(configs, hasSize(1)); assertEmbeddingInference(oldClusterId); } else if (isMixedCluster()) { var configs = getConfigsWithBreakingChangeHandling(testTaskType, oldClusterId); assertEquals("hugging_face", configs.get(0).get("service")); assertEmbeddingInference(oldClusterId); } else if (isUpgradedCluster()) { // check old cluster model var configs = (List<Map<String, Object>>) get(testTaskType, oldClusterId).get("endpoints"); assertEquals("hugging_face", configs.get(0).get("service")); // Inference on old cluster model assertEmbeddingInference(oldClusterId); embeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponse())); put(upgradedClusterId, embeddingConfig(getUrl(embeddingsServer)), testTaskType); configs = (List<Map<String, Object>>) get(testTaskType, upgradedClusterId).get("endpoints"); assertThat(configs, hasSize(1)); assertEmbeddingInference(upgradedClusterId); delete(oldClusterId); delete(upgradedClusterId); } } void assertEmbeddingInference(String inferenceId) throws IOException { embeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponse())); var inferenceMap = inference(inferenceId, TaskType.TEXT_EMBEDDING, "some text"); assertThat(inferenceMap.entrySet(), not(empty())); } @SuppressWarnings("unchecked") public void testElser() throws IOException { var supported = oldClusterHasFeature(HF_ELSER_TEST_FEATURE); String old_cluster_endpoint_identifier = oldClusterHasFeature(MODELS_RENAMED_TO_ENDPOINTS_FEATURE) ? "endpoints" : "models"; assumeTrue("HF elser service supported", supported); final String oldClusterId = "old-cluster-elser"; final String upgradedClusterId = "upgraded-cluster-elser"; var testTaskType = TaskType.SPARSE_EMBEDDING; if (isOldCluster()) { elserServer.enqueue(new MockResponse().setResponseCode(200).setBody(elserResponse())); put(oldClusterId, elserConfig(getUrl(elserServer)), testTaskType); var configs = (List<Map<String, Object>>) get(testTaskType, oldClusterId).get(old_cluster_endpoint_identifier); assertThat(configs, hasSize(1)); assertElser(oldClusterId); } else if (isMixedCluster()) { var configs = getConfigsWithBreakingChangeHandling(testTaskType, oldClusterId); assertEquals("hugging_face", configs.get(0).get("service")); assertElser(oldClusterId); } else if (isUpgradedCluster()) { // check old cluster model var configs = (List<Map<String, Object>>) get(testTaskType, oldClusterId).get("endpoints"); assertEquals("hugging_face", configs.get(0).get("service")); var taskSettings = (Map<String, Object>) configs.get(0).get("task_settings"); assertThat(taskSettings, anyOf(nullValue(), anEmptyMap())); assertElser(oldClusterId); // New endpoint elserServer.enqueue(new MockResponse().setResponseCode(200).setBody(elserResponse())); put(upgradedClusterId, elserConfig(getUrl(elserServer)), testTaskType); configs = (List<Map<String, Object>>) get(upgradedClusterId).get("endpoints"); assertThat(configs, hasSize(1)); assertElser(upgradedClusterId); delete(oldClusterId); delete(upgradedClusterId); } } private void assertElser(String inferenceId) throws IOException { elserServer.enqueue(new MockResponse().setResponseCode(200).setBody(elserResponse())); var inferenceMap = inference(inferenceId, TaskType.SPARSE_EMBEDDING, "some text"); assertThat(inferenceMap.entrySet(), not(empty())); } static String embeddingConfig(String url) { return Strings.format(""" { "service": "hugging_face", "service_settings": { "url": "%s", "api_key": "XXXX" } } """, url); } private String embeddingResponse() { return """ [ [ 0.014539449, -0.015288644 ] ] """; } static String elserConfig(String url) { return Strings.format(""" { "service": "hugging_face", "service_settings": { "api_key": "XXXX", "url": "%s" } } """, url); } static String elserResponse() { return """ [ { ".": 0.133155956864357, "the": 0.6747211217880249 } ] """; } }
HuggingFaceServiceUpgradeIT
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/lossy/CutleryInventoryMapper.java
{ "start": 366, "end": 552 }
interface ____ { CutleryInventoryMapper INSTANCE = Mappers.getMapper( CutleryInventoryMapper.class ); CutleryInventoryEntity map( CutleryInventoryDto in ); }
CutleryInventoryMapper
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ZippedElementsShouldSatisfy_create_Test.java
{ "start": 1217, "end": 4045 }
class ____ { private AssertionInfo info; @BeforeEach public void setUp() { info = someInfo(); } @Test void should_create_error_message() { // GIVEN List<ZipSatisfyError> errors = list(new ZipSatisfyError("Luke", "LUKE", "error luke"), new ZipSatisfyError("Yo-da", "YODA", "error yoda")); ErrorMessageFactory factory = zippedElementsShouldSatisfy(info, list("Luke", "Yo-da"), list("LUKE", "YODA"), errors); // WHEN String message = factory.create(new TextDescription("Test"), info.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting zipped elements of:%n" + " [\"Luke\", \"Yo-da\"]%n" + "and:%n" + " [\"LUKE\", \"YODA\"]%n" + "to satisfy given requirements but these zipped elements did not:" + "%n%n- (\"Luke\", \"LUKE\")%n" + "error: error luke" + "%n%n- (\"Yo-da\", \"YODA\")%n" + "error: error yoda")); } @Test void should_create_error_message_and_escape_percent_correctly() { // GIVEN List<ZipSatisfyError> errors = list(new ZipSatisfyError("Luke", "LU%dKE", "error luke"), new ZipSatisfyError("Yo-da", "YODA", "error yoda")); ErrorMessageFactory factory = zippedElementsShouldSatisfy(info, list("Luke", "Yo-da"), list("LU%dKE", "YODA"), errors); // WHEN String message = factory.create(new TextDescription("Test"), info.representation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting zipped elements of:%n" + " [\"Luke\", \"Yo-da\"]%n" + "and:%n" + " [\"LU%%dKE\", \"YODA\"]%n" + "to satisfy given requirements but these zipped elements did not:" + "%n%n- (\"Luke\", \"LU%%dKE\")%n" + "error: error luke" + "%n%n- (\"Yo-da\", \"YODA\")%n" + "error: error yoda")); } }
ZippedElementsShouldSatisfy_create_Test
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/text/StrMatcher.java
{ "start": 1022, "end": 1117 }
class ____ can be queried to determine if a character array * portion matches. * <p> * This
that
java
apache__camel
components/camel-jcr/src/main/java/org/apache/camel/component/jcr/JcrConsumer.java
{ "start": 6572, "end": 7591 }
class ____ implements Runnable { @Override public void run() { LOG.debug("JcrConsumerSessionListenerChecker starts."); boolean isSessionLive = false; lock.lock(); try { if (JcrConsumer.this.session != null) { try { isSessionLive = JcrConsumer.this.session.isLive(); } catch (Exception e) { LOG.debug("Exception while checking jcr session", e); } } } finally { lock.unlock(); } if (!isSessionLive) { try { createSessionAndRegisterListener(); } catch (RepositoryException e) { LOG.error("Failed to create session and register listener", e); } } LOG.debug("JcrConsumerSessionListenerChecker stops."); } } }
JcrConsumerSessionListenerChecker
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/DataAttachmentParserTests.java
{ "start": 925, "end": 2344 }
class ____ extends ESTestCase { public void testSerializationWorks() throws Exception { Map<String, EmailAttachmentParser<?>> attachmentParsers = new HashMap<>(); attachmentParsers.put(DataAttachmentParser.TYPE, new DataAttachmentParser()); EmailAttachmentsParser emailAttachmentsParser = new EmailAttachmentsParser(attachmentParsers); String id = "some-id"; XContentBuilder builder = jsonBuilder().startObject() .startObject(id) .startObject(DataAttachmentParser.TYPE) .field("format", randomFrom("yaml", "json")) .endObject() .endObject() .endObject(); XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); logger.info("JSON: {}", Strings.toString(builder)); EmailAttachments emailAttachments = emailAttachmentsParser.parse(parser); assertThat(emailAttachments.getAttachments(), hasSize(1)); XContentBuilder toXcontentBuilder = jsonBuilder().startObject(); List<EmailAttachmentParser.EmailAttachment> attachments = new ArrayList<>(emailAttachments.getAttachments()); attachments.get(0).toXContent(toXcontentBuilder, ToXContent.EMPTY_PARAMS); toXcontentBuilder.endObject(); assertThat(Strings.toString(toXcontentBuilder), is(Strings.toString(builder))); } }
DataAttachmentParserTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/client/RestTestClientTests.java
{ "start": 2122, "end": 3890 }
class ____ { @ParameterizedTest @ValueSource(strings = {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"}) void testMethod(String method) { RestTestClientTests.this.client.method(HttpMethod.valueOf(method)).uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo(method); } @Test void testGet() { RestTestClientTests.this.client.get().uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo("GET"); } @Test void testPost() { RestTestClientTests.this.client.post().uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo("POST"); } @Test void testPut() { RestTestClientTests.this.client.put().uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo("PUT"); } @Test void testDelete() { RestTestClientTests.this.client.delete().uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo("DELETE"); } @Test void testPatch() { RestTestClientTests.this.client.patch().uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo("PATCH"); } @Test void testHead() { RestTestClientTests.this.client.head().uri("/test") .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.method").isEqualTo("HEAD"); } @Test void testOptions() { RestTestClientTests.this.client.options().uri("/test") .exchange() .expectStatus().isOk() .expectHeader().valueEquals("Allow", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS") .expectBody().isEmpty(); } } @Nested
HttpMethods
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestSequenceFileAsTextInputFormat.java
{ "start": 1362, "end": 3537 }
class ____ { private static final Logger LOG = FileInputFormat.LOG; private static int MAX_LENGTH = 10000; private static Configuration conf = new Configuration(); @Test public void testFormat() throws Exception { JobConf job = new JobConf(conf); FileSystem fs = FileSystem.getLocal(conf); Path dir = new Path(System.getProperty("test.build.data",".") + "/mapred"); Path file = new Path(dir, "test.seq"); Reporter reporter = Reporter.NULL; int seed = new Random().nextInt(); //LOG.info("seed = "+seed); Random random = new Random(seed); fs.delete(dir, true); FileInputFormat.setInputPaths(job, dir); // for a variety of lengths for (int length = 0; length < MAX_LENGTH; length+= random.nextInt(MAX_LENGTH/10)+1) { //LOG.info("creating; entries = " + length); // create a file with length entries SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, file, IntWritable.class, LongWritable.class); try { for (int i = 0; i < length; i++) { IntWritable key = new IntWritable(i); LongWritable value = new LongWritable(10 * i); writer.append(key, value); } } finally { writer.close(); } // try splitting the file in a variety of sizes InputFormat<Text, Text> format = new SequenceFileAsTextInputFormat(); for (int i = 0; i < 3; i++) { int numSplits = random.nextInt(MAX_LENGTH/(SequenceFile.SYNC_INTERVAL/20))+1; //LOG.info("splitting: requesting = " + numSplits); InputSplit[] splits = format.getSplits(job, numSplits); //LOG.info("splitting: got = " + splits.length); // check each split BitSet bits = new BitSet(length); for (int j = 0; j < splits.length; j++) { RecordReader<Text, Text> reader = format.getRecordReader(splits[j], job, reporter); Class readerClass = reader.getClass(); assertEquals(SequenceFileAsTextRecordReader.class, readerClass, "reader
TestSequenceFileAsTextInputFormat
java
google__guava
android/guava-tests/test/com/google/common/reflect/TypesTest.java
{ "start": 7610, "end": 10396 }
class ____ { @SuppressWarnings("unused") void withoutBound(List<?> list) {} @SuppressWarnings("unused") void withObjectBound(List<? extends Object> list) {} @SuppressWarnings("unused") void withUpperBound(List<? extends int[][]> list) {} @SuppressWarnings("unused") void withLowerBound(List<? super String[][]> list) {} static WildcardType getWildcardType(String methodName) throws Exception { ParameterizedType parameterType = (ParameterizedType) WithWildcardType.class.getDeclaredMethod(methodName, List.class) .getGenericParameterTypes()[0]; return (WildcardType) parameterType.getActualTypeArguments()[0]; } } public void testNewWildcardType() throws Exception { WildcardType noBoundJvmType = WithWildcardType.getWildcardType("withoutBound"); WildcardType objectBoundJvmType = WithWildcardType.getWildcardType("withObjectBound"); WildcardType upperBoundJvmType = WithWildcardType.getWildcardType("withUpperBound"); WildcardType lowerBoundJvmType = WithWildcardType.getWildcardType("withLowerBound"); WildcardType objectBound = Types.subtypeOf(Object.class); WildcardType upperBound = Types.subtypeOf(int[][].class); WildcardType lowerBound = Types.supertypeOf(String[][].class); assertEqualWildcardType(noBoundJvmType, objectBound); assertEqualWildcardType(objectBoundJvmType, objectBound); assertEqualWildcardType(upperBoundJvmType, upperBound); assertEqualWildcardType(lowerBoundJvmType, lowerBound); new EqualsTester() .addEqualityGroup(noBoundJvmType, objectBoundJvmType, objectBound) .addEqualityGroup(upperBoundJvmType, upperBound) .addEqualityGroup(lowerBoundJvmType, lowerBound) .testEquals(); } public void testNewWildcardType_primitiveTypeBound() { assertThrows(IllegalArgumentException.class, () -> Types.subtypeOf(int.class)); } public void testNewWildcardType_serializable() { SerializableTester.reserializeAndAssert(Types.supertypeOf(String.class)); SerializableTester.reserializeAndAssert(Types.subtypeOf(String.class)); SerializableTester.reserializeAndAssert(Types.subtypeOf(Object.class)); } private static void assertEqualWildcardType(WildcardType expected, WildcardType actual) { assertEquals(expected.toString(), actual.toString()); assertEquals(actual.toString(), expected.hashCode(), actual.hashCode()); assertThat(actual.getLowerBounds()) .asList() .containsExactlyElementsIn(asList(expected.getLowerBounds())) .inOrder(); assertThat(actual.getUpperBounds()) .asList() .containsExactlyElementsIn(asList(expected.getUpperBounds())) .inOrder(); } private static
WithWildcardType
java
apache__camel
components/camel-cxf/camel-cxf-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerStreamCacheTest.java
{ "start": 2486, "end": 4571 }
class ____ { @POST @Path("/echo") @Consumes(MediaType.WILDCARD) @Produces(MediaType.TEXT_PLAIN) public String echo(String body) { return body; } } @Override protected RouteBuilder createRouteBuilder() { final String cxfrsUri = "cxfrs://http://localhost:" + port + "/rs" + "?httpClientAPI=true" + "&throwExceptionOnFailure=false"; return new RouteBuilder() { @Override public void configure() { // Ensure stream caching is ON for the context getContext().setStreamCaching(true); getContext().getStreamCachingStrategy().setSpoolEnabled(true); getContext().getStreamCachingStrategy().setSpoolThreshold(1024 * 1024 * 10); // 10MB from("direct:start") .setHeader(Exchange.HTTP_METHOD, constant("POST")) .setHeader(Exchange.HTTP_PATH, constant("/echo")) .setExchangePattern(ExchangePattern.InOut) // 1) Call the REST endpoint via cxfrs PRODUCER .to(cxfrsUri) // 2) read response after cxfrs call multiple times .process(e -> { String body = e.getIn().getBody(String.class); }) .log("The body is ===> ${body}"); } }; } @Test public void testProducerStreamCacheWithCxfrs() throws InterruptedException { final String payload = "hello-cxfrs-producer-stream-cache"; InputStream body = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8)); ProducerTemplate tpl = template; String response = tpl.requestBody("direct:start", body, String.class); assertEquals(payload, response, "Echo response must match original payload"); getMockEndpoint("mock:result").expectedMessageCount(1); } }
EchoResource
java
spring-projects__spring-framework
spring-expression/src/main/java/org/springframework/expression/TypedValue.java
{ "start": 1119, "end": 2994 }
class ____ { /** * {@link TypedValue} for {@code null}. */ public static final TypedValue NULL = new TypedValue(null); private final @Nullable Object value; private @Nullable TypeDescriptor typeDescriptor; /** * Create a {@link TypedValue} for a simple object. The {@link TypeDescriptor} * is inferred from the object, so no generic declarations are preserved. * @param value the object value */ public TypedValue(@Nullable Object value) { this.value = value; this.typeDescriptor = null; // initialized when/if requested } /** * Create a {@link TypedValue} for a particular value with a particular * {@link TypeDescriptor} which may contain additional generic declarations. * @param value the object value * @param typeDescriptor a type descriptor describing the type of the value */ public TypedValue(@Nullable Object value, @Nullable TypeDescriptor typeDescriptor) { this.value = value; this.typeDescriptor = typeDescriptor; } public @Nullable Object getValue() { return this.value; } public @Nullable TypeDescriptor getTypeDescriptor() { if (this.typeDescriptor == null && this.value != null) { this.typeDescriptor = TypeDescriptor.forObject(this.value); } return this.typeDescriptor; } @Override public boolean equals(@Nullable Object other) { // Avoid TypeDescriptor initialization if not necessary return (this == other || (other instanceof TypedValue that && ObjectUtils.nullSafeEquals(this.value, that.value) && ((this.typeDescriptor == null && that.typeDescriptor == null) || ObjectUtils.nullSafeEquals(getTypeDescriptor(), that.getTypeDescriptor())))); } @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(this.value); } @Override public String toString() { return "TypedValue: '" + this.value + "' of [" + getTypeDescriptor() + "]"; } }
TypedValue
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/reader/filter/TimelinePrefixFilter.java
{ "start": 1165, "end": 2823 }
class ____ extends TimelineFilter { private TimelineCompareOp compareOp; private String prefix; public TimelinePrefixFilter() { } public TimelinePrefixFilter(TimelineCompareOp op, String prefix) { this.prefix = prefix; if (op != TimelineCompareOp.EQUAL && op != TimelineCompareOp.NOT_EQUAL) { throw new IllegalArgumentException("CompareOp for prefix filter should " + "be EQUAL or NOT_EQUAL"); } this.compareOp = op; } @Override public TimelineFilterType getFilterType() { return TimelineFilterType.PREFIX; } public String getPrefix() { return prefix; } public TimelineCompareOp getCompareOp() { return compareOp; } @Override public String toString() { return String.format("%s (%s %s)", this.getClass().getSimpleName(), this.compareOp.name(), this.prefix); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((compareOp == null) ? 0 : compareOp.hashCode()); result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimelinePrefixFilter other = (TimelinePrefixFilter) obj; if (compareOp != other.compareOp) { return false; } if (prefix == null) { if (other.prefix != null) { return false; } } else if (!prefix.equals(other.prefix)){ return false; } return true; } }
TimelinePrefixFilter
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/SplitterShareUnitOfWorkCompletionAwareTest.java
{ "start": 1841, "end": 2409 }
class ____ implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } String body = oldExchange.getIn().getBody() + "+" + newExchange.getIn().getBody(); oldExchange.getIn().setBody(body); return oldExchange; } @Override public void onCompletion(Exchange exchange) { exchange.getIn().setHeader("foo", "bar"); } } }
MyStrategy
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/LastUpdateListener.java
{ "start": 274, "end": 450 }
class ____ { @PreUpdate @PrePersist public void setLastUpdate(Cat o) { o.setLastUpdate( new Date() ); o.setManualVersion( o.getManualVersion() + 1 ); } }
LastUpdateListener
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringRouteStartupOrderTest.java
{ "start": 1042, "end": 1308 }
class ____ extends RouteStartupOrderTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/RouteStartupOrderTest.xml"); } }
SpringRouteStartupOrderTest
java
google__guava
android/guava/src/com/google/common/math/LongMath.java
{ "start": 36445, "end": 47907 }
enum ____ { /** Works for inputs ≤ FLOOR_SQRT_MAX_LONG. */ SMALL { @Override long mulMod(long a, long b, long m) { /* * lowasser, 2015-Feb-12: Benchmarks suggest that changing this to UnsignedLongs.remainder * and increasing the threshold to 2^32 doesn't pay for itself, and adding another enum * constant hurts performance further -- I suspect because bimorphic implementation is a * sweet spot for the JVM. */ return (a * b) % m; } @Override long squareMod(long a, long m) { return (a * a) % m; } }, /** Works for all nonnegative signed longs. */ LARGE { /** Returns (a + b) mod m. Precondition: {@code 0 <= a}, {@code b < m < 2^63}. */ private long plusMod(long a, long b, long m) { return (a >= m - b) ? (a + b - m) : (a + b); } /** Returns (a * 2^32) mod m. a may be any unsigned long. */ private long times2ToThe32Mod(long a, long m) { int remainingPowersOf2 = 32; do { int shift = min(remainingPowersOf2, Long.numberOfLeadingZeros(a)); // shift is either the number of powers of 2 left to multiply a by, or the biggest shift // possible while keeping a in an unsigned long. a = UnsignedLongs.remainder(a << shift, m); remainingPowersOf2 -= shift; } while (remainingPowersOf2 > 0); return a; } @Override long mulMod(long a, long b, long m) { long aHi = a >>> 32; // < 2^31 long bHi = b >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 long bLo = b & 0xFFFFFFFFL; // < 2^32 /* * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo. * == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo * * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63 result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64 if (result < 0) { result = UnsignedLongs.remainder(result, m); } // result < 2^63 again result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod(result, UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m), m); } @Override long squareMod(long a, long m) { long aHi = a >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 /* * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2 * == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2 * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63 long hiLo = aHi * aLo * 2; if (hiLo < 0) { hiLo = UnsignedLongs.remainder(hiLo, m); } // hiLo < 2^63 result += hiLo; // result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod(result, UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m), m); } }; static boolean test(long base, long n) { // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG, // so long as n <= FLOOR_SQRT_MAX_LONG. return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n); } /** Returns a * b mod m. */ abstract long mulMod(long a, long b, long m); /** Returns a^2 mod m. */ abstract long squareMod(long a, long m); /** Returns a^p mod m. */ private long powMod(long a, long p, long m) { long res = 1; for (; p != 0; p >>= 1) { if ((p & 1) != 0) { res = mulMod(res, a, m); } a = squareMod(a, m); } return res; } /** Returns true if n is a strong probable prime relative to the specified base. */ private boolean testWitness(long base, long n) { int r = Long.numberOfTrailingZeros(n - 1); long d = (n - 1) >> r; base %= n; if (base == 0) { return true; } // Calculate a := base^d mod n. long a = powMod(base, d, n); // n passes this test if // base^d = 1 (mod n) // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r. if (a == 1) { return true; } int j = 0; while (a != n - 1) { if (++j == r) { return false; } a = squareMod(a, n); } return true; } } /** * Returns {@code x}, rounded to a {@code double} with the specified rounding mode. If {@code x} * is precisely representable as a {@code double}, its {@code double} value will be returned; * otherwise, the rounding will choose between the two nearest representable values with {@code * mode}. * * <p>For the case of {@link RoundingMode#HALF_EVEN}, this implementation uses the IEEE 754 * default rounding mode: if the two nearest representable values are equally near, the one with * the least significant bit zero is chosen. (In such cases, both of the nearest representable * values are even integers; this method returns the one that is a multiple of a greater power of * two.) * * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not precisely representable as a {@code double} * @since 30.0 */ @GwtIncompatible public static double roundToDouble(long x, RoundingMode mode) { // Logic adapted from ToDoubleRounder. double roundArbitrarily = (double) x; long roundArbitrarilyAsLong = (long) roundArbitrarily; int cmpXToRoundArbitrarily; if (roundArbitrarilyAsLong == Long.MAX_VALUE) { /* * For most values, the conversion from roundArbitrarily to roundArbitrarilyAsLong is * lossless. In that case we can compare x to roundArbitrarily using Long.compare(x, * roundArbitrarilyAsLong). The exception is for values where the conversion to double rounds * up to give roundArbitrarily equal to 2^63, so the conversion back to long overflows and * roundArbitrarilyAsLong is Long.MAX_VALUE. (This is the only way this condition can occur as * otherwise the conversion back to long pads with zero bits.) In this case we know that * roundArbitrarily > x. (This is important when x == Long.MAX_VALUE == * roundArbitrarilyAsLong.) */ cmpXToRoundArbitrarily = -1; } else { cmpXToRoundArbitrarily = Long.compare(x, roundArbitrarilyAsLong); } switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(cmpXToRoundArbitrarily == 0); return roundArbitrarily; case FLOOR: return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); case CEILING: return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); case DOWN: if (x >= 0) { return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); } else { return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); } case UP: if (x >= 0) { return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); } else { return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); } case HALF_DOWN: case HALF_UP: case HALF_EVEN: { long roundFloor; double roundFloorAsDouble; long roundCeiling; double roundCeilingAsDouble; if (cmpXToRoundArbitrarily >= 0) { roundFloorAsDouble = roundArbitrarily; roundFloor = roundArbitrarilyAsLong; roundCeilingAsDouble = Math.nextUp(roundArbitrarily); roundCeiling = (long) Math.ceil(roundCeilingAsDouble); } else { roundCeilingAsDouble = roundArbitrarily; roundCeiling = roundArbitrarilyAsLong; roundFloorAsDouble = DoubleUtils.nextDown(roundArbitrarily); roundFloor = (long) Math.floor(roundFloorAsDouble); } long deltaToFloor = x - roundFloor; long deltaToCeiling = roundCeiling - x; if (roundCeiling == Long.MAX_VALUE) { // correct for Long.MAX_VALUE as discussed above: roundCeilingAsDouble must be 2^63, but // roundCeiling is 2^63-1. deltaToCeiling++; } int diff = Long.compare(deltaToFloor, deltaToCeiling); if (diff < 0) { // closer to floor return roundFloorAsDouble; } else if (diff > 0) { // closer to ceiling return roundCeilingAsDouble; } // halfway between the representable values; do the half-whatever logic switch (mode) { case HALF_EVEN: return ((DoubleUtils.getSignificand(roundFloorAsDouble) & 1L) == 0) ? roundFloorAsDouble : roundCeilingAsDouble; case HALF_DOWN: return (x >= 0) ? roundFloorAsDouble : roundCeilingAsDouble; case HALF_UP: return (x >= 0) ? roundCeilingAsDouble : roundFloorAsDouble; default: throw new AssertionError("impossible"); } } } throw new AssertionError("impossible"); } /** * Returns the closest representable {@code long} to the absolute value of {@code x}. * * <p>This is the same thing as the true absolute value of {@code x} except in the case when * {@code x} is {@link Long#MIN_VALUE}, in which case this returns {@link Long#MAX_VALUE}. (Note * that {@code Long.MAX_VALUE} is mathematically equal to {@code -Long.MIN_VALUE - 1}.) * * <p>There are three common APIs for determining the absolute value of a long, all of which * behave identically except when passed {@code Long.MIN_VALUE}. Those methods are: * * <ul> * <li>{@link Math#abs(long)}, which returns {@code Long.MIN_VALUE} when passed {@code * Long.MIN_VALUE} * <li>{@link Math#absExact(long)}, which throws {@link ArithmeticException} when passed {@code * Long.MIN_VALUE} * <li>this method, {@code LongMath.saturatedAbs(long)}, which returns {@code Long.MAX_VALUE} * when passed {@code Long.MIN_VALUE} * </ul> * * <p>Note that if your only goal is to turn a well-distributed {@code long} (such as a random * number) into a well-distributed nonnegative number, the most even distribution is achieved not * by this method or other absolute value methods, but by {@code x & Long.MAX_VALUE}. * * @since 33.5.0 */ public static long saturatedAbs(long x) { return (x == Long.MIN_VALUE) ? Long.MAX_VALUE : Math.abs(x); } private LongMath() {} }
MillerRabinTester
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationPreparedEvent.java
{ "start": 1225, "end": 1935 }
class ____ extends SpringApplicationEvent { private final ConfigurableApplicationContext context; /** * Create a new {@link ApplicationPreparedEvent} instance. * @param application the current application * @param args the arguments the application is running with * @param context the ApplicationContext about to be refreshed */ public ApplicationPreparedEvent(SpringApplication application, String[] args, ConfigurableApplicationContext context) { super(application, args); this.context = context; } /** * Return the application context. * @return the context */ public ConfigurableApplicationContext getApplicationContext() { return this.context; } }
ApplicationPreparedEvent
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/GetDestinationResponse.java
{ "start": 1270, "end": 1981 }
class ____ { public static GetDestinationResponse newInstance() throws IOException { return StateStoreSerializer .newRecord(GetDestinationResponse.class); } public static GetDestinationResponse newInstance( Collection<String> nsIds) throws IOException { GetDestinationResponse request = newInstance(); request.setDestinations(nsIds); return request; } @Public @Unstable public abstract Collection<String> getDestinations(); @Public @Unstable public void setDestination(String nsId) { setDestinations(Collections.singletonList(nsId)); } @Public @Unstable public abstract void setDestinations(Collection<String> nsIds); }
GetDestinationResponse
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/LongPollingService.java
{ "start": 13337, "end": 13611 }
class ____ implements Runnable { @Override public void run() { MEMORY_LOG.info("[long-pulling] client count " + allSubs.size()); MetricsMonitor.getLongPollingMonitor().set(allSubs.size()); } } public
StatTask
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/spi/NOPLogger.java
{ "start": 1165, "end": 6007 }
class ____ extends Logger { /** * Create instance of Logger. * * @param repo repository, may not be null. * @param name name, may not be null, use "root" for root logger. */ public NOPLogger(final NOPLoggerRepository repo, final String name) { super(name); this.repository = repo; this.level = Level.OFF; this.parent = this; } /** {@inheritDoc} */ @Override public void addAppender(final Appender newAppender) { // NOP } /** {@inheritDoc} */ @Override public void assertLog(final boolean assertion, final String msg) { // NOP } /** {@inheritDoc} */ @Override public void callAppenders(final LoggingEvent event) { // NOP } void closeNestedAppenders() { // NOP } /** {@inheritDoc} */ @Override public void debug(final Object message) { // NOP } /** {@inheritDoc} */ @Override public void debug(final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void error(final Object message) { // NOP } /** {@inheritDoc} */ @Override public void error(final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void fatal(final Object message) { // NOP } /** {@inheritDoc} */ @Override public void fatal(final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public Enumeration getAllAppenders() { return new Vector<>().elements(); } /** {@inheritDoc} */ @Override public Appender getAppender(final String name) { return null; } /** {@inheritDoc} */ @Override public Priority getChainedPriority() { return getEffectiveLevel(); } /** {@inheritDoc} */ @Override public Level getEffectiveLevel() { return Level.OFF; } /** {@inheritDoc} */ @Override public ResourceBundle getResourceBundle() { return null; } /** {@inheritDoc} */ @Override public void info(final Object message) { // NOP } /** {@inheritDoc} */ @Override public void info(final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public boolean isAttached(final Appender appender) { return false; } /** {@inheritDoc} */ @Override public boolean isDebugEnabled() { return false; } /** {@inheritDoc} */ @Override public boolean isEnabledFor(final Priority level) { return false; } /** {@inheritDoc} */ @Override public boolean isInfoEnabled() { return false; } /** {@inheritDoc} */ @Override public boolean isTraceEnabled() { return false; } /** {@inheritDoc} */ @Override public void l7dlog(final Priority priority, final String key, final Object[] params, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void l7dlog(final Priority priority, final String key, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void log(final Priority priority, final Object message) { // NOP } /** {@inheritDoc} */ @Override public void log(final Priority priority, final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void log(final String callerFQCN, final Priority level, final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void removeAllAppenders() { // NOP } /** {@inheritDoc} */ @Override public void removeAppender(final Appender appender) { // NOP } /** {@inheritDoc} */ @Override public void removeAppender(final String name) { // NOP } /** {@inheritDoc} */ @Override public void setLevel(final Level level) { // NOP } /** {@inheritDoc} */ @Override public void setPriority(final Priority priority) { // NOP } /** {@inheritDoc} */ @Override public void setResourceBundle(final ResourceBundle bundle) { // NOP } /** {@inheritDoc} */ @Override public void trace(final Object message) { // NOP } /** {@inheritDoc} */ @Override public void trace(final Object message, final Throwable t) { // NOP } /** {@inheritDoc} */ @Override public void warn(final Object message) { // NOP } /** {@inheritDoc} */ @Override public void warn(final Object message, final Throwable t) { // NOP } }
NOPLogger
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java
{ "start": 3663, "end": 6654 }
class ____ { int thisAsClassCounter; int thisAsInterfaceCounter; int targetAsClassCounter; int targetAsInterfaceCounter; int thisAsClassAndTargetAsClassCounter; int thisAsInterfaceAndTargetAsInterfaceCounter; int thisAsInterfaceAndTargetAsClassCounter; int atTargetClassAnnotationCounter; int atAnnotationMethodAnnotationCounter; public void reset() { thisAsClassCounter = 0; thisAsInterfaceCounter = 0; targetAsClassCounter = 0; targetAsInterfaceCounter = 0; thisAsClassAndTargetAsClassCounter = 0; thisAsInterfaceAndTargetAsInterfaceCounter = 0; thisAsInterfaceAndTargetAsClassCounter = 0; atTargetClassAnnotationCounter = 0; atAnnotationMethodAnnotationCounter = 0; } @Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)") public void incrementThisAsClassCounter() { thisAsClassCounter++; } @Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface)") public void incrementThisAsInterfaceCounter() { thisAsInterfaceCounter++; } @Before("target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)") public void incrementTargetAsClassCounter() { targetAsClassCounter++; } @Before("target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface)") public void incrementTargetAsInterfaceCounter() { targetAsInterfaceCounter++; } @Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl) " + "&& target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)") public void incrementThisAsClassAndTargetAsClassCounter() { thisAsClassAndTargetAsClassCounter++; } @Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface) " + "&& target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface)") public void incrementThisAsInterfaceAndTargetAsInterfaceCounter() { thisAsInterfaceAndTargetAsInterfaceCounter++; } @Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface) " + "&& target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)") public void incrementThisAsInterfaceAndTargetAsClassCounter() { thisAsInterfaceAndTargetAsClassCounter++; } @Before("@target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestAnnotation)") public void incrementAtTargetClassAnnotationCounter() { atTargetClassAnnotationCounter++; } @Before("@annotation(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestAnnotation)") public void incrementAtAnnotationMethodAnnotationCounter() { atAnnotationMethodAnnotationCounter++; } } }
Counter
java
junit-team__junit5
platform-tooling-support-tests/src/test/java/platform/tooling/support/tests/MavenSurefireCompatibilityTests.java
{ "start": 993, "end": 2269 }
class ____ { static final String MINIMUM_SUPPORTED_SUREFIRE_VERSION = "3.0.0"; @ManagedResource LocalMavenRepo localMavenRepo; @Test void testMavenSurefireCompatibilityProject(@TempDir Path workspace, @FilePrefix("maven") OutputFiles outputFiles) throws Exception { var result = ProcessStarters.maven(Helper.getJavaHome(17).orElseThrow(TestAbortedException::new)) // .workingDir(copyToWorkspace(Projects.MAVEN_SUREFIRE_COMPATIBILITY, workspace)) // .addArguments(localMavenRepo.toCliArgument(), "-Dmaven.repo=" + MavenRepo.dir()) // .addArguments("-Dsurefire.version=" + MINIMUM_SUPPORTED_SUREFIRE_VERSION) // .addArguments("--update-snapshots", "--batch-mode", "test") // .redirectOutput(outputFiles) // .startAndWait(); assertEquals(0, result.exitCode()); assertEquals("", result.stdErr()); var output = result.stdOutLines(); assertTrue(output.contains("[INFO] BUILD SUCCESS")); assertTrue(output.contains("[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0")); var targetDir = workspace.resolve("target"); try (var stream = Files.list(targetDir)) { assertThat(stream.filter(file -> file.getFileName().toString().startsWith("junit-platform-unique-ids"))) // .hasSize(1); } } }
MavenSurefireCompatibilityTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/AsynchronousFileIOChannel.java
{ "start": 17569, "end": 18179 }
class ____ implements ReadRequest, WriteRequest { private final AsynchronousFileIOChannel<?, ?> channel; private final long position; protected SeekRequest(AsynchronousFileIOChannel<?, ?> channel, long position) { this.channel = channel; this.position = position; } @Override public void requestDone(IOException ioex) {} @Override public void read() throws IOException { this.channel.fileChannel.position(position); } @Override public void write() throws IOException { this.channel.fileChannel.position(position); } }
SeekRequest
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/saml/RestSamlAuthenticateAction.java
{ "start": 1599, "end": 1800 }
class ____ extends SamlBaseRestHandler implements RestRequestFilter { private static final Logger logger = LogManager.getLogger(RestSamlAuthenticateAction.class); static
RestSamlAuthenticateAction
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/resource/gif/GifOptions.java
{ "start": 274, "end": 1138 }
class ____ { /** * Indicates the {@link com.bumptech.glide.load.DecodeFormat} that will be used in conjunction * with the particular GIF to determine the {@link android.graphics.Bitmap.Config} to use when * decoding frames of GIFs. */ public static final Option<DecodeFormat> DECODE_FORMAT = Option.memory( "com.bumptech.glide.load.resource.gif.GifOptions.DecodeFormat", DecodeFormat.DEFAULT); /** * If set to {@code true}, disables the GIF {@link com.bumptech.glide.load.ResourceDecoder}s * ({@link ResourceDecoder#handles(Object, Options)} will return {@code false}). Defaults to * {@code false}. */ public static final Option<Boolean> DISABLE_ANIMATION = Option.memory("com.bumptech.glide.load.resource.gif.GifOptions.DisableAnimation", false); private GifOptions() { // Utility class. } }
GifOptions
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java
{ "start": 5122, "end": 5311 }
class ____ { public static void main(String... args) { someOtherMethod(); } private static void someOtherMethod() { mainMethod.set(new MainMethod()); } } public static
Valid
java
apache__camel
components/camel-docker/src/test/java/org/apache/camel/component/docker/consumer/DockerEventsConsumerTest.java
{ "start": 1673, "end": 3199 }
class ____ extends CamelTestSupport { private String host = "localhost"; private Integer port = 2375; private DockerConfiguration dockerConfiguration; @Mock private EventsCmd eventsCmd; @Mock private DockerClient dockerClient; public void setupMocks() { Mockito.when(dockerClient.eventsCmd()).thenReturn(eventsCmd); Mockito.when(eventsCmd.withSince(anyString())).thenReturn(eventsCmd); } @Test void testEvent() { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("docker://events?host=" + host + "&port=" + port).log("${body}").to("mock:result"); } }; } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); dockerConfiguration = new DockerConfiguration(); dockerConfiguration.setParameters(DockerTestUtils.getDefaultParameters(host, port, dockerConfiguration)); DockerComponent dockerComponent = new DockerComponent(dockerConfiguration); dockerComponent.setClient(DockerTestUtils.getClientProfile(host, port, dockerConfiguration), dockerClient); camelContext.addComponent("docker", dockerComponent); setupMocks(); return camelContext; } }
DockerEventsConsumerTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/types/Key.java
{ "start": 1730, "end": 2271 }
interface ____<T> extends Value, Comparable<T> { /** * All keys must override the hash-code function to generate proper deterministic hash codes, * based on their contents. * * @return The hash code of the key */ public int hashCode(); /** * Compares the object on equality with another object. * * @param other The other object to compare against. * @return True, iff this object is identical to the other object, false otherwise. */ public boolean equals(Object other); }
Key
java
apache__flink
flink-datastream-api/src/main/java/org/apache/flink/datastream/api/common/Collector.java
{ "start": 997, "end": 1412 }
interface ____<OUT> { /** * Collect record to output stream. * * @param record to be collected. */ void collect(OUT record); /** * Overwrite the timestamp of this record and collect it to output stream. * * @param record to be collected. * @param timestamp of the processed data. */ void collectAndOverwriteTimestamp(OUT record, long timestamp); }
Collector
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/ingest/SamplingService.java
{ "start": 56377, "end": 57089 }
class ____ extends AckedBatchedClusterStateUpdateTask { private final ProjectId projectId; private final String indexName; private final SamplingConfiguration samplingConfiguration; UpdateSamplingConfigurationTask( ProjectId projectId, String indexName, SamplingConfiguration samplingConfiguration, TimeValue ackTimeout, ActionListener<AcknowledgedResponse> listener ) { super(ackTimeout, listener); this.projectId = projectId; this.indexName = indexName; this.samplingConfiguration = samplingConfiguration; } } static
UpdateSamplingConfigurationTask
java
quarkusio__quarkus
extensions/devservices/oracle/src/main/java/io/quarkus/devservices/oracle/deployment/OracleDevServicesProcessor.java
{ "start": 1685, "end": 7040 }
class ____ { private static final Logger LOG = Logger.getLogger(OracleDevServicesProcessor.class); /** * This is the container name as defined by the Testcontainer's OracleContainer: * does not necessarily match the container name that Quarkus will default to use. */ public static final String ORIGINAL_IMAGE_NAME = "gvenzl/oracle-xe"; public static final int PORT = 1521; private static final OracleDatasourceServiceConfigurator configurator = new OracleDatasourceServiceConfigurator(); @BuildStep DevServicesDatasourceProviderBuildItem setupOracle( List<DevServicesSharedNetworkBuildItem> devServicesSharedNetworkBuildItem, DevServicesComposeProjectBuildItem composeProjectBuildItem, DevServicesConfig devServicesConfig) { return new DevServicesDatasourceProviderBuildItem(DatabaseKind.ORACLE, new DevServicesDatasourceProvider() { @Override public RunningDevServicesDatasource startDatabase(Optional<String> username, Optional<String> password, String datasourceName, DevServicesDatasourceContainerConfig containerConfig, LaunchMode launchMode, Optional<Duration> startupTimeout) { boolean useSharedNetwork = DevServicesSharedNetworkBuildItem.isSharedNetworkRequired(devServicesConfig, devServicesSharedNetworkBuildItem); String effectiveUsername = containerConfig.getUsername().orElse(username.orElse(DEFAULT_DATABASE_USERNAME)); String effectivePassword = containerConfig.getPassword().orElse(password.orElse(DEFAULT_DATABASE_PASSWORD)); String effectiveDbName = containerConfig.getDbName().orElse( DataSourceUtil.isDefault(datasourceName) ? DEFAULT_DATABASE_NAME : datasourceName); Supplier<RunningDevServicesDatasource> startService = () -> { QuarkusOracleServerContainer container = new QuarkusOracleServerContainer(containerConfig.getImageName(), containerConfig.getFixedExposedPort(), composeProjectBuildItem.getDefaultNetworkId(), useSharedNetwork); startupTimeout.ifPresent(container::withStartupTimeout); container.withUsername(effectiveUsername) .withPassword(effectivePassword) .withDatabaseName(effectiveDbName) .withReuse(containerConfig.isReuse()); Labels.addDataSourceLabel(container, datasourceName); Volumes.addVolumes(container, containerConfig.getVolumes()); container.withEnv(containerConfig.getContainerEnv()); // We need to limit the maximum amount of CPUs being used by the container; // otherwise the hardcoded memory configuration of the DB might not be enough to successfully boot it. // See https://github.com/gvenzl/oci-oracle-xe/issues/64 // I choose to limit it to "2 cpus": should be more than enough for any local testing needs, // and keeps things simple. container.withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withNanoCPUs(2_000_000_000l)); containerConfig.getAdditionalJdbcUrlProperties().forEach(container::withUrlParam); containerConfig.getCommand().ifPresent(container::setCommand); containerConfig.getInitScriptPath().ifPresent(container::withInitScripts); if (containerConfig.getInitPrivilegedScriptPath().isPresent()) { for (String initScript : containerConfig.getInitPrivilegedScriptPath().get()) { container.withCopyFileToContainer(MountableFile.forClasspathResource(initScript), "/container-entrypoint-startdb.d/" + initScript); } } if (containerConfig.isShowLogs()) { container.withLogConsumer(new JBossLoggingConsumer(LOG)); } container.start(); LOG.info("Dev Services for Oracle started."); return new RunningDevServicesDatasource(container.getContainerId(), container.getEffectiveJdbcUrl(), container.getReactiveUrl(), container.getUsername(), container.getPassword(), new ContainerShutdownCloseable(container, "Oracle")); }; List<String> images = List.of( containerConfig.getImageName().orElseGet(() -> ConfigureUtil.getDefaultImageNameFor("oracle")), "oracle"); return ComposeLocator.locateContainer(composeProjectBuildItem, images, PORT, launchMode, useSharedNetwork) .map(containerAddress -> configurator.composeRunningService(containerAddress, containerConfig)) .orElseGet(startService); } }); } private static
OracleDevServicesProcessor
java
redisson__redisson
redisson/src/main/java/org/redisson/cache/LocalCachedMapDisableAck.java
{ "start": 746, "end": 857 }
class ____ implements Serializable { public LocalCachedMapDisableAck() { } }
LocalCachedMapDisableAck
java
spring-projects__spring-framework
spring-r2dbc/src/main/java/org/springframework/r2dbc/core/binding/BindMarkersFactoryResolver.java
{ "start": 3459, "end": 4028 }
class ____ extends NonTransientDataAccessException { /** * Constructor for NoBindMarkersFactoryException. * @param msg the detail message */ public NoBindMarkersFactoryException(String msg) { super(msg); } } /** * Built-in bind marker factories. * * <p>Typically used as the last {@link BindMarkerFactoryProvider} when other * providers are registered with a higher precedence. * * @see org.springframework.core.Ordered * @see org.springframework.core.annotation.AnnotationAwareOrderComparator */ static
NoBindMarkersFactoryException
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryStringBuilderTest.java
{ "start": 5180, "end": 5454 }
class ____ { void f() { var sb = new StringBuilder().append("hello"); System.err.println(sb); } } """) .addOutputLines( "Test.java", """ abstract
Test
java
apache__flink
flink-formats/flink-json/src/main/java/org/apache/flink/formats/json/ogg/OggJsonFormatFactory.java
{ "start": 2759, "end": 6463 }
class ____ implements DeserializationFormatFactory, SerializationFormatFactory { public static final String IDENTIFIER = "ogg-json"; /** Validator for ogg decoding format. */ private static void validateDecodingFormatOptions(ReadableConfig tableOptions) { JsonFormatOptionsUtil.validateDecodingFormatOptions(tableOptions); } /** Validator for ogg encoding format. */ private static void validateEncodingFormatOptions(ReadableConfig tableOptions) { JsonFormatOptionsUtil.validateEncodingFormatOptions(tableOptions); } @Override public DecodingFormat<DeserializationSchema<RowData>> createDecodingFormat( DynamicTableFactory.Context context, ReadableConfig formatOptions) { FactoryUtil.validateFactoryOptions(this, formatOptions); validateDecodingFormatOptions(formatOptions); final boolean ignoreParseErrors = formatOptions.get(IGNORE_PARSE_ERRORS); final TimestampFormat timestampFormat = JsonFormatOptionsUtil.getTimestampFormat(formatOptions); return new OggJsonDecodingFormat(ignoreParseErrors, timestampFormat); } @Override public EncodingFormat<SerializationSchema<RowData>> createEncodingFormat( DynamicTableFactory.Context context, ReadableConfig formatOptions) { FactoryUtil.validateFactoryOptions(this, formatOptions); validateEncodingFormatOptions(formatOptions); TimestampFormat timestampFormat = JsonFormatOptionsUtil.getTimestampFormat(formatOptions); JsonFormatOptions.MapNullKeyMode mapNullKeyMode = JsonFormatOptionsUtil.getMapNullKeyMode(formatOptions); String mapNullKeyLiteral = formatOptions.get(JSON_MAP_NULL_KEY_LITERAL); final boolean encodeDecimalAsPlainNumber = formatOptions.get(ENCODE_DECIMAL_AS_PLAIN_NUMBER); final boolean ignoreNullFields = formatOptions.get(ENCODE_IGNORE_NULL_FIELDS); return new EncodingFormat<SerializationSchema<RowData>>() { @Override public ChangelogMode getChangelogMode() { return ChangelogMode.newBuilder() .addContainedKind(RowKind.INSERT) .addContainedKind(RowKind.UPDATE_BEFORE) .addContainedKind(RowKind.UPDATE_AFTER) .addContainedKind(RowKind.DELETE) .build(); } @Override public SerializationSchema<RowData> createRuntimeEncoder( DynamicTableSink.Context context, DataType consumedDataType) { final RowType rowType = (RowType) consumedDataType.getLogicalType(); return new OggJsonSerializationSchema( rowType, timestampFormat, mapNullKeyMode, mapNullKeyLiteral, encodeDecimalAsPlainNumber, ignoreNullFields); } }; } @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Set<ConfigOption<?>> requiredOptions() { return Collections.emptySet(); } @Override public Set<ConfigOption<?>> optionalOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(IGNORE_PARSE_ERRORS); options.add(TIMESTAMP_FORMAT); options.add(JSON_MAP_NULL_KEY_MODE); options.add(JSON_MAP_NULL_KEY_LITERAL); options.add(ENCODE_DECIMAL_AS_PLAIN_NUMBER); options.add(ENCODE_IGNORE_NULL_FIELDS); return options; } }
OggJsonFormatFactory
java
apache__kafka
connect/runtime/src/test/resources/test-plugins/sampling-converter/test/plugins/SamplingConverter.java
{ "start": 1398, "end": 2802 }
class ____ implements SamplingTestPlugin, Converter { private static final ClassLoader STATIC_CLASS_LOADER; private static List<SamplingTestPlugin> instances; private final ClassLoader classloader; private Map<String, SamplingTestPlugin> samples; static { STATIC_CLASS_LOADER = Thread.currentThread().getContextClassLoader(); instances = Collections.synchronizedList(new ArrayList<>()); } { samples = new HashMap<>(); classloader = Thread.currentThread().getContextClassLoader(); } public SamplingConverter() { logMethodCall(samples); instances.add(this); } @Override public void configure(final Map<String, ?> configs, final boolean isKey) { logMethodCall(samples); } @Override public byte[] fromConnectData(final String topic, final Schema schema, final Object value) { logMethodCall(samples); return new byte[0]; } @Override public SchemaAndValue toConnectData(final String topic, final byte[] value) { logMethodCall(samples); return null; } @Override public ClassLoader staticClassloader() { return STATIC_CLASS_LOADER; } @Override public ClassLoader classloader() { return classloader; } @Override public Map<String, SamplingTestPlugin> otherSamples() { return samples; } @Override public List<SamplingTestPlugin> allInstances() { return instances; } }
SamplingConverter
java
quarkusio__quarkus
integration-tests/test-extension/extension/runtime/src/main/java/io/quarkus/extest/runtime/config/TestMappingBuildTimeRunTime.java
{ "start": 666, "end": 766 }
interface ____ { /** * A Group value. */ String value(); } }
Group
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/jdk/CustomMapKeys2454Test.java
{ "start": 583, "end": 738 }
class ____ { @JsonDeserialize(keyUsing = Key2454Deserializer.class) @JsonSerialize(keyUsing = Key2454Serializer.class) static
CustomMapKeys2454Test
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_containsExactly_Test.java
{ "start": 982, "end": 1397 }
class ____ extends IterableAssertBaseTest { @Override protected ConcreteIterableAssert<Object> invoke_api_method() { return assertions.containsExactly("Yoda", "Luke"); } @Override protected void verify_internal_effects() { Object[] values = { "Yoda", "Luke" }; verify(iterables).assertContainsExactly(getInfo(assertions), getActual(assertions), values); } }
IterableAssert_containsExactly_Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest3.java
{ "start": 565, "end": 685 }
class ____ { public Integer status; @JSONField(name = "status") public Integer status2; } }
VO
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java
{ "start": 23607, "end": 24127 }
class ____ { @com.google.errorprone.annotations.CheckReturnValue public Inner() {} } public static void foo() { // BUG: Diagnostic contains: CheckReturnValue new Test().new Inner() {}; } } """) .doTest(); } @Test public void constructor_anonymousClassInheritsCRV_syntheticConstructor() { compilationHelper .addSourceLines( "Test.java", "
Inner
java
apache__camel
components/camel-aws/camel-aws2-lambda/src/test/java/org/apache/camel/component/aws2/lambda/LambdaComponentClientRegistryTest.java
{ "start": 1242, "end": 3001 }
class ____ extends CamelTestSupport { @Test public void createEndpointWithMinimalKMSClientConfiguration() throws Exception { LambdaClient awsLambdaClient = new AmazonLambdaClientMock(); context.getRegistry().bind("awsLambdaClient", awsLambdaClient); Lambda2Component component = context.getComponent("aws2-lambda", Lambda2Component.class); Lambda2Endpoint endpoint = (Lambda2Endpoint) component .createEndpoint( "aws2-lambda://myFunction?operation=getFunction&awsLambdaClient=#awsLambdaClient&accessKey=xxx&secretKey=yyy"); assertNotNull(endpoint.getConfiguration().getAwsLambdaClient()); } @Test public void createEndpointWithMinimalKMSClientMisconfiguration() { Lambda2Component component = context.getComponent("aws2-lambda", Lambda2Component.class); assertThrows(PropertyBindingException.class, () -> { component .createEndpoint( "aws2-lambda://myFunction?operation=getFunction&awsLambdaClient=#awsLambdaClient&accessKey=xxx&secretKey=yyy"); }); } @Test public void createEndpointWithAutowire() throws Exception { LambdaClient awsLambdaClient = new AmazonLambdaClientMock(); context.getRegistry().bind("awsLambdaClient", awsLambdaClient); Lambda2Component component = context.getComponent("aws2-lambda", Lambda2Component.class); Lambda2Endpoint endpoint = (Lambda2Endpoint) component .createEndpoint("aws2-lambda://myFunction?operation=getFunction&accessKey=xxx&secretKey=yyy"); assertSame(awsLambdaClient, endpoint.getConfiguration().getAwsLambdaClient()); } }
LambdaComponentClientRegistryTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/profile/query/ProfileScorer.java
{ "start": 3808, "end": 4684 }
class ____ extends DocIdSetIterator { private final DocIdSetIterator in; TimedDocIdSetIterator(DocIdSetIterator in) { this.in = in; } @Override public int advance(int target) throws IOException { advanceTimer.start(); try { return in.advance(target); } finally { advanceTimer.stop(); } } @Override public int nextDoc() throws IOException { nextDocTimer.start(); try { return in.nextDoc(); } finally { nextDocTimer.stop(); } } @Override public int docID() { return in.docID(); } @Override public long cost() { return in.cost(); } } }
TimedDocIdSetIterator
java
apache__camel
components/camel-aws/camel-aws2-cw/src/test/java/org/apache/camel/component/aws2/cw/CwComponentConfigurationTest.java
{ "start": 1353, "end": 7165 }
class ____ extends CamelTestSupport { @BindToRegistry("now") public static final Instant NOW = Instant.now(); @Test public void createEndpointWithAllOptions() throws Exception { CloudWatchClient cloudWatchClient = new CloudWatchClientMock(); context.getRegistry().bind("amazonCwClient", cloudWatchClient); Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); Cw2Endpoint endpoint = (Cw2Endpoint) component .createEndpoint( "aws2-cw://camel.apache.org/test?amazonCwClient=#amazonCwClient&name=testMetric&value=2&unit=Count&timestamp=#now"); assertEquals("camel.apache.org/test", endpoint.getConfiguration().getNamespace()); assertEquals("testMetric", endpoint.getConfiguration().getName()); assertEquals(Double.valueOf(2), endpoint.getConfiguration().getValue()); assertEquals("Count", endpoint.getConfiguration().getUnit()); assertEquals(NOW, endpoint.getConfiguration().getTimestamp()); } @Test public void createEndpointWithoutAccessKeyConfiguration() { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); assertThrows(IllegalArgumentException.class, () -> { component.createEndpoint("aws2-cw://camel.apache.org/test?secretKey=yyy"); }); } @Test public void createEndpointWithoutSecretKeyConfiguration() { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); assertThrows(IllegalArgumentException.class, () -> { component.createEndpoint("aws2-cw://camel.apache.org/test?accessKey=xxx"); }); } @Test public void createEndpointWithoutSecretKeyAndAccessKeyConfiguration() { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); assertThrows(IllegalArgumentException.class, () -> { component.createEndpoint("aws2-cw://camel.apache.org/test"); }); } @Test public void createEndpointWithComponentElements() throws Exception { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); component.getConfiguration().setAccessKey("XXX"); component.getConfiguration().setSecretKey("YYY"); Cw2Endpoint endpoint = (Cw2Endpoint) component.createEndpoint("aws2-cw://camel.apache.org/test"); assertEquals("camel.apache.org/test", endpoint.getConfiguration().getNamespace()); assertEquals("XXX", endpoint.getConfiguration().getAccessKey()); assertEquals("YYY", endpoint.getConfiguration().getSecretKey()); } @Test public void createEndpointWithComponentAndEndpointElements() throws Exception { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); component.getConfiguration().setAccessKey("XXX"); component.getConfiguration().setSecretKey("YYY"); component.getConfiguration().setRegion(Region.US_WEST_1.toString()); Cw2Endpoint endpoint = (Cw2Endpoint) component .createEndpoint("aws2-cw://camel.apache.org/test?accessKey=xxxxxx&secretKey=yyyyy&region=US_EAST_1"); assertEquals("camel.apache.org/test", endpoint.getConfiguration().getNamespace()); assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey()); assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey()); assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion()); } @Test public void createEndpointWithComponentEndpointOptionsAndProxy() throws Exception { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); component.getConfiguration().setAccessKey("XXX"); component.getConfiguration().setSecretKey("YYY"); component.getConfiguration().setRegion(Region.US_WEST_1.id()); Cw2Endpoint endpoint = (Cw2Endpoint) component .createEndpoint( "aws2-cw://camel.apache.org/test?accessKey=xxxxxx&secretKey=yyyyy&region=US_EAST_1&proxyHost=localhost&proxyPort=9000"); assertEquals("camel.apache.org/test", endpoint.getConfiguration().getNamespace()); assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey()); assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey()); assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion()); assertEquals("localhost", endpoint.getConfiguration().getProxyHost()); assertEquals(Integer.valueOf(9000), endpoint.getConfiguration().getProxyPort()); assertEquals(Protocol.HTTPS, endpoint.getConfiguration().getProxyProtocol()); } @Test public void createEndpointWithEndpointOverride() throws Exception { Cw2Component component = context.getComponent("aws2-cw", Cw2Component.class); component.getConfiguration().setAccessKey("XXX"); component.getConfiguration().setSecretKey("YYY"); component.getConfiguration().setRegion(Region.US_WEST_1.toString()); Cw2Endpoint endpoint = (Cw2Endpoint) component .createEndpoint( "aws2-cw://camel.apache.org/test?overrideEndpoint=true&uriEndpointOverride=http://localhost:9090"); assertEquals("camel.apache.org/test", endpoint.getConfiguration().getNamespace()); assertEquals("XXX", endpoint.getConfiguration().getAccessKey()); assertEquals("YYY", endpoint.getConfiguration().getSecretKey()); assertEquals("us-west-1", endpoint.getConfiguration().getRegion()); assertTrue(endpoint.getConfiguration().isOverrideEndpoint()); assertEquals("http://localhost:9090", endpoint.getConfiguration().getUriEndpointOverride()); } }
CwComponentConfigurationTest
java
apache__kafka
raft/src/test/java/org/apache/kafka/raft/ProspectiveStateTest.java
{ "start": 1664, "end": 20305 }
class ____ { private final ReplicaKey localReplicaKey = ReplicaKey.of(0, Uuid.randomUuid()); private final Endpoints leaderEndpoints = Endpoints.fromInetSocketAddresses( Map.of( ListenerName.normalised("CONTROLLER"), InetSocketAddress.createUnresolved("mock-host-3", 1234) ) ); private final int epoch = 5; private final MockTime time = new MockTime(); private final int electionTimeoutMs = 10000; private final LogContext logContext = new LogContext(); private final int localId = 0; private final int votedId = 1; private final Uuid votedDirectoryId = Uuid.randomUuid(); private final ReplicaKey votedKeyWithDirectoryId = ReplicaKey.of(votedId, votedDirectoryId); private final ReplicaKey votedKeyWithoutDirectoryId = ReplicaKey.of(votedId, ReplicaKey.NO_DIRECTORY_ID); private ProspectiveState newProspectiveState( VoterSet voters, OptionalInt leaderId, Optional<ReplicaKey> votedKey ) { return new ProspectiveState( time, localReplicaKey.id(), epoch, leaderId, leaderId.isPresent() ? leaderEndpoints : Endpoints.empty(), votedKey, voters, Optional.empty(), electionTimeoutMs, logContext ); } private ProspectiveState newProspectiveState(VoterSet voters) { return new ProspectiveState( time, localReplicaKey.id(), epoch, OptionalInt.empty(), Endpoints.empty(), Optional.empty(), voters, Optional.empty(), electionTimeoutMs, logContext ); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testSingleNodeQuorum(boolean withDirectoryId) { ProspectiveState state = newProspectiveState(voterSetWithLocal(IntStream.empty(), withDirectoryId)); assertTrue(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertEquals(Set.of(), state.epochElection().unrecordedVoters()); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testTwoNodeQuorumVoteRejected(boolean withDirectoryId) { ReplicaKey otherNode = replicaKey(1, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(otherNode), withDirectoryId) ); assertFalse(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertEquals(Set.of(otherNode), state.epochElection().unrecordedVoters()); assertTrue(state.recordRejectedVote(otherNode.id())); assertFalse(state.epochElection().isVoteGranted()); assertTrue(state.epochElection().isVoteRejected()); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testTwoNodeQuorumVoteGranted(boolean withDirectoryId) { ReplicaKey otherNode = replicaKey(1, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(otherNode), withDirectoryId) ); assertFalse(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertEquals(Set.of(otherNode), state.epochElection().unrecordedVoters()); assertTrue(state.recordGrantedVote(otherNode.id())); assertEquals(Set.of(), state.epochElection().unrecordedVoters()); assertFalse(state.epochElection().isVoteRejected()); assertTrue(state.epochElection().isVoteGranted()); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testThreeNodeQuorumVoteGranted(boolean withDirectoryId) { ReplicaKey node1 = replicaKey(1, withDirectoryId); ReplicaKey node2 = replicaKey(2, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(node1, node2), withDirectoryId) ); assertFalse(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertEquals(Set.of(node1, node2), state.epochElection().unrecordedVoters()); assertTrue(state.recordGrantedVote(node1.id())); assertEquals(Set.of(node2), state.epochElection().unrecordedVoters()); assertTrue(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertTrue(state.recordRejectedVote(node2.id())); assertEquals(Set.of(), state.epochElection().unrecordedVoters()); assertTrue(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testThreeNodeQuorumVoteRejected(boolean withDirectoryId) { ReplicaKey node1 = replicaKey(1, withDirectoryId); ReplicaKey node2 = replicaKey(2, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(node1, node2), withDirectoryId) ); assertFalse(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertEquals(Set.of(node1, node2), state.epochElection().unrecordedVoters()); assertTrue(state.recordRejectedVote(node1.id())); assertEquals(Set.of(node2), state.epochElection().unrecordedVoters()); assertFalse(state.epochElection().isVoteGranted()); assertFalse(state.epochElection().isVoteRejected()); assertTrue(state.recordRejectedVote(node2.id())); assertEquals(Set.of(), state.epochElection().unrecordedVoters()); assertFalse(state.epochElection().isVoteGranted()); assertTrue(state.epochElection().isVoteRejected()); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testCanChangePreVote(boolean withDirectoryId) { int voter1 = 1; int voter2 = 2; ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.of(voter1, voter2), withDirectoryId) ); assertTrue(state.recordGrantedVote(voter1)); assertTrue(state.epochElection().isVoteGranted()); assertFalse(state.recordRejectedVote(voter1)); assertFalse(state.epochElection().isVoteGranted()); assertTrue(state.recordRejectedVote(voter2)); assertTrue(state.epochElection().isVoteRejected()); assertFalse(state.recordGrantedVote(voter2)); assertFalse(state.epochElection().isVoteRejected()); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testCannotGrantOrRejectNonVoters(boolean withDirectoryId) { int nonVoterId = 1; ProspectiveState state = newProspectiveState(voterSetWithLocal(IntStream.empty(), withDirectoryId)); assertThrows(IllegalArgumentException.class, () -> state.recordGrantedVote(nonVoterId)); assertThrows(IllegalArgumentException.class, () -> state.recordRejectedVote(nonVoterId)); } @ParameterizedTest @ValueSource(booleans = { true, false }) public void testConsecutiveGrant(boolean withDirectoryId) { int otherNodeId = 1; ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.of(otherNodeId), withDirectoryId) ); assertTrue(state.recordGrantedVote(otherNodeId)); assertFalse(state.recordGrantedVote(otherNodeId)); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testConsecutiveReject(boolean withDirectoryId) { int otherNodeId = 1; ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.of(otherNodeId), withDirectoryId) ); assertTrue(state.recordRejectedVote(otherNodeId)); assertFalse(state.recordRejectedVote(otherNodeId)); } @ParameterizedTest @CsvSource({ "true,true", "true,false", "false,true", "false,false" }) public void testGrantVote(boolean isLogUpToDate, boolean withDirectoryId) { ReplicaKey node0 = replicaKey(0, withDirectoryId); ReplicaKey node1 = replicaKey(1, withDirectoryId); ReplicaKey node2 = replicaKey(2, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(node1, node2), withDirectoryId) ); assertEquals(isLogUpToDate, state.canGrantVote(node0, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node1, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node2, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node0, isLogUpToDate, false)); assertEquals(isLogUpToDate, state.canGrantVote(node1, isLogUpToDate, false)); assertEquals(isLogUpToDate, state.canGrantVote(node2, isLogUpToDate, false)); } @ParameterizedTest @CsvSource({ "true,true", "true,false", "false,true", "false,false" }) public void testGrantVoteWithVotedKey(boolean isLogUpToDate, boolean withDirectoryId) { ReplicaKey node0 = replicaKey(0, withDirectoryId); ReplicaKey node1 = replicaKey(1, withDirectoryId); ReplicaKey node2 = replicaKey(2, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(node1, node2), withDirectoryId), OptionalInt.empty(), Optional.of(node1) ); assertEquals(isLogUpToDate, state.canGrantVote(node0, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node1, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node2, isLogUpToDate, true)); assertFalse(state.canGrantVote(node0, isLogUpToDate, false)); assertTrue(state.canGrantVote(node1, isLogUpToDate, false)); assertFalse(state.canGrantVote(node2, isLogUpToDate, false)); } @ParameterizedTest @CsvSource({ "true,true", "true,false", "false,true", "false,false" }) public void testGrantVoteWithLeader(boolean isLogUpToDate, boolean withDirectoryId) { ReplicaKey node0 = replicaKey(0, withDirectoryId); ReplicaKey node1 = replicaKey(1, withDirectoryId); ReplicaKey node2 = replicaKey(2, withDirectoryId); ProspectiveState state = newProspectiveState( voterSetWithLocal(Stream.of(node1, node2), withDirectoryId), OptionalInt.of(node1.id()), Optional.empty() ); assertEquals(isLogUpToDate, state.canGrantVote(node0, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node1, isLogUpToDate, true)); assertEquals(isLogUpToDate, state.canGrantVote(node2, isLogUpToDate, true)); assertFalse(state.canGrantVote(node0, isLogUpToDate, false)); assertFalse(state.canGrantVote(node1, isLogUpToDate, false)); assertFalse(state.canGrantVote(node2, isLogUpToDate, false)); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testElectionState(boolean withDirectoryId) { VoterSet voters = voterSetWithLocal(IntStream.of(1, 2, 3), withDirectoryId); ProspectiveState state = newProspectiveState(voters); assertEquals( ElectionState.withUnknownLeader( epoch, voters.voterIds() ), state.election() ); // with leader state = newProspectiveState(voters, OptionalInt.of(1), Optional.empty()); assertEquals( ElectionState.withElectedLeader( epoch, 1, Optional.empty(), voters.voterIds() ), state.election() ); // with voted key ReplicaKey votedKey = replicaKey(1, withDirectoryId); state = newProspectiveState(voters, OptionalInt.empty(), Optional.of(votedKey)); assertEquals( ElectionState.withVotedCandidate( epoch, votedKey, voters.voterIds() ), state.election() ); // with both state = newProspectiveState(voters, OptionalInt.of(1), Optional.of(votedKey)); assertEquals( ElectionState.withElectedLeader( epoch, 1, Optional.of(votedKey), voters.voterIds() ), state.election() ); } @Test public void testElectionTimeout() { ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.empty(), true), OptionalInt.empty(), Optional.of(votedKeyWithDirectoryId) ); assertEquals(epoch, state.epoch()); assertEquals(votedKeyWithDirectoryId, state.votedKey().get()); assertEquals( ElectionState.withVotedCandidate(epoch, votedKeyWithDirectoryId, Set.of(localId)), state.election() ); assertEquals(electionTimeoutMs, state.remainingElectionTimeMs(time.milliseconds())); assertFalse(state.hasElectionTimeoutExpired(time.milliseconds())); time.sleep(5000); assertEquals(electionTimeoutMs - 5000, state.remainingElectionTimeMs(time.milliseconds())); assertFalse(state.hasElectionTimeoutExpired(time.milliseconds())); time.sleep(5000); assertEquals(0, state.remainingElectionTimeMs(time.milliseconds())); assertTrue(state.hasElectionTimeoutExpired(time.milliseconds())); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testCanGrantVoteWithoutDirectoryId(boolean isLogUpToDate) { ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.empty(), true), OptionalInt.empty(), Optional.of(votedKeyWithoutDirectoryId)); assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, true) ); assertTrue(state.canGrantVote(ReplicaKey.of(votedId, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, false)); assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId, Uuid.randomUuid()), isLogUpToDate, true) ); assertTrue(state.canGrantVote(ReplicaKey.of(votedId, Uuid.randomUuid()), isLogUpToDate, false)); // Can grant PreVote to other replicas even if we have granted a standard vote to another replica assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId + 1, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, true) ); assertFalse(state.canGrantVote(ReplicaKey.of(votedId + 1, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, false)); } @ParameterizedTest @ValueSource(booleans = {true, false}) void testCanGrantVoteWithDirectoryId(boolean isLogUpToDate) { ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.empty(), true), OptionalInt.empty(), Optional.of(votedKeyWithDirectoryId)); // Same voterKey // We will not grant PreVote for a replica we have already granted a standard vote to if their log is behind assertEquals( isLogUpToDate, state.canGrantVote(votedKeyWithDirectoryId, isLogUpToDate, true) ); assertTrue(state.canGrantVote(votedKeyWithDirectoryId, isLogUpToDate, false)); // Different directoryId // We can grant PreVote for a replica we have already granted a standard vote to if their log is up-to-date, // even if the directoryId is different assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId, Uuid.randomUuid()), isLogUpToDate, true) ); assertFalse(state.canGrantVote(ReplicaKey.of(votedId, Uuid.randomUuid()), isLogUpToDate, false)); // Missing directoryId assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, true) ); assertFalse(state.canGrantVote(ReplicaKey.of(votedId, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, false)); // Different voterId assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId + 1, votedDirectoryId), isLogUpToDate, true) ); assertEquals( isLogUpToDate, state.canGrantVote(ReplicaKey.of(votedId + 1, ReplicaKey.NO_DIRECTORY_ID), isLogUpToDate, true) ); assertFalse(state.canGrantVote(ReplicaKey.of(votedId + 1, votedDirectoryId), true, false)); assertFalse(state.canGrantVote(ReplicaKey.of(votedId + 1, ReplicaKey.NO_DIRECTORY_ID), true, false)); } @Test public void testLeaderEndpoints() { ProspectiveState state = newProspectiveState( voterSetWithLocal(IntStream.of(1, 2, 3), true), OptionalInt.empty(), Optional.of(ReplicaKey.of(1, Uuid.randomUuid())) ); assertEquals(Endpoints.empty(), state.leaderEndpoints()); state = newProspectiveState( voterSetWithLocal(IntStream.of(1, 2, 3), true), OptionalInt.of(3), Optional.of(ReplicaKey.of(1, Uuid.randomUuid())) ); assertEquals(leaderEndpoints, state.leaderEndpoints()); } private ReplicaKey replicaKey(int id, boolean withDirectoryId) { Uuid directoryId = withDirectoryId ? Uuid.randomUuid() : ReplicaKey.NO_DIRECTORY_ID; return ReplicaKey.of(id, directoryId); } private VoterSet voterSetWithLocal(IntStream remoteVoterIds, boolean withDirectoryId) { Stream<ReplicaKey> remoteVoterKeys = remoteVoterIds .boxed() .map(id -> replicaKey(id, withDirectoryId)); return voterSetWithLocal(remoteVoterKeys, withDirectoryId); } private VoterSet voterSetWithLocal(Stream<ReplicaKey> remoteVoterKeys, boolean withDirectoryId) { ReplicaKey actualLocalVoter = withDirectoryId ? localReplicaKey : ReplicaKey.of(localReplicaKey.id(), ReplicaKey.NO_DIRECTORY_ID); return VoterSetTest.voterSet( Stream.concat(Stream.of(actualLocalVoter), remoteVoterKeys) ); } }
ProspectiveStateTest
java
redisson__redisson
redisson/src/main/java/org/redisson/RedissonBinaryStream.java
{ "start": 1515, "end": 2169 }
class ____ extends OutputStream { @Override public void write(int b) throws IOException { write(new byte[] {(byte) b}); } @Override public void write(byte[] b, int off, int len) throws IOException { byte[] dest; if (b.length == len && off == 0) { dest = b; } else { dest = new byte[len]; System.arraycopy(b, off, dest, 0, len); } get(commandExecutor.writeAsync(getRawName(), codec, RedisCommands.APPEND, getRawName(), dest)); } }
RedissonOutputStream
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/body/ByteBodyWriter.java
{ "start": 1239, "end": 2081 }
class ____ implements TypedMessageBodyWriter<ByteBody>, ResponseBodyWriter<ByteBody> { @Override public @NonNull CloseableByteBody writePiece(@NonNull ByteBodyFactory bodyFactory, @NonNull HttpRequest<?> request, @NonNull HttpResponse<?> response, @NonNull Argument<ByteBody> type, @NonNull MediaType mediaType, ByteBody object) throws CodecException { return object.move(); } @Override public @NonNull Argument<ByteBody> getType() { return Argument.of(ByteBody.class); } @Override public void writeTo(@NonNull Argument<ByteBody> type, @NonNull MediaType mediaType, ByteBody object, @NonNull MutableHeaders outgoingHeaders, @NonNull OutputStream outputStream) throws CodecException { throw new UnsupportedOperationException("Cannot write ByteBody to OutputStream"); } }
ByteBodyWriter
java
elastic__elasticsearch
x-pack/plugin/otel-data/src/main/java/org/elasticsearch/xpack/oteldata/otlp/tsid/ResourceTsidFunnel.java
{ "start": 646, "end": 1582 }
class ____ implements TsidFunnel<ResourceMetrics> { private final BufferedByteStringAccessor byteStringAccessor; public ResourceTsidFunnel(BufferedByteStringAccessor byteStringAccessor) { this.byteStringAccessor = byteStringAccessor; } public static TsidBuilder forResource(BufferedByteStringAccessor byteStringAccessor, ResourceMetrics resourceMetrics) { TsidBuilder tsidBuilder = new TsidBuilder(resourceMetrics.getResource().getAttributesCount()); new ResourceTsidFunnel(byteStringAccessor).add(resourceMetrics, tsidBuilder); return tsidBuilder; } @Override public void add(ResourceMetrics resourceMetrics, TsidBuilder tsidBuilder) { List<KeyValue> resourceAttributes = resourceMetrics.getResource().getAttributesList(); tsidBuilder.add(resourceAttributes, AttributeListTsidFunnel.get(byteStringAccessor, "resource.attributes.")); } }
ResourceTsidFunnel
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RBoundedBlockingQueue.java
{ "start": 838, "end": 1222 }
interface ____<V> extends RBlockingQueue<V>, RBoundedBlockingQueueAsync<V> { /** * Sets queue capacity only if it is not set before. * * @param capacity - queue capacity * @return <code>true</code> if capacity set successfully * <code>false</code> if capacity already set */ boolean trySetCapacity(int capacity); }
RBoundedBlockingQueue
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/QueryableBuiltInRolesUtilsTests.java
{ "start": 1454, "end": 13761 }
class ____ extends ESTestCase { @BeforeClass public static void setupReservedRolesStore() { new ReservedRolesStore(); // initialize the store } public void testCalculateHash() { assertThat( QueryableBuiltInRolesUtils.calculateHash(ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR), equalTo("bWEFdFo4WX229wdhdecfiz5QHMYEssh3ex8hizRgg+Q=") ); } public void testEmptyOrNullRolesToUpsertOrDelete() { // test empty roles and index digests final QueryableBuiltInRoles emptyRoles = new QueryableBuiltInRoles(Map.of(), Set.of()); assertThat(determineRolesToDelete(emptyRoles, Map.of()), is(empty())); assertThat(determineRolesToUpsert(emptyRoles, Map.of()), is(empty())); // test empty roles and null indexed digests assertThat(determineRolesToDelete(emptyRoles, null), is(empty())); assertThat(determineRolesToUpsert(emptyRoles, null), is(empty())); } public void testNoRolesToUpsertOrDelete() { { QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor") ) ); // no roles to delete or upsert since the built-in roles are the same as the indexed roles assertThat(determineRolesToDelete(currentBuiltInRoles, currentBuiltInRoles.rolesDigest()), is(empty())); assertThat(determineRolesToUpsert(currentBuiltInRoles, currentBuiltInRoles.rolesDigest()), is(empty())); } { QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor"), supermanRole("monitor", "read") ) ); Map<String, String> digests = buildDigests( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor"), supermanRole("monitor", "read") ) ); // no roles to delete or upsert since the built-in roles are the same as the indexed roles assertThat(determineRolesToDelete(currentBuiltInRoles, digests), is(empty())); assertThat(determineRolesToUpsert(currentBuiltInRoles, digests), is(empty())); } { final RoleDescriptor randomRole = RoleDescriptorTestHelper.randomRoleDescriptor(); final QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles(Set.of(randomRole)); final Map<String, String> digests = buildDigests( Set.of( new RoleDescriptor( randomRole.getName(), randomRole.getClusterPrivileges(), randomRole.getIndicesPrivileges(), randomRole.getApplicationPrivileges(), randomRole.getConditionalClusterPrivileges(), randomRole.getRunAs(), randomRole.getMetadata(), randomRole.getTransientMetadata(), randomRole.getRemoteIndicesPrivileges(), randomRole.getRemoteClusterPermissions(), randomRole.getRestriction(), randomRole.getDescription() ) ) ); assertThat(determineRolesToDelete(currentBuiltInRoles, digests), is(empty())); assertThat(determineRolesToUpsert(currentBuiltInRoles, digests), is(empty())); } } public void testRolesToDeleteOnly() { Map<String, String> indexedDigests = buildDigests( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor"), supermanRole("monitor", "read", "view_index_metadata", "read_cross_cluster") ) ); QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor") ) ); // superman is the only role that needs to be deleted since it is not in a current built-in role assertThat(determineRolesToDelete(currentBuiltInRoles, indexedDigests), containsInAnyOrder("superman")); assertThat(determineRolesToUpsert(currentBuiltInRoles, indexedDigests), is(empty())); // passing empty built-in roles should result in all indexed roles needing to be deleted QueryableBuiltInRoles emptyBuiltInRoles = new QueryableBuiltInRoles(Map.of(), Set.of()); assertThat( determineRolesToDelete(emptyBuiltInRoles, indexedDigests), containsInAnyOrder("superman", "viewer", "editor", "superuser") ); assertThat(determineRolesToUpsert(emptyBuiltInRoles, indexedDigests), is(empty())); } public void testRolesToUpdateOnly() { Map<String, String> indexedDigests = buildDigests( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor"), supermanRole("monitor", "read", "write") ) ); RoleDescriptor updatedSupermanRole = supermanRole("monitor", "read", "view_index_metadata", "read_cross_cluster"); QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor"), updatedSupermanRole ) ); // superman is the only role that needs to be updated since its definition has changed assertThat(determineRolesToDelete(currentBuiltInRoles, indexedDigests), is(empty())); assertThat(determineRolesToUpsert(currentBuiltInRoles, indexedDigests), containsInAnyOrder(updatedSupermanRole)); assertThat(currentBuiltInRoles.rolesDigest().get("superman"), is(not(equalTo(indexedDigests.get("superman"))))); } public void testRolesToCreateOnly() { Map<String, String> indexedDigests = buildDigests( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor") ) ); RoleDescriptor newSupermanRole = supermanRole("monitor", "read", "view_index_metadata", "read_cross_cluster"); QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor"), newSupermanRole ) ); // superman is the only role that needs to be created since it is not in the indexed roles assertThat(determineRolesToDelete(currentBuiltInRoles, indexedDigests), is(empty())); assertThat(determineRolesToUpsert(currentBuiltInRoles, indexedDigests), containsInAnyOrder(newSupermanRole)); // passing empty indexed roles should result in all roles needing to be created assertThat(determineRolesToDelete(currentBuiltInRoles, Map.of()), is(empty())); assertThat( determineRolesToUpsert(currentBuiltInRoles, Map.of()), containsInAnyOrder(currentBuiltInRoles.roleDescriptors().toArray(new RoleDescriptor[0])) ); } public void testRolesToUpsertAndDelete() { Map<String, String> indexedDigests = buildDigests( Set.of( ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, ReservedRolesStore.roleDescriptor("viewer"), ReservedRolesStore.roleDescriptor("editor") ) ); RoleDescriptor newSupermanRole = supermanRole("monitor"); QueryableBuiltInRoles currentBuiltInRoles = buildQueryableBuiltInRoles( Set.of(ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR, newSupermanRole) ); // superman is the only role that needs to be updated since its definition has changed assertThat(determineRolesToDelete(currentBuiltInRoles, indexedDigests), containsInAnyOrder("viewer", "editor")); assertThat(determineRolesToUpsert(currentBuiltInRoles, indexedDigests), containsInAnyOrder(newSupermanRole)); } private static RoleDescriptor supermanRole(String... indicesPrivileges) { return new RoleDescriptor( "superman", new String[] { "all" }, new RoleDescriptor.IndicesPrivileges[] { RoleDescriptor.IndicesPrivileges.builder().indices("*").privileges("all").allowRestrictedIndices(false).build(), RoleDescriptor.IndicesPrivileges.builder() .indices("*") .privileges(indicesPrivileges) .allowRestrictedIndices(true) .build() }, new RoleDescriptor.ApplicationResourcePrivileges[] { RoleDescriptor.ApplicationResourcePrivileges.builder().application("*").privileges("*").resources("*").build() }, null, new String[] { "*" }, randomlyOrderedSupermanMetadata(), Collections.emptyMap(), new RoleDescriptor.RemoteIndicesPrivileges[] { new RoleDescriptor.RemoteIndicesPrivileges( RoleDescriptor.IndicesPrivileges.builder().indices("*").privileges("all").allowRestrictedIndices(false).build(), "*" ), new RoleDescriptor.RemoteIndicesPrivileges( RoleDescriptor.IndicesPrivileges.builder() .indices("*") .privileges(indicesPrivileges) .allowRestrictedIndices(true) .build(), "*" ) }, new RemoteClusterPermissions().addGroup( new RemoteClusterPermissionGroup( RemoteClusterPermissions.getSupportedRemoteClusterPermissions().toArray(new String[0]), new String[] { "*" } ) ), null, "Grants full access to cluster management and data indices." ); } private static Map<String, Object> randomlyOrderedSupermanMetadata() { final LinkedHashMap<String, Object> metadata = new LinkedHashMap<>(); if (randomBoolean()) { metadata.put("foo", "bar"); metadata.put("baz", "qux"); metadata.put(RESERVED_METADATA_KEY, true); } else { metadata.put(RESERVED_METADATA_KEY, true); metadata.put("foo", "bar"); metadata.put("baz", "qux"); } return metadata; } public static QueryableBuiltInRoles buildQueryableBuiltInRoles(Set<RoleDescriptor> roles) { final Map<String, String> digests = buildDigests(roles); return new QueryableBuiltInRoles(digests, roles); } public static Map<String, String> buildDigests(Set<RoleDescriptor> roles) { final Map<String, String> digests = new HashMap<>(); for (RoleDescriptor role : roles) { digests.put(role.getName(), QueryableBuiltInRolesUtils.calculateHash(role)); } return digests; } }
QueryableBuiltInRolesUtilsTests
java
elastic__elasticsearch
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistField.java
{ "start": 892, "end": 925 }
class ____/field. */ public
variable