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
elastic__elasticsearch
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/SecurityPluginTests.java
{ "start": 5905, "end": 6915 }
class ____ extends Realm implements Closeable { public static final String TYPE = "dummy"; public DummyRealm(RealmConfig config) { super(config); REALM_INIT_FLAG.set(true); } @Override public boolean supports(AuthenticationToken token) { return false; } @Override public UsernamePasswordToken token(ThreadContext threadContext) { return null; } @Override public void authenticate(AuthenticationToken authToken, ActionListener<AuthenticationResult<User>> listener) { listener.onResponse(AuthenticationResult.notHandled()); } @Override public void lookupUser(String username, ActionListener<User> listener) { // Lookup (run-as) is not supported in this realm listener.onResponse(null); } @Override public void close() { REALM_CLOSE_FLAG.set(true); } } }
DummyRealm
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/aggregate/MaxTests.java
{ "start": 1731, "end": 12475 }
class ____ extends AbstractAggregationTestCase { public MaxTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { var suppliers = new ArrayList<TestCaseSupplier>(); Stream.of( MultiRowTestCaseSupplier.intCases(1, 1000, Integer.MIN_VALUE, Integer.MAX_VALUE, true), MultiRowTestCaseSupplier.longCases(1, 1000, Long.MIN_VALUE, Long.MAX_VALUE, true), MultiRowTestCaseSupplier.doubleCases(1, 1000, -Double.MAX_VALUE, Double.MAX_VALUE, true), MultiRowTestCaseSupplier.aggregateMetricDoubleCases(1, 1000, -Double.MAX_VALUE, Double.MAX_VALUE), MultiRowTestCaseSupplier.dateCases(1, 1000), MultiRowTestCaseSupplier.booleanCases(1, 1000), MultiRowTestCaseSupplier.ipCases(1, 1000), MultiRowTestCaseSupplier.versionCases(1, 1000), MultiRowTestCaseSupplier.stringCases(1, 1000, DataType.KEYWORD), MultiRowTestCaseSupplier.stringCases(1, 1000, DataType.TEXT), MultiRowTestCaseSupplier.exponentialHistogramCases(1, 100) ).flatMap(List::stream).map(MaxTests::makeSupplier).collect(Collectors.toCollection(() -> suppliers)); FunctionAppliesTo unsignedLongAppliesTo = appliesTo(FunctionAppliesToLifecycle.GA, "9.2.0", "", true); for (TestCaseSupplier.TypedDataSupplier supplier : MultiRowTestCaseSupplier.ulongCases( 1, 1000, BigInteger.ZERO, UNSIGNED_LONG_MAX, true )) { suppliers.add(makeSupplier(supplier.withAppliesTo(unsignedLongAppliesTo))); } suppliers.addAll( List.of( // Folding new TestCaseSupplier( List.of(DataType.INTEGER), () -> new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(200), DataType.INTEGER, "field")), standardAggregatorName("Max", DataType.INTEGER), DataType.INTEGER, equalTo(200) ) ), new TestCaseSupplier( List.of(DataType.LONG), () -> new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(200L), DataType.LONG, "field")), standardAggregatorName("Max", DataType.LONG), DataType.LONG, equalTo(200L) ) ), new TestCaseSupplier( List.of(DataType.UNSIGNED_LONG), () -> new TestCaseSupplier.TestCase( List.of( TestCaseSupplier.TypedData.multiRow(List.of(new BigInteger("200")), DataType.UNSIGNED_LONG, "field") .withAppliesTo(unsignedLongAppliesTo) ), standardAggregatorName("Max", DataType.UNSIGNED_LONG), DataType.UNSIGNED_LONG, equalTo(new BigInteger("200")) ) ), new TestCaseSupplier( List.of(DataType.DOUBLE), () -> new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(200.), DataType.DOUBLE, "field")), standardAggregatorName("Max", DataType.DOUBLE), DataType.DOUBLE, equalTo(200.) ) ), new TestCaseSupplier( List.of(DataType.DATETIME), () -> new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(200L), DataType.DATETIME, "field")), standardAggregatorName("Max", DataType.DATETIME), DataType.DATETIME, equalTo(200L) ) ), new TestCaseSupplier( List.of(DataType.DATE_NANOS), () -> new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(200L), DataType.DATE_NANOS, "field")), standardAggregatorName("Max", DataType.DATE_NANOS), DataType.DATE_NANOS, equalTo(200L) ) ), new TestCaseSupplier( List.of(DataType.BOOLEAN), () -> new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(true), DataType.BOOLEAN, "field")), standardAggregatorName("Max", DataType.BOOLEAN), DataType.BOOLEAN, equalTo(true) ) ), new TestCaseSupplier( List.of(DataType.IP), () -> new TestCaseSupplier.TestCase( List.of( TestCaseSupplier.TypedData.multiRow( List.of(new BytesRef(InetAddressPoint.encode(InetAddresses.forString("127.0.0.1")))), DataType.IP, "field" ) ), standardAggregatorName("Max", DataType.IP), DataType.IP, equalTo(new BytesRef(InetAddressPoint.encode(InetAddresses.forString("127.0.0.1")))) ) ), new TestCaseSupplier(List.of(DataType.KEYWORD), () -> { var value = new BytesRef(randomAlphaOfLengthBetween(0, 50)); return new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(value), DataType.KEYWORD, "field")), standardAggregatorName("Max", DataType.KEYWORD), DataType.KEYWORD, equalTo(value) ); }), new TestCaseSupplier(List.of(DataType.TEXT), () -> { var value = new BytesRef(randomAlphaOfLengthBetween(0, 50)); return new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(value), DataType.TEXT, "field")), standardAggregatorName("Max", DataType.TEXT), DataType.KEYWORD, equalTo(value) ); }), new TestCaseSupplier(List.of(DataType.VERSION), () -> { var value = randomBoolean() ? new Version(randomAlphaOfLengthBetween(1, 10)).toBytesRef() : new Version(randomIntBetween(0, 100) + "." + randomIntBetween(0, 100) + "." + randomIntBetween(0, 100)) .toBytesRef(); return new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(value), DataType.VERSION, "field")), standardAggregatorName("Max", DataType.VERSION), DataType.VERSION, equalTo(value) ); }), new TestCaseSupplier(List.of(DataType.AGGREGATE_METRIC_DOUBLE), () -> { var value = new AggregateMetricDoubleBlockBuilder.AggregateMetricDoubleLiteral( randomDouble(), randomDouble(), randomDouble(), randomNonNegativeInt() ); return new TestCaseSupplier.TestCase( List.of(TestCaseSupplier.TypedData.multiRow(List.of(value), DataType.AGGREGATE_METRIC_DOUBLE, "field")), standardAggregatorName("Max", DataType.AGGREGATE_METRIC_DOUBLE), DataType.DOUBLE, equalTo(value.max()) ); }) ) ); return parameterSuppliersFromTypedDataWithDefaultChecks(suppliers, false); } @Override protected Expression build(Source source, List<Expression> args) { return new Max(source, args.get(0)); } @SuppressWarnings("unchecked") private static TestCaseSupplier makeSupplier(TestCaseSupplier.TypedDataSupplier fieldSupplier) { return new TestCaseSupplier(fieldSupplier.name(), List.of(fieldSupplier.type()), () -> { var fieldTypedData = fieldSupplier.get(); Comparable<?> expected; DataType expectedReturnType; if (fieldSupplier.type() == DataType.AGGREGATE_METRIC_DOUBLE) { expected = fieldTypedData.multiRowData() .stream() .map( v -> (Comparable< ? super Comparable<?>>) ((Object) ((AggregateMetricDoubleBlockBuilder.AggregateMetricDoubleLiteral) v).max()) ) .max(Comparator.naturalOrder()) .orElse(null); expectedReturnType = DataType.DOUBLE; } else if (fieldSupplier.type() == DataType.EXPONENTIAL_HISTOGRAM) { expected = fieldTypedData.multiRowData() .stream() .map(obj -> (ExponentialHistogram) obj) .filter(histo -> histo.valueCount() > 0) // only non-empty histograms have an influence .map(ExponentialHistogram::max) .min(Comparator.naturalOrder()) .orElse(null); expectedReturnType = DataType.DOUBLE; } else { expected = fieldTypedData.multiRowData() .stream() .map(v -> (Comparable<? super Comparable<?>>) v) .max(Comparator.naturalOrder()) .orElse(null); expectedReturnType = fieldSupplier.type(); } return new TestCaseSupplier.TestCase( List.of(fieldTypedData), standardAggregatorName("Max", fieldSupplier.type()), expectedReturnType, equalTo(expected) ); }); } }
MaxTests
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/component/properties/HelloBean.java
{ "start": 869, "end": 1151 }
class ____ { private String greeting; public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } public String say(String hi) { return greeting + " " + hi; } }
HelloBean
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cache/ManyToOneWithOptimisticLockingTest.java
{ "start": 1846, "end": 5096 }
class ____ { private static final String ID = "ID"; private static final String OPERATOR_ID = "operatorID"; private static final ProductPK PRODUCT_PK = new ProductPK( ID, OPERATOR_ID ); @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { Operator operator = new Operator( OPERATOR_ID ); Product product = new Product( ID, operator, "test" ); session.persist( operator ); session.persist( product ); session.getFactory().getCache().evictEntityData(); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); scope.getSessionFactory().getCache().evictEntityData(); } @Test public void testFind(SessionFactoryScope scope) { StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { Product product = session.find( Product.class, PRODUCT_PK ); assertThat( product ).isNotNull(); Operator operator = product.getOperator(); assertThat( operator ).isNotNull(); assertThat( operator.getOperatorId() ).isEqualTo( OPERATOR_ID ); // Operator has not been initialized, only the Product has been cached assertThat( statistics.getSecondLevelCachePutCount() ).isEqualTo( 1 ); } ); statistics.clear(); scope.inTransaction( session -> { Product product = session.find( Product.class, PRODUCT_PK ); assertThat( product ).isNotNull(); Operator operator = product.getOperator(); assertThat( operator ).isNotNull(); assertThat( operator.getOperatorId() ).isEqualTo( OPERATOR_ID ); assertThat( statistics.getSecondLevelCacheHitCount() ).isEqualTo( 1 ); assertThat( statistics.getSecondLevelCacheMissCount() ).isEqualTo( 1 ); } ); } @Test public void testFind2(SessionFactoryScope scope) { StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { Product product = session.find( Product.class, PRODUCT_PK ); assertThat( product ).isNotNull(); Operator operator = product.getOperator(); assertThat( operator ).isNotNull(); assertThat( operator.getOperatorId() ).isEqualTo( OPERATOR_ID ); operator.getName(); // Operator has been initialized, both Product and Operator have been cached assertThat( statistics.getSecondLevelCachePutCount() ).isEqualTo( 2 ); } ); statistics.clear(); scope.inTransaction( session -> { Product product = session.find( Product.class, PRODUCT_PK ); assertThat( product ).isNotNull(); Operator operator = product.getOperator(); assertThat( operator ).isNotNull(); assertThat( operator.getOperatorId() ).isEqualTo( OPERATOR_ID ); assertThat( statistics.getSecondLevelCacheHitCount() ).isEqualTo( 2 ); assertThat( statistics.getSecondLevelCacheMissCount() ).isEqualTo( 0 ); } ); } @Entity(name = "Product") @IdClass(ProductPK.class) @OptimisticLocking(type = OptimisticLockType.ALL) @DynamicUpdate @Cacheable @Cache(usage = READ_WRITE) @Table(name = "PRODUCT_TABLE") public static
ManyToOneWithOptimisticLockingTest
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/extensions/ClassicDelegationTokenManager.java
{ "start": 7372, "end": 7919 }
class ____ extends SecretManager<StubAbfsTokenIdentifier> { public TokenSecretManager() { } @Override protected byte[] createPassword(StubAbfsTokenIdentifier identifier) { return getSecretManagerPassword(); } @Override public byte[] retrievePassword(StubAbfsTokenIdentifier identifier) throws InvalidToken { return getSecretManagerPassword(); } @Override public StubAbfsTokenIdentifier createIdentifier() { return new StubAbfsTokenIdentifier(); } } }
TokenSecretManager
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/IndexBalanceAllocationDecider.java
{ "start": 2459, "end": 9086 }
class ____ extends AllocationDecider { private static final Logger logger = LogManager.getLogger(IndexBalanceAllocationDecider.class); private static final String EMPTY = ""; public static final String NAME = "index_balance"; private final IndexBalanceConstraintSettings indexBalanceConstraintSettings; private final boolean isStateless; private volatile DiscoveryNodeFilters clusterRequireFilters; private volatile DiscoveryNodeFilters clusterIncludeFilters; private volatile DiscoveryNodeFilters clusterExcludeFilters; public IndexBalanceAllocationDecider(Settings settings, ClusterSettings clusterSettings) { this.indexBalanceConstraintSettings = new IndexBalanceConstraintSettings(clusterSettings); setClusterRequireFilters(CLUSTER_ROUTING_REQUIRE_GROUP_SETTING.getAsMap(settings)); setClusterExcludeFilters(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getAsMap(settings)); setClusterIncludeFilters(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getAsMap(settings)); clusterSettings.addAffixMapUpdateConsumer(CLUSTER_ROUTING_REQUIRE_GROUP_SETTING, this::setClusterRequireFilters, (a, b) -> {}); clusterSettings.addAffixMapUpdateConsumer(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING, this::setClusterExcludeFilters, (a, b) -> {}); clusterSettings.addAffixMapUpdateConsumer(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING, this::setClusterIncludeFilters, (a, b) -> {}); isStateless = DiscoveryNode.isStateless(settings); } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { if (indexBalanceConstraintSettings.isDeciderEnabled() == false || isStateless == false || hasFilters()) { return allocation.decision(Decision.YES, NAME, "Decider is disabled."); } Index index = shardRouting.index(); if (node.hasIndex(index) == false) { return allocation.decision(Decision.YES, NAME, "Node does not currently host this index."); } assert node.node() != null; assert node.node().getRoles().contains(INDEX_ROLE) || node.node().getRoles().contains(SEARCH_ROLE); if (node.node().getRoles().contains(INDEX_ROLE) && shardRouting.primary() == false) { return allocation.decision(Decision.YES, NAME, "An index node cannot own search shards. Decider inactive."); } if (node.node().getRoles().contains(SEARCH_ROLE) && shardRouting.primary()) { return allocation.decision(Decision.YES, NAME, "A search node cannot own primary shards. Decider inactive."); } final ProjectId projectId = allocation.getClusterState().metadata().projectFor(index).id(); final Set<DiscoveryNode> eligibleNodes = new HashSet<>(); int totalShards = 0; String nomenclature = EMPTY; if (node.node().getRoles().contains(INDEX_ROLE)) { collectEligibleNodes(allocation, eligibleNodes, INDEX_ROLE); // Primary shards only. totalShards = allocation.getClusterState().routingTable(projectId).index(index).size(); nomenclature = "index"; } else if (node.node().getRoles().contains(SEARCH_ROLE)) { collectEligibleNodes(allocation, eligibleNodes, SEARCH_ROLE); // Replicas only. final IndexMetadata indexMetadata = allocation.getClusterState().metadata().getProject(projectId).index(index); totalShards = indexMetadata.getNumberOfShards() * indexMetadata.getNumberOfReplicas(); nomenclature = "search"; } assert eligibleNodes.isEmpty() == false; if (eligibleNodes.isEmpty()) { return allocation.decision(Decision.YES, NAME, "There are no eligible nodes available."); } assert totalShards > 0; final double idealAllocation = Math.ceil((double) totalShards / eligibleNodes.size()); // Adding the excess shards before division ensures that with tolerance 1 we get: // 2 shards, 2 nodes, allow 2 on each // 3 shards, 2 nodes, allow 2 on each etc. final int threshold = Math.ceilDiv(totalShards + indexBalanceConstraintSettings.getExcessShards(), eligibleNodes.size()); final int currentAllocation = node.numberOfOwningShardsForIndex(index); if (currentAllocation >= threshold) { String explanation = Strings.format( "There are [%d] eligible nodes in the [%s] tier for assignment of [%d] shards in index [%s]. Ideally no more than [%.0f] " + "shard would be assigned per node (the index balance excess shards setting is [%d]). This node is already assigned" + " [%d] shards of the index.", eligibleNodes.size(), nomenclature, totalShards, index, idealAllocation, indexBalanceConstraintSettings.getExcessShards(), currentAllocation ); logger.trace(explanation); return allocation.decision(Decision.NOT_PREFERRED, NAME, explanation); } return allocation.decision(Decision.YES, NAME, "Node index shard allocation is under the threshold."); } private void collectEligibleNodes(RoutingAllocation allocation, Set<DiscoveryNode> eligibleNodes, DiscoveryNodeRole role) { for (DiscoveryNode discoveryNode : allocation.nodes()) { if (discoveryNode.getRoles().contains(role) && allocation.metadata().nodeShutdowns().contains(discoveryNode.getId()) == false) { eligibleNodes.add(discoveryNode); } } } private void setClusterRequireFilters(Map<String, List<String>> filters) { clusterRequireFilters = DiscoveryNodeFilters.trimTier(DiscoveryNodeFilters.buildFromKeyValues(AND, filters)); } private void setClusterIncludeFilters(Map<String, List<String>> filters) { clusterIncludeFilters = DiscoveryNodeFilters.trimTier(DiscoveryNodeFilters.buildFromKeyValues(OR, filters)); } private void setClusterExcludeFilters(Map<String, List<String>> filters) { clusterExcludeFilters = DiscoveryNodeFilters.trimTier(DiscoveryNodeFilters.buildFromKeyValues(OR, filters)); } private boolean hasFilters() { return (clusterExcludeFilters != null && clusterExcludeFilters.hasFilters()) || (clusterIncludeFilters != null && clusterIncludeFilters.hasFilters()) || (clusterRequireFilters != null && clusterRequireFilters.hasFilters()); } }
IndexBalanceAllocationDecider
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/ArraySortedAssert.java
{ "start": 1174, "end": 1552 }
class ____ must be a array type (e.g. arrays, collections).<br> * Please read &quot;<a href="http://bit.ly/1IZIRcY" target="_blank">Emulating 'self types' using Java Generics to * simplify fluent API implementation</a>&quot; for more details. * @param <ELEMENT> the array element type. * * @author Joel Costigliola * @author Mikhail Mazursky */ public
that
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/CodeGenerator.java
{ "start": 1750, "end": 7528 }
class ____ { private static final Logger log = Logger.getLogger(CodeGenerator.class); private static final String META_INF_SERVICES = "META-INF/services/"; private static final List<String> CONFIG_SERVICES = List.of( "org.eclipse.microprofile.config.spi.Converter", "org.eclipse.microprofile.config.spi.ConfigSource", "org.eclipse.microprofile.config.spi.ConfigSourceProvider", "io.smallrye.config.ConfigSourceInterceptor", "io.smallrye.config.ConfigSourceInterceptorFactory", "io.smallrye.config.ConfigSourceFactory", "io.smallrye.config.SecretKeysHandler", "io.smallrye.config.SecretKeysHandlerFactory", "io.smallrye.config.ConfigValidator"); // used by Gradle and Maven public static void initAndRun(QuarkusClassLoader classLoader, PathCollection sourceParentDirs, Path generatedSourcesDir, Path buildDir, Consumer<Path> sourceRegistrar, ApplicationModel appModel, Properties properties, String launchMode, boolean test) throws CodeGenException { Map<String, String> props = new HashMap<>(); properties.entrySet().stream().forEach(e -> props.put((String) e.getKey(), (String) e.getValue())); final List<CodeGenData> generators = init(appModel, props, classLoader, sourceParentDirs, generatedSourcesDir, buildDir, sourceRegistrar); if (generators.isEmpty()) { return; } final LaunchMode mode = LaunchMode.valueOf(launchMode); final Config config = getConfig(appModel, mode, properties, classLoader); for (CodeGenData generator : generators) { generator.setRedirectIO(true); trigger(classLoader, generator, appModel, config, test); } } private static List<CodeGenData> init( ApplicationModel model, Map<String, String> properties, ClassLoader deploymentClassLoader, PathCollection sourceParentDirs, Path generatedSourcesDir, Path buildDir, Consumer<Path> sourceRegistrar) throws CodeGenException { return callWithClassloader(deploymentClassLoader, () -> { final List<CodeGenProvider> codeGenProviders = loadCodeGenProviders(deploymentClassLoader); if (codeGenProviders.isEmpty()) { return List.of(); } final List<CodeGenData> result = new ArrayList<>(codeGenProviders.size()); for (CodeGenProvider provider : codeGenProviders) { provider.init(model, properties); Path outputDir = codeGenOutDir(generatedSourcesDir, provider, sourceRegistrar); for (Path sourceParentDir : sourceParentDirs) { Path in = provider.getInputDirectory(); if (in == null) { in = sourceParentDir.resolve(provider.inputDirectory()); } result.add( new CodeGenData(provider, outputDir, in, buildDir)); } } return result; }); } public static List<CodeGenData> init(ApplicationModel model, Map<String, String> properties, ClassLoader deploymentClassLoader, Collection<ModuleInfo> modules) throws CodeGenException { return callWithClassloader(deploymentClassLoader, () -> { List<CodeGenProvider> codeGenProviders = null; List<CodeGenData> codeGens = List.of(); for (DevModeContext.ModuleInfo module : modules) { if (!module.getSourceParents().isEmpty() && module.getPreBuildOutputDir() != null) { // it's null for remote dev if (codeGenProviders == null) { codeGenProviders = loadCodeGenProviders(deploymentClassLoader); if (codeGenProviders.isEmpty()) { return List.of(); } } for (CodeGenProvider provider : codeGenProviders) { provider.init(model, properties); Path outputDir = codeGenOutDir(Path.of(module.getPreBuildOutputDir()), provider, sourcePath -> module.addSourcePathFirst(sourcePath.toAbsolutePath().toString())); for (Path sourceParentDir : module.getSourceParents()) { if (codeGens.isEmpty()) { codeGens = new ArrayList<>(); } Path in = provider.getInputDirectory(); if (in == null) { in = sourceParentDir.resolve(provider.inputDirectory()); } codeGens.add( new CodeGenData(provider, outputDir, in, Path.of(module.getTargetDir()))); } } } } return codeGens; }); } @SuppressWarnings("unchecked") private static List<CodeGenProvider> loadCodeGenProviders(ClassLoader deploymentClassLoader) throws CodeGenException { Class<? extends CodeGenProvider> codeGenProviderClass; try { //noinspection unchecked codeGenProviderClass = (Class<? extends CodeGenProvider>) deploymentClassLoader .loadClass(CodeGenProvider.class.getName()); } catch (ClassNotFoundException e) { throw new CodeGenException("Failed to load CodeGenProvider
CodeGenerator
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/clock/Clock.java
{ "start": 1035, "end": 2273 }
interface ____ { /** * The elapsed time since the creation of the clock * * @return The elapsed time, in milliseconds, since the creation of the exchange */ long elapsed(); /** * The point in time the clock was created * * @return The point in time, in milliseconds, the exchange was created. * @see System#currentTimeMillis() */ long getCreated(); /** * Get the creation date/time as with time-zone information * * @return A ZonedDateTime instance from the computed creation time */ default ZonedDateTime asZonedCreationDateTime() { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(getCreated()), ZoneId.systemDefault()); } /** * Get the creation date/time as regular Java Date instance * * @return A Date instance from the computed creation time */ default Date asDate() { return new Date(getCreated()); } /** * Get the elapsed duration for this clock in the standard Java Duration * * @return A new Duration instance representing the elapsed duration for this clock */ default Duration asDuration() { return Duration.ofMillis(elapsed()); } }
Clock
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/api/AuthenticationExtensionsClientInput.java
{ "start": 993, "end": 1573 }
interface ____<T> extends Serializable { /** * Gets the <a href="https://www.w3.org/TR/webauthn-3/#extension-identifier">extension * identifier</a>. * @return the * <a href="https://www.w3.org/TR/webauthn-3/#extension-identifier">extension * identifier</a>. */ String getExtensionId(); /** * Gets the <a href="https://www.w3.org/TR/webauthn-3/#client-extension-input">client * extension</a>. * @return the * <a href="https://www.w3.org/TR/webauthn-3/#client-extension-input">client * extension</a>. */ T getInput(); }
AuthenticationExtensionsClientInput
java
apache__camel
components/camel-ibm/camel-ibm-cos/src/test/java/org/apache/camel/component/ibm/cos/integration/IBMCOSProducerAdditionalOperationsIT.java
{ "start": 2368, "end": 9045 }
class ____ extends IBMCOSTestSupport { @EndpointInject private ProducerTemplate template; @EndpointInject("mock:result") private MockEndpoint mockResult; @BeforeEach public void resetMocks() { mockResult.reset(); } @Test public void testDeleteObjects() throws Exception { // Create multiple test objects final String key1 = "batch-delete-1.txt"; final String key2 = "batch-delete-2.txt"; final String key3 = "batch-delete-3.txt"; // Upload test objects for (String key : new String[] { key1, key2, key3 }) { template.send("direct:putObject", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IBMCOSConstants.KEY, key); exchange.getIn().setBody(new ByteArrayInputStream("Test content".getBytes())); } }); } // Verify objects exist assertTrue(cosClient.doesObjectExist(bucketName, key1), "Object 1 should exist"); assertTrue(cosClient.doesObjectExist(bucketName, key2), "Object 2 should exist"); assertTrue(cosClient.doesObjectExist(bucketName, key3), "Object 3 should exist"); // Delete multiple objects List<String> keysToDelete = new ArrayList<>(); keysToDelete.add(key1); keysToDelete.add(key2); keysToDelete.add(key3); template.send("direct:deleteObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IBMCOSConstants.KEYS_TO_DELETE, keysToDelete); } }); // Verify objects are deleted await().atMost(10, TimeUnit.SECONDS) .untilAsserted(() -> { assertFalse(cosClient.doesObjectExist(bucketName, key1), "Object 1 should be deleted"); assertFalse(cosClient.doesObjectExist(bucketName, key2), "Object 2 should be deleted"); assertFalse(cosClient.doesObjectExist(bucketName, key3), "Object 3 should be deleted"); }); } @Test public void testGetObjectRange() throws Exception { final String testKey = "range-test.txt"; final String testContent = "0123456789ABCDEFGHIJ"; // 20 characters // Upload test object template.send("direct:putObject", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IBMCOSConstants.KEY, testKey); exchange.getIn().setBody(new ByteArrayInputStream(testContent.getBytes())); } }); // Get partial object (bytes 5-9, should be "56789") Exchange getExchange = template.request("direct:getObjectRange", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IBMCOSConstants.KEY, testKey); exchange.getIn().setHeader(IBMCOSConstants.RANGE_START, 5L); exchange.getIn().setHeader(IBMCOSConstants.RANGE_END, 9L); } }); assertNotNull(getExchange); InputStream is = getExchange.getMessage().getBody(InputStream.class); assertNotNull(is); String retrievedContent = IOHelper.loadText(is).trim(); assertEquals("56789", retrievedContent, "Should retrieve only bytes 5-9"); } @Test public void testHeadBucket() throws Exception { // Test bucket exists (our test bucket should exist) Exchange headExchange = template.request("direct:headBucket", new Processor() { @Override public void process(Exchange exchange) { // No headers needed, uses bucket from endpoint } }); assertNotNull(headExchange); Boolean bucketExists = headExchange.getMessage().getBody(Boolean.class); assertTrue(bucketExists, "Test bucket should exist"); } @Test public void testCreateAndDeleteBucket() throws Exception { final String testBucketName = "camel-test-create-" + System.currentTimeMillis(); try { // Create bucket Exchange createExchange = template.request("direct:createBucket", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IBMCOSConstants.BUCKET_NAME, testBucketName); } }); assertNotNull(createExchange); // Verify bucket exists assertTrue(cosClient.doesBucketExistV2(testBucketName), "Created bucket should exist"); // Delete bucket template.send("direct:deleteBucket", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(IBMCOSConstants.BUCKET_NAME, testBucketName); } }); // Verify bucket is deleted assertFalse(cosClient.doesBucketExistV2(testBucketName), "Bucket should be deleted"); } finally { // Cleanup in case test fails try { if (cosClient.doesBucketExistV2(testBucketName)) { cosClient.deleteBucket(testBucketName); } } catch (Exception e) { // Ignore cleanup errors } } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:putObject") .to(buildEndpointUri("putObject")) .to("mock:result"); from("direct:deleteObjects") .to(buildEndpointUri("deleteObjects")) .to("mock:result"); from("direct:getObjectRange") .to(buildEndpointUri("getObjectRange")) .to("mock:result"); from("direct:headBucket") .to(buildEndpointUri("headBucket")) .to("mock:result"); from("direct:createBucket") .to(buildEndpointUri("createBucket")) .to("mock:result"); from("direct:deleteBucket") .to(buildEndpointUri("deleteBucket")) .to("mock:result"); } }; } }
IBMCOSProducerAdditionalOperationsIT
java
reactor__reactor-core
reactor-core/src/test/java/reactor/util/repeat/RepeatSpecTest.java
{ "start": 1058, "end": 6439 }
class ____ { @Test public void builderMethodsProduceNewInstances() { RepeatSpec init = RepeatSpec.times(1); assertThat(init).isNotSameAs(init.onlyIf(signal -> true)) .isNotSameAs(init.doBeforeRepeat(signal -> { })) .isNotSameAs(init.doAfterRepeat(signal -> { })) .isNotSameAs(init.withFixedDelay(Duration.ofMillis(100))) .isNotSameAs(init.jitter(0.5)) .isNotSameAs(init.withScheduler(Schedulers.immediate())); } @Test void onlyIfReplacesPredicate() { RepeatSpec repeatSpec = RepeatSpec.times(5) .onlyIf(signal -> signal.iteration() < 5) .onlyIf(signal -> signal.iteration() == 0); RepeatSpec.RepeatSignal acceptSignal = new ImmutableRepeatSignal(0, 123L, Duration.ofMillis(0), Context.empty()); RepeatSpec.RepeatSignal rejectSignal = new ImmutableRepeatSignal(4, 123L, Duration.ofMillis(0), Context.empty()); assertThat(repeatSpec.repeatPredicate).accepts(acceptSignal) .rejects(rejectSignal); } @Test void doBeforeRepeatIsCumulative() { AtomicInteger counter = new AtomicInteger(); RepeatSpec.RepeatSignal dummySignal = new ImmutableRepeatSignal(0, 0L, Duration.ZERO, Context.empty()); RepeatSpec repeatSpec = RepeatSpec.times(1) .doBeforeRepeat(signal -> counter.incrementAndGet()) .doBeforeRepeat(signal -> counter.addAndGet(10)); repeatSpec.beforeRepeatHook.accept(dummySignal); assertThat(counter.get()).isEqualTo(11); } @Test void doAfterRepeatIsCumulative() { AtomicInteger counter = new AtomicInteger(); RepeatSpec.RepeatSignal dummySignal = new ImmutableRepeatSignal(0, 0L, Duration.ZERO, Context.empty()); RepeatSpec repeatSpec = RepeatSpec.times(1) .doAfterRepeat(signal -> counter.incrementAndGet()) .doAfterRepeat(signal -> counter.addAndGet(10)); repeatSpec.afterRepeatHook.accept(dummySignal); assertThat(counter.get()).isEqualTo(11); } @Test void settersApplyConfigurationCorrectly() { Duration delay = Duration.ofMillis(123); double jitter = 0.42; Scheduler single = Schedulers.single(); RepeatSpec repeatSpec = RepeatSpec.times(3) .withFixedDelay(delay) .jitter(jitter) .withScheduler(single); assertThat(repeatSpec.fixedDelay).isEqualTo(delay); assertThat(repeatSpec.jitterFactor).isEqualTo(jitter); assertThat(repeatSpec.scheduler).isSameAs(single); } @Test void repeatMaxLimitsRepeats() { AtomicInteger subscriptionCounter = new AtomicInteger(); Flux<String> flux = Flux.defer(() -> { subscriptionCounter.incrementAndGet(); return Flux.just("foo", "bar"); }); Flux<String> repeated = flux.repeatWhen(RepeatSpec.times(3)); StepVerifier.create(repeated) .expectNext("foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar") .expectComplete() .verify(); assertThat(subscriptionCounter.get()).isEqualTo(4); } @Test void onlyIfPredicateControlsTermination() { AtomicInteger attempts = new AtomicInteger(); Flux<String> source = Flux.defer(() -> { int i = attempts.getAndIncrement(); return Flux.just("foo" + i); }); RepeatSpec repeatSpec = RepeatSpec.times(100) .onlyIf(signal -> signal.iteration() < 2); StepVerifier.create(source.repeatWhen(repeatSpec)) .expectNext("foo0", "foo1", "foo2") .expectComplete() .verify(); assertThat(attempts.get()).isEqualTo(3); } @Test void jitterProducesDelayInExpectedRange() { Duration baseDelay = Duration.ofMillis(1000); double jitterFactor = 0.2; int samples = 1000; RepeatSpec repeatSpec = RepeatSpec.times(1) .withFixedDelay(baseDelay) .jitter(jitterFactor); long minExpected = (long) (baseDelay.toMillis() * (1 - jitterFactor)); long maxExpected = (long) (baseDelay.toMillis() * (1 + jitterFactor)); for (int i = 0; i < samples; i++) { Duration actual = repeatSpec.calculateDelay(); long millis = actual.toMillis(); assertThat(millis).as("Delay in range") .isBetween(minExpected, maxExpected); } } @Test void repeatContextCanInfluencePredicate() { RepeatSpec repeatSpec = RepeatSpec.times(5) .withRepeatContext(Context.of("stopAfterOne", true)) .onlyIf(signal -> { Boolean contextEntry = signal.repeatContextView() .getOrDefault("stopAfterOne", Boolean.FALSE); boolean stopAfterOne = Boolean.TRUE.equals(contextEntry); return !stopAfterOne || signal.iteration() == 0; }); AtomicInteger subscriptionCount = new AtomicInteger(); Flux<String> source = Flux.defer(() -> { subscriptionCount.incrementAndGet(); return Flux.just("foo"); }); StepVerifier.create(source.repeatWhen(repeatSpec)) .expectNext("foo", "foo") .verifyComplete(); assertThat(subscriptionCount.get()).isEqualTo(2); } }
RepeatSpecTest
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 50253, "end": 50687 }
class ____ { void f() { int y = 1; System.err.println(y); } } """) .doTest(); } @Test public void compilesWithFix_releaseFlag() { BugCheckerRefactoringTestHelper.newInstance(CompilesWithFixChecker.class, getClass()) .setArgs("--release", "9") .addInputLines( "in/Test.java", """
Test
java
quarkusio__quarkus
integration-tests/opentelemetry-reactive/src/main/java/io/quarkus/it/opentelemetry/reactive/ReactiveResource.java
{ "start": 668, "end": 3428 }
class ____ { public static final int MILLISECONDS_DELAY = 100; @Inject Tracer tracer; @Inject @RestClient ReactiveRestClient client; private ScheduledExecutorService executor; @PostConstruct public void init() { executor = Executors.newScheduledThreadPool(2); } @GET public Uni<String> helloGet(@QueryParam("name") String name) { Span span = tracer.spanBuilder("helloGet").startSpan(); return Uni.createFrom().item("Hello " + name).onItem().delayIt().by(Duration.ofMillis(MILLISECONDS_DELAY)) .eventually((Runnable) span::end); } @GET @Path("/hello-get-uni-delay") @WithSpan("helloGetUniDelay") public Uni<String> helloGetUniDelay() { return Uni.createFrom().item("helloGetUniDelay").onItem().delayIt().by(Duration.ofMillis(MILLISECONDS_DELAY)); } @GET @Path("/hello-get-uni-executor") @WithSpan("helloGetUniExecutor") public Uni<String> helloGetUniExecutor() { return Uni.createFrom().item("helloGetUniExecutor") .onItem().delayIt().onExecutor(executor).by(Duration.ofMillis(MILLISECONDS_DELAY)); } @GET @Path("/multiple-chain") public Uni<String> helloMultipleUsingChain() { return client.helloGet("Naruto") .chain(s1 -> client.helloGet("Goku").map(s2 -> s1 + " and " + s2)); } @GET @Path("/multiple-combine") public Uni<String> helloMultipleUsingCombine() { return Uni.combine().all().unis( client.helloGet("Naruto"), client.helloGet("Goku")) .combinedWith((s, s2) -> s + " and " + s2); } @GET @Path("/multiple-combine-different-paths") public Uni<String> helloMultipleUsingCombineDifferentPaths() { return Uni.combine().all().unis( client.helloGetUniDelay(), client.helloGet("Naruto"), client.helloGet("Goku"), client.helloGetUniExecutor()) .with((s, s2, s3, s4) -> s + " and " + s2 + " and " + s3 + " and " + s4); } @POST public Uni<String> helloPost(String body) { Span span = tracer.spanBuilder("helloPost").startSpan(); return Uni.createFrom().item("Hello " + body).onItem().delayIt().by(Duration.ofMillis(MILLISECONDS_DELAY)) .eventually((Runnable) span::end); } @Path("blockingException") @GET public String blockingException() { throw new NoStackTraceException("dummy"); } @Path("reactiveException") @GET public Uni<String> reactiveException() { return Uni.createFrom().item(() -> { throw new NoStackTraceException("dummy2"); }); } }
ReactiveResource
java
apache__camel
catalog/camel-catalog-maven/src/main/java/org/apache/camel/catalog/maven/DefaultMavenArtifactProvider.java
{ "start": 5743, "end": 6175 }
class ____ String javaType = extractComponentJavaType(classLoader, scheme, logger); if (javaType != null) { String json = loadComponentJSonSchema(classLoader, scheme, logger); if (json != null) { logger.info("Adding component: {}", scheme); camelCatalog.addComponent(scheme, javaType, json); names.add(scheme); } } } }
name
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DebeziumOracleComponentBuilderFactory.java
{ "start": 105397, "end": 108353 }
class ____ should be used to * determine the topic name for data change, schema change, transaction, * heartbeat event etc. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: io.debezium.schema.SchemaTopicNamingStrategy * Group: oracle * * @param topicNamingStrategy the value to set * @return the dsl builder */ default DebeziumOracleComponentBuilder topicNamingStrategy(java.lang.String topicNamingStrategy) { doSetProperty("topicNamingStrategy", topicNamingStrategy); return this; } /** * Topic prefix that identifies and provides a namespace for the * particular database server/cluster is capturing changes. The topic * prefix should be unique across all other connectors, since it is used * as a prefix for all Kafka topic names that receive events emitted by * this connector. Only alphanumeric characters, hyphens, dots and * underscores must be accepted. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: oracle * * @param topicPrefix the value to set * @return the dsl builder */ default DebeziumOracleComponentBuilder topicPrefix(java.lang.String topicPrefix) { doSetProperty("topicPrefix", topicPrefix); return this; } /** * Class to make transaction context &amp; transaction struct/schemas. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: * io.debezium.pipeline.txmetadata.DefaultTransactionMetadataFactory * Group: oracle * * @param transactionMetadataFactory the value to set * @return the dsl builder */ default DebeziumOracleComponentBuilder transactionMetadataFactory(java.lang.String transactionMetadataFactory) { doSetProperty("transactionMetadataFactory", transactionMetadataFactory); return this; } /** * Specify the constant that will be provided by Debezium to indicate * that the original value is unavailable and not provided by the * database. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: __debezium_unavailable_value * Group: oracle * * @param unavailableValuePlaceholder the value to set * @return the dsl builder */ default DebeziumOracleComponentBuilder unavailableValuePlaceholder(java.lang.String unavailableValuePlaceholder) { doSetProperty("unavailableValuePlaceholder", unavailableValuePlaceholder); return this; } }
that
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_25_concat.java
{ "start": 1100, "end": 3049 }
class ____ extends DB2Test { public void test_0() throws Exception { String sql = "select ID, AUTHORITY_TYPE from t_authority a where authority_type like CONCAT('%', ?)"; DB2StatementParser parser = new DB2StatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); System.out.println(stmt.getSelect().getQuery()); assertEquals(1, statementList.size()); DB2SchemaStatVisitor visitor = new DB2SchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(2, visitor.getColumns().size()); assertEquals(1, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("t_authority"))); // assertTrue(visitor.getColumns().contains(new Column("DSN8B10.EMP", "WORKDEPT"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name"))); assertEquals("SELECT ID, AUTHORITY_TYPE\n" + "FROM t_authority a\n" + "WHERE authority_type LIKE CONCAT('%', ?)", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2)); assertEquals("select ID, AUTHORITY_TYPE\n" + "from t_authority a\n" + "where authority_type like CONCAT('%', ?)", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } }
DB2SelectTest_25_concat
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cut/MonetoryAmountUserType.java
{ "start": 2278, "end": 2381 }
class ____ { // private BigDecimal amount; // private Currency currency; // } }
MonetaryAmountEmbeddable
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/TestNamingStrategyStd.java
{ "start": 3356, "end": 3664 }
class ____ { public String firstName; protected FirstNameBean() { } public FirstNameBean(String n) { firstName = n; } } @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation public @
FirstNameBean
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/MoreThanOneScopeAnnotationOnClassTest.java
{ "start": 3753, "end": 3906 }
class ____ {} /** Class has two scoped annotations, but is a Dagger subcomponent */ @Singleton @SessionScoped @Subcomponent public
DaggerComponent
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/metadata/BeanMetadataTest.java
{ "start": 476, "end": 974 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(Controller.class); @Test public void testBeanMetadata() { ArcContainer arc = Arc.container(); Bean<?> bean = arc.instance(Controller.class).get().bean; assertNotNull(bean); assertEquals(2, bean.getTypes().size()); assertTrue(bean.getTypes().contains(Controller.class)); assertTrue(bean.getTypes().contains(Object.class)); } }
BeanMetadataTest
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/PluginDiscoveryMode.java
{ "start": 1086, "end": 2538 }
enum ____ { /** * Scan for plugins reflectively. This corresponds to the legacy behavior of Connect prior to KIP-898. * <p>Note: the following plugins are still loaded using {@link java.util.ServiceLoader} in this mode: * <ul> * <li>{@link org.apache.kafka.common.config.provider.ConfigProvider}</li> * <li>{@link org.apache.kafka.connect.rest.ConnectRestExtension}</li> * <li>{@link org.apache.kafka.connect.connector.policy.ConnectorClientConfigOverridePolicy}</li> * </ul> */ ONLY_SCAN, /** * Scan for plugins reflectively and via {@link java.util.ServiceLoader}. * Emit warnings if one or more plugins is not available via {@link java.util.ServiceLoader} */ HYBRID_WARN, /** * Scan for plugins reflectively and via {@link java.util.ServiceLoader}. * Fail worker during startup if one or more plugins is not available via {@link java.util.ServiceLoader} */ HYBRID_FAIL, /** * Discover plugins via {@link java.util.ServiceLoader} only. * Plugins may not be usable if they are not available via {@link java.util.ServiceLoader} */ SERVICE_LOAD; public boolean reflectivelyScan() { return this != SERVICE_LOAD; } public boolean serviceLoad() { return this != ONLY_SCAN; } @Override public String toString() { return name().toLowerCase(Locale.ROOT); } }
PluginDiscoveryMode
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpRequestTimeoutTest.java
{ "start": 1303, "end": 2620 }
class ____ extends BaseNettyTest { @Test public void testRequestTimeout() { try { template.requestBody("netty-http:http://localhost:{{port}}/timeout?requestTimeout=1000", "Hello Camel", String.class); fail("Should have thrown exception"); } catch (CamelExecutionException e) { ReadTimeoutException cause = assertIsInstanceOf(ReadTimeoutException.class, e.getCause()); assertNotNull(cause); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("netty-http:http://localhost:{{port}}/timeout") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); if (body.contains("Camel")) { Thread.sleep(3000); } } }) .transform().constant("Bye World"); } }; } }
NettyHttpRequestTimeoutTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/ClassAssertBaseTest.java
{ "start": 1043, "end": 1255 }
class ____ extends BaseTestTemplate<ClassAssert, Class<?>> { protected Classes classes; protected Objects objects; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @
ClassAssertBaseTest
java
quarkusio__quarkus
extensions/scheduler/api/src/main/java/io/quarkus/scheduler/Scheduled.java
{ "start": 2347, "end": 7563 }
interface ____ { /** * Constant value for {@link #timeZone()} indicating that the default timezone should be used. */ String DEFAULT_TIMEZONE = "<<default timezone>>"; /** * Constant value for {@link #executeWith()} indicating that the implementation should be selected automatically, i.e. the * implementation with highest priority is used. */ String AUTO = "<<auto>>"; /** * Constant value for {@link #executeWith()} indicating that the simple in-memory implementation provided by the * {@code quarkus-scheduler} extension should be used. * <p> * This implementation has priority {@code 0}. */ String SIMPLE = "SIMPLE"; /** * Constant value for {@link #executeWith()} indicating that the Quartz implementation provided by the * {@code quarkus-quartz} extension should be used. * <p> * This implementation has priority {@code 1}. */ String QUARTZ = "QUARTZ"; /** * Optionally defines a unique identifier for this job. * <p> * The value can be a property expression. In this case, the scheduler attempts to use the configured value instead: * {@code @Scheduled(identity = "${myJob.identity}")}. * Additionally, the property expression can specify a default value: {@code @Scheduled(identity = * "${myJob.identity:defaultIdentity}")}. * <p> * If the value is not provided then a unique id is generated. * * @return the unique identity of the schedule */ String identity() default ""; /** * Defines a cron-like expression. For example "0 15 10 * * ?" fires at 10:15am every day. * <p> * The value can be a property expression. In this case, the scheduler attempts to use the configured value instead: * {@code @Scheduled(cron = "${myJob.cronExpression}")}. * Additionally, the property expression can specify a default value: {@code @Scheduled(cron = "${myJob.cronExpression:0/2 * * * * * ?}")}. * <p> * Furthermore, two special constants can be used to disable the scheduled method: {@code off} and {@code disabled}. For * example, {@code @Scheduled(cron="${myJob.cronExpression:off}")} means that if the property is undefined then * the method is never executed. * * @return the cron-like expression */ String cron() default ""; /** * Defines the period between invocations. * <p> * The value is parsed with {@link DurationConverter#parseDuration(String)}. Note that the absolute value of the value is * always used. * <p> * A value less than one second may not be supported by the underlying scheduler implementation. In that case a warning * message is logged during build and application start. * <p> * The value can be a property expression. In this case, the scheduler attempts to use the configured value instead: * {@code @Scheduled(every = "${myJob.everyExpression}")}. * Additionally, the property expression can specify a default value: {@code @Scheduled(every = * "${myJob.everyExpression:5m}")}. * <p> * Furthermore, two special constants can be used to disable the scheduled method: {@code off} and {@code disabled}. For * example, {@code @Scheduled(every="${myJob.everyExpression:off}")} means that if the property is undefined then * the method is never executed. * * @return the period expression based on the ISO-8601 duration format {@code PnDTnHnMn.nS} */ String every() default ""; /** * Delays the time the trigger should start at. The value is rounded to full second. * <p> * By default, the trigger starts when registered. * * @return the initial delay */ long delay() default 0; /** * * @return the unit of initial delay * @see Scheduled#delay() */ TimeUnit delayUnit() default TimeUnit.MINUTES; /** * Defines a period after which the trigger should start. It's an alternative to {@link #delay()}. If {@link #delay()} is * set to a value greater than zero the value of {@link #delayed()} is ignored. * <p> * The value is parsed with {@link DurationConverter#parseDuration(String)}. Note that the absolute value of the value is * always used. * <p> * The value can be a property expression. In this case, the scheduler attempts to use the configured value instead: * {@code @Scheduled(delayed = "${myJob.delayedExpression}")}. * Additionally, the property expression can specify a default value: {@code @Scheduled(delayed = * "${myJob.delayedExpression:5m}")}. * * @return the period expression based on the ISO-8601 duration format {@code PnDTnHnMn.nS} */ String delayed() default ""; /** * Specify the strategy to handle concurrent execution of a scheduled method. By default, a scheduled method can be executed * concurrently. * * @return the concurrent execution strategy */ ConcurrentExecution concurrentExecution() default PROCEED; /** * Specify the predicate that can be used to skip an execution of a scheduled method. * <p> * The
Scheduled
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/bugs/creation/MockClassWithMissingStaticDepTest.java
{ "start": 1332, "end": 1593 }
class ____."); } catch (NoClassDefFoundError ex) { // Note: mock-maker-subclass will throw the NoClassDefFoundError as is assertThat(ex.getMessage()) .isEqualTo("Simulate missing transitive dependency used in
init
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/includeexclude/IncludeExcludeTest.java
{ "start": 611, "end": 1105 }
class ____ { @Test @WithClasses({ Foo.class, Bar.class, Baz.class }) @WithProcessorOption(key = HibernateProcessor.INCLUDE, value = "org.hibernate.processor.test.includeexclude.*") @WithProcessorOption(key = HibernateProcessor.EXCLUDE, value = "org.hibernate.processor.test.includeexclude.F*") void testQueryMethod() { assertNoMetamodelClassGeneratedFor( Foo.class ); assertMetamodelClassGeneratedFor( Bar.class ); assertNoMetamodelClassGeneratedFor( Baz.class ); } }
IncludeExcludeTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/RedundantNullCheckTest.java
{ "start": 9568, "end": 10029 }
class ____ { // Even though the lib is not @NullMarked, the @NonNull is explicit public static @NonNull String getString() { return "non-null"; } } """) .addSourceLines( "Test.java", """ import org.jspecify.annotations.NullMarked; import mylib.NonAnnotatedLibNonNull; @NullMarked
NonAnnotatedLibNonNull
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxWindowBoundary.java
{ "start": 2868, "end": 9951 }
class ____<T, U> implements InnerOperator<T, Flux<T>>, Disposable { final Supplier<? extends Queue<T>> processorQueueSupplier; final WindowBoundaryOther<U> boundary; final Queue<Object> queue; final CoreSubscriber<? super Flux<T>> actual; Sinks.Many<T> window; @SuppressWarnings("NotNullFieldNotInitialized") // s is set in onSubscribe volatile Subscription s; // https://github.com/uber/NullAway/issues/1157 @SuppressWarnings({"rawtypes", "DataFlowIssue"}) static final AtomicReferenceFieldUpdater<WindowBoundaryMain, @Nullable Subscription> S = AtomicReferenceFieldUpdater.newUpdater(WindowBoundaryMain.class, Subscription.class, "s"); volatile long requested; @SuppressWarnings("rawtypes") static final AtomicLongFieldUpdater<WindowBoundaryMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(WindowBoundaryMain.class, "requested"); volatile @Nullable Throwable error; // https://github.com/uber/NullAway/issues/1157 @SuppressWarnings({"rawtypes", "DataFlowIssue"}) static final AtomicReferenceFieldUpdater<WindowBoundaryMain, @Nullable Throwable> ERROR = AtomicReferenceFieldUpdater.newUpdater(WindowBoundaryMain.class, Throwable.class, "error"); volatile int cancelled; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<WindowBoundaryMain> CANCELLED = AtomicIntegerFieldUpdater.newUpdater(WindowBoundaryMain.class, "cancelled"); volatile int windowCount; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<WindowBoundaryMain> WINDOW_COUNT = AtomicIntegerFieldUpdater.newUpdater(WindowBoundaryMain.class, "windowCount"); volatile int wip; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<WindowBoundaryMain> WIP = AtomicIntegerFieldUpdater.newUpdater(WindowBoundaryMain.class, "wip"); boolean done; static final Object BOUNDARY_MARKER = new Object(); static final Object DONE = new Object(); WindowBoundaryMain(CoreSubscriber<? super Flux<T>> actual, Supplier<? extends Queue<T>> processorQueueSupplier, Queue<T> processorQueue) { this.actual = actual; this.processorQueueSupplier = processorQueueSupplier; this.window = Sinks.unsafe().many().unicast().onBackpressureBuffer(processorQueue, this); WINDOW_COUNT.lazySet(this, 2); this.boundary = new WindowBoundaryOther<>(this); this.queue = Queues.unboundedMultiproducer().get(); } @Override public final CoreSubscriber<? super Flux<T>> actual() { return actual; } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return s; if (key == Attr.ERROR) return error; if (key == Attr.CANCELLED) return cancelled == 1; if (key == Attr.TERMINATED) return done; if (key == Attr.PREFETCH) return Integer.MAX_VALUE; if (key == Attr.REQUESTED_FROM_DOWNSTREAM) return requested; if (key == Attr.BUFFERED) return queue.size(); if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return InnerOperator.super.scanUnsafe(key); } @Override public Stream<? extends Scannable> inners() { return Stream.of(boundary, Scannable.from(window)); } @Override public void onSubscribe(Subscription s) { if (Operators.setOnce(S, this, s)) { s.request(Long.MAX_VALUE); } } @Override public void onNext(T t) { if (done) { Operators.onNextDropped(t, actual.currentContext()); return; } synchronized (this) { queue.offer(t); } drain(); } @Override public void onError(Throwable t) { if (done) { Operators.onErrorDropped(t, actual.currentContext()); return; } done = true; boundary.cancel(); if (Exceptions.addThrowable(ERROR, this, t)) { drain(); } } @Override public void onComplete() { if (done) { return; } done = true; boundary.cancel(); synchronized (this) { queue.offer(DONE); } drain(); } @Override public void dispose() { if (WINDOW_COUNT.decrementAndGet(this) == 0) { cancelMain(); boundary.cancel(); } } @Override public boolean isDisposed() { return cancelled == 1 || done; } @Override public void request(long n) { if (Operators.validate(n)) { Operators.addCap(REQUESTED, this, n); } } void cancelMain() { Operators.terminate(S, this); } @Override public void cancel() { if (CANCELLED.compareAndSet(this, 0, 1)) { dispose(); } } void boundaryNext() { synchronized (this) { queue.offer(BOUNDARY_MARKER); } if (cancelled != 0) { boundary.cancel(); } drain(); } void boundaryError(Throwable e) { cancelMain(); if (Exceptions.addThrowable(ERROR, this, e)) { drain(); } else { Operators.onErrorDropped(e, actual.currentContext()); } } void boundaryComplete() { cancelMain(); synchronized (this) { queue.offer(DONE); } drain(); } void drain() { if (WIP.getAndIncrement(this) != 0) { return; } final Subscriber<? super Flux<T>> a = actual; final Queue<Object> q = queue; Sinks.Many<T> w = window; int missed = 1; for (;;) { for (;;) { if (error != null) { q.clear(); Throwable e = Exceptions.terminate(ERROR, this); if (e != Exceptions.TERMINATED) { // we just checked whether error was null, but we extract it via a proxy assert e != null; w.emitError(wrapSource(e), Sinks.EmitFailureHandler.FAIL_FAST); a.onError(e); } return; } Object o = q.poll(); if (o == null) { break; } if (o == DONE) { q.clear(); w.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST); a.onComplete(); return; } if (o != BOUNDARY_MARKER) { @SuppressWarnings("unchecked") T v = (T)o; w.emitNext(v, Sinks.EmitFailureHandler.FAIL_FAST); } if (o == BOUNDARY_MARKER) { w.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST); if (cancelled == 0) { if (requested != 0L) { Queue<T> pq = processorQueueSupplier.get(); WINDOW_COUNT.getAndIncrement(this); w = Sinks.unsafe().many().unicast().onBackpressureBuffer(pq, this); window = w; a.onNext(w.asFlux()); if (requested != Long.MAX_VALUE) { REQUESTED.decrementAndGet(this); } } else { q.clear(); cancelMain(); boundary.cancel(); a.onError(Exceptions.failWithOverflow("Could not create new window due to lack of requests")); return; } } } } missed = WIP.addAndGet(this, -missed); if (missed == 0) { break; } } } boolean emit(Sinks.Many<T> w) { long r = requested; if (r != 0L) { actual.onNext(w.asFlux()); if (r != Long.MAX_VALUE) { REQUESTED.decrementAndGet(this); } return true; } else { cancel(); actual.onError(Exceptions.failWithOverflow("Could not emit buffer due to lack of requests")); return false; } } } static final
WindowBoundaryMain
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/proxy/MyCoolServiceBean.java
{ "start": 859, "end": 1138 }
class ____ implements MyCoolService { @Override public String hello(String name) throws MyAppException { if ("Kaboom".equals(name)) { throw new MyAppException("Invalid name", "Kaboom"); } return "Hello " + name; } }
MyCoolServiceBean
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java
{ "start": 292830, "end": 293169 }
class ____ extends PicocliException { private static final long serialVersionUID = 4251973913816346114L; public TypeConversionException(final String msg) { super(msg); } } /** Exception indicating something went wrong while parsing command line options. */ public static
TypeConversionException
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/NamedParameterComment.java
{ "start": 1889, "end": 6421 }
enum ____ { /** The NamedParameterComment exactly matches the parameter name. */ EXACT_MATCH, /** The NamedParameterComment doesn't match the parameter name. */ BAD_MATCH, /** * There is no NamedParameterComment but a word in one of the other comments equals the * parameter name. */ APPROXIMATE_MATCH, /** There is no NamedParameterComment and no approximate matches */ NOT_ANNOTATED, } record MatchedComment(Optional<ErrorProneComment> comment, MatchType matchType) { static MatchedComment create(Optional<ErrorProneComment> comment, MatchType matchType) { return new MatchedComment(comment, matchType); } static MatchedComment notAnnotated() { return new MatchedComment(Optional.empty(), MatchType.NOT_ANNOTATED); } } private static boolean isApproximateMatchingComment(ErrorProneComment comment, String formal) { switch (comment.getStyle()) { case BLOCK, LINE -> { // sometimes people use comments around arguments for higher level structuring - such as // dividing two separate blocks of arguments. In these cases we want to avoid concluding // that it's a match. Therefore we also check to make sure that the comment is not really // long and that it doesn't contain acsii-art style markup. String commentText = Comments.getTextFromComment(comment); boolean textMatches = Arrays.asList(commentText.split("[^a-zA-Z0-9_]+", -1)).contains(formal); boolean tooLong = commentText.length() > formal.length() + 5 && commentText.length() > 50; boolean tooMuchMarkup = CharMatcher.anyOf("-*!@<>").countIn(commentText) > 5; return textMatches && !tooLong && !tooMuchMarkup; } default -> { return false; } } } /** * Determine the kind of match we have between the comments on this argument and the formal * parameter name. */ static MatchedComment match(Commented<ExpressionTree> actual, String formal) { Optional<ErrorProneComment> lastBlockComment = Streams.findLast( actual.beforeComments().stream() .filter(c -> c.getStyle() == ErrorProneCommentStyle.BLOCK)); if (lastBlockComment.isPresent()) { Matcher m = PARAMETER_COMMENT_PATTERN.matcher(Comments.getTextFromComment(lastBlockComment.get())); if (m.matches()) { return MatchedComment.create( lastBlockComment, m.group(1).equals(formal) ? MatchType.EXACT_MATCH : MatchType.BAD_MATCH); } } Optional<ErrorProneComment> approximateMatchComment = Stream.concat(actual.beforeComments().stream(), actual.afterComments().stream()) .filter(comment -> isApproximateMatchingComment(comment, formal)) .findFirst(); if (approximateMatchComment.isPresent()) { // Report EXACT_MATCH for comments that don't use the recommended style (e.g. `/*foo*/` // instead of `/* foo= */`), but which match the formal parameter name exactly, since it's // a style nit rather than a possible correctness issue. // TODO(cushon): revisit this if we standardize on the recommended comment style. String text = CharMatcher.anyOf("=:") .trimTrailingFrom(Comments.getTextFromComment(approximateMatchComment.get()).trim()); return MatchedComment.create( approximateMatchComment, text.equals(formal) ? MatchType.EXACT_MATCH : MatchType.APPROXIMATE_MATCH); } return MatchedComment.notAnnotated(); } /** * Generate comment text which {@code exactMatch} would consider to match the formal parameter * name. */ static String toCommentText(String formal) { return String.format("/* %s%s */", formal, PARAMETER_COMMENT_MARKER); } // Include: // * enclosing instance parameters, as javac doesn't account for parameters when associating // names (see b/64954766). // * synthetic constructor parameters, e.g. in anonymous classes (see b/65065109) private static final Pattern SYNTHETIC_PARAMETER_NAME = Pattern.compile("(arg|this\\$|x)[0-9]+"); /** * Returns true if the method has synthetic parameter names, indicating the real names are not * available. */ public static boolean containsSyntheticParameterName(MethodSymbol sym) { return sym.getParameters().stream() .anyMatch(p -> SYNTHETIC_PARAMETER_NAME.matcher(p.getSimpleName()).matches()); } private NamedParameterComment() {} }
MatchType
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/FirstLongByTimestampAggregatorFunctionTests.java
{ "start": 887, "end": 2848 }
class ____ extends AggregatorFunctionTestCase { @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { FirstLongByTimestampGroupingAggregatorFunctionTests.TimestampGen tsgen = randomFrom( FirstLongByTimestampGroupingAggregatorFunctionTests.TimestampGen.values() ); return new TupleLongLongBlockSourceOperator( blockFactory, IntStream.range(0, size).mapToObj(l -> Tuple.tuple(randomLong(), tsgen.gen())) ); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new FirstLongByTimestampAggregatorFunctionSupplier(); } @Override protected int inputCount() { return 2; } @Override protected String expectedDescriptionOfAggregator() { return "first_long_by_timestamp"; } @Override public void assertSimpleOutput(List<Page> input, Block result) { ExpectedWork work = new ExpectedWork(true); for (Page page : input) { LongBlock values = page.getBlock(0); LongBlock timestamps = page.getBlock(1); for (int p = 0; p < page.getPositionCount(); p++) { int tsStart = timestamps.getFirstValueIndex(p); int tsEnd = tsStart + timestamps.getValueCount(p); for (int tsOffset = tsStart; tsOffset < tsEnd; tsOffset++) { long timestamp = timestamps.getLong(tsOffset); int vStart = values.getFirstValueIndex(p); int vEnd = vStart + values.getValueCount(p); for (int vOffset = vStart; vOffset < vEnd; vOffset++) { long value = values.getLong(vOffset); work.add(timestamp, value); } } } } work.check(BlockUtils.toJavaObject(result, 0)); } }
FirstLongByTimestampAggregatorFunctionTests
java
elastic__elasticsearch
plugins/analysis-icu/src/test/java/org/elasticsearch/plugin/analysis/icu/SimpleIcuAnalysisTests.java
{ "start": 911, "end": 2123 }
class ____ extends ESTestCase { public void testDefaultsIcuAnalysis() throws IOException { TestAnalysis analysis = createTestAnalysis(new Index("test", "_na_"), Settings.EMPTY, new AnalysisICUPlugin()); TokenizerFactory tokenizerFactory = analysis.tokenizer.get("icu_tokenizer"); assertThat(tokenizerFactory, instanceOf(IcuTokenizerFactory.class)); TokenFilterFactory filterFactory = analysis.tokenFilter.get("icu_normalizer"); assertThat(filterFactory, instanceOf(IcuNormalizerTokenFilterFactory.class)); filterFactory = analysis.tokenFilter.get("icu_folding"); assertThat(filterFactory, instanceOf(IcuFoldingTokenFilterFactory.class)); filterFactory = analysis.tokenFilter.get("icu_collation"); assertThat(filterFactory, instanceOf(IcuCollationTokenFilterFactory.class)); filterFactory = analysis.tokenFilter.get("icu_transform"); assertThat(filterFactory, instanceOf(IcuTransformTokenFilterFactory.class)); CharFilterFactory charFilterFactory = analysis.charFilter.get("icu_normalizer"); assertThat(charFilterFactory, instanceOf(IcuNormalizerCharFilterFactory.class)); } }
SimpleIcuAnalysisTests
java
google__guava
android/guava/src/com/google/common/collect/Collections2.java
{ "start": 20987, "end": 23139 }
class ____<E> extends AbstractIterator<List<E>> { final List<E> list; final int[] c; final int[] o; int j; PermutationIterator(List<E> list) { this.list = new ArrayList<>(list); int n = list.size(); c = new int[n]; o = new int[n]; Arrays.fill(c, 0); Arrays.fill(o, 1); j = Integer.MAX_VALUE; } @Override protected @Nullable List<E> computeNext() { if (j <= 0) { return endOfData(); } ImmutableList<E> next = ImmutableList.copyOf(list); calculateNextPermutation(); return next; } void calculateNextPermutation() { j = list.size() - 1; int s = 0; // Handle the special case of an empty list. Skip the calculation of the // next permutation. if (j == -1) { return; } while (true) { int q = c[j] + o[j]; if (q < 0) { switchDirection(); continue; } if (q == j + 1) { if (j == 0) { break; } s++; switchDirection(); continue; } Collections.swap(list, j - c[j] + s, j - q + s); c[j] = q; break; } } void switchDirection() { o[j] = -o[j]; j--; } } /** Returns {@code true} if the second list is a permutation of the first. */ private static boolean isPermutation(List<?> first, List<?> second) { if (first.size() != second.size()) { return false; } ObjectCountHashMap<?> firstCounts = counts(first); ObjectCountHashMap<?> secondCounts = counts(second); if (first.size() != second.size()) { return false; } for (int i = 0; i < first.size(); i++) { if (firstCounts.getValue(i) != secondCounts.get(firstCounts.getKey(i))) { return false; } } return true; } private static <E extends @Nullable Object> ObjectCountHashMap<E> counts( Collection<E> collection) { ObjectCountHashMap<E> map = new ObjectCountHashMap<>(); for (E e : collection) { map.put(e, map.get(e) + 1); } return map; } }
PermutationIterator
java
apache__spark
sql/catalyst/src/test/java/org/apache/spark/sql/connector/catalog/CatalogLoadingSuite.java
{ "start": 7742, "end": 8083 }
class ____ implements CatalogPlugin { // fails in its constructor ConstructorFailureCatalogPlugin() { throw new RuntimeException("Expected failure."); } @Override public void initialize(String name, CaseInsensitiveStringMap options) { } @Override public String name() { return null; } }
ConstructorFailureCatalogPlugin
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java
{ "start": 9738, "end": 10626 }
class ____ test method (if requested) to build the name of the * transaction. * @param testContext the {@code TestContext} upon which to base the name * @param targetAttribute the {@code TransactionAttribute} to delegate to * @param includeMethodName {@code true} if the test method's name should be * included in the name of the transaction * @return the delegating {@code TransactionAttribute} * @since 6.1 */ public static TransactionAttribute createDelegatingTransactionAttribute( TestContext testContext, TransactionAttribute targetAttribute, boolean includeMethodName) { Assert.notNull(testContext, "TestContext must not be null"); Assert.notNull(targetAttribute, "Target TransactionAttribute must not be null"); return new TestContextTransactionAttribute(targetAttribute, testContext, includeMethodName); } @SuppressWarnings("serial") private static
and
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/ParentAnnotation.java
{ "start": 464, "end": 1052 }
class ____ implements Parent { /** * Used in creating dynamic annotation instances (e.g. from XML) */ public ParentAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public ParentAnnotation(Parent annotation, ModelsContext modelContext) { } /** * Used in creating annotation instances from Jandex variant */ public ParentAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { } @Override public Class<? extends Annotation> annotationType() { return Parent.class; } }
ParentAnnotation
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/Arrays_assertContains_Test.java
{ "start": 1483, "end": 7766 }
class ____ extends BaseArraysTest { @Test void should_pass_if_actual_contains_given_values() { arrays.assertContains(someInfo(), failures, actual, array("Luke")); } @Test void should_pass_if_actual_contains_given_values_in_different_order() { arrays.assertContains(someInfo(), failures, actual, array("Leia", "Yoda")); } @Test void should_pass_if_actual_contains_all_given_values() { arrays.assertContains(someInfo(), failures, actual, array("Luke", "Yoda", "Leia")); } @Test void should_pass_if_actual_contains_given_values_more_than_once() { actual = array("Luke", "Yoda", "Leia", "Luke", "Luke"); arrays.assertContains(someInfo(), failures, actual, array("Luke")); } @Test void should_pass_if_actual_contains_given_values_even_if_duplicated() { arrays.assertContains(someInfo(), failures, actual, array("Luke", "Luke")); } @Test void should_pass_if_actual_and_given_values_are_empty() { actual = new String[0]; arrays.assertContains(someInfo(), failures, actual, array()); } @Test void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), failures, actual, emptyArray())); } @Test void should_throw_error_if_array_of_values_to_look_for_is_null() { assertThatNullPointerException().isThrownBy(() -> arrays.assertContains(someInfo(), failures, actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), failures, null, array("Yoda"))) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_contain_values() { AssertionInfo info = someInfo(); Object[] expected = { "Leia", "Yoda", "John" }; Throwable error = catchThrowable(() -> arrays.assertContains(info, failures, actual, expected)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContain(actual, expected, newLinkedHashSet("John"))); } // ------------------------------------------------------------------------------------------------------------------ // tests using a custom comparison strategy // ------------------------------------------------------------------------------------------------------------------ @Test void should_pass_if_actual_contains_given_values_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, array("LUKE")); } @Test void should_pass_if_actual_contains_given_values_in_different_order_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, array("LEIA", "yODa")); } @Test void should_pass_if_actual_contains_all_given_values_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, array("luke", "YODA", "leia")); } @Test void should_pass_if_actual_contains_given_values_more_than_once_according_to_custom_comparison_strategy() { actual = array("Luke", "Yoda", "Leia", "Luke", "Luke"); arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, array("LUke")); } @Test void should_pass_if_actual_contains_given_values_even_if_duplicated_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, array("LUke", "LuKe")); } @Test void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, emptyArray())); } @Test void should_throw_error_if_array_of_values_to_look_for_is_null_whatever_custom_comparison_strategy_is() { assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), failures, null, array("LUke"))) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_contain_values_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Object[] expected = { "LeiA", "YODA", "JOhN" }; Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContains(info, failures, actual, expected)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContain(actual, expected, newLinkedHashSet("JOhN"), caseInsensitiveStringComparisonStrategy)); } }
Arrays_assertContains_Test
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/state/BackendSwitchSpecs.java
{ "start": 2704, "end": 2840 }
interface ____ creating a state backend that should be able to restore its state * from the given state handles. */ public
for
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticatorTests.java
{ "start": 2106, "end": 18923 }
class ____ extends AbstractAuthenticatorTests { private ThreadContext threadContext; private Realms realms; private RealmDomain domain1; private Realm realm1; private RealmDomain domain2; private Realm realm2; private RealmDomain domain3; private Realm realm3; private AuthenticationService.AuditableRequest request; private AuthenticationToken authenticationToken; private String username; private User user; private AtomicLong numInvalidation; private Cache<String, Realm> lastSuccessfulAuthCache; private String nodeName; private RealmsAuthenticator realmsAuthenticator; private TestTelemetryPlugin telemetryPlugin; private TestNanoTimeSupplier nanoTimeSupplier; @SuppressWarnings("unchecked") @Before public void init() throws Exception { threadContext = new ThreadContext(Settings.EMPTY); nodeName = randomAlphaOfLength(8); realms = mock(Realms.class); domain1 = randomFrom(new RealmDomain("domain1", Set.of()), null); realm1 = mock(Realm.class); when(realm1.name()).thenReturn("realm1"); when(realm1.type()).thenReturn("realm1"); when(realm1.toString()).thenReturn("realm1/realm1"); when(realm1.realmRef()).thenReturn(new Authentication.RealmRef("realm1", "realm1", nodeName, domain1)); domain2 = randomFrom(new RealmDomain("domain2", Set.of()), null); realm2 = mock(Realm.class); when(realm2.name()).thenReturn("realm2"); when(realm2.type()).thenReturn("realm2"); when(realm2.toString()).thenReturn("realm2/realm2"); when(realm2.realmRef()).thenReturn(new Authentication.RealmRef("realm2", "realm2", nodeName, domain2)); domain3 = randomFrom(new RealmDomain("domain3", Set.of()), null); realm3 = mock(Realm.class); when(realm3.toString()).thenReturn("realm3/realm3"); when(realms.getActiveRealms()).thenReturn(List.of(realm1, realm2)); when(realms.getUnlicensedRealms()).thenReturn(List.of(realm3)); when(realm3.realmRef()).thenReturn(new Authentication.RealmRef("realm3", "realm3", nodeName, domain3)); request = randomBoolean() ? mock(AuthenticationService.AuditableHttpRequest.class) : mock(AuthenticationService.AuditableTransportRequest.class); authenticationToken = mock(AuthenticationToken.class); username = randomAlphaOfLength(5); when(authenticationToken.principal()).thenReturn(username); user = new User(username); numInvalidation = new AtomicLong(); lastSuccessfulAuthCache = mock(Cache.class); telemetryPlugin = new TestTelemetryPlugin(); nanoTimeSupplier = new TestNanoTimeSupplier(randomLongBetween(0, 100)); realmsAuthenticator = new RealmsAuthenticator( numInvalidation, lastSuccessfulAuthCache, telemetryPlugin.getTelemetryProvider(Settings.EMPTY).getMeterRegistry(), nanoTimeSupplier ); } public void testExtractCredentials() { if (randomBoolean()) { when(realm1.token(threadContext)).thenReturn(authenticationToken); } else { when(realm2.token(threadContext)).thenReturn(authenticationToken); } assertThat(realmsAuthenticator.extractCredentials(createAuthenticatorContext()), is(authenticationToken)); } public void testWillAuditOnCredentialsExtractionFailure() { final RuntimeException cause = new RuntimeException("fail"); final ElasticsearchSecurityException wrapped = new ElasticsearchSecurityException("wrapped"); when(request.exceptionProcessingRequest(cause, null)).thenReturn(wrapped); doThrow(cause).when(randomBoolean() ? realm1 : realm2).token(threadContext); assertThat( expectThrows(ElasticsearchSecurityException.class, () -> realmsAuthenticator.extractCredentials(createAuthenticatorContext())), is(wrapped) ); } public void testAuthenticate() { when(lastSuccessfulAuthCache.get(username)).thenReturn(randomFrom(realm1, realm2, null)); final Realm successfulRealm, unsuccessfulRealm; if (randomBoolean()) { successfulRealm = realm1; unsuccessfulRealm = realm2; } else { successfulRealm = realm2; unsuccessfulRealm = realm1; } when(successfulRealm.supports(authenticationToken)).thenReturn(true); doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") final ActionListener<AuthenticationResult<User>> listener = (ActionListener<AuthenticationResult<User>>) invocationOnMock .getArguments()[1]; listener.onResponse(AuthenticationResult.success(user)); return null; }).when(successfulRealm).authenticate(eq(authenticationToken), any()); when(unsuccessfulRealm.supports(authenticationToken)).thenReturn(randomBoolean()); doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") final ActionListener<AuthenticationResult<User>> listener = (ActionListener<AuthenticationResult<User>>) invocationOnMock .getArguments()[1]; listener.onResponse(AuthenticationResult.unsuccessful("unsuccessful", null)); return null; }).when(unsuccessfulRealm).authenticate(eq(authenticationToken), any()); final Authenticator.Context context = createAuthenticatorContext(); context.addAuthenticationToken(authenticationToken); final PlainActionFuture<AuthenticationResult<Authentication>> future = new PlainActionFuture<>(); realmsAuthenticator.authenticate(context, future); final AuthenticationResult<Authentication> result = future.actionGet(); assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS)); final Authentication authentication = result.getValue(); assertThat(authentication.getEffectiveSubject().getUser(), is(user)); assertThat( authentication.getAuthenticatingSubject().getRealm(), is( new Authentication.RealmRef( successfulRealm.name(), successfulRealm.type(), nodeName, successfulRealm.realmRef().getDomain() ) ) ); } public void testNullUser() throws IllegalAccessException { if (randomBoolean()) { when(realm1.supports(authenticationToken)).thenReturn(true); configureRealmAuthResponse(realm1, AuthenticationResult.unsuccessful("unsuccessful", null)); } else { when(realm1.supports(authenticationToken)).thenReturn(false); } if (randomBoolean()) { when(realm2.supports(authenticationToken)).thenReturn(true); configureRealmAuthResponse(realm2, AuthenticationResult.unsuccessful("unsuccessful", null)); } else { when(realm2.supports(authenticationToken)).thenReturn(false); } final Authenticator.Context context = createAuthenticatorContext(); context.addAuthenticationToken(authenticationToken); final ElasticsearchSecurityException e = new ElasticsearchSecurityException("fail"); when(request.authenticationFailed(authenticationToken)).thenReturn(e); try (var mockLog = MockLog.capture(RealmsAuthenticator.class)) { mockLog.addExpectation( new MockLog.SeenEventExpectation( "unlicensed realms", RealmsAuthenticator.class.getName(), Level.WARN, "Authentication failed using realms [realm1/realm1,realm2/realm2]." + " Realms [realm3/realm3] were skipped because they are not permitted on the current license" ) ); final PlainActionFuture<AuthenticationResult<Authentication>> future = new PlainActionFuture<>(); realmsAuthenticator.authenticate(context, future); assertThat(expectThrows(ElasticsearchSecurityException.class, future::actionGet), is(e)); mockLog.assertAllExpectationsMatched(); } } public void testLookupRunAsUser() { when(lastSuccessfulAuthCache.get(username)).thenReturn(randomFrom(realm1, realm2, null)); final String runAsUsername = randomAlphaOfLength(10); threadContext.putHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, runAsUsername); final boolean lookupByRealm1 = randomBoolean(); if (lookupByRealm1) { configureRealmUserResponse(realm1, runAsUsername); configureRealmUserResponse(realm2, null); } else { configureRealmUserResponse(realm1, null); configureRealmUserResponse(realm2, runAsUsername); } final Realm authRealm = randomFrom(realm1, realm2); final Authentication authentication = Authentication.newRealmAuthentication(user, authRealm.realmRef()); final PlainActionFuture<Tuple<User, Realm>> future = new PlainActionFuture<>(); realmsAuthenticator.lookupRunAsUser(createAuthenticatorContext(), authentication, future); final Tuple<User, Realm> tuple = future.actionGet(); assertThat(tuple.v1(), equalTo(new User(runAsUsername))); assertThat(tuple.v2().name(), is(lookupByRealm1 ? realm1.name() : realm2.name())); assertThat(tuple.v2().realmRef(), is(lookupByRealm1 ? realm1.realmRef() : realm2.realmRef())); } public void testNullRunAsUser() { final PlainActionFuture<Tuple<User, Realm>> future = new PlainActionFuture<>(); realmsAuthenticator.lookupRunAsUser(createAuthenticatorContext(), AuthenticationTestHelper.builder().build(false), future); assertThat(future.actionGet(), nullValue()); } public void testEmptyRunAsUsernameWillFail() { threadContext.putHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, ""); final Realm authRealm = randomFrom(realm1, realm2); final Authentication authentication = Authentication.newRealmAuthentication(user, authRealm.realmRef()); final PlainActionFuture<Tuple<User, Realm>> future = new PlainActionFuture<>(); final ElasticsearchSecurityException e = new ElasticsearchSecurityException("fail"); when(request.runAsDenied(any(), any())).thenReturn(e); realmsAuthenticator.lookupRunAsUser(createAuthenticatorContext(), authentication, future); assertThat(expectThrows(ElasticsearchSecurityException.class, future::actionGet), is(e)); } public void testRecodingSuccessfulAuthenticationMetrics() { when(lastSuccessfulAuthCache.get(username)).thenReturn(randomFrom(realm1, realm2, null)); final Realm successfulRealm = randomFrom(realm1, realm2); when(successfulRealm.supports(authenticationToken)).thenReturn(true); final long successfulExecutionTimeInNanos = randomLongBetween(0, 500); doAnswer(invocationOnMock -> { nanoTimeSupplier.advanceTime(successfulExecutionTimeInNanos); @SuppressWarnings("unchecked") final ActionListener<AuthenticationResult<User>> listener = (ActionListener<AuthenticationResult<User>>) invocationOnMock .getArguments()[1]; listener.onResponse(AuthenticationResult.success(user)); return null; }).when(successfulRealm).authenticate(eq(authenticationToken), any()); final Authenticator.Context context = createAuthenticatorContext(); context.addAuthenticationToken(authenticationToken); final PlainActionFuture<AuthenticationResult<Authentication>> future = new PlainActionFuture<>(); realmsAuthenticator.authenticate(context, future); final AuthenticationResult<Authentication> result = future.actionGet(); assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS)); assertSingleSuccessAuthMetric( telemetryPlugin, SecurityMetricType.AUTHC_REALMS, Map.ofEntries( Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_NAME, successfulRealm.name()), Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_TYPE, successfulRealm.type()) ) ); assertZeroFailedAuthMetrics(telemetryPlugin, SecurityMetricType.AUTHC_REALMS); assertAuthenticationTimeMetric( telemetryPlugin, SecurityMetricType.AUTHC_REALMS, successfulExecutionTimeInNanos, Map.ofEntries( Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_NAME, successfulRealm.name()), Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_TYPE, successfulRealm.type()) ) ); } public void testRecordingFailedAuthenticationMetric() { when(lastSuccessfulAuthCache.get(username)).thenReturn(randomFrom(realm1, realm2, null)); final Realm unsuccessfulRealm; if (randomBoolean()) { when(realm1.supports(authenticationToken)).thenReturn(false); unsuccessfulRealm = realm2; } else { when(realm2.supports(authenticationToken)).thenReturn(false); unsuccessfulRealm = realm1; } when(unsuccessfulRealm.supports(authenticationToken)).thenReturn(true); final long unsuccessfulExecutionTimeInNanos = randomLongBetween(0, 500); doAnswer(invocationOnMock -> { nanoTimeSupplier.advanceTime(unsuccessfulExecutionTimeInNanos); @SuppressWarnings("unchecked") final ActionListener<AuthenticationResult<User>> listener = (ActionListener<AuthenticationResult<User>>) invocationOnMock .getArguments()[1]; listener.onResponse(AuthenticationResult.unsuccessful("unsuccessful realms authentication", null)); return null; }).when(unsuccessfulRealm).authenticate(eq(authenticationToken), any()); final Authenticator.Context context = createAuthenticatorContext(); final ElasticsearchSecurityException exception = new ElasticsearchSecurityException("realms authentication failed"); when(request.authenticationFailed(same(authenticationToken))).thenReturn(exception); context.addAuthenticationToken(authenticationToken); final PlainActionFuture<AuthenticationResult<Authentication>> future = new PlainActionFuture<>(); realmsAuthenticator.authenticate(context, future); var e = expectThrows(ElasticsearchSecurityException.class, () -> future.actionGet()); assertThat(e, sameInstance(exception)); assertSingleFailedAuthMetric( telemetryPlugin, SecurityMetricType.AUTHC_REALMS, Map.ofEntries( Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_NAME, unsuccessfulRealm.name()), Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_TYPE, unsuccessfulRealm.type()) ) ); assertZeroSuccessAuthMetrics(telemetryPlugin, SecurityMetricType.AUTHC_REALMS); assertAuthenticationTimeMetric( telemetryPlugin, SecurityMetricType.AUTHC_REALMS, unsuccessfulExecutionTimeInNanos, Map.ofEntries( Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_NAME, unsuccessfulRealm.name()), Map.entry(RealmsAuthenticator.ATTRIBUTE_REALM_TYPE, unsuccessfulRealm.type()) ) ); } private void configureRealmAuthResponse(Realm realm, AuthenticationResult<User> authenticationResult) { doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") final ActionListener<AuthenticationResult<User>> listener = (ActionListener<AuthenticationResult<User>>) invocationOnMock .getArguments()[1]; listener.onResponse(authenticationResult); return null; }).when(realm).authenticate(eq(authenticationToken), any()); } private void configureRealmUserResponse(Realm realm, String runAsUsername) { doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") final ActionListener<User> listener = (ActionListener<User>) invocationOnMock.getArguments()[1]; listener.onResponse(runAsUsername == null ? null : new User(runAsUsername)); return null; }).when(realm).lookupUser(runAsUsername == null ? anyString() : eq(runAsUsername), any()); } private Authenticator.Context createAuthenticatorContext() { return new Authenticator.Context(threadContext, request, null, true, realms); } }
RealmsAuthenticatorTests
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptorSecure.java
{ "start": 20291, "end": 20753 }
class ____ extends PolicyProvider { private MockRMPolicyProvider() { } private final Service[] resourceManagerServices = new Service[]{ new Service( YarnConfiguration.YARN_SECURITY_SERVICE_AUTHORIZATION_APPLICATIONCLIENT_PROTOCOL, ApplicationClientProtocolPB.class), }; @Override public Service[] getServices() { return resourceManagerServices; } } }
MockRMPolicyProvider
java
greenrobot__greendao
tests/DaoTestBase/src/main/java/org/greenrobot/greendao/daotest/IndexedStringEntityDao.java
{ "start": 784, "end": 4254 }
class ____ { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property IndexedString = new Property(1, String.class, "indexedString", false, "INDEXED_STRING"); } public IndexedStringEntityDao(DaoConfig config) { super(config); } public IndexedStringEntityDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"INDEXED_STRING_ENTITY\" (" + // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id "\"INDEXED_STRING\" TEXT);"); // 1: indexedString // Add Indexes db.execSQL("CREATE INDEX " + constraint + "IDX_INDEXED_STRING_ENTITY_INDEXED_STRING ON INDEXED_STRING_ENTITY" + " (\"INDEXED_STRING\");"); } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"INDEXED_STRING_ENTITY\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, IndexedStringEntity entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String indexedString = entity.getIndexedString(); if (indexedString != null) { stmt.bindString(2, indexedString); } } @Override protected final void bindValues(SQLiteStatement stmt, IndexedStringEntity entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String indexedString = entity.getIndexedString(); if (indexedString != null) { stmt.bindString(2, indexedString); } } @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } @Override public IndexedStringEntity readEntity(Cursor cursor, int offset) { IndexedStringEntity entity = new IndexedStringEntity( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1) // indexedString ); return entity; } @Override public void readEntity(Cursor cursor, IndexedStringEntity entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setIndexedString(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); } @Override protected final Long updateKeyAfterInsert(IndexedStringEntity entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(IndexedStringEntity entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(IndexedStringEntity entity) { return entity.getId() != null; } @Override protected final boolean isEntityUpdateable() { return true; } }
Properties
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/Employee.java
{ "start": 290, "end": 632 }
class ____ implements Serializable { private Integer id; private Collection employers; public Integer getId() { return id; } public void setId(Integer integer) { id = integer; } public Collection getEmployers() { return employers; } public void setEmployers(Collection employers) { this.employers = employers; } }
Employee
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/embeddable/JoinedSubclassWithEmbeddableTest.java
{ "start": 1441, "end": 2194 }
class ____ { @Test public void testSelectFromEmbeddedField(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createNativeQuery( "select * from employee_emb_person_map" ).getResultList(); } ); } @Test public void testSelectFromSubclass(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createNativeQuery( "select * from embeddable_person_map" ).getResultList(); } ); } @Test public void testSelectFromParent(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createNativeQuery( "select * from person_map" ).getResultList(); } ); } @Entity(name = "Person") @Inheritance(strategy = InheritanceType.JOINED) public static abstract
JoinedSubclassWithEmbeddableTest
java
apache__camel
components/camel-cxf/camel-cxf-spring-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/simplebinding/CxfRsConsumerSimpleBindingTest.java
{ "start": 2948, "end": 17640 }
class ____ extends CamelTestSupport { private static final String PORT_PATH = CXFTestSupport.getPort1() + "/CxfRsConsumerTest"; private static final String CXF_RS_ENDPOINT_URI = "cxfrs://http://localhost:" + PORT_PATH + "/rest?resourceClasses=org.apache.camel.component.cxf.jaxrs.simplebinding.testbean.CustomerServiceResource&bindingStyle=SimpleConsumer"; private JAXBContext jaxb; private CloseableHttpClient httpclient; @Override public void setupResources() throws Exception { httpclient = HttpClientBuilder.create().build(); jaxb = JAXBContext.newInstance(CustomerList.class, Customer.class, Order.class, Product.class); } @Override public void cleanupResources() throws Exception { httpclient.close(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from(CXF_RS_ENDPOINT_URI) .recipientList(simple("direct:${header.operationName}")); from("direct:getCustomer").process(new Processor() { public void process(Exchange exchange) throws Exception { assertNotNull(exchange.getIn().getHeader("id")); long id = exchange.getIn().getHeader("id", Long.class); if (id == 123) { assertEquals("123", exchange.getIn().getHeader("id")); assertEquals(MessageContentsList.class, exchange.getIn().getBody().getClass()); exchange.getMessage().setBody(new Customer(123, "Raul")); exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 200); } else if (id == 456) { exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 404); } else { fail(); } } }); from("direct:updateCustomer").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("123", exchange.getIn().getHeader("id")); Customer c = exchange.getIn().getBody(Customer.class); assertEquals(123, c.getId()); assertNotNull(c); } }); from("direct:newCustomer").process(new Processor() { public void process(Exchange exchange) throws Exception { Customer c = exchange.getIn().getBody(Customer.class); assertNotNull(c); assertEquals(123, c.getId()); } }); from("direct:listVipCustomers").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("gold", exchange.getIn().getHeader("status", String.class)); assertEquals(MessageContentsList.class, exchange.getIn().getBody().getClass()); assertEquals(0, exchange.getIn().getBody(MessageContentsList.class).size()); CustomerList response = new CustomerList(); List<Customer> list = new ArrayList<>(2); list.add(new Customer(123, "Raul")); list.add(new Customer(456, "Raul2")); response.setCustomers(list); exchange.getMessage().setBody(response); } }); from("direct:updateVipCustomer").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("gold", exchange.getIn().getHeader("status", String.class)); assertEquals("123", exchange.getIn().getHeader("id")); Customer c = exchange.getIn().getBody(Customer.class); assertEquals(123, c.getId()); assertNotNull(c); } }); from("direct:deleteVipCustomer").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("gold", exchange.getIn().getHeader("status", String.class)); assertEquals("123", exchange.getIn().getHeader("id")); } }); from("direct:uploadImageInputStream").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("123", exchange.getIn().getHeader("id")); assertEquals("image/jpeg", exchange.getIn().getHeader("Content-Type")); assertTrue(InputStream.class.isAssignableFrom(exchange.getIn().getBody().getClass())); InputStream is = exchange.getIn().getBody(InputStream.class); is.close(); exchange.getMessage().setBody(null); } }); from("direct:uploadImageDataHandler").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("123", exchange.getIn().getHeader("id")); assertEquals("image/jpeg", exchange.getIn().getHeader("Content-Type")); assertTrue(DataHandler.class.isAssignableFrom(exchange.getIn().getBody().getClass())); DataHandler dh = exchange.getIn().getBody(DataHandler.class); assertEquals("image/jpeg", dh.getContentType()); dh.getInputStream().close(); exchange.getMessage().setBody(null); } }); from("direct:multipartPostWithParametersAndPayload").process(new Processor() { public void process(Exchange exchange) throws Exception { assertEquals("abcd", exchange.getIn().getHeader("query")); assertEquals("123", exchange.getIn().getHeader("id")); assertNotNull(exchange.getIn(AttachmentMessage.class).getAttachment("part1")); assertNotNull(exchange.getIn(AttachmentMessage.class).getAttachment("part2")); assertNull(exchange.getIn().getHeader("part1")); assertNull(exchange.getIn().getHeader("part2")); assertEquals(Customer.class, exchange.getIn().getHeader("body").getClass()); exchange.getMessage().setBody(null); } }); from("direct:multipartPostWithoutParameters").process(new Processor() { public void process(Exchange exchange) throws Exception { assertNotNull(exchange.getIn(AttachmentMessage.class).getAttachment("part1")); assertNotNull(exchange.getIn(AttachmentMessage.class).getAttachment("part2")); assertNull(exchange.getIn().getHeader("part1")); assertNull(exchange.getIn().getHeader("part2")); assertEquals(Customer.class, exchange.getIn().getHeader("body").getClass()); exchange.getMessage().setBody(null); } }); } }; } @Test public void testGetCustomerOnlyHeaders() throws Exception { HttpGet get = new HttpGet("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/123"); get.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(get); assertEquals(200, response.getCode()); Customer entity = (Customer) jaxb.createUnmarshaller().unmarshal(response.getEntity().getContent()); assertEquals(123, entity.getId()); } @Test public void testGetCustomerHttp404CustomStatus() throws Exception { HttpGet get = new HttpGet("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/456"); get.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(get); assertEquals(404, response.getCode()); } @Test public void testUpdateCustomerBodyAndHeaders() throws Exception { HttpPut put = new HttpPut("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/123"); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw); put.setEntity(new StringEntity(sw.toString())); put.addHeader("Content-Type", "text/xml"); put.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(put); assertEquals(200, response.getCode()); } @Test public void testNewCustomerOnlyBody() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers"); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw); post.setEntity(new StringEntity(sw.toString())); post.addHeader("Content-Type", "text/xml"); post.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(post); assertEquals(200, response.getCode()); } @Test public void testListVipCustomers() throws Exception { HttpGet get = new HttpGet("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/vip/gold"); get.addHeader("Content-Type", "text/xml"); get.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(get); assertEquals(200, response.getCode()); CustomerList cl = (CustomerList) jaxb.createUnmarshaller() .unmarshal(new StringReader(EntityUtils.toString(response.getEntity()))); List<Customer> vips = cl.getCustomers(); assertEquals(2, vips.size()); assertEquals(123, vips.get(0).getId()); assertEquals(456, vips.get(1).getId()); } @Test public void testUpdateVipCustomer() throws Exception { HttpPut put = new HttpPut("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/vip/gold/123"); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul2"), sw); put.setEntity(new StringEntity(sw.toString())); put.addHeader("Content-Type", "text/xml"); put.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(put); assertEquals(200, response.getCode()); } @Test public void testDeleteVipCustomer() throws Exception { HttpDelete delete = new HttpDelete("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/vip/gold/123"); delete.addHeader("Accept", "text/xml"); CloseableHttpResponse response = httpclient.execute(delete); assertEquals(200, response.getCode()); } @Test public void testUploadInputStream() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/123/image_inputstream"); post.addHeader("Content-Type", "image/jpeg"); post.addHeader("Accept", "text/xml"); post.setEntity(new InputStreamEntity(this.getClass().getClassLoader().getResourceAsStream("java.jpg"), 100, null)); CloseableHttpResponse response = httpclient.execute(post); assertEquals(200, response.getCode()); } @Test public void testUploadDataHandler() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/123/image_datahandler"); post.addHeader("Content-Type", "image/jpeg"); post.addHeader("Accept", "text/xml"); post.setEntity(new InputStreamEntity(this.getClass().getClassLoader().getResourceAsStream("java.jpg"), 100, null)); CloseableHttpResponse response = httpclient.execute(post); assertEquals(200, response.getCode()); } @Test public void testMultipartPostWithParametersAndPayload() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/123?query=abcd"); MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT); builder.addBinaryBody("part1", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg"); builder.addBinaryBody("part2", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg"); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw); builder.addTextBody("body", sw.toString(), ContentType.TEXT_XML); post.setEntity(builder.build()); CloseableHttpResponse response = httpclient.execute(post); assertEquals(200, response.getCode()); } @Test public void testMultipartPostWithoutParameters() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/withoutParameters"); MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT); builder.addBinaryBody("part1", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg"); builder.addBinaryBody("part2", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg"); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw); builder.addTextBody("body", sw.toString(), ContentType.TEXT_XML); post.setEntity(builder.build()); CloseableHttpResponse response = httpclient.execute(post); assertEquals(200, response.getCode()); } }
CxfRsConsumerSimpleBindingTest
java
grpc__grpc-java
alts/src/main/java/io/grpc/alts/AltsServerCredentials.java
{ "start": 1275, "end": 1683 }
class ____ { private static final Logger logger = Logger.getLogger(AltsServerCredentials.class.getName()); private AltsServerCredentials() {} public static ServerCredentials create() { return newBuilder().build(); } public static Builder newBuilder() { return new Builder(); } @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") public static final
AltsServerCredentials
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/SpliteratorTester.java
{ "start": 2110, "end": 2245 }
class ____<E extends @Nullable Object> { /** Return type from "contains the following elements" assertions. */ public
SpliteratorTester
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java
{ "start": 8357, "end": 9349 }
class ____ extends ThriftContainer { public final ThriftObject elementData; ThriftSet( ThriftObject parent, TFieldIdEnum fieldId, FieldMetaData data, List<ThriftField> fields) { super(parent, fieldId, data); this.elementData = ThriftObject.Factory.createNew( this, FieldTypeEnum.SET_ELEMENT, new FieldMetaData( getSubElementName(fieldId), TFieldRequirementType.REQUIRED, ((SetMetaData) data.valueMetaData).elemMetaData), fields); } @Override public boolean hasUnion() { return this.elementData instanceof ThriftUnion; } @Override protected void toPrettyString(StringBuilder sb, int level) { this.append(sb, "%sset<\n", this.getIndent(level)); this.elementData.toPrettyString(sb, level + 1); this.append(sb, "%s> %s;\n", this.getIndent(level), this.getName()); } } public static
ThriftSet
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/share/persister/ReadShareGroupStateSummaryParameters.java
{ "start": 2363, "end": 3285 }
class ____ { private GroupTopicPartitionData<PartitionIdLeaderEpochData> groupTopicPartitionData; public Builder setGroupTopicPartitionData(GroupTopicPartitionData<PartitionIdLeaderEpochData> groupTopicPartitionData) { this.groupTopicPartitionData = groupTopicPartitionData; return this; } public ReadShareGroupStateSummaryParameters build() { return new ReadShareGroupStateSummaryParameters(groupTopicPartitionData); } } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; ReadShareGroupStateSummaryParameters that = (ReadShareGroupStateSummaryParameters) o; return Objects.equals(groupTopicPartitionData, that.groupTopicPartitionData); } @Override public int hashCode() { return Objects.hashCode(groupTopicPartitionData); } }
Builder
java
netty__netty
transport-sctp/src/main/java/io/netty/handler/codec/sctp/SctpOutboundByteStreamHandler.java
{ "start": 1142, "end": 2524 }
class ____ extends MessageToMessageEncoder<ByteBuf> { private final int streamIdentifier; private final int protocolIdentifier; private final boolean unordered; /** * @param streamIdentifier stream number, this should be >=0 or <= max stream number of the association. * @param protocolIdentifier supported application protocol id. */ public SctpOutboundByteStreamHandler(int streamIdentifier, int protocolIdentifier) { this(streamIdentifier, protocolIdentifier, false); } /** * @param streamIdentifier stream number, this should be >=0 or <= max stream number of the association. * @param protocolIdentifier supported application protocol id. * @param unordered if {@literal true}, SCTP Data Chunks will be sent with the U (unordered) flag set. */ public SctpOutboundByteStreamHandler(int streamIdentifier, int protocolIdentifier, boolean unordered) { super(ByteBuf.class); this.streamIdentifier = streamIdentifier; this.protocolIdentifier = protocolIdentifier; this.unordered = unordered; } @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(new SctpMessage(protocolIdentifier, streamIdentifier, unordered, msg.retain())); } }
SctpOutboundByteStreamHandler
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PutTrainedModelAction.java
{ "start": 1165, "end": 1758 }
class ____ extends ActionType<PutTrainedModelAction.Response> { public static final String DEFER_DEFINITION_DECOMPRESSION = "defer_definition_decompression"; public static final PutTrainedModelAction INSTANCE = new PutTrainedModelAction(); public static final String NAME = "cluster:admin/xpack/ml/inference/put"; public static final String MODEL_ALREADY_EXISTS_ERROR_MESSAGE_FRAGMENT = "the model id is the same as the deployment id of a current model deployment"; private PutTrainedModelAction() { super(NAME); } public static
PutTrainedModelAction
java
dropwizard__dropwizard
dropwizard-testing/src/main/java/io/dropwizard/testing/junit5/ResourceExtension.java
{ "start": 637, "end": 2691 }
class ____ extends Resource.Builder<Builder> { /** * Builds a {@link ResourceExtension} with a configured Jersey testing environment. * * @return a new {@link ResourceExtension} */ public ResourceExtension build() { return new ResourceExtension(buildResource()); } } /** * Creates a new Jersey testing environment builder for {@link ResourceExtension} * * @return a new {@link Builder} */ public static Builder builder() { return new Builder(); } private final Resource resource; private ResourceExtension(Resource resource) { this.resource = resource; } public Validator getValidator() { return resource.getValidator(); } public ObjectMapper getObjectMapper() { return resource.getObjectMapper(); } public Consumer<ClientConfig> getClientConfigurator() { return resource.getClientConfigurator(); } /** * Creates a web target to be sent to the resource under testing. * * @param path relative path (from tested application base URI) this web target should point to. * @return the created JAX-RS web target. */ public WebTarget target(String path) { return resource.target(path); } /** * Returns the pre-configured {@link Client} for this test. For sending * requests prefer {@link #target(String)} * * @return the {@link JerseyTest} configured {@link Client} */ public Client client() { return resource.client(); } /** * Returns the underlying {@link JerseyTest}. For sending requests prefer * {@link #target(String)}. * * @return the underlying {@link JerseyTest} */ public JerseyTest getJerseyTest() { return resource.getJerseyTest(); } @Override public void before() throws Throwable { resource.before(); } @Override public void after() throws Throwable { resource.after(); } }
Builder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/jdk8/OptionalTest.java
{ "start": 2639, "end": 2999 }
class ____ { @JsonSerialize(contentUsing=UpperCasingSerializer.class) @JsonDeserialize(contentUsing=LowerCasingDeserializer.class) public Optional<String> value; CaseChangingStringWrapper() { } public CaseChangingStringWrapper(String s) { value = Optional.ofNullable(s); } } public static
CaseChangingStringWrapper
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/ContainerLogContext.java
{ "start": 1120, "end": 1991 }
class ____ { private final ContainerId containerId; private final ContainerType containerType; private int exitCode; @Public @Unstable public ContainerLogContext(ContainerId containerId, ContainerType containerType, int exitCode) { this.containerId = containerId; this.containerType = containerType; this.exitCode = exitCode; } /** * Get {@link ContainerId} of the container. * * @return the container ID */ public ContainerId getContainerId() { return containerId; } /** * Get {@link ContainerType} the type of the container. * * @return the type of the container */ public ContainerType getContainerType() { return containerType; } /** * Get the exit code of the container. * * @return the exit code */ public int getExitCode() { return exitCode; } }
ContainerLogContext
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/StateUtilTest.java
{ "start": 1376, "end": 2667 }
class ____ { @Test void testDiscardStateSize() throws Exception { assertThat(discardStateFuture(completedFuture(new TestStateObject(1234, 123)))) .isEqualTo(Tuple2.of(1234L, 123L)); Tuple2<Long, Long> zeroSize = Tuple2.of(0L, 0L); assertThat(discardStateFuture(null)).isEqualTo(zeroSize); assertThat(discardStateFuture(new CompletableFuture<>())).isEqualTo(zeroSize); assertThat(discardStateFuture(completedExceptionally(new RuntimeException()))) .isEqualTo(zeroSize); assertThat(discardStateFuture(emptyFuture(false, true))).isEqualTo(zeroSize); assertThat(discardStateFuture(emptyFuture(false, false))).isEqualTo(zeroSize); assertThat(discardStateFuture(emptyFuture(true, true))).isEqualTo(zeroSize); assertThat(discardStateFuture(emptyFuture(true, false))).isEqualTo(zeroSize); } @Test void unexpectedStateExceptionForSingleExpectedType() { Exception exception = StateUtil.unexpectedStateHandleException( KeyGroupsStateHandle.class, KeyGroupsStateHandle.class); assertThat(exception.getMessage()) .contains( "Unexpected state handle type, expected one of:
StateUtilTest
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/TimelineKeyValuesFilter.java
{ "start": 1238, "end": 3527 }
class ____ extends TimelineFilter { private TimelineCompareOp compareOp; private String key; private Set<Object> values; public TimelineKeyValuesFilter() { } public TimelineKeyValuesFilter(TimelineCompareOp op, String key, Set<Object> values) { if (op != TimelineCompareOp.EQUAL && op != TimelineCompareOp.NOT_EQUAL) { throw new IllegalArgumentException("TimelineCompareOp for multi value " + "equality filter should be EQUAL or NOT_EQUAL"); } this.compareOp = op; this.key = key; this.values = values; } @Override public TimelineFilterType getFilterType() { return TimelineFilterType.KEY_VALUES; } public String getKey() { return key; } public Set<Object> getValues() { return values; } public void setKeyAndValues(String keyForValues, Set<Object> vals) { key = keyForValues; values = vals; } public void setCompareOp(TimelineCompareOp op) { compareOp = op; } public TimelineCompareOp getCompareOp() { return compareOp; } @Override public String toString() { return String.format("%s (%s, %s:%s)", this.getClass().getSimpleName(), this.compareOp.name(), this.key, (values == null) ? "" : values.toString()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((compareOp == null) ? 0 : compareOp.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((values == null) ? 0 : values.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; } TimelineKeyValuesFilter other = (TimelineKeyValuesFilter) obj; if (compareOp != other.compareOp) { return false; } if (key == null) { if (other.key != null) { return false; } } else if (!key.equals(other.key)) { return false; } if (values == null) { if (other.values != null) { return false; } } else if (!values.equals(other.values)) { return false; } return true; } }
TimelineKeyValuesFilter
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/proxy/AbstractGlobalProxyPasswordTest.java
{ "start": 263, "end": 842 }
class ____ extends ProxyTestBase { protected static QuarkusUnitTest config(String applicationProperties) { return new QuarkusUnitTest() .withApplicationRoot( jar -> jar.addClasses(Client1.class, ViaHeaderReturningResource.class)) .withConfigurationResource(applicationProperties); } @RestClient Client1 client1; @Test void shouldProxyCDIWithPerClientSettings() { assertThat(client1.get().readEntity(String.class)).isEqualTo(AUTHENTICATED_PROXY); } }
AbstractGlobalProxyPasswordTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileChangedZeroLengthReadLockTest.java
{ "start": 1069, "end": 1983 }
class ____ extends ContextTestSupport { @Test public void testChangedReadLock() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedFileExists(testFile("out/zerofile.dat")); writeZeroLengthFile(); assertMockEndpointsSatisfied(); } private void writeZeroLengthFile() throws Exception { Files.write(testFile("in/zerofile.dat"), new byte[0]); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(fileUri("in?initialDelay=0&delay=10&readLock=changed&readLockCheckInterval=100&readLockMinLength=0")) .to(fileUri("out"), "mock:result"); } }; } }
FileChangedZeroLengthReadLockTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/ICounter.java
{ "start": 703, "end": 831 }
interface ____ { void increment(); void decrement(); int getCount(); void setCount(int counter); void reset(); }
ICounter
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java
{ "start": 40390, "end": 41046 }
class ____ { @Order(1) public static FactoryBean<NumberStore<Double>> newDoubleStore() { return new FactoryBean<>() { @Override public NumberStore<Double> getObject() { return new DoubleStore(); } @Override public Class<?> getObjectType() { return DoubleStore.class; } }; } @Order(0) public static FactoryBean<NumberStore<Float>> newFloatStore() { return new FactoryBean<>() { @Override public NumberStore<Float> getObject() { return new FloatStore(); } @Override public Class<?> getObjectType() { return FloatStore.class; } }; } } public
NumberStoreFactoryBeans
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/error/uri/ShouldHaveNoHost_create_Test.java
{ "start": 1182, "end": 2403 }
class ____ { @Test void should_create_error_message_with_URI() throws URISyntaxException { // GIVEN ErrorMessageFactory underTest = shouldHaveNoHost(new URI("https://example.com")); // WHEN String message = underTest.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting no host for:%n" + " https://example.com%n" + "but found:%n" + " \"example.com\"")); } @Test void should_create_error_message_with_URL() throws MalformedURLException { // GIVEN ErrorMessageFactory underTest = shouldHaveNoHost(new URL("https://example.com")); // WHEN String message = underTest.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting no host for:%n" + " https://example.com%n" + "but found:%n" + " \"example.com\"")); } }
ShouldHaveNoHost_create_Test
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/DataTypeExtractorTest.java
{ "start": 37836, "end": 37926 }
class ____<T> extends TableFunction<T[]> {} private static
TableFunctionWithGenericArray0
java
google__guava
android/guava/src/com/google/common/reflect/Types.java
{ "start": 20519, "end": 24595 }
enum ____ { JAVA6 { @Override GenericArrayType newArrayType(Type componentType) { return new GenericArrayTypeImpl(componentType); } @Override Type usedInGenericType(Type type) { checkNotNull(type); if (type instanceof Class) { Class<?> cls = (Class<?>) type; if (cls.isArray()) { return new GenericArrayTypeImpl(cls.getComponentType()); } } return type; } }, JAVA7 { @Override Type newArrayType(Type componentType) { if (componentType instanceof Class) { return getArrayClass((Class<?>) componentType); } else { return new GenericArrayTypeImpl(componentType); } } @Override Type usedInGenericType(Type type) { return checkNotNull(type); } }, JAVA8 { @Override Type newArrayType(Type componentType) { return JAVA7.newArrayType(componentType); } @Override Type usedInGenericType(Type type) { return JAVA7.usedInGenericType(type); } /* * We use this only when getTypeName is available. * * Well, really, we use this when we think we're running under Java 8, as determined by some * logic in the static initializer, which does not check for getTypeName specifically. We * should really validate that it works as desired for all Android versions that we support. */ @IgnoreJRERequirement @SuppressWarnings("NewApi") @Override String typeName(Type type) { return type.getTypeName(); } }, JAVA9 { @Override Type newArrayType(Type componentType) { return JAVA8.newArrayType(componentType); } @Override Type usedInGenericType(Type type) { return JAVA8.usedInGenericType(type); } @IgnoreJRERequirement @SuppressWarnings("NewApi") // see JAVA8.typeName @Override String typeName(Type type) { return type.getTypeName(); } @Override boolean jdkTypeDuplicatesOwnerName() { return false; } }; static final JavaVersion CURRENT; static { // Under Android, TypeVariable does not implement AnnotatedElement even under recent versions. if (AnnotatedElement.class.isAssignableFrom(TypeVariable.class)) { if (new TypeCapture<Entry<String, int[][]>>() {}.capture() .toString() .contains("java.util.Map.java.util.Map")) { CURRENT = JAVA8; } else { CURRENT = JAVA9; } } else if (new TypeCapture<int[]>() {}.capture() instanceof Class) { CURRENT = JAVA7; } else { CURRENT = JAVA6; } } abstract Type newArrayType(Type componentType); abstract Type usedInGenericType(Type type); final ImmutableList<Type> usedInGenericType(Type[] types) { ImmutableList.Builder<Type> builder = ImmutableList.builder(); for (Type type : types) { builder.add(usedInGenericType(type)); } return builder.build(); } String typeName(Type type) { return Types.toString(type); } boolean jdkTypeDuplicatesOwnerName() { return true; } } /** * Per <a href="https://github.com/google/guava/issues/1635">issue 1635</a>, In JDK 1.7.0_51-b13, * {@link TypeVariableImpl#equals(Object)} is changed to no longer be equal to custom TypeVariable * implementations. As a result, we need to make sure our TypeVariable implementation respects * symmetry. Moreover, we don't want to reconstruct a native type variable {@code <A>} using our * implementation unless some of its bounds have changed in resolution. This avoids creating * unequal TypeVariable implementation unnecessarily. When the bounds do change, however, it's * fine for the synthetic TypeVariable to be unequal to any native TypeVariable anyway. */ @SuppressWarnings("UnusedTypeParameter") // It's used reflectively. static final
JavaVersion
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractClientSockJsSession.java
{ "start": 10381, "end": 10426 }
enum ____ { NEW, OPEN, CLOSING, CLOSED } }
State
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/main/java/org/hibernate/processor/xml/XmlMetaCollection.java
{ "start": 230, "end": 603 }
class ____ extends XmlMetaAttribute implements MetaCollection { private String collectionType; public XmlMetaCollection(XmlMetaEntity parent, String propertyName, String type, String collectionType) { super( parent, propertyName, type ); this.collectionType = collectionType; } @Override public String getMetaType() { return collectionType; } }
XmlMetaCollection
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/monitoring/MonitoringField.java
{ "start": 478, "end": 1350 }
class ____ { /** * The minimum amount of time allowed for the history duration. */ public static final TimeValue HISTORY_DURATION_MINIMUM = TimeValue.timeValueHours(24); /** * The default retention duration of the monitoring history data. * <p> * Expected values: * <ul> * <li>Default: 7 days</li> * <li>Minimum: 1 day</li> * </ul> * * @see MonitoringField#HISTORY_DURATION_MINIMUM */ public static final Setting<TimeValue> HISTORY_DURATION = timeSetting( "xpack.monitoring.history.duration", TimeValue.timeValueHours(7 * 24), // default value (7 days) HISTORY_DURATION_MINIMUM, // minimum value Setting.Property.Dynamic, Setting.Property.NodeScope, Setting.Property.DeprecatedWarning ); private MonitoringField() {} }
MonitoringField
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/MatchingIdSelectionHelper.java
{ "start": 3047, "end": 12829 }
class ____ { private static final Logger LOG = Logger.getLogger( MatchingIdSelectionHelper.class ); /// Generates a query-spec for selecting all ids matching the restriction defined as part /// of the user's update/delete query. This query-spec is generally used: /// /// * to select all the matching ids via JDBC - see {@link MatchingIdSelectionHelper#selectMatchingIds} /// * as a sub-query restriction to insert rows into an "id table" public static SelectStatement generateMatchingIdSelectStatement( EntityMappingType targetEntityDescriptor, SqmDeleteOrUpdateStatement<?> sqmStatement, boolean queryRoot, Predicate restriction, MultiTableSqmMutationConverter sqmConverter, DomainQueryExecutionContext executionContext) { final EntityDomainType<?> entityDomainType = sqmStatement.getTarget().getModel(); if ( LOG.isTraceEnabled() ) { LOG.tracef( "Starting generation of entity-id SQM selection - %s", entityDomainType.getHibernateEntityName() ); } final QuerySpec idSelectionQuery = new QuerySpec( queryRoot, 1 ); idSelectionQuery.applyPredicate( restriction ); final TableGroup mutatingTableGroup = sqmConverter.getMutatingTableGroup(); idSelectionQuery.getFromClause().addRoot( mutatingTableGroup ); final List<DomainResult<?>> domainResults = new ArrayList<>(); sqmConverter.getProcessingStateStack().push( new SqlAstQueryPartProcessingStateImpl( idSelectionQuery, sqmConverter.getCurrentProcessingState(), sqmConverter.getSqlAstCreationState(), sqmConverter.getCurrentClauseStack()::getCurrent, false ) ); targetEntityDescriptor.getIdentifierMapping().applySqlSelections( mutatingTableGroup.getNavigablePath(), mutatingTableGroup, sqmConverter, (selection, jdbcMapping) -> domainResults.add( new BasicResult<>( selection.getValuesArrayPosition(), null, jdbcMapping ) ) ); sqmConverter.getProcessingStateStack().pop(); targetEntityDescriptor.getEntityPersister().applyBaseRestrictions( idSelectionQuery::applyPredicate, mutatingTableGroup, true, executionContext.getSession().getLoadQueryInfluencers().getEnabledFilters(), false, null, sqmConverter ); return new SelectStatement( idSelectionQuery, domainResults ); } /// Generates a query-spec for selecting all ids matching the restriction defined as part /// of the user's update/delete query. This query-spec is generally used: /// /// * to select all the matching ids via JDBC - see {@link MatchingIdSelectionHelper#selectMatchingIds} /// * as a sub-query restriction to insert rows into an "id table" public static SqmSelectStatement<?> generateMatchingIdSelectStatement( SqmDeleteOrUpdateStatement<?> sqmStatement, EntityMappingType entityDescriptor) { final NodeBuilder nodeBuilder = sqmStatement.nodeBuilder(); final SqmQuerySpec<Object[]> sqmQuerySpec = new SqmQuerySpec<>( nodeBuilder ); sqmQuerySpec.setFromClause( new SqmFromClause( 1 ) ); sqmQuerySpec.addRoot( sqmStatement.getTarget() ); sqmQuerySpec.setSelectClause( new SqmSelectClause( false, 1, sqmQuerySpec.nodeBuilder() ) ); entityDescriptor.getIdentifierMapping() .forEachSelectable( 0, (selectionIndex, selectableMapping) -> sqmQuerySpec.getSelectClause().addSelection( SelectableMappingExpressionConverter.forSelectableMapping( sqmStatement.getTarget(), selectableMapping ) )); sqmQuerySpec.setWhereClause( sqmStatement.getWhereClause() ); return new SqmSelectStatement<>( sqmQuerySpec, Object[].class, SqmQuerySource.CRITERIA, nodeBuilder ); } /** * Centralized selection of ids matching the restriction of the DELETE * or UPDATE SQM query */ public static CacheableSqmInterpretation<SelectStatement, JdbcOperationQuerySelect> createMatchingIdsSelect( SqmDeleteOrUpdateStatement<?> sqmMutationStatement, DomainParameterXref domainParameterXref, DomainQueryExecutionContext executionContext, MutableObject<JdbcParameterBindings> firstJdbcParameterBindingsConsumer) { final SessionFactoryImplementor factory = executionContext.getSession().getFactory(); final EntityMappingType entityDescriptor = factory.getMappingMetamodel() .getEntityDescriptor( sqmMutationStatement.getTarget().getModel().getHibernateEntityName() ); final SqmSelectStatement<?> sqmSelectStatement = generateMatchingIdSelectStatement( sqmMutationStatement, entityDescriptor ); final SqmQuerySpec<?> sqmQuerySpec = sqmSelectStatement.getQuerySpec(); if ( sqmMutationStatement instanceof SqmDeleteStatement<?> ) { // For delete statements we also want to collect FK values to execute collection table cleanups entityDescriptor.visitSubTypeAttributeMappings( attribute -> { if ( attribute instanceof PluralAttributeMapping pluralAttribute ) { if ( pluralAttribute.getSeparateCollectionTable() != null ) { // Ensure that the FK target columns are available final ValuedModelPart targetPart = pluralAttribute.getKeyDescriptor().getTargetPart(); final boolean useFkTarget = !targetPart.isEntityIdentifierMapping(); if ( useFkTarget ) { targetPart.forEachSelectable( 0, (selectionIndex, selectableMapping) -> sqmQuerySpec.getSelectClause().addSelection( SelectableMappingExpressionConverter.forSelectableMapping( sqmMutationStatement.getTarget(), selectableMapping ) ) ); } } } } ); } final SqmTranslator<SelectStatement> translator = factory.getQueryEngine() .getSqmTranslatorFactory() .createSelectTranslator( sqmSelectStatement, executionContext.getQueryOptions(), domainParameterXref, executionContext.getQueryParameterBindings(), executionContext.getSession().getLoadQueryInfluencers(), factory.getSqlTranslationEngine(), true ); final SqmTranslation<SelectStatement> translation = translator.translate(); final JdbcServices jdbcServices = factory.getJdbcServices(); final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment(); final SqlAstTranslator<JdbcOperationQuerySelect> sqlAstSelectTranslator = jdbcEnvironment .getSqlAstTranslatorFactory() .buildSelectTranslator( factory, translation.getSqlAst() ); final Map<QueryParameterImplementor<?>, Map<SqmParameter<?>, List<JdbcParametersList>>> jdbcParamsXref = SqmUtil.generateJdbcParamsXref( domainParameterXref, translator ); final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings( executionContext.getQueryParameterBindings(), domainParameterXref, jdbcParamsXref, new SqmParameterMappingModelResolutionAccess() { @Override @SuppressWarnings("unchecked") public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) { return (MappingModelExpressible<T>) translation.getSqmParameterMappingModelTypeResolutions() .get( parameter ); } } , executionContext.getSession() ); final LockOptions lockOptions = executionContext.getQueryOptions().getLockOptions().makeCopy(); final LockMode lockMode = lockOptions.getLockMode(); // Acquire a WRITE lock for the rows that are about to be modified lockOptions.setLockMode( LockMode.WRITE ); // Visit the table joins and reset the lock mode if we encounter OUTER joins that are not supported if ( !jdbcEnvironment.getDialect().supportsOuterJoinForUpdate() ) { translation.getSqlAst().getQuerySpec().getFromClause().visitTableJoins( tableJoin -> { if ( tableJoin.isInitialized() && tableJoin.getJoinType() != SqlAstJoinType.INNER ) { lockOptions.setLockMode( lockMode ); } } ); } firstJdbcParameterBindingsConsumer.set( jdbcParameterBindings ); return new CacheableSqmInterpretation<>( translation.getSqlAst(), sqlAstSelectTranslator.translate( jdbcParameterBindings, executionContext.getQueryOptions() ), jdbcParamsXref, translation.getSqmParameterMappingModelTypeResolutions() ); } /** * Centralized selection of ids matching the restriction of the DELETE * or UPDATE SQM query */ public static List<Object> selectMatchingIds( SqmDeleteOrUpdateStatement<?> sqmMutationStatement, DomainParameterXref domainParameterXref, DomainQueryExecutionContext executionContext) { final MutableObject<JdbcParameterBindings> jdbcParameterBindings = new MutableObject<>(); final CacheableSqmInterpretation<SelectStatement, JdbcOperationQuerySelect> interpretation = createMatchingIdsSelect( sqmMutationStatement, domainParameterXref, executionContext, jdbcParameterBindings ); return selectMatchingIds( interpretation, jdbcParameterBindings.get(), executionContext ); } public static List<Object> selectMatchingIds( CacheableSqmInterpretation<SelectStatement, JdbcOperationQuerySelect> interpretation, JdbcParameterBindings jdbcParameterBindings, DomainQueryExecutionContext executionContext) { final RowTransformer<?> rowTransformer; if ( interpretation.statement().getDomainResultDescriptors().size() == 1 ) { rowTransformer = RowTransformerSingularReturnImpl.instance(); } else { rowTransformer = RowTransformerArrayImpl.instance(); } //noinspection unchecked return executionContext.getSession().getFactory().getJdbcServices().getJdbcSelectExecutor().list( interpretation.jdbcOperation(), jdbcParameterBindings, SqmJdbcExecutionContextAdapter.omittingLockingAndPaging( executionContext ), (RowTransformer<Object>) rowTransformer, ListResultsConsumer.UniqueSemantic.FILTER ); } }
MatchingIdSelectionHelper
java
quarkusio__quarkus
integration-tests/kafka-streams/src/main/java/io/quarkus/it/kafka/streams/KafkaStreamsEventCounter.java
{ "start": 301, "end": 700 }
class ____ { LongAdder eventCount = new LongAdder(); void onKafkaStreamsEvent(@Observes KafkaStreams kafkaStreams, StreamsConfig streamsConfig) { assert kafkaStreams.state() == KafkaStreams.State.CREATED; assert streamsConfig != null; eventCount.increment(); } public int getEventCount() { return eventCount.intValue(); } }
KafkaStreamsEventCounter
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableSwitchIfEmpty.java
{ "start": 1334, "end": 2462 }
class ____<T> implements FlowableSubscriber<T> { final Subscriber<? super T> downstream; final Publisher<? extends T> other; final SubscriptionArbiter arbiter; boolean empty; SwitchIfEmptySubscriber(Subscriber<? super T> actual, Publisher<? extends T> other) { this.downstream = actual; this.other = other; this.empty = true; this.arbiter = new SubscriptionArbiter(false); } @Override public void onSubscribe(Subscription s) { arbiter.setSubscription(s); } @Override public void onNext(T t) { if (empty) { empty = false; } downstream.onNext(t); } @Override public void onError(Throwable t) { downstream.onError(t); } @Override public void onComplete() { if (empty) { empty = false; other.subscribe(this); } else { downstream.onComplete(); } } } }
SwitchIfEmptySubscriber
java
quarkusio__quarkus
extensions/kubernetes/spi/src/test/java/io/quarkus/kubernetes/spi/KubernetesDeploymentTargetBuildItemTest.java
{ "start": 251, "end": 1945 }
class ____ { @Test void testMergeList() { List<KubernetesDeploymentTargetBuildItem> input = Arrays.asList( new KubernetesDeploymentTargetBuildItem("n1", "k1", "g1", "v1", 0, false, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n2", "k2", "g1", "v1", 10, false, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n1", "k1", "g1", "v1", -10, false, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n3", "k3", "g1", "v1", Integer.MIN_VALUE, false, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n4", "k4", "g1", "v1", Integer.MIN_VALUE, true, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n2", "k2", "g1", "v1", -10, true, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n4", "k4", "g1", "v1", Integer.MAX_VALUE, true, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n1", "k1", "g1", "v1", 100, false, CreateOrUpdate)); List<KubernetesDeploymentTargetBuildItem> result = KubernetesDeploymentTargetBuildItem.mergeList(input); assertThat(result).containsOnly( new KubernetesDeploymentTargetBuildItem("n1", "k1", "g1", "v1", 100, false, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n2", "k2", "g1", "v1", 10, true, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n3", "k3", "g1", "v1", Integer.MIN_VALUE, false, CreateOrUpdate), new KubernetesDeploymentTargetBuildItem("n4", "k4", "g1", "v1", Integer.MAX_VALUE, true, CreateOrUpdate)); } }
KubernetesDeploymentTargetBuildItemTest
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh11162ConsumerPomScopesTest.java
{ "start": 1382, "end": 3490 }
class ____ extends AbstractMavenIntegrationTestCase { @Test void testConsumerPomFiltersScopes() throws Exception { Path basedir = extractResources("/gh-11162-consumer-pom-scopes").toPath(); Verifier verifier = newVerifier(basedir.toString()); verifier.addCliArgument("install"); verifier.addCliArgument("-Dmaven.consumer.pom.flatten=true"); verifier.execute(); verifier.verifyErrorFreeLog(); Path consumerPom = basedir.resolve(Paths.get( "target", "project-local-repo", "org.apache.maven.its.gh11162", "consumer-pom-scopes-app", "1.0", "consumer-pom-scopes-app-1.0-consumer.pom")); assertTrue(Files.exists(consumerPom), "consumer pom not found at " + consumerPom); Model consumerPomModel; try (Reader r = Files.newBufferedReader(consumerPom)) { consumerPomModel = new MavenStaxReader().read(r); } long numDeps = consumerPomModel.getDependencies() != null ? consumerPomModel.getDependencies().size() : 0; assertEquals(2, numDeps, "Consumer POM should keep only compile and runtime dependencies"); boolean hasCompile = consumerPomModel.getDependencies().stream() .anyMatch(d -> "compile".equals(d.getScope()) && "compile-dep".equals(d.getArtifactId())); boolean hasRuntime = consumerPomModel.getDependencies().stream() .anyMatch(d -> "runtime".equals(d.getScope()) && "runtime-dep".equals(d.getArtifactId())); assertTrue(hasCompile, "compile dependency should be present"); assertTrue(hasRuntime, "runtime dependency should be present"); long dropped = consumerPomModel.getDependencies().stream() .map(d -> d.getScope()) .filter(s -> !"compile".equals(s) && !"runtime".equals(s)) .count(); assertEquals(0, dropped, "All non compile/runtime scopes should be dropped in consumer POM"); } }
MavenITgh11162ConsumerPomScopesTest
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/cli/AbstractConnectCliTest.java
{ "start": 7328, "end": 7956 }
class ____ simulate it being only in plugin.path, not classpath. if (name.equals(restrictedClassName)) { throw new ClassNotFoundException("Class " + name + " not found (restricted for testing)"); } // For other classes, delegate to system classloader return systemLoader.loadClass(name); } } /** * Exception thrown by createHerder to indicate that createConfig succeeded and correct order was maintained. * If this exception is thrown, it means compareAndSwapWithDelegatingLoader was called before createConfig. */ private static
to
java
apache__camel
components/camel-cron/src/test/java/org/apache/camel/component/cron/CronPatternsTest.java
{ "start": 1423, "end": 2853 }
class ____ extends CamelTestSupport { @ParameterizedTest @ValueSource(strings = { "cron:tab?schedule=0/1 * * * * ? 1 2", "cron:tab?schedule=wrong pattern", "cron://name?schedule=0+0/5+12-18+?+*+MON-FRI+2019+1" }) @DisplayName("Test parsing with too many, too little and invalid characters in the pattern") void testParts(String endpointUri) throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from(endpointUri) .to("mock:result"); } }); assertThrows(FailedToCreateRouteException.class, () -> { context.start(); }); } @Test void testPlusInURI() throws Exception { BeanIntrospection bi = PluginHelper.getBeanIntrospection(context); bi.setExtendedStatistics(true); bi.setLoggingLevel(LoggingLevel.INFO); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("cron://name?schedule=0+0/5+12-18+?+*+MON-FRI") .to("mock:result"); } }); context.start(); Thread.sleep(5); context.stop(); Assertions.assertEquals(0, bi.getInvokedCounter()); } @Override public boolean isUseRouteBuilder() { return false; } }
CronPatternsTest
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoContextWrite.java
{ "start": 892, "end": 1588 }
class ____<T> extends InternalMonoOperator<T, T> implements Fuseable { final Function<Context, Context> doOnContext; MonoContextWrite(Mono<? extends T> source, Function<Context, Context> doOnContext) { super(source); this.doOnContext = Objects.requireNonNull(doOnContext, "doOnContext"); } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { Context c = doOnContext.apply(actual.currentContext()); return new FluxContextWrite.ContextWriteSubscriber<>(actual, c); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } }
MonoContextWrite
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/SystemUtils.java
{ "start": 36279, "end": 36775 }
class ____ loaded. * </p> */ public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6"); /** * The constant {@code true} if this is Java version 1.7 (also 1.7.x versions). * <p> * The result depends on the value of the {@link #JAVA_SPECIFICATION_VERSION} constant. * </p> * <p> * The field will return {@code false} if {@link #JAVA_SPECIFICATION_VERSION} is {@code null}. * </p> * <p> * This value is initialized when the
is
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxDoOnEach.java
{ "start": 2629, "end": 6487 }
class ____<T> implements InnerOperator<T, T>, Signal<T> { static final short STATE_FLUX_START = (short) 0; static final short STATE_MONO_START = (short) 1; static final short STATE_SKIP_HANDLER = (short) 2; static final short STATE_DONE = (short) 3; final CoreSubscriber<? super T> actual; final Context cachedContext; final Consumer<? super Signal<T>> onSignal; @Nullable T t; @SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe Subscription s; Fuseable.@Nullable QueueSubscription<T> qs; short state; DoOnEachSubscriber(CoreSubscriber<? super T> actual, Consumer<? super Signal<T>> onSignal, boolean monoFlavor) { this.actual = actual; this.cachedContext = actual.currentContext(); this.onSignal = onSignal; this.state = monoFlavor ? STATE_MONO_START : STATE_FLUX_START; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { s.cancel(); } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.s, s)) { this.s = s; this.qs = Operators.as(s); actual.onSubscribe(this); } } @Override public Context currentContext() { return cachedContext; } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) { return s; } if (key == Attr.TERMINATED) { return state == STATE_DONE; } if (key == RUN_STYLE) { return SYNC; } return InnerOperator.super.scanUnsafe(key); } @Override public void onNext(T t) { if (state == STATE_DONE) { Operators.onNextDropped(t, cachedContext); return; } try { this.t = t; onSignal.accept(this); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, t, cachedContext)); return; } if (state == STATE_MONO_START) { state = STATE_SKIP_HANDLER; try { onSignal.accept(Signal.complete(cachedContext)); } catch (Throwable e) { state = STATE_MONO_START; onError(Operators.onOperatorError(s, e, cachedContext)); return; } } actual.onNext(t); } @Override public void onError(Throwable t) { if (state == STATE_DONE) { Operators.onErrorDropped(t, cachedContext); return; } boolean applyHandler = state < STATE_SKIP_HANDLER; state = STATE_DONE; if (applyHandler) { try { onSignal.accept(Signal.error(t, cachedContext)); } catch (Throwable e) { //this performs a throwIfFatal or suppresses t in e t = Operators.onOperatorError(null, e, t, cachedContext); } } try { actual.onError(t); } catch (UnsupportedOperationException use) { if (!Exceptions.isErrorCallbackNotImplemented(use) && use.getCause() != t) { throw use; } //ignore if missing callback } } @Override public void onComplete() { if (state == STATE_DONE) { return; } short oldState = state; state = STATE_DONE; if (oldState < STATE_SKIP_HANDLER) { try { onSignal.accept(Signal.complete(cachedContext)); } catch (Throwable e) { state = oldState; onError(Operators.onOperatorError(s, e, cachedContext)); return; } } actual.onComplete(); } @Override public CoreSubscriber<? super T> actual() { return actual; } @Override public @Nullable Throwable getThrowable() { return null; } @Override public @Nullable Subscription getSubscription() { return null; } @Override public @Nullable T get() { return t; } @Override public ContextView getContextView() { return cachedContext; } @Override public SignalType getType() { return SignalType.ON_NEXT; } @Override public String toString() { return "doOnEach_onNext(" + t + ")"; } } static
DoOnEachSubscriber
java
apache__camel
components/camel-jaxb/src/test/java/org/apache/camel/converter/jaxb/NonXmlFilterReaderTest.java
{ "start": 3420, "end": 3882 }
class ____ extends Reader { private char[] constant; ConstantReader(char[] constant) { this.constant = constant; } @Override public void close() { } @Override public int read(char[] cbuf, int off, int len) { int length = Math.min(len, constant.length); System.arraycopy(constant, 0, cbuf, off, length); return length; } } }
ConstantReader
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestUtils.java
{ "start": 1547, "end": 3595 }
class ____ { /** * Determines if an {@link OidcUserRequest} should attempt to retrieve the user info. * Will return true if all the following are true: * * <ul> * <li>The user info endpoint is defined on the ClientRegistration</li> * <li>The Client Registration uses the * {@link AuthorizationGrantType#AUTHORIZATION_CODE}</li> * </ul> * @param userRequest * @return */ static boolean shouldRetrieveUserInfo(OidcUserRequest userRequest) { // Auto-disabled if UserInfo Endpoint URI is not provided ClientRegistration.ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails(); if (StringUtils.hasLength(providerDetails.getUserInfoEndpoint().getUri()) && AuthorizationGrantType.AUTHORIZATION_CODE .equals(userRequest.getClientRegistration().getAuthorizationGrantType())) { return true; } return false; } static OidcUser getUser(OidcUserSource userMetadata) { OidcUserRequest userRequest = userMetadata.getUserRequest(); OidcUserInfo userInfo = userMetadata.getUserInfo(); Set<GrantedAuthority> authorities = new LinkedHashSet<>(); ClientRegistration.ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails(); String userNameAttributeName = providerDetails.getUserInfoEndpoint().getUserNameAttributeName(); if (StringUtils.hasText(userNameAttributeName)) { authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo, userNameAttributeName)); } else { authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo)); } OAuth2AccessToken token = userRequest.getAccessToken(); for (String scope : token.getScopes()) { authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope)); } if (StringUtils.hasText(userNameAttributeName)) { return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName); } return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo); } private OidcUserRequestUtils() { } }
OidcUserRequestUtils
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/ShardOperationFailedExceptionTests.java
{ "start": 772, "end": 2520 }
class ____ extends ESTestCase { public void testCauseCannotBeNull() { NullPointerException nullPointerException = expectThrows( NullPointerException.class, () -> new Failure( randomAlphaOfLengthBetween(3, 10), randomInt(), randomAlphaOfLengthBetween(5, 10), randomFrom(RestStatus.values()), null ) ); assertEquals("cause cannot be null", nullPointerException.getMessage()); } public void testStatusCannotBeNull() { NullPointerException nullPointerException = expectThrows( NullPointerException.class, () -> new Failure( randomAlphaOfLengthBetween(3, 10), randomInt(), randomAlphaOfLengthBetween(5, 10), null, new IllegalArgumentException() ) ); assertEquals("status cannot be null", nullPointerException.getMessage()); } public void testReasonCannotBeNull() { NullPointerException nullPointerException = expectThrows( NullPointerException.class, () -> new Failure( randomAlphaOfLengthBetween(3, 10), randomInt(), null, randomFrom(RestStatus.values()), new IllegalArgumentException() ) ); assertEquals("reason cannot be null", nullPointerException.getMessage()); } public void testIndexIsNullable() { new Failure(null, randomInt(), randomAlphaOfLengthBetween(5, 10), randomFrom(RestStatus.values()), new IllegalArgumentException()); } private static
ShardOperationFailedExceptionTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/procedure/HANAStoredProcedureTest.java
{ "start": 2381, "end": 13664 }
class ____ { @Id Long id; String name; } @BeforeEach public void prepareSchemaAndData(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.doWork( connection -> { try ( Statement statement = connection.createStatement() ) { statement.executeUpdate( "CREATE OR REPLACE PROCEDURE sp_count_phones ( " + " IN personId INTEGER, " + " OUT phoneCount INTEGER ) " + "AS " + "BEGIN " + " SELECT COUNT(*) INTO phoneCount " + " FROM phone " + " WHERE person_id = :personId; " + "END;" ); statement.executeUpdate( "CREATE OR REPLACE PROCEDURE sp_person_phones ( " + " IN personId INTEGER, " + " OUT personPhones phone ) " + "AS " + "BEGIN " + " personPhones = " + " SELECT *" + " FROM phone " + " WHERE person_id = :personId; " + "END;" ); statement.executeUpdate( "CREATE OR REPLACE FUNCTION fn_count_phones ( " + " IN personId INTEGER ) " + " RETURNS phoneCount INTEGER " + "AS " + "BEGIN " + " SELECT COUNT(*) INTO phoneCount " + " FROM phone " + " WHERE person_id = :personId; " + "END;" ); statement.executeUpdate( "CREATE OR REPLACE FUNCTION fn_person_and_phones ( " + " IN personId INTEGER ) " + " RETURNS TABLE (\"pr.id\" BIGINT," + " \"pr.name\" NVARCHAR(5000)," + " \"pr.nickName\" NVARCHAR(5000)," + " \"pr.address\" NVARCHAR(5000)," + " \"pr.createdOn\" TIMESTAMP," + " \"pr.version\" INTEGER," + " \"ph.id\" BIGINT," + " \"ph.person_id\" BIGINT," + " \"ph.phone_number\" NVARCHAR(5000)," + " \"ph.valid\" BOOLEAN)" + "AS " + "BEGIN " + " RETURN " + " SELECT " + " pr.id AS \"pr.id\", " + " pr.name AS \"pr.name\", " + " pr.nickName AS \"pr.nickName\", " + " pr.address AS \"pr.address\", " + " pr.createdOn AS \"pr.createdOn\", " + " pr.version AS \"pr.version\", " + " ph.id AS \"ph.id\", " + " ph.person_id AS \"ph.person_id\", " + " ph.phone_number AS \"ph.phone_number\", " + " ph.valid AS \"ph.valid\" " + " FROM person pr " + " JOIN phone ph ON pr.id = ph.person_id " + " WHERE pr.id = personId; " + "END;" ); statement.executeUpdate( "CREATE OR REPLACE " + "PROCEDURE singleRefCursor(OUT p_recordset TABLE(id INTEGER)) AS " + " BEGIN " + " p_recordset = " + " SELECT 1 as id " + " FROM SYS.DUMMY; " + " END; " ); statement.executeUpdate( "CREATE OR REPLACE " + "PROCEDURE outAndRefCursor(OUT p_value INTEGER, OUT p_recordset TABLE(id INTEGER)) AS " + " BEGIN " + " p_recordset = " + " SELECT 1 as id " + " FROM SYS.DUMMY; " + " SELECT 1 INTO p_value FROM SYS.DUMMY; " + " END; " ); statement.executeUpdate( "CREATE OR REPLACE PROCEDURE sp_phone_validity ( " + " IN validity BOOLEAN, " + " OUT personPhones TABLE (\"phone_number\" VARCHAR(255)) ) " + "AS " + "BEGIN " + " personPhones = SELECT phone_number as \"phone_number\" " + " FROM phone " + " WHERE valid = validity; " + "END;" ); statement.executeUpdate( "CREATE OR REPLACE PROCEDURE sp_votes ( " + " IN validity VARCHAR(1), " + " OUT votes TABLE (\"id\" BIGINT) ) " + "AS " + "BEGIN " + " votes = SELECT id as \"id\" " + " FROM vote " + " WHERE vote_choice = validity; " + "END;" ); } } ); } ); scope.inTransaction( (session) -> { Person person1 = new Person( 1L, "John Doe" ); person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ).toInstant( ZoneOffset.UTC ) ) ); session.persist( person1 ); Phone phone1 = new Phone( "123-456-7890" ); phone1.setId( 1L ); phone1.setValid( true ); person1.addPhone( phone1 ); Phone phone2 = new Phone( "098_765-4321" ); phone2.setId( 2L ); phone2.setValid( false ); person1.addPhone( phone2 ); } ); } @AfterEach public void cleanUpSchemaAndData(SessionFactoryScope scope) { scope.inTransaction( (session) -> { session.createMutationQuery( "delete Phone" ).executeUpdate(); session.createMutationQuery( "delete Person" ).executeUpdate(); } ); scope.inTransaction( (session) -> session.doWork( connection -> { try ( Statement statement = connection.createStatement() ) { statement.executeUpdate( "DROP PROCEDURE sp_count_phones" ); statement.executeUpdate( "DROP PROCEDURE sp_person_phones" ); statement.executeUpdate( "DROP FUNCTION fn_count_phones" ); statement.executeUpdate( "DROP PROCEDURE singleRefCursor" ); statement.executeUpdate( "DROP PROCEDURE outAndRefCursor" ); } catch (SQLException ignore) { } } ) ); } @Test @JiraKey( "HHH-12138") public void testStoredProcedureOutParameter(SessionFactoryScope scope) { scope.inTransaction( (session) -> { StoredProcedureQuery query = session.createStoredProcedureQuery( "sp_count_phones" ); query.registerStoredProcedureParameter( 1, Long.class, ParameterMode.IN ); query.registerStoredProcedureParameter( 2, Long.class, ParameterMode.OUT ); query.setParameter( 1, 1L ); query.execute(); Long phoneCount = (Long) query.getOutputParameterValue( 2 ); assertEquals( Long.valueOf( 2 ), phoneCount ); } ); } @Test @JiraKey( "HHH-12138") public void testStoredProcedureRefCursor(SessionFactoryScope scope) { scope.inTransaction( (session) -> { StoredProcedureQuery query = session.createStoredProcedureQuery( "sp_person_phones" ); query.registerStoredProcedureParameter( 1, Long.class, ParameterMode.IN ); query.registerStoredProcedureParameter( 2, Class.class, ParameterMode.REF_CURSOR ); query.setParameter( 1, 1L ); query.execute(); //noinspection unchecked List<Object[]> postComments = query.getResultList(); Assertions.assertNotNull( postComments ); } ); } @Test @JiraKey( "HHH-12138") public void testHibernateProcedureCallRefCursor(SessionFactoryScope scope) { scope.inTransaction( (session) -> { ProcedureCall call = session.createStoredProcedureCall( "sp_person_phones" ); final ProcedureParameter<Long> inParam = call.registerParameter( 1, Long.class, ParameterMode.IN ); call.setParameter( inParam, 1L ); call.registerParameter( 2, Class.class, ParameterMode.REF_CURSOR ); Output output = call.getOutputs().getCurrent(); //noinspection unchecked List<Object[]> postComments = ( (ResultSetOutput) output ).getResultList(); assertEquals( 2, postComments.size() ); } ); } @Test @JiraKey( "HHH-12138") public void testStoredProcedureReturnValue(SessionFactoryScope scope) { scope.inTransaction( (session) -> { Integer phoneCount = (Integer) session .createNativeQuery( "SELECT fn_count_phones(:personId) FROM SYS.DUMMY", Integer.class ) .setParameter( "personId", 1 ) .getSingleResult(); assertEquals( Integer.valueOf( 2 ), phoneCount ); } ); } @Test @JiraKey( "HHH-12138") public void testNamedNativeQueryStoredProcedureRefCursor(SessionFactoryScope scope) { scope.inTransaction( (session) -> { List<Object[]> postAndComments = session.createNamedQuery( "fn_person_and_phones_hana", Object[].class ) .setParameter( 1, 1L ) .getResultList(); assertThat( postAndComments ).hasSize( 2 ); Object[] postAndComment = postAndComments.get( 0 ); assertThat( postAndComment[0] ).isInstanceOf( Person.class ); assertThat( postAndComment[1] ).isInstanceOf( Phone.class ); } ); } @Test @JiraKey( "HHH-12138") public void testFunctionCallWithJDBC(SessionFactoryScope scope) { scope.inTransaction( (session) -> session.doWork( connection -> { try ( PreparedStatement function = connection.prepareStatement( "select * from fn_person_and_phones( ? )" ) ) { function.setInt( 1, 1 ); function.execute(); try ( ResultSet resultSet = function.getResultSet() ) { while ( resultSet.next() ) { assertThat( resultSet.getLong( 1 ) ).isInstanceOf( Long.class ); assertThat( resultSet.getString( 2 ) ).isInstanceOf( String.class ); } } } } ) ); } @Test @JiraKey( "HHH-12138") public void testSysRefCursorAsOutParameter(SessionFactoryScope scope) { scope.inTransaction( (session) -> { StoredProcedureQuery function = session.createNamedStoredProcedureQuery( "singleRefCursor" ); function.execute(); Integer value = (Integer) function.getSingleResult(); Assertions.assertFalse( function.hasMoreResults() ); assertEquals( Integer.valueOf( 1 ), value ); } ); } @Test @JiraKey( "HHH-12138") public void testOutAndSysRefCursorAsOutParameter(SessionFactoryScope scope) { scope.inTransaction( (session) -> { StoredProcedureQuery function = session.createNamedStoredProcedureQuery( "outAndRefCursor" ); function.execute(); Integer value = (Integer) function.getSingleResult(); assertEquals( Integer.valueOf( 1 ), value ); assertEquals( 1, function.getOutputParameterValue( 1 ) ); Assertions.assertFalse( function.hasMoreResults() ); } ); } @Test @JiraKey( "HHH-12661") public void testBindParameterAsHibernateType(SessionFactoryScope scope) { scope.inTransaction( (session) -> { StoredProcedureQuery query = session.createStoredProcedureQuery( "sp_phone_validity" ) .registerStoredProcedureParameter( 1, NumericBooleanConverter.class, ParameterMode.IN ) .registerStoredProcedureParameter( 2, Class.class, ParameterMode.REF_CURSOR ) .setParameter( 1, true ); query.execute(); List<?> phones = query.getResultList(); assertEquals( 1, phones.size() ); assertEquals( "123-456-7890", phones.get( 0 ) ); } ); scope.inTransaction( (session) -> { Vote vote1 = new Vote(); vote1.setId( 1L ); vote1.setVoteChoice( true ); session.persist( vote1 ); Vote vote2 = new Vote(); vote2.setId( 2L ); vote2.setVoteChoice( false ); session.persist( vote2 ); } ); scope.inTransaction( (session) -> { StoredProcedureQuery query = session.createStoredProcedureQuery( "sp_votes" ) .registerStoredProcedureParameter( 1, YesNoConverter.class, ParameterMode.IN ) .registerStoredProcedureParameter( 2, Class.class, ParameterMode.REF_CURSOR ) .setParameter( 1, true ); query.execute(); List<?> votes = query.getResultList(); assertEquals( 1, votes.size() ); assertEquals( 1, ( (Number) votes.get( 0 ) ).intValue() ); } ); } }
IdHolder
java
google__dagger
javatests/dagger/functional/generictypes/subpackage/PackagePrivateContainer.java
{ "start": 739, "end": 840 }
class ____ { @Inject PublicEnclosed() {} } private PackagePrivateContainer() {} }
PublicEnclosed
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/enums/EnumSerializationTest.java
{ "start": 778, "end": 939 }
class ____ extends DatabindTestUtil { /** * Test enumeration for verifying Enum serialization functionality. */ protected
EnumSerializationTest
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/metrics/DataSourcePoolMetricsTests.java
{ "start": 2032, "end": 2185 }
class ____ { @Bean MeterRegistry registry() { return new SimpleMeterRegistry(); } } @Configuration(proxyBeanMethods = false) static
MetricsApp
java
apache__camel
components/camel-as2/camel-as2-component/src/test/java/org/apache/camel/component/as2/AS2ServerManagerIT.java
{ "start": 3210, "end": 3340 }
class ____ {@link org.apache.camel.component.as2.api.AS2ServerManager} APIs that uses unencrypted AS2 message * types. */ public
for
java
quarkusio__quarkus
independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/model/ResourceInterceptors.java
{ "start": 4410, "end": 4970 }
interface ____ { VisitResult visitPreMatchRequestFilter(ResourceInterceptor<ContainerRequestFilter> interceptor); VisitResult visitGlobalRequestFilter(ResourceInterceptor<ContainerRequestFilter> interceptor); VisitResult visitNamedRequestFilter(ResourceInterceptor<ContainerRequestFilter> interceptor); VisitResult visitGlobalResponseFilter(ResourceInterceptor<ContainerResponseFilter> interceptor); VisitResult visitNamedResponseFilter(ResourceInterceptor<ContainerResponseFilter> interceptor);
FiltersVisitor
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
{ "start": 79006, "end": 79055 }
class ____<T> { static
EnclosedInParameterizedType
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/OpensslCtrCryptoCodec.java
{ "start": 3654, "end": 5877 }
class ____ implements Encryptor, Decryptor { private final OpensslCipher cipher; private final int mode; private boolean contextReset = false; public OpensslCtrCipher(int mode, CipherSuite suite, String engineId) throws GeneralSecurityException { this.mode = mode; cipher = OpensslCipher.getInstance(suite.getName(), engineId); } public OpensslCtrCipher(int mode, CipherSuite suite) throws GeneralSecurityException { this.mode = mode; cipher = OpensslCipher.getInstance(suite.getName()); } @Override public void init(byte[] key, byte[] iv) throws IOException { Preconditions.checkNotNull(key); Preconditions.checkNotNull(iv); contextReset = false; cipher.init(mode, key, iv); } /** * AES-CTR will consume all of the input data. It requires enough space in * the destination buffer to encrypt entire input buffer. */ @Override public void encrypt(ByteBuffer inBuffer, ByteBuffer outBuffer) throws IOException { process(inBuffer, outBuffer); } /** * AES-CTR will consume all of the input data. It requires enough space in * the destination buffer to decrypt entire input buffer. */ @Override public void decrypt(ByteBuffer inBuffer, ByteBuffer outBuffer) throws IOException { process(inBuffer, outBuffer); } private void process(ByteBuffer inBuffer, ByteBuffer outBuffer) throws IOException { try { int inputSize = inBuffer.remaining(); // OpensslCipher#update will maintain crypto context. int n = cipher.update(inBuffer, outBuffer); if (n < inputSize) { /** * Typically code will not get here. OpensslCipher#update will * consume all input data and put result in outBuffer. * OpensslCipher#doFinal will reset the crypto context. */ contextReset = true; cipher.doFinal(outBuffer); } } catch (Exception e) { throw new IOException(e); } } @Override public boolean isContextReset() { return contextReset; } } }
OpensslCtrCipher
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
{ "start": 22246, "end": 27713 }
interface ____ extends RequestHeadersSpec<RequestBodySpec> { /** * Set the length of the body in bytes, as specified by the * {@code Content-Length} header. * @param contentLength the content length * @return this builder * @see HttpHeaders#setContentLength(long) */ RequestBodySpec contentLength(long contentLength); /** * Set the {@linkplain MediaType media type} of the body, as specified * by the {@code Content-Type} header. * @param contentType the content type * @return this builder * @see HttpHeaders#setContentType(MediaType) */ RequestBodySpec contentType(MediaType contentType); /** * Shortcut for {@link #body(BodyInserter)} with a * {@linkplain BodyInserters#fromValue value inserter}. * For example: * <p><pre class="code"> * Person person = ... ; * * Mono&lt;Void&gt; result = client.post() * .uri("/persons/{id}", id) * .contentType(MediaType.APPLICATION_JSON) * .bodyValue(person) * .retrieve() * .bodyToMono(Void.class); * </pre> * <p>For multipart requests consider providing * {@link org.springframework.util.MultiValueMap MultiValueMap} prepared * with {@link org.springframework.http.client.MultipartBodyBuilder * MultipartBodyBuilder}. * @param body the value to write to the request body * @return this builder * @throws IllegalArgumentException if {@code body} is a * {@link Publisher} or producer known to {@link ReactiveAdapterRegistry} * @since 5.2 * @see #bodyValue(Object, ParameterizedTypeReference) */ RequestHeadersSpec<?> bodyValue(Object body); /** * Shortcut for {@link #body(BodyInserter)} with a * {@linkplain BodyInserters#fromValue value inserter}. * For example: * <p><pre class="code"> * List&lt;Person&gt; list = ... ; * * Mono&lt;Void&gt; result = client.post() * .uri("/persons/{id}", id) * .contentType(MediaType.APPLICATION_JSON) * .bodyValue(list, new ParameterizedTypeReference&lt;List&lt;Person&gt;&gt;() {};) * .retrieve() * .bodyToMono(Void.class); * </pre> * <p>For multipart requests consider providing * {@link org.springframework.util.MultiValueMap MultiValueMap} prepared * with {@link org.springframework.http.client.MultipartBodyBuilder * MultipartBodyBuilder}. * @param body the value to write to the request body * @param bodyType the type of the body, used to capture the generic type * @param <T> the type of the body * @return this builder * @throws IllegalArgumentException if {@code body} is a * {@link Publisher} or producer known to {@link ReactiveAdapterRegistry} * @since 6.2 */ <T> RequestHeadersSpec<?> bodyValue(T body, ParameterizedTypeReference<T> bodyType); /** * Shortcut for {@link #body(BodyInserter)} with a * {@linkplain BodyInserters#fromPublisher Publisher inserter}. * For example: * <p><pre> * Mono&lt;Person&gt; personMono = ... ; * * Mono&lt;Void&gt; result = client.post() * .uri("/persons/{id}", id) * .contentType(MediaType.APPLICATION_JSON) * .body(personMono, Person.class) * .retrieve() * .bodyToMono(Void.class); * </pre> * @param publisher the {@code Publisher} to write to the request * @param elementClass the type of elements published * @param <T> the type of the elements contained in the publisher * @param <P> the type of the {@code Publisher} * @return this builder */ <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, Class<T> elementClass); /** * Variant of {@link #body(Publisher, Class)} that allows providing * element type information with generics. * @param publisher the {@code Publisher} to write to the request * @param elementTypeRef the type of elements published * @param <T> the type of the elements contained in the publisher * @param <P> the type of the {@code Publisher} * @return this builder */ <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, ParameterizedTypeReference<T> elementTypeRef); /** * Variant of {@link #body(Publisher, Class)} that allows using any * producer that can be resolved to {@link Publisher} via * {@link ReactiveAdapterRegistry}. * @param producer the producer to write to the request * @param elementClass the type of elements produced * @return this builder * @since 5.2 */ RequestHeadersSpec<?> body(Object producer, Class<?> elementClass); /** * Variant of {@link #body(Publisher, ParameterizedTypeReference)} that * allows using any producer that can be resolved to {@link Publisher} * via {@link ReactiveAdapterRegistry}. * @param producer the producer to write to the request * @param elementTypeRef the type of elements produced * @return this builder * @since 5.2 */ RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementTypeRef); /** * Set the body of the request using the given body inserter. * See {@link BodyInserters} for built-in {@link BodyInserter} implementations. * @param inserter the body inserter to use for the request body * @return this builder * @see org.springframework.web.reactive.function.BodyInserters */ RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter); } /** * Contract for specifying response operations following the exchange. */
RequestBodySpec
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/es816/BinarizedByteVectorValues.java
{ "start": 1339, "end": 3567 }
class ____ extends ByteVectorValues { public abstract float[] getCorrectiveTerms(int vectorOrd) throws IOException; /** Return the dimension of the vectors */ public abstract int dimension(); /** Returns the centroid distance for the vector */ public abstract float getCentroidDistance(int vectorOrd) throws IOException; /** Returns the vector magnitude for the vector */ public abstract float getVectorMagnitude(int vectorOrd) throws IOException; /** Returns OOQ corrective factor for the given vector ordinal */ public abstract float getOOQ(int targetOrd) throws IOException; /** * Returns the norm of the target vector w the centroid corrective factor for the given vector * ordinal */ public abstract float getNormOC(int targetOrd) throws IOException; /** * Returns the target vector dot product the centroid corrective factor for the given vector * ordinal */ public abstract float getODotC(int targetOrd) throws IOException; /** * @return the quantizer used to quantize the vectors */ public abstract BinaryQuantizer getQuantizer(); public abstract float[] getCentroid() throws IOException; /** * Return the number of vectors for this field. * * @return the number of vectors returned by this iterator */ public abstract int size(); int discretizedDimensions() { return BQVectorUtils.discretize(dimension(), 64); } float sqrtDimensions() { return (float) constSqrt(dimension()); } float maxX1() { return (float) (1.9 / constSqrt(discretizedDimensions() - 1.0)); } /** * Return a {@link VectorScorer} for the given query vector. * * @param query the query vector * @return a {@link VectorScorer} instance or null */ public abstract VectorScorer scorer(float[] query) throws IOException; @Override public abstract BinarizedByteVectorValues copy() throws IOException; float getCentroidDP() throws IOException { // this only gets executed on-merge float[] centroid = getCentroid(); return VectorUtil.dotProduct(centroid, centroid); } }
BinarizedByteVectorValues
java
elastic__elasticsearch
x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/DeprecationChecker.java
{ "start": 1756, "end": 2424 }
class ____ { private final NamedXContentRegistry xContentRegistry; private final Settings settings; private final Client client; Components(NamedXContentRegistry xContentRegistry, Settings settings, OriginSettingClient client) { this.xContentRegistry = xContentRegistry; this.settings = settings; this.client = client; } public NamedXContentRegistry xContentRegistry() { return xContentRegistry; } public Settings settings() { return settings; } public Client client() { return client; } } }
Components
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/component/extension/ComponentVerifierExtension.java
{ "start": 14351, "end": 15026 }
interface ____ extends Attribute { /** * The erroneous HTTP code that occurred */ HttpAttribute HTTP_CODE = new HttpErrorAttribute("HTTP_CODE"); /** * HTTP response's body */ HttpAttribute HTTP_TEXT = new HttpErrorAttribute("HTTP_TEXT"); /** * If given as details, specifies that a redirect happened and the content of this detail is the redirect * URL */ HttpAttribute HTTP_REDIRECT = new HttpErrorAttribute("HTTP_REDIRECT"); } /** * Group related details */
HttpAttribute
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/dynamic/DynMethods.java
{ "start": 13157, "end": 14205 }
class ____ check for an implementation * @param methodName name of a method (different from constructor) * @param argClasses argument classes for the method * @return this Builder for method chaining */ public Builder hiddenImpl(Class<?> targetClass, String methodName, Class<?>... argClasses) { // don't do any work if an implementation has been found if (method != null) { return this; } try { Method hidden = targetClass.getDeclaredMethod(methodName, argClasses); AccessController.doPrivileged(new MakeAccessible(hidden)); this.method = new UnboundMethod(hidden, name); } catch (SecurityException | NoSuchMethodException e) { // unusable or not the right implementation LOG.debug("failed to load method {} from class {}", methodName, targetClass, e); } return this; } /** * Checks for a method implementation. * <p> * The name passed to the constructor is the method name used. * @param targetClass the
to
java
apache__camel
test-infra/camel-test-infra-smb/src/test/java/org/apache/camel/test/infra/smb/services/SmbServiceFactory.java
{ "start": 2404, "end": 2904 }
class ____ extends SmbRemoteInfraService implements SmbService { @Override public <T> T copyFileFromContainer(String fileName, ThrowingFunction<InputStream, T> function) { return null; } } public static SimpleTestServiceBuilder<SmbService> builder() { return new SimpleTestServiceBuilder<>("smb"); } public static SmbService createSingletonService() { return SingletonServiceHolder.INSTANCE; } private static
SmbRemoteService
java
apache__logging-log4j2
log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationFactoryTest.java
{ "start": 1175, "end": 1935 }
class ____ { @BeforeAll static void beforeAll() { System.setProperty( ConfigurationFactory.LOG4J1_CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j1-file-1.properties"); } @Test void testProperties() { final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); File file = new File("target/temp.A1"); assertTrue(file.exists(), "File A1 was not created"); assertTrue(file.length() > 0, "File A1 is empty"); file = new File("target/temp.A2"); assertTrue(file.exists(), "File A2 was not created"); assertTrue(file.length() > 0, "File A2 is empty"); } }
PropertiesConfigurationFactoryTest
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/server/TServlet.java
{ "start": 708, "end": 3524 }
class ____ extends HttpServlet { private final TProcessor processor; private final TProtocolFactory inProtocolFactory; private final TProtocolFactory outProtocolFactory; private final Collection<Map.Entry<String, String>> customHeaders; /** * @see HttpServlet#HttpServlet() */ public TServlet( TProcessor processor, TProtocolFactory inProtocolFactory, TProtocolFactory outProtocolFactory) { super(); this.processor = processor; this.inProtocolFactory = inProtocolFactory; this.outProtocolFactory = outProtocolFactory; this.customHeaders = new ArrayList<Map.Entry<String, String>>(); } /** * @see HttpServlet#HttpServlet() */ public TServlet(TProcessor processor, TProtocolFactory protocolFactory) { this(processor, protocolFactory, protocolFactory); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { TTransport inTransport = null; TTransport outTransport = null; try { response.setContentType("application/x-thrift"); if (null != this.customHeaders) { for (Map.Entry<String, String> header : this.customHeaders) { response.addHeader(header.getKey(), header.getValue()); } } InputStream in = request.getInputStream(); OutputStream out = response.getOutputStream(); TTransport transport = new TIOStreamTransport(in, out); inTransport = transport; outTransport = transport; TProtocol inProtocol = inProtocolFactory.getProtocol(inTransport); TProtocol outProtocol = outProtocolFactory.getProtocol(outTransport); processor.process(inProtocol, outProtocol); out.flush(); } catch (TException te) { throw new ServletException(te); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void addCustomHeader(final String key, final String value) { this.customHeaders.add( new Map.Entry<String, String>() { @Override public String getKey() { return key; } @Override public String getValue() { return value; } @Override public String setValue(String value) { return null; } }); } public void setCustomHeaders(Collection<Map.Entry<String, String>> headers) { this.customHeaders.clear(); this.customHeaders.addAll(headers); } }
TServlet
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/persistent/UpdatePersistentTaskRequestTests.java
{ "start": 1005, "end": 1876 }
class ____ extends AbstractWireSerializingTestCase<Request> { @Override protected Request createTestInstance() { return new Request(randomTimeValue(), UUIDs.base64UUID(), randomLong(), new State(randomAlphaOfLength(10))); } @Override protected Request mutateInstance(Request instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Request> instanceReader() { return Request::new; } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { return new NamedWriteableRegistry( Collections.singletonList( new NamedWriteableRegistry.Entry(PersistentTaskState.class, TestPersistentTasksExecutor.NAME, State::new) ) ); } }
UpdatePersistentTaskRequestTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/desirednodes/TransportGetDesiredNodesAction.java
{ "start": 1300, "end": 2785 }
class ____ extends TransportMasterNodeReadAction< GetDesiredNodesAction.Request, GetDesiredNodesAction.Response> { @Inject public TransportGetDesiredNodesAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters ) { super( GetDesiredNodesAction.NAME, transportService, clusterService, threadPool, actionFilters, GetDesiredNodesAction.Request::new, GetDesiredNodesAction.Response::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); } @Override protected void masterOperation( Task task, GetDesiredNodesAction.Request request, ClusterState state, ActionListener<GetDesiredNodesAction.Response> listener ) throws Exception { final DesiredNodes latestDesiredNodes = DesiredNodes.latestFromClusterState(state); if (latestDesiredNodes == null) { listener.onFailure(new ResourceNotFoundException("Desired nodes not found")); } else { listener.onResponse(new GetDesiredNodesAction.Response(latestDesiredNodes)); } } @Override protected ClusterBlockException checkBlock(GetDesiredNodesAction.Request request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); } }
TransportGetDesiredNodesAction
java
apache__hadoop
hadoop-tools/hadoop-federation-balance/src/main/java/org/apache/hadoop/tools/fedbalance/FedBalanceOptions.java
{ "start": 990, "end": 1064 }
class ____ { /** * The private construct protects this
FedBalanceOptions
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/OnlyEagerBasicUpdateTest.java
{ "start": 1680, "end": 7226 }
class ____ { private Long entityId; SQLStatementInspector statementInspector(SessionFactoryScope scope) { return (SQLStatementInspector) scope.getSessionFactory().getSessionFactoryOptions().getStatementInspector(); } private void initNull(SessionFactoryScope scope) { scope.inTransaction( s -> { EagerEntity entity = new EagerEntity(); s.persist( entity ); entityId = entity.getId(); } ); } private void initNonNull(SessionFactoryScope scope) { scope.inTransaction( s -> { EagerEntity entity = new EagerEntity(); entity.setEagerProperty1( "eager1_initial" ); entity.setEagerProperty2( "eager2_initial" ); s.persist( entity ); entityId = entity.getId(); } ); } @BeforeEach public void clearStatementInspector(SessionFactoryScope scope) { statementInspector( scope ).clear(); } @Test public void updateSomeEagerProperty_nullToNull(SessionFactoryScope scope) { initNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( null ); } ); // We should not update entities when property values did not change statementInspector( scope ).assertNoUpdate(); } @Test public void updateSomeEagerProperty_nullToNonNull(SessionFactoryScope scope) { initNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( "eager1_update" ); } ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); assertEquals( "eager1_update", entity.getEagerProperty1() ); assertNull( entity.getEagerProperty2() ); } ); } @Test public void updateSomeEagerProperty_nonNullToNonNull_differentValues(SessionFactoryScope scope) { initNonNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( "eager1_update" ); } ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); assertEquals( "eager1_update", entity.getEagerProperty1() ); assertEquals( "eager2_initial", entity.getEagerProperty2() ); } ); } @Test public void updateSomeEagerProperty_nonNullToNonNull_sameValues(SessionFactoryScope scope) { initNonNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( entity.getEagerProperty1() ); } ); // We should not update entities when property values did not change statementInspector( scope ).assertNoUpdate(); } @Test public void updateSomeEagerProperty_nonNullToNull(SessionFactoryScope scope) { initNonNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( null ); } ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); assertNull( entity.getEagerProperty1() ); assertEquals( "eager2_initial", entity.getEagerProperty2() ); } ); } @Test public void updateAllEagerProperties_nullToNull(SessionFactoryScope scope) { initNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( null ); entity.setEagerProperty2( null ); } ); // We should not update entities when property values did not change statementInspector( scope ).assertNoUpdate(); } @Test public void updateAllEagerProperties_nullToNonNull(SessionFactoryScope scope) { initNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( "eager1_update" ); entity.setEagerProperty2( "eager2_update" ); } ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); assertEquals( "eager1_update", entity.getEagerProperty1() ); assertEquals( "eager2_update", entity.getEagerProperty2() ); } ); } @Test public void updateAllEagerProperties_nonNullToNonNull_differentValues(SessionFactoryScope scope) { initNonNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( "eager1_update" ); entity.setEagerProperty2( "eager2_update" ); } ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); assertEquals( "eager1_update", entity.getEagerProperty1() ); assertEquals( "eager2_update", entity.getEagerProperty2() ); } ); } @Test public void updateAllEagerProperties_nonNullToNonNull_sameValues(SessionFactoryScope scope) { initNonNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( entity.getEagerProperty1() ); entity.setEagerProperty2( entity.getEagerProperty2() ); } ); // We should not update entities when property values did not change statementInspector( scope ).assertNoUpdate(); } @Test public void updateAllEagerProperties_nonNullToNull(SessionFactoryScope scope) { initNonNull( scope ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); entity.setEagerProperty1( null ); entity.setEagerProperty2( null ); } ); scope.inTransaction( s -> { EagerEntity entity = s.get( EagerEntity.class, entityId ); assertNull( entity.getEagerProperty1() ); assertNull( entity.getEagerProperty2() ); } ); } @Entity @Table(name = "LAZY_ENTITY") static
OnlyEagerBasicUpdateTest