language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/JobHistoryParser.java
{ "start": 1007, "end": 1058 }
interface ____ a Job History file parser. */ public
of
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java
{ "start": 2038, "end": 3870 }
class ____ extends AbstractExpressionTests { @Test void simpleAccess01() { evaluate("name", "Nikola Tesla", String.class); } @Test void simpleAccess02() { evaluate("placeOfBirth.city", "Smiljan", String.class); } @Test void simpleAccess03() { evaluate("stringArrayOfThreeItems.length", "3", Integer.class); } @Test void nonExistentPropertiesAndMethods() { // madeup does not exist as a property evaluateAndCheckError("madeup", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 0); // name is ok but foobar does not exist: evaluateAndCheckError("name.foobar", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 5); } /** * The standard reflection resolver cannot find properties on null objects but some * supplied resolver might be able to - so null shouldn't crash the reflection resolver. */ @Test void accessingOnNullObject() { SpelExpression expr = (SpelExpression) parser.parseExpression("madeup"); EvaluationContext context = new StandardEvaluationContext(null); assertThatSpelEvaluationException() .isThrownBy(() -> expr.getValue(context)) .extracting(SpelEvaluationException::getMessageCode).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL); assertThat(expr.isWritable(context)).isFalse(); assertThatSpelEvaluationException() .isThrownBy(() -> expr.setValue(context, "abc")) .extracting(SpelEvaluationException::getMessageCode).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL); } @Test // Adding a new property accessor just for a particular type void addingSpecificPropertyAccessor() { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext ctx = new StandardEvaluationContext(); // Even though this property accessor is added after the reflection one, it specifically // names the String
PropertyAccessTests
java
elastic__elasticsearch
x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/async/AsyncTaskManagementServiceTests.java
{ "start": 2323, "end": 2637 }
class ____ extends LegacyActionRequest { private final String string; public TestRequest(String string) { this.string = string; } @Override public ActionRequestValidationException validate() { return null; } } public static
TestRequest
java
apache__kafka
server-common/src/test/java/org/apache/kafka/server/purgatory/DelayedOperationTest.java
{ "start": 1753, "end": 10374 }
class ____ { private final MockKey test1 = new MockKey("test1"); private final MockKey test2 = new MockKey("test2"); private final MockKey test3 = new MockKey("test3"); private final Random random = new Random(); private DelayedOperationPurgatory<DelayedOperation> purgatory; private ScheduledExecutorService executorService; @BeforeEach public void setUp() { purgatory = new DelayedOperationPurgatory<>("mock", 0); } @AfterEach public void tearDown() throws Exception { purgatory.shutdown(); if (executorService != null) executorService.shutdown(); } private record MockKey(String key) implements DelayedOperationKey { @Override public String keyLabel() { return key; } } @Test public void testLockInTryCompleteElseWatch() { DelayedOperation op = new DelayedOperation(100000L) { @Override public void onExpiration() {} @Override public void onComplete() {} @Override public boolean tryComplete() { assertTrue(((ReentrantLock) lock).isHeldByCurrentThread()); return false; } @Override public boolean safeTryComplete() { fail("tryCompleteElseWatch should not use safeTryComplete"); return super.safeTryComplete(); } }; purgatory.tryCompleteElseWatch(op, List.of(new MockKey("key"))); } private DelayedOperation op(boolean shouldComplete) { return new DelayedOperation(100000L) { @Override public void onExpiration() {} @Override public void onComplete() {} @Override public boolean tryComplete() { assertTrue(((ReentrantLock) lock).isHeldByCurrentThread()); return shouldComplete; } }; } @Test public void testSafeTryCompleteOrElse() { final AtomicBoolean pass = new AtomicBoolean(); assertFalse(op(false).safeTryCompleteOrElse(() -> pass.set(true))); assertTrue(pass.get()); assertTrue(op(true).safeTryCompleteOrElse(() -> fail("this method should NOT be executed"))); } @Test public void testRequestSatisfaction() { MockDelayedOperation r1 = new MockDelayedOperation(100000L); MockDelayedOperation r2 = new MockDelayedOperation(100000L); assertEquals(0, purgatory.checkAndComplete(test1), "With no waiting requests, nothing should be satisfied"); assertFalse(purgatory.tryCompleteElseWatch(r1, List.of(new MockKey("test1"))), "r1 not satisfied and hence watched"); assertEquals(0, purgatory.checkAndComplete(test1), "Still nothing satisfied"); assertFalse(purgatory.tryCompleteElseWatch(r2, List.of(new MockKey("test2"))), "r2 not satisfied and hence watched"); assertEquals(0, purgatory.checkAndComplete(test2), "Still nothing satisfied"); r1.completable = true; assertEquals(1, purgatory.checkAndComplete(test1), "r1 satisfied"); assertEquals(0, purgatory.checkAndComplete(test1), "Nothing satisfied"); r2.completable = true; assertEquals(1, purgatory.checkAndComplete(test2), "r2 satisfied"); assertEquals(0, purgatory.checkAndComplete(test2), "Nothing satisfied"); } @Test public void testRequestExpiry() throws Exception { long expiration = 20L; long start = Time.SYSTEM.hiResClockMs(); MockDelayedOperation r1 = new MockDelayedOperation(expiration); MockDelayedOperation r2 = new MockDelayedOperation(200000L); assertFalse(purgatory.tryCompleteElseWatch(r1, List.of(test1)), "r1 not satisfied and hence watched"); assertFalse(purgatory.tryCompleteElseWatch(r2, List.of(test2)), "r2 not satisfied and hence watched"); r1.awaitExpiration(); long elapsed = Time.SYSTEM.hiResClockMs() - start; assertTrue(r1.isCompleted(), "r1 completed due to expiration"); assertFalse(r2.isCompleted(), "r2 hasn't completed"); assertTrue(elapsed >= expiration, "Time for expiration " + elapsed + " should at least " + expiration); } @Test public void testRequestPurge() { MockDelayedOperation r1 = new MockDelayedOperation(100000L); MockDelayedOperation r2 = new MockDelayedOperation(100000L); MockDelayedOperation r3 = new MockDelayedOperation(100000L); purgatory.tryCompleteElseWatch(r1, List.of(test1)); purgatory.tryCompleteElseWatch(r2, List.of(test1, test2)); purgatory.tryCompleteElseWatch(r3, List.of(test1, test2, test3)); assertEquals(3, purgatory.numDelayed(), "Purgatory should have 3 total delayed operations"); assertEquals(6, purgatory.watched(), "Purgatory should have 6 watched elements"); // complete the operations, it should immediately be purged from the delayed operation r2.completable = true; r2.tryComplete(); assertEquals(2, purgatory.numDelayed(), "Purgatory should have 2 total delayed operations instead of " + purgatory.numDelayed()); r3.completable = true; r3.tryComplete(); assertEquals(1, purgatory.numDelayed(), "Purgatory should have 1 total delayed operations instead of " + purgatory.numDelayed()); // checking a watch should purge the watch list purgatory.checkAndComplete(test1); assertEquals(4, purgatory.watched(), "Purgatory should have 4 watched elements instead of " + purgatory.watched()); purgatory.checkAndComplete(test2); assertEquals(2, purgatory.watched(), "Purgatory should have 2 watched elements instead of " + purgatory.watched()); purgatory.checkAndComplete(test3); assertEquals(1, purgatory.watched(), "Purgatory should have 1 watched elements instead of " + purgatory.watched()); } @Test public void shouldCancelForKeyReturningCancelledOperations() { purgatory.tryCompleteElseWatch(new MockDelayedOperation(10000L), List.of(test1)); purgatory.tryCompleteElseWatch(new MockDelayedOperation(10000L), List.of(test1)); purgatory.tryCompleteElseWatch(new MockDelayedOperation(10000L), List.of(test2)); List<DelayedOperation> cancelledOperations = purgatory.cancelForKey(test1); assertEquals(2, cancelledOperations.size()); assertEquals(1, purgatory.numDelayed()); assertEquals(1, purgatory.watched()); } @Test public void shouldReturnNilOperationsOnCancelForKeyWhenKeyDoesntExist() { List<DelayedOperation> cancelledOperations = purgatory.cancelForKey(test1); assertTrue(cancelledOperations.isEmpty()); } /** * Test `tryComplete` with multiple threads to verify that there are no timing windows * when completion is not performed even if the thread that makes the operation completable * may not be able to acquire the operation lock. Since it is difficult to test all scenarios, * this test uses random delays with a large number of threads. */ @Test public void testTryCompleteWithMultipleThreads() throws ExecutionException, InterruptedException { executorService = Executors.newScheduledThreadPool(20); int maxDelayMs = 10; int completionAttempts = 20; List<TestDelayOperation> ops = new ArrayList<>(); for (int i = 0; i < 100; i++) { TestDelayOperation op = new TestDelayOperation(i, completionAttempts, maxDelayMs); purgatory.tryCompleteElseWatch(op, List.of(op.key)); ops.add(op); } List<Future<?>> futures = new ArrayList<>(); for (int i = 1; i <= completionAttempts; i++) { for (TestDelayOperation op : ops) { futures.add(scheduleTryComplete(executorService, op, random.nextInt(maxDelayMs))); } } for (Future<?> future : futures) { future.get(); } ops.forEach(op -> assertTrue(op.isCompleted(), "Operation " + op.key.keyLabel() + " should have completed")); } private Future<?> scheduleTryComplete(ScheduledExecutorService executorService, TestDelayOperation op, long delayMs) { return executorService.schedule(() -> { if (op.completionAttemptsRemaining.decrementAndGet() == 0) { op.completable = true; } purgatory.checkAndComplete(op.key); }, delayMs, TimeUnit.MILLISECONDS); } private static
DelayedOperationTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/intercepted/InterceptedRestClientTest.java
{ "start": 1944, "end": 2292 }
interface ____ { @GET @Path("/{path}") String hello(@MyAnnotation("skip") @PathParam("path") String path); @GET @Path("/{path}") String ping(@MyAnnotation("don't skip") @PathParam("path") String param); } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @
Client
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfTests.java
{ "start": 3837, "end": 3984 }
class ____ { @Bean Boolean booleanTrueBean() { return Boolean.TRUE; } @Bean String stringTrueBean() { return "true"; } } }
Config
java
google__guice
core/src/com/google/inject/internal/ConstantProviderInternalFactory.java
{ "start": 878, "end": 1893 }
class ____<T> extends ProviderInternalFactory<T> { private final Provider<T> provider; @Nullable private final ProvisionListenerStackCallback<T> provisionCallback; ConstantProviderInternalFactory( Class<? super T> rawType, Provider<T> provider, Object source, @Nullable ProvisionListenerStackCallback<T> provisionCallback, int circularFactoryId) { super(rawType, source, circularFactoryId); this.provider = checkNotNull(provider); this.provisionCallback = provisionCallback; } @Override public T get(InternalContext context, Dependency<?> dependency, boolean linked) throws InternalProvisionException { return circularGet(provider, context, dependency, provisionCallback); } @Override MethodHandleResult makeHandle(LinkageContext context, boolean linked) { return makeCachable( circularGetHandleImmediate( InternalMethodHandles.constantFactoryGetHandle(provider), provisionCallback)); } }
ConstantProviderInternalFactory
java
google__auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationTemplateVars.java
{ "start": 932, "end": 1607 }
class ____ extends TemplateVars { /** The members of the annotation being implemented. */ Map<String, AutoAnnotationProcessor.Member> members; /** * The parameters in the {@code @AutoAnnotation} method, which are also the constructor parameters * in the generated class. */ Map<String, AutoAnnotationProcessor.Parameter> params; /** * A string representing the parameter type declaration of the equals(Object) method, including * any annotations. */ String equalsParameterType; /** The encoded form of the {@code Generated} class, or empty if it is not available. */ String generated; /** * The package of the
AutoAnnotationTemplateVars
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/size/Teacher.java
{ "start": 461, "end": 1228 }
class ____ { private Integer id; private Set<Student> students = new HashSet<>(); private Set<Skill> skills = new HashSet<>(); @Id @Column(name = "teacher_id") @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @OneToMany(mappedBy = "teacher") public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } public void addStudent(Student student) { students.add( student ); } @ManyToMany public Set<Skill> getSkills() { return skills; } public void addSkill(Skill skill) { skills.add( skill ); skill.addTeacher( this ); } public void setSkills(Set<Skill> skills) { this.skills = skills; } }
Teacher
java
apache__spark
common/kvstore/src/test/java/org/apache/spark/util/kvstore/RocksDBTypeInfoSuite.java
{ "start": 991, "end": 5789 }
class ____ { @Test public void testIndexAnnotation() throws Exception { KVTypeInfo ti = new KVTypeInfo(CustomType1.class); assertEquals(5, ti.indices().count()); CustomType1 t1 = new CustomType1(); t1.key = "key"; t1.id = "id"; t1.name = "name"; t1.num = 42; t1.child = "child"; assertEquals(t1.key, ti.getIndexValue(KVIndex.NATURAL_INDEX_NAME, t1)); assertEquals(t1.id, ti.getIndexValue("id", t1)); assertEquals(t1.name, ti.getIndexValue("name", t1)); assertEquals(t1.num, ti.getIndexValue("int", t1)); assertEquals(t1.child, ti.getIndexValue("child", t1)); } @Test public void testNoNaturalIndex() { assertThrows(IllegalArgumentException.class, () -> newTypeInfo(NoNaturalIndex.class)); } @Test public void testNoNaturalIndex2() { assertThrows(IllegalArgumentException.class, () -> newTypeInfo(NoNaturalIndex2.class)); } @Test public void testDuplicateIndex() { assertThrows(IllegalArgumentException.class, () -> newTypeInfo(DuplicateIndex.class)); } @Test public void testEmptyIndexName() { assertThrows(IllegalArgumentException.class, () -> newTypeInfo(EmptyIndexName.class)); } @Test public void testIllegalIndexName() { assertThrows(IllegalArgumentException.class, () -> newTypeInfo(IllegalIndexName.class)); } @Test public void testIllegalIndexMethod() { assertThrows(IllegalArgumentException.class, () -> newTypeInfo(IllegalIndexMethod.class)); } @Test public void testKeyClashes() throws Exception { RocksDBTypeInfo ti = newTypeInfo(CustomType1.class); CustomType1 t1 = new CustomType1(); t1.key = "key1"; t1.name = "a"; CustomType1 t2 = new CustomType1(); t2.key = "key2"; t2.name = "aa"; CustomType1 t3 = new CustomType1(); t3.key = "key3"; t3.name = "aaa"; // Make sure entries with conflicting names are sorted correctly. assertBefore(ti.index("name").entityKey(null, t1), ti.index("name").entityKey(null, t2)); assertBefore(ti.index("name").entityKey(null, t1), ti.index("name").entityKey(null, t3)); assertBefore(ti.index("name").entityKey(null, t2), ti.index("name").entityKey(null, t3)); } @Test public void testNumEncoding() throws Exception { RocksDBTypeInfo.Index idx = newTypeInfo(CustomType1.class).indices().iterator().next(); assertEquals("+=00000001", new String(idx.toKey(1), UTF_8)); assertEquals("+=00000010", new String(idx.toKey(16), UTF_8)); assertEquals("+=7fffffff", new String(idx.toKey(Integer.MAX_VALUE), UTF_8)); assertBefore(idx.toKey(1), idx.toKey(2)); assertBefore(idx.toKey(-1), idx.toKey(2)); assertBefore(idx.toKey(-11), idx.toKey(2)); assertBefore(idx.toKey(-11), idx.toKey(-1)); assertBefore(idx.toKey(1), idx.toKey(11)); assertBefore(idx.toKey(Integer.MIN_VALUE), idx.toKey(Integer.MAX_VALUE)); assertBefore(idx.toKey(1L), idx.toKey(2L)); assertBefore(idx.toKey(-1L), idx.toKey(2L)); assertBefore(idx.toKey(Long.MIN_VALUE), idx.toKey(Long.MAX_VALUE)); assertBefore(idx.toKey((short) 1), idx.toKey((short) 2)); assertBefore(idx.toKey((short) -1), idx.toKey((short) 2)); assertBefore(idx.toKey(Short.MIN_VALUE), idx.toKey(Short.MAX_VALUE)); assertBefore(idx.toKey((byte) 1), idx.toKey((byte) 2)); assertBefore(idx.toKey((byte) -1), idx.toKey((byte) 2)); assertBefore(idx.toKey(Byte.MIN_VALUE), idx.toKey(Byte.MAX_VALUE)); byte prefix = RocksDBTypeInfo.ENTRY_PREFIX; assertSame(new byte[] { prefix, RocksDBTypeInfo.FALSE }, idx.toKey(false)); assertSame(new byte[] { prefix, RocksDBTypeInfo.TRUE }, idx.toKey(true)); } @Test public void testArrayIndices() throws Exception { RocksDBTypeInfo.Index idx = newTypeInfo(CustomType1.class).indices().iterator().next(); assertBefore(idx.toKey(new String[] { "str1" }), idx.toKey(new String[] { "str2" })); assertBefore(idx.toKey(new String[] { "str1", "str2" }), idx.toKey(new String[] { "str1", "str3" })); assertBefore(idx.toKey(new int[] { 1 }), idx.toKey(new int[] { 2 })); assertBefore(idx.toKey(new int[] { 1, 2 }), idx.toKey(new int[] { 1, 3 })); } private RocksDBTypeInfo newTypeInfo(Class<?> type) throws Exception { return new RocksDBTypeInfo(null, type, type.getName().getBytes(UTF_8)); } private void assertBefore(byte[] key1, byte[] key2) { assertBefore(new String(key1, UTF_8), new String(key2, UTF_8)); } private void assertBefore(String str1, String str2) { assertTrue(str1.compareTo(str2) < 0, String.format("%s < %s failed", str1, str2)); } private void assertSame(byte[] key1, byte[] key2) { assertEquals(new String(key1, UTF_8), new String(key2, UTF_8)); } public static
RocksDBTypeInfoSuite
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/BindingToUnqualifiedCommonTypeTest.java
{ "start": 3636, "end": 3830 }
class ____ { // All of the tagged instances would normally be flagged, but aren't because it's in a JUnit4 // class @RunWith(JUnit4.class) static
BindingToUnqualifiedCommonTypeNegativeCases
java
apache__camel
components/camel-xslt/src/main/java/org/apache/camel/component/xslt/XmlSourceHandlerFactoryImpl.java
{ "start": 1490, "end": 5929 }
class ____ implements SourceHandlerFactory { private XMLConverterHelper converter = new XMLConverterHelper(); private boolean isFailOnNullBody = true; /** * Returns true if we fail when the body is null. */ public boolean isFailOnNullBody() { return isFailOnNullBody; } /** * Set if we should fail when the body is null */ public void setFailOnNullBody(boolean failOnNullBody) { isFailOnNullBody = failOnNullBody; } @Override public Source getSource(Exchange exchange, Expression source) throws Exception { // only convert to input stream if really needed if (isInputStreamNeeded(exchange)) { InputStream is = exchange.getIn().getBody(InputStream.class); return getSource(exchange, is); } else { Object body = source != null ? source.evaluate(exchange, Object.class) : exchange.getMessage().getBody(); return getSource(exchange, body); } } /** * Checks whether we need an {@link InputStream} to access the message body. * <p/> * Depending on the content in the message body, we may not need to convert to {@link InputStream}. * * @param exchange the current exchange * @return <tt>true</tt> to convert to {@link InputStream} beforehand converting to {@link Source} * afterwards. */ protected boolean isInputStreamNeeded(Exchange exchange) { Object body = exchange.getIn().getBody(); if (body == null) { return false; } if (body instanceof InputStream) { return true; } else if (body instanceof Source) { return false; } else if (body instanceof String) { return false; } else if (body instanceof byte[]) { return false; } else if (body instanceof Node) { return false; } else if (exchange.getContext().getTypeConverterRegistry().lookup(Source.class, body.getClass()) != null) { //there is a direct and hopefully optimized converter to Source return false; } // yes an input stream is needed return true; } /** * Converts the inbound body to a {@link Source}, if the body is <b>not</b> already a {@link Source}. * <p/> * This implementation will prefer to source in the following order: * <ul> * <li>StAX - If StAX is allowed</li> * <li>SAX - SAX as 2nd choice</li> * <li>Stream - Stream as 3rd choice</li> * <li>DOM - DOM as 4th choice</li> * </ul> */ protected Source getSource(Exchange exchange, Object body) { // body may already be a source if (body instanceof Source) { return (Source) body; } Source source = null; if (body != null) { // then try SAX source = exchange.getContext().getTypeConverter().tryConvertTo(SAXSource.class, exchange, body); if (source == null) { // then try stream source = exchange.getContext().getTypeConverter().tryConvertTo(StreamSource.class, exchange, body); } if (source == null) { // and fallback to DOM source = exchange.getContext().getTypeConverter().tryConvertTo(DOMSource.class, exchange, body); } // as the TypeConverterRegistry will look up source the converter differently if the type converter is loaded different // now we just put the call of source converter at last if (source == null) { TypeConverter tc = exchange.getContext().getTypeConverterRegistry().lookup(Source.class, body.getClass()); if (tc != null) { source = tc.convertTo(Source.class, exchange, body); } } } if (source == null) { if (isFailOnNullBody()) { throw new ExpectedBodyTypeException(exchange, Source.class); } else { try { source = converter.toDOMSource(converter.createDocument()); } catch (ParserConfigurationException | TransformerException e) { throw new RuntimeTransformException(e); } } } return source; } }
XmlSourceHandlerFactoryImpl
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/plugins/RepositoryPlugin.java
{ "start": 1224, "end": 3003 }
interface ____ { /** * Returns repository types added by this plugin. * * @param env The environment for the local node, which may be used for the local settings and path.repo * * The key of the returned {@link Map} is the type name of the repository and * the value is a factory to construct the {@link Repository} interface. */ default Map<String, Repository.Factory> getRepositories( Environment env, NamedXContentRegistry namedXContentRegistry, ClusterService clusterService, BigArrays bigArrays, RecoverySettings recoverySettings, RepositoriesMetrics repositoriesMetrics, SnapshotMetrics snapshotMetrics ) { return Collections.emptyMap(); } /** * Returns internal repository types added by this plugin. Internal repositories cannot be registered * through the external API. * * @param env The environment for the local node, which may be used for the local settings and path.repo * * The key of the returned {@link Map} is the type name of the repository and * the value is a factory to construct the {@link Repository} interface. */ default Map<String, Repository.Factory> getInternalRepositories( Environment env, NamedXContentRegistry namedXContentRegistry, ClusterService clusterService, RecoverySettings recoverySettings ) { return Collections.emptyMap(); } /** * Returns a check that is run on restore. This allows plugins to prevent certain restores from happening. * * returns null if no check is provided */ default BiConsumer<Snapshot, IndexVersion> addPreRestoreVersionCheck() { return null; } }
RepositoryPlugin
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByExpression.java
{ "start": 3747, "end": 4345 }
class ____ extends GuardedByExpression { public abstract GuardedByExpression base(); public static Select create(GuardedByExpression base, Symbol sym, Type type) { return new AutoValue_GuardedByExpression_Select(Kind.SELECT, sym, type, base); } /** Finds this {@link Select}'s nearest non-Select ancestor. */ public GuardedByExpression root() { GuardedByExpression exp = this.base(); while (exp.kind() == Kind.SELECT) { exp = ((Select) exp).base(); } return exp; } } /** Makes {@link GuardedByExpression}s. */ public static
Select
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_16.java
{ "start": 1037, "end": 2756 }
class ____ extends DB2Test { public void test_0() throws Exception { String sql = "SELECT (CURRVAL FOR TEST_SEQ) FROM SYSIBM.SYSDUMMY1"; DB2StatementParser parser = new DB2StatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); 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(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("SYSIBM.SYSDUMMY1"))); // 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 TEST_SEQ.CURRVAL" + "\nFROM SYSIBM.SYSDUMMY1", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2)); assertEquals("select TEST_SEQ.currval" + "\nfrom SYSIBM.SYSDUMMY1", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } }
DB2SelectTest_16
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/GlobalKTable.java
{ "start": 4108, "end": 4407 }
interface ____<K, V> { /** * Get the name of the local state store that can be used to query this {@code GlobalKTable}. * * @return the underlying state store name, or {@code null} if this {@code GlobalKTable} cannot be queried. */ String queryableStoreName(); }
GlobalKTable
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WasmEndpointBuilderFactory.java
{ "start": 1414, "end": 1533 }
interface ____ { /** * Builder for endpoint for the Wasm component. */ public
WasmEndpointBuilderFactory
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/hotreload/CodeChangeTest.java
{ "start": 516, "end": 2537 }
class ____ { @RegisterExtension final static QuarkusDevModeTest TEST = new QuarkusDevModeTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClasses(SomeSource.class, SomeSink.class, SomeProcessor.class)); @Test public void testUpdatingCode() { await().until(() -> get().size() > 5); assertThat(get()).contains("-1", "-2", "-3", "-4"); // Update processor TEST.modifySourceFile("SomeProcessor.java", s -> s.replace("* -1", "* -2")); await().until(() -> get().size() > 5); assertThat(get()).contains("-2", "-4", "-6").doesNotContain("-1", "-3"); // Update source TEST.modifySourceFile("SomeSource.java", s -> s.replace("+ 1", "+ 100")); await().until(() -> get().size() > 5); assertThat(get()).contains("-200", "-202", "-204", "-206"); // Update sink TEST.modifySourceFile("SomeSink.java", s -> s.replace("items.add(l)", "items.add(l+ \"foo\")")); await().until(() -> get().size() > 5); assertThat(get()).contains("-200foo", "-202foo", "-204foo", "-206foo"); } @Test public void testUpdatingAnnotations() { await().until(() -> get().size() > 5); assertThat(get()).contains("-1", "-2", "-3", "-4"); TEST.modifySourceFile("SomeProcessor.java", s -> s.replace("my-source", "my-source-2")); TEST.modifySourceFile("SomeSource.java", s -> s.replace("my-source", "my-source-2")); TEST.modifySourceFile("SomeSink.java", s -> s.replace("my-sink", "my-sink-2")); JsonArray array = get(); Assertions.assertTrue(array.isEmpty()); TEST.modifySourceFile("SomeProcessor.java", s -> s.replace("my-sink", "my-sink-2")); await().until(() -> get().size() > 5); assertThat(get()).contains("-1", "-2", "-3", "-4"); } static JsonArray get() { return new JsonArray(RestAssured.get().asString()); } }
CodeChangeTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/XAttrPermissionFilter.java
{ "start": 2532, "end": 5057 }
class ____ { static void checkPermissionForApi(FSPermissionChecker pc, XAttr xAttr, boolean isRawPath) throws AccessControlException { final boolean isSuperUser = pc.isSuperUser(); final String xAttrString = "XAttr [ns=" + xAttr.getNameSpace() + ", name=" + xAttr.getName() + "]"; if (xAttr.getNameSpace() == XAttr.NameSpace.USER || (xAttr.getNameSpace() == XAttr.NameSpace.TRUSTED && isSuperUser)) { if (isSuperUser) { // call the external enforcer for audit. pc.checkSuperuserPrivilege(xAttrString); } return; } if (xAttr.getNameSpace() == XAttr.NameSpace.RAW && isRawPath) { return; } if (XAttrHelper.getPrefixedName(xAttr). equals(SECURITY_XATTR_UNREADABLE_BY_SUPERUSER)) { if (xAttr.getValue() != null) { // Notify external enforcer for audit String errorMessage = "Attempt to set a value for '" + SECURITY_XATTR_UNREADABLE_BY_SUPERUSER + "'. Values are not allowed for this xattr."; pc.denyUserAccess(xAttrString, errorMessage); } return; } pc.denyUserAccess(xAttrString, "User doesn't have permission for xattr: " + XAttrHelper.getPrefixedName(xAttr)); } static void checkPermissionForApi(FSPermissionChecker pc, List<XAttr> xAttrs, boolean isRawPath) throws AccessControlException { Preconditions.checkArgument(xAttrs != null); if (xAttrs.isEmpty()) { return; } for (XAttr xAttr : xAttrs) { checkPermissionForApi(pc, xAttr, isRawPath); } } static List<XAttr> filterXAttrsForApi(FSPermissionChecker pc, List<XAttr> xAttrs, boolean isRawPath) { assert xAttrs != null : "xAttrs can not be null"; if (xAttrs.isEmpty()) { return xAttrs; } List<XAttr> filteredXAttrs = Lists.newArrayListWithCapacity(xAttrs.size()); final boolean isSuperUser = pc.isSuperUser(); for (XAttr xAttr : xAttrs) { if (xAttr.getNameSpace() == XAttr.NameSpace.USER) { filteredXAttrs.add(xAttr); } else if (xAttr.getNameSpace() == XAttr.NameSpace.TRUSTED && isSuperUser) { filteredXAttrs.add(xAttr); } else if (xAttr.getNameSpace() == XAttr.NameSpace.RAW && isRawPath) { filteredXAttrs.add(xAttr); } else if (XAttrHelper.getPrefixedName(xAttr). equals(SECURITY_XATTR_UNREADABLE_BY_SUPERUSER)) { filteredXAttrs.add(xAttr); } } return filteredXAttrs; } }
XAttrPermissionFilter
java
spring-projects__spring-boot
module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizer.java
{ "start": 1568, "end": 1786 }
interface ____<T extends WebServerFactory> { /** * Customize the specified {@link WebServerFactory}. * @param factory the web server factory to customize */ void customize(T factory); }
WebServerFactoryCustomizer
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java
{ "start": 1370, "end": 3857 }
class ____ extends AbstractMBeanServerTests { @SuppressWarnings("deprecation") private final String serviceUrl = "service:jmx:jmxmp://localhost:" + TestSocketUtils.findAvailableTcpPort(); @Test void noServiceUrl() { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); assertThatIllegalArgumentException() .isThrownBy(bean::afterPropertiesSet) .withMessage("Property 'serviceUrl' is required"); } @Test void validConnection() throws Exception { JMXConnectorServer connectorServer = startConnectorServer(); try { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(this.serviceUrl); bean.afterPropertiesSet(); try { MBeanServerConnection connection = bean.getObject(); assertThat(connection).as("Connection should not be null").isNotNull(); // perform simple MBean count test assertThat(connection.getMBeanCount()).as("MBean count should be the same").isEqualTo(getServer().getMBeanCount()); } finally { bean.destroy(); } } finally { connectorServer.stop(); } } @Test void lazyConnection() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(this.serviceUrl); bean.setConnectOnStartup(false); bean.afterPropertiesSet(); MBeanServerConnection connection = bean.getObject(); assertThat(AopUtils.isAopProxy(connection)).isTrue(); JMXConnectorServer connector = null; try { connector = startConnectorServer(); assertThat(connection.getMBeanCount()).as("Incorrect MBean count").isEqualTo(getServer().getMBeanCount()); } finally { bean.destroy(); if (connector != null) { connector.stop(); } } } @Test void lazyConnectionAndNoAccess() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(this.serviceUrl); bean.setConnectOnStartup(false); bean.afterPropertiesSet(); MBeanServerConnection connection = bean.getObject(); assertThat(AopUtils.isAopProxy(connection)).isTrue(); bean.destroy(); } private JMXConnectorServer startConnectorServer() throws Exception { JMXServiceURL jmxServiceUrl = new JMXServiceURL(this.serviceUrl); JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxServiceUrl, null, getServer()); connectorServer.start(); return connectorServer; } }
MBeanServerConnectionFactoryBeanTests
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/serde/RexNodeJsonSerializer.java
{ "start": 3704, "end": 24611 }
class ____ extends StdSerializer<RexNode> { private static final long serialVersionUID = 1L; // Common fields static final String FIELD_NAME_KIND = "kind"; static final String FIELD_NAME_VALUE = "value"; static final String FIELD_NAME_TYPE = "type"; static final String FIELD_NAME_NAME = "name"; static final String FIELD_NAME_INPUT_INDEX = "inputIndex"; // INPUT_REF static final String KIND_INPUT_REF = "INPUT_REF"; // LITERAL static final String KIND_LITERAL = "LITERAL"; // Sarg fields and values static final String FIELD_NAME_SARG = "sarg"; static final String FIELD_NAME_RANGES = "ranges"; static final String FIELD_NAME_BOUND_LOWER = "lower"; static final String FIELD_NAME_BOUND_UPPER = "upper"; static final String FIELD_NAME_BOUND_TYPE = "boundType"; static final String FIELD_NAME_CONTAINS_NULL = "containsNull"; static final String FIELD_NAME_NULL_AS = "nullAs"; // Symbol fields static final String FIELD_NAME_SYMBOL = "symbol"; // FIELD_ACCESS static final String KIND_FIELD_ACCESS = "FIELD_ACCESS"; static final String FIELD_NAME_EXPR = "expr"; // CORREL_VARIABLE static final String KIND_CORREL_VARIABLE = "CORREL_VARIABLE"; static final String FIELD_NAME_CORREL = "correl"; // PATTERN_INPUT_REF static final String KIND_PATTERN_INPUT_REF = "PATTERN_INPUT_REF"; static final String FIELD_NAME_ALPHA = "alpha"; // CALL static final String KIND_CALL = "CALL"; static final String FIELD_NAME_OPERANDS = "operands"; static final String FIELD_NAME_INTERNAL_NAME = "internalName"; static final String FIELD_NAME_SYSTEM_NAME = "systemName"; static final String FIELD_NAME_CATALOG_NAME = "catalogName"; static final String FIELD_NAME_SYNTAX = "syntax"; static final String FIELD_NAME_SQL_KIND = "sqlKind"; static final String FIELD_NAME_CLASS = "class"; // TABLE_ARG_CALL static final String KIND_TABLE_ARG_CALL = "TABLE_ARG_CALL"; static final String FIELD_NAME_PARTITION_KEYS = "partitionKeys"; static final String FIELD_NAME_ORDER_KEYS = "orderKeys"; RexNodeJsonSerializer() { super(RexNode.class); } @Override public void serialize( RexNode rexNode, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { final ReadableConfig config = SerdeContext.get(serializerProvider).getConfiguration(); final CatalogPlanCompilation compilationStrategy = config.get(TableConfigOptions.PLAN_COMPILE_CATALOG_OBJECTS); switch (rexNode.getKind()) { case INPUT_REF: case TABLE_INPUT_REF: serializeInputRef((RexInputRef) rexNode, jsonGenerator, serializerProvider); break; case LITERAL: serializeLiteral((RexLiteral) rexNode, jsonGenerator, serializerProvider); break; case FIELD_ACCESS: serializeFieldAccess((RexFieldAccess) rexNode, jsonGenerator, serializerProvider); break; case CORREL_VARIABLE: serializeCorrelVariable( (RexCorrelVariable) rexNode, jsonGenerator, serializerProvider); break; case PATTERN_INPUT_REF: serializePatternFieldRef( (RexPatternFieldRef) rexNode, jsonGenerator, serializerProvider); break; default: if (rexNode instanceof RexTableArgCall) { serializeTableArgCall( (RexTableArgCall) rexNode, jsonGenerator, serializerProvider); } else if (rexNode instanceof RexCall) { serializeCall( (RexCall) rexNode, jsonGenerator, serializerProvider, compilationStrategy); } else { throw new TableException("Unknown RexNode: " + rexNode); } } } private static void serializePatternFieldRef( RexPatternFieldRef inputRef, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_PATTERN_INPUT_REF); gen.writeStringField(FIELD_NAME_ALPHA, inputRef.getAlpha()); gen.writeNumberField(FIELD_NAME_INPUT_INDEX, inputRef.getIndex()); serializerProvider.defaultSerializeField(FIELD_NAME_TYPE, inputRef.getType(), gen); gen.writeEndObject(); } private static void serializeInputRef( RexInputRef inputRef, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_INPUT_REF); gen.writeNumberField(FIELD_NAME_INPUT_INDEX, inputRef.getIndex()); serializerProvider.defaultSerializeField(FIELD_NAME_TYPE, inputRef.getType(), gen); gen.writeEndObject(); } private static void serializeLiteral( RexLiteral literal, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_LITERAL); final Comparable<?> value = literal.getValueAs(Comparable.class); if (literal.getTypeName() == SARG) { serializeSargValue((Sarg<?>) value, literal.getType().getSqlTypeName(), gen); } else { serializeLiteralValue(value, literal.getType().getSqlTypeName(), gen); } serializerProvider.defaultSerializeField(FIELD_NAME_TYPE, literal.getType(), gen); gen.writeEndObject(); } private static void serializeLiteralValue( Comparable<?> value, SqlTypeName literalTypeName, JsonGenerator gen) throws IOException { if (value == null) { gen.writeNullField(FIELD_NAME_VALUE); return; } switch (literalTypeName) { case BOOLEAN: gen.writeBooleanField(FIELD_NAME_VALUE, (Boolean) value); break; case TINYINT: gen.writeNumberField(FIELD_NAME_VALUE, ((BigDecimal) value).byteValue()); break; case SMALLINT: gen.writeNumberField(FIELD_NAME_VALUE, ((BigDecimal) value).shortValue()); break; case INTEGER: gen.writeNumberField(FIELD_NAME_VALUE, ((BigDecimal) value).intValue()); break; case BIGINT: gen.writeNumberField(FIELD_NAME_VALUE, ((BigDecimal) value).longValue()); break; case DOUBLE: case FLOAT: case DECIMAL: case INTERVAL_YEAR: case INTERVAL_YEAR_MONTH: case INTERVAL_MONTH: case INTERVAL_DAY: case INTERVAL_DAY_HOUR: case INTERVAL_DAY_MINUTE: case INTERVAL_DAY_SECOND: case INTERVAL_HOUR: case INTERVAL_HOUR_MINUTE: case INTERVAL_HOUR_SECOND: case INTERVAL_MINUTE: case INTERVAL_MINUTE_SECOND: case INTERVAL_SECOND: case DATE: case TIME: case TIMESTAMP: case TIMESTAMP_WITH_LOCAL_TIME_ZONE: gen.writeStringField(FIELD_NAME_VALUE, value.toString()); break; case BINARY: case VARBINARY: gen.writeStringField(FIELD_NAME_VALUE, ((ByteString) value).toBase64String()); break; case CHAR: case VARCHAR: gen.writeStringField(FIELD_NAME_VALUE, ((NlsString) value).getValue()); break; case SYMBOL: final SerializableSymbol symbol = calciteToSerializable((Enum<?>) value); gen.writeStringField(FIELD_NAME_SYMBOL, symbol.getKind()); gen.writeStringField(FIELD_NAME_VALUE, symbol.getValue()); break; default: throw new TableException( String.format( "Literal type '%s' is not supported for serializing value '%s'.", literalTypeName, value)); } } @SuppressWarnings("UnstableApiUsage") private static void serializeSargValue( Sarg<?> value, SqlTypeName sqlTypeName, JsonGenerator gen) throws IOException { gen.writeFieldName(FIELD_NAME_SARG); gen.writeStartObject(); gen.writeFieldName(FIELD_NAME_RANGES); gen.writeStartArray(); for (Range<?> range : value.rangeSet.asRanges()) { gen.writeStartObject(); if (range.hasLowerBound()) { gen.writeFieldName(FIELD_NAME_BOUND_LOWER); gen.writeStartObject(); serializeLiteralValue(range.lowerEndpoint(), sqlTypeName, gen); final SerializableSymbol symbol = calciteToSerializable(range.lowerBoundType()); gen.writeStringField(FIELD_NAME_BOUND_TYPE, symbol.getValue()); gen.writeEndObject(); } if (range.hasUpperBound()) { gen.writeFieldName(FIELD_NAME_BOUND_UPPER); gen.writeStartObject(); serializeLiteralValue(range.upperEndpoint(), sqlTypeName, gen); final SerializableSymbol symbol = calciteToSerializable(range.upperBoundType()); gen.writeStringField(FIELD_NAME_BOUND_TYPE, symbol.getValue()); gen.writeEndObject(); } gen.writeEndObject(); } gen.writeEndArray(); final SerializableSymbol symbol = calciteToSerializable(value.nullAs); gen.writeStringField(FIELD_NAME_NULL_AS, symbol.getValue()); gen.writeEndObject(); } private static void serializeFieldAccess( RexFieldAccess fieldAccess, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_FIELD_ACCESS); gen.writeStringField(FIELD_NAME_NAME, fieldAccess.getField().getName()); serializerProvider.defaultSerializeField( FIELD_NAME_EXPR, fieldAccess.getReferenceExpr(), gen); gen.writeEndObject(); } private static void serializeCorrelVariable( RexCorrelVariable variable, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_CORREL_VARIABLE); gen.writeStringField(FIELD_NAME_CORREL, variable.getName()); serializerProvider.defaultSerializeField(FIELD_NAME_TYPE, variable.getType(), gen); gen.writeEndObject(); } private static void serializeTableArgCall( RexTableArgCall tableArgCall, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_TABLE_ARG_CALL); gen.writeNumberField(FIELD_NAME_INPUT_INDEX, tableArgCall.getInputIndex()); gen.writeFieldName(FIELD_NAME_PARTITION_KEYS); gen.writeArray(tableArgCall.getPartitionKeys(), 0, tableArgCall.getPartitionKeys().length); gen.writeFieldName(FIELD_NAME_ORDER_KEYS); gen.writeArray(tableArgCall.getOrderKeys(), 0, tableArgCall.getOrderKeys().length); serializerProvider.defaultSerializeField(FIELD_NAME_TYPE, tableArgCall.getType(), gen); gen.writeEndObject(); } private static void serializeCall( RexCall call, JsonGenerator gen, SerializerProvider serializerProvider, CatalogPlanCompilation compilationStrategy) throws IOException { gen.writeStartObject(); gen.writeStringField(FIELD_NAME_KIND, KIND_CALL); serializeSqlOperator( call.getOperator(), gen, serializerProvider, compilationStrategy == CatalogPlanCompilation.ALL); gen.writeFieldName(FIELD_NAME_OPERANDS); gen.writeStartArray(); for (RexNode operand : call.getOperands()) { serializerProvider.defaultSerializeValue(operand, gen); } gen.writeEndArray(); serializerProvider.defaultSerializeField(FIELD_NAME_TYPE, call.getType(), gen); gen.writeEndObject(); } // -------------------------------------------------------------------------------------------- /** Logic shared with {@link AggregateCallJsonSerializer}. */ static void serializeSqlOperator( SqlOperator operator, JsonGenerator gen, SerializerProvider serializerProvider, boolean serializeCatalogObjects) throws IOException { if (operator.getSyntax() != SqlSyntax.FUNCTION) { gen.writeStringField( FIELD_NAME_SYNTAX, calciteToSerializable(operator.getSyntax()).getValue()); } if (operator instanceof BridgingSqlFunction) { final BridgingSqlFunction function = (BridgingSqlFunction) operator; serializeBridgingSqlFunction( function.getName(), function.getResolvedFunction(), gen, serializerProvider, serializeCatalogObjects); } else if (operator instanceof BridgingSqlAggFunction) { final BridgingSqlAggFunction function = (BridgingSqlAggFunction) operator; serializeBridgingSqlFunction( function.getName(), function.getResolvedFunction(), gen, serializerProvider, serializeCatalogObjects); } else if (operator instanceof ScalarSqlFunction || operator instanceof TableSqlFunction || operator instanceof AggSqlFunction) { throw legacyException(operator.toString()); } else { if (operator.getName().isEmpty()) { gen.writeStringField(FIELD_NAME_SQL_KIND, operator.getKind().name()); } else { // We assume that all regular SqlOperators are internal. Only the function // definitions // stack is exposed to the user and can thus be external. gen.writeStringField( FIELD_NAME_INTERNAL_NAME, BuiltInSqlOperator.toQualifiedName(operator)); } } } private static void serializeBridgingSqlFunction( String summaryName, ContextResolvedFunction resolvedFunction, JsonGenerator gen, SerializerProvider serializerProvider, boolean serializeCatalogObjects) throws IOException { final FunctionDefinition definition = resolvedFunction.getDefinition(); if (definition instanceof ScalarFunctionDefinition || definition instanceof TableFunctionDefinition || definition instanceof TableAggregateFunctionDefinition || definition instanceof AggregateFunctionDefinition) { throw legacyException(summaryName); } if (definition instanceof BuiltInFunctionDefinition) { final BuiltInFunctionDefinition builtInFunction = (BuiltInFunctionDefinition) definition; gen.writeStringField(FIELD_NAME_INTERNAL_NAME, builtInFunction.getQualifiedName()); } else if (resolvedFunction.isAnonymous()) { serializeInlineFunction(summaryName, definition, gen); } else if (resolvedFunction.isTemporary()) { serializeTemporaryFunction(resolvedFunction, gen, serializerProvider); } else { assert resolvedFunction.isPermanent(); serializePermanentFunction( resolvedFunction, gen, serializerProvider, serializeCatalogObjects); } } private static void serializeInlineFunction( String summaryName, FunctionDefinition definition, JsonGenerator gen) throws IOException { if (!(definition instanceof UserDefinedFunction) || !isClassNameSerializable((UserDefinedFunction) definition)) { throw cannotSerializeInlineFunction(summaryName); } gen.writeStringField(FIELD_NAME_CLASS, definition.getClass().getName()); } private static void serializeTemporaryFunction( ContextResolvedFunction resolvedFunction, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { assert resolvedFunction.getIdentifier().isPresent(); final FunctionIdentifier identifier = resolvedFunction.getIdentifier().get(); if (identifier.getSimpleName().isPresent()) { gen.writeStringField(FIELD_NAME_SYSTEM_NAME, identifier.getSimpleName().get()); } else { assert identifier.getIdentifier().isPresent(); serializerProvider.defaultSerializeField( FIELD_NAME_CATALOG_NAME, identifier.getIdentifier().get(), gen); } } private static void serializePermanentFunction( ContextResolvedFunction resolvedFunction, JsonGenerator gen, SerializerProvider serializerProvider, boolean serializeCatalogObjects) throws IOException { final FunctionIdentifier identifier = resolvedFunction .getIdentifier() .orElseThrow( () -> new IllegalArgumentException( "Permanent functions should own a function identifier.")); if (identifier.getSimpleName().isPresent()) { // Module provided system function gen.writeStringField(FIELD_NAME_SYSTEM_NAME, identifier.getSimpleName().get()); } else { assert identifier.getIdentifier().isPresent(); serializeCatalogFunction( identifier.getIdentifier().get(), resolvedFunction, gen, serializerProvider, serializeCatalogObjects); } } private static void serializeCatalogFunction( ObjectIdentifier objectIdentifier, ContextResolvedFunction resolvedFunction, JsonGenerator gen, SerializerProvider serializerProvider, boolean serializeCatalogObjects) throws IOException { serializerProvider.defaultSerializeField(FIELD_NAME_CATALOG_NAME, objectIdentifier, gen); if (!serializeCatalogObjects) { return; } if (resolvedFunction.getCatalogFunction() != null && !resolvedFunction.getCatalogFunction().getOptions().isEmpty()) { throw new TableException( String.format( "Catalog functions with custom options can not be serialized into the " + "compiled plan. Please set the option '%s'='%s' to only" + " serialize the function's identifier.", TableConfigOptions.PLAN_COMPILE_CATALOG_OBJECTS.key(), CatalogPlanCompilation.IDENTIFIER)); } final FunctionDefinition definition = resolvedFunction.getDefinition(); if (!(definition instanceof UserDefinedFunction) || !isClassNameSerializable((UserDefinedFunction) definition)) { throw cannotSerializePermanentCatalogFunction(objectIdentifier); } gen.writeStringField(FIELD_NAME_CLASS, definition.getClass().getName()); } private static TableException legacyException(String summaryName) { return new TableException( String.format( "Functions of the deprecated function stack are not supported. " + "Please update '%s' to the new interfaces.", summaryName)); } private static TableException cannotSerializeInlineFunction(String summaryName) { return new TableException( String.format( "Anonymous function '%s' is not serializable. The function's implementation " + "
RexNodeJsonSerializer
java
google__guice
core/test/com/google/inject/ScopesTest.java
{ "start": 11933, "end": 12596 }
class ____ extends AbstractModule { @Override protected void configure() { bindScope(NotRuntimeRetainedScoped.class, Scopes.NO_SCOPE); } } @Test public void testScopeAnnotationWithoutRuntimeRetention() { try { Guice.createInjector(new OuterRuntimeModule()); fail(); } catch (CreationException expected) { assertContains( expected.getMessage(), "Please annotate ScopesTest$NotRuntimeRetainedScoped with @Retention(RUNTIME).", "at ScopesTest$InnerRuntimeModule.configure", "ScopesTest$OuterRuntimeModule -> ScopesTest$InnerRuntimeModule"); } } static
InnerRuntimeModule
java
apache__camel
components/camel-infinispan/camel-infinispan-embedded/src/generated/java/org/apache/camel/component/infinispan/embedded/InfinispanEmbeddedProducerInvokeOnHeaderFactory.java
{ "start": 432, "end": 1085 }
class ____ implements InvokeOnHeaderStrategy { @Override public Object invoke(Object obj, String key, Exchange exchange, AsyncCallback callback) throws Exception { org.apache.camel.component.infinispan.embedded.InfinispanEmbeddedProducer target = (org.apache.camel.component.infinispan.embedded.InfinispanEmbeddedProducer) obj; switch (key) { case "query": case "QUERY": target.onQuery(exchange.getMessage()); return null; case "stats": case "STATS": target.onStats(exchange.getMessage()); return null; default: return null; } } }
InfinispanEmbeddedProducerInvokeOnHeaderFactory
java
apache__camel
components/camel-test/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestContextLoaderTestExecutionListener.java
{ "start": 1056, "end": 1364 }
class ____ in {@link CamelSpringTestHelper} * almost immediately before the loader initializes the Spring context. * <p/> * Implemented as a listener as the state can be set on a {@code ThreadLocal} and we are pretty sure that the same * thread will be used to initialize the Spring context. */ public
state
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
{ "start": 59325, "end": 59914 }
class ____ { private final Object actual = new LongAdder(); @Test void createAssert() { // WHEN LongAdderAssert result = LONG_ADDER.createAssert(actual); // THEN result.hasValue(0L); } @Test void createAssert_with_ValueProvider() { // GIVEN ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual); // WHEN LongAdderAssert result = LONG_ADDER.createAssert(valueProvider); // THEN result.hasValue(0L); verify(valueProvider).apply(LongAdder.class); } } @Nested
LongAdder_Factory
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/PropertyConfigurerGetter.java
{ "start": 850, "end": 1194 }
interface ____ identify the object as being a configurer which can provide details about the options the * configurer supports. * <p/> * This is used in Camel to have fast property configuration of Camel components & endpoints, and for EIP patterns as * well. * * @see PropertyConfigurer * @see ExtendedPropertyConfigurerGetter */ public
to
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java
{ "start": 854, "end": 907 }
enum ____ { TYPE_A, TYPE_B, TYPE_C }
TestEnum
java
quarkusio__quarkus
independent-projects/qute/generator/src/main/java/io/quarkus/qute/generator/ValueResolverGenerator.java
{ "start": 11298, "end": 46048 }
interface ____ target = clazz; while (target != null) { for (DotName interfaceName : target.interfaceNames()) { ClassInfo interfaceClass = index.getClassByName(interfaceName); if (interfaceClass == null) { LOGGER.warnf("Skipping implemented interface %s - not found in the index", interfaceName); continue; } for (MethodInfo method : interfaceClass.methods()) { if (method.isDefault() && filter.test(method)) { methods.add(new MethodKey(method)); } } } DotName superName = target.superName(); if (ignoreSuperclasses || target.isEnum() || superName == null || superName.equals(DotNames.OBJECT)) { target = null; } else { target = index.getClassByName(superName); } } // Sort methods, getters must come before is/has properties, etc. List<MethodKey> sortedMethods = methods.stream().sorted().toList(); return new ScanResult(fields, sortedMethods); } record ScanResult(List<FieldInfo> fields, List<MethodKey> methods) { boolean isEmpty() { return fields.isEmpty() && methods.isEmpty(); } List<MethodKey> noParamMethods() { return methods().stream().filter(m -> m.method.parametersCount() == 0).toList(); } // name, number of params -> list of methods; excluding no-args methods Map<Match, List<MethodInfo>> argsMatches() { Map<Match, List<MethodInfo>> ret = new HashMap<>(); for (MethodKey methodKey : methods) { MethodInfo method = methodKey.method; if (method.parametersCount() != 0) { Match match = new Match(method.name(), method.parametersCount()); List<MethodInfo> methodMatches = ret.get(match); if (methodMatches == null) { methodMatches = new ArrayList<>(); ret.put(match, methodMatches); } methodMatches.add(method); } } return ret; } Map<Match, List<MethodInfo>> varargsMatches() { Map<Match, List<MethodInfo>> ret = new HashMap<>(); for (MethodKey methodKey : methods) { MethodInfo method = methodKey.method; if (method.parametersCount() != 0 && isVarArgs(method)) { // The last argument is a sequence of arguments -> match name and min number of params // getList(int age, String... names) -> "getList", 1 Match match = new Match(method.name(), method.parametersCount() - 1); List<MethodInfo> methodMatches = ret.get(match); if (methodMatches == null) { methodMatches = new ArrayList<>(); ret.put(match, methodMatches); } methodMatches.add(method); } } return ret; } } private void implementGetPriority(ClassCreator valueResolver, int priority) { valueResolver.method("getPriority", mc -> { mc.returning(int.class); mc.body(bc -> bc.return_(priority)); }); } private void implementGetNamespace(ClassCreator namespaceResolver, String namespace) { namespaceResolver.method("getNamespace", mc -> { mc.returning(String.class); mc.body(bc -> bc.return_(namespace)); }); } private void implementResolve(ClassCreator valueResolver, String clazzName, ClassInfo clazz, ScanResult result) { valueResolver.method("resolve", mc -> { mc.returning(CompletionStage.class); ParamVar evalContext = mc.parameter("ec", EvalContext.class); mc.body(bc -> { LocalVar base = bc.localVar("base", bc.invokeInterface(Descriptors.GET_BASE, evalContext)); LocalVar name = bc.localVar("name", bc.invokeInterface(Descriptors.GET_NAME, evalContext)); List<MethodKey> noParamMethods = result.noParamMethods(); Map<Match, List<MethodInfo>> argsMatches = result.argsMatches(); Map<Match, List<MethodInfo>> varargsMatches = result.varargsMatches(); LocalVar params = null, paramsCount = null; if (!argsMatches.isEmpty() || !varargsMatches.isEmpty()) { // Only create the local variables if needed params = bc.localVar("params", bc.invokeInterface(Descriptors.GET_PARAMS, evalContext)); paramsCount = bc.localVar("paramsCount", bc.invokeInterface(Descriptors.COLLECTION_SIZE, params)); } Function<FieldInfo, String> fieldToGetterFun = forceGettersFunction != null ? forceGettersFunction.apply(clazz) : null; if (!noParamMethods.isEmpty() || !result.fields().isEmpty()) { Expr hasNoParams; if (paramsCount != null) { hasNoParams = bc.eq(paramsCount, 0); } else { hasNoParams = bc.invokeStatic(Descriptors.VALUE_RESOLVERS_HAS_NO_PARAMS, evalContext); } bc.if_(hasNoParams, zeroParams -> { zeroParams.switch_(name, sc -> { Set<String> matchedNames = new HashSet<>(); for (MethodKey methodKey : noParamMethods) { // No params - just invoke the method if the name matches MethodInfo method = methodKey.method; List<String> matchingNames = new ArrayList<>(); if (matchedNames.add(method.name())) { matchingNames.add(method.name()); } String propertyName = isGetterName(method.name(), method.returnType()) ? getPropertyName(method.name()) : null; if (propertyName != null // No method with exact name match exists && noParamMethods.stream().noneMatch(mk -> mk.name.equals(propertyName)) && matchedNames.add(propertyName)) { matchingNames.add(propertyName); } if (matchingNames.isEmpty()) { continue; } LOGGER.debugf("No-args method added %s", method); sc.case_(cac -> { for (String matchingName : matchingNames) { cac.of(matchingName); } cac.body(cbc -> { Type returnType = method.returnType(); Expr invokeRet = method.declaringClass().isInterface() ? cbc.invokeInterface(methodDescOf(method), base) : cbc.invokeVirtual(methodDescOf(method), base); processReturnVal(cbc, returnType, invokeRet, valueResolver); }); }); } for (FieldInfo field : result.fields()) { String getterName = fieldToGetterFun != null ? fieldToGetterFun.apply(field) : null; if (getterName != null && noneMethodMatches(noParamMethods, getterName) && matchedNames.add(getterName)) { LOGGER.debugf("Forced getter added: %s", field); List<String> matching; if (matchedNames.add(field.name())) { matching = List.of(getterName, field.name()); } else { matching = List.of(getterName); } sc.case_(cac -> { for (String matchingName : matching) { cac.of(matchingName); } cac.body(cbc -> { Expr val = clazz.isInterface() ? cbc.invokeInterface(InterfaceMethodDesc.of(classDescOf(clazz), getterName, MethodTypeDesc.of(classDescOf(field.type()))), base) : cbc.invokeVirtual(ClassMethodDesc.of(classDescOf(clazz), getterName, MethodTypeDesc.of(classDescOf(field.type()))), base); processReturnVal(cbc, field.type(), val, valueResolver); }); }); } else if (matchedNames.add(field.name())) { LOGGER.debugf("Field added: %s", field); sc.caseOf(Const.of(field.name()), cac -> { Expr castBase = cac.cast(base, classDescOf(field.declaringClass())); Expr val = castBase.field(fieldDescOf(field)); processReturnVal(cac, field.type(), val, valueResolver); }); } } }); }); } // Match methods by name and number of params for (Entry<Match, List<MethodInfo>> entry : argsMatches.entrySet()) { Match match = entry.getKey(); // The set of matching methods is made up of the methods matching the name and number of params + varargs methods matching the name and minimal number of params // For example both the methods getList(int age, String... names) and getList(int age) match "getList" and 1 param Set<MethodInfo> methodMatches = new HashSet<>(entry .getValue()); varargsMatches.entrySet().stream() .filter(e -> e.getKey().name.equals(match.name) && e.getKey().paramsCount >= match.paramsCount) .forEach(e -> methodMatches.addAll(e.getValue())); if (methodMatches.size() == 1) { // Single method matches the name and number of params matchMethod(methodMatches.iterator().next(), clazz, bc, base, name, params, paramsCount, evalContext); } else { // Multiple methods match the name and number of params matchMethods(match.name, match.paramsCount, methodMatches, clazz, bc, base, name, params, paramsCount, evalContext); } } // For varargs methods we also need to match name and any number of params Map<String, List<MethodInfo>> varargsMap = new HashMap<>(); for (Entry<Match, List<MethodInfo>> entry : varargsMatches.entrySet()) { List<MethodInfo> list = varargsMap.get(entry.getKey().name); if (list == null) { list = new ArrayList<>(); varargsMap.put(entry.getKey().name, list); } list.addAll(entry.getValue()); } for (Entry<String, List<MethodInfo>> entry : varargsMap.entrySet()) { matchMethods(entry.getKey(), Integer.MIN_VALUE, entry.getValue(), clazz, bc, base, name, params, paramsCount, evalContext); } // No result found bc.return_(bc.invokeStatic(Descriptors.RESULTS_NOT_FOUND_EC, evalContext)); }); }); } private void implementNamespaceResolve(ClassCreator valueResolver, String clazzName, ClassInfo clazz, ScanResult result) { valueResolver.method("resolve", mc -> { mc.returning(CompletionStage.class); ParamVar evalContext = mc.parameter("ec", EvalContext.class); mc.body(bc -> { LocalVar base = bc.localVar("base", bc.invokeInterface(Descriptors.GET_BASE, evalContext)); LocalVar name = bc.localVar("name", bc.invokeInterface(Descriptors.GET_NAME, evalContext)); List<MethodKey> noParamMethods = result.noParamMethods(); Map<Match, List<MethodInfo>> argsMatches = result.argsMatches(); Map<Match, List<MethodInfo>> varargsMatches = result.varargsMatches(); LocalVar params = null, paramsCount = null; if (!argsMatches.isEmpty() || !varargsMatches.isEmpty()) { // Only create the local variables if needed params = bc.localVar("params", bc.invokeInterface(Descriptors.GET_PARAMS, evalContext)); paramsCount = bc.localVar("paramsCount", bc.invokeInterface(Descriptors.COLLECTION_SIZE, params)); } if (!noParamMethods.isEmpty() || !result.fields().isEmpty()) { Expr hasNoParams; if (paramsCount != null) { hasNoParams = bc.eq(paramsCount, 0); } else { hasNoParams = bc.invokeStatic(Descriptors.VALUE_RESOLVERS_HAS_NO_PARAMS, evalContext); } bc.if_(hasNoParams, zeroParams -> { zeroParams.switch_(name, sc -> { Set<String> matchedNames = new HashSet<>(); // no-args methods for (MethodKey methodKey : noParamMethods) { MethodInfo method = methodKey.method; List<String> matchingNames = new ArrayList<>(); if (matchedNames.add(method.name())) { matchingNames.add(method.name()); } String propertyName = isGetterName(method.name(), method.returnType()) ? getPropertyName(method.name()) : null; if (propertyName != null // No method with exact name match exists && noParamMethods.stream().noneMatch(mk -> mk.name.equals(propertyName)) && matchedNames.add(propertyName)) { matchingNames.add(propertyName); } if (matchingNames.isEmpty()) { continue; } // No params - just invoke the method if the name matches LOGGER.debugf("No-args static method added %s", method); sc.case_(cac -> { for (String matchingName : matchingNames) { cac.of(matchingName); } cac.body(cbc -> { Type returnType = method.returnType(); Expr invokeRet = cbc.invokeStatic(methodDescOf(method)); processReturnVal(cbc, returnType, invokeRet, valueResolver); }); }); } // fields for (FieldInfo field : result.fields()) { if (matchedNames.add(field.name())) { LOGGER.debugf("Static field added: %s", field); sc.caseOf(Const.of(field.name()), cbc -> { Expr val = cbc.getStaticField(fieldDescOf(field)); processReturnVal(cbc, field.type(), val, valueResolver); }); } } }); }); } // Match methods by name and number of params for (Entry<Match, List<MethodInfo>> entry : argsMatches.entrySet()) { Match match = entry.getKey(); // The set of matching methods is made up of the methods matching the name and number of params + varargs methods matching the name and minimal number of params // For example both the methods getList(int age, String... names) and getList(int age) match "getList" and 1 param Set<MethodInfo> methodMatches = new HashSet<>(entry.getValue()); varargsMatches.entrySet().stream() .filter(e -> e.getKey().name.equals(match.name) && e.getKey().paramsCount >= match.paramsCount) .forEach(e -> methodMatches.addAll(e.getValue())); if (methodMatches.size() == 1) { // Single method matches the name and number of params matchMethod(methodMatches.iterator().next(), clazz, bc, base, name, params, paramsCount, evalContext); } else { // Multiple methods match the name and number of params matchMethods(match.name, match.paramsCount, methodMatches, clazz, bc, base, name, params, paramsCount, evalContext); } } // For varargs methods we also need to match name and any number of params Map<String, List<MethodInfo>> varargsMap = new HashMap<>(); for (Entry<Match, List<MethodInfo>> entry : varargsMatches.entrySet()) { List<MethodInfo> list = varargsMap.get(entry.getKey().name); if (list == null) { list = new ArrayList<>(); varargsMap.put(entry.getKey().name, list); } list.addAll(entry.getValue()); } for (Entry<String, List<MethodInfo>> entry : varargsMap.entrySet()) { matchMethods(entry.getKey(), Integer.MIN_VALUE, entry.getValue(), clazz, bc, base, name, params, paramsCount, evalContext); } // No result found bc.return_(bc.invokeStatic(Descriptors.RESULTS_NOT_FOUND_EC, evalContext)); }); }); } private void matchMethod(MethodInfo method, ClassInfo clazz, BlockCreator resolve, LocalVar base, LocalVar name, LocalVar params, LocalVar paramsCount, ParamVar evalContext) { List<Type> methodParams = method.parameterTypes(); LOGGER.debugf("Method added %s", method); ifMethodMatch(resolve, method.name(), methodParams.size(), method.returnType(), name, params, paramsCount, bc -> { // Invoke the method // Evaluate the params first LocalVar ret = bc.localVar("ret", bc.new_(CompletableFuture.class)); LocalVar evaluatedParams = bc.localVar("evaluatedParams", bc.invokeStatic(Descriptors.EVALUATED_PARAMS_EVALUATE, evalContext)); // The CompletionStage upon which we invoke whenComplete() Expr paramsReady = evaluatedParams.field(Descriptors.EVALUATED_PARAMS_STAGE); Expr whenCompleteFun = bc.lambda(BiConsumer.class, lc -> { Var capturedBase = lc.capture(base); Var capturedRet = lc.capture(ret); Var capturedEvaluatedParams = lc.capture(evaluatedParams); Var capturedEvalContext = lc.capture(evalContext); ParamVar result = lc.parameter("r", 0); ParamVar throwable = lc.parameter("t", 1); lc.body(whenComplete -> { whenComplete.ifElse(whenComplete.isNull(throwable), success -> { // Check type parameters and return NO_RESULT if failed LocalVar paramTypesArray = success.localVar("pt", success.newArray(Class.class, method.parameterTypes() .stream() .map(parameterType -> Const.of(classDescOf(parameterType))) .toList())); success.ifNot( success.invokeVirtual(Descriptors.EVALUATED_PARAMS_PARAM_TYPES_MATCH, capturedEvaluatedParams, Const.of(isVarArgs(method)), paramTypesArray), typeMatchFailed -> { typeMatchFailed.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE, capturedRet, typeMatchFailed.invokeStatic(Descriptors.NOT_FOUND_FROM_EC, capturedEvalContext)); typeMatchFailed.return_(); }); doInvoke(success, capturedRet, capturedEvaluatedParams, capturedBase, result, method); }, failure -> { // CompletableFuture.completeExceptionally(Throwable) failure.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, capturedRet, throwable); }); whenComplete.return_(); }); }); bc.invokeInterface(Descriptors.CF_WHEN_COMPLETE, paramsReady, whenCompleteFun); bc.return_(ret); }); } private void doInvoke(BlockCreator bc, Var capturedRet, Var capturedEvaluatedParams, Var capturedBase, ParamVar result, MethodInfo method) { LocalVar invokeRet = bc.localVar("ret", Const.ofNull(Object.class)); List<Type> parameterTypes = method.parameterTypes(); bc.try_(tc -> { tc.body(tryBlock -> { Var[] args = new Var[parameterTypes.size()]; if (isVarArgs(method)) { // For varargs the number of results may be higher than the number of method params // First get the regular params for (int i = 0; i < parameterTypes.size() - 1; i++) { LocalVar arg = tryBlock.localVar("arg" + i, tryBlock.invokeVirtual( Descriptors.EVALUATED_PARAMS_GET_RESULT, capturedEvaluatedParams, Const.of(i))); args[i] = arg; } // Then we need to create an array for the last argument Type varargsParam = parameterTypes.get(parameterTypes.size() - 1); Expr constituentType = Const .of(classDescOf(varargsParam.asArrayType().constituent())); LocalVar varargsResults = tryBlock.localVar("vararg", tryBlock.invokeVirtual( Descriptors.EVALUATED_PARAMS_GET_VARARGS_RESULTS, capturedEvaluatedParams, Const.of(parameterTypes.size()), constituentType)); // E.g. String, String, String -> String, String[] args[parameterTypes.size() - 1] = varargsResults; } else { if (parameterTypes.size() == 1) { args[0] = result; } else { for (int i = 0; i < parameterTypes.size(); i++) { LocalVar arg = tryBlock.localVar("arg" + i, tryBlock.invokeVirtual( Descriptors.EVALUATED_PARAMS_GET_RESULT, capturedEvaluatedParams, Const.of(i))); args[i] = arg; } } } // Now call the method if (Modifier.isStatic(method.flags())) { tryBlock.set(invokeRet, tryBlock.invokeStatic(methodDescOf(method), args)); } else { if (method.declaringClass().isInterface()) { tryBlock.set(invokeRet, tryBlock.invokeInterface(methodDescOf(method), capturedBase, args)); } else { tryBlock.set(invokeRet, tryBlock.invokeVirtual(methodDescOf(method), capturedBase, args)); } } if (hasCompletionStage(method.returnType())) { Expr fun2 = tryBlock.lambda(BiConsumer.class, lc2 -> { Var capturedRet2 = lc2.capture(capturedRet); ParamVar result2 = lc2.parameter("r", 0); ParamVar throwable2 = lc2.parameter("t", 1); lc2.body(whenComplete2 -> { whenComplete2.ifNull(throwable2, success2 -> { success2.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE, capturedRet2, result2); success2.return_(); }); whenComplete2.invokeVirtual( Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, capturedRet2, throwable2); whenComplete2.return_(); }); }); tryBlock.invokeInterface(Descriptors.CF_WHEN_COMPLETE, invokeRet, fun2); } else { tryBlock.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE, capturedRet, invokeRet); } }); tc.catch_(Throwable.class, "t", (cb, e) -> { cb.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, capturedRet, e); }); }); } private void matchMethods(String matchName, int matchParamsCount, Collection<MethodInfo> methods, ClassInfo clazz, BlockCreator resolve, LocalVar base, LocalVar name, LocalVar params, LocalVar paramsCount, ParamVar evalContext) { LOGGER.debugf("Methods added %s", methods); ifMethodMatch(resolve, matchName, matchParamsCount, null, name, params, paramsCount, bc -> { // Invoke the method, if available // Evaluate the params first LocalVar ret = bc.localVar("ret", bc.new_(CompletableFuture.class)); // The CompletionStage upon which we invoke whenComplete() LocalVar evaluatedParams = bc.localVar("evaluatedParams", bc.invokeStatic(Descriptors.EVALUATED_PARAMS_EVALUATE, evalContext)); Expr paramsReady = evaluatedParams.field(Descriptors.EVALUATED_PARAMS_STAGE); Expr whenCompleteFun = bc.lambda(BiConsumer.class, lc -> { Var capturedBase = lc.capture(base); Var capturedRet = lc.capture(ret); Var capturedEvaluatedParams = lc.capture(evaluatedParams); Var capturedEvalContext = lc.capture(evalContext); ParamVar result = lc.parameter("r", 0); ParamVar throwable = lc.parameter("t", 1); lc.body(whenComplete -> { whenComplete.ifElse(whenComplete.isNull(throwable), success -> { for (MethodInfo method : methods) { boolean isVarArgs = isVarArgs(method); success.block(nested -> { // Try to match parameter types LocalVar paramTypesArray = nested.localVar("pt", nested.newArray(Class.class, method.parameterTypes() .stream() .map(parameterType -> Const.of(classDescOf(parameterType))) .toList())); nested.ifNot( nested.invokeVirtual(Descriptors.EVALUATED_PARAMS_PARAM_TYPES_MATCH, capturedEvaluatedParams, Const.of(isVarArgs), paramTypesArray), notMatched -> notMatched.break_(nested)); // Parameters matched doInvoke(nested, capturedRet, capturedEvaluatedParams, capturedBase, result, method); nested.return_(); }); } // No method matches - result not found success.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE, capturedRet, success.invokeStatic(Descriptors.NOT_FOUND_FROM_EC, capturedEvalContext)); success.return_(); }, failure -> { // CompletableFuture.completeExceptionally(Throwable) failure.invokeVirtual(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, capturedRet, throwable); failure.return_(); }); }); }); bc.invokeInterface(Descriptors.CF_WHEN_COMPLETE, paramsReady, whenCompleteFun); bc.return_(ret); }); } private void ifMethodMatch(BlockCreator bc, String methodName, int methodParams, Type returnType, LocalVar name, LocalVar params, LocalVar paramsCount, Consumer<BlockCreator> whenMatch) { bc.block(nested -> { // Match name if (methodParams <= 0 && isGetterName(methodName, returnType)) { // Getter found - match the property name first nested.ifNot(nested.objEquals(name, Const.of(getPropertyName(methodName))), propertyNotMatched -> { // If the property does not match then try to use the exact method name propertyNotMatched.ifNot(propertyNotMatched.objEquals(name, Const.of(methodName)), nameNotMatched -> { nameNotMatched.break_(nested); }); }); } else { // No getter - only match the exact method name nested.ifNot(nested.objEquals(name, Const.of(methodName)), notMatched -> { notMatched.break_(nested); }); } // Match number of params if (methodParams >= 0) { nested.ifNot(nested.eq(paramsCount, methodParams), notMatched -> { notMatched.break_(nested); }); } whenMatch.accept(nested); }); } private void implementAppliesTo(ClassCreator valueResolver, ClassInfo clazz) { valueResolver.method("appliesTo", mc -> { mc.returning(boolean.class); ParamVar evalContext = mc.parameter("ec", EvalContext.class); mc.body(bc -> { bc.return_(bc.invokeStatic(Descriptors.VALUE_RESOLVERS_MATCH_CLASS, evalContext, Const.of(classDescOf(clazz)))); }); }); } public static
methods
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/PartitionAccessor.java
{ "start": 282, "end": 1303 }
class ____ { private final Collection<RedisClusterNode> partitions; PartitionAccessor(Collection<RedisClusterNode> partitions) { this.partitions = partitions; } List<RedisClusterNode> getUpstream() { return get(redisClusterNode -> redisClusterNode.is(RedisClusterNode.NodeFlag.UPSTREAM)); } List<RedisClusterNode> getReadCandidates(RedisClusterNode upstream) { return get(redisClusterNode -> redisClusterNode.getNodeId().equals(upstream.getNodeId()) || (redisClusterNode.is(RedisClusterNode.NodeFlag.REPLICA) && upstream.getNodeId().equals(redisClusterNode.getSlaveOf()))); } List<RedisClusterNode> get(Predicate<RedisClusterNode> test) { List<RedisClusterNode> result = new ArrayList<>(partitions.size()); for (RedisClusterNode partition : partitions) { if (test.test(partition)) { result.add(partition); } } return result; } }
PartitionAccessor
java
quarkusio__quarkus
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoCollection.java
{ "start": 22665, "end": 23702 }
class ____ decode each document into * @param <D> the target document type of the iterable. * @param options the stream options * @return the stream of changes */ <D> Multi<ChangeStreamDocument<D>> watch(ClientSession clientSession, Class<D> clazz, ChangeStreamOptions options); /** * Creates a change stream for this collection. * * @param clientSession the client session with which to associate this operation * @param pipeline the aggregation pipeline to apply to the change stream * @param options the stream options * @return the stream of changes */ Multi<ChangeStreamDocument<Document>> watch(ClientSession clientSession, List<? extends Bson> pipeline, ChangeStreamOptions options); /** * Creates a change stream for this collection. * * @param clientSession the client session with which to associate this operation * @param pipeline the aggregation pipeline to apply to the change stream * @param clazz the
to
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/config/InProcess.java
{ "start": 304, "end": 551 }
interface ____ extends Enabled { /** * Explicitly enable use of in-process. */ @WithDefault("false") boolean enabled(); /** * Set in-process name. */ @WithDefault("quarkus-grpc") String name(); }
InProcess
java
elastic__elasticsearch
x-pack/plugin/snapshot-repo-test-kit/src/main/java/org/elasticsearch/repositories/blobstore/testkit/integrity/TransportRepositoryVerifyIntegrityAction.java
{ "start": 2924, "end": 8086 }
class ____ extends LegacyActionRequest { private final DiscoveryNode coordinatingNode; private final long coordinatingTaskId; private final RepositoryVerifyIntegrityParams requestParams; Request(DiscoveryNode coordinatingNode, long coordinatingTaskId, RepositoryVerifyIntegrityParams requestParams) { this.coordinatingNode = coordinatingNode; this.coordinatingTaskId = coordinatingTaskId; this.requestParams = Objects.requireNonNull(requestParams); } Request(StreamInput in) throws IOException { super(in); coordinatingNode = new DiscoveryNode(in); coordinatingTaskId = in.readVLong(); requestParams = new RepositoryVerifyIntegrityParams(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); coordinatingNode.writeTo(out); out.writeVLong(coordinatingTaskId); requestParams.writeTo(out); } @Override public ActionRequestValidationException validate() { return null; } @Override public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) { return new RepositoryVerifyIntegrityTask(id, type, action, getDescription(), parentTaskId, headers); } } @Override protected void doExecute(Task rawTask, Request request, ActionListener<RepositoryVerifyIntegrityResponse> listener) { final var responseWriter = new RepositoryVerifyIntegrityResponseChunk.Writer() { // no need to obtain a fresh connection each time - this connection shouldn't close, so if it does we can fail the verification final Transport.Connection responseConnection = transportService.getConnection(request.coordinatingNode); @Override public void writeResponseChunk(RepositoryVerifyIntegrityResponseChunk responseChunk, ActionListener<Void> listener) { transportService.sendChildRequest( responseConnection, TransportRepositoryVerifyIntegrityResponseChunkAction.ACTION_NAME, new TransportRepositoryVerifyIntegrityResponseChunkAction.Request(request.coordinatingTaskId, responseChunk), rawTask, TransportRequestOptions.EMPTY, new ActionListenerResponseHandler<TransportResponse>( listener.map(ignored -> null), in -> ActionResponse.Empty.INSTANCE, executor ) ); } }; final LongSupplier currentTimeMillisSupplier = transportService.getThreadPool()::absoluteTimeInMillis; final var repository = (BlobStoreRepository) repositoriesService.repository(request.requestParams.repository()); final var task = (RepositoryVerifyIntegrityTask) rawTask; SubscribableListener .<RepositoryData>newForked(l -> repository.getRepositoryData(executor, l)) .andThenApply(repositoryData -> { ensureValidGenId(repositoryData.getGenId()); final var cancellableThreads = new CancellableThreads(); task.addListener(() -> cancellableThreads.cancel("task cancelled")); final var verifier = new RepositoryIntegrityVerifier( currentTimeMillisSupplier, repository, responseWriter, request.requestParams.withResolvedDefaults(repository.threadPool().info(ThreadPool.Names.SNAPSHOT_META)), repositoryData, cancellableThreads ); task.setStatusSupplier(verifier::getStatus); return verifier; }) .<RepositoryIntegrityVerifier>andThen( (l, repositoryIntegrityVerifier) -> new RepositoryVerifyIntegrityResponseChunk.Builder( responseWriter, RepositoryVerifyIntegrityResponseChunk.Type.START_RESPONSE, currentTimeMillisSupplier.getAsLong() ).write(l.map(ignored -> repositoryIntegrityVerifier)) ) .<RepositoryVerifyIntegrityResponse>andThen((l, repositoryIntegrityVerifier) -> repositoryIntegrityVerifier.start(l)) .addListener(listener); } static void ensureValidGenId(long repositoryGenId) { if (repositoryGenId == RepositoryData.EMPTY_REPO_GEN) { throw new IllegalArgumentException("repository is empty, cannot verify its integrity"); } if (repositoryGenId < 0) { final var exception = new IllegalStateException( "repository is in an unexpected state [" + repositoryGenId + "], cannot verify its integrity" ); assert false : exception; // cannot be unknown, and if corrupt we throw a corruptedStateException from getRepositoryData throw exception; } } }
Request
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/GridmixJob.java
{ "start": 17008, "end": 17205 }
class ____<V> extends Partitioner<GridmixKey,V> { public int getPartition(GridmixKey key, V value, int numReduceTasks) { return key.getPartition(); } } public static
DraftPartitioner
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2300/Issue2358.java
{ "start": 1291, "end": 1697 }
class ____ { private String test1; private String test2; public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } } }
TestJson2
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 95297, "end": 96065 }
class ____<K, V> { abstract MyMapBuilder<K, V> mapBuilder(); abstract BuildMyMap<K, V> build(); } } @Test public void testMyMapBuilder() { BuildMyMap.Builder<String, Integer> builder = BuildMyMap.builder(); MyMapBuilder<String, Integer> mapBuilder = builder.mapBuilder(); mapBuilder.put("23", 23); BuildMyMap<String, Integer> built = builder.build(); assertThat(built.map()).containsExactly("23", 23); BuildMyMap.Builder<String, Integer> builder2 = built.toBuilder(); MyMapBuilder<String, Integer> mapBuilder2 = builder2.mapBuilder(); mapBuilder2.put("17", 17); BuildMyMap<String, Integer> built2 = builder2.build(); assertThat(built2.map()).containsExactly("23", 23, "17", 17); } public static
Builder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProvider.java
{ "start": 4542, "end": 6742 }
class ____ implements ThreadFactory, Thread.UncaughtExceptionHandler { private static final Logger LOG = LoggerFactory.getLogger(SourceCoordinatorProvider.class); private final String coordinatorThreadName; private final ClassLoader cl; private final Thread.UncaughtExceptionHandler errorHandler; @Nullable private Thread t; CoordinatorExecutorThreadFactory( final String coordinatorThreadName, final OperatorCoordinator.Context context) { this( coordinatorThreadName, context.getUserCodeClassloader(), (t, e) -> { LOG.error( "Thread '{}' produced an uncaught exception. Failing the job.", t.getName(), e); context.failJob(e); }); } CoordinatorExecutorThreadFactory( final String coordinatorThreadName, final ClassLoader contextClassLoader, final Thread.UncaughtExceptionHandler errorHandler) { this.coordinatorThreadName = coordinatorThreadName; this.cl = contextClassLoader; this.errorHandler = errorHandler; } @Override public synchronized Thread newThread(Runnable r) { checkState( t == null, "Please using the new CoordinatorExecutorThreadFactory," + " this factory cannot new multiple threads."); t = new Thread(r, coordinatorThreadName); t.setContextClassLoader(cl); t.setUncaughtExceptionHandler(this); return t; } @Override public synchronized void uncaughtException(Thread t, Throwable e) { errorHandler.uncaughtException(t, e); } String getCoordinatorThreadName() { return coordinatorThreadName; } boolean isCurrentThreadCoordinatorThread() { return Thread.currentThread() == t; } } }
CoordinatorExecutorThreadFactory
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/CxfrsComponentBuilderFactory.java
{ "start": 1949, "end": 7198 }
interface ____ extends ComponentBuilder<CxfRsComponent> { /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default CxfrsComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default CxfrsComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Sets whether synchronous processing should be strictly used. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param synchronous the value to set * @return the dsl builder */ default CxfrsComponentBuilder synchronous(boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default CxfrsComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter * header to and from Camel message. * * The option is a: * &lt;code&gt;org.apache.camel.spi.HeaderFilterStrategy&lt;/code&gt; * type. * * Group: filter * * @param headerFilterStrategy the value to set * @return the dsl builder */ default CxfrsComponentBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Enable usage of global SSL context parameters. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useGlobalSslContextParameters the value to set * @return the dsl builder */ default CxfrsComponentBuilder useGlobalSslContextParameters(boolean useGlobalSslContextParameters) { doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters); return this; } }
CxfrsComponentBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java
{ "start": 1018, "end": 1796 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JUnit4TestNotRun.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(JUnit4TestNotRun.class, getClass()); @Test public void positiveCase1() { compilationHelper .addSourceLines( "JUnit4TestNotRunPositiveCase1.java", """ package com.google.errorprone.bugpatterns.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public
JUnit4TestNotRunTest
java
apache__hadoop
hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/SimpleKMSAuditLogger.java
{ "start": 1698, "end": 3497 }
class ____ implements KMSAuditLogger { final private Logger auditLog = LoggerFactory.getLogger(KMS_LOGGER_NAME); @Override public void cleanup() throws IOException { } @Override public void initialize(Configuration conf) throws IOException { } @Override public void logAuditEvent(final OpStatus status, final AuditEvent event) { if (!Strings.isNullOrEmpty(event.getUser()) && !Strings .isNullOrEmpty(event.getKeyName()) && (event.getOp() != null) && KMSAudit.AGGREGATE_OPS_WHITELIST.contains(event.getOp())) { switch (status) { case OK: auditLog.info( "{}[op={}, key={}, user={}, accessCount={}, interval={}ms] {}", status, event.getOp(), event.getKeyName(), event.getUser(), event.getAccessCount().get(), (event.getEndTime() - event.getStartTime()), event.getExtraMsg()); break; case UNAUTHORIZED: logAuditSimpleFormat(status, event); break; default: logAuditSimpleFormat(status, event); break; } } else { logAuditSimpleFormat(status, event); } } private void logAuditSimpleFormat(final OpStatus status, final AuditEvent event) { final List<String> kvs = new LinkedList<>(); if (event.getOp() != null) { kvs.add("op=" + event.getOp()); } if (!Strings.isNullOrEmpty(event.getKeyName())) { kvs.add("key=" + event.getKeyName()); } if (!Strings.isNullOrEmpty(event.getUser())) { kvs.add("user=" + event.getUser()); } if (kvs.isEmpty()) { auditLog.info("{} {}", status, event.getExtraMsg()); } else { final String join = Joiner.on(", ").join(kvs); auditLog.info("{}[{}] {}", status, join, event.getExtraMsg()); } } }
SimpleKMSAuditLogger
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/Float2DArrayAssert.java
{ "start": 1279, "end": 13886 }
class ____ extends Abstract2DArrayAssert<Float2DArrayAssert, float[][], Float> { // TODO reduce the visibility of the fields annotated with @VisibleForTesting protected Float2DArrays float2dArrays = Float2DArrays.instance(); private final Failures failures = Failures.instance(); public Float2DArrayAssert(float[][] actual) { super(actual, Float2DArrayAssert.class); } /** * Verifies that the actual {@code float[][]} is <b>deeply</b> equal to the given one. * <p> * Two arrays are considered deeply equal if both are {@code null} * or if they refer to arrays that contain the same number of elements and * all corresponding pairs of elements in the two arrays are deeply equal. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}}).isDeepEqualTo(new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}}); * * // assertions will fail * assertThat(new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}}).isDeepEqualTo(new float[][] {{1.0f, 2.0f}, {9.0f, 10.0f}}); * assertThat(new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}}).isDeepEqualTo(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f}});</code></pre> * * @param expected the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is not deeply equal to the given one. */ @Override public Float2DArrayAssert isDeepEqualTo(float[][] expected) { if (actual == expected) return myself; isNotNull(); if (expected.length != actual.length) { throw failures.failure(info, shouldHaveSameSizeAs(actual, expected, actual.length, expected.length)); } for (int i = 0; i < actual.length; i++) { float[] actualSubArray = actual[i]; float[] expectedSubArray = expected[i]; if (actualSubArray == expectedSubArray) continue; if (actualSubArray == null) throw failures.failure(info, shouldNotBeNull("actual[" + i + "]")); if (expectedSubArray.length != actualSubArray.length) { throw failures.failure(info, subarraysShouldHaveSameSize(actual, expected, actualSubArray, actualSubArray.length, expectedSubArray, expectedSubArray.length, i), info.representation().toStringOf(actual), info.representation().toStringOf(expected)); } for (int j = 0; j < actualSubArray.length; j++) { if (actualSubArray[j] != expectedSubArray[j]) { throw failures.failure(info, elementShouldBeEqual(actualSubArray[j], expectedSubArray[j], i, j), info.representation().toStringOf(actual), info.representation().toStringOf(expected)); } } } return myself; } /** * Verifies that the actual {@code float[][]} is equal to the given one. * <p> * <b>WARNING!</b> This method will use {@code equals} to compare (it will compare arrays references only).<br> * Unless you specify a comparator with {@link #usingComparator(Comparator)}, it is advised to use * {@link #isDeepEqualTo(float[][])} instead. * <p> * Example: * <pre><code class='java'> float[][] array = {{1.0f, 2.0f}, {3.0f, 4.0f}}; * * // assertion will pass * assertThat(array).isEqualTo(array); * * // assertion will fail as isEqualTo calls equals which compares arrays references only. * assertThat(array).isEqualTo(new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}});</code></pre> * * @param expected the given value to compare the actual {@code float[][]} to. * @return {@code this} assertion object. * @throws AssertionError if the actual {@code float[][]} is not equal to the given one. */ @Override public Float2DArrayAssert isEqualTo(Object expected) { return super.isEqualTo(expected); } /** * Verifies that the actual {@code float[][]} is {@code null} or empty, empty means the array has no elements, * said otherwise it can have any number of rows but all rows must be empty. * <p> * Example: * <pre><code class='java'> // assertions will pass * float[][] array = null; * assertThat(array).isNullOrEmpty(); * assertThat(new float[][] { }).isNullOrEmpty(); * assertThat(new float[][] {{ }}).isNullOrEmpty(); * // this is considered empty as there are no elements in the 2d array which is comprised of 3 empty rows. * assertThat(new float[][] {{ }, { }, { }}).isNullOrEmpty(); * * // assertion will fail * assertThat(new float[][] {{ 1.0 }, { 2.0 }}).isNullOrEmpty();</code></pre> * * @throws AssertionError if the actual {@code float[][]} is not {@code null} or not empty. */ @Override public void isNullOrEmpty() { float2dArrays.assertNullOrEmpty(info, actual); } /** * Verifies that the actual {@code float[][]} is empty, empty means the array has no elements, * said otherwise it can have any number of rows but all rows must be empty. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat(new float[][] {{}}).isEmpty(); * // this is considered empty as there are no elements in the 2d array which is comprised of 3 empty rows. * assertThat(new float[][] {{ }, { }, { }}).isEmpty(); * * // assertions will fail * assertThat(new float[][] {{ 1.0 }, { 2.0 }}).isEmpty(); * float[][] array = null; * assertThat(array).isEmpty();</code></pre> * * @throws AssertionError if the actual {@code float[][]} is not empty. */ @Override public void isEmpty() { float2dArrays.assertEmpty(info, actual); } /** * Verifies that the actual {@code float[][]} is not empty, not empty means the array has at least one element. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat(new float[][] {{ 1.0 }, { 2.0 }}).isNotEmpty(); * assertThat(new float[][] {{ }, { 2.0 }}).isNotEmpty(); * * // assertions will fail * assertThat(new float[][] { }).isNotEmpty(); * assertThat(new float[][] {{ }}).isNotEmpty(); * // this is considered empty as there are no elements in the 2d array which is comprised of 3 empty rows. * assertThat(new float[][] {{ }, { }, { }}).isNotEmpty(); * float[][] array = null; * assertThat(array).isNotEmpty();</code></pre> * * @return {@code this} assertion object. * @throws AssertionError if the actual {@code float[][]} is empty or null. */ @Override public Float2DArrayAssert isNotEmpty() { float2dArrays.assertNotEmpty(info, actual); return myself; } /** * Verifies that the actual {@code float[][]} has the given dimensions. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}).hasDimensions(2, 3); * * // assertions will fail * assertThat(new float[][] { }).hasSize(1, 1); * assertThat(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}).hasDimensions(3, 2); * assertThat(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f, 7.0f}}).hasDimensions(2, 3); </code></pre> * * @param expectedFirstDimension the expected number of values in first dimension of the actual {@code float[][]}. * @param expectedSecondDimension the expected number of values in second dimension of the actual {@code float[][]}. * @return {@code this} assertion object. * @throws AssertionError if the actual {@code float[][]}'s dimensions are not equal to the given ones. */ @Override public Float2DArrayAssert hasDimensions(int expectedFirstDimension, int expectedSecondDimension) { float2dArrays.assertHasDimensions(info, actual, expectedFirstDimension, expectedSecondDimension); return myself; } /** * Verifies that the actual two-dimensional array has the given number of rows. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}).hasNumberOfRows(2); * assertThat(new float[][] {{1.0f}, {1.0f, 2.0f}, {1.0f, 2.0f, 3.0f}}).hasNumberOfRows(3); * * // assertions will fail * assertThat(new float[][] { }).hasNumberOfRows(1); * assertThat(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}).hasNumberOfRows(3); * assertThat(new float[][] {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f, 7.0f}}).hasNumberOfRows(1); </code></pre> * * @param expected the expected number of rows of the two-dimensional array. * @return {@code this} assertion object. * @throws AssertionError if the actual number of rows are not equal to the given one. */ @Override public Float2DArrayAssert hasNumberOfRows(int expected) { float2dArrays.assertNumberOfRows(info, actual, expected); return myself; } /** * Verifies that the actual {@code float[][]} has the same dimensions as the given array. * <p> * Parameter is declared as Object to accept both Object and primitive arrays. * </p> * Example: * <pre><code class='java'> float[][] floatArray = {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}; * char[][] charArray = {{'a', 'b', 'c'}, {'d', 'e', 'f'}}; * * // assertion will pass * assertThat(floatArray).hasSameDimensionsAs(charArray); * * // assertions will fail * assertThat(floatArray).hasSameDimensionsAs(new char[][] {{'a', 'b'}, {'c', 'd'}, {'e', 'f'}}); * assertThat(floatArray).hasSameDimensionsAs(new char[][] {{'a', 'b'}, {'c', 'd', 'e'}}); * assertThat(floatArray).hasSameDimensionsAs(new char[][] {{'a', 'b', 'c'}, {'d', 'e'}});</code></pre> * * @param array the array to compare dimensions with actual {@code float[][]}. * @return {@code this} assertion object. * @throws AssertionError if the actual {@code float[][]} is {@code null}. * @throws AssertionError if the array parameter is {@code null} or is not a true array. * @throws AssertionError if actual {@code float[][]} and given array don't have the same dimensions. */ @Override public Float2DArrayAssert hasSameDimensionsAs(Object array) { float2dArrays.assertHasSameDimensionsAs(info, actual, array); return myself; } /** * Verifies that the actual array contains the given float[] at the given index. * <p> * Example: * <pre><code class='java'> float[][] values = new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}, {5.0f, 6.0f}}; * * // assertion will pass * assertThat(values).contains(new float[] {1.0f, 2.0f}, atIndex(O)) * .contains(new float[] {5.0f, 6.0f}, atIndex(2)); * * // assertions will fail * assertThat(values).contains(new float[] {1.0f, 2.0f}, atIndex(1)); * assertThat(values).contains(new float[] {7.0f, 8.0f}, atIndex(2));</code></pre> * * @param value the value to look for. * @param index the index where the value should be stored in the actual array. * @return {@code this} assertion object. * @throws AssertionError if the actual array is {@code null} or empty. * @throws NullPointerException if the given {@code Index} is {@code null}. * @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of * the actual array. * @throws AssertionError if the actual array does not contain the given value at the given index. */ public Float2DArrayAssert contains(float[] value, Index index) { float2dArrays.assertContains(info, actual, value, index); return myself; } /** * Verifies that the actual array does not contain the given float[] at the given index. * <p> * Example: * <pre><code class='java'> float[][] values = new float[][] {{1.0f, 2.0f}, {3.0f, 4.0f}, {5.0f, 6.0f}}; * * // assertion will pass * assertThat(values).doesNotContain(new float[] {1.0f, 2.0f}, atIndex(1)) * .doesNotContain(new float[] {3.0f, 4.0f}, atIndex(0)); * * // assertion will fail * assertThat(values).doesNotContain(new float[] {1.0f, 2.0f}, atIndex(0));</code></pre> * * @param value the value to look for. * @param index the index where the value should be stored in the actual array. * @return {@code this} assertion object. * @throws AssertionError if the actual array is {@code null}. * @throws NullPointerException if the given {@code Index} is {@code null}. * @throws AssertionError if the actual array contains the given value at the given index. */ public Float2DArrayAssert doesNotContain(float[] value, Index index) { float2dArrays.assertDoesNotContain(info, actual, value, index); return myself; } }
Float2DArrayAssert
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/support/jsse/SecureRandomParameters.java
{ "start": 1022, "end": 3788 }
class ____ extends JsseParameters { private static final Logger LOG = LoggerFactory.getLogger(SecureRandomParameters.class); protected String algorithm; protected String provider; /** * Returns a {@code SecureRandom} instance initialized using the configured algorithm and provider, if specified. * * @return the configured instance * * @throws GeneralSecurityException if the algorithm is not implemented by any registered provider or if the * identified provider does not exist. */ public SecureRandom createSecureRandom() throws GeneralSecurityException { LOG.debug("Creating SecureRandom from SecureRandomParameters: {}", this); SecureRandom secureRandom; if (this.getProvider() != null) { secureRandom = SecureRandom.getInstance(this.parsePropertyValue(this.getAlgorithm()), this.parsePropertyValue(this.getProvider())); } else { secureRandom = SecureRandom.getInstance(this.parsePropertyValue(this.getAlgorithm())); } LOG.debug("SecureRandom [{}] is using provider [{}] and algorithm [{}].", secureRandom, secureRandom.getProvider(), secureRandom.getAlgorithm()); return secureRandom; } public String getAlgorithm() { return algorithm; } /** * Sets the Random Number Generator (RNG) algorithm identifier for the {@link SecureRandom} factory method used to * create the {@link SecureRandom} represented by this object's configuration. * * See https://docs.oracle.com/en/java/javase/17/docs/specs/security/standard-names.html * * @param value the algorithm identifier */ public void setAlgorithm(String value) { this.algorithm = value; } public String getProvider() { return provider; } /** * Sets the optional provider identifier for the {@link SecureRandom} factory method used to create the * {@link SecureRandom} represented by this object's configuration. * * @param value the provider identifier or {@code null} to use the highest priority provider implementing the * desired algorithm * * @see Security#getProviders() */ public void setProvider(String value) { this.provider = value; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("SecureRandomParameters[algorithm="); builder.append(algorithm); builder.append(", provider="); builder.append(provider); builder.append("]"); return builder.toString(); } }
SecureRandomParameters
java
apache__spark
sql/core/src/test/java/test/org/apache/spark/sql/connector/JavaAdvancedDataSourceV2WithV2Filter.java
{ "start": 1662, "end": 2022 }
class ____ implements TestingV2Source { @Override public Table getTable(CaseInsensitiveStringMap options) { return new JavaSimpleBatchTable() { @Override public ScanBuilder newScanBuilder(CaseInsensitiveStringMap options) { return new AdvancedScanBuilderWithV2Filter(); } }; } static
JavaAdvancedDataSourceV2WithV2Filter
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/internal/DefaultMethods.java
{ "start": 1288, "end": 5470 }
enum ____ { /** * Open (via reflection construction of {@link Lookup}) method handle lookup. Works with Java 8 and with Java 9 * permitting illegal access. */ OPEN { private final Optional<Constructor<Lookup>> constructor = getLookupConstructor(); @Override MethodHandle lookup(Method method) throws ReflectiveOperationException { Constructor<Lookup> constructor = this.constructor .orElseThrow(() -> new IllegalStateException("Could not obtain MethodHandles.lookup constructor")); return constructor.newInstance(method.getDeclaringClass()).unreflectSpecial(method, method.getDeclaringClass()); } @Override boolean isAvailable() { return constructor.isPresent(); } }, /** * Encapsulated {@link MethodHandle} lookup working on Java 9. */ ENCAPSULATED { Method privateLookupIn = findBridgeMethod(); @Override MethodHandle lookup(Method method) throws ReflectiveOperationException { MethodType methodType = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); return getLookup(method.getDeclaringClass()).findSpecial(method.getDeclaringClass(), method.getName(), methodType, method.getDeclaringClass()); } private Method findBridgeMethod() { try { return MethodHandles.class.getDeclaredMethod("privateLookupIn", Class.class, Lookup.class); } catch (ReflectiveOperationException e) { return null; } } private Lookup getLookup(Class<?> declaringClass) { Lookup lookup = MethodHandles.lookup(); if (privateLookupIn != null) { try { return (Lookup) privateLookupIn.invoke(null, declaringClass, lookup); } catch (ReflectiveOperationException e) { return lookup; } } return lookup; } @Override boolean isAvailable() { return true; } }; /** * Lookup a {@link MethodHandle} given {@link Method} to look up. * * @param method must not be {@code null}. * @return the method handle. * @throws ReflectiveOperationException */ abstract MethodHandle lookup(Method method) throws ReflectiveOperationException; /** * @return {@code true} if the lookup is available. */ abstract boolean isAvailable(); /** * Obtain the first available {@link MethodHandleLookup}. * * @return the {@link MethodHandleLookup} * @throws IllegalStateException if no {@link MethodHandleLookup} is available. */ public static MethodHandleLookup getMethodHandleLookup() { return Arrays.stream(MethodHandleLookup.values()).filter(MethodHandleLookup::isAvailable).findFirst() .orElseThrow(() -> new IllegalStateException("No MethodHandleLookup available!")); } private static Optional<Constructor<Lookup>> getLookupConstructor() { try { Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return Optional.of(constructor); } catch (Exception ex) { // this is the signal that we are on Java 9 (encapsulated) and can't use the accessible constructor approach. if (ex.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) { return Optional.empty(); } throw new IllegalStateException(ex); } } } }
MethodHandleLookup
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/IntraQueueCandidatesSelector.java
{ "start": 2343, "end": 2955 }
class ____ implements Serializable, Comparator<TempAppPerPartition> { @Override public int compare(TempAppPerPartition ta1, TempAppPerPartition ta2) { Priority p1 = Priority.newInstance(ta1.getPriority()); Priority p2 = Priority.newInstance(ta2.getPriority()); if (!p1.equals(p2)) { return p1.compareTo(p2); } return ta1.getApplicationId().compareTo(ta2.getApplicationId()); } } /* * Order first by amount used from least to most. Then order from oldest to * youngest if amount used is the same. */ static
TAPriorityComparator
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/ColumnLoadOperatorTests.java
{ "start": 746, "end": 3203 }
class ____ extends OperatorTestCase { @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { return new SequenceIntBlockSourceOperator(blockFactory, IntStream.range(0, size).map(l -> between(0, 4))); } @Override protected void assertSimpleOutput(List<Page> input, List<Page> results) { int count = input.stream().mapToInt(Page::getPositionCount).sum(); assertThat(results.stream().mapToInt(Page::getPositionCount).sum(), equalTo(count)); int keysIdx = 0; int loadedIdx = 0; IntBlock keys = null; int keysOffset = 0; LongBlock loaded = null; int loadedOffset = 0; int p = 0; while (p < count) { if (keys == null) { keys = input.get(keysIdx++).getBlock(0); } if (loaded == null) { loaded = results.get(loadedIdx++).getBlock(1); } int valueCount = keys.getValueCount(p - keysOffset); assertThat(loaded.getValueCount(p - loadedOffset), equalTo(valueCount)); int keysStart = keys.getFirstValueIndex(p - keysOffset); int loadedStart = loaded.getFirstValueIndex(p - loadedOffset); for (int k = keysStart, l = loadedStart; k < keysStart + valueCount; k++, l++) { assertThat(loaded.getLong(l), equalTo(3L * keys.getInt(k))); } p++; if (p - keysOffset == keys.getPositionCount()) { keysOffset += keys.getPositionCount(); keys = null; } if (p - loadedOffset == loaded.getPositionCount()) { loadedOffset += loaded.getPositionCount(); loaded = null; } } } @Override protected Operator.OperatorFactory simple(SimpleOptions options) { return new ColumnLoadOperator.Factory( new ColumnLoadOperator.Values( "values", TestBlockFactory.getNonBreakingInstance().newLongArrayVector(new long[] { 0, 3, 6, 9, 12 }, 5).asBlock() ), 0 ); } @Override protected Matcher<String> expectedDescriptionOfSimple() { return equalTo("ColumnLoad[values=values:LONG, positions=0]"); } @Override protected Matcher<String> expectedToStringOfSimple() { return expectedDescriptionOfSimple(); } }
ColumnLoadOperatorTests
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java
{ "start": 3007, "end": 9139 }
class ____ { private static final String CONFIG_LOCATION_PREFIX = "classpath:org/springframework/security/config/http/FormLoginConfigTests"; public final SpringTestContext spring = new SpringTestContext(this); @Autowired MockMvc mvc; @Test public void getProtectedPageWhenFormLoginConfiguredThenRedirectsToDefaultLoginPage() throws Exception { this.spring.configLocations(this.xml("WithRequestMatcher")).autowire(); // @formatter:off this.mvc.perform(get("/")) .andExpect(redirectedUrl("/login")); // @formatter:on } @Test public void authenticateWhenDefaultTargetUrlConfiguredThenRedirectsAccordingly() throws Exception { this.spring.configLocations(this.xml("WithDefaultTargetUrl")).autowire(); // @formatter:off MockHttpServletRequestBuilder loginRequest = post("/login") .param("username", "user") .param("password", "password") .with(csrf()); this.mvc.perform(loginRequest) .andExpect(redirectedUrl("/default")); // @formatter:on } @Test public void authenticateWhenConfiguredWithSpelThenRedirectsAccordingly() throws Exception { this.spring.configLocations(this.xml("UsingSpel")).autowire(); // @formatter:off MockHttpServletRequestBuilder loginRequest = post("/login") .param("username", "user") .param("password", "password") .with(csrf()); this.mvc.perform(loginRequest) .andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/default")); MockHttpServletRequestBuilder invalidPassword = post("/login") .param("username", "user") .param("password", "wrong") .with(csrf()); this.mvc.perform(invalidPassword) .andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/failure")); this.mvc.perform(get("/")) .andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/login")); // @formatter:on } @Test public void autowireWhenLoginPageIsMisconfiguredThenDetects() { assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashLoginPage")).autowire()); } @Test public void autowireWhenDefaultTargetUrlIsMisconfiguredThenDetects() { assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashDefaultTargetUrl")).autowire()); } @Test public void authenticateWhenCustomHandlerBeansConfiguredThenInvokesAccordingly() throws Exception { this.spring.configLocations(this.xml("WithSuccessAndFailureHandlers")).autowire(); // @formatter:off MockHttpServletRequestBuilder loginRequest = post("/login") .param("username", "user") .param("password", "password") .with(csrf()); this.mvc.perform(loginRequest) .andExpect(status().isIAmATeapot()); MockHttpServletRequestBuilder invalidPassword = post("/login") .param("username", "user") .param("password", "wrong") .with(csrf()); this.mvc.perform(invalidPassword) .andExpect(status().isIAmATeapot()); // @formatter:on } @Test public void authenticateWhenCustomUsernameAndPasswordParametersThenSucceeds() throws Exception { this.spring.configLocations(this.xml("WithUsernameAndPasswordParameters")).autowire(); this.mvc.perform(post("/login").param("xname", "user").param("xpass", "password").with(csrf())) .andExpect(redirectedUrl("/")); } @Test public void authenticateWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { this.spring.configLocations(this.xml("WithCustomSecurityContextHolderStrategy")).autowire(); SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class); this.mvc.perform(post("/login").with(csrf())).andExpect(redirectedUrl("/login?error")); verify(strategy, atLeastOnce()).getContext(); } /** * SEC-2919 - DefaultLoginGeneratingFilter incorrectly used if login-url="/login" */ @Test public void autowireWhenCustomLoginPageIsSlashLoginThenNoDefaultLoginPageGeneratingFilterIsWired() throws Exception { this.spring.configLocations(this.xml("ForSec2919")).autowire(); this.mvc.perform(get("/login")).andExpect(content().string("teapot")); assertThat(getFilter(this.spring.getContext(), DefaultLoginPageGeneratingFilter.class)).isNull(); } @Test public void authenticateWhenCsrfIsEnabledThenRequiresToken() throws Exception { this.spring.configLocations(this.xml("WithCsrfEnabled")).autowire(); // @formatter:off MockHttpServletRequestBuilder loginRequest = post("/login") .param("username", "user") .param("password", "password"); this.mvc.perform(loginRequest) .andExpect(status().isForbidden()); // @formatter:on } @Test public void authenticateWhenCsrfIsDisabledThenDoesNotRequireToken() throws Exception { this.spring.configLocations(this.xml("WithCsrfDisabled")).autowire(); // @formatter:off MockHttpServletRequestBuilder loginRequest = post("/login") .param("username", "user") .param("password", "password"); this.mvc.perform(loginRequest) .andExpect(status().isFound()); // @formatter:on } /** * SEC-3147: authentication-failure-url should be contained "error" parameter if * login-page="/login" */ @Test public void authenticateWhenLoginPageIsSlashLoginAndAuthenticationFailsThenRedirectContainsErrorParameter() throws Exception { this.spring.configLocations(this.xml("ForSec3147")).autowire(); // @formatter:off MockHttpServletRequestBuilder loginRequest = post("/login") .param("username", "user") .param("password", "wrong") .with(csrf()); this.mvc.perform(loginRequest) .andExpect(redirectedUrl("/login?error")); // @formatter:on } private Filter getFilter(ApplicationContext context, Class<? extends Filter> filterClass) { FilterChainProxy filterChain = context.getBean(BeanIds.FILTER_CHAIN_PROXY, FilterChainProxy.class); List<Filter> filters = filterChain.getFilters("/any"); for (Filter filter : filters) { if (filter.getClass() == filterClass) { return filter; } } return null; } private String xml(String configName) { return CONFIG_LOCATION_PREFIX + "-" + configName + ".xml"; } @RestController public static
FormLoginConfigTests
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java
{ "start": 1362, "end": 3296 }
class ____ extends AbstractLookup { private static final Logger LOGGER = StatusLogger.getLogger(); private static final Marker LOOKUP = MarkerManager.getMarker("LOOKUP"); /** JNDI resource path prefix used in a J2EE container */ static final String CONTAINER_JNDI_RESOURCE_PATH_PREFIX = "java:comp/env/"; /** * Constructs a new instance or throw IllegalStateException if this feature is disabled. */ public JndiLookup() { if (!JndiManager.isJndiLookupEnabled()) { throw new IllegalStateException("JNDI must be enabled by setting log4j2.enableJndiLookup=true"); } } /** * Looks up the value of the JNDI resource. * * @param key the JNDI resource name to be looked up, may be null * @return The String value of the JNDI resource. */ @Override public String lookup(final LogEvent ignored, final String key) { if (key == null) { return null; } final String jndiName = convertJndiName(key); try (final JndiManager jndiManager = JndiManager.getDefaultManager()) { return Objects.toString(jndiManager.lookup(jndiName), null); } catch (final NamingException e) { LOGGER.warn(LOOKUP, "Error looking up JNDI resource [{}].", jndiName, e); return null; } } /** * Convert the given JNDI name to the actual JNDI name to use. Default implementation applies the "java:comp/env/" * prefix unless other scheme like "java:" is given. * * @param jndiName The name of the resource. * @return The fully qualified name to look up. */ private String convertJndiName(final String jndiName) { if (!jndiName.startsWith(CONTAINER_JNDI_RESOURCE_PATH_PREFIX) && jndiName.indexOf(':') == -1) { return CONTAINER_JNDI_RESOURCE_PATH_PREFIX + jndiName; } return jndiName; } }
JndiLookup
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java
{ "start": 52046, "end": 58912 }
class ____ { @ParameterizedTest @ValueSource(strings = { "testWithRepeatableCsvFileSource", "testWithRepeatableCsvFileSourceAsMetaAnnotation" }) void executesWithRepeatableCsvFileSource(String methodName) { var results = execute(methodName, String.class, String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] column1 = foo, column2 = 1"), finishedWithFailure(message("foo 1")))) // .haveExactly(1, event(test(), displayName("[5] FRUIT = apple, RANK = 1"), finishedWithFailure(message("apple 1")))); } @ParameterizedTest @ValueSource(strings = { "testWithRepeatableCsvSource", "testWithRepeatableCsvSourceAsMetaAnnotation" }) void executesWithRepeatableCsvSource(String methodName) { var results = execute(methodName, String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = a"), finishedWithFailure(message("a")))) // .haveExactly(1, event(test(), displayName("[2] argument = b"), finishedWithFailure(message("b")))); } @ParameterizedTest @ValueSource(strings = { "testWithRepeatableMethodSource", "testWithRepeatableMethodSourceAsMetaAnnotation" }) void executesWithRepeatableMethodSource(String methodName) { var results = execute(methodName, String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = some"), finishedWithFailure(message("some")))) // .haveExactly(1, event(test(), displayName("[2] argument = other"), finishedWithFailure(message("other")))); } @ParameterizedTest @ValueSource(strings = { "testWithRepeatableEnumSource", "testWithRepeatableEnumSourceAsMetaAnnotation" }) void executesWithRepeatableEnumSource(String methodName) { var results = execute(methodName, Action.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = FOO"), finishedWithFailure(message("FOO")))) // .haveExactly(1, event(test(), displayName("[2] argument = BAR"), finishedWithFailure(message("BAR")))); } @ParameterizedTest @ValueSource(strings = { "testWithRepeatableValueSource", "testWithRepeatableValueSourceAsMetaAnnotation" }) void executesWithRepeatableValueSource(String methodName) { var results = execute(methodName, String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = foo"), finishedWithFailure(message("foo")))) // .haveExactly(1, event(test(), displayName("[2] argument = bar"), finishedWithFailure(message("bar")))); } @ParameterizedTest @ValueSource(strings = { "testWithRepeatableFieldSource", "testWithRepeatableFieldSourceAsMetaAnnotation" }) void executesWithRepeatableFieldSource(String methodName) { var results = execute(methodName, String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = some"), finishedWithFailure(message("some")))) // .haveExactly(1, event(test(), displayName("[2] argument = other"), finishedWithFailure(message("other")))); } @ParameterizedTest @ValueSource(strings = { "testWithRepeatableArgumentsSource", "testWithRepeatableArgumentsSourceAsMetaAnnotation" }) void executesWithRepeatableArgumentsSource(String methodName) { var results = execute(methodName, String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = foo"), finishedWithFailure(message("foo")))) // .haveExactly(1, event(test(), displayName("[2] argument = bar"), finishedWithFailure(message("bar")))) // .haveExactly(1, event(test(), displayName("[3] argument = foo"), finishedWithFailure(message("foo")))) // .haveExactly(1, event(test(), displayName("[4] argument = bar"), finishedWithFailure(message("bar")))); } @Test void executesWithSameRepeatableAnnotationMultipleTimes() { var results = execute("testWithSameRepeatableAnnotationMultipleTimes", String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), started())) // .haveExactly(1, event(test(), finishedWithFailure(message("foo")))); } @Test void executesWithDifferentRepeatableAnnotations() { var results = execute("testWithDifferentRepeatableAnnotations", String.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), displayName("[1] argument = a"), finishedWithFailure(message("a")))) // .haveExactly(1, event(test(), displayName("[2] argument = b"), finishedWithFailure(message("b")))) // .haveExactly(1, event(test(), displayName("[3] argument = c"), finishedWithFailure(message("c")))) // .haveExactly(1, event(test(), displayName("[4] argument = d"), finishedWithFailure(message("d")))); } private EngineExecutionResults execute(String methodName, Class<?>... methodParameterTypes) { return ParameterizedTestIntegrationTests.this.execute(RepeatableSourcesTestCase.class, methodName, methodParameterTypes); } } @Test void closeAutoCloseableArgumentsAfterTest() { var results = execute("testWithAutoCloseableArgument", AutoCloseableArgument.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), finishedSuccessfully())); assertEquals(2, AutoCloseableArgument.closeCounter); } @Test void doNotCloseAutoCloseableArgumentsAfterTestWhenDisabled() { var results = execute("testWithAutoCloseableArgumentButDisabledCleanup", AutoCloseableArgument.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), finishedSuccessfully())); assertEquals(0, AutoCloseableArgument.closeCounter); } @Test void closeAutoCloseableArgumentsAfterTestDespiteEarlyFailure() { var results = execute(FailureInBeforeEachTestCase.class, "test", AutoCloseableArgument.class); results.allEvents().assertThatEvents() // .haveExactly(1, event(test(), finishedWithFailure(message("beforeEach")))); assertEquals(2, AutoCloseableArgument.closeCounter); } @Test void executesTwoIterationsBasedOnIterationAndUniqueIdSelector() { var methodId = uniqueIdForTestTemplateMethod(TestCase.class, "testWithThreeIterations(int)"); var results = executeTests(selectUniqueId(appendTestTemplateInvocationSegment(methodId, 3)), selectIteration(selectMethod(TestCase.class, "testWithThreeIterations", "int"), 1)); results.allEvents().assertThatEvents() // .haveExactly(2, event(test(), finishedWithFailure())) // .haveExactly(1, event(test(), displayName("[2] argument = 3"), finishedWithFailure())) // .haveExactly(1, event(test(), displayName("[3] argument = 5"), finishedWithFailure())); } @Nested
RepeatableSourcesIntegrationTests
java
apache__maven
impl/maven-cli/src/main/java/org/apache/maven/cling/event/ExecutionEventLogger.java
{ "start": 2086, "end": 17907 }
class ____ extends AbstractExecutionListener { private static final int MAX_LOG_PREFIX_SIZE = 8; // "[ERROR] " private static final int PROJECT_STATUS_SUFFIX_SIZE = 20; // "SUCCESS [ 0.000 s]" private static final int MIN_TERMINAL_WIDTH = 60; private static final int DEFAULT_TERMINAL_WIDTH = 80; private static final int MAX_TERMINAL_WIDTH = 130; private static final int MAX_PADDED_BUILD_TIME_DURATION_LENGTH = 9; private final MessageBuilderFactory messageBuilderFactory; private final Logger logger; private int terminalWidth; private int lineLength; private int maxProjectNameLength; private int totalProjects; private volatile int currentVisitedProjectCount; public ExecutionEventLogger(MessageBuilderFactory messageBuilderFactory) { this(messageBuilderFactory, LoggerFactory.getLogger(ExecutionEventLogger.class)); } public ExecutionEventLogger(MessageBuilderFactory messageBuilderFactory, Logger logger) { this(messageBuilderFactory, logger, -1); } public ExecutionEventLogger(MessageBuilderFactory messageBuilderFactory, Logger logger, int terminalWidth) { this.logger = Objects.requireNonNull(logger, "logger cannot be null"); this.messageBuilderFactory = messageBuilderFactory; this.terminalWidth = terminalWidth; } private static String chars(char c, int count) { return String.valueOf(c).repeat(Math.max(0, count)); } private void infoLine(char c) { infoMain(chars(c, lineLength)); } private void infoMain(String msg) { logger.info(builder().strong(msg).toString()); } private void init() { if (maxProjectNameLength == 0) { if (terminalWidth < 0) { terminalWidth = messageBuilderFactory.getTerminalWidth(); } terminalWidth = Math.min( MAX_TERMINAL_WIDTH, Math.max(terminalWidth <= 0 ? DEFAULT_TERMINAL_WIDTH : terminalWidth, MIN_TERMINAL_WIDTH)); lineLength = terminalWidth - MAX_LOG_PREFIX_SIZE; maxProjectNameLength = lineLength - PROJECT_STATUS_SUFFIX_SIZE; } } @Override public void projectDiscoveryStarted(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); logger.info("Scanning for projects..."); } } @Override public void sessionStarted(ExecutionEvent event) { if (logger.isInfoEnabled() && event.getSession().getProjects().size() > 1) { init(); infoLine('-'); infoMain("Reactor Build Order:"); logger.info(""); final List<MavenProject> projects = event.getSession().getProjects(); for (MavenProject project : projects) { int len = lineLength - project.getName().length() - project.getPackaging().length() - 2; logger.info("{}{}[{}]", project.getName(), chars(' ', (len > 0) ? len : 1), project.getPackaging()); } final List<MavenProject> allProjects = event.getSession().getAllProjects(); currentVisitedProjectCount = allProjects.size() - projects.size(); totalProjects = allProjects.size(); } } @Override public void sessionEnded(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); if (event.getSession().getProjects().size() > 1) { logReactorSummary(event.getSession()); } ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if (iLoggerFactory instanceof org.apache.maven.logging.api.LogLevelRecorder recorder && recorder.hasReachedMaxLevel()) { event.getSession() .getResult() .addException( new Exception("Build failed due to log statements with a higher severity than allowed. " + "Fix the logged issues or remove flag --fail-on-severity (-fos).")); } logResult(event.getSession()); logStats(event.getSession()); infoLine('-'); } } private boolean isSingleVersionedReactor(MavenSession session) { boolean result = true; MavenProject topProject = session.getTopLevelProject(); List<MavenProject> sortedProjects = session.getProjectDependencyGraph().getSortedProjects(); for (MavenProject mavenProject : sortedProjects) { if (!topProject.getVersion().equals(mavenProject.getVersion())) { result = false; break; } } return result; } private void logReactorSummary(MavenSession session) { boolean isSingleVersion = isSingleVersionedReactor(session); infoLine('-'); StringBuilder summary = new StringBuilder("Reactor Summary"); if (isSingleVersion) { summary.append(" for "); summary.append(session.getTopLevelProject().getName()); summary.append(" "); summary.append(session.getTopLevelProject().getVersion()); } summary.append(":"); infoMain(summary.toString()); logger.info(""); MavenExecutionResult result = session.getResult(); List<MavenProject> projects = session.getProjects(); StringBuilder buffer = new StringBuilder(128); for (MavenProject project : projects) { buffer.append(project.getName()); buffer.append(' '); if (!isSingleVersion) { buffer.append(project.getVersion()); buffer.append(' '); } if (buffer.length() <= maxProjectNameLength) { while (buffer.length() < maxProjectNameLength) { buffer.append('.'); } buffer.append(' '); } BuildSummary buildSummary = result.getBuildSummary(project); if (buildSummary == null) { buffer.append(builder().warning("SKIPPED")); } else if (buildSummary instanceof BuildSuccess) { buffer.append(builder().success("SUCCESS")); buffer.append(" ["); String buildTimeDuration = formatDuration(buildSummary.getExecTime()); int padSize = MAX_PADDED_BUILD_TIME_DURATION_LENGTH - buildTimeDuration.length(); if (padSize > 0) { buffer.append(chars(' ', padSize)); } buffer.append(buildTimeDuration); buffer.append(']'); } else if (buildSummary instanceof BuildFailure) { buffer.append(builder().failure("FAILURE")); buffer.append(" ["); String buildTimeDuration = formatDuration(buildSummary.getExecTime()); int padSize = MAX_PADDED_BUILD_TIME_DURATION_LENGTH - buildTimeDuration.length(); if (padSize > 0) { buffer.append(chars(' ', padSize)); } buffer.append(buildTimeDuration); buffer.append(']'); } logger.info(buffer.toString()); buffer.setLength(0); } } private void logResult(MavenSession session) { infoLine('-'); MessageBuilder buffer = builder(); if (session.getResult().hasExceptions()) { buffer.failure("BUILD FAILURE"); } else { buffer.success("BUILD SUCCESS"); } logger.info(buffer.toString()); } private MessageBuilder builder() { return messageBuilderFactory.builder(); } private void logStats(MavenSession session) { infoLine('-'); Instant finish = MonotonicClock.now(); Duration time = Duration.between(session.getRequest().getStartInstant(), finish); String wallClock = session.getRequest().getDegreeOfConcurrency() > 1 ? " (Wall Clock)" : ""; logger.info("Total time: {}{}", formatDuration(time), wallClock); ZonedDateTime rounded = finish.truncatedTo(ChronoUnit.SECONDS).atZone(ZoneId.systemDefault()); logger.info("Finished at: {}", formatTimestamp(rounded)); } @Override public void projectSkipped(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); logger.info(""); infoLine('-'); String name = event.getProject().getName(); infoMain("Skipping " + name); logger.info("{} was not built because a module it depends on failed to build.", name); infoLine('-'); } } @Override public void projectStarted(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); MavenProject project = event.getProject(); logger.info(""); // -------< groupId:artifactId >------- String projectKey = project.getGroupId() + ':' + project.getArtifactId(); final String preHeader = "--< "; final String postHeader = " >--"; final int headerLen = preHeader.length() + projectKey.length() + postHeader.length(); String prefix = chars('-', Math.max(0, (lineLength - headerLen) / 2)) + preHeader; String suffix = postHeader + chars('-', Math.max(0, lineLength - headerLen - prefix.length() + preHeader.length())); logger.info( builder().strong(prefix).project(projectKey).strong(suffix).toString()); // Building Project Name Version [i/n] String building = "Building " + event.getProject().getName() + " " + event.getProject().getVersion(); if (totalProjects <= 1) { infoMain(building); } else { // display progress [i/n] int number; synchronized (this) { number = ++currentVisitedProjectCount; } String progress = " [" + number + '/' + totalProjects + ']'; int pad = lineLength - building.length() - progress.length(); infoMain(building + ((pad > 0) ? chars(' ', pad) : "") + progress); } // path to pom.xml File currentPom = project.getFile(); if (currentPom != null) { MavenSession session = event.getSession(); Path current = currentPom.toPath().toAbsolutePath().normalize(); Path topDirectory = session.getTopDirectory(); if (topDirectory != null && current.startsWith(topDirectory)) { current = topDirectory.relativize(current); } logger.info(" from " + current); } // ----------[ packaging ]---------- prefix = chars('-', Math.max(0, (lineLength - project.getPackaging().length() - 4) / 2)); suffix = chars('-', Math.max(0, lineLength - project.getPackaging().length() - 4 - prefix.length())); infoMain(prefix + "[ " + project.getPackaging() + " ]" + suffix); } } @Override public void mojoSkipped(ExecutionEvent event) { if (logger.isWarnEnabled()) { init(); logger.warn( "Goal '{}' requires online mode for execution but Maven is currently offline, skipping", event.getMojoExecution().getGoal()); } } /** * <pre>--- mojo-artifactId:version:goal (mojo-executionId) @ project-artifactId ---</pre> */ @Override public void mojoStarted(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); logger.info(""); MessageBuilder buffer = builder().strong("--- "); append(buffer, event.getMojoExecution()); append(buffer, event.getProject()); buffer.strong(" ---"); logger.info(buffer.toString()); } } // CHECKSTYLE_OFF: LineLength /** * <pre>&gt;&gt;&gt; mojo-artifactId:version:goal (mojo-executionId) &gt; :forked-goal @ project-artifactId &gt;&gt;&gt;</pre> * <pre>&gt;&gt;&gt; mojo-artifactId:version:goal (mojo-executionId) &gt; [lifecycle]phase @ project-artifactId &gt;&gt;&gt;</pre> */ // CHECKSTYLE_ON: LineLength @Override public void forkStarted(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); logger.info(""); MessageBuilder buffer = builder().strong(">>> "); append(buffer, event.getMojoExecution()); buffer.strong(" > "); appendForkInfo(buffer, event.getMojoExecution().getMojoDescriptor()); append(buffer, event.getProject()); buffer.strong(" >>>"); logger.info(buffer.toString()); } } // CHECKSTYLE_OFF: LineLength /** * <pre>&lt;&lt;&lt; mojo-artifactId:version:goal (mojo-executionId) &lt; :forked-goal @ project-artifactId &lt;&lt;&lt;</pre> * <pre>&lt;&lt;&lt; mojo-artifactId:version:goal (mojo-executionId) &lt; [lifecycle]phase @ project-artifactId &lt;&lt;&lt;</pre> */ // CHECKSTYLE_ON: LineLength @Override public void forkSucceeded(ExecutionEvent event) { if (logger.isInfoEnabled()) { init(); logger.info(""); MessageBuilder buffer = builder().strong("<<< "); append(buffer, event.getMojoExecution()); buffer.strong(" < "); appendForkInfo(buffer, event.getMojoExecution().getMojoDescriptor()); append(buffer, event.getProject()); buffer.strong(" <<<"); logger.info(buffer.toString()); logger.info(""); } } private void append(MessageBuilder buffer, MojoExecution me) { String prefix = me.getMojoDescriptor().getPluginDescriptor().getGoalPrefix(); if (prefix == null || prefix.isEmpty()) { prefix = me.getGroupId() + ":" + me.getArtifactId(); } buffer.mojo(prefix + ':' + me.getVersion() + ':' + me.getGoal()); if (me.getExecutionId() != null) { buffer.a(' ').strong('(' + me.getExecutionId() + ')'); } } private void appendForkInfo(MessageBuilder buffer, MojoDescriptor md) { StringBuilder buff = new StringBuilder(); if (md.getExecutePhase() != null && !md.getExecutePhase().isEmpty()) { // forked phase if (md.getExecuteLifecycle() != null && !md.getExecuteLifecycle().isEmpty()) { buff.append('['); buff.append(md.getExecuteLifecycle()); buff.append(']'); } buff.append(md.getExecutePhase()); } else { // forked goal buff.append(':'); buff.append(md.getExecuteGoal()); } buffer.strong(buff.toString()); } private void append(MessageBuilder buffer, MavenProject project) { buffer.a(" @ ").project(project.getArtifactId()); } @Override public void forkedProjectStarted(ExecutionEvent event) { if (logger.isInfoEnabled() && event.getMojoExecution().getForkedExecutions().size() > 1) { init(); logger.info(""); infoLine('>'); infoMain("Forking " + event.getProject().getName() + " " + event.getProject().getVersion()); infoLine('>'); } } }
ExecutionEventLogger
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/condition/ConditionEvaluationResultTests.java
{ "start": 884, "end": 4372 }
class ____ { @Test void enabledWithReason() { var result = ConditionEvaluationResult.enabled("reason"); assertThat(result.isDisabled()).isFalse(); assertThat(result.getReason()).contains("reason"); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = true, reason = 'reason']"); } @BlankReasonsTest void enabledWithBlankReason(@Nullable String reason) { var result = ConditionEvaluationResult.enabled(reason); assertThat(result.isDisabled()).isFalse(); assertThat(result.getReason()).isEmpty(); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = true, reason = '<unknown>']"); } @Test void disabledWithDefaultReason() { var result = ConditionEvaluationResult.disabled("default"); assertThat(result.isDisabled()).isTrue(); assertThat(result.getReason()).contains("default"); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = false, reason = 'default']"); } @BlankReasonsTest void disabledWithBlankDefaultReason(@Nullable String reason) { var result = ConditionEvaluationResult.disabled(reason); assertThat(result.isDisabled()).isTrue(); assertThat(result.getReason()).isEmpty(); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = false, reason = '<unknown>']"); } @BlankReasonsTest void disabledWithDefaultReasonAndBlankCustomReason(@Nullable String customReason) { var result = ConditionEvaluationResult.disabled("default", customReason); assertThat(result.isDisabled()).isTrue(); assertThat(result.getReason()).contains("default"); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = false, reason = 'default']"); } @BlankReasonsTest void disabledWithBlankDefaultReasonAndCustomReason(@Nullable String reason) { var result = ConditionEvaluationResult.disabled(reason, "custom"); assertThat(result.isDisabled()).isTrue(); assertThat(result.getReason()).contains("custom"); assertThat(result).asString().isEqualTo("ConditionEvaluationResult [enabled = false, reason = 'custom']"); } @BlankReasonsTest void disabledWithBlankDefaultReasonAndBlankCustomReason(@Nullable String reason) { // We intentionally use the reason as both the default and custom reason. var result = ConditionEvaluationResult.disabled(reason, reason); assertThat(result.isDisabled()).isTrue(); assertThat(result.getReason()).isEmpty(); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = false, reason = '<unknown>']"); } @Test void disabledWithDefaultReasonAndCustomReason() { disabledWithDefaultReasonAndCustomReason("default", "custom"); } @Test void disabledWithDefaultReasonAndCustomReasonWithLeadingAndTrailingWhitespace() { disabledWithDefaultReasonAndCustomReason(" default ", " custom "); } private static void disabledWithDefaultReasonAndCustomReason(String defaultReason, String customReason) { var result = ConditionEvaluationResult.disabled(defaultReason, customReason); assertThat(result.isDisabled()).isTrue(); assertThat(result.getReason()).contains("default ==> custom"); assertThat(result).asString()// .isEqualTo("ConditionEvaluationResult [enabled = false, reason = 'default ==> custom']"); } @Retention(RetentionPolicy.RUNTIME) @ParameterizedTest @NullSource @ValueSource(strings = { "", " ", " ", "\t", "\f", "\r", "\n", "\r\n" }) @
ConditionEvaluationResultTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatabaseConnectionInfoImpl.java
{ "start": 1285, "end": 8586 }
class ____ implements DatabaseConnectionInfo { public static final String DEFAULT = "undefined/unknown"; private final Class<?> connectionProviderClass; protected final String jdbcUrl; protected final String jdbcDriver; private final Class<? extends Dialect> dialectClass; protected final DatabaseVersion dialectVersion; private final boolean hasSchema; private final boolean hasCatalog; protected final String schema; protected final String catalog; protected final String autoCommitMode; protected final String isolationLevel; protected final Integer poolMinSize; protected final Integer poolMaxSize; private final Integer fetchSize; public DatabaseConnectionInfoImpl( Class<? extends ConnectionProvider> connectionProviderClass, String jdbcUrl, String jdbcDriver, Class<? extends Dialect> dialectClass, DatabaseVersion dialectVersion, boolean hasSchema, boolean hasCatalog, String schema, String catalog, String autoCommitMode, String isolationLevel, Integer poolMinSize, Integer poolMaxSize, Integer fetchSize) { this.connectionProviderClass = connectionProviderClass; this.jdbcUrl = nullIfEmpty( jdbcUrl ); this.jdbcDriver = nullIfEmpty( jdbcDriver ); this.dialectVersion = dialectVersion; this.hasSchema = hasSchema; this.hasCatalog = hasCatalog; this.schema = schema; this.catalog = catalog; this.autoCommitMode = nullIfEmpty( autoCommitMode ); this.isolationLevel = nullIfEmpty( isolationLevel ); this.poolMinSize = poolMinSize; this.poolMaxSize = poolMaxSize; this.fetchSize = fetchSize; this.dialectClass = dialectClass; } public DatabaseConnectionInfoImpl(Map<String, Object> settings, Dialect dialect) { this( null, determineUrl( settings ), determineDriver( settings ), dialect.getClass(), dialect.getVersion(), true, true, null, null, determineAutoCommitMode( settings ), determineIsolationLevel( settings ), // No setting for min. pool size null, determinePoolMaxSize( settings ), null ); } public DatabaseConnectionInfoImpl(Dialect dialect) { this( null, null, null, dialect.getClass(), dialect.getVersion(), true, true, null, null, null, null, null, null, null ); } public static boolean hasSchema(Connection connection) { try { return connection.getMetaData().supportsSchemasInDataManipulation(); } catch ( SQLException ignored ) { return true; } } public static boolean hasCatalog(Connection connection) { try { return connection.getMetaData().supportsCatalogsInDataManipulation(); } catch ( SQLException ignored ) { return true; } } public static String getSchema(Connection connection) { try { // method introduced in 1.7 return connection.getSchema(); } catch ( SQLException|AbstractMethodError ignored ) { return null; } } public static String getCatalog(Connection connection) { try { return connection.getCatalog(); } catch ( SQLException ignored ) { return null; } } public static Integer getFetchSize(Connection connection) { try ( var statement = connection.createStatement() ) { return statement.getFetchSize(); } catch ( SQLException ignored ) { return null; } } public static Integer getIsolation(Connection connection) { try { return connection.getTransactionIsolation(); } catch ( SQLException ignored ) { return null; } } public static String getDriverName(Connection connection) { try { return connection.getMetaData().getDriverName(); } catch (SQLException e) { return null; } } @Override public String getJdbcUrl() { return jdbcUrl; } @Override public String getJdbcDriver() { return jdbcDriver; } @Override public DatabaseVersion getDialectVersion() { return dialectVersion; } @Override public String getAutoCommitMode() { return autoCommitMode; } @Override public String getIsolationLevel() { return isolationLevel; } @Override public Integer getPoolMinSize() { return poolMinSize; } @Override public Integer getPoolMaxSize() { return poolMaxSize; } @Override public @Nullable Integer getJdbcFetchSize() { return fetchSize; } @Override public @Nullable String getSchema() { return schema; } @Override public @Nullable String getCatalog() { return catalog; } @Override public boolean hasSchema() { return hasSchema; } @Override public boolean hasCatalog() { return hasCatalog; } @Override public String toInfoString() { return """ \tDatabase JDBC URL [%s] \tDatabase driver: %s \tDatabase dialect: %s \tDatabase version: %s \tDefault catalog/schema: %s/%s \tAutocommit mode: %s \tIsolation level: %s \tJDBC fetch size: %s \tPool: %s \tMinimum pool size: %s \tMaximum pool size: %s""" .formatted( handleEmpty( jdbcUrl ), handleEmpty( jdbcDriver ), handleEmpty( dialectClass ), handleEmpty( dialectVersion ), handleEmpty( catalog, hasCatalog ), handleEmpty( schema, hasSchema ), handleEmpty( autoCommitMode ), handleEmpty( isolationLevel ), handleFetchSize( fetchSize ), handleEmpty( connectionProviderClass ), handleEmpty( poolMinSize ), handleEmpty( poolMaxSize ) ); } private static String handleEmpty(String value) { return isNotEmpty( value ) ? value : DEFAULT; } private static String handleEmpty(String value, boolean defined) { return isNotEmpty( value ) ? value : (defined ? "unknown" : "undefined"); } private static String handleEmpty(DatabaseVersion dialectVersion) { return dialectVersion != null ? dialectVersion.toString() : ZERO_VERSION.toString(); } private static String handleEmpty(Integer value) { return value != null ? value.toString() : DEFAULT; } private static String handleFetchSize(Integer value) { return value != null ? ( value == 0 ? "none" : value.toString() ) : DEFAULT; } private static String handleEmpty(Class<?> value) { return value != null ? value.getSimpleName() : DEFAULT; } @SuppressWarnings("deprecation") private static String determineUrl(Map<String, Object> settings) { return NullnessHelper.coalesceSuppliedValues( () -> getString( JdbcSettings.JAKARTA_JDBC_URL, settings ), () -> getString( JdbcSettings.URL, settings ), () -> getString( JdbcSettings.JPA_JDBC_URL, settings ) ); } @SuppressWarnings("deprecation") private static String determineDriver(Map<String, Object> settings) { return NullnessHelper.coalesceSuppliedValues( () -> getString( JdbcSettings.JAKARTA_JDBC_DRIVER, settings ), () -> getString( JdbcSettings.DRIVER, settings ), () -> getString( JdbcSettings.JPA_JDBC_DRIVER, settings ) ); } private static String determineAutoCommitMode(Map<String, Object> settings) { return getString( JdbcSettings.AUTOCOMMIT, settings ); } private static String determineIsolationLevel(Map<String, Object> settings) { return toIsolationNiceName( interpretIsolation( settings.get(JdbcSettings.ISOLATION ) ) ); } private static Integer determinePoolMaxSize(Map<String, Object> settings) { return ConfigurationHelper.getInteger( JdbcSettings.POOL_SIZE, settings ); } }
DatabaseConnectionInfoImpl
java
spring-projects__spring-boot
module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/GraphQlAutoConfigurationTests.java
{ "start": 12246, "end": 12605 }
class ____ { @Bean GraphQlSource.SchemaResourceBuilder customGraphQlSourceBuilder() { return GraphQlSource.schemaResourceBuilder() .schemaResources(new ClassPathResource("graphql/schema.graphqls"), new ClassPathResource("graphql/types/book.graphqls")); } } @Configuration(proxyBeanMethods = false) static
CustomGraphQlBuilderConfiguration
java
mockito__mockito
mockito-core/src/main/java/org/mockito/stubbing/VoidAnswer4.java
{ "start": 166, "end": 1228 }
interface ____ be used for configuring mock's answer for a four argument invocation that returns nothing. * * Answer specifies an action that is executed when you interact with the mock. * <p> * Example of stubbing a mock with this custom answer: * * <pre class="code"><code class="java"> * import static org.mockito.AdditionalAnswers.answerVoid; * * doAnswer(answerVoid( * new VoidAnswer4&lt;String, Integer, String, Character&gt;() { * public void answer(String msg, Integer count, String another, Character c) throws Exception { * throw new Exception(String.format(msg, another, c, count)); * } * })).when(mock).someMethod(anyString(), anyInt(), anyString(), anyChar()); * * //Following will raise an exception with the message "ka-boom &lt;3" * mock.someMethod("%s-boom %c%d", 3, "ka", '&lt;'); * </code></pre> * * @param <A0> type of the first argument * @param <A1> type of the second argument * @param <A2> type of the third argument * @param <A3> type of the fourth argument * @see Answer */ public
to
java
quarkusio__quarkus
core/builder/src/main/java/io/quarkus/builder/ConsumeFlag.java
{ "start": 36, "end": 192 }
enum ____ { /** * Do not exclude the build step even if the given resource is not produced by any other build step. */ OPTIONAL, }
ConsumeFlag
java
quarkusio__quarkus
extensions/panache/mongodb-panache/deployment/src/test/java/io/quarkus/mongodb/panache/DuplicateIdReactiveMongoEntity.java
{ "start": 165, "end": 281 }
class ____ extends ReactivePanacheMongoEntity { @BsonId public String customId; }
DuplicateIdReactiveMongoEntity
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1180/Issue1180Test.java
{ "start": 731, "end": 1180 }
class ____ { @ProcessorTest @ExpectedCompilationOutcome(value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = ErroneousIssue1180Mapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 18, messageRegExp = "No property named \"sourceProperty\\.nonExistant\" exists.*") }) public void shouldCompileButNotGiveNullPointer() { } }
Issue1180Test
java
greenrobot__greendao
tests/DaoTestBase/src/main/java/org/greenrobot/greendao/daotest/TestEntityDao.java
{ "start": 737, "end": 9476 }
class ____ { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property SimpleInt = new Property(1, int.class, "simpleInt", false, "SIMPLE_INT"); public final static Property SimpleInteger = new Property(2, Integer.class, "simpleInteger", false, "SIMPLE_INTEGER"); public final static Property SimpleStringNotNull = new Property(3, String.class, "simpleStringNotNull", false, "SIMPLE_STRING_NOT_NULL"); public final static Property SimpleString = new Property(4, String.class, "simpleString", false, "SIMPLE_STRING"); public final static Property IndexedString = new Property(5, String.class, "indexedString", false, "INDEXED_STRING"); public final static Property IndexedStringAscUnique = new Property(6, String.class, "indexedStringAscUnique", false, "INDEXED_STRING_ASC_UNIQUE"); public final static Property SimpleDate = new Property(7, java.util.Date.class, "simpleDate", false, "SIMPLE_DATE"); public final static Property SimpleBoolean = new Property(8, Boolean.class, "simpleBoolean", false, "SIMPLE_BOOLEAN"); public final static Property SimpleByteArray = new Property(9, byte[].class, "simpleByteArray", false, "SIMPLE_BYTE_ARRAY"); } public TestEntityDao(DaoConfig config) { super(config); } public TestEntityDao(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 + "\"TEST_ENTITY\" (" + // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id "\"SIMPLE_INT\" INTEGER NOT NULL ," + // 1: simpleInt "\"SIMPLE_INTEGER\" INTEGER," + // 2: simpleInteger "\"SIMPLE_STRING_NOT_NULL\" TEXT NOT NULL ," + // 3: simpleStringNotNull "\"SIMPLE_STRING\" TEXT," + // 4: simpleString "\"INDEXED_STRING\" TEXT," + // 5: indexedString "\"INDEXED_STRING_ASC_UNIQUE\" TEXT," + // 6: indexedStringAscUnique "\"SIMPLE_DATE\" INTEGER," + // 7: simpleDate "\"SIMPLE_BOOLEAN\" INTEGER," + // 8: simpleBoolean "\"SIMPLE_BYTE_ARRAY\" BLOB);"); // 9: simpleByteArray // Add Indexes db.execSQL("CREATE INDEX " + constraint + "IDX_TEST_ENTITY_INDEXED_STRING ON TEST_ENTITY" + " (\"INDEXED_STRING\");"); db.execSQL("CREATE UNIQUE INDEX " + constraint + "IDX_TEST_ENTITY_INDEXED_STRING_ASC_UNIQUE ON TEST_ENTITY" + " (\"INDEXED_STRING_ASC_UNIQUE\" ASC);"); } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"TEST_ENTITY\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, TestEntity entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } stmt.bindLong(2, entity.getSimpleInt()); Integer simpleInteger = entity.getSimpleInteger(); if (simpleInteger != null) { stmt.bindLong(3, simpleInteger); } stmt.bindString(4, entity.getSimpleStringNotNull()); String simpleString = entity.getSimpleString(); if (simpleString != null) { stmt.bindString(5, simpleString); } String indexedString = entity.getIndexedString(); if (indexedString != null) { stmt.bindString(6, indexedString); } String indexedStringAscUnique = entity.getIndexedStringAscUnique(); if (indexedStringAscUnique != null) { stmt.bindString(7, indexedStringAscUnique); } java.util.Date simpleDate = entity.getSimpleDate(); if (simpleDate != null) { stmt.bindLong(8, simpleDate.getTime()); } Boolean simpleBoolean = entity.getSimpleBoolean(); if (simpleBoolean != null) { stmt.bindLong(9, simpleBoolean ? 1L: 0L); } byte[] simpleByteArray = entity.getSimpleByteArray(); if (simpleByteArray != null) { stmt.bindBlob(10, simpleByteArray); } } @Override protected final void bindValues(SQLiteStatement stmt, TestEntity entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } stmt.bindLong(2, entity.getSimpleInt()); Integer simpleInteger = entity.getSimpleInteger(); if (simpleInteger != null) { stmt.bindLong(3, simpleInteger); } stmt.bindString(4, entity.getSimpleStringNotNull()); String simpleString = entity.getSimpleString(); if (simpleString != null) { stmt.bindString(5, simpleString); } String indexedString = entity.getIndexedString(); if (indexedString != null) { stmt.bindString(6, indexedString); } String indexedStringAscUnique = entity.getIndexedStringAscUnique(); if (indexedStringAscUnique != null) { stmt.bindString(7, indexedStringAscUnique); } java.util.Date simpleDate = entity.getSimpleDate(); if (simpleDate != null) { stmt.bindLong(8, simpleDate.getTime()); } Boolean simpleBoolean = entity.getSimpleBoolean(); if (simpleBoolean != null) { stmt.bindLong(9, simpleBoolean ? 1L: 0L); } byte[] simpleByteArray = entity.getSimpleByteArray(); if (simpleByteArray != null) { stmt.bindBlob(10, simpleByteArray); } } @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } @Override public TestEntity readEntity(Cursor cursor, int offset) { TestEntity entity = new TestEntity( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.getInt(offset + 1), // simpleInt cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2), // simpleInteger cursor.getString(offset + 3), // simpleStringNotNull cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // simpleString cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // indexedString cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // indexedStringAscUnique cursor.isNull(offset + 7) ? null : new java.util.Date(cursor.getLong(offset + 7)), // simpleDate cursor.isNull(offset + 8) ? null : cursor.getShort(offset + 8) != 0, // simpleBoolean cursor.isNull(offset + 9) ? null : cursor.getBlob(offset + 9) // simpleByteArray ); return entity; } @Override public void readEntity(Cursor cursor, TestEntity entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setSimpleInt(cursor.getInt(offset + 1)); entity.setSimpleInteger(cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2)); entity.setSimpleStringNotNull(cursor.getString(offset + 3)); entity.setSimpleString(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4)); entity.setIndexedString(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5)); entity.setIndexedStringAscUnique(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6)); entity.setSimpleDate(cursor.isNull(offset + 7) ? null : new java.util.Date(cursor.getLong(offset + 7))); entity.setSimpleBoolean(cursor.isNull(offset + 8) ? null : cursor.getShort(offset + 8) != 0); entity.setSimpleByteArray(cursor.isNull(offset + 9) ? null : cursor.getBlob(offset + 9)); } @Override protected final Long updateKeyAfterInsert(TestEntity entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(TestEntity entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(TestEntity entity) { return entity.getId() != null; } @Override protected final boolean isEntityUpdateable() { return true; } }
Properties
java
alibaba__druid
core/src/test/java/com/alibaba/druid/pool/MemTest.java
{ "start": 309, "end": 1396 }
class ____ { HashMap m = new HashMap(); HashMap m1 = new HashMap(1); ConcurrentHashMap cm = new ConcurrentHashMap(); ConcurrentHashMap cm1 = new ConcurrentHashMap(1, 0.75f, 1); ConcurrentSkipListMap csm = new ConcurrentSkipListMap(); Hashtable ht = new Hashtable(); Properties p = new Properties(); TreeMap t = new TreeMap(); LinkedHashMap l = new LinkedHashMap(); TreeSet ts = new TreeSet(); HashSet hs = new HashSet(); LinkedHashSet lhs = new LinkedHashSet(); ArrayList list = new ArrayList(); ArrayList list1 = new ArrayList(1); CopyOnWriteArrayList cpl = new CopyOnWriteArrayList(); CopyOnWriteArraySet cps = new CopyOnWriteArraySet(); Vector v = new Vector(); LinkedList ll = new LinkedList(); Stack stack = new Stack(); PriorityQueue pq = new PriorityQueue(); ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue(); public static void main(String[] args) throws Exception { MemTest o = new MemTest(); Thread.sleep(1000 * 1000); System.out.println(o); } }
MemTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/domain/InjectedLookupListItem.java
{ "start": 213, "end": 595 }
class ____ implements LookupListItem { private Integer id; private String displayValue; @Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } }
InjectedLookupListItem
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/JobLeaderIdActions.java
{ "start": 1065, "end": 1964 }
interface ____ { /** * Callback when a monitored job leader lost its leadership. * * @param jobId identifying the job whose leader lost leadership * @param oldJobMasterId of the job manager which lost leadership */ void jobLeaderLostLeadership(JobID jobId, JobMasterId oldJobMasterId); /** * Notify a job timeout. The job is identified by the given JobID. In order to check for the * validity of the timeout the timeout id of the triggered timeout is provided. * * @param jobId JobID which identifies the timed out job * @param timeoutId Id of the calling timeout to differentiate valid from invalid timeouts */ void notifyJobTimeout(JobID jobId, UUID timeoutId); /** * Callback to report occurring errors. * * @param error which has occurred */ void handleError(Throwable error); }
JobLeaderIdActions
java
spring-projects__spring-framework
spring-core-test/src/test/java/org/springframework/aot/agent/InstrumentedMethodTests.java
{ "start": 1360, "end": 3604 }
class ____ { final RecordedInvocation stringGetClasses = RecordedInvocation.of(InstrumentedMethod.CLASS_GETCLASSES) .onInstance(String.class).returnValue(String.class.getClasses()).build(); final RecordedInvocation stringGetDeclaredClasses = RecordedInvocation.of(InstrumentedMethod.CLASS_GETDECLAREDCLASSES) .onInstance(String.class).returnValue(String.class.getDeclaredClasses()).build(); @Test void classForNameShouldMatchReflectionOnType() { RecordedInvocation invocation = RecordedInvocation.of(InstrumentedMethod.CLASS_FORNAME) .withArgument("java.lang.String").returnValue(String.class).build(); hints.reflection().registerType(String.class); assertThatInvocationMatches(InstrumentedMethod.CLASS_FORNAME, invocation); } @Test void classForNameShouldNotMatchWhenMissingReflectionOnType() { RecordedInvocation invocation = RecordedInvocation.of(InstrumentedMethod.CLASS_FORNAME) .withArgument("java.lang.String").returnValue(String.class).build(); assertThatInvocationDoesNotMatch(InstrumentedMethod.CLASS_FORNAME, invocation); } @Test void classGetClassesShouldMatchReflectionOnType() { hints.reflection().registerType(String.class); assertThatInvocationMatches(InstrumentedMethod.CLASS_GETCLASSES, this.stringGetClasses); } @Test void classGetDeclaredClassesShouldMatchReflectionOnType() { hints.reflection().registerType(String.class); assertThatInvocationMatches(InstrumentedMethod.CLASS_GETDECLAREDCLASSES, this.stringGetDeclaredClasses); } @Test void classGetDeclaredClassesShouldNotMatchWhenMissingReflectionOnType() { assertThatInvocationDoesNotMatch(InstrumentedMethod.CLASS_GETDECLAREDCLASSES, this.stringGetDeclaredClasses); } @Test void classLoaderLoadClassShouldMatchReflectionHintOnType() { RecordedInvocation invocation = RecordedInvocation.of(InstrumentedMethod.CLASSLOADER_LOADCLASS) .onInstance(ClassLoader.getSystemClassLoader()) .withArgument(PublicField.class.getCanonicalName()).returnValue(PublicField.class).build(); hints.reflection().registerType(PublicField.class); assertThatInvocationMatches(InstrumentedMethod.CLASSLOADER_LOADCLASS, invocation); } } @Nested
ClassReflectionInstrumentationTests
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServices.java
{ "start": 6351, "end": 6943 }
class ____ extends JerseyTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestRMWebServices.class); private static MockRM rm; @Override protected Application configure() { ResourceConfig config = new ResourceConfig(); config.register(new JerseyBinder()); config.register(RMWebServices.class); config.register(GenericExceptionHandler.class); config.register(new JettisonFeature()).register(JAXBContextResolver.class); forceSet(TestProperties.CONTAINER_PORT, JERSEY_RANDOM_PORT); return config; } private static
TestRMWebServices
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/model/Component.java
{ "start": 941, "end": 1742 }
class ____ { private String type; @JsonProperty("sub_type") private String subType; private List<Parameter> parameters; private String index; public Component() { } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSubType() { return subType; } public void setSubType(String subType) { this.subType = subType; } public List<Parameter> getParameters() { return parameters; } public void setParameters(List<Parameter> parameters) { this.parameters = parameters; } public String getIndex() { return index; } public void setIndex(String index) { this.index = index; } }
Component
java
grpc__grpc-java
examples/src/main/java/io/grpc/examples/manualflowcontrol/BidiBlockingClient.java
{ "start": 1269, "end": 8407 }
class ____ { private static final Logger logger = Logger.getLogger(BidiBlockingClient.class.getName()); /** * Greet server. If provided, the first element of {@code args} is the name to use in the * greeting. The second argument is the target server. You can see the multiplexing in the server * logs. */ public static void main(String[] args) throws Exception { System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS %5$s%6$s%n"); // Access a service running on the local machine on port 50051 String target = "localhost:50051"; // Allow passing in the user and target strings as command line arguments if (args.length > 0) { if ("--help".equals(args[0])) { System.err.println("Usage: [target]\n"); System.err.println(" target The server to connect to. Defaults to " + target); System.exit(1); } target = args[0]; } // Create a communication channel to the server, known as a Channel. Channels are thread-safe // and reusable. It is common to create channels at the beginning of your application and reuse // them until the application shuts down. // // For the example we use plaintext insecure credentials to avoid needing TLS certificates. To // use TLS, use TlsChannelCredentials instead. ManagedChannel channel = Grpc.newChannelBuilder(target, InsecureChannelCredentials.create()) .build(); StreamingGreeterBlockingV2Stub blockingStub = StreamingGreeterGrpc.newBlockingV2Stub(channel); List<String> echoInput = names(); try { long start = System.currentTimeMillis(); List<String> twoThreadResult = useTwoThreads(blockingStub, echoInput); long finish = System.currentTimeMillis(); System.out.println("The echo requests and results were:"); printResultMessage("Input", echoInput, 0L); printResultMessage("2 threads", twoThreadResult, finish - start); } finally { // ManagedChannels use resources like threads and TCP connections. To prevent leaking these // resources the channel should be shut down when it will no longer be used. If it may be used // again leave it running. channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } private static void printResultMessage(String type, List<String> result, long millis) { String msg = String.format("%-32s: %2d, %.3f sec", type, result.size(), millis/1000.0); logger.info(msg); } private static void logMethodStart(String method) { logger.info("--------------------- Starting to process using method: " + method); } /** * Create 2 threads, one that writes all values, and one that reads until the stream closes. */ private static List<String> useTwoThreads(StreamingGreeterBlockingV2Stub blockingStub, List<String> valuesToWrite) throws InterruptedException { logMethodStart("Two Threads"); List<String> readValues = new ArrayList<>(); final BlockingClientCall<HelloRequest, HelloReply> stream = blockingStub.sayHelloStreaming(); Thread reader = new Thread(null, new Runnable() { @Override public void run() { int count = 0; try { while (stream.hasNext()) { readValues.add(stream.read().getMessage()); if (++count % 10 == 0) { logger.info("Finished " + count + " reads"); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); stream.cancel("Interrupted", e); } catch (StatusException e) { logger.warning("Encountered error while reading: " + e); } } },"reader"); Thread writer = new Thread(null, new Runnable() { @Override public void run() { ByteString padding = createPadding(); int count = 0; Iterator<String> iterator = valuesToWrite.iterator(); boolean hadProblem = false; try { while (iterator.hasNext()) { if (!stream.write(HelloRequest.newBuilder().setName(iterator.next()).setPadding(padding) .build())) { logger.warning("Stream closed before writes completed"); hadProblem = true; break; } if (++count % 10 == 0) { logger.info("Finished " + count + " writes"); } } if (!hadProblem) { logger.info("Completed writes"); stream.halfClose(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); stream.cancel("Interrupted", e); } catch (StatusException e) { logger.warning("Encountered error while writing: " + e); } } }, "writer"); writer.start(); reader.start(); writer.join(); reader.join(); return readValues; } private static ByteString createPadding() { int multiple = 50; ByteBuffer data = ByteBuffer.allocate(1024 * multiple); for (int i = 0; i < multiple * 1024 / 4; i++) { data.putInt(4 * i, 1111); } return ByteString.copyFrom(data); } private static List<String> names() { return Arrays.asList( "Sophia", "Jackson", "Emma", "Aiden", "Olivia", "Lucas", "Ava", "Liam", "Mia", "Noah", "Isabella", "Ethan", "Riley", "Mason", "Aria", "Caden", "Zoe", "Oliver", "Charlotte", "Elijah", "Lily", "Grayson", "Layla", "Jacob", "Amelia", "Michael", "Emily", "Benjamin", "Madelyn", "Carter", "Aubrey", "James", "Adalyn", "Jayden", "Madison", "Logan", "Chloe", "Alexander", "Harper", "Caleb", "Abigail", "Ryan", "Aaliyah", "Luke", "Avery", "Daniel", "Evelyn", "Jack", "Kaylee", "William", "Ella", "Owen", "Ellie", "Gabriel", "Scarlett", "Matthew", "Arianna", "Connor", "Hailey", "Jayce", "Nora", "Isaac", "Addison", "Sebastian", "Brooklyn", "Henry", "Hannah", "Muhammad", "Mila", "Cameron", "Leah", "Wyatt", "Elizabeth", "Dylan", "Sarah", "Nathan", "Eliana", "Nicholas", "Mackenzie", "Julian", "Peyton", "Eli", "Maria", "Levi", "Grace", "Isaiah", "Adeline", "Landon", "Elena", "David", "Anna", "Christian", "Victoria", "Andrew", "Camilla", "Brayden", "Lillian", "John", "Natalie", "Lincoln" ); } }
BidiBlockingClient
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generics/compositeid/CompositeIdWithGenericPartInMappedSuperclassTest.java
{ "start": 2184, "end": 2308 }
class ____ extends SampleSuperclass<Long> { private String sampleField; } @MappedSuperclass abstract static
SampleEntity
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/RequireBodyHandlerBuildItem.java
{ "start": 415, "end": 2145 }
class ____ extends MultiBuildItem { private final BooleanSupplier bodyHandlerRequiredCondition; /** * Creates {@link RequireBodyHandlerBuildItem} that requires body handler unconditionally installed on all routes. */ public RequireBodyHandlerBuildItem() { bodyHandlerRequiredCondition = null; } /** * Creates {@link RequireBodyHandlerBuildItem} that requires body handler installed on all routes if the supplier returns * true. * * @param bodyHandlerRequiredCondition supplier that returns true at runtime if the body handler should be created */ public RequireBodyHandlerBuildItem(BooleanSupplier bodyHandlerRequiredCondition) { this.bodyHandlerRequiredCondition = bodyHandlerRequiredCondition; } private BooleanSupplier getBodyHandlerRequiredCondition() { return bodyHandlerRequiredCondition; } public static BooleanSupplier[] getBodyHandlerRequiredConditions(List<RequireBodyHandlerBuildItem> bodyHandlerBuildItems) { if (bodyHandlerBuildItems.isEmpty()) { return new BooleanSupplier[] {}; } BooleanSupplier[] customRuntimeConditions = bodyHandlerBuildItems .stream() .map(RequireBodyHandlerBuildItem::getBodyHandlerRequiredCondition) .filter(Objects::nonNull) .toArray(BooleanSupplier[]::new); if (customRuntimeConditions.length == bodyHandlerBuildItems.size()) { return customRuntimeConditions; } // at least one item requires body handler unconditionally return new BooleanSupplier[] { new VertxHttpRecorder.AlwaysCreateBodyHandlerSupplier() }; } }
RequireBodyHandlerBuildItem
java
apache__hadoop
hadoop-tools/hadoop-extras/src/main/java/org/apache/hadoop/mapred/tools/GetGroups.java
{ "start": 1177, "end": 1809 }
class ____ extends GetGroupsBase { static { Configuration.addDefaultResource("mapred-default.xml"); Configuration.addDefaultResource("mapred-site.xml"); } GetGroups(Configuration conf) { super(conf); } GetGroups(Configuration conf, PrintStream out) { super(conf, out); } @Override protected InetSocketAddress getProtocolAddress(Configuration conf) throws IOException { throw new UnsupportedOperationException(); } public static void main(String[] argv) throws Exception { int res = ToolRunner.run(new GetGroups(new Configuration()), argv); System.exit(res); } }
GetGroups
java
spring-projects__spring-boot
module/spring-boot-jpa-test/src/main/java/org/springframework/boot/jpa/test/autoconfigure/TestEntityManager.java
{ "start": 1285, "end": 8175 }
class ____ { private final EntityManagerFactory entityManagerFactory; /** * Create a new {@link TestEntityManager} instance for the given * {@link EntityManagerFactory}. * @param entityManagerFactory the source entity manager factory */ public TestEntityManager(EntityManagerFactory entityManagerFactory) { Assert.notNull(entityManagerFactory, "'entityManagerFactory' must not be null"); this.entityManagerFactory = entityManagerFactory; } /** * Make an instance managed and persistent then return its ID. Delegates to * {@link EntityManager#persist(Object)} then {@link #getId(Object)}. * <p> * Helpful when setting up test data in a test: <pre class="code"> * Object entityId = this.testEntityManager.persist(new MyEntity("Spring")); * </pre> * @param entity the source entity * @return the ID of the newly persisted entity */ public @Nullable Object persistAndGetId(Object entity) { persist(entity); return getId(entity); } /** * Make an instance managed and persistent then return its ID. Delegates to * {@link EntityManager#persist(Object)} then {@link #getId(Object, Class)}. * <p> * Helpful when setting up test data in a test: <pre class="code"> * Long entityId = this.testEntityManager.persist(new MyEntity("Spring"), Long.class); * </pre> * @param <T> the ID type * @param entity the source entity * @param idType the ID type * @return the ID of the newly persisted entity */ public <T> @Nullable T persistAndGetId(Object entity, Class<T> idType) { persist(entity); return getId(entity, idType); } /** * Make an instance managed and persistent. Delegates to * {@link EntityManager#persist(Object)} then returns the original source entity. * <p> * Helpful when setting up test data in a test: <pre class="code"> * MyEntity entity = this.testEntityManager.persist(new MyEntity("Spring")); * </pre> * @param <E> the entity type * @param entity the entity to persist * @return the persisted entity */ public <E> E persist(E entity) { getEntityManager().persist(entity); return entity; } /** * Make an instance managed and persistent, synchronize the persistence context to the * underlying database and finally find the persisted entity by its ID. Delegates to * {@link #persistAndFlush(Object)} then {@link #find(Class, Object)} with the * {@link #getId(Object) entity ID}. * <p> * Helpful when ensuring that entity data is actually written and read from the * underlying database correctly. * @param <E> the entity type * @param entity the entity to persist * @return the entity found using the ID of the persisted entity */ @SuppressWarnings("unchecked") public <E> E persistFlushFind(E entity) { EntityManager entityManager = getEntityManager(); persistAndFlush(entity); Object id = getId(entity); entityManager.detach(entity); return (E) entityManager.find(entity.getClass(), id); } /** * Make an instance managed and persistent then synchronize the persistence context to * the underlying database. Delegates to {@link EntityManager#persist(Object)} then * {@link #flush()} and finally returns the original source entity. * <p> * Helpful when setting up test data in a test: <pre class="code"> * MyEntity entity = this.testEntityManager.persistAndFlush(new MyEntity("Spring")); * </pre> * @param <E> the entity type * @param entity the entity to persist * @return the persisted entity */ public <E> E persistAndFlush(E entity) { persist(entity); flush(); return entity; } /** * Merge the state of the given entity into the current persistence context. Delegates * to {@link EntityManager#merge(Object)} * @param <E> the entity type * @param entity the entity to merge * @return the merged entity */ public <E> E merge(E entity) { return getEntityManager().merge(entity); } /** * Remove the entity instance. Delegates to {@link EntityManager#remove(Object)} * @param entity the entity to remove */ public void remove(Object entity) { getEntityManager().remove(entity); } /** * Find by primary key. Delegates to {@link EntityManager#find(Class, Object)}. * @param <E> the entity type * @param entityClass the entity class * @param primaryKey the entity primary key * @return the found entity or {@code null} if the entity does not exist * @see #getId(Object) */ public <E> @Nullable E find(Class<E> entityClass, Object primaryKey) { return getEntityManager().find(entityClass, primaryKey); } /** * Synchronize the persistence context to the underlying database. Delegates to * {@link EntityManager#flush()}. */ public void flush() { getEntityManager().flush(); } /** * Refresh the state of the instance from the database, overwriting changes made to * the entity, if any. Delegates to {@link EntityManager#refresh(Object)}. * @param <E> the entity type * @param entity the entity to refresh * @return the refreshed entity */ public <E> E refresh(E entity) { getEntityManager().refresh(entity); return entity; } /** * Clear the persistence context, causing all managed entities to become detached. * Delegates to {@link EntityManager#clear()} */ public void clear() { getEntityManager().clear(); } /** * Remove the given entity from the persistence context, causing a managed entity to * become detached. Delegates to {@link EntityManager#detach(Object)}. * @param entity the entity to detach. */ public void detach(Object entity) { getEntityManager().detach(entity); } /** * Return the ID of the given entity. Delegates to * {@link PersistenceUnitUtil#getIdentifier(Object)}. * @param entity the source entity * @return the ID of the entity or {@code null} * @see #getId(Object, Class) */ public @Nullable Object getId(Object entity) { return this.entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); } /** * Return the ID of the given entity cast to a specific type. Delegates to * {@link PersistenceUnitUtil#getIdentifier(Object)}. * @param <T> the ID type * @param entity the source entity * @param idType the expected ID type * @return the ID of the entity or {@code null} * @see #getId(Object) */ @SuppressWarnings("unchecked") public <T> @Nullable T getId(Object entity, Class<T> idType) { Object id = getId(entity); Assert.isInstanceOf(idType, id, "ID mismatch:"); return (T) id; } /** * Return the underlying {@link EntityManager} that's actually used to perform all * operations. * @return the entity manager */ public final EntityManager getEntityManager() { EntityManager manager = EntityManagerFactoryUtils.getTransactionalEntityManager(this.entityManagerFactory); Assert.state(manager != null, "No transactional EntityManager found, is your test running in a transaction?"); return manager; } }
TestEntityManager
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/internal/util/beans/BeanInfoHelper.java
{ "start": 518, "end": 3086 }
interface ____<T> { T processBeanInfo(BeanInfo beanInfo) throws Exception; } private final Class<?> beanClass; private final Class<?> stopClass; public BeanInfoHelper(Class<?> beanClass) { this( beanClass, Object.class ); } public BeanInfoHelper(Class<?> beanClass, Class<?> stopClass) { this.beanClass = beanClass; this.stopClass = stopClass; } public void applyToBeanInfo(Object bean, BeanInfoDelegate delegate) { if ( ! beanClass.isInstance( bean ) ) { throw new BeanIntrospectionException( "Bean [" + bean + "] was not of declared bean type [" + beanClass.getName() + "]" ); } visitBeanInfo( beanClass, stopClass, delegate ); } public static void visitBeanInfo(Class<?> beanClass, BeanInfoDelegate delegate) { visitBeanInfo( beanClass, Object.class, delegate ); } public static void visitBeanInfo(Class<?> beanClass, Class<?> stopClass, BeanInfoDelegate delegate) { try { BeanInfo info = Introspector.getBeanInfo( beanClass, stopClass ); try { delegate.processBeanInfo( info ); } catch ( RuntimeException e ) { throw e; } catch ( InvocationTargetException e ) { throw new BeanIntrospectionException( "Error delegating bean info use", e.getTargetException() ); } catch ( Exception e ) { throw new BeanIntrospectionException( "Error delegating bean info use", e ); } finally { Introspector.flushFromCaches( beanClass ); } } catch ( IntrospectionException e ) { throw new BeanIntrospectionException( "Unable to determine bean info from class [" + beanClass.getName() + "]", e ); } } public static <T> T visitBeanInfo(Class<?> beanClass, ReturningBeanInfoDelegate<T> delegate) { return visitBeanInfo( beanClass, null, delegate ); } public static <T> T visitBeanInfo(Class<?> beanClass, Class<?> stopClass, ReturningBeanInfoDelegate<T> delegate) { try { BeanInfo info = Introspector.getBeanInfo( beanClass, stopClass ); try { return delegate.processBeanInfo( info ); } catch ( RuntimeException e ) { throw e; } catch ( InvocationTargetException e ) { throw new BeanIntrospectionException( "Error delegating bean info use", e.getTargetException() ); } catch ( Exception e ) { throw new BeanIntrospectionException( "Error delegating bean info use", e ); } finally { Introspector.flushFromCaches( beanClass ); } } catch ( IntrospectionException e ) { throw new BeanIntrospectionException( "Unable to determine bean info from class [" + beanClass.getName() + "]", e ); } } }
ReturningBeanInfoDelegate
java
spring-projects__spring-security
oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2DeviceAuthorizationResponse.java
{ "start": 3987, "end": 7567 }
class ____ { private final String deviceCode; private final String userCode; private String verificationUri; private String verificationUriComplete; private long expiresIn; private long interval; private Map<String, Object> additionalParameters; private Builder(OAuth2DeviceCode deviceCode, OAuth2UserCode userCode) { this.deviceCode = deviceCode.getTokenValue(); this.userCode = userCode.getTokenValue(); this.expiresIn = ChronoUnit.SECONDS.between(deviceCode.getIssuedAt(), deviceCode.getExpiresAt()); } private Builder(String deviceCode, String userCode) { this.deviceCode = deviceCode; this.userCode = userCode; } /** * Sets the end-user verification URI. * @param verificationUri the end-user verification URI * @return the {@link Builder} */ public Builder verificationUri(String verificationUri) { this.verificationUri = verificationUri; return this; } /** * Sets the end-user verification URI that includes the user code. * @param verificationUriComplete the end-user verification URI that includes the * user code * @return the {@link Builder} */ public Builder verificationUriComplete(String verificationUriComplete) { this.verificationUriComplete = verificationUriComplete; return this; } /** * Sets the lifetime (in seconds) of the device code and user code. * @param expiresIn the lifetime (in seconds) of the device code and user code * @return the {@link Builder} */ public Builder expiresIn(long expiresIn) { this.expiresIn = expiresIn; return this; } /** * Sets the minimum amount of time (in seconds) that the client should wait * between polling requests to the token endpoint. * @param interval the minimum amount of time between polling requests * @return the {@link Builder} */ public Builder interval(long interval) { this.interval = interval; return this; } /** * Sets the additional parameters returned in the response. * @param additionalParameters the additional parameters returned in the response * @return the {@link Builder} */ public Builder additionalParameters(Map<String, Object> additionalParameters) { this.additionalParameters = additionalParameters; return this; } /** * Builds a new {@link OAuth2DeviceAuthorizationResponse}. * @return a {@link OAuth2DeviceAuthorizationResponse} */ public OAuth2DeviceAuthorizationResponse build() { Assert.hasText(this.verificationUri, "verificationUri cannot be empty"); Assert.isTrue(this.expiresIn > 0, "expiresIn must be greater than zero"); Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(this.expiresIn); OAuth2DeviceCode deviceCode = new OAuth2DeviceCode(this.deviceCode, issuedAt, expiresAt); OAuth2UserCode userCode = new OAuth2UserCode(this.userCode, issuedAt, expiresAt); OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = new OAuth2DeviceAuthorizationResponse(); deviceAuthorizationResponse.deviceCode = deviceCode; deviceAuthorizationResponse.userCode = userCode; deviceAuthorizationResponse.verificationUri = this.verificationUri; deviceAuthorizationResponse.verificationUriComplete = this.verificationUriComplete; deviceAuthorizationResponse.interval = this.interval; deviceAuthorizationResponse.additionalParameters = Collections .unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap() : this.additionalParameters); return deviceAuthorizationResponse; } } }
Builder
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastCodeBlock.java
{ "start": 1388, "end": 2762 }
class ____ { private final String code; private final String returnTerm; private final String isNullTerm; private CastCodeBlock(String code, String returnTerm, String isNullTerm) { this.code = code; this.returnTerm = returnTerm; this.isNullTerm = isNullTerm; } public static CastCodeBlock withoutCode(String returnTerm, String isNullTerm) { return new CastCodeBlock("", returnTerm, isNullTerm); } public static CastCodeBlock withCode(String code, String returnTerm, String isNullTerm) { return new CastCodeBlock(code, returnTerm, isNullTerm); } public String getCode() { return code; } public String getReturnTerm() { return returnTerm; } public String getIsNullTerm() { return isNullTerm; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CastCodeBlock that = (CastCodeBlock) o; return Objects.equals(code, that.code) && Objects.equals(returnTerm, that.returnTerm) && Objects.equals(isNullTerm, that.isNullTerm); } @Override public int hashCode() { return Objects.hash(code, returnTerm, isNullTerm); } }
CastCodeBlock
java
quarkusio__quarkus
integration-tests/smallrye-graphql-client-keycloak/src/test/java/io/quarkus/it/smallrye/graphql/keycloak/KeycloakRealmResourceManager.java
{ "start": 826, "end": 5781 }
class ____ implements QuarkusTestResourceLifecycleManager { private static final String KEYCLOAK_SERVER_URL = System.getProperty("keycloak.url", "http://localhost:8180"); private static final String KEYCLOAK_REALM = "quarkus"; @Override public Map<String, String> start() { RealmRepresentation realm = createRealm(KEYCLOAK_REALM); realm.setRevokeRefreshToken(true); realm.setRefreshTokenMaxReuse(0); realm.setAccessTokenLifespan(3); realm.setRequiredActions(List.of()); realm.getClients().add(createClient("quarkus-app")); realm.getUsers().add(createUser("alice", "user")); try { Response response = RestAssured .given() .auth().oauth2(getAdminAccessToken()) .contentType("application/json") .body(JsonSerialization.writeValueAsBytes(realm)) .when() .post(KEYCLOAK_SERVER_URL + "/admin/realms"); response.then() .statusCode(201); } catch (IOException e) { throw new RuntimeException(e); } Map<String, String> properties = new HashMap<>(); properties.put("quarkus.oidc.auth-server-url", KEYCLOAK_SERVER_URL + "/realms/" + KEYCLOAK_REALM); properties.put("keycloak.url", KEYCLOAK_SERVER_URL); return properties; } private static String getAdminAccessToken() { return RestAssured .given() .param("grant_type", "password") .param("username", "admin") .param("password", "admin") .param("client_id", "admin-cli") .when() .post(KEYCLOAK_SERVER_URL + "/realms/master/protocol/openid-connect/token") .as(AccessTokenResponse.class).getToken(); } private static RealmRepresentation createRealm(String name) { RealmRepresentation realm = new RealmRepresentation(); realm.setRealm(name); realm.setEnabled(true); realm.setRequiredActions(List.of()); realm.setUsers(new ArrayList<>()); realm.setClients(new ArrayList<>()); realm.setAccessTokenLifespan(3); realm.setSsoSessionMaxLifespan(3); realm.setRequiredActions(List.of()); RolesRepresentation roles = new RolesRepresentation(); List<RoleRepresentation> realmRoles = new ArrayList<>(); roles.setRealm(realmRoles); realm.setRoles(roles); realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false)); realm.getRoles().getRealm().add(new RoleRepresentation("admin", null, false)); return realm; } private static ClientRepresentation createClient(String clientId) { ClientRepresentation client = new ClientRepresentation(); client.setClientId(clientId); client.setPublicClient(false); client.setSecret("secret"); client.setDirectAccessGrantsEnabled(true); client.setServiceAccountsEnabled(true); client.setRedirectUris(Arrays.asList("*")); client.setEnabled(true); client.setDefaultClientScopes(List.of("microprofile-jwt")); return client; } private static UserRepresentation createUser(String username, String... realmRoles) { UserRepresentation user = new UserRepresentation(); user.setUsername(username); user.setEnabled(true); user.setRealmRoles(Arrays.asList(realmRoles)); user.setEmail(username + "@gmail.com"); user.setRequiredActions(List.of()); user.setEmailVerified(true); CredentialRepresentation credential = new CredentialRepresentation(); credential.setType(CredentialRepresentation.PASSWORD); credential.setValue(username); credential.setTemporary(false); user.setCredentials(List.of(credential)); return user; } @Override public void stop() { RestAssured .given() .auth().oauth2(getAdminAccessToken()) .when() .delete(KEYCLOAK_SERVER_URL + "/admin/realms/" + KEYCLOAK_REALM).then().statusCode(204); } public static String getAccessToken() { io.restassured.response.Response response = RestAssured.given() .contentType("application/x-www-form-urlencoded") .accept("application/json") .formParam("username", "alice") .formParam("password", "alice") .param("client_id", "quarkus-app") .param("client_secret", "secret") .formParam("grant_type", "password") .post(KEYCLOAK_SERVER_URL + "/realms/" + KEYCLOAK_REALM + "/protocol/openid-connect/token"); return response.getBody().jsonPath().getString("access_token"); } }
KeycloakRealmResourceManager
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/CamelCustomDefaultThreadPoolProfileTest.java
{ "start": 1307, "end": 3064 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext camel = super.createCamelContext(); ThreadPoolProfile profile = new ThreadPoolProfile("custom"); profile.setPoolSize(5); profile.setMaxPoolSize(15); profile.setKeepAliveTime(25L); profile.setMaxQueueSize(250); profile.setAllowCoreThreadTimeOut(true); profile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort); DefaultExecutorServiceManager executorServiceManager = new DefaultExecutorServiceManager(camel); executorServiceManager.setDefaultThreadPoolProfile(profile); camel.setExecutorServiceManager(executorServiceManager); return camel; } @Test public void testCamelCustomDefaultThreadPoolProfile() { DefaultExecutorServiceManager manager = (DefaultExecutorServiceManager) context.getExecutorServiceManager(); ThreadPoolProfile profile = manager.getDefaultThreadPoolProfile(); assertEquals(5, profile.getPoolSize().intValue()); assertEquals(15, profile.getMaxPoolSize().intValue()); assertEquals(25, profile.getKeepAliveTime().longValue()); assertEquals(250, profile.getMaxQueueSize().intValue()); assertTrue(profile.getAllowCoreThreadTimeOut().booleanValue()); assertEquals(ThreadPoolRejectedPolicy.Abort, profile.getRejectedPolicy()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").threads(25, 45).to("mock:result"); } }; } }
CamelCustomDefaultThreadPoolProfileTest
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Beans.java
{ "start": 61277, "end": 61971 }
class ____ implements BiFunction<String, ClassVisitor, ClassVisitor> { @Override public ClassVisitor apply(String className, ClassVisitor classVisitor) { ClassTransformer transformer = new ClassTransformer(className); transformer.modifyMethod(MethodDescriptor.ofConstructor(className)).removeModifiers(Opcodes.ACC_PRIVATE); LOGGER.debugf("Changed visibility of a private no-args constructor to package-private: %s", className); return transformer.applyTo(classVisitor); } } // alters an injected field modifier from private to package private static
PrivateNoArgsConstructorTransformFunction
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/functions/table/fullcache/inputformat/FullCacheTestInputFormat.java
{ "start": 6449, "end": 6983 }
class ____ implements InputSplit { private final transient ConcurrentLinkedQueue<RowData> queue; private final int splitNumber; public QueueInputSplit(ConcurrentLinkedQueue<RowData> queue, int splitNumber) { this.queue = queue; this.splitNumber = splitNumber; } @Override public int getSplitNumber() { return splitNumber; } public ConcurrentLinkedQueue<RowData> getQueue() { return queue; } } }
QueueInputSplit
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/InvokerHelper.java
{ "start": 174, "end": 540 }
class ____ { private final Map<String, Invoker<?, ?>> invokers; public InvokerHelper(Map<String, Invoker<?, ?>> invokers) { this.invokers = invokers; } public <T, R> Invoker<T, R> getInvoker(String id) { Invoker<T, R> result = (Invoker<T, R>) invokers.get(id); assertNotNull(result); return result; } }
InvokerHelper
java
apache__avro
lang/java/protobuf/src/test/java/org/apache/avro/protobuf/multiplefiles/M.java
{ "start": 2319, "end": 2611 }
enum ____ with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static N valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding
associated
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/cluster/node/stats/NodesStatsRequestParametersTests.java
{ "start": 1958, "end": 2619 }
enum ____ change or extension public void testEnsureMetricOrdinalsOrder() { EnumSerializationTestUtils.assertEnumSerialization( Metric.class, Metric.OS, Metric.PROCESS, Metric.JVM, Metric.THREAD_POOL, Metric.FS, Metric.TRANSPORT, Metric.HTTP, Metric.BREAKER, Metric.SCRIPT, Metric.DISCOVERY, Metric.INGEST, Metric.ADAPTIVE_SELECTION, Metric.SCRIPT_CACHE, Metric.INDEXING_PRESSURE, Metric.REPOSITORIES, Metric.ALLOCATIONS ); } }
ordering
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/ConnectableFluxOnAssembly.java
{ "start": 1638, "end": 2868 }
class ____<T> extends InternalConnectableFluxOperator<T, T> implements Fuseable, AssemblyOp, Scannable { final AssemblySnapshot stacktrace; ConnectableFluxOnAssembly(ConnectableFlux<T> source, AssemblySnapshot stacktrace) { super(source); this.stacktrace = stacktrace; } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { return FluxOnAssembly.wrapSubscriber(actual, source, this, stacktrace); } @Override public void connect(Consumer<? super Disposable> cancelSupport) { source.connect(cancelSupport); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PREFETCH) return getPrefetch(); if (key == Attr.PARENT) return source; if (key == Attr.ACTUAL_METADATA) return !stacktrace.isCheckpoint; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } @Override public String stepName() { return stacktrace.operatorAssemblyInformation(); } @Override public String toString() { return stacktrace.operatorAssemblyInformation(); } }
ConnectableFluxOnAssembly
java
quarkusio__quarkus
integration-tests/devmode/src/test/java/io/quarkus/test/devui/MyEntity.java
{ "start": 149, "end": 470 }
class ____ { @Id Long id; @Column String field; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getField() { return field; } public void setField(String field) { this.field = field; } }
MyEntity
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/filters/PropertyPathTest.java
{ "start": 1920, "end": 2415 }
class ____ { private int id; private C c; private D d; public int getId() { return id; } public void setId(int id) { this.id = id; } public C getC() { return c; } public void setC(C c) { this.c = c; } public D getD() { return d; } public void setD(D d) { this.d = d; } } public static
B
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/setup/SharedHttpSessionConfigurer.java
{ "start": 1469, "end": 2127 }
class ____ implements MockMvcConfigurer { private @Nullable HttpSession session; @Override public void afterConfigurerAdded(ConfigurableMockMvcBuilder<?> builder) { builder.alwaysDo(result -> this.session = result.getRequest().getSession(false)); } @Override public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) { return request -> { if (this.session != null) { request.setSession(this.session); } return request; }; } public static SharedHttpSessionConfigurer sharedHttpSession() { return new SharedHttpSessionConfigurer(); } }
SharedHttpSessionConfigurer
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/EsqlFunctionRegistry.java
{ "start": 64879, "end": 65770 }
interface ____<T> { T build(Source source, Expression left, Expression right, Configuration configuration); } /** * Build a {@linkplain FunctionDefinition} for a ternary function that is configuration aware. */ @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do protected static <T extends Function> FunctionDefinition def( Class<T> function, TernaryConfigurationAwareBuilder<T> ctorRef, String... names ) { FunctionBuilder builder = (source, children, cfg) -> { checkIsOptionalTriFunction(function, children.size()); return ctorRef.build(source, children.get(0), children.get(1), children.size() == 3 ? children.get(2) : null, cfg); }; return def(function, builder, names); } protected
BinaryConfigurationAwareBuilder
java
apache__dubbo
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java
{ "start": 10238, "end": 10304 }
enum ____ { Start, Reset, Stop } }
Command
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreEvent.java
{ "start": 932, "end": 1082 }
class ____ extends AbstractEvent<RMStateStoreEventType> { public RMStateStoreEvent(RMStateStoreEventType type) { super(type); } }
RMStateStoreEvent
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/alternatives/priority/AlternativeProducerPriorityOnClassTest.java
{ "start": 530, "end": 912 }
class ____ { @RegisterExtension ArcTestContainer testContainer = new ArcTestContainer(Producer.class, Consumer.class); @Test public void testAlternativePriorityResolution() { Consumer bean = Arc.container().instance(Consumer.class).get(); assertNotNull(bean.foo); assertNotNull(bean.bar); } static
AlternativeProducerPriorityOnClassTest
java
redisson__redisson
redisson-hibernate/redisson-hibernate-5/src/main/java/org/redisson/hibernate/RedissonCacheKeysFactory.java
{ "start": 1106, "end": 2227 }
class ____ extends DefaultCacheKeysFactory { private final Codec codec; public RedissonCacheKeysFactory(Codec codec) { this.codec = codec; } @Override public Object createCollectionKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { try { String[] parts = persister.getRole().split("\\."); Field f = ReflectHelper.findField(id.getClass(), parts[parts.length - 1]); Object prev = f.get(id); f.set(id, null); ByteBuf state = codec.getMapKeyEncoder().encode(id); Object newId = codec.getMapKeyDecoder().decode(state, null); state.release(); f.set(id, prev); return super.createCollectionKey(newId, persister, factory, tenantIdentifier); } catch (PropertyNotFoundException e) { return super.createCollectionKey(id, persister, factory, tenantIdentifier); } catch (IllegalAccessException | IOException e) { throw new IllegalStateException(e); } } }
RedissonCacheKeysFactory
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/function/SupplierUtils.java
{ "start": 962, "end": 1908 }
class ____ { /** * Resolve the given {@code Supplier}, getting its result or immediately * returning {@code null} if the supplier itself was {@code null}. * @param supplier the supplier to resolve * @return the supplier's result, or {@code null} if none */ @Contract("null -> null") public static <T extends @Nullable Object> @Nullable T resolve(@Nullable Supplier<T> supplier) { return (supplier != null ? supplier.get() : null); } /** * Resolve a given {@code Supplier}, getting its result or immediately * returning the given Object as-is if not a {@code Supplier}. * @param candidate the candidate to resolve (potentially a {@code Supplier}) * @return a supplier's result or the given Object as-is * @since 6.1.4 */ @Contract("null -> null") public static @Nullable Object resolve(@Nullable Object candidate) { return (candidate instanceof Supplier<?> supplier ? supplier.get() : candidate); } }
SupplierUtils
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/ClassNameFilter.java
{ "start": 2406, "end": 2531 }
class ____ be excluded from the result set. * * @param patterns regular expressions to match against fully qualified *
will
java
grpc__grpc-java
netty/src/main/java/io/grpc/netty/GrpcSslContexts.java
{ "start": 1766, "end": 11050 }
class ____ { private static final Logger logger = Logger.getLogger(GrpcSslContexts.class.getName()); private GrpcSslContexts() {} // The "h2" string identifies HTTP/2 when used over TLS private static final String HTTP2_VERSION = "h2"; /* * List of ALPN/NPN protocols in order of preference. */ private static final List<String> NEXT_PROTOCOL_VERSIONS = Collections.unmodifiableList(Arrays.asList(HTTP2_VERSION)); /* * These configs use ACCEPT due to limited support in OpenSSL. Actual protocol enforcement is * done in ProtocolNegotiators. */ private static final ApplicationProtocolConfig ALPN = new ApplicationProtocolConfig( Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, NEXT_PROTOCOL_VERSIONS); private static final ApplicationProtocolConfig NPN = new ApplicationProtocolConfig( Protocol.NPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, NEXT_PROTOCOL_VERSIONS); private static final ApplicationProtocolConfig NPN_AND_ALPN = new ApplicationProtocolConfig( Protocol.NPN_AND_ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, NEXT_PROTOCOL_VERSIONS); private static final String SUN_PROVIDER_NAME = "SunJSSE"; private static final String IBM_PROVIDER_NAME = "IBMJSSE2"; private static final String OPENJSSE_PROVIDER_NAME = "OpenJSSE"; private static final String BCJSSE_PROVIDER_NAME = "BCJSSE"; /** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forClient() * @see #configure(SslContextBuilder) */ public static SslContextBuilder forClient() { return configure(SslContextBuilder.forClient()); } /** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forServer(File, File) * @see #configure(SslContextBuilder) */ public static SslContextBuilder forServer(File keyCertChainFile, File keyFile) { return configure(SslContextBuilder.forServer(keyCertChainFile, keyFile)); } /** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forServer(File, File, String) * @see #configure(SslContextBuilder) */ public static SslContextBuilder forServer( File keyCertChainFile, File keyFile, String keyPassword) { return configure(SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword)); } /** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forServer(InputStream, InputStream) * @see #configure(SslContextBuilder) */ public static SslContextBuilder forServer(InputStream keyCertChain, InputStream key) { return configure(SslContextBuilder.forServer(keyCertChain, key)); } /** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forServer(InputStream, InputStream, String) * @see #configure(SslContextBuilder) */ public static SslContextBuilder forServer( InputStream keyCertChain, InputStream key, String keyPassword) { return configure(SslContextBuilder.forServer(keyCertChain, key, keyPassword)); } /** * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if * an application requires particular settings it should override the options set here. */ @CanIgnoreReturnValue public static SslContextBuilder configure(SslContextBuilder builder) { return configure(builder, defaultSslProvider()); } /** * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if * an application requires particular settings it should override the options set here. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1784") @CanIgnoreReturnValue public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) { switch (provider) { case JDK: { Provider jdkProvider = findJdkProvider(); if (jdkProvider == null) { throw new IllegalArgumentException( "Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers"); } return configure(builder, jdkProvider); } case OPENSSL: { ApplicationProtocolConfig apc; if (OpenSsl.isAlpnSupported()) { apc = NPN_AND_ALPN; } else { apc = NPN; } return builder .sslProvider(SslProvider.OPENSSL) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(apc); } default: throw new IllegalArgumentException("Unsupported provider: " + provider); } } /** * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if * an application requires particular settings it should override the options set here. */ @CanIgnoreReturnValue public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) { ApplicationProtocolConfig apc; if (SUN_PROVIDER_NAME.equals(jdkProvider.getName())) { // Jetty ALPN/NPN only supports one of NPN or ALPN if (JettyTlsUtil.isJettyAlpnConfigured()) { apc = ALPN; } else if (JettyTlsUtil.isJettyNpnConfigured()) { apc = NPN; } else if (JettyTlsUtil.isJava9AlpnAvailable()) { apc = ALPN; } else { throw new IllegalArgumentException( jdkProvider.getName() + " selected, but Java 9+ and Jetty NPN/ALPN unavailable"); } } else if (IBM_PROVIDER_NAME.equals(jdkProvider.getName()) || OPENJSSE_PROVIDER_NAME.equals(jdkProvider.getName()) || BCJSSE_PROVIDER_NAME.equals(jdkProvider.getName())) { if (JettyTlsUtil.isJava9AlpnAvailable()) { apc = ALPN; } else { throw new IllegalArgumentException( jdkProvider.getName() + " selected, but Java 9+ ALPN unavailable"); } } else if (ConscryptLoader.isConscrypt(jdkProvider)) { apc = ALPN; // TODO: Conscrypt triggers failures in the TrustManager. // https://github.com/grpc/grpc-java/issues/7765 builder.protocols("TLSv1.2"); } else { throw new IllegalArgumentException("Unknown provider; can't configure: " + jdkProvider); } return builder .sslProvider(SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(apc) .sslContextProvider(jdkProvider); } /** * Returns OpenSSL if available, otherwise returns the JDK provider. */ private static SslProvider defaultSslProvider() { if (OpenSsl.isAvailable()) { logger.log(Level.FINE, "Selecting OPENSSL"); return SslProvider.OPENSSL; } Provider provider = findJdkProvider(); if (provider != null) { logger.log(Level.FINE, "Selecting JDK with provider {0}", provider); return SslProvider.JDK; } logger.log(Level.INFO, "Java 9 ALPN API unavailable (this may be normal)"); logger.log(Level.INFO, "netty-tcnative unavailable (this may be normal)", OpenSsl.unavailabilityCause()); logger.log(Level.INFO, "Conscrypt not found (this may be normal)", ConscryptHolder.UNAVAILABILITY_CAUSE); logger.log(Level.INFO, "Jetty ALPN unavailable (this may be normal)", JettyTlsUtil.getJettyAlpnUnavailabilityCause()); throw new IllegalStateException( "Could not find TLS ALPN provider; " + "no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available"); } private static Provider findJdkProvider() { for (Provider provider : Security.getProviders("SSLContext.TLS")) { if (SUN_PROVIDER_NAME.equals(provider.getName())) { if (JettyTlsUtil.isJettyAlpnConfigured() || JettyTlsUtil.isJettyNpnConfigured() || JettyTlsUtil.isJava9AlpnAvailable()) { return provider; } } else if (IBM_PROVIDER_NAME.equals(provider.getName()) || OPENJSSE_PROVIDER_NAME.equals(provider.getName()) || BCJSSE_PROVIDER_NAME.equals(provider.getName())) { if (JettyTlsUtil.isJava9AlpnAvailable()) { return provider; } } else if (ConscryptLoader.isConscrypt(provider)) { return provider; } } if (ConscryptHolder.PROVIDER != null) { return ConscryptHolder.PROVIDER; } return null; } @SuppressWarnings("deprecation") static void ensureAlpnAndH2Enabled( io.netty.handler.ssl.ApplicationProtocolNegotiator alpnNegotiator) { checkArgument(alpnNegotiator != null, "ALPN must be configured"); checkArgument(alpnNegotiator.protocols() != null && !alpnNegotiator.protocols().isEmpty(), "ALPN must be enabled and list HTTP/2 as a supported protocol."); checkArgument( alpnNegotiator.protocols().contains(HTTP2_VERSION), "This ALPN config does not support HTTP/2. Expected %s, but got %s'.", HTTP2_VERSION, alpnNegotiator.protocols()); } private static
GrpcSslContexts
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EscapeConvertedCharArrayTest.java
{ "start": 1042, "end": 2861 }
class ____ { private static final String STRING_PROP = "TEST123456"; @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { Vehicle vehicle = new Vehicle( 1L, STRING_PROP.toCharArray(), STRING_PROP ); session.persist( vehicle ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> session.createMutationQuery( "delete from Vehicle" ).executeUpdate() ); } @Test public void testCharArrayPropEscapeLiteral(SessionFactoryScope scope) { testLikeEscape( scope, "charArrayProp", false ); } @Test public void testCharArrayPropEscapeParameter(SessionFactoryScope scope) { testLikeEscape( scope, "charArrayProp", true ); } @Test public void testConvertedStringPropEscapeLiteral(SessionFactoryScope scope) { testLikeEscape( scope, "convertedStringProp", false ); } @Test public void testConvertedStringPropEscapeParameter(SessionFactoryScope scope) { testLikeEscape( scope, "convertedStringProp", true ); } private void testLikeEscape(SessionFactoryScope scope, String propertyName, boolean parameter) { scope.inTransaction( session -> { final TypedQuery<Vehicle> query = session.createQuery( String.format( "from Vehicle where %s like :param escape %s", propertyName, parameter ? ":escape" : "'!'" ), Vehicle.class ) .setParameter( "param", "TEST%" ); if ( parameter ) { query.setParameter( "escape", '!' ); } final Vehicle vehicle = query.getSingleResult(); assertEquals( 1L, vehicle.getId() ); assertArrayEquals( STRING_PROP.toCharArray(), vehicle.getCharArrayProp() ); assertEquals( STRING_PROP, vehicle.getConvertedStringProp() ); } ); } @Entity(name = "Vehicle") public static
EscapeConvertedCharArrayTest
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java
{ "start": 115131, "end": 115517 }
class ____ extends ScalarFunction { @FunctionHint( arguments = { @ArgumentHint(type = @DataTypeHint("STRING")), @ArgumentHint(type = @DataTypeHint("INTEGER")) }) public String eval(String f1, Integer f2) { return ""; } } private static
ArgumentHintMissingNameScalarFunction
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StYSerializationTests.java
{ "start": 450, "end": 871 }
class ____ extends AbstractExpressionSerializationTests<StY> { @Override protected StY createTestInstance() { return new StY(randomSource(), randomChild()); } @Override protected StY mutateInstance(StY instance) throws IOException { return new StY(instance.source(), randomValueOtherThan(instance.field(), AbstractExpressionSerializationTests::randomChild)); } }
StYSerializationTests
java
apache__flink
flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/RegistryAvroDeserializationSchema.java
{ "start": 1945, "end": 2749 }
class ____ which deserialize. Should be either {@link SpecificRecord} or * {@link GenericRecord}. * @param reader reader's Avro schema. Should be provided if recordClazz is {@link * GenericRecord} * @param schemaCoderProvider schema provider that allows instantiation of {@link SchemaCoder} * that will be used for schema reading */ public RegistryAvroDeserializationSchema( Class<T> recordClazz, @Nullable Schema reader, SchemaCoder.SchemaCoderProvider schemaCoderProvider) { this(recordClazz, reader, schemaCoderProvider, AvroEncoding.BINARY); } /** * Creates Avro deserialization schema that reads schema from input stream using provided {@link * SchemaCoder}. * * @param recordClazz
to
java
apache__camel
components/camel-soap/src/main/java/org/apache/camel/dataformat/soap/name/XmlRootElementPreferringElementNameStrategy.java
{ "start": 1079, "end": 3270 }
class ____ implements ElementNameStrategy { private static final String DEFAULT_NS = "##default"; @Override public QName findQNameForSoapActionOrType(String soapAction, Class<?> type) { XmlType xmlType = type.getAnnotation(XmlType.class); if (xmlType == null || xmlType.name() == null) { throw new RuntimeException("The type " + type.getName() + " needs to have an XmlType annotation with name"); } // prefer name+ns from the XmlRootElement, and fallback to XmlType String localName = null; String nameSpace = null; XmlRootElement root = type.getAnnotation(XmlRootElement.class); if (root != null) { localName = ObjectHelper.isEmpty(localName) ? root.name() : localName; nameSpace = isInValidNamespace(nameSpace) ? root.namespace() : nameSpace; } if (ObjectHelper.isEmpty(localName)) { localName = xmlType.name(); } if (isInValidNamespace(nameSpace)) { XmlSchema xmlSchema = type.getPackage().getAnnotation(XmlSchema.class); if (xmlSchema != null) { nameSpace = xmlSchema.namespace(); } } if (isInValidNamespace(nameSpace)) { nameSpace = xmlType.namespace(); } if (ObjectHelper.isEmpty(localName) || isInValidNamespace(nameSpace)) { throw new IllegalStateException("Unable to determine localName or namespace for type <" + type.getName() + ">"); } return new QName(nameSpace, localName); } private boolean isInValidNamespace(String namespace) { return ObjectHelper.isEmpty(namespace) || DEFAULT_NS.equalsIgnoreCase(namespace); } @Override public Class<? extends Exception> findExceptionForFaultName(QName faultName) { throw new UnsupportedOperationException("Exception lookup is not supported"); } @Override public Class<? extends Exception> findExceptionForSoapActionAndFaultName(String soapAction, QName faultName) { throw new UnsupportedOperationException("Exception lookup is not supported"); } }
XmlRootElementPreferringElementNameStrategy
java
grpc__grpc-java
netty/src/test/java/io/grpc/netty/NettyServerProviderTest.java
{ "start": 1091, "end": 2133 }
class ____ { private NettyServerProvider provider = new NettyServerProvider(); @Test public void provided() { assertSame(NettyServerProvider.class, ServerProvider.provider().getClass()); } @Test public void basicMethods() { assertTrue(provider.isAvailable()); assertEquals(5, provider.priority()); } @Test public void builderIsANettyBuilder() { assertSame(NettyServerBuilder.class, provider.builderForPort(443).getClass()); } @Test public void newServerBuilderForPort_success() { ServerProvider.NewServerBuilderResult result = provider.newServerBuilderForPort(80, InsecureServerCredentials.create()); assertThat(result.getServerBuilder()).isInstanceOf(NettyServerBuilder.class); } @Test public void newServerBuilderForPort_fail() { ServerProvider.NewServerBuilderResult result = provider.newServerBuilderForPort( 80, new FakeServerCredentials()); assertThat(result.getError()).contains("FakeServerCredentials"); } private static final
NettyServerProviderTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/ExponentialHistogramStates.java
{ "start": 3781, "end": 7502 }
class ____ implements GroupingAggregatorState { private ObjectArray<ExponentialHistogramMerger> states; private final HistoBreaker breaker; private final BigArrays bigArrays; GroupingState(BigArrays bigArrays, CircuitBreaker breaker) { this.states = bigArrays.newObjectArray(1); this.bigArrays = bigArrays; this.breaker = new HistoBreaker(breaker); } ExponentialHistogramMerger getOrNull(int position) { if (position < states.size()) { return states.get(position); } else { return null; } } public void add(int groupId, ExponentialHistogram histogram, boolean allowUpscale) { if (histogram == null) { return; } ensureCapacity(groupId); var state = states.get(groupId); if (state == null) { state = ExponentialHistogramMerger.create(MAX_BUCKET_COUNT, breaker); states.set(groupId, state); } if (allowUpscale) { state.add(histogram); } else { state.addWithoutUpscaling(histogram); } } private void ensureCapacity(int groupId) { states = bigArrays.grow(states, groupId + 1); } @Override public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) { assert blocks.length >= offset + 2 : "blocks=" + blocks.length + ",offset=" + offset; try ( var histoBuilder = driverContext.blockFactory().newExponentialHistogramBlockBuilder(selected.getPositionCount()); var seenBuilder = driverContext.blockFactory().newBooleanBlockBuilder(selected.getPositionCount()); ) { for (int i = 0; i < selected.getPositionCount(); i++) { int groupId = selected.getInt(i); ExponentialHistogramMerger state = getOrNull(groupId); if (state != null) { seenBuilder.appendBoolean(true); histoBuilder.append(state.get()); } else { seenBuilder.appendBoolean(false); histoBuilder.append(ExponentialHistogram.empty()); } } blocks[offset] = histoBuilder.build(); blocks[offset + 1] = seenBuilder.build(); } } public Block evaluateFinal(IntVector selected, DriverContext driverContext) { try (var builder = driverContext.blockFactory().newExponentialHistogramBlockBuilder(selected.getPositionCount());) { for (int i = 0; i < selected.getPositionCount(); i++) { int groupId = selected.getInt(i); ExponentialHistogramMerger state = getOrNull(groupId); if (state != null) { builder.append(state.get()); } else { builder.appendNull(); } } return builder.build(); } } @Override public void close() { for (int i = 0; i < states.size(); i++) { Releasables.close(states.get(i)); } Releasables.close(states); states = null; } @Override public void enableGroupIdTracking(SeenGroupIds seenGroupIds) { // noop - we handle the null states inside `toIntermediate` and `evaluateFinal` } } }
GroupingState
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_280.java
{ "start": 826, "end": 3981 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "select date(created_at)创建日期,\n" + "count(distinct task_id)整体维修创建量,\n" + "count(distinct case when order_type='客户预约'then task_id end)预约报修创建量,\n" + "count(distinct case when order_type='客户预约'then task_id end)/count(distinct task_id)预约维修创建比例,\n" + "count(distinct case when hour(created_at)>=9 and hour(created_at)<21 and order_type='客户预约'then task_id end)预约维修工作时间创建量,\n" + "count(case when hour(created_at)>=9 and hour(created_at)<21 and timestampdiff(MINUTE,created_at,assign_at)<=30 then task_id end)预约维修工作时间及时受理量,\n" + "count(case when hour(created_at)>=9 and hour(created_at)<21 and timestampdiff(MINUTE,created_at,assign_at)<=30 then task_id end)/count(distinct case when hour(created_at)>=9 and hour(created_at)<21 and order_type='客户预约'then task_id end)30分钟受理率(工作时间)\n" + "from basic_repair_tasks\n" + "where date(created_at)>='2019-03-01'\n" + "and date(created_at)<=date_sub(curdate(),interval 1 day)\n" + "group by date(created_at)"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT date(created_at) AS 创建日期, count(DISTINCT task_id) AS 整体维修创建量\n" + "\t, count(DISTINCT CASE\n" + "\t\tWHEN order_type = '客户预约' THEN task_id\n" + "\tEND) AS 预约报修创建量\n" + "\t, count(DISTINCT CASE\n" + "\t\tWHEN order_type = '客户预约' THEN task_id\n" + "\tEND) / count(DISTINCT task_id) AS 预约维修创建比例\n" + "\t, count(DISTINCT CASE\n" + "\t\tWHEN hour(created_at) >= 9\n" + "\t\t\tAND hour(created_at) < 21\n" + "\t\t\tAND order_type = '客户预约'\n" + "\t\tTHEN task_id\n" + "\tEND) AS 预约维修工作时间创建量\n" + "\t, count(CASE\n" + "\t\tWHEN hour(created_at) >= 9\n" + "\t\t\tAND hour(created_at) < 21\n" + "\t\t\tAND timestampdiff(MINUTE, created_at, assign_at) <= 30\n" + "\t\tTHEN task_id\n" + "\tEND) AS 预约维修工作时间及时受理量\n" + "\t, count(CASE\n" + "\t\tWHEN hour(created_at) >= 9\n" + "\t\t\tAND hour(created_at) < 21\n" + "\t\t\tAND timestampdiff(MINUTE, created_at, assign_at) <= 30\n" + "\t\tTHEN task_id\n" + "\tEND) / count(DISTINCT CASE\n" + "\t\tWHEN hour(created_at) >= 9\n" + "\t\t\tAND hour(created_at) < 21\n" + "\t\t\tAND order_type = '客户预约'\n" + "\t\tTHEN task_id\n" + "\tEND) AS 30分钟受理率(工作时间)\n" + "FROM basic_repair_tasks\n" + "WHERE date(created_at) >= '2019-03-01'\n" + "\tAND date(created_at) <= date_sub(curdate(), INTERVAL 1 DAY)\n" + "GROUP BY date(created_at)", stmt.toString()); } }
MySqlSelectTest_280
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 61538, "end": 61993 }
class ____ { static <@ImmutableTypeParameter T> void f() {} } """) .doTest(); } @Test public void immutableTypeParameterUsage_interface() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.ImmutableTypeParameter; @Immutable
T