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__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/component/properties/SpringPropertiesComponentFunctionTest.java
{ "start": 1238, "end": 2051 }
class ____ implements PropertiesFunction { @Override public String getName() { return "beer"; } @Override public String apply(String remainder) { return "mock:" + remainder.toLowerCase(); } } @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/component/properties/SpringPropertiesComponentFunctionTest.xml"); } @Test public void testFunction() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } }
MyFunction
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleRelatedComponentMapper.java
{ "start": 531, "end": 1526 }
class ____ extends AbstractMiddleComponentMapper { private final MiddleIdData relatedIdData; public MiddleRelatedComponentMapper(MiddleIdData relatedIdData) { this.relatedIdData = relatedIdData; } @Override public Object mapToObjectFromFullMap( EntityInstantiator entityInstantiator, Map<String, Object> data, Object dataObject, Number revision) { return entityInstantiator.createInstanceFromVersionsEntity( relatedIdData.getEntityName(), data, revision ); } @Override public void mapToMapFromObject( SharedSessionContractImplementor session, Map<String, Object> idData, Map<String, Object> data, Object obj) { relatedIdData.getPrefixedMapper().mapToMapFromEntity( idData, obj ); } @Override public void addMiddleEqualToQuery( Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { relatedIdData.getPrefixedMapper().addIdsEqualToQuery( parameters, idPrefix1, idPrefix2 ); } }
MiddleRelatedComponentMapper
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/Project.java
{ "start": 1347, "end": 4271 }
class ____ extends UnaryPlan implements Streaming, SortAgnostic { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(LogicalPlan.class, "Project", Project::new); private final List<? extends NamedExpression> projections; public Project(Source source, LogicalPlan child, List<? extends NamedExpression> projections) { super(source, child); this.projections = projections; assert validateProjections(projections); } private boolean validateProjections(List<? extends NamedExpression> projections) { for (NamedExpression ne : projections) { if (ne instanceof Alias as) { if (as.child() instanceof Attribute == false) { return false; } } else if (ne instanceof Attribute == false && ne instanceof UnresolvedNamedExpression == false) { return false; } } return true; } private Project(StreamInput in) throws IOException { this( Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(LogicalPlan.class), in.readNamedWriteableCollectionAsList(NamedExpression.class) ); } @Override public void writeTo(StreamOutput out) throws IOException { Source.EMPTY.writeTo(out); out.writeNamedWriteable(child()); out.writeNamedWriteableCollection(projections()); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected NodeInfo<Project> info() { return NodeInfo.create(this, Project::new, child(), projections); } @Override public Project replaceChild(LogicalPlan newChild) { return new Project(source(), newChild, projections); } public List<? extends NamedExpression> projections() { return projections; } public Project withProjections(List<? extends NamedExpression> projections) { return new Project(source(), child(), projections); } @Override public boolean resolved() { return super.resolved() && Expressions.anyMatch(projections, Functions::isAggregate) == false; } @Override public boolean expressionsResolved() { return Resolvables.resolved(projections); } @Override public List<Attribute> output() { return Expressions.asAttributes(projections); } @Override public int hashCode() { return Objects.hash(projections, child()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Project other = (Project) obj; return Objects.equals(projections, other.projections) && Objects.equals(child(), other.child()); } }
Project
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/Constants.java
{ "start": 12620, "end": 12971 }
class ____ the constant definitions * @param namePrefix prefix of the searched constant names * @param value the looked up constant value */ public ConstantException(String className, String namePrefix, Object value) { super("No '" + namePrefix + "' field with value '" + value + "' found in class [" + className + "]"); } } }
containing
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexHHH18771ListInitializerTest.java
{ "start": 2026, "end": 3213 }
class ____ { @Id private Long id; @OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = CascadeType.ALL) @OrderColumn(name = "order_id") @ListIndexBase(100) private List<Phone> phones = new ArrayList<>(); @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name = "parent_child_relationships", joinColumns = @JoinColumn(name = "parent_id"), inverseJoinColumns = @JoinColumn(name = "child_id")) @OrderColumn(name = "pos") @ListIndexBase(200) private List<Person> children = new ArrayList<>(); @ManyToOne @JoinColumn(name = "mother_id") private Person mother; public Person() { } public Person(Long id) { this.id = id; } public List<Phone> getPhones() { return phones; } public void addPhone(Phone phone) { phones.add( phone ); phone.setPerson( this ); } public List<Person> getChildren() { return children; } public Person getMother() { return mother; } public void setMother(Person mother) { this.mother = mother; } public void removePhone(Phone phone) { phones.remove( phone ); phone.setPerson( null ); } } @Entity(name = "Phone") public static
Person
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
{ "start": 86133, "end": 86678 }
class ____ implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerDiagnosticsUpdateEvent updateEvent = (ContainerDiagnosticsUpdateEvent) event; container.addDiagnostics(updateEvent.getDiagnosticsUpdate() + "\n"); } } /** * Transitions upon receiving PAUSE_CONTAINER. * - RUNNING -> PAUSING */ @SuppressWarnings("unchecked") // dispatcher not typed static
ContainerDiagnosticsUpdateTransition
java
elastic__elasticsearch
distribution/tools/windows-service-cli/src/main/java/org/elasticsearch/windows/service/WindowsServiceStopCommand.java
{ "start": 565, "end": 1085 }
class ____ extends ProcrunCommand { WindowsServiceStopCommand() { super("Stops the Elasticsearch Windows Service", "SS"); } @Override protected String getSuccessMessage(String serviceId) { return String.format(java.util.Locale.ROOT, "The service '%s' has been stopped", serviceId); } @Override protected String getFailureMessage(String serviceId) { return String.format(java.util.Locale.ROOT, "Failed stopping '%s' service", serviceId); } }
WindowsServiceStopCommand
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java
{ "start": 8397, "end": 10157 }
class ____ that includes the designated * files and archives. */ public synchronized ClassLoader makeClassLoader(final ClassLoader parent) throws MalformedURLException { if (classLoaderCreated != null) { throw new IllegalStateException("A classloader was already created"); } final URL[] urls = new URL[localClasspaths.size()]; for (int i = 0; i < localClasspaths.size(); ++i) { urls[i] = new File(localClasspaths.get(i)).toURI().toURL(); LOG.info(urls[i].toString()); } return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { classLoaderCreated = new URLClassLoader(urls, parent); return classLoaderCreated; } }); } public synchronized void close() throws IOException { if(classLoaderCreated != null) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { try { classLoaderCreated.close(); classLoaderCreated = null; } catch (IOException e) { LOG.warn("Failed to close classloader created " + "by LocalDistributedCacheManager"); } return null; } }); } for (File symlink : symlinksCreated) { if (!symlink.delete()) { LOG.warn("Failed to delete symlink created by the local job runner: " + symlink); } } FileContext localFSFileContext = FileContext.getLocalFSFileContext(); for (String archive : localArchives) { localFSFileContext.delete(new Path(archive), true); } for (String file : localFiles) { localFSFileContext.delete(new Path(file), true); } } }
loader
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddbstream/Ddb2StreamComponent.java
{ "start": 1130, "end": 3057 }
class ____ extends HealthCheckComponent { @Metadata private Ddb2StreamConfiguration configuration = new Ddb2StreamConfiguration(); public Ddb2StreamComponent() { this(null); } public Ddb2StreamComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { if (remaining == null || remaining.isBlank()) { throw new IllegalArgumentException("Table name must be specified."); } Ddb2StreamConfiguration configuration = this.configuration != null ? this.configuration.copy() : new Ddb2StreamConfiguration(); configuration.setTableName(remaining); Ddb2StreamEndpoint endpoint = new Ddb2StreamEndpoint(uri, configuration, this); setProperties(endpoint, parameters); if (Boolean.FALSE.equals(configuration.isUseDefaultCredentialsProvider()) && Boolean.FALSE.equals(configuration.isUseProfileCredentialsProvider()) && Boolean.FALSE.equals(configuration.isUseSessionCredentials()) && configuration.getAmazonDynamoDbStreamsClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException( "useDefaultCredentialsProvider is set to false, useProfileCredentialsProvider is set to false, useSessionCredentials is set to false, amazonDDBStreamsClient or accessKey and secretKey must be specified"); } return endpoint; } public Ddb2StreamConfiguration getConfiguration() { return configuration; } /** * The component configuration */ public void setConfiguration(Ddb2StreamConfiguration configuration) { this.configuration = configuration; } }
Ddb2StreamComponent
java
google__guava
guava/src/com/google/common/util/concurrent/AbstractFutureState.java
{ "start": 13590, "end": 17482 }
class ____ loaded * before the ATOMIC_HELPER. Apparently this is possible on some android platforms. */ Waiter(boolean unused) {} Waiter() { // avoid volatile write, write is made visible by subsequent CAS on waitersField field putThread(this, Thread.currentThread()); } // non-volatile write to the next field. Should be made visible by a subsequent CAS on // waitersField. void setNext(@Nullable Waiter next) { putNext(this, next); } void unpark() { // This is racy with removeWaiter. The consequence of the race is that we may spuriously call // unpark even though the thread has already removed itself from the list. But even if we did // use a CAS, that race would still exist (it would just be ever so slightly smaller). Thread w = thread; if (w != null) { thread = null; LockSupport.unpark(w); } } } /* * Now that we've initialized everything else, we can run the initialization code for * ATOMIC_HELPER. That initialization code may log after we assign to ATOMIC_HELPER. */ private static final AtomicHelper ATOMIC_HELPER; static { AtomicHelper helper; Throwable thrownUnsafeFailure = null; Throwable thrownAtomicReferenceFieldUpdaterFailure = null; helper = VarHandleAtomicHelperMaker.INSTANCE.tryMakeVarHandleAtomicHelper(); if (helper == null) { try { helper = new UnsafeAtomicHelper(); } catch (Exception | Error unsafeFailure) { // sneaky checked exception thrownUnsafeFailure = unsafeFailure; // Catch absolutely everything and fall through to AtomicReferenceFieldUpdaterAtomicHelper. try { helper = new AtomicReferenceFieldUpdaterAtomicHelper(); } catch (Exception // sneaky checked exception | Error atomicReferenceFieldUpdaterFailure) { // Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause // getDeclaredField to throw a NoSuchFieldException when the field is definitely there. // For these users fallback to a suboptimal implementation, based on synchronized. This // will be a definite performance hit to those users. thrownAtomicReferenceFieldUpdaterFailure = atomicReferenceFieldUpdaterFailure; helper = new SynchronizedHelper(); } } } ATOMIC_HELPER = helper; // Prevent rare disastrous classloading in first call to LockSupport.park. // See: https://bugs.openjdk.org/browse/JDK-8074773 @SuppressWarnings("unused") Class<?> ensureLoaded = LockSupport.class; // Log after all static init is finished; if an installed logger uses any Futures methods, it // shouldn't break in cases where reflection is missing/broken. if (thrownAtomicReferenceFieldUpdaterFailure != null) { log.get().log(SEVERE, "UnsafeAtomicHelper is broken!", thrownUnsafeFailure); log.get() .log( SEVERE, "AtomicReferenceFieldUpdaterAtomicHelper is broken!", thrownAtomicReferenceFieldUpdaterFailure); } } // TODO(lukes): Investigate using a @Contended annotation on these fields once one is available. /* * The following fields are package-private, even though we intend never to use them outside this * file. If they were instead private, then we wouldn't be able to access them reflectively from * within VarHandleAtomicHelper and AtomicReferenceFieldUpdaterAtomicHelper. * * Package-private "shouldn't" be necessary: The *AtomicHelper classes and AbstractFutureState * "should" be nestmates, so a call to MethodHandles.lookup or * AtomicReferenceFieldUpdater.newUpdater inside *AtomicHelper "should" have access to * AbstractFutureState's private fields. However, our open-source build uses `-source 8 -target * 8`, so the
is
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java
{ "start": 32679, "end": 32797 }
class ____ extends ExternalMessageProvider<EmailMessage, EmailSearchConditions> { } public static
EmailMessageProvider
java
apache__flink
flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/operations/OperationUtilsTest.java
{ "start": 1002, "end": 2430 }
class ____ { @Test void testSimpleIndent() { String sourceQuery = "SELECT * FROM source_t"; String s = String.format( "SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery)); assertThat(s) .isEqualTo("SELECT * FROM (\n" + " SELECT * FROM source_t\n" + ") WHERE a > 5"); } @Test void testIndentChildWithLiteralWithNewline() { String sourceQuery = "SELECT *, '\n' FROM source_t"; String s = String.format( "SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery)); assertThat(s) .isEqualTo( "SELECT * FROM (\n" + " SELECT *, '\n' FROM source_t\n" + ") WHERE a > 5"); } @Test void testIndentChildWithEscapedQuotes() { String sourceQuery = "SELECT *, '',\n'' FROM source_t"; String s = String.format( "SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery)); assertThat(s) .isEqualTo( "SELECT * FROM (\n" + " SELECT *, '',\n" + " '' FROM source_t\n" + ") WHERE a > 5"); } }
OperationUtilsTest
java
quarkusio__quarkus
extensions/cache/deployment/src/test/java/io/quarkus/cache/test/runtime/CacheKeyGeneratorTest.java
{ "start": 3400, "end": 4924 }
class ____ { private static final String CACHE_NAME = "test-cache"; // This method is used to test a CDI injection into a cache key generator. public String getCauliflower() { return CAULIFLOWER; } @CacheResult(cacheName = CACHE_NAME, keyGenerator = SingletonKeyGen.class) public String cachedMethod1(/* Key element */ Object param0, /* Not used */ Integer param1) { return new String(); } @CacheResult(cacheName = CACHE_NAME, keyGenerator = DependentKeyGen.class) public BigInteger cachedMethod2() { return BigInteger.valueOf(new SecureRandom().nextInt()); } // The cache key elements will vary depending on which annotation is evaluated during the interception. @CacheInvalidate(cacheName = CACHE_NAME, keyGenerator = RequestScopedKeyGen.class) @CacheInvalidate(cacheName = CACHE_NAME) public void invalidate1(@CacheKey String param0, Object param1) { } @CacheResult(cacheName = CACHE_NAME, keyGenerator = ApplicationScopedKeyGen.class) public Object cachedMethod3(/* Not used */ Object param0, /* Not used */ String param1) { return new Object(); } @CacheInvalidate(cacheName = CACHE_NAME, keyGenerator = NotABeanKeyGen.class) public void invalidate2(/* Key element */ String param0, /* Not used */ Long param1, /* Key element */ String param2) { } } @Singleton public static
CachedService
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesServiceAccountsEndpointBuilderFactory.java
{ "start": 21267, "end": 21679 }
class ____ extends AbstractEndpointBuilder implements KubernetesServiceAccountsEndpointBuilder, AdvancedKubernetesServiceAccountsEndpointBuilder { public KubernetesServiceAccountsEndpointBuilderImpl(String path) { super(componentName, path); } } return new KubernetesServiceAccountsEndpointBuilderImpl(path); } }
KubernetesServiceAccountsEndpointBuilderImpl
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/cuckoo/ReactiveCuckooCommands.java
{ "start": 653, "end": 7452 }
interface ____<K, V> extends ReactiveRedisCommands { /** * Execute the command <a href="https://redis.io/commands/cf.add">CF.ADD</a>. * Summary: Adds the specified element to the specified Cuckoo filter. * Group: cuckoo * <p> * If the cuckoo filter does not exist, it creates a new one. * * @param key the key * @param value the value, must not be {@code null} * @return a uni producing {@code null} when the operation completes **/ Uni<Void> cfadd(K key, V value); /** * Execute the command <a href="https://redis.io/commands/cf.addnx">CF.ADDNX</a>. * Summary: Adds an item to a cuckoo filter if the item did not exist previously. * Group: cuckoo * <p> * If the cuckoo filter does not exist, it creates a new one. * * @param key the key * @param value the value, must not be {@code null} * @return a Uni producing {@code true} if the value was added to the filter, {@code false} otherwise **/ Uni<Boolean> cfaddnx(K key, V value); /** * Execute the command <a href="https://redis.io/commands/cf.count">CF.COUNT</a>. * Summary: Returns the number of times an item may be in the filter. Because this is a probabilistic data structure, * this may not necessarily be accurate. * Group: cuckoo * <p> * * @param key the key * @param value the value, must not be {@code null} * @return a Uni producing the count of possible matching copies of the value in the filter **/ Uni<Long> cfcount(K key, V value); /** * Execute the command <a href="https://redis.io/commands/cf.del">CF.DEL</a>. * Summary: Deletes an item once from the filter. If the item exists only once, it will be removed from the filter. * If the item was added multiple times, it will still be present. * Group: cuckoo * <p> * * @param key the key * @param value the value, must not be {@code null} * @return a Uni producing {@code true} if the value was removed from the filter, {@code false} otherwise * (the value was not found in the filter) **/ Uni<Boolean> cfdel(K key, V value); /** * Execute the command <a href="https://redis.io/commands/cf.exists">CF.EXISTS</a>. * Summary: Check if an item exists in a Cuckoo filter * Group: cuckoo * <p> * * @param key the key * @param value the value, must not be {@code null} * @return a Uni producing {@code true} if the value was found in the filter, {@code false} otherwise. **/ Uni<Boolean> cfexists(K key, V value); /** * Execute the command <a href="https://redis.io/commands/cf.insert">CF.INSERT</a>. * Summary: Adds one or more items to a cuckoo filter, allowing the filter to be created with a custom capacity if * it does not exist yet. * Group: cuckoo * <p> * * @param key the key * @param values the values, must not be {@code null}, must not be empty, must not contain {@code null} * @return a uni producing {@code null} when the operation completes **/ Uni<Void> cfinsert(K key, V... values); /** * Execute the command <a href="https://redis.io/commands/cf.insert">CF.INSERT</a>. * Summary: Adds one or more items to a cuckoo filter, allowing the filter to be created with a custom capacity if * it does not exist yet. * Group: cuckoo * <p> * * @param key the key * @param args the extra arguments * @param values the values, must not be {@code null}, must not be empty, must not contain {@code null} * @return a uni producing {@code null} when the operation completes **/ Uni<Void> cfinsert(K key, CfInsertArgs args, V... values); /** * Execute the command <a href="https://redis.io/commands/cf.insertnx">CF.INSERTNX</a>. * Summary: Adds one or more items to a cuckoo filter, allowing the filter to be created with a custom capacity if * it does not exist yet. * Group: cuckoo * <p> * * @param key the key * @param values the values, must not be {@code null}, must not be empty, must not contain {@code null} * @return a uni producing a list of boolean. For each added value, the corresponding boolean is {@code true} if the * value has been added (non-existing) or {@code false} if the value was already present in the filter. **/ Uni<List<Boolean>> cfinsertnx(K key, V... values); /** * Execute the command <a href="https://redis.io/commands/cf.insertnx">CF.INSERTNX</a>. * Summary: Adds one or more items to a cuckoo filter, allowing the filter to be created with a custom capacity if * it does not exist yet. * Group: cuckoo * <p> * * @param key the key * @param args the extra arguments * @param values the values, must not be {@code null}, must not be empty, must not contain {@code null} * @return a uni producing a list of boolean. For each added value, the corresponding boolean is {@code true} if the * value has been added (non-existing) or {@code false} if the value was already present in the filter. **/ Uni<List<Boolean>> cfinsertnx(K key, CfInsertArgs args, V... values); /** * Execute the command <a href="https://redis.io/commands/cf.mexists">CF.MEXISTS</a>. * Summary: Check if an item exists in a Cuckoo filter * Group: cuckoo * <p> * * @param key the key * @param values the values, must not be {@code null}, must not contain {@code null}, must not be empty * @return a uni producing a list of boolean indicating, for each corresponding value, if the value exists in the * filter or not. **/ Uni<List<Boolean>> cfmexists(K key, V... values); /** * Execute the command <a href="https://redis.io/commands/cf.reserve">CF.RESERVE</a>. * Summary: Create a Cuckoo Filter as key with a single sub-filter for the initial amount of capacity for items. * Group: cuckoo * <p> * * @param key the key * @param capacity the capacity * @return a uni producing {@code null} when the operation completes **/ Uni<Void> cfreserve(K key, long capacity); /** * Execute the command <a href="https://redis.io/commands/cf.reserve">CF.RESERVE</a>. * Summary: Create a Cuckoo Filter as key with a single sub-filter for the initial amount of capacity for items. * Group: cuckoo * <p> * * @param key the key * @param capacity the capacity * @param args the extra parameters * @return a uni producing {@code null} when the operation completes **/ Uni<Void> cfreserve(K key, long capacity, CfReserveArgs args); }
ReactiveCuckooCommands
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/SpringExtensionParameterizedTests.java
{ "start": 1732, "end": 2471 }
class ____ { @ParameterizedTest @ValueSource(strings = { "Dilbert", "Wally" }) void people(String name, @Autowired List<Person> people) { assertThat(people.stream().map(Person::getName).filter(name::equals)).hasSize(1); } @ParameterizedTest @CsvSource("dogbert, Dogbert") void dogs(String beanName, String dogName, ApplicationContext context) { assertThat(context.getBean(beanName, Dog.class)).extracting(Dog::getName).isEqualTo(dogName); } @ParameterizedTest @CsvSource({ "garfield, Garfield", "catbert, Catbert" }) void cats(String beanName, String catName, ApplicationContext context) { assertThat(context.getBean(beanName, Cat.class)).extracting(Cat::getName).isEqualTo(catName); } }
SpringExtensionParameterizedTests
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/DockerComposeFileTests.java
{ "start": 1229, "end": 5611 }
class ____ { @TempDir @SuppressWarnings("NullAway.Init") File temp; @Test void hashCodeAndEquals() throws Exception { File f1 = new File(this.temp, "compose.yml"); File f2 = new File(this.temp, "docker-compose.yml"); FileCopyUtils.copy(new byte[0], f1); FileCopyUtils.copy(new byte[0], f2); DockerComposeFile c1 = DockerComposeFile.of(f1); DockerComposeFile c2 = DockerComposeFile.of(f1); DockerComposeFile c3 = DockerComposeFile.find(f1.getParentFile()); DockerComposeFile c4 = DockerComposeFile.of(f2); assertThat(c1).hasSameHashCodeAs(c2).hasSameHashCodeAs(c3); assertThat(c1).isEqualTo(c1).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c4); } @Test void toStringReturnsFileName() throws Exception { DockerComposeFile composeFile = createComposeFile("compose.yml"); assertThat(composeFile.toString()).endsWith(File.separator + "compose.yml"); } @Test void toStringReturnsFileNameList() throws Exception { File file1 = createTempFile("1.yml"); File file2 = createTempFile("2.yml"); DockerComposeFile composeFile = DockerComposeFile.of(List.of(file1, file2)); assertThat(composeFile).hasToString(file1 + ", " + file2); } @Test void findFindsSingleFile() throws Exception { File file = new File(this.temp, "docker-compose.yml").getCanonicalFile(); FileCopyUtils.copy(new byte[0], file); DockerComposeFile composeFile = DockerComposeFile.find(file.getParentFile()); assertThat(composeFile).isNotNull(); assertThat(composeFile.getFiles()).containsExactly(file); } @Test void findWhenMultipleFilesPicksBest() throws Exception { File f1 = new File(this.temp, "docker-compose.yml").getCanonicalFile(); FileCopyUtils.copy(new byte[0], f1); File f2 = new File(this.temp, "compose.yml").getCanonicalFile(); FileCopyUtils.copy(new byte[0], f2); DockerComposeFile composeFile = DockerComposeFile.find(f1.getParentFile()); assertThat(composeFile).isNotNull(); assertThat(composeFile.getFiles()).containsExactly(f2); } @Test void findWhenNoComposeFilesReturnsNull() throws Exception { File file = new File(this.temp, "not-a-compose.yml"); FileCopyUtils.copy(new byte[0], file); DockerComposeFile composeFile = DockerComposeFile.find(file.getParentFile()); assertThat(composeFile).isNull(); } @Test void findWhenWorkingDirectoryDoesNotExistReturnsNull() { File directory = new File(this.temp, "missing"); DockerComposeFile composeFile = DockerComposeFile.find(directory); assertThat(composeFile).isNull(); } @Test void findWhenWorkingDirectoryIsNotDirectoryThrowsException() throws Exception { File file = createTempFile("iamafile"); assertThatIllegalStateException().isThrownBy(() -> DockerComposeFile.find(file)) .withMessageEndingWith("is not a directory"); } @Test void ofReturnsDockerComposeFile() throws Exception { File file = createTempFile("compose.yml"); DockerComposeFile composeFile = DockerComposeFile.of(file); assertThat(composeFile).isNotNull(); assertThat(composeFile.getFiles()).containsExactly(file); } @Test void ofWithMultipleFilesReturnsDockerComposeFile() throws Exception { File file1 = createTempFile("1.yml"); File file2 = createTempFile("2.yml"); DockerComposeFile composeFile = DockerComposeFile.of(List.of(file1, file2)); assertThat(composeFile).isNotNull(); assertThat(composeFile.getFiles()).containsExactly(file1, file2); } @Test @SuppressWarnings("NullAway") // Test null check void ofWhenFileIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> DockerComposeFile.of((File) null)) .withMessage("'file' must not be null"); } @Test void ofWhenFileDoesNotExistThrowsException() { File file = new File(this.temp, "missing"); assertThatIllegalArgumentException().isThrownBy(() -> DockerComposeFile.of(file)) .withMessageEndingWith("must exist"); } @Test void ofWhenFileIsNotFileThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> DockerComposeFile.of(this.temp)) .withMessageEndingWith("must be a normal file"); } private DockerComposeFile createComposeFile(String name) throws IOException { return DockerComposeFile.of(createTempFile(name)); } private File createTempFile(String name) throws IOException { File file = new File(this.temp, name); FileCopyUtils.copy(new byte[0], file); return file.getCanonicalFile(); } }
DockerComposeFileTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/internal/ResultMementoEntityJpa.java
{ "start": 1011, "end": 4027 }
class ____ implements ResultMementoEntity, FetchMemento.Parent { private final NavigablePath navigablePath; private final EntityMappingType entityDescriptor; private final LockMode lockMode; private final FetchMementoBasic discriminatorMemento; private final Map<String, FetchMemento> explicitFetchMementoMap; public ResultMementoEntityJpa( EntityMappingType entityDescriptor, LockMode lockMode, FetchMementoBasic discriminatorMemento, Map<String, FetchMemento> explicitFetchMementoMap) { this.navigablePath = new NavigablePath( entityDescriptor.getEntityName() ); this.entityDescriptor = entityDescriptor; this.lockMode = lockMode; this.discriminatorMemento = discriminatorMemento; this.explicitFetchMementoMap = explicitFetchMementoMap; } @Override public NavigablePath getNavigablePath() { return navigablePath; } @Override public ResultBuilderEntityValued resolve( Consumer<String> querySpaceConsumer, ResultSetMappingResolutionContext context) { final HashMap<Fetchable, FetchBuilder> explicitFetchBuilderMap = new HashMap<>(); // If there are no explicit fetches, we don't register DELAYED // builders to get implicit fetching of all basic fetchables if ( !explicitFetchMementoMap.isEmpty() ) { explicitFetchMementoMap.forEach( (relativePath, fetchMemento) -> explicitFetchBuilderMap.put( (Fetchable) entityDescriptor.findByPath( relativePath ), fetchMemento.resolve( this, querySpaceConsumer, context ) ) ); final boolean isEnhancedForLazyLoading = entityDescriptor.getRepresentationStrategy().isBytecodeEnhanced(); // Implicit basic fetches are DELAYED by default, so register // fetch builders for the remaining basic fetchables entityDescriptor.forEachAttributeMapping( attributeMapping -> { final var basicPart = attributeMapping.asBasicValuedModelPart(); if ( basicPart != null ) { explicitFetchBuilderMap.computeIfAbsent( attributeMapping, k -> new DelayedFetchBuilderBasicPart( navigablePath.append( k.getFetchableName() ), basicPart, isEnhancedForLazyLoading ) ); } } ); } return new CompleteResultBuilderEntityJpa( navigablePath, entityDescriptor, lockMode, discriminatorFetchBuilder( querySpaceConsumer, context ), explicitFetchBuilderMap ); } private FetchBuilderBasicValued discriminatorFetchBuilder( Consumer<String> querySpaceConsumer, ResultSetMappingResolutionContext context) { final var discriminatorMapping = entityDescriptor.getDiscriminatorMapping(); if ( discriminatorMapping == null || !entityDescriptor.hasSubclasses() ) { assert discriminatorMemento == null; return null; } else { return discriminatorMemento == null ? new ImplicitFetchBuilderBasic( navigablePath, discriminatorMapping ) : (FetchBuilderBasicValued) discriminatorMemento.resolve( this, querySpaceConsumer, context ); } } }
ResultMementoEntityJpa
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java
{ "start": 1212, "end": 2617 }
class ____ implements PropertySourceLoader { private static final String XML_FILE_EXTENSION = ".xml"; @Override public String[] getFileExtensions() { return new String[] { "properties", "xml" }; } @Override public List<PropertySource<?>> load(String name, Resource resource) throws IOException { List<Map<String, ?>> properties = loadProperties(resource); if (properties.isEmpty()) { return Collections.emptyList(); } List<PropertySource<?>> propertySources = new ArrayList<>(properties.size()); for (int i = 0; i < properties.size(); i++) { String documentNumber = (properties.size() != 1) ? " (document #" + i + ")" : ""; propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber, Collections.unmodifiableMap(properties.get(i)), true)); } return propertySources; } @SuppressWarnings({ "unchecked", "rawtypes" }) private List<Map<String, ?>> loadProperties(Resource resource) throws IOException { String filename = resource.getFilename(); List<Map<String, ?>> result = new ArrayList<>(); if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { result.add((Map) PropertiesLoaderUtils.loadProperties(resource)); } else { List<Document> documents = new OriginTrackedPropertiesLoader(resource).load(); documents.forEach((document) -> result.add(document.asMap())); } return result; } }
PropertiesPropertySourceLoader
java
apache__camel
components/camel-sql/src/generated/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java
{ "start": 230, "end": 392 }
class ____ extends Error { /** * The version identifier for this Serializable class. * Increment only if the <i>serialized</i> form of the *
TokenMgrError
java
mapstruct__mapstruct
integrationtest/src/test/resources/superTypeGenerationTest/usage/src/main/java/org/mapstruct/itest/supertypegeneration/usage/AnotherOrderMapper.java
{ "start": 337, "end": 519 }
class ____ { public static final AnotherOrderMapper INSTANCE = Mappers.getMapper( AnotherOrderMapper.class ); public abstract OrderDto orderToDto(Order order); }
AnotherOrderMapper
java
quarkusio__quarkus
extensions/qute/runtime/src/main/java/io/quarkus/qute/runtime/TemplateProducer.java
{ "start": 5807, "end": 10682 }
class ____ implements Template { private final String path; private final TemplateVariants variants; private final Engine engine; // Some methods may only work if a single template variant is found private final LazyValue<Template> unambiguousTemplate; private final RenderedResults renderedResults; InjectableTemplate(String path, Map<String, TemplateVariants> templateVariants, Engine engine, RenderedResults renderedResults) { this.path = path; this.variants = templateVariants.get(path); this.engine = engine; if (variants == null || variants.variantToTemplate.size() == 1) { unambiguousTemplate = new LazyValue<>(new Supplier<Template>() { @Override public Template get() { String id = variants != null ? variants.defaultTemplate : path; return engine.getTemplate(id); } }); } else { unambiguousTemplate = null; } this.renderedResults = renderedResults; } @Override public SectionNode getRootNode() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getRootNode(); } throw ambiguousTemplates("getRootNode()"); } @Override public Optional<URI> getSource() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getSource(); } throw ambiguousTemplates("getSource()"); } @Override public TemplateInstance instance() { TemplateInstance instance = new InjectableTemplateInstanceImpl(); return renderedResults != null ? new ResultsCollectingTemplateInstance(instance, renderedResults) : instance; } @Override public List<Expression> getExpressions() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getExpressions(); } throw ambiguousTemplates("getExpressions()"); } @Override public Expression findExpression(Predicate<Expression> predicate) { if (unambiguousTemplate != null) { return unambiguousTemplate.get().findExpression(predicate); } throw ambiguousTemplates("findExpression()"); } @Override public List<ParameterDeclaration> getParameterDeclarations() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getParameterDeclarations(); } throw ambiguousTemplates("getParameterDeclarations()"); } @Override public String getGeneratedId() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getGeneratedId(); } throw ambiguousTemplates("getGeneratedId()"); } @Override public Optional<Variant> getVariant() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getVariant(); } throw ambiguousTemplates("getVariant()"); } @Override public String getId() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getId(); } throw ambiguousTemplates("getId()"); } @Override public Fragment getFragment(String identifier) { return new InjectableFragment(identifier); } @Override public Set<String> getFragmentIds() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getFragmentIds(); } throw ambiguousTemplates("getFragmentIds()"); } @Override public List<TemplateNode> getNodes() { if (unambiguousTemplate != null) { return unambiguousTemplate.get().getNodes(); } throw ambiguousTemplates("getNodes()"); } @Override public Collection<TemplateNode> findNodes(Predicate<TemplateNode> predicate) { if (unambiguousTemplate != null) { return unambiguousTemplate.get().findNodes(predicate); } throw ambiguousTemplates("findNodes()"); } private UnsupportedOperationException ambiguousTemplates(String method) { return new UnsupportedOperationException("Ambiguous injected templates do not support " + method); } @Override public String toString() { return "Injectable template [path=" + path + "]"; }
InjectableTemplate
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/contracts/services/AzureServiceErrorCode.java
{ "start": 1230, "end": 6680 }
enum ____ { FILE_SYSTEM_ALREADY_EXISTS("FilesystemAlreadyExists", HttpURLConnection.HTTP_CONFLICT, null), PATH_ALREADY_EXISTS("PathAlreadyExists", HttpURLConnection.HTTP_CONFLICT, null), BLOB_ALREADY_EXISTS("BlobAlreadyExists", HttpURLConnection.HTTP_CONFLICT, null), INTERNAL_OPERATION_ABORT("InternalOperationAbortError", HttpURLConnection.HTTP_CONFLICT, null), PATH_CONFLICT("PathConflict", HttpURLConnection.HTTP_CONFLICT, null), FILE_SYSTEM_NOT_FOUND("FilesystemNotFound", HttpURLConnection.HTTP_NOT_FOUND, null), PATH_NOT_FOUND("PathNotFound", HttpURLConnection.HTTP_NOT_FOUND, null), BLOB_PATH_NOT_FOUND("BlobNotFound", HttpURLConnection.HTTP_NOT_FOUND, null), PRE_CONDITION_FAILED("PreconditionFailed", HttpURLConnection.HTTP_PRECON_FAILED, null), SOURCE_PATH_NOT_FOUND("SourcePathNotFound", HttpURLConnection.HTTP_NOT_FOUND, null), INVALID_SOURCE_OR_DESTINATION_RESOURCE_TYPE("InvalidSourceOrDestinationResourceType", HttpURLConnection.HTTP_CONFLICT, null), RENAME_DESTINATION_PARENT_PATH_NOT_FOUND("RenameDestinationParentPathNotFound", HttpURLConnection.HTTP_NOT_FOUND, null), INVALID_RENAME_SOURCE_PATH("InvalidRenameSourcePath", HttpURLConnection.HTTP_CONFLICT, null), NON_EMPTY_DIRECTORY_DELETE("DirectoryNotEmpty", HttpURLConnection.HTTP_CONFLICT, "The recursive query parameter value must be true to delete a non-empty directory"), INGRESS_OVER_ACCOUNT_LIMIT("ServerBusy", HttpURLConnection.HTTP_UNAVAILABLE, "Ingress is over the account limit."), EGRESS_OVER_ACCOUNT_LIMIT("ServerBusy", HttpURLConnection.HTTP_UNAVAILABLE, "Egress is over the account limit."), TPS_OVER_ACCOUNT_LIMIT("ServerBusy", HttpURLConnection.HTTP_UNAVAILABLE, "Operations per second is over the account limit."), OTHER_SERVER_THROTTLING("ServerBusy", HttpURLConnection.HTTP_UNAVAILABLE, "The server is currently unable to receive requests. Please retry your request."), INVALID_QUERY_PARAMETER_VALUE("InvalidQueryParameterValue", HttpURLConnection.HTTP_BAD_REQUEST, null), AUTHORIZATION_PERMISSION_MISS_MATCH("AuthorizationPermissionMismatch", HttpURLConnection.HTTP_FORBIDDEN, null), ACCOUNT_REQUIRES_HTTPS("AccountRequiresHttps", HttpURLConnection.HTTP_BAD_REQUEST, null), MD5_MISMATCH("Md5Mismatch", HttpURLConnection.HTTP_BAD_REQUEST, "The MD5 value specified in the request did not match with the MD5 value calculated by the server."), COPY_BLOB_FAILED("CopyBlobFailed", HttpURLConnection.HTTP_INTERNAL_ERROR, null), COPY_BLOB_ABORTED("CopyBlobAborted", HttpURLConnection.HTTP_INTERNAL_ERROR, null), BLOB_OPERATION_NOT_SUPPORTED("BlobOperationNotSupported", HttpURLConnection.HTTP_CONFLICT, null), INVALID_APPEND_OPERATION("InvalidAppendOperation", HttpURLConnection.HTTP_CONFLICT, null), UNAUTHORIZED_BLOB_OVERWRITE("UnauthorizedBlobOverwrite", HttpURLConnection.HTTP_FORBIDDEN, "This request is not authorized to perform blob overwrites."), UNKNOWN(null, -1, null); private final String errorCode; private final int httpStatusCode; private final String errorMessage; private static final Logger LOG1 = LoggerFactory.getLogger(AzureServiceErrorCode.class); AzureServiceErrorCode(String errorCode, int httpStatusCodes, String errorMessage) { this.errorCode = errorCode; this.httpStatusCode = httpStatusCodes; this.errorMessage = errorMessage; } public int getStatusCode() { return this.httpStatusCode; } public String getErrorCode() { return this.errorCode; } public String getErrorMessage() { return this.errorMessage; } public static List<AzureServiceErrorCode> getAzureServiceCode(int httpStatusCode) { List<AzureServiceErrorCode> errorCodes = new ArrayList<>(); if (httpStatusCode == UNKNOWN.httpStatusCode) { errorCodes.add(UNKNOWN); return errorCodes; } for (AzureServiceErrorCode azureServiceErrorCode : AzureServiceErrorCode.values()) { if (azureServiceErrorCode.httpStatusCode == httpStatusCode) { errorCodes.add(azureServiceErrorCode); } } return errorCodes; } public static AzureServiceErrorCode getAzureServiceCode(int httpStatusCode, String errorCode) { if (errorCode == null || errorCode.isEmpty() || httpStatusCode == UNKNOWN.httpStatusCode) { return UNKNOWN; } for (AzureServiceErrorCode azureServiceErrorCode : AzureServiceErrorCode.values()) { if (errorCode.equalsIgnoreCase(azureServiceErrorCode.errorCode) && azureServiceErrorCode.httpStatusCode == httpStatusCode) { return azureServiceErrorCode; } } return UNKNOWN; } public static AzureServiceErrorCode getAzureServiceCode(int httpStatusCode, String errorCode, final String errorMessage) { if (errorCode == null || errorCode.isEmpty() || httpStatusCode == UNKNOWN.httpStatusCode || errorMessage == null || errorMessage.isEmpty()) { return UNKNOWN; } String[] errorMessages = errorMessage.split(System.lineSeparator(), 2); for (AzureServiceErrorCode azureServiceErrorCode : AzureServiceErrorCode.values()) { if (azureServiceErrorCode.getStatusCode() == httpStatusCode && azureServiceErrorCode.getErrorCode().equalsIgnoreCase(errorCode) && azureServiceErrorCode.getErrorMessage() .equalsIgnoreCase(errorMessages[0])) { return azureServiceErrorCode; } } return UNKNOWN; } }
AzureServiceErrorCode
java
apache__camel
components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/spring/FhirJsonDataFormatSpringTest.java
{ "start": 1574, "end": 3663 }
class ____ extends CamelSpringTestSupport { private static final String PATIENT = "{\"resourceType\":\"Patient\"," + "\"name\":[{\"family\":\"Holmes\",\"given\":[\"Sherlock\"]}]," + "\"address\":[{\"line\":[\"221b Baker St, Marylebone, London NW1 6XE, UK\"]}]}"; private MockEndpoint mockEndpoint; @Override public void doPostSetup() { mockEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); } @Test public void unmarshal() throws Exception { mockEndpoint.expectedMessageCount(1); template.sendBody("direct:unmarshal", PATIENT); mockEndpoint.assertIsSatisfied(); Exchange exchange = mockEndpoint.getExchanges().get(0); Patient patient = (Patient) exchange.getIn().getBody(); assertTrue(patient.equalsDeep(getPatient()), "Patients should be equal!"); } @Test public void marshal() throws Exception { mockEndpoint.expectedMessageCount(1); Patient patient = getPatient(); template.sendBody("direct:marshal", patient); mockEndpoint.assertIsSatisfied(); Exchange exchange = mockEndpoint.getExchanges().get(0); InputStream inputStream = exchange.getIn().getBody(InputStream.class); IBaseResource iBaseResource = FhirContext.forR4().newJsonParser().parseResource(new InputStreamReader(inputStream)); assertTrue(patient.equalsDeep((Base) iBaseResource), "Patients should be equal!"); } private Patient getPatient() { Patient patient = new Patient(); patient.addName(new HumanName().addGiven("Sherlock").setFamily("Holmes")) .addAddress(new Address().addLine("221b Baker St, Marylebone, London NW1 6XE, UK")); return patient; } @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/dataformat/fhir/json/FhirJsonDataFormatSpringTest.xml"); } }
FhirJsonDataFormatSpringTest
java
spring-projects__spring-security
saml2/saml2-service-provider/src/opensaml5Test/java/org/springframework/security/saml2/provider/service/registration/OpenSaml5AssertingPartyMetadataRepositoryTests.java
{ "start": 16202, "end": 16830 }
class ____ extends Dispatcher { private final MockResponse head = new MockResponse(); private final Map<String, MockResponse> responses = new ConcurrentHashMap<>(); private MetadataDispatcher() { } @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if ("HEAD".equals(request.getMethod())) { return this.head; } return this.responses.get(request.getPath()); } private MetadataDispatcher addResponse(String path, String body) { this.responses.put(path, new MockResponse().setBody(body).setResponseCode(200)); return this; } } }
MetadataDispatcher
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/cache/NoCacheOnMethodsTest.java
{ "start": 819, "end": 2395 }
class ____ { @RegisterExtension static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest() .addScanCustomizer(new Consumer<ResteasyReactiveDeploymentManager.ScanStep>() { @Override public void accept(ResteasyReactiveDeploymentManager.ScanStep scanStep) { scanStep.addMethodScanner(new CacheControlScanner()); } }) .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(ResourceWithNoCache.class); } }); @Test public void testWithFields() { RestAssured.get("/test/withFields") .then() .statusCode(200) .body(equalTo("withFields")) .header("Cache-Control", "no-cache=\"f1\", no-cache=\"f2\""); } @Test public void testWithoutFields() { RestAssured.get("/test/withoutFields") .then() .statusCode(200) .body(equalTo("withoutFields")) .header("Cache-Control", "no-cache"); } @Test public void testWithoutAnnotation() { RestAssured.get("/test/withoutAnnotation") .then() .statusCode(200) .body(equalTo("withoutAnnotation")) .header("Cache-Control", nullValue()); } @Path("test") public static
NoCacheOnMethodsTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_areEqual_Test.java
{ "start": 11058, "end": 11371 }
class ____ { private final Object other; NonSymmetric(Object other) { this.other = other; } @Override public boolean equals(Object obj) { return obj == other; } @Override public String toString() { return "non symmetric"; } } private static
NonSymmetric
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 4663, "end": 5080 }
class ____ { private final Override override = null; } """) .doTest(); } @Test public void enumsDefaultToImmutable() { compilationHelper .addSourceLines( "Test.java", """ import javax.lang.model.element.ElementKind; import com.google.errorprone.annotations.Immutable; @Immutable
Test
java
square__javapoet
src/main/java/com/squareup/javapoet/TypeSpec.java
{ "start": 1680, "end": 13722 }
class ____ { public final Kind kind; public final String name; public final CodeBlock anonymousTypeArguments; public final CodeBlock javadoc; public final List<AnnotationSpec> annotations; public final Set<Modifier> modifiers; public final List<TypeVariableName> typeVariables; public final TypeName superclass; public final List<TypeName> superinterfaces; public final Map<String, TypeSpec> enumConstants; public final List<FieldSpec> fieldSpecs; public final CodeBlock staticBlock; public final CodeBlock initializerBlock; public final List<MethodSpec> methodSpecs; public final List<TypeSpec> typeSpecs; final Set<String> nestedTypesSimpleNames; public final List<Element> originatingElements; public final Set<String> alwaysQualifiedNames; private TypeSpec(Builder builder) { this.kind = builder.kind; this.name = builder.name; this.anonymousTypeArguments = builder.anonymousTypeArguments; this.javadoc = builder.javadoc.build(); this.annotations = Util.immutableList(builder.annotations); this.modifiers = Util.immutableSet(builder.modifiers); this.typeVariables = Util.immutableList(builder.typeVariables); this.superclass = builder.superclass; this.superinterfaces = Util.immutableList(builder.superinterfaces); this.enumConstants = Util.immutableMap(builder.enumConstants); this.fieldSpecs = Util.immutableList(builder.fieldSpecs); this.staticBlock = builder.staticBlock.build(); this.initializerBlock = builder.initializerBlock.build(); this.methodSpecs = Util.immutableList(builder.methodSpecs); this.typeSpecs = Util.immutableList(builder.typeSpecs); this.alwaysQualifiedNames = Util.immutableSet(builder.alwaysQualifiedNames); nestedTypesSimpleNames = new HashSet<>(builder.typeSpecs.size()); List<Element> originatingElementsMutable = new ArrayList<>(); originatingElementsMutable.addAll(builder.originatingElements); for (TypeSpec typeSpec : builder.typeSpecs) { nestedTypesSimpleNames.add(typeSpec.name); originatingElementsMutable.addAll(typeSpec.originatingElements); } this.originatingElements = Util.immutableList(originatingElementsMutable); } /** * Creates a dummy type spec for type-resolution only (in CodeWriter) * while emitting the type declaration but before entering the type body. */ private TypeSpec(TypeSpec type) { assert type.anonymousTypeArguments == null; this.kind = type.kind; this.name = type.name; this.anonymousTypeArguments = null; this.javadoc = type.javadoc; this.annotations = Collections.emptyList(); this.modifiers = Collections.emptySet(); this.typeVariables = Collections.emptyList(); this.superclass = null; this.superinterfaces = Collections.emptyList(); this.enumConstants = Collections.emptyMap(); this.fieldSpecs = Collections.emptyList(); this.staticBlock = type.staticBlock; this.initializerBlock = type.initializerBlock; this.methodSpecs = Collections.emptyList(); this.typeSpecs = Collections.emptyList(); this.originatingElements = Collections.emptyList(); this.nestedTypesSimpleNames = Collections.emptySet(); this.alwaysQualifiedNames = Collections.emptySet(); } public boolean hasModifier(Modifier modifier) { return modifiers.contains(modifier); } public static Builder classBuilder(String name) { return new Builder(Kind.CLASS, checkNotNull(name, "name == null"), null); } public static Builder classBuilder(ClassName className) { return classBuilder(checkNotNull(className, "className == null").simpleName()); } public static Builder interfaceBuilder(String name) { return new Builder(Kind.INTERFACE, checkNotNull(name, "name == null"), null); } public static Builder interfaceBuilder(ClassName className) { return interfaceBuilder(checkNotNull(className, "className == null").simpleName()); } public static Builder enumBuilder(String name) { return new Builder(Kind.ENUM, checkNotNull(name, "name == null"), null); } public static Builder enumBuilder(ClassName className) { return enumBuilder(checkNotNull(className, "className == null").simpleName()); } public static Builder anonymousClassBuilder(String typeArgumentsFormat, Object... args) { return anonymousClassBuilder(CodeBlock.of(typeArgumentsFormat, args)); } public static Builder anonymousClassBuilder(CodeBlock typeArguments) { return new Builder(Kind.CLASS, null, typeArguments); } public static Builder annotationBuilder(String name) { return new Builder(Kind.ANNOTATION, checkNotNull(name, "name == null"), null); } public static Builder annotationBuilder(ClassName className) { return annotationBuilder(checkNotNull(className, "className == null").simpleName()); } public Builder toBuilder() { Builder builder = new Builder(kind, name, anonymousTypeArguments); builder.javadoc.add(javadoc); builder.annotations.addAll(annotations); builder.modifiers.addAll(modifiers); builder.typeVariables.addAll(typeVariables); builder.superclass = superclass; builder.superinterfaces.addAll(superinterfaces); builder.enumConstants.putAll(enumConstants); builder.fieldSpecs.addAll(fieldSpecs); builder.methodSpecs.addAll(methodSpecs); builder.typeSpecs.addAll(typeSpecs); builder.initializerBlock.add(initializerBlock); builder.staticBlock.add(staticBlock); builder.originatingElements.addAll(originatingElements); builder.alwaysQualifiedNames.addAll(alwaysQualifiedNames); return builder; } void emit(CodeWriter codeWriter, String enumName, Set<Modifier> implicitModifiers) throws IOException { // Nested classes interrupt wrapped line indentation. Stash the current wrapping state and put // it back afterwards when this type is complete. int previousStatementLine = codeWriter.statementLine; codeWriter.statementLine = -1; try { if (enumName != null) { codeWriter.emitJavadoc(javadoc); codeWriter.emitAnnotations(annotations, false); codeWriter.emit("$L", enumName); if (!anonymousTypeArguments.formatParts.isEmpty()) { codeWriter.emit("("); codeWriter.emit(anonymousTypeArguments); codeWriter.emit(")"); } if (fieldSpecs.isEmpty() && methodSpecs.isEmpty() && typeSpecs.isEmpty()) { return; // Avoid unnecessary braces "{}". } codeWriter.emit(" {\n"); } else if (anonymousTypeArguments != null) { TypeName supertype = !superinterfaces.isEmpty() ? superinterfaces.get(0) : superclass; codeWriter.emit("new $T(", supertype); codeWriter.emit(anonymousTypeArguments); codeWriter.emit(") {\n"); } else { // Push an empty type (specifically without nested types) for type-resolution. codeWriter.pushType(new TypeSpec(this)); codeWriter.emitJavadoc(javadoc); codeWriter.emitAnnotations(annotations, false); codeWriter.emitModifiers(modifiers, Util.union(implicitModifiers, kind.asMemberModifiers)); if (kind == Kind.ANNOTATION) { codeWriter.emit("$L $L", "@interface", name); } else { codeWriter.emit("$L $L", kind.name().toLowerCase(Locale.US), name); } codeWriter.emitTypeVariables(typeVariables); List<TypeName> extendsTypes; List<TypeName> implementsTypes; if (kind == Kind.INTERFACE) { extendsTypes = superinterfaces; implementsTypes = Collections.emptyList(); } else { extendsTypes = superclass.equals(ClassName.OBJECT) ? Collections.emptyList() : Collections.singletonList(superclass); implementsTypes = superinterfaces; } if (!extendsTypes.isEmpty()) { codeWriter.emit(" extends"); boolean firstType = true; for (TypeName type : extendsTypes) { if (!firstType) codeWriter.emit(","); codeWriter.emit(" $T", type); firstType = false; } } if (!implementsTypes.isEmpty()) { codeWriter.emit(" implements"); boolean firstType = true; for (TypeName type : implementsTypes) { if (!firstType) codeWriter.emit(","); codeWriter.emit(" $T", type); firstType = false; } } codeWriter.popType(); codeWriter.emit(" {\n"); } codeWriter.pushType(this); codeWriter.indent(); boolean firstMember = true; boolean needsSeparator = kind == Kind.ENUM && (!fieldSpecs.isEmpty() || !methodSpecs.isEmpty() || !typeSpecs.isEmpty()); for (Iterator<Map.Entry<String, TypeSpec>> i = enumConstants.entrySet().iterator(); i.hasNext(); ) { Map.Entry<String, TypeSpec> enumConstant = i.next(); if (!firstMember) codeWriter.emit("\n"); enumConstant.getValue().emit(codeWriter, enumConstant.getKey(), Collections.emptySet()); firstMember = false; if (i.hasNext()) { codeWriter.emit(",\n"); } else if (!needsSeparator) { codeWriter.emit("\n"); } } if (needsSeparator) codeWriter.emit(";\n"); // Static fields. for (FieldSpec fieldSpec : fieldSpecs) { if (!fieldSpec.hasModifier(Modifier.STATIC)) continue; if (!firstMember) codeWriter.emit("\n"); fieldSpec.emit(codeWriter, kind.implicitFieldModifiers); firstMember = false; } if (!staticBlock.isEmpty()) { if (!firstMember) codeWriter.emit("\n"); codeWriter.emit(staticBlock); firstMember = false; } // Non-static fields. for (FieldSpec fieldSpec : fieldSpecs) { if (fieldSpec.hasModifier(Modifier.STATIC)) continue; if (!firstMember) codeWriter.emit("\n"); fieldSpec.emit(codeWriter, kind.implicitFieldModifiers); firstMember = false; } // Initializer block. if (!initializerBlock.isEmpty()) { if (!firstMember) codeWriter.emit("\n"); codeWriter.emit(initializerBlock); firstMember = false; } // Constructors. for (MethodSpec methodSpec : methodSpecs) { if (!methodSpec.isConstructor()) continue; if (!firstMember) codeWriter.emit("\n"); methodSpec.emit(codeWriter, name, kind.implicitMethodModifiers); firstMember = false; } // Methods (static and non-static). for (MethodSpec methodSpec : methodSpecs) { if (methodSpec.isConstructor()) continue; if (!firstMember) codeWriter.emit("\n"); methodSpec.emit(codeWriter, name, kind.implicitMethodModifiers); firstMember = false; } // Types. for (TypeSpec typeSpec : typeSpecs) { if (!firstMember) codeWriter.emit("\n"); typeSpec.emit(codeWriter, null, kind.implicitTypeModifiers); firstMember = false; } codeWriter.unindent(); codeWriter.popType(); codeWriter.popTypeVariables(typeVariables); codeWriter.emit("}"); if (enumName == null && anonymousTypeArguments == null) { codeWriter.emit("\n"); // If this type isn't also a value, include a trailing newline. } } finally { codeWriter.statementLine = previousStatementLine; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; return toString().equals(o.toString()); } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { StringBuilder out = new StringBuilder(); try { CodeWriter codeWriter = new CodeWriter(out); emit(codeWriter, null, Collections.emptySet()); return out.toString(); } catch (IOException e) { throw new AssertionError(); } } public
TypeSpec
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingPhysicalSlotProvider.java
{ "start": 1885, "end": 7773 }
class ____ implements PhysicalSlotProvider { private final Map<SlotRequestId, PhysicalSlotRequest> requests; private final Map<SlotRequestId, CompletableFuture<TestingPhysicalSlot>> responses; private final Map<SlotRequestId, Throwable> cancellations; private final Function<ResourceProfile, CompletableFuture<TestingPhysicalSlot>> physicalSlotCreator; private boolean batchSlotRequestTimeoutCheckEnabled = true; public static TestingPhysicalSlotProvider create( Function<ResourceProfile, CompletableFuture<TestingPhysicalSlot>> physicalSlotCreator) { return new TestingPhysicalSlotProvider(physicalSlotCreator); } public static TestingPhysicalSlotProvider createWithInfiniteSlotCreation() { return create( (resourceProfile) -> CompletableFuture.completedFuture( new TestingPhysicalSlot(resourceProfile, new AllocationID()))); } public static TestingPhysicalSlotProvider createWithoutImmediatePhysicalSlotCreation() { return create((ignored) -> new CompletableFuture<>()); } public static TestingPhysicalSlotProvider createWithFailingPhysicalSlotCreation(Throwable t) { return create((ignored) -> FutureUtils.completedExceptionally(t)); } public static TestingPhysicalSlotProvider createWithLimitedAmountOfPhysicalSlots( int slotCount) { return createWithLimitedAmountOfPhysicalSlots( slotCount, new SimpleAckingTaskManagerGateway()); } public static TestingPhysicalSlotProvider createWithLimitedAmountOfPhysicalSlots( int slotCount, TaskManagerGateway taskManagerGateway) { AtomicInteger availableSlotCount = new AtomicInteger(slotCount); return create( (resourceProfile) -> { int count = availableSlotCount.getAndDecrement(); if (count > 0) { return CompletableFuture.completedFuture( TestingPhysicalSlot.builder() .withResourceProfile(resourceProfile) .withTaskManagerGateway(taskManagerGateway) .build()); } else { return FutureUtils.completedExceptionally( new NoResourceAvailableException( String.format( "The limit of %d provided slots was reached. No available slots can be provided.", slotCount))); } }); } private TestingPhysicalSlotProvider( Function<ResourceProfile, CompletableFuture<TestingPhysicalSlot>> physicalSlotCreator) { this.physicalSlotCreator = physicalSlotCreator; this.requests = new HashMap<>(); this.responses = new HashMap<>(); this.cancellations = new HashMap<>(); } @Override public Map<SlotRequestId, CompletableFuture<PhysicalSlotRequest.Result>> allocatePhysicalSlots( Collection<PhysicalSlotRequest> physicalSlotRequests) { Map<SlotRequestId, CompletableFuture<PhysicalSlotRequest.Result>> result = new HashMap<>(physicalSlotRequests.size()); for (PhysicalSlotRequest physicalSlotRequest : physicalSlotRequests) { SlotRequestId slotRequestId = physicalSlotRequest.getSlotRequestId(); requests.put(slotRequestId, physicalSlotRequest); final CompletableFuture<TestingPhysicalSlot> resultFuture = physicalSlotCreator.apply( physicalSlotRequest.getSlotProfile().getPhysicalSlotResourceProfile()); responses.put(slotRequestId, resultFuture); CompletableFuture<PhysicalSlotRequest.Result> physicalSlotFuture = resultFuture.thenApply( physicalSlot -> new PhysicalSlotRequest.Result(slotRequestId, physicalSlot)); result.put(slotRequestId, physicalSlotFuture); } return result; } @Override public void cancelSlotRequest(SlotRequestId slotRequestId, Throwable cause) { cancellations.put(slotRequestId, cause); } @Override public void disableBatchSlotRequestTimeoutCheck() { batchSlotRequestTimeoutCheckEnabled = false; } public CompletableFuture<TestingPhysicalSlot> getResultForRequestId( SlotRequestId slotRequestId) { return getResponses().get(slotRequestId); } PhysicalSlotRequest getFirstRequestOrFail() { return getFirstElementOrFail(requests.values()); } public void awaitAllSlotRequests() { getResponses().values().forEach(CompletableFuture::join); } public Map<SlotRequestId, PhysicalSlotRequest> getRequests() { return Collections.unmodifiableMap(requests); } public CompletableFuture<TestingPhysicalSlot> getFirstResponseOrFail() { return getFirstElementOrFail(responses.values()); } public Map<SlotRequestId, CompletableFuture<TestingPhysicalSlot>> getResponses() { return Collections.unmodifiableMap(responses); } public Map<SlotRequestId, Throwable> getCancellations() { return Collections.unmodifiableMap(cancellations); } private static <T> T getFirstElementOrFail(Collection<T> collection) { Optional<T> element = collection.stream().findFirst(); Preconditions.checkState(element.isPresent()); return element.get(); } boolean isBatchSlotRequestTimeoutCheckEnabled() { return batchSlotRequestTimeoutCheckEnabled; } }
TestingPhysicalSlotProvider
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/StructuredLogLayoutTests.java
{ "start": 5966, "end": 6161 }
class ____ implements StructuredLogFormatter<LogEvent> { @Override public String format(LogEvent event) { return "custom-format"; } } static final
CustomLog4j2StructuredLoggingFormatter
java
quarkusio__quarkus
integration-tests/opentelemetry-jdbc-instrumentation/src/test/java/io/quarkus/it/opentelemetry/H2DatabaseTestResource.java
{ "start": 221, "end": 1813 }
class ____ implements QuarkusTestResourceLifecycleManager { public static final String QUARKUS_OTEL_SDK_DISABLED = "quarkus.otel.sdk.disabled"; private Server tcpServer; private Map<String, String> initProperties; @Override public void init(Map<String, String> initArgs) { initProperties = initArgs; } @Override public Map<String, String> start() { try { tcpServer = Server.createTcpServer("-ifNotExists"); tcpServer.start(); System.out.println("[INFO] H2 database started in TCP server mode; server status: " + tcpServer.getStatus()); } catch (SQLException e) { throw new RuntimeException(e); } Map<String, String> properties = new HashMap<>(initProperties); properties.put("quarkus.datasource.h2.jdbc.url", "jdbc:h2:tcp://localhost/mem:test"); properties.put("quarkus.hibernate-orm.h2.schema-management.strategy", "drop-and-create"); properties.put("quarkus.hibernate-orm.postgresql.active", "false"); properties.put("quarkus.hibernate-orm.oracle.active", "false"); properties.put("quarkus.hibernate-orm.mariadb.active", "false"); properties.put("quarkus.hibernate-orm.db2.active", "false"); return properties; } @Override public synchronized void stop() { if (tcpServer != null) { tcpServer.stop(); System.out.println("[INFO] H2 database was shut down; server status: " + tcpServer.getStatus()); tcpServer = null; } } }
H2DatabaseTestResource
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/IfNullTypeStrategy.java
{ "start": 1575, "end": 2439 }
class ____ implements TypeStrategy { @Override public Optional<DataType> inferType(CallContext callContext) { final List<DataType> argumentDataTypes = callContext.getArgumentDataTypes(); final DataType inputDataType = argumentDataTypes.get(0); final DataType nullReplacementDataType = argumentDataTypes.get(1); if (!inputDataType.getLogicalType().isNullable()) { return Optional.of(inputDataType); } return LogicalTypeMerging.findCommonType( Arrays.asList( inputDataType.getLogicalType(), nullReplacementDataType.getLogicalType())) .map(t -> t.copy(nullReplacementDataType.getLogicalType().isNullable())) .map(TypeConversions::fromLogicalToDataType); } }
IfNullTypeStrategy
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/sample/ClassWithNestedRepository.java
{ "start": 908, "end": 978 }
interface ____ extends Repository<User, Integer> {} }
NestedUserRepository
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/boot/model/Cloneable.java
{ "start": 225, "end": 387 }
interface ____<T> { /** * Creates a new, deep-copied instance of this object * @return a deep-copy clone of the referenced object */ T deepCopy(); }
Cloneable
java
quarkusio__quarkus
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/RedirectHandler.java
{ "start": 361, "end": 628 }
interface ____ { int DEFAULT_PRIORITY = 5000; URI handle(Response response); default int getPriority() { return Optional.ofNullable(this.getClass().getAnnotation(Priority.class)).map(Priority::value).orElse(DEFAULT_PRIORITY); } }
RedirectHandler
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/http/impl/HttpClientRequestBaseTest.java
{ "start": 656, "end": 2008 }
class ____ extends HttpTestBase { @Test public void testPathCacheAndQueryCache() { server.requestHandler(req -> {}); server.listen(testAddress).onComplete(onSuccess(server -> { client.request(new RequestOptions(requestOptions).setURI("/?")).onComplete(onSuccess(req -> { assertThat(req.getURI(), is("/?")); assertThat(req.path(), is("/")); assertThat(req.query(), is("")); req.setURI("/index.html"); assertThat(req.getURI(), is("/index.html")); assertThat(req.path(), is("/index.html")); assertThat(req.query(), is(nullValue())); req.setURI("/foo?bar"); assertThat(req.getURI(), is("/foo?bar")); assertThat(req.path(), is("/foo")); assertThat(req.query(), is("bar")); req.setURI("/baz?key=value"); assertThat(req.getURI(), is("/baz?key=value")); assertThat(req.path(), is("/baz")); assertThat(req.query(), is("key=value")); req.setURI(""); assertThat(req.getURI(), is("")); assertThat(req.path(), is("")); assertThat(req.query(), is(nullValue())); req.setURI("?"); assertThat(req.getURI(), is("?")); assertThat(req.path(), is("")); assertThat(req.query(), is("")); testComplete(); })); })); await(); } }
HttpClientRequestBaseTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/ExecutionConfig.java
{ "start": 21355, "end": 22233 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; /** * Convert UserConfig into a {@code Map<String, String>} representation. This can be used by * the runtime, for example for presenting the user config in the web frontend. * * @return Key/Value representation of the UserConfig */ public Map<String, String> toMap() { return Collections.emptyMap(); } @Override public boolean equals(Object obj) { if (obj == null || this.getClass() != obj.getClass()) { return false; } return true; } @Override public int hashCode() { return Objects.hash(); } } /** Configuration settings for the closure cleaner. */ public
GlobalJobParameters
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java
{ "start": 7339, "end": 7818 }
class ____ { static final String MY_COOL_PATTERN = "a+"; public static void myPopularStaticMethod() { Pattern somePattern = Pattern.compile(MY_COOL_PATTERN); Matcher m = somePattern.matcher("aaaaab"); } } """) .addOutputLines( "in/Test.java", """ import java.util.regex.Matcher; import java.util.regex.Pattern;
Test
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/writer/BeanDefinitionWriter.java
{ "start": 249345, "end": 250010 }
interface ____ { /** * The builder. * * @param statements The statements * @param self The self * @param parameters The parameters * @param values The constructor values * @return The built instance */ ExpressionDef build(List<StatementDef> statements, VariableDef.This self, List<VariableDef.MethodParameter> parameters, List<? extends ExpressionDef> values); } /** * Data used when visiting method. */ @Internal public static final
CustomInitializerBuilder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/SecureRandomUtils.java
{ "start": 666, "end": 1544 }
class ____ { private SecureRandomUtils() {} /** * Returns a cryptographically secure Base64 encoded {@link SecureString} of {@code numBytes} random bytes. */ public static SecureString getBase64SecureRandomString(int numBytes) { byte[] randomBytes = null; byte[] encodedBytes = null; try { randomBytes = new byte[numBytes]; SecureRandomHolder.INSTANCE.nextBytes(randomBytes); encodedBytes = Base64.getUrlEncoder().withoutPadding().encode(randomBytes); return new SecureString(CharArrays.utf8BytesToChars(encodedBytes)); } finally { if (randomBytes != null) { Arrays.fill(randomBytes, (byte) 0); } if (encodedBytes != null) { Arrays.fill(encodedBytes, (byte) 0); } } } }
SecureRandomUtils
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/operator/topn/ResultBuilderForBytesRef.java
{ "start": 606, "end": 2368 }
class ____ implements ResultBuilder { private final BytesRefBlock.Builder builder; private final boolean inKey; private final TopNEncoder encoder; private final BytesRef scratch = new BytesRef(); /** * The value previously set by {@link #decodeKey}. */ private BytesRef key; ResultBuilderForBytesRef(BlockFactory blockFactory, TopNEncoder encoder, boolean inKey, int initialSize) { this.encoder = encoder; this.inKey = inKey; this.builder = blockFactory.newBytesRefBlockBuilder(initialSize); } @Override public void decodeKey(BytesRef keys) { assert inKey; key = encoder.toSortable().decodeBytesRef(keys, scratch); } @Override public void decodeValue(BytesRef values) { int count = TopNEncoder.DEFAULT_UNSORTABLE.decodeVInt(values); switch (count) { case 0 -> { builder.appendNull(); } case 1 -> builder.appendBytesRef(inKey ? key : readValueFromValues(values)); default -> { builder.beginPositionEntry(); for (int i = 0; i < count; i++) { builder.appendBytesRef(readValueFromValues(values)); } builder.endPositionEntry(); } } } private BytesRef readValueFromValues(BytesRef values) { return encoder.toUnsortable().decodeBytesRef(values, scratch); } @Override public BytesRefBlock build() { return builder.build(); } @Override public String toString() { return "ResultBuilderForBytesRef[inKey=" + inKey + "]"; } @Override public void close() { builder.close(); } }
ResultBuilderForBytesRef
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/crypto/key/TestValueQueue.java
{ "start": 2251, "end": 13156 }
class ____ implements QueueRefiller<String> { final LinkedBlockingQueue<FillInfo> fillCalls = new LinkedBlockingQueue<FillInfo>(); @Override public void fillQueueForKey(String keyName, Queue<String> keyQueue, int numValues) throws IOException { fillCalls.add(new FillInfo(numValues, keyName)); for(int i = 0; i < numValues; i++) { keyQueue.add("test"); } } public FillInfo getTop() throws InterruptedException { return fillCalls.poll(500, TimeUnit.MILLISECONDS); } } private void waitForRefill(ValueQueue<?> valueQueue, String queueName, int queueSize) throws TimeoutException, InterruptedException { GenericTestUtils.waitFor(() -> { int size = valueQueue.getSize(queueName); if (size != queueSize) { LOG.info("Current ValueQueue size is " + size); return false; } return true; }, 100, 3000); } /** * Verifies that Queue is initially filled to "numInitValues" */ @Test @Timeout(value = 30) public void testInitFill() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(10, 0.1f, 30000, 1, SyncGenerationPolicy.ALL, filler); assertEquals("test", vq.getNext("k1")); assertEquals(1, filler.getTop().num); vq.shutdown(); } /** * Verifies that Queue is initialized (Warmed-up) for provided keys */ @Test @Timeout(value = 30) public void testWarmUp() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(10, 0.5f, 30000, 1, SyncGenerationPolicy.ALL, filler); vq.initializeQueuesForKeys("k1", "k2", "k3"); FillInfo[] fillInfos = {filler.getTop(), filler.getTop(), filler.getTop()}; assertEquals(5, fillInfos[0].num); assertEquals(5, fillInfos[1].num); assertEquals(5, fillInfos[2].num); assertEquals(new HashSet<>(Arrays.asList("k1", "k2", "k3")), new HashSet<>(Arrays.asList(fillInfos[0].key, fillInfos[1].key, fillInfos[2].key))); vq.shutdown(); } /** * Verifies that Queue is initialized (Warmed-up) for partial keys. */ @Test @Timeout(value = 30) public void testPartialWarmUp() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<>(10, 0.5f, 30000, 1, SyncGenerationPolicy.ALL, filler); @SuppressWarnings("unchecked") LoadingCache<String, LinkedBlockingQueue<KeyProviderCryptoExtension.EncryptedKeyVersion>> kq = (LoadingCache<String, LinkedBlockingQueue<KeyProviderCryptoExtension.EncryptedKeyVersion>>) FieldUtils.getField(ValueQueue.class, "keyQueues", true).get(vq); LoadingCache<String, LinkedBlockingQueue<KeyProviderCryptoExtension.EncryptedKeyVersion>> kqSpy = spy(kq); doThrow(new ExecutionException(new Exception())).when(kqSpy).get("k2"); FieldUtils.writeField(vq, "keyQueues", kqSpy, true); assertThrows(IOException.class, () -> vq.initializeQueuesForKeys("k1", "k2", "k3")); verify(kqSpy, times(1)).get("k2"); FillInfo[] fillInfos = {filler.getTop(), filler.getTop(), filler.getTop()}; assertEquals(5, fillInfos[0].num); assertEquals(5, fillInfos[1].num); assertNull(fillInfos[2]); assertEquals(new HashSet<>(Arrays.asList("k1", "k3")), new HashSet<>(Arrays.asList(fillInfos[0].key, fillInfos[1].key))); vq.shutdown(); } /** * Verifies that the refill task is executed after "checkInterval" if * num values below "lowWatermark" */ @Test @Timeout(value = 30) public void testRefill() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(100, 0.1f, 30000, 1, SyncGenerationPolicy.ALL, filler); // Trigger a prefill (10) and an async refill (91) assertEquals("test", vq.getNext("k1")); assertEquals(10, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 100); // Refill task should add 91 values to get to a full queue (10 produced by // the prefill to the low watermark, 1 consumed by getNext()) assertEquals(91, filler.getTop().num); vq.shutdown(); } /** * Verifies that the No refill Happens after "checkInterval" if * num values above "lowWatermark" */ @Test @Timeout(value = 30) public void testNoRefill() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(10, 0.5f, 30000, 1, SyncGenerationPolicy.ALL, filler); // Trigger a prefill (5) and an async refill (6) assertEquals("test", vq.getNext("k1")); assertEquals(5, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 6 values to get to a full queue (5 produced by // the prefill to the low watermark, 1 consumed by getNext()) assertEquals(6, filler.getTop().num); // Take another value, queue is still above the watermark assertEquals("test", vq.getNext("k1")); // Wait a while to make sure that no async refills are triggered try { waitForRefill(vq, "k1", 10); } catch (TimeoutException ignored) { // This is the correct outcome - no refill is expected } assertEquals(null, filler.getTop()); vq.shutdown(); } /** * Verify getAtMost when SyncGeneration Policy = ALL */ @Test @Timeout(value = 30) public void testGetAtMostPolicyALL() throws Exception { MockFiller filler = new MockFiller(); final ValueQueue<String> vq = new ValueQueue<String>(10, 0.1f, 30000, 1, SyncGenerationPolicy.ALL, filler); // Trigger a prefill (1) and an async refill (10) assertEquals("test", vq.getNext("k1")); assertEquals(1, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 10 values to get to a full queue (1 produced by // the prefill to the low watermark, 1 consumed by getNext()) assertEquals(10, filler.getTop().num); // Drain completely, no further refills triggered vq.drain("k1"); // Wait a while to make sure that no async refills are triggered try { waitForRefill(vq, "k1", 10); } catch (TimeoutException ignored) { // This is the correct outcome - no refill is expected } assertNull(filler.getTop()); // Synchronous call: // 1. Synchronously fill returned list // 2. Start another async task to fill the queue in the cache assertEquals(10, vq.getAtMost("k1", 10).size(), "Failed in sync call."); assertEquals(10, filler.getTop().num, "Sync call filler got wrong number."); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 10 values to get to a full queue assertEquals(10, filler.getTop().num, "Failed in async call."); // Drain completely after filled by the async thread vq.drain("k1"); assertEquals(0, vq.getSize("k1"), "Failed to drain completely after async."); // Synchronous call assertEquals(19, vq.getAtMost("k1", 19).size(), "Failed to get all 19."); assertEquals(19, filler.getTop().num, "Failed in sync call."); vq.shutdown(); } /** * Verify getAtMost when SyncGeneration Policy = ALL */ @Test @Timeout(value = 30) public void testgetAtMostPolicyATLEAST_ONE() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(10, 0.3f, 30000, 1, SyncGenerationPolicy.ATLEAST_ONE, filler); // Trigger a prefill (3) and an async refill (8) assertEquals("test", vq.getNext("k1")); assertEquals(3, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 8 values to get to a full queue (3 produced by // the prefill to the low watermark, 1 consumed by getNext()) assertEquals(8, filler.getTop().num, "Failed in async call."); // Drain completely, no further refills triggered vq.drain("k1"); // Queue is empty, sync will return a single value and trigger a refill assertEquals(1, vq.getAtMost("k1", 10).size()); assertEquals(1, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 10 values to get to a full queue assertEquals(10, filler.getTop().num, "Failed in async call."); vq.shutdown(); } /** * Verify getAtMost when SyncGeneration Policy = LOW_WATERMARK */ @Test @Timeout(value = 30) public void testgetAtMostPolicyLOW_WATERMARK() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(10, 0.3f, 30000, 1, SyncGenerationPolicy.LOW_WATERMARK, filler); // Trigger a prefill (3) and an async refill (8) assertEquals("test", vq.getNext("k1")); assertEquals(3, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 8 values to get to a full queue (3 produced by // the prefill to the low watermark, 1 consumed by getNext()) assertEquals(8, filler.getTop().num, "Failed in async call."); // Drain completely, no further refills triggered vq.drain("k1"); // Queue is empty, sync will return 3 values and trigger a refill assertEquals(3, vq.getAtMost("k1", 10).size()); assertEquals(3, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 10 values to get to a full queue assertEquals(10, filler.getTop().num, "Failed in async call."); vq.shutdown(); } @Test @Timeout(value = 30) public void testDrain() throws Exception { MockFiller filler = new MockFiller(); ValueQueue<String> vq = new ValueQueue<String>(10, 0.1f, 30000, 1, SyncGenerationPolicy.ALL, filler); // Trigger a prefill (1) and an async refill (10) assertEquals("test", vq.getNext("k1")); assertEquals(1, filler.getTop().num); // Wait for the async task to finish waitForRefill(vq, "k1", 10); // Refill task should add 10 values to get to a full queue (1 produced by // the prefill to the low watermark, 1 consumed by getNext()) assertEquals(10, filler.getTop().num); // Drain completely, no further refills triggered vq.drain("k1"); // Wait a while to make sure that no async refills are triggered try { waitForRefill(vq, "k1", 10); } catch (TimeoutException ignored) { // This is the correct outcome - no refill is expected } assertNull(filler.getTop()); vq.shutdown(); } }
MockFiller
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/connector/sink2/CommitterInitContext.java
{ "start": 1059, "end": 1233 }
interface ____ extends InitContext { /** * @return The metric group this committer belongs to. */ SinkCommitterMetricGroup metricGroup(); }
CommitterInitContext
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/boot/model/Bindable.java
{ "start": 233, "end": 294 }
interface ____<T> { /** * Builds the specified binded
Bindable
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_516/Target.java
{ "start": 285, "end": 675 }
class ____ { private List<String> elements; public List<String> getElements() { return elements; } public void setElements(List<String> elements) { this.elements = elements; } public void addElement(String element) { if ( elements == null ) { elements = new ArrayList<>(); } elements.add( element ); } }
Target
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java
{ "start": 27473, "end": 28425 }
class ____ { private final StructKind kind; private final List<String> names; private final List<RelDataType> types; private final boolean nullable; Key(StructKind kind, List<String> names, List<RelDataType> types, boolean nullable) { this.kind = kind; this.names = names; this.types = types; this.nullable = nullable; } @Override public int hashCode() { return Objects.hash(kind, names, types, nullable); } @Override public boolean equals(@Nullable Object obj) { return obj == this || obj instanceof Key && kind == ((Key) obj).kind && names.equals(((Key) obj).names) && types.equals(((Key) obj).types) && nullable == ((Key) obj).nullable; } } }
Key
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/BlockingHttpClient.java
{ "start": 1033, "end": 1229 }
interface ____ features a subset of the operations provided by {@link HttpClient} and * is designed primarily for testing purposes. * * @author Graeme Rocher * @since 1.0 */ @Blocking public
that
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/ServerListener.java
{ "start": 800, "end": 1369 }
interface ____ { /** * Called upon the establishment of a new client connection. * * @param transport the new transport to be observed. * @return a listener for stream creation events on the transport. */ ServerTransportListener transportCreated(ServerTransport transport); /** * The server is shutting down. No new transports will be processed, but existing transports may * continue. Shutdown is only caused by a call to {@link InternalServer#shutdown()}. All * resources have been released. */ void serverShutdown(); }
ServerListener
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/aggregate/DoubleValueSum.java
{ "start": 1171, "end": 2434 }
class ____ implements ValueAggregator<String> { double sum = 0; /** * The default constructor * */ public DoubleValueSum() { reset(); } /** * add a value to the aggregator * * @param val * an object whose string representation represents a double value. * */ public void addNextValue(Object val) { this.sum += Double.parseDouble(val.toString()); } /** * add a value to the aggregator * * @param val * a double value. * */ public void addNextValue(double val) { this.sum += val; } /** * @return the string representation of the aggregated value */ public String getReport() { return "" + sum; } /** * @return the aggregated value */ public double getSum() { return this.sum; } /** * reset the aggregator */ public void reset() { sum = 0; } /** * @return return an array of one element. The element is a string * representation of the aggregated value. The return value is * expected to be used by the a combiner. */ public ArrayList<String> getCombinerOutput() { ArrayList<String> retv = new ArrayList<String>(1); retv.add("" + sum); return retv; } }
DoubleValueSum
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/reverse/erroneous/SourceTargetMapperAmbiguous2.java
{ "start": 515, "end": 1500 }
interface ____ { SourceTargetMapperAmbiguous2 INSTANCE = Mappers.getMapper( SourceTargetMapperAmbiguous2.class ); @Mappings({ @Mapping(target = "stringPropY", source = "stringPropX"), @Mapping(target = "integerPropY", source = "integerPropX"), @Mapping(target = "propertyNotToIgnoreUpstream", source = "propertyToIgnoreDownstream") }) Target forward(Source source); @Mappings({ @Mapping(target = "stringPropY", source = "stringPropX"), @Mapping(target = "integerPropY", source = "integerPropX"), @Mapping(target = "propertyNotToIgnoreUpstream", source = "propertyToIgnoreDownstream") }) Target forwardNotToReverse(Source source); @InheritInverseConfiguration(name = "blah") @Mappings({ @Mapping(target = "someConstantDownstream", constant = "test"), @Mapping(target = "propertyToIgnoreDownstream", ignore = true) }) Source reverse(Target target); }
SourceTargetMapperAmbiguous2
java
apache__flink
flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/metadata/SavepointMetadataV2.java
{ "start": 1690, "end": 5984 }
class ____ { private final long checkpointId; private final int maxParallelism; private final Collection<MasterState> masterStates; private final Map<OperatorID, OperatorStateSpecV2> operatorStateIndex; public SavepointMetadataV2( long checkpointId, int maxParallelism, Collection<MasterState> masterStates, Collection<OperatorState> initialStates) { Preconditions.checkArgument( maxParallelism > 0 && maxParallelism <= UPPER_BOUND_MAX_PARALLELISM, "Maximum parallelism must be between 1 and " + UPPER_BOUND_MAX_PARALLELISM + ". Found: " + maxParallelism); Preconditions.checkNotNull(masterStates); this.checkpointId = checkpointId; this.maxParallelism = maxParallelism; this.masterStates = new ArrayList<>(masterStates); this.operatorStateIndex = CollectionUtil.newHashMapWithExpectedSize(initialStates.size()); initialStates.forEach( existingState -> operatorStateIndex.put( existingState.getOperatorID(), OperatorStateSpecV2.existing(existingState))); } public long getCheckpointId() { return checkpointId; } public int getMaxParallelism() { return maxParallelism; } public Collection<MasterState> getMasterStates() { return masterStates; } /** * @return Operator state for the given UID. * @throws IOException If the savepoint does not contain operator state with the given uid. */ public OperatorState getOperatorState(OperatorIdentifier identifier) throws IOException { OperatorID operatorID = identifier.getOperatorId(); OperatorStateSpecV2 operatorState = operatorStateIndex.get(operatorID); if (operatorState == null || operatorState.isNewStateTransformation()) { throw new IOException( "Savepoint does not contain state with operator " + identifier .getUid() .map(uid -> "uid " + uid) .orElse("hash " + operatorID.toHexString())); } return operatorState.asExistingState(); } public void removeOperator(OperatorIdentifier identifier) { operatorStateIndex.remove(identifier.getOperatorId()); } public void addOperator( OperatorIdentifier identifier, StateBootstrapTransformation<?> transformation) { OperatorID id = identifier.getOperatorId(); if (operatorStateIndex.containsKey(id)) { throw new IllegalArgumentException( "The savepoint already contains " + identifier .getUid() .map(uid -> "uid " + uid) .orElse("hash " + id.toHexString()) + ". All uid's/hashes must be unique."); } operatorStateIndex.put( id, OperatorStateSpecV2.newWithTransformation( new StateBootstrapTransformationWithID<>(identifier, transformation))); } /** * @return List of {@link OperatorState} that already exists within the savepoint. */ public List<OperatorState> getExistingOperators() { return operatorStateIndex.values().stream() .filter(OperatorStateSpecV2::isExistingState) .map(OperatorStateSpecV2::asExistingState) .collect(Collectors.toList()); } /** * @return List of new operator states for the savepoint, represented by their target {@link * OperatorID} and {@link StateBootstrapTransformation}. */ public List<StateBootstrapTransformationWithID<?>> getNewOperators() { return operatorStateIndex.values().stream() .filter(OperatorStateSpecV2::isNewStateTransformation) .map(OperatorStateSpecV2::asNewStateTransformation) .collect(Collectors.toList()); } }
SavepointMetadataV2
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/async/utils/AsyncClass.java
{ "start": 3230, "end": 8392 }
class ____ extends SyncClass{ private static final Logger LOG = LoggerFactory.getLogger(AsyncClass.class); private ExecutorService executorService; private final static String ASYNC_WORKER = "Async Worker"; public AsyncClass(long timeConsuming) { super(timeConsuming); executorService = Executors.newFixedThreadPool(1, r -> { Thread asyncWork = new Thread(r); asyncWork.setDaemon(true); asyncWork.setName(ASYNC_WORKER); return asyncWork; }); } @Override public String applyMethod(int input) { timeConsumingMethod(input); asyncApply(res -> { return "applyMethod" + res; }); return asyncReturn(String.class); } @Override public String applyMethod(int input, boolean canException) { timeConsumingMethod(input); asyncApply(res -> { if (canException) { if (res.equals("[2]")) { throw new IOException("input 2 exception"); } else if (res.equals("[3]")) { throw new RuntimeException("input 3 exception"); } } return res; }); return asyncReturn(String.class); } @Override public String exceptionMethod(int input) { if (input == 2) { asyncThrowException(new IOException("input 2 exception")); return null; } else if (input == 3) { asyncThrowException(new RuntimeException("input 3 exception")); return null; } return applyMethod(input); } @Override public String forEachMethod(List<Integer> list) { StringBuilder result = new StringBuilder(); asyncForEach(list.iterator(), (forEach, input) -> { timeConsumingMethod(input); asyncApply(res -> { result.append("forEach" + res + ","); return result.toString(); }); }); return asyncReturn(String.class); } @Override public String forEachBreakMethod(List<Integer> list) { StringBuilder result = new StringBuilder(); asyncForEach(list.iterator(), (forEach, input) -> { timeConsumingMethod(input); asyncApply(res -> { if (res.equals("[2]")) { forEach.breakNow(); } else { result.append("forEach" + res + ","); } return result.toString(); }); }); return asyncReturn(String.class); } @Override public String forEachBreakByExceptionMethod(List<Integer> list) { StringBuilder result = new StringBuilder(); asyncForEach(list.iterator(), (forEach, input) -> { asyncTry(() -> { applyMethod(input, true); asyncApply(res -> { result.append("forEach" + res + ","); return result.toString(); }); }); asyncCatch((res, e) -> { if (e instanceof IOException) { result.append(e + ","); } else if (e instanceof RuntimeException) { forEach.breakNow(); } return result.toString(); }, Exception.class); }); return asyncReturn(String.class); } @Override public String applyThenApplyMethod(int input) { timeConsumingMethod(input); asyncApply((AsyncApplyFunction<String, String>) res -> { if (res.equals("[1]")) { timeConsumingMethod(2); } else { asyncComplete(res); } }); return asyncReturn(String.class); } @Override public String applyCatchThenApplyMethod(int input) { asyncTry(() -> applyMethod(input, true)); asyncCatch((AsyncCatchFunction<String, IOException>) (res, ioe) -> { applyMethod(1); }, IOException.class); return asyncReturn(String.class); } @Override public String applyCatchFinallyMethod( int input, List<String> resource) { asyncTry(() -> applyMethod(input, true)); asyncCatch((res, e) -> { throw new IOException("Catch " + e.getMessage()); }, IOException.class); asyncFinally((FinallyFunction<String>) res -> { resource.clear(); return res; }); return asyncReturn(String.class); } @Override public String currentMethod(List<Integer> list) { asyncCurrent(list, input -> applyMethod(input, true), (Function<CompletableFuture<String>[], String>) futures -> { StringBuilder result = new StringBuilder(); for (Future<String> future : futures) { try { String res = future.get(); result.append(res + ","); } catch (Exception e) { result.append(e.getMessage() + ","); } } return result.toString(); }); return asyncReturn(String.class); } @Override public String timeConsumingMethod(int input) { CompletableFuture<Object> result = CompletableFuture .supplyAsync(() -> { LOG.info("[{} thread] invoke consumingMethod for parameter: {}", Thread.currentThread().getName(), input); return AsyncClass.super.timeConsumingMethod(input); }, executorService); Async.CUR_COMPLETABLE_FUTURE.set(result); return null; } }
AsyncClass
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/mailbox/MailboxProcessor.java
{ "start": 1847, "end": 2396 }
class ____ the logic of the mailbox-based execution model. At the core of this model * {@link #runMailboxLoop()} that continuously executes the provided {@link MailboxDefaultAction} in * a loop. On each iteration, the method also checks if there are pending actions in the mailbox and * executes such actions. This model ensures single-threaded execution between the default action * (e.g. record processing) and mailbox actions (e.g. checkpoint trigger, timer firing, ...). * * <p>The {@link MailboxDefaultAction} interacts with this
encapsulates
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 4430, "end": 5371 }
interface ____ {", " List<Integer> listOfInteger();", "}"); CompilerTests.daggerCompiler(parent, child, another, componentFile) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining("List<Integer> is bound multiple times"); subject.hasErrorContaining( "@Provides List<Integer> ChildNumberModule.provideListB(Integer)"); subject.hasErrorContaining( "@Provides List<Integer> AnotherModule.provideListOfInteger()"); }); } @Test public void privateNestedClassWithWarningThatIsAnErrorInComponent() { Source outerClass = CompilerTests.javaSource("test.OuterClass", "package test;", "", "import javax.inject.Inject;", "", "final
BadComponent
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/SubResourceTest.java
{ "start": 916, "end": 4678 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(RootClient.class, SubClient.class, SubSubClient.class, Resource.class)); @TestHTTPResource URI baseUri; @RestClient RootClient injectedClient; @Test void testInjectedClient() { // should result in sending GET /path/rt/mthd/simple String result = injectedClient.sub("rt", "mthd").simpleGet(); assertThat(result).isEqualTo("rt/mthd/simple"); } @Test void shouldPassParamsToSubResource() { // should result in sending GET /path/rt/mthd/simple RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); String result = rootClient.sub("rt", "mthd").simpleGet(); assertThat(result).isEqualTo("rt/mthd/simple"); } @Test void shouldPassParamsToSubSubResource() { // should result in sending GET /path/rt/mthd/sub/simple RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); String result = rootClient.sub("rt", "mthd").sub().simpleSub(); assertThat(result).isEqualTo("rt/mthd/sub/subSimple"); } @Test void shouldPassPathParamsToSubSubResource() { // should result in sending GET /path/rt/mthd/sub/s/ss RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); String result = rootClient.sub("rt", "mthd").sub("s").get("ss"); assertThat(result).isEqualTo("rt/mthd/sub/s/ss"); } @Test void shouldDoMultiplePosts() { RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); SubClient sub = rootClient.sub("rt", "mthd"); Response result = sub.postWithQueryParam("prm", "ent1t1"); assertThat(result.readEntity(String.class)).isEqualTo("rt/mthd:ent1t1:prm"); MultivaluedMap<String, Object> headers = result.getHeaders(); assertThat(headers.get("fromRoot").get(0)).isEqualTo("headerValue"); assertThat(headers.get("overridable").get(0)).isEqualTo("SubClient"); assertThat(headers.get("fromRootMethod").get(0)).isEqualTo("RootClientComputed"); assertThat(headers.get("fromSubMethod").get(0)).isEqualTo("SubClientComputed"); // check that a second usage of the sub stub works result = sub.postWithQueryParam("prm", "ent1t1"); assertThat(result.readEntity(String.class)).isEqualTo("rt/mthd:ent1t1:prm"); } @Test void shouldDoMultiplePostsInSubSubResource() { RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); SubSubClient sub = rootClient.sub("rt", "mthd").sub(); Response result = sub.postWithQueryParam("prm", "ent1t1"); assertThat(result.readEntity(String.class)).isEqualTo("rt/mthd/sub:ent1t1:prm"); MultivaluedMap<String, Object> headers = result.getHeaders(); assertThat(headers.get("overridable").get(0)).isEqualTo("SubSubClient"); assertThat(headers.get("fromSubMethod").get(0)).isEqualTo("SubSubClientComputed"); // check that a second usage of the sub stub works result = sub.postWithQueryParam("prm", "ent1t1"); assertThat(result.readEntity(String.class)).isEqualTo("rt/mthd/sub:ent1t1:prm"); } @Path("/path/{rootParam}") @RegisterRestClient(baseUri = "http://localhost:8081") @Consumes("text/plain") @Produces("text/plain") @ClientHeaderParam(name = "fromRoot", value = "headerValue") @ClientHeaderParam(name = "overridable", value = "RootClient")
SubResourceTest
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java
{ "start": 22338, "end": 22441 }
class ____ { } @Aspect("pertarget(execution(* *.getSpouse()))") @Order(10) static
PerCflowBelowAspect
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/language/JqExpression.java
{ "start": 1301, "end": 1939 }
class ____ extends SingleInputTypedExpressionDefinition { public JqExpression() { } protected JqExpression(JqExpression source) { super(source); } public JqExpression(String expression) { super(expression); } private JqExpression(Builder builder) { super(builder); } @Override public JqExpression copyDefinition() { return new JqExpression(this); } @Override public String getLanguage() { return "jq"; } /** * {@code Builder} is a specific builder for {@link JqExpression}. */ @XmlTransient public static
JqExpression
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/TypeComparators_Test.java
{ "start": 4046, "end": 4088 }
class ____ implements I3 { } private
Bar
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/spatial/SpatialExtentGeoShapeDocValuesAggregatorFunctionSupplier.java
{ "start": 818, "end": 1959 }
class ____ implements AggregatorFunctionSupplier { public SpatialExtentGeoShapeDocValuesAggregatorFunctionSupplier() { } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return SpatialExtentGeoShapeDocValuesAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return SpatialExtentGeoShapeDocValuesGroupingAggregatorFunction.intermediateStateDesc(); } @Override public SpatialExtentGeoShapeDocValuesAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return SpatialExtentGeoShapeDocValuesAggregatorFunction.create(driverContext, channels); } @Override public SpatialExtentGeoShapeDocValuesGroupingAggregatorFunction groupingAggregator( DriverContext driverContext, List<Integer> channels) { return SpatialExtentGeoShapeDocValuesGroupingAggregatorFunction.create(channels, driverContext); } @Override public String describe() { return "spatial_extent_geo_shape_doc of valuess"; } }
SpatialExtentGeoShapeDocValuesAggregatorFunctionSupplier
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 76767, "end": 76872 }
class ____ { @Autowired B b; @Bean public Z z() { return new Z(); } } public static
AStrich
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerBase.java
{ "start": 41360, "end": 41773 }
class ____ DirectoryStreamStateHandle with reference by ongoing checkpoint. If an * ongoing checkpoint which reference the directory handle complete or be subsumed, we will stop * tracking the handle, because the ownership of the handle is handover to JobManager. * JobManager acknowledges the handle and will clean up the directory when it is no longer * needed. */ protected static
wrap
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/CastTest.java
{ "start": 931, "end": 1490 }
class ____ { private String name; public Body(){ } public Body(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private List<Item> items = new ArrayList<Item>(); public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } } public static
Body
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
{ "start": 57565, "end": 57696 }
interface ____ { @AliasFor("bar") String foo() default ""; } @AliasForNonexistentAttribute static
AliasForNonexistentAttribute
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/intarray/IntArrayAssert_containsOnlyOnce_Test.java
{ "start": 970, "end": 1324 }
class ____ extends IntArrayAssertBaseTest { @Override protected IntArrayAssert invoke_api_method() { return assertions.containsOnlyOnce(6, 8); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsOnlyOnce(getInfo(assertions), getActual(assertions), arrayOf(6, 8)); } }
IntArrayAssert_containsOnlyOnce_Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/util/FieldInfoTest.java
{ "start": 3830, "end": 4204 }
class ____ { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } }
ValueObject
java
google__guice
core/test/com/google/inject/spi/ProviderMethodsTest.java
{ "start": 34076, "end": 36964 }
class ____ extends AbstractModule { @Provides static String provideString() { return ""; } } @Test public void testDeduplicateProviderMethodsBindings_sameInstance_staticMethod() { Module module = new DeduplicateStaticModule(); Guice.createInjector(Stage.PRODUCTION, module, module); } @Test public void testDeduplicateProviderMethodsBindings_differentInstances_staticMethod() { Guice.createInjector( Stage.PRODUCTION, new DeduplicateStaticModule(), new DeduplicateStaticModule()); } private void runNullableTest(Injector injector, Dependency<?> dependency, Module module) { switch (InternalFlags.getNullableProvidesOption()) { case ERROR: validateNullableFails(injector, module); break; case IGNORE: validateNullableIgnored(injector); break; case WARN: validateNullableWarns(injector, dependency); break; } } private void validateNullableFails(Injector injector, Module module) { try { injector.getInstance(Integer.class); fail(); } catch (ProvisionException expected) { String moduleName = module.getClass().getName().replace("com.google.inject.spi.", ""); assertContains( expected.getMessage(), "null returned by binding at " + moduleName + ".configure(", "but the 1st parameter foo of " + moduleName + ".fail(", "is not @Nullable", "for 1st parameter", "while locating Integer"); assertEquals(1, expected.getErrorMessages().size()); } } private void validateNullableIgnored(Injector injector) { injector.getInstance(Integer.class); // no exception } private void validateNullableWarns(Injector injector, Dependency<?> dependency) { final List<LogRecord> logRecords = Lists.newArrayList(); final Handler fakeHandler = new Handler() { @Override public void publish(LogRecord logRecord) { logRecords.add(logRecord); } @Override public void flush() {} @Override public void close() throws SecurityException {} }; Logger.getLogger(Guice.class.getName()).addHandler(fakeHandler); try { injector.getInstance(Integer.class); // no exception, but assert it does log. LogRecord record = Iterables.getOnlyElement(logRecords); assertEquals( "Guice injected null into {0} (a {1}), please mark it @Nullable." + " Use -Dguice_check_nullable_provides_params=ERROR to turn this into an" + " error.", record.getMessage()); assertEquals(Errors.convert(dependency.getKey()), record.getParameters()[1]); } finally { Logger.getLogger(Guice.class.getName()).removeHandler(fakeHandler); } } @Retention(RetentionPolicy.RUNTIME) @
DeduplicateStaticModule
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/DeSelectFields.java
{ "start": 1415, "end": 3060 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(DeSelectFields.class.getName()); private final Set<DeSelectType> types; public DeSelectFields() { this.types = new HashSet<DeSelectType>(); } /** * Initial DeSelectFields with unselected fields. * @param unselectedFields a set of unselected field. */ public void initFields(Set<String> unselectedFields) { if (unselectedFields == null) { return; } for (String field : unselectedFields) { if (!field.trim().isEmpty()) { String[] literalsArray = field.split(","); for (String literals : literalsArray) { if (literals != null && !literals.trim().isEmpty()) { DeSelectType type = DeSelectType.obtainType(literals); if (type == null) { LOG.warn("Invalid deSelects string " + literals.trim()); DeSelectType[] typeArray = DeSelectType.values(); String allSupportLiterals = Arrays.toString(typeArray); throw new BadRequestException("Invalid deSelects string " + literals.trim() + " specified. It should be one of " + allSupportLiterals); } else { this.types.add(type); } } } } } } /** * Determine to deselect type should be handled or not. * @param type deselected type * @return true if the deselect type should be handled */ public boolean contains(DeSelectType type) { return types.contains(type); } /** * Deselect field type, can be boosted in the future. */ public
DeSelectFields
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/NameNodeAdapter.java
{ "start": 2770, "end": 2836 }
class ____ expose NameNode functionality for unit tests. */ public
to
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java
{ "start": 1753, "end": 3649 }
interface ____ { MavenExecutionPlan calculateExecutionPlan(MavenSession session, MavenProject project, List<Task> tasks) throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List<Task> tasks, boolean setup) throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; void calculateForkedExecutions(MojoExecution mojoExecution, MavenSession session) throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; void setupMojoExecution( MavenSession session, MavenProject project, MojoExecution mojoExecution, Set<MojoDescriptor> alreadyPlannedExecutions) throws PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; }
LifecycleExecutionPlanCalculator
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/configuration/ConfigurationValidationType.java
{ "start": 357, "end": 998 }
enum ____ { LESS_THAN, GREATER_THAN, LIST_TYPE, INCLUDED_IN, REGEX; @Override public String toString() { return name().toLowerCase(Locale.ROOT); } public static ConfigurationValidationType validationType(String type) { for (ConfigurationValidationType displayType : ConfigurationValidationType.values()) { if (displayType.name().equalsIgnoreCase(type)) { return displayType; } } throw new IllegalArgumentException("Unknown " + ConfigurationValidationType.class.getSimpleName() + " [" + type + "]."); } }
ConfigurationValidationType
java
apache__camel
components/camel-ai/camel-langchain4j-agent/src/test/java/org/apache/camel/component/langchain4j/agent/LangChain4jAgentWithMemoryServiceTest.java
{ "start": 1814, "end": 7241 }
class ____ extends BaseLangChain4jAgent { @RegisterExtension public static OpenAIMock openAIMock = new OpenAIMock().builder() .when("Hi! Can you look up user 123 and tell me about our rental policies?") .assertRequest(request -> { // Both tools are part of the request Assertions.assertThat(request).contains("QueryUserDatabaseByUserID", "GetCurrentWeatherInformation"); }) .invokeTool("QueryUserDatabaseByUserID") .withParam("userId", "123") .replyWithToolContent(" " + COMPANY_KNOWLEDGE_BASE) .end() .when("What's his preferred vehicle type?") .assertRequest(request -> { // Assert that memory is working as expected Assertions.assertThat(request) .contains("Hi! Can you look up user 123 and tell me about our rental policies?"); }) .replyWith("SUV") .end() .when("What's the weather in London?") .invokeTool("GetCurrentWeatherInformation") .withParam("location", "London") .end() .build(); @Override protected void setupResources() throws Exception { super.setupResources(); chatMemoryStore = new PersistentChatMemoryStore(); chatModel = createChatModel(null, openAIMock.getBaseUrl()); chatMemoryProvider = createMemoryProvider(chatMemoryStore); } @Test public void testToolThenMemoryThenAnotherTool() throws Exception { MockEndpoint mockEndpoint = this.context.getEndpoint("mock:agent-response", MockEndpoint.class); mockEndpoint.expectedMessageCount(3); AiAgentBody<?> firstRequest = new AiAgentBody<>( "Hi! Can you look up user 123 and tell me about our rental policies?", null, MEMORY_ID_SESSION); String firstResponse = template.requestBody( "direct:complete-agent", firstRequest, String.class); assertNotNull(firstResponse, "First response should not be null"); Assertions.assertThat(firstResponse).contains("John Smith", "Gold") .withFailMessage("Response should contain user information from tools"); Assertions.assertThat(firstResponse).contains("21", "age", "rental") .withFailMessage("Response should contain rental policy information from RAG"); // Second interaction: Follow-up question AiAgentBody<?> secondRequest = new AiAgentBody<>( "What's his preferred vehicle type?", null, MEMORY_ID_SESSION); String secondResponse = template.requestBody( "direct:complete-agent", secondRequest, String.class); assertNotNull(secondResponse, "Second response should not be null"); Assertions.assertThat(secondResponse).isEqualTo("SUV"); // Third interaction: Follow-up weather question AiAgentBody<?> thirdRequest = new AiAgentBody<>( "What's the weather in London?", null, MEMORY_ID_SESSION); String thirdResponse = template.requestBody( "direct:complete-agent", thirdRequest, String.class); assertNotNull(thirdRequest, "Third response should not be null"); Assertions.assertThat(thirdResponse).contains(WEATHER_INFO); mockEndpoint.assertIsSatisfied(); // Verify guardrails were called assertTrue(TestSuccessInputGuardrail.wasValidated(), "Input guardrail should have been called"); // Verify memory persistence assertTrue(chatMemoryStore.getMemoryCount() > 0, "Memory should be persisted"); assertFalse(chatMemoryStore.getMessages(MEMORY_ID_SESSION).isEmpty(), "Session memory should contain messages"); } @Override protected RouteBuilder createRouteBuilder() { AgentConfiguration configuration = new AgentConfiguration() .withChatModel(chatModel) .withChatMemoryProvider(chatMemoryProvider) .withInputGuardrailClassesList("org.apache.camel.component.langchain4j.agent.pojos.TestSuccessInputGuardrail") .withOutputGuardrailClasses(List.of()); Agent agent = new AgentWithMemory(configuration); this.context.getRegistry().bind("agent", agent); return new RouteBuilder() { public void configure() { // Tools + Memory + Guardrails + RAG from("direct:complete-agent") .to("langchain4j-agent:complete?agent=#agent&tags=users,weather") .to("mock:agent-response"); // Tool routes for function calling from("langchain4j-tools:userDb?tags=users&description=Query user database by user ID&parameter.userId=string") .setBody(constant(USER_DATABASE)); from("langchain4j-tools:weatherService?tags=weather&description=Get current weather information&parameter.location=string") .setBody(constant("{\"weather\": \"" + WEATHER_INFO + "\", \"location\": \"Current Location\"}")); } }; } }
LangChain4jAgentWithMemoryServiceTest
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/registration/HttpSessionPublicKeyCredentialCreationOptionsRepository.java
{ "start": 1009, "end": 1908 }
class ____ implements PublicKeyCredentialCreationOptionsRepository { static final String DEFAULT_ATTR_NAME = PublicKeyCredentialCreationOptions.class.getName().concat("ATTR_NAME"); private String attrName = DEFAULT_ATTR_NAME; @Override public void save(HttpServletRequest request, HttpServletResponse response, @Nullable PublicKeyCredentialCreationOptions options) { request.getSession().setAttribute(this.attrName, options); } public @Nullable PublicKeyCredentialCreationOptions load(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return null; } return (PublicKeyCredentialCreationOptions) session.getAttribute(this.attrName); } public void setAttrName(String attrName) { Assert.notNull(attrName, "attrName cannot be null"); this.attrName = attrName; } }
HttpSessionPublicKeyCredentialCreationOptionsRepository
java
spring-projects__spring-boot
module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/web/mappings/RequestMappingConditionsDescription.java
{ "start": 3243, "end": 3760 }
class ____ { private final String mediaType; private final boolean negated; MediaTypeExpressionDescription(MediaTypeExpression expression) { this.mediaType = expression.getMediaType().toString(); this.negated = expression.isNegated(); } public String getMediaType() { return this.mediaType; } public boolean isNegated() { return this.negated; } } /** * A description of a {@link NameValueExpression} in a request mapping condition. */ public static
MediaTypeExpressionDescription
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsWithGenericTypeHierarchiesTests.java
{ "start": 879, "end": 956 }
class ____ implements InterfaceDouble, InterfaceGenericNumber<Number> { }
AB
java
apache__flink
flink-test-utils-parent/flink-migration-test-utils/src/main/java/org/apache/flink/test/migration/SnapshotGeneratorUtils.java
{ "start": 7772, "end": 8190 }
class ____ due to argument lists type not supported: " + argumentLists.getClass()); } } } throw new RuntimeException( "Could not create the object for " + migrationTestClass + ": No default constructor or @Parameterized.Parameters or @Parameters method found."); } }
object
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/rest/RestControllerTests.java
{ "start": 63668, "end": 64447 }
class ____ extends AbstractLifecycleComponent implements HttpServerTransport { TestHttpServerTransport() {} @Override protected void doStart() {} @Override protected void doStop() {} @Override protected void doClose() {} @Override public BoundTransportAddress boundAddress() { TransportAddress transportAddress = buildNewFakeTransportAddress(); return new BoundTransportAddress(new TransportAddress[] { transportAddress }, transportAddress); } @Override public HttpInfo info() { return null; } @Override public HttpStats stats() { return null; } } public static final
TestHttpServerTransport
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/math/Fraction.java
{ "start": 16876, "end": 16981 }
class ____ immutable). */ private transient int hashCode; /** * Cached output toString (
is
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ZoneReencryptionStatus.java
{ "start": 987, "end": 1183 }
class ____ information about re-encryption of an encryption zone. * <p> * FSDirectory lock is used for synchronization (except test-only methods, which * are not protected). */ public
representing
java
apache__camel
components/camel-workday/src/generated/java/org/apache/camel/component/workday/WorkdayEndpointUriFactory.java
{ "start": 517, "end": 2648 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":entity:path"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(10); props.add("clientId"); props.add("clientSecret"); props.add("entity"); props.add("host"); props.add("httpConnectionManager"); props.add("lazyStartProducer"); props.add("path"); props.add("reportFormat"); props.add("tenant"); props.add("tokenRefresh"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(3); secretProps.add("clientId"); secretProps.add("clientSecret"); secretProps.add("tokenRefresh"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "workday".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "entity", null, true, copy); uri = buildPathParameter(syntax, uri, "path", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
WorkdayEndpointUriFactory
java
quarkusio__quarkus
extensions/cache/deployment/src/main/java/io/quarkus/cache/deployment/devui/CacheDevUiProcessor.java
{ "start": 426, "end": 1065 }
class ____ { @BuildStep(onlyIf = IsLocalDevelopment.class) CardPageBuildItem create(CurateOutcomeBuildItem bi) { CardPageBuildItem pageBuildItem = new CardPageBuildItem(); pageBuildItem.addPage(Page.webComponentPageBuilder() .title("Caches") .componentLink("qwc-cache-caches.js") .icon("font-awesome-solid:database")); return pageBuildItem; } @BuildStep(onlyIf = IsLocalDevelopment.class) JsonRPCProvidersBuildItem createJsonRPCServiceForCache() { return new JsonRPCProvidersBuildItem(CacheJsonRPCService.class); } }
CacheDevUiProcessor
java
elastic__elasticsearch
x-pack/plugin/mapper-unsigned-long/src/test/java/org/elasticsearch/xpack/unsignedlong/UnsignedLongFieldMapperTests.java
{ "start": 18997, "end": 22605 }
class ____ implements SyntheticSourceSupport { private final BigInteger nullValue = usually() ? null : BigInteger.valueOf(randomNonNegativeLong()); private final boolean ignoreMalformedEnabled; NumberSyntheticSourceSupport(boolean ignoreMalformedEnabled) { this.ignoreMalformedEnabled = ignoreMalformedEnabled; } @Override public SyntheticSourceExample example(int maxVals) { if (randomBoolean()) { Value v = generateValue(); if (v.malformedOutput == null) { return new SyntheticSourceExample(v.input, v.output, this::mapping); } return new SyntheticSourceExample(v.input, v.malformedOutput, this::mapping); } List<Value> values = randomList(1, maxVals, this::generateValue); List<Object> in = values.stream().map(Value::input).toList(); List<BigInteger> outputFromDocValues = values.stream() .filter(v -> v.malformedOutput == null) .map(Value::output) .sorted() .toList(); Stream<Object> malformedOutput = values.stream().filter(v -> v.malformedOutput != null).map(Value::malformedOutput); // Malformed values are always last in the implementation. List<Object> outList = Stream.concat(outputFromDocValues.stream(), malformedOutput).toList(); Object out = outList.size() == 1 ? outList.get(0) : outList; return new SyntheticSourceExample(in, out, this::mapping); } private record Value(Object input, BigInteger output, Object malformedOutput) {} private Value generateValue() { if (nullValue != null && randomBoolean()) { return new Value(null, nullValue, null); } if (ignoreMalformedEnabled && randomBoolean()) { List<Supplier<Object>> choices = List.of(() -> randomAlphaOfLengthBetween(1, 10)); var malformedInput = randomFrom(choices).get(); return new Value(malformedInput, null, malformedInput); } long n = randomNonNegativeLong(); BigInteger b = BigInteger.valueOf(n); if (b.signum() < 0) { b = b.add(BigInteger.ONE.shiftLeft(64)); } return new Value(n, b, null); } private void mapping(XContentBuilder b) throws IOException { minimalMapping(b); if (nullValue != null) { b.field("null_value", nullValue); } if (rarely()) { b.field("index", false); } if (rarely()) { b.field("store", false); } if (ignoreMalformedEnabled) { b.field("ignore_malformed", "true"); } } @Override public List<SyntheticSourceInvalidExample> invalidExample() { return List.of(); } } @Override protected Object[] getThreeEncodedSampleValues() { return Arrays.stream(super.getThreeEncodedSampleValues()) .map(v -> UnsignedLongFieldMapper.sortableSignedLongToUnsigned((Long) v)) .toArray(); } @Override protected boolean supportsBulkLongBlockReading() { return true; } @Override protected List<SortShortcutSupport> getSortShortcutSupport() { return List.of(new SortShortcutSupport(this::minimalMapping, this::writeField, true)); } }
NumberSyntheticSourceSupport
java
apache__dubbo
dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
{ "start": 38082, "end": 38603 }
class ____ { private int id; private String name; public User() {} public User(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
User
java
quarkusio__quarkus
extensions/security/spi/src/main/java/io/quarkus/security/spi/ClassSecurityAnnotationBuildItem.java
{ "start": 438, "end": 747 }
class ____ and * security interceptors for security annotations (such as selecting tenant or authentication mechanism). * We strongly recommended to secure CDI beans with {@link AdditionalSecuredMethodsBuildItem} * if additional security is required. If you decide to use this build item, you must use *
level
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/FirstValueWithRetractAggFunctionWithOrderTest.java
{ "start": 12418, "end": 13679 }
class ____<T> extends FirstValueWithRetractAggFunctionWithOrderTestBase<T> { protected abstract T getValue(String v); @Override protected List<List<T>> getInputValueSets() { return Arrays.asList( Arrays.asList( getValue("1"), null, getValue("-99"), getValue("3"), null, getValue("3"), getValue("2"), getValue("-99")), Arrays.asList(null, null, null, null), Arrays.asList(null, getValue("10"), null, getValue("5"))); } @Override protected List<List<Long>> getInputOrderSets() { return Arrays.asList( Arrays.asList(10L, 2L, 5L, 6L, 11L, 3L, 7L, 5L), Arrays.asList(8L, 6L, 9L, 5L), Arrays.asList(null, 6L, 4L, 3L)); } @Override protected List<T> getExpectedResults() { return Arrays.asList(getValue("3"), null, getValue("5")); } } }
NumberFirstValueWithRetractAggFunctionWithOrderTestBase
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/MemberAssignment.java
{ "start": 1082, "end": 2241 }
class ____ { private final Set<TopicPartition> topicPartitions; /** * Creates an instance with the specified parameters. * * @param topicPartitions List of topic partitions */ public MemberAssignment(Set<TopicPartition> topicPartitions) { this.topicPartitions = topicPartitions == null ? Collections.emptySet() : Set.copyOf(topicPartitions); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MemberAssignment that = (MemberAssignment) o; return Objects.equals(topicPartitions, that.topicPartitions); } @Override public int hashCode() { return topicPartitions != null ? topicPartitions.hashCode() : 0; } /** * The topic partitions assigned to a group member. */ public Set<TopicPartition> topicPartitions() { return topicPartitions; } @Override public String toString() { return "(topicPartitions=" + topicPartitions.stream().map(TopicPartition::toString).collect(Collectors.joining(",")) + ")"; } }
MemberAssignment
java
google__dagger
dagger-producers/main/java/dagger/producers/Produced.java
{ "start": 3524, "end": 4348 }
class ____<T> extends Produced<T> { private final Throwable throwable; private Failed(Throwable throwable) { this.throwable = checkNotNull(throwable); } @Override public T get() throws ExecutionException { throw new ExecutionException(throwable); } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof Failed) { Failed<?> that = (Failed<?>) o; return this.throwable.equals(that.throwable); } else { return false; } } @Override public int hashCode() { return throwable.hashCode(); } @Override public String toString() { return "Produced[failed with " + throwable.getClass().getCanonicalName() + "]"; } } private Produced() {} }
Failed
java
apache__maven
compat/maven-builder-support/src/test/java/org/apache/maven/building/DefaultProblemCollectorTest.java
{ "start": 1114, "end": 2814 }
class ____ { @Test void testGetProblems() { DefaultProblemCollector collector = new DefaultProblemCollector(null); assertNotNull(collector.getProblems()); assertEquals(0, collector.getProblems().size()); collector.add(null, "MESSAGE1", -1, -1, null); Exception e2 = new Exception(); collector.add(Severity.WARNING, null, 42, 127, e2); assertEquals(2, collector.getProblems().size()); Problem p1 = collector.getProblems().get(0); assertEquals(Severity.ERROR, p1.getSeverity()); assertEquals("MESSAGE1", p1.getMessage()); assertEquals(-1, p1.getLineNumber()); assertEquals(-1, p1.getColumnNumber()); assertNull(p1.getException()); Problem p2 = collector.getProblems().get(1); assertEquals(Severity.WARNING, p2.getSeverity()); assertEquals("", p2.getMessage()); assertEquals(42, p2.getLineNumber()); assertEquals(127, p2.getColumnNumber()); assertEquals(e2, p2.getException()); } @Test void testSetSource() { DefaultProblemCollector collector = new DefaultProblemCollector(null); collector.add(null, "PROBLEM1", -1, -1, null); collector.setSource("SOURCE_PROBLEM2"); collector.add(null, "PROBLEM2", -1, -1, null); collector.setSource("SOURCE_PROBLEM3"); collector.add(null, "PROBLEM3", -1, -1, null); assertEquals("", collector.getProblems().get(0).getSource()); assertEquals("SOURCE_PROBLEM2", collector.getProblems().get(1).getSource()); assertEquals("SOURCE_PROBLEM3", collector.getProblems().get(2).getSource()); } }
DefaultProblemCollectorTest
java
apache__dubbo
dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilder.java
{ "start": 987, "end": 1959 }
class ____ { /** * The argument index: index -1 represents not set */ private Integer index = -1; /** * Argument type */ private String type; /** * Whether the argument is the callback interface */ private Boolean callback; public static ArgumentBuilder newBuilder() { return new ArgumentBuilder(); } public ArgumentBuilder index(Integer index) { this.index = index; return this; } public ArgumentBuilder type(String type) { this.type = type; return this; } public ArgumentBuilder callback(Boolean callback) { this.callback = callback; return this; } public ArgumentConfig build() { ArgumentConfig argumentConfig = new ArgumentConfig(); argumentConfig.setIndex(index); argumentConfig.setType(type); argumentConfig.setCallback(callback); return argumentConfig; } }
ArgumentBuilder
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-kafka/src/main/java/smoketest/kafka/Producer.java
{ "start": 773, "end": 1126 }
class ____ { private final KafkaTemplate<Object, SampleMessage> kafkaTemplate; Producer(KafkaTemplate<Object, SampleMessage> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void send(SampleMessage message) { this.kafkaTemplate.send("testTopic", message); System.out.println("Sent sample message [" + message + "]"); } }
Producer
java
square__retrofit
retrofit/src/main/java/retrofit2/Converter.java
{ "start": 1580, "end": 3586 }
class ____ { /** * Returns a {@link Converter} for converting an HTTP response body to {@code type}, or null if * {@code type} cannot be handled by this factory. This is used to create converters for * response types such as {@code SimpleResponse} from a {@code Call<SimpleResponse>} * declaration. */ public @Nullable Converter<ResponseBody, ?> responseBodyConverter( Type type, Annotation[] annotations, Retrofit retrofit) { return null; } /** * Returns a {@link Converter} for converting {@code type} to an HTTP request body, or null if * {@code type} cannot be handled by this factory. This is used to create converters for types * specified by {@link Body @Body}, {@link Part @Part}, and {@link PartMap @PartMap} values. */ public @Nullable Converter<?, RequestBody> requestBodyConverter( Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { return null; } /** * Returns a {@link Converter} for converting {@code type} to a {@link String}, or null if * {@code type} cannot be handled by this factory. This is used to create converters for types * specified by {@link Field @Field}, {@link FieldMap @FieldMap} values, {@link Header @Header}, * {@link HeaderMap @HeaderMap}, {@link Path @Path}, {@link Query @Query}, and {@link * QueryMap @QueryMap} values. */ public @Nullable Converter<?, String> stringConverter( Type type, Annotation[] annotations, Retrofit retrofit) { return null; } /** * Extract the upper bound of the generic parameter at {@code index} from {@code type}. For * example, index 1 of {@code Map<String, ? extends Runnable>} returns {@code Runnable}. */ protected static Type getParameterUpperBound(int index, ParameterizedType type) { return Utils.getParameterUpperBound(index, type); } /** * Extract the raw
Factory
java
google__truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldScopeLogicMap.java
{ "start": 1617, "end": 1738 }
class ____<V> implements FieldScopeLogicContainer<FieldScopeLogicMap<V>> { @AutoValue abstract static
FieldScopeLogicMap
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java
{ "start": 1660, "end": 1770 }
class ____ listeners whose functionality results in flushing. * * @author Steve Ebersole */ public abstract
for
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java
{ "start": 12110, "end": 12717 }
class ____ implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { if (bean instanceof ProtectedLifecycleBean) { ((ProtectedLifecycleBean) bean).postProcessBeforeInit(); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { if (bean instanceof ProtectedLifecycleBean) { ((ProtectedLifecycleBean) bean).postProcessAfterInit(); } return bean; } } } /** * @author Rod Johnson */ @SuppressWarnings("serial")
PostProcessor
java
quarkusio__quarkus
extensions/amazon-lambda/deployment/src/test/java/io/quarkus/amazon/lambda/deployment/RequestHandlerJandexUtilTest.java
{ "start": 20770, "end": 20998 }
class ____ implements RequestHandler<String, Boolean> { // Abstract method - should be ignored public abstract Boolean handleRequest(String input, Context context); } public static
AbstractParentWithAbstract
java
micronaut-projects__micronaut-core
jackson-databind/src/main/java/io/micronaut/jackson/serialize/OptionalValuesSerializer.java
{ "start": 1211, "end": 2705 }
class ____ extends ValueSerializer<OptionalValues<?>> { private final boolean alwaysSerializeErrorsAsList; public OptionalValuesSerializer() { this.alwaysSerializeErrorsAsList = false; } @Inject public OptionalValuesSerializer(JacksonConfiguration jacksonConfiguration) { this.alwaysSerializeErrorsAsList = jacksonConfiguration.isAlwaysSerializeErrorsAsList(); } @Override public boolean isEmpty(SerializationContext provider, OptionalValues<?> value) { return value.isEmpty(); } @Override public void serialize(OptionalValues<?> value, JsonGenerator gen, SerializationContext serializers) { gen.writeStartObject(); for (CharSequence key : value) { Optional<?> opt = value.get(key); if (opt.isPresent()) { String fieldName = key.toString(); gen.writeName(fieldName); Object v = opt.get(); if (value instanceof OptionalMultiValues) { List<?> list = (List<?>) v; if (list.size() == 1 && (list.get(0).getClass() != JsonError.class || !alwaysSerializeErrorsAsList)) { gen.writePOJO(list.get(0)); } else { gen.writePOJO(list); } } else { gen.writePOJO(v); } } } gen.writeEndObject(); } }
OptionalValuesSerializer
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/CommonArrayInputTypeStrategy.java
{ "start": 1217, "end": 1474 }
class ____ extends CommonCollectionInputTypeStrategy { public CommonArrayInputTypeStrategy(ArgumentCount argumentCount) { super(argumentCount, "All arguments requires to be a ARRAY type", LogicalTypeRoot.ARRAY); } }
CommonArrayInputTypeStrategy
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java
{ "start": 37426, "end": 37606 }
class ____ implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange); } } }
TestWebFilter
java
quarkusio__quarkus
extensions/liquibase/liquibase/deployment/src/test/java/io/quarkus/liquibase/test/LiquibaseExtensionConfigActiveFalseNamedDatasourceStaticInjectionTest.java
{ "start": 2583, "end": 2786 }
class ____ { @Inject @LiquibaseDataSource("users") LiquibaseFactory liquibase; public void useLiquibase() { liquibase.getConfiguration(); } } }
MyBean
java
bumptech__glide
integration/cronet/src/main/java/com/bumptech/glide/integration/cronet/ChromiumUrlFetcher.java
{ "start": 369, "end": 1566 }
class ____<T> implements DataFetcher<T>, ChromiumRequestSerializer.Listener { private final ChromiumRequestSerializer serializer; private final ByteBufferParser<T> parser; private final GlideUrl url; private DataCallback<? super T> callback; public ChromiumUrlFetcher( ChromiumRequestSerializer serializer, ByteBufferParser<T> parser, GlideUrl url) { this.serializer = serializer; this.parser = parser; this.url = url; } @Override public void loadData(Priority priority, DataCallback<? super T> callback) { this.callback = callback; serializer.startRequest(priority, url, this); } @Override public void cleanup() { // Nothing to cleanup. } @Override public void cancel() { serializer.cancelRequest(url, this); } @Override public Class<T> getDataClass() { return parser.getDataClass(); } @Override public DataSource getDataSource() { return DataSource.REMOTE; } @Override public void onRequestComplete(ByteBuffer byteBuffer) { callback.onDataReady(parser.parse(byteBuffer)); } @Override public void onRequestFailed(@Nullable Exception e) { callback.onLoadFailed(e); } }
ChromiumUrlFetcher