language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationToNotAuditedManyJoinQueryTest.java
{ "start": 1892, "end": 4223 }
class ____ { @Id private Long id; private String name; @OneToMany @AuditJoinTable(name = "entitya_onetomany_entityb_aud") @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) private Set<EntityB> bOneToMany = new HashSet<>(); @ManyToMany @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) @JoinTable(name = "entitya_manytomany_entityb") private Set<EntityB> bManyToMany = new HashSet<>(); // @OneToMany(mappedBy="bidiAManyToOneOwning") // @Audited(targetAuditMode=RelationTargetAuditMode.NOT_AUDITED) // private Set<EntityC> bidiCOneToManyInverse = new HashSet<>(); @ManyToMany @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) @AuditJoinTable(name = "entitya_entityc_bidi_aud") private Set<EntityC> bidiCManyToManyOwning = new HashSet<>(); // @ManyToMany(mappedBy="bidiAManyToManyOwning") // @Audited(targetAuditMode=RelationTargetAuditMode.NOT_AUDITED) // private Set<EntityC> bidiCManyToManyInverse = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<EntityB> getbOneToMany() { return bOneToMany; } public void setbOneToMany(Set<EntityB> bOneToMany) { this.bOneToMany = bOneToMany; } public Set<EntityB> getbManyToMany() { return bManyToMany; } public void setbManyToMany(Set<EntityB> bManyToMany) { this.bManyToMany = bManyToMany; } // public Set<EntityC> getBidiCOneToManyInverse() { // return bidiCOneToManyInverse; // } // // // // public void setBidiCOneToManyInverse(Set<EntityC> bidiCOneToManyInverse) { // this.bidiCOneToManyInverse = bidiCOneToManyInverse; // } public Set<EntityC> getBidiCManyToManyOwning() { return bidiCManyToManyOwning; } public void setBidiCManyToManyOwning(Set<EntityC> bidiCManyToManyOwning) { this.bidiCManyToManyOwning = bidiCManyToManyOwning; } // public Set<EntityC> getBidiCManyToManyInverse() { // return bidiCManyToManyInverse; // } // // // public void setBidiCManyToManyInverse(Set<EntityC> bidiCManyToManyInverse) { // this.bidiCManyToManyInverse = bidiCManyToManyInverse; // } } @Entity(name = "EntityB") public static
EntityA
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/BeanDefinition.java
{ "start": 2365, "end": 11930 }
interface ____<T> extends QualifiedBeanType<T>, Named, BeanType<T>, ArgumentCoercible<T> { /** * @return The type information for the bean. * @since 4.8.0 */ default @NonNull TypeInformation<T> getTypeInformation() { return new TypeInformation<>() { @Override public String getBeanTypeString(TypeFormat format) { Class<T> beanType = getType(); boolean synthetic = beanType.isSynthetic(); if (synthetic) { AnnotationMetadata annotationMetadata = getAnnotationMetadata(); // synthetic bean so produce better formatting. if (annotationMetadata.hasDeclaredStereotype(ANN_ADAPTER)) { @SuppressWarnings("unchecked") ExecutableMethod<Object, ?> method = (ExecutableMethod<Object, ?>) BeanDefinition.this.getExecutableMethods().iterator().next(); // Not great, but to produce accurate debug output we have to reach into AOP internals Class<?> resolvedBeanType = method.classValue(ANN_ADAPTER, "adaptedBean") .orElse(beanType); return TypeFormat.getBeanTypeString( format, resolvedBeanType, getGenericBeanType().getTypeVariables(), annotationMetadata ); } else if (InterceptedBean.class.isAssignableFrom(beanType)) { if (beanType.isInterface()) { return TypeFormat.getBeanTypeString( format, beanType.getInterfaces()[0], getGenericBeanType().getTypeVariables(), annotationMetadata ); } else { return TypeFormat.getBeanTypeString( format, beanType.getSuperclass(), getGenericBeanType().getTypeVariables(), annotationMetadata ); } } else { return TypeInformation.super.getBeanTypeString(format); } } else { return TypeInformation.super.getBeanTypeString(format); } } @Override public Class<T> getType() { return getBeanType(); } @Override public Map<String, Argument<?>> getTypeVariables() { return BeanDefinition.this.getGenericBeanType().getTypeVariables(); } @Override public AnnotationMetadata getAnnotationMetadata() { return BeanDefinition.this.getAnnotationMetadata(); } }; } /** * @return The scope of the bean */ default Optional<Class<? extends Annotation>> getScope() { return Optional.empty(); } /** * @return The name of the scope */ default Optional<String> getScopeName() { return Optional.empty(); } /** * @return Whether the scope is singleton */ default boolean isSingleton() { final String scopeName = getScopeName().orElse(null); if (scopeName != null && scopeName.equals(AnnotationUtil.SINGLETON)) { return true; } else { return getAnnotationMetadata().stringValue(DefaultScope.class) .map(t -> t.equals(Singleton.class.getName()) || t.equals(AnnotationUtil.SINGLETON)) .orElse(false); } } /** * If {@link #isContainerType()} returns true this will return the container element. * @return The container element. */ default Optional<Argument<?>> getContainerElement() { return Optional.empty(); } @Override @SuppressWarnings("java:S3776") default boolean isCandidateBean(@Nullable Argument<?> beanType) { if (beanType == null) { return false; } if (QualifiedBeanType.super.isCandidateBean(beanType)) { final Argument<?>[] typeArguments = beanType.getTypeParameters(); final int len = typeArguments.length; Class<?> beanClass = beanType.getType(); if (len == 0) { if (isContainerType()) { if (getBeanType().isAssignableFrom(beanClass)) { return true; } final Optional<Argument<?>> containerElement = getContainerElement(); if (containerElement.isPresent()) { final Class<?> t = containerElement.get().getType(); return beanType.isAssignableFrom(t) || beanClass == t; } else { return false; } } else { return true; } } else { final Argument<?>[] beanTypeParameters; if (!Iterable.class.isAssignableFrom(beanClass)) { final Optional<Argument<?>> containerElement = getContainerElement(); //noinspection OptionalIsPresent if (containerElement.isPresent()) { beanTypeParameters = containerElement.get().getTypeParameters(); } else { beanTypeParameters = getTypeArguments(beanClass).toArray(Argument.ZERO_ARGUMENTS); } } else { beanTypeParameters = getTypeArguments(beanClass).toArray(Argument.ZERO_ARGUMENTS); } if (len != beanTypeParameters.length) { return false; } for (int i = 0; i < beanTypeParameters.length; i++) { Argument<?> candidateParameter = beanTypeParameters[i]; final Argument<?> requestedParameter = typeArguments[i]; if (!requestedParameter.isAssignableFrom(candidateParameter.getType())) { if (!(candidateParameter.isTypeVariable() && candidateParameter.isAssignableFrom(requestedParameter.getType()))) { return false; } } } return true; } } return false; } /** * @return Whether the bean declared with {@link io.micronaut.context.annotation.EachProperty} or * {@link io.micronaut.context.annotation.EachBean} */ default boolean isIterable() { return hasDeclaredStereotype(EachProperty.class) || hasDeclaredStereotype(EachBean.class); } /** * @return Is the type configuration properties. */ default boolean isConfigurationProperties() { return isIterable() || hasDeclaredStereotype(ConfigurationReader.class); } /** * @return The produced bean type */ @Override Class<T> getBeanType(); /** * @return The type that declares this definition, null if not applicable. */ default Optional<Class<?>> getDeclaringType() { return Optional.empty(); } /** * The single concrete constructor that is an injection point for creating the bean. * * @return The constructor injection point */ default ConstructorInjectionPoint<T> getConstructor() { return new ConstructorInjectionPoint<>() { @Override public Argument<?>[] getArguments() { return Argument.ZERO_ARGUMENTS; } @Override public BeanDefinition<T> getDeclaringBean() { return BeanDefinition.this; } @Override public String toString() { return getDeclaringBeanType().getName() + "(" + Argument.toString(getArguments()) + ")"; } }; } /** * @return All required components for this entity definition */ default Collection<Class<?>> getRequiredComponents() { return Collections.emptyList(); } /** * All methods that require injection. This is a subset of all the methods in the class. * * @return The required properties */ default Collection<MethodInjectionPoint<T, ?>> getInjectedMethods() { return Collections.emptyList(); } /** * All the fields that require injection. * * @return The required fields */ default Collection<FieldInjectionPoint<T, ?>> getInjectedFields() { return Collections.emptyList(); } /** * All the methods that should be called once the bean has been fully initialized and constructed. * * @return Methods to call post construct */ default Collection<MethodInjectionPoint<T, ?>> getPostConstructMethods() { return Collections.emptyList(); } /** * All the methods that should be called when the object is to be destroyed. * * @return Methods to call pre-destroy */ default Collection<MethodInjectionPoint<T, ?>> getPreDestroyMethods() { return Collections.emptyList(); } /** * @return The
BeanDefinition
java
spring-projects__spring-framework
spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/beans/MultiplePrototypesInSpringContextTestBean.java
{ "start": 687, "end": 756 }
class ____ extends TestBean { }
MultiplePrototypesInSpringContextTestBean
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java
{ "start": 995, "end": 4020 }
class ____ extends AbstractPropertyResolver { private final @Nullable PropertySources propertySources; /** * Create a new resolver against the given property sources. * @param propertySources the set of {@link PropertySource} objects to use */ public PropertySourcesPropertyResolver(@Nullable PropertySources propertySources) { this.propertySources = propertySources; } @Override public boolean containsProperty(String key) { if (this.propertySources != null) { for (PropertySource<?> propertySource : this.propertySources) { if (propertySource.containsProperty(key)) { return true; } } } return false; } @Override public @Nullable String getProperty(String key) { return getProperty(key, String.class, true); } @Override public <T> @Nullable T getProperty(String key, Class<T> targetValueType) { return getProperty(key, targetValueType, true); } @Override protected @Nullable String getPropertyAsRawString(String key) { return getProperty(key, String.class, false); } protected <T> @Nullable T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) { if (this.propertySources != null) { for (PropertySource<?> propertySource : this.propertySources) { if (logger.isTraceEnabled()) { logger.trace("Searching for key '" + key + "' in PropertySource '" + propertySource.getName() + "'"); } Object value = propertySource.getProperty(key); if (value != null) { if (resolveNestedPlaceholders) { if (value instanceof String string) { value = resolveNestedPlaceholders(string); } else if ((value instanceof CharSequence cs) && (String.class.equals(targetValueType) || CharSequence.class.equals(targetValueType))) { value = resolveNestedPlaceholders(cs.toString()); } } logKeyFound(key, propertySource, value); return convertValueIfNecessary(value, targetValueType); } } } if (logger.isTraceEnabled()) { logger.trace("Could not find key '" + key + "' in any property source"); } return null; } /** * Log the given key as found in the given {@link PropertySource}, resulting in * the given value. * <p>The default implementation writes a debug log message with key and source. * As of 4.3.3, this does not log the value anymore in order to avoid accidental * logging of sensitive settings. Subclasses may override this method to change * the log level and/or log message, including the property's value if desired. * @param key the key found * @param propertySource the {@code PropertySource} that the key has been found in * @param value the corresponding value * @since 4.3.1 */ protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) { if (logger.isDebugEnabled()) { logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName() + "' with value of type " + value.getClass().getSimpleName()); } } }
PropertySourcesPropertyResolver
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java
{ "start": 994, "end": 1701 }
class ____ implementing custom {@link NamespaceHandler NamespaceHandlers}. * Parsing and decorating of individual {@link Node Nodes} is done via {@link BeanDefinitionParser} * and {@link BeanDefinitionDecorator} strategy interfaces, respectively. * * <p>Provides the {@link #registerBeanDefinitionParser} and {@link #registerBeanDefinitionDecorator} * methods for registering a {@link BeanDefinitionParser} or {@link BeanDefinitionDecorator} * to handle a specific element. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 * @see #registerBeanDefinitionParser(String, BeanDefinitionParser) * @see #registerBeanDefinitionDecorator(String, BeanDefinitionDecorator) */ public abstract
for
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/EnumMappingOptions.java
{ "start": 912, "end": 5002 }
class ____ extends DelegatingOptions { private final EnumMappingGem enumMapping; private final boolean inverse; private final boolean valid; private EnumMappingOptions(EnumMappingGem enumMapping, boolean inverse, boolean valid, DelegatingOptions next) { super( next ); this.enumMapping = enumMapping; this.inverse = inverse; this.valid = valid; } @Override public boolean hasAnnotation() { return enumMapping != null; } public boolean isValid() { return valid; } public boolean hasNameTransformationStrategy() { return hasAnnotation() && Strings.isNotEmpty( getNameTransformationStrategy() ); } public String getNameTransformationStrategy() { return enumMapping.nameTransformationStrategy().getValue(); } public String getNameTransformationConfiguration() { return enumMapping.configuration().getValue(); } @Override public TypeMirror getUnexpectedValueMappingException() { if ( enumMapping != null && enumMapping.unexpectedValueMappingException().hasValue() ) { return enumMapping.unexpectedValueMappingException().getValue(); } return next().getUnexpectedValueMappingException(); } public AnnotationMirror getMirror() { return Optional.ofNullable( enumMapping ).map( EnumMappingGem::mirror ).orElse( null ); } public boolean isInverse() { return inverse; } public EnumMappingOptions inverse() { return new EnumMappingOptions( enumMapping, true, valid, next() ); } public static EnumMappingOptions getInstanceOn(ExecutableElement method, MapperOptions mapperOptions, Map<String, EnumTransformationStrategy> enumTransformationStrategies, FormattingMessager messager) { EnumMappingGem enumMapping = EnumMappingGem.instanceOn( method ); if ( enumMapping == null ) { return new EnumMappingOptions( null, false, true, mapperOptions ); } else if ( !isConsistent( enumMapping, method, enumTransformationStrategies, messager ) ) { return new EnumMappingOptions( null, false, false, mapperOptions ); } return new EnumMappingOptions( enumMapping, false, true, mapperOptions ); } private static boolean isConsistent(EnumMappingGem gem, ExecutableElement method, Map<String, EnumTransformationStrategy> enumTransformationStrategies, FormattingMessager messager) { String strategy = gem.nameTransformationStrategy().getValue(); String configuration = gem.configuration().getValue(); boolean isConsistent = false; if ( Strings.isNotEmpty( strategy ) || Strings.isNotEmpty( configuration ) ) { if ( !enumTransformationStrategies.containsKey( strategy ) ) { String registeredStrategies = Strings.join( enumTransformationStrategies.keySet(), ", " ); messager.printMessage( method, gem.mirror(), gem.nameTransformationStrategy().getAnnotationValue(), ENUMMAPPING_INCORRECT_TRANSFORMATION_STRATEGY, strategy, registeredStrategies ); return false; } else if ( Strings.isEmpty( configuration ) ) { messager.printMessage( method, gem.mirror(), gem.configuration().getAnnotationValue(), ENUMMAPPING_MISSING_CONFIGURATION ); return false; } isConsistent = true; } isConsistent = isConsistent || gem.unexpectedValueMappingException().hasValue(); if ( !isConsistent ) { messager.printMessage( method, gem.mirror(), ENUMMAPPING_NO_ELEMENTS ); } return isConsistent; } }
EnumMappingOptions
java
playframework__playframework
persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java
{ "start": 542, "end": 8291 }
class ____ { @Test public void createDatabase() { Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test"); assertThat(db.getName()).isEqualTo("test"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:test"); db.shutdown(); } @Test public void createDefaultDatabase() { Database db = Databases.createFrom("org.h2.Driver", "jdbc:h2:mem:default"); assertThat(db.getName()).isEqualTo("default"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:default"); db.shutdown(); } @Test public void createConfiguredDatabase() throws Exception { Map<String, String> config = ImmutableMap.of("jndiName", "DefaultDS"); Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test", config); assertThat(db.getName()).isEqualTo("test"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:test"); // Forces the data source initialization, and then JNDI registration. db.getDataSource(); assertThat(JNDI.initialContext().lookup("DefaultDS")).isEqualTo(db.getDataSource()); db.shutdown(); } @Test public void createDefaultInMemoryDatabase() { Database db = Databases.inMemory(); assertThat(db.getName()).isEqualTo("default"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:default"); db.shutdown(); } @Test public void createNamedInMemoryDatabase() { Database db = Databases.inMemory("test"); assertThat(db.getName()).isEqualTo("test"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:test"); db.shutdown(); } @Test public void createInMemoryDatabaseWithUrlOptions() { Map<String, String> options = ImmutableMap.of("MODE", "MySQL"); Map<String, Object> config = ImmutableMap.of(); Database db = Databases.inMemory("test", options, config); assertThat(db.getName()).isEqualTo("test"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:test;MODE=MySQL"); db.shutdown(); } @Test public void createConfiguredInMemoryDatabase() throws Exception { Database db = Databases.inMemoryWith("jndiName", "DefaultDS"); assertThat(db.getName()).isEqualTo("default"); assertThat(db.getUrl()).isEqualTo("jdbc:h2:mem:default"); // Forces the data source initialization, and then JNDI registration. db.getDataSource(); assertThat(JNDI.initialContext().lookup("DefaultDS")).isEqualTo(db.getDataSource()); db.shutdown(); } @Test public void supplyConnections() throws Exception { Database db = Databases.inMemory("test-connection"); try (Connection connection = db.getConnection()) { connection .createStatement() .execute("create table test (id bigint not null, name varchar(255))"); } db.shutdown(); } @Test public void enableAutocommitByDefault() throws Exception { Database db = Databases.inMemory("test-autocommit"); try (Connection c1 = db.getConnection(); Connection c2 = db.getConnection()) { c1.createStatement().execute("create table test (id bigint not null, name varchar(255))"); c1.createStatement().execute("insert into test (id, name) values (1, 'alice')"); ResultSet results = c2.createStatement().executeQuery("select * from test"); assertThat(results.next()).isTrue(); assertThat(results.next()).isFalse(); } db.shutdown(); } @Test public void provideConnectionHelpers() { Database db = Databases.inMemory("test-withConnection"); db.withConnection( c -> { c.createStatement().execute("create table test (id bigint not null, name varchar(255))"); c.createStatement().execute("insert into test (id, name) values (1, 'alice')"); }); boolean result = db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); assertThat(results.next()).isTrue(); assertThat(results.next()).isFalse(); return true; }); assertThat(result).isTrue(); db.shutdown(); } @Test public void provideConnectionHelpersWithAutoCommitIsFalse() { Database db = Databases.inMemory("test-withConnection(autoCommit = false"); db.withConnection( false, c -> { c.createStatement().execute("create table test (id bigint not null, name varchar(255))"); c.createStatement().execute("insert into test (id, name) values (1, 'alice')"); }); boolean result = db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); assertThat(results.next()).isFalse(); return true; }); assertThat(result).isTrue(); db.shutdown(); } @Test public void provideTransactionHelper() { Database db = Databases.inMemory("test-withTransaction"); boolean created = db.withTransaction( c -> { c.createStatement() .execute("create table test (id bigint not null, name varchar(255))"); c.createStatement().execute("insert into test (id, name) values (1, 'alice')"); return true; }); assertThat(created).isTrue(); db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); assertThat(results.next()).isTrue(); assertThat(results.next()).isFalse(); }); try { db.withTransaction( (Connection c) -> { c.createStatement().execute("insert into test (id, name) values (2, 'bob')"); throw new RuntimeException("boom"); }); } catch (Exception e) { assertThat(e.getMessage()).isEqualTo("boom"); } db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); assertThat(results.next()).isTrue(); assertThat(results.next()).isFalse(); }); db.shutdown(); } @Test public void notSupplyConnectionsAfterShutdown() throws Exception { Database db = Databases.inMemory("test-shutdown"); db.getConnection().close(); db.shutdown(); SQLException sqlException = assertThrows(SQLException.class, () -> db.getConnection().close()); assertThat(sqlException.getMessage()).endsWith("has been closed."); } @Test public void useConnectionPoolDataSourceProxyWhenLogSqlIsTrue() throws Exception { Map<String, String> config = ImmutableMap.of("jndiName", "DefaultDS", "logSql", "true"); Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test", config); assertThat(db.getDataSource()).isInstanceOf(ConnectionPoolDataSourceProxy.class); assertThat(JNDI.initialContext().lookup("DefaultDS")) .isInstanceOf(ConnectionPoolDataSourceProxy.class); db.shutdown(); } @Test public void manualSetupTransactionIsolationLevel() throws Exception { Database db = Databases.inMemory("test-withTransaction"); boolean created = db.withTransaction( TransactionIsolationLevel.Serializable, c -> { c.createStatement() .execute("create table test (id bigint not null, name varchar(255))"); c.createStatement().execute("insert into test (id, name) values (1, 'alice')"); return true; }); assertThat(created).isTrue(); db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); assertThat(results.next()).isTrue(); assertThat(results.next()).isFalse(); }); db.shutdown(); } }
DatabaseTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jEmbeddingStoreEndpointBuilderFactory.java
{ "start": 9740, "end": 11921 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final LangChain4jEmbeddingStoreHeaderNameBuilder INSTANCE = new LangChain4jEmbeddingStoreHeaderNameBuilder(); /** * The action to be performed. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * Langchain4jEmbeddingStoreAction}. */ public String langchain4jEmbeddingStoreAction() { return "CamelLangchain4jEmbeddingStoreAction"; } /** * Maximum number of search results to return. * * The option is a: {@code Integer} type. * * Default: 5 * Group: producer * * @return the name of the header {@code * Langchain4jEmbeddingStoreMaxResults}. */ public String langchain4jEmbeddingStoreMaxResults() { return "CamelLangchain4jEmbeddingStoreMaxResults"; } /** * Minimum similarity score for search results. * * The option is a: {@code Double} type. * * Group: producer * * @return the name of the header {@code * Langchain4jEmbeddingStoreMinScore}. */ public String langchain4jEmbeddingStoreMinScore() { return "CamelLangchain4jEmbeddingStoreMinScore"; } /** * Search filter for metadata-based constraints. * * The option is a: {@code * dev.langchain4j.store.embedding.filter.Filter} type. * * Group: producer * * @return the name of the header {@code * Langchain4jEmbeddingStoreFilter}. */ public String langchain4jEmbeddingStoreFilter() { return "CamelLangchain4jEmbeddingStoreFilter"; } } static LangChain4jEmbeddingStoreEndpointBuilder endpointBuilder(String componentName, String path) {
LangChain4jEmbeddingStoreHeaderNameBuilder
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/scripting/xmltags/XMLScriptBuilder.java
{ "start": 6513, "end": 7471 }
class ____ implements NodeHandler { public ForEachHandler() { // Prevent Synthetic Access } @Override public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) { MixedSqlNode mixedSqlNode = parseDynamicTags(nodeToHandle); String collection = nodeToHandle.getStringAttribute("collection"); Boolean nullable = nodeToHandle.getBooleanAttribute("nullable"); String item = nodeToHandle.getStringAttribute("item"); String index = nodeToHandle.getStringAttribute("index"); String open = nodeToHandle.getStringAttribute("open"); String close = nodeToHandle.getStringAttribute("close"); String separator = nodeToHandle.getStringAttribute("separator"); ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, open, close, separator); targetContents.add(forEachSqlNode); } } private
ForEachHandler
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SourceStreamTaskTest.java
{ "start": 39098, "end": 40014 }
class ____<T> extends FromElementsFunction<T> { private static final long serialVersionUID = 8713065281092996067L; private static MultiShotLatch dataProcessing = new MultiShotLatch(); private static MultiShotLatch cancellationWaiting = new MultiShotLatch(); public CancelTestSource(TypeSerializer<T> serializer, T... elements) throws IOException { super(serializer, elements); } @Override public void run(SourceContext<T> ctx) throws Exception { super.run(ctx); dataProcessing.trigger(); cancellationWaiting.await(); } @Override public void cancel() { super.cancel(); cancellationWaiting.trigger(); } public static MultiShotLatch getDataProcessing() { return dataProcessing; } } private static final
CancelTestSource
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/BufferHolder.java
{ "start": 1744, "end": 4189 }
class ____ { private static final int ARRAY_MAX = ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH; // buffer is guarantee to be word-aligned since UnsafeRow assumes each field is word-aligned. private byte[] buffer; private int cursor = Platform.BYTE_ARRAY_OFFSET; private final UnsafeRow row; private final int fixedSize; BufferHolder(UnsafeRow row) { this(row, 64); } BufferHolder(UnsafeRow row, int initialSize) { int bitsetWidthInBytes = UnsafeRow.calculateBitSetWidthInBytes(row.numFields()); if (row.numFields() > (ARRAY_MAX - initialSize - bitsetWidthInBytes) / 8) { throw new SparkUnsupportedOperationException( "_LEGACY_ERROR_TEMP_3130", Map.of("numFields", String.valueOf(row.numFields()))); } this.fixedSize = bitsetWidthInBytes + 8 * row.numFields(); int roundedSize = ByteArrayMethods.roundNumberOfBytesToNearestWord(fixedSize + initialSize); this.buffer = new byte[roundedSize]; this.row = row; this.row.pointTo(buffer, buffer.length); } /** * Grows the buffer by at least neededSize and points the row to the buffer. */ void grow(int neededSize) { if (neededSize < 0) { throw new SparkIllegalArgumentException( "_LEGACY_ERROR_TEMP_3198", Map.of("neededSize", String.valueOf(neededSize))); } if (neededSize > ARRAY_MAX - totalSize()) { throw new SparkIllegalArgumentException( "_LEGACY_ERROR_TEMP_3199", Map.of("neededSize", String.valueOf(neededSize), "arrayMax", String.valueOf(ARRAY_MAX))); } final int length = totalSize() + neededSize; if (buffer.length < length) { // This will not happen frequently, because the buffer is re-used. int newLength = length < ARRAY_MAX / 2 ? length * 2 : ARRAY_MAX; int roundedSize = ByteArrayMethods.roundNumberOfBytesToNearestWord(newLength); final byte[] tmp = new byte[roundedSize]; Platform.copyMemory( buffer, Platform.BYTE_ARRAY_OFFSET, tmp, Platform.BYTE_ARRAY_OFFSET, totalSize()); buffer = tmp; row.pointTo(buffer, buffer.length); } } byte[] getBuffer() { return buffer; } int getCursor() { return cursor; } void increaseCursor(int val) { cursor += val; } void reset() { cursor = Platform.BYTE_ARRAY_OFFSET + fixedSize; } int totalSize() { return cursor - Platform.BYTE_ARRAY_OFFSET; } }
BufferHolder
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportDeleteModelSnapshotAction.java
{ "start": 1511, "end": 5302 }
class ____ extends HandledTransportAction<DeleteModelSnapshotAction.Request, AcknowledgedResponse> { private static final Logger logger = LogManager.getLogger(TransportDeleteModelSnapshotAction.class); private final Client client; private final JobManager jobManager; private final JobResultsProvider jobResultsProvider; private final AnomalyDetectionAuditor auditor; @Inject public TransportDeleteModelSnapshotAction( TransportService transportService, ActionFilters actionFilters, JobResultsProvider jobResultsProvider, Client client, JobManager jobManager, AnomalyDetectionAuditor auditor ) { super( DeleteModelSnapshotAction.NAME, transportService, actionFilters, DeleteModelSnapshotAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.client = client; this.jobManager = jobManager; this.jobResultsProvider = jobResultsProvider; this.auditor = auditor; } @Override protected void doExecute(Task task, DeleteModelSnapshotAction.Request request, ActionListener<AcknowledgedResponse> listener) { // Verify the snapshot exists jobResultsProvider.modelSnapshots(request.getJobId(), 0, 1, null, null, null, true, request.getSnapshotId(), null, page -> { List<ModelSnapshot> deleteCandidates = page.results(); if (deleteCandidates.size() > 1) { logger.warn( "More than one model found for [job_id: " + request.getJobId() + ", snapshot_id: " + request.getSnapshotId() + "] tuple." ); } if (deleteCandidates.isEmpty()) { listener.onFailure( new ResourceNotFoundException( Messages.getMessage(Messages.REST_NO_SUCH_MODEL_SNAPSHOT, request.getSnapshotId(), request.getJobId()) ) ); return; } ModelSnapshot deleteCandidate = deleteCandidates.get(0); // Verify the snapshot is not being used jobManager.getJob(request.getJobId(), listener.delegateFailureAndWrap((delegate, job) -> { String currentModelInUse = job.getModelSnapshotId(); if (currentModelInUse != null && currentModelInUse.equals(request.getSnapshotId())) { delegate.onFailure( new IllegalArgumentException( Messages.getMessage(Messages.REST_CANNOT_DELETE_HIGHEST_PRIORITY, request.getSnapshotId(), request.getJobId()) ) ); return; } // Delete the snapshot and any associated state files JobDataDeleter deleter = new JobDataDeleter(client, request.getJobId()); deleter.deleteModelSnapshots(Collections.singletonList(deleteCandidate), delegate.safeMap(bulkResponse -> { String msg = Messages.getMessage( Messages.JOB_AUDIT_SNAPSHOT_DELETED, deleteCandidate.getSnapshotId(), deleteCandidate.getDescription() ); auditor.info(request.getJobId(), msg); logger.debug(() -> format("[%s] %s", request.getJobId(), msg)); // We don't care about the bulk response, just that it succeeded return AcknowledgedResponse.TRUE; })); })); }, listener::onFailure); } }
TransportDeleteModelSnapshotAction
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inject/ScopeAnnotationOnInterfaceOrAbstractClass.java
{ "start": 1915, "end": 1969 }
class ____ not allowed", severity = WARNING) public
is
java
quarkusio__quarkus
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/ui/CustomConfigTest.java
{ "start": 333, "end": 907 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset("quarkus.smallrye-graphql.ui.root-path=/custom"), "application.properties")); @Test public void shouldUseCustomConfig() { RestAssured.when().get("/custom").then().statusCode(200).body(containsString("SmallRye GraphQL")); RestAssured.when().get("/custom/index.html").then().statusCode(200).body(containsString("SmallRye GraphQL")); } }
CustomConfigTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/CatalogStoreFactory.java
{ "start": 1734, "end": 2007 }
class ____ implements CatalogStore { * * private JdbcConnectionPool jdbcConnectionPool; * public JdbcCatalogStore(JdbcConnectionPool jdbcConnectionPool) { * this.jdbcConnectionPool = jdbcConnectionPool; * } * ... * } * * public
JdbcCatalogStore
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/starrocks/StarrocksResourceTest.java
{ "start": 160, "end": 431 }
class ____ extends SQLResourceTest { public StarrocksResourceTest() { super(DbType.starrocks); } @Test public void starrocks_parse() throws Exception { fileTest(0, 999, i -> "bvt/parser/starrocks/" + i + ".txt"); } }
StarrocksResourceTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/events/PreDeleteEventListenerTest.java
{ "start": 1989, "end": 2224 }
class ____ { @Id String id = UUID.randomUUID().toString(); @ManyToMany(fetch = LAZY) Set<Child> children = new HashSet<>(); public Set<Child> getChildren() { return children; } } @Entity(name= "Child") public static
Parent
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/mutable/MutableLongTest.java
{ "start": 1188, "end": 8693 }
class ____ extends AbstractLangTest { @Test void testAddAndGetValueObject() { final MutableLong mutableLong = new MutableLong(0L); final long result = mutableLong.addAndGet(Long.valueOf(1L)); assertEquals(1L, result); assertEquals(1L, mutableLong.longValue()); } @Test void testAddAndGetValuePrimitive() { final MutableLong mutableLong = new MutableLong(0L); final long result = mutableLong.addAndGet(1L); assertEquals(1L, result); assertEquals(1L, mutableLong.longValue()); } @Test void testAddValueObject() { final MutableLong mutNum = new MutableLong(1); mutNum.add(Long.valueOf(1)); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } @Test void testAddValuePrimitive() { final MutableLong mutNum = new MutableLong(1); mutNum.add(1); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } @Test void testCompareTo() { final MutableLong mutNum = new MutableLong(0); assertEquals(0, mutNum.compareTo(new MutableLong(0))); assertEquals(+1, mutNum.compareTo(new MutableLong(-1))); assertEquals(-1, mutNum.compareTo(new MutableLong(1))); } @Test void testCompareToNull() { final MutableLong mutNum = new MutableLong(0); assertNullPointerException(() -> mutNum.compareTo(null)); } @Test void testConstructorNull() { assertNullPointerException(() -> new MutableLong((Number) null)); } @Test void testConstructors() { assertEquals(0, new MutableLong().longValue()); assertEquals(1, new MutableLong(1).longValue()); assertEquals(2, new MutableLong(Long.valueOf(2)).longValue()); assertEquals(3, new MutableLong(new MutableLong(3)).longValue()); assertEquals(2, new MutableLong("2").longValue()); } @Test void testDecrement() { final MutableLong mutNum = new MutableLong(1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } @Test void testDecrementAndGet() { final MutableLong mutNum = new MutableLong(1L); final long result = mutNum.decrementAndGet(); assertEquals(0, result); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } @Test void testEquals() { final MutableLong mutNumA = new MutableLong(0); final MutableLong mutNumB = new MutableLong(0); final MutableLong mutNumC = new MutableLong(1); assertEquals(mutNumA, mutNumA); assertEquals(mutNumA, mutNumB); assertEquals(mutNumB, mutNumA); assertEquals(mutNumB, mutNumB); assertNotEquals(mutNumA, mutNumC); assertNotEquals(mutNumB, mutNumC); assertEquals(mutNumC, mutNumC); assertNotEquals(null, mutNumA); assertNotEquals(mutNumA, Long.valueOf(0)); assertNotEquals("0", mutNumA); } @Test void testGetAndAddValueObject() { final MutableLong mutableLong = new MutableLong(0L); final long result = mutableLong.getAndAdd(Long.valueOf(1L)); assertEquals(0L, result); assertEquals(1L, mutableLong.longValue()); } @Test void testGetAndAddValuePrimitive() { final MutableLong mutableLong = new MutableLong(0L); final long result = mutableLong.getAndAdd(1L); assertEquals(0L, result); assertEquals(1L, mutableLong.longValue()); } @Test void testGetAndDecrement() { final MutableLong mutNum = new MutableLong(1L); final long result = mutNum.getAndDecrement(); assertEquals(1, result); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } @Test void testGetAndIncrement() { final MutableLong mutNum = new MutableLong(1L); final long result = mutNum.getAndIncrement(); assertEquals(1, result); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } @Test void testGetSet() { final MutableLong mutNum = new MutableLong(0); assertEquals(0, new MutableLong().longValue()); assertEquals(Long.valueOf(0), new MutableLong().get()); assertEquals(Long.valueOf(0), new MutableLong().getValue()); mutNum.setValue(1); assertEquals(1, mutNum.longValue()); assertEquals(Long.valueOf(1), mutNum.get()); assertEquals(Long.valueOf(1), mutNum.getValue()); mutNum.setValue(Long.valueOf(2)); assertEquals(2, mutNum.longValue()); assertEquals(Long.valueOf(2), mutNum.get()); assertEquals(Long.valueOf(2), mutNum.getValue()); mutNum.setValue(new MutableLong(3)); assertEquals(3, mutNum.longValue()); assertEquals(Long.valueOf(3), mutNum.get()); assertEquals(Long.valueOf(3), mutNum.getValue()); } @Test void testHashCode() { final MutableLong mutNumA = new MutableLong(0); final MutableLong mutNumB = new MutableLong(0); final MutableLong mutNumC = new MutableLong(1); assertEquals(mutNumA.hashCode(), mutNumA.hashCode()); assertEquals(mutNumA.hashCode(), mutNumB.hashCode()); assertNotEquals(mutNumA.hashCode(), mutNumC.hashCode()); assertEquals(mutNumA.hashCode(), Long.valueOf(0).hashCode()); } @Test void testIncrement() { final MutableLong mutNum = new MutableLong(1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } @Test void testIncrementAndGet() { final MutableLong mutNum = new MutableLong(1L); final long result = mutNum.incrementAndGet(); assertEquals(2, result); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } @Test void testPrimitiveValues() { final MutableLong mutNum = new MutableLong(1L); assertEquals(1.0F, mutNum.floatValue()); assertEquals(1.0, mutNum.doubleValue()); assertEquals((byte) 1, mutNum.byteValue()); assertEquals((short) 1, mutNum.shortValue()); assertEquals(1, mutNum.intValue()); assertEquals(1L, mutNum.longValue()); } @Test void testSetNull() { final MutableLong mutNum = new MutableLong(0); assertNullPointerException(() -> mutNum.setValue(null)); } @Test void testSubtractValueObject() { final MutableLong mutNum = new MutableLong(1); mutNum.subtract(Long.valueOf(1)); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } @Test void testSubtractValuePrimitive() { final MutableLong mutNum = new MutableLong(1); mutNum.subtract(1); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } @Test void testToLong() { assertEquals(Long.valueOf(0L), new MutableLong(0L).toLong()); assertEquals(Long.valueOf(123L), new MutableLong(123L).toLong()); } @Test void testToString() { assertEquals("0", new MutableLong(0).toString()); assertEquals("10", new MutableLong(10).toString()); assertEquals("-123", new MutableLong(-123).toString()); } }
MutableLongTest
java
quarkusio__quarkus
test-framework/common/src/test/java/io/quarkus/test/common/TestResourceManagerTest.java
{ "start": 6216, "end": 7168 }
class ____ implements QuarkusTestResourceLifecycleManager { @Override public Map<String, String> start() { parallelTestResourceRunned = true; return Collections.singletonMap("key2", "value2"); } @Override public void stop() { } @Override public int order() { return 2; } } @ParameterizedTest @ValueSource(classes = { RepeatableAnnotationBasedTestResourcesTest.class, RepeatableAnnotationBasedTestResourcesTest2.class }) void testAnnotationBased(Class<?> clazz) { TestResourceManager manager = new TestResourceManager(clazz); manager.init("test"); Map<String, String> props = manager.start(); Assertions.assertEquals("value", props.get("annotationkey1")); Assertions.assertEquals("value", props.get("annotationkey2")); } public static
SecondParallelQuarkusTestResource
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java
{ "start": 13504, "end": 13628 }
class ____ { StringNameHandler(BeanFactory beanFactory) { beanFactory.getBean("test-string"); } } }
StringNameHandler
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/bidirectional/BiDirectionalOneToOneFetchTest.java
{ "start": 7224, "end": 7507 }
class ____ { @Id private Long id; @OneToOne(mappedBy = "b", fetch = FetchType.EAGER) private EntityA a; public EntityB() { } public EntityB(Long id) { this.id = id; } public EntityA getA() { return a; } } @Entity(name = "EntityC") public static
EntityB
java
quarkusio__quarkus
integration-tests/mongodb-client/src/test/java/io/quarkus/it/mongodb/PojoResourceTest.java
{ "start": 562, "end": 1518 }
class ____ { private static Jsonb jsonb; @BeforeAll public static void giveMeAMapper() { jsonb = Utils.initialiseJsonb(); } @AfterAll public static void releaseMapper() throws Exception { jsonb.close(); } @BeforeEach public void clearCollection() { Response response = RestAssured .given() .delete("/pojos") .andReturn(); Assertions.assertEquals(200, response.statusCode()); } @Test public void testPojoEndpoint() { Pojo pojo = new Pojo(); pojo.description = "description"; pojo.optionalString = Optional.of("optional"); given().header("Content-Type", "application/json") .body(jsonb.toJson(pojo)) .when().post("/pojos") .then().statusCode(201); given().get("/pojos").then().statusCode(200).body("size()", is(1)); } }
PojoResourceTest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java
{ "start": 2626, "end": 18035 }
class ____ { private PostProcessorRegistrationDelegate() { } public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // WARNING: Although it may appear that the body of this method can be easily // refactored to avoid the use of multiple loops and multiple lists, the use // of multiple lists and multiple passes over the names of processors is // intentional. We must ensure that we honor the contracts for PriorityOrdered // and Ordered processors. Specifically, we must NOT cause processors to be // instantiated (via getBean() invocations) or registered in the ApplicationContext // in the wrong order. // // Before submitting a pull request (PR) to change this method, please review the // list of all declined PRs involving changes to PostProcessorRegistrationDelegate // to ensure that your proposal does not result in a breaking change: // https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22 // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set<String> processedBeans = new HashSet<>(); if (beanFactory instanceof BeanDefinitionRegistry registry) { List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) { registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { regularPostProcessors.add(postProcessor); } } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup()); currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup()); currentRegistryProcessors.clear(); // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. boolean reiterate = true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup()); currentRegistryProcessors.clear(); } // Now, invoke the postProcessBeanFactory callback of all processors handled so far. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // Finally, invoke all other BeanFactoryPostProcessors. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // Clear cached merged bean definitions since the post-processors might have // modified the original metadata, for example, replacing placeholders in values... beanFactory.clearMetadataCache(); } public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { // WARNING: Although it may appear that the body of this method can be easily // refactored to avoid the use of multiple loops and multiple lists, the use // of multiple lists and multiple passes over the names of processors is // intentional. We must ensure that we honor the contracts for PriorityOrdered // and Ordered processors. Specifically, we must NOT cause processors to be // instantiated (via getBean() invocations) or registered in the ApplicationContext // in the wrong order. // // Before submitting a pull request (PR) to change this method, please review the // list of all declined PRs involving changes to PostProcessorRegistrationDelegate // to ensure that your proposal does not result in a breaking change: // https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs a warn message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor( new BeanPostProcessorChecker(beanFactory, postProcessorNames, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); } /** * Load and sort the post-processors of the specified type. * @param beanFactory the bean factory to use * @param beanPostProcessorType the post-processor type * @param <T> the post-processor type * @return a list of sorted post-processors for the specified type */ static <T extends BeanPostProcessor> List<T> loadBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, Class<T> beanPostProcessorType) { String[] postProcessorNames = beanFactory.getBeanNamesForType(beanPostProcessorType, true, false); List<T> postProcessors = new ArrayList<>(); for (String ppName : postProcessorNames) { postProcessors.add(beanFactory.getBean(ppName, beanPostProcessorType)); } sortPostProcessors(postProcessors, beanFactory); return postProcessors; } /** * Selectively invoke {@link MergedBeanDefinitionPostProcessor} instances * registered in the specified bean factory, resolving bean definitions and * any attributes if necessary as well as any inner bean definitions that * they may contain. * @param beanFactory the bean factory to use */ static void invokeMergedBeanDefinitionPostProcessors(DefaultListableBeanFactory beanFactory) { new MergedBeanDefinitionPostProcessorInvoker(beanFactory).invokeMergedBeanDefinitionPostProcessors(); } private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) { // Nothing to sort? if (postProcessors.size() <= 1) { return; } Comparator<Object> comparatorToUse = null; if (beanFactory instanceof DefaultListableBeanFactory dlbf) { comparatorToUse = dlbf.getDependencyComparator(); } if (comparatorToUse == null) { comparatorToUse = OrderComparator.INSTANCE; } postProcessors.sort(comparatorToUse); } /** * Invoke the given BeanDefinitionRegistryPostProcessor beans. */ private static void invokeBeanDefinitionRegistryPostProcessors( Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) { for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) { StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process") .tag("postProcessor", postProcessor::toString); postProcessor.postProcessBeanDefinitionRegistry(registry); postProcessBeanDefRegistry.end(); } } /** * Invoke the given BeanFactoryPostProcessor beans. */ private static void invokeBeanFactoryPostProcessors( Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) { for (BeanFactoryPostProcessor postProcessor : postProcessors) { StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process") .tag("postProcessor", postProcessor::toString); postProcessor.postProcessBeanFactory(beanFactory); postProcessBeanFactory.end(); } } /** * Register the given BeanPostProcessor beans. */ private static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, List<? extends BeanPostProcessor> postProcessors) { if (beanFactory instanceof AbstractBeanFactory abstractBeanFactory) { // Bulk addition is more efficient against our CopyOnWriteArrayList there abstractBeanFactory.addBeanPostProcessors(postProcessors); } else { for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); } } } /** * BeanPostProcessor that logs a warn message when a bean is created during * BeanPostProcessor instantiation, i.e. when a bean is not eligible for * getting processed by all BeanPostProcessors. */ private static final
PostProcessorRegistrationDelegate
java
apache__flink
flink-filesystems/flink-s3-fs-base/src/test/java/org/apache/flink/fs/s3/common/S5CmdOnMinioITCase.java
{ "start": 3709, "end": 11524 }
class ____ { private static final int CHECKPOINT_INTERVAL = 100; @RegisterExtension @Order(1) private static final AllCallbackWrapper<TestContainerExtension<MinioTestContainer>> MINIO_EXTENSION = new AllCallbackWrapper<>(new TestContainerExtension<>(MinioTestContainer::new)); @RegisterExtension @Order(2) private static final MiniClusterExtension MINI_CLUSTER_EXTENSION = new MiniClusterExtension( () -> { final Configuration configuration = createConfiguration(); FileSystem.initialize(configuration, null); return new MiniClusterResourceConfiguration.Builder() .setNumberSlotsPerTaskManager(4) .setConfiguration(configuration) .build(); }); private static Configuration createConfiguration() { final Configuration config = new Configuration(); getMinioContainer().setS3ConfigOptions(config); File credentialsFile = new File(temporaryDirectory, "credentials"); try { // It looks like on the CI machines s5cmd by default is using some other default // authentication mechanism, that takes precedence over passing secret and access keys // via environment variables. For example maybe there exists a credentials file in the // default location with secrets from the S3, not MinIO. To circumvent it, lets use our // own credentials file with secrets for MinIO. checkState(credentialsFile.createNewFile()); getMinioContainer().writeCredentialsFile(credentialsFile); config.set( S5CMD_EXTRA_ARGS, S5CMD_EXTRA_ARGS.defaultValue() + " --credentials-file " + credentialsFile.getAbsolutePath()); config.set(AbstractS3FileSystemFactory.S5CMD_PATH, getS5CmdPath()); } catch (IOException ex) { throw new RuntimeException(ex); } config.set(CHECKPOINTS_DIRECTORY, createS3URIWithSubPath("checkpoints")); // Effectively disable using ByteStreamStateHandle to ensure s5cmd is being used config.set(FS_SMALL_FILE_THRESHOLD, MemorySize.parse("1b")); return config; } @TempDir public static File temporaryDirectory; private static MinioTestContainer getMinioContainer() { return MINIO_EXTENSION.getCustomExtension().getTestContainer(); } @BeforeAll static void prepareS5Cmd() throws Exception { Path s5CmdTgz = Paths.get(temporaryDirectory.getPath(), "s5cmd.tar.gz"); MessageDigest md = MessageDigest.getInstance("MD5"); final URI uri; String expectedMd5; switch (OperatingSystem.getCurrentOperatingSystem()) { case LINUX: uri = new URI( "https://github.com/peak/s5cmd/releases/download/v2.2.2/s5cmd_2.2.2_Linux-64bit.tar.gz"); expectedMd5 = "66549a8bef5183f6ee65bf793aefca0e"; break; case MAC_OS: uri = new URI( "https://github.com/peak/s5cmd/releases/download/v2.2.2/s5cmd_2.2.2_macOS-64bit.tar.gz"); expectedMd5 = "c90292139a9bb8e6643f8970d858c7b9"; break; default: throw new UnsupportedOperationException( String.format( "Unsupported operating system [%s] for this test.", OperatingSystem.getCurrentOperatingSystem())); } try (InputStream inputStream = uri.toURL().openStream()) { DigestInputStream digestInputStream = new DigestInputStream(inputStream, md); Files.copy(digestInputStream, s5CmdTgz, StandardCopyOption.REPLACE_EXISTING); } String actualMd5 = digestToHexMd5(md.digest()); checkState( expectedMd5.equals(actualMd5), "Expected md5 [%s] and actual md5 [%s] differ", expectedMd5, actualMd5); CompressionUtils.extractTarFile(s5CmdTgz.toString(), temporaryDirectory.getPath()); } private static String digestToHexMd5(byte[] digest) { StringBuffer sb = new StringBuffer(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } @AfterAll static void unsetFileSystem() { FileSystem.initialize(new Configuration(), null); } @Test void testS5CmdConfigurationIsUsed(@InjectMiniCluster MiniCluster flinkCluster) throws Exception { String moveFrom = getS5CmdPath(); String moveTo = moveFrom + "-moved"; new File(moveFrom).renameTo(new File(moveTo)); try { testRecoveryWithS5Cmd(flinkCluster); } catch (Exception e) { ExceptionUtils.assertThrowable( e, throwable -> throwable.getMessage().contains("Unable to find s5cmd")); } finally { new File(moveTo).renameTo(new File(moveFrom)); } } @Test void testRecoveryWithS5Cmd(@InjectMiniCluster MiniCluster flinkCluster) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(2); env.enableCheckpointing(CHECKPOINT_INTERVAL); RestartStrategyUtils.configureFixedDelayRestartStrategy(env, 1, 0L); StateBackendUtils.configureRocksDBStateBackend(env); // Disable changelog, to make sure state is stored in the RocksDB, not in changelog, as // currently only RocksDB is using s5cmd. env.enableChangelogStateBackend(false); try (CloseableIterator<Record> results = env.addSource(new FailingSource()) .keyBy(x -> x.key) .reduce( (ReduceFunction<Record>) (record1, record2) -> { checkState(record1.key == record2.key); return new Record( record1.key, record1.value + record2.value); }) .collectAsync()) { env.execute(); // verify that the max emitted values are exactly the sum of all emitted records long maxValue1 = 0; long maxValue2 = 0; while (results.hasNext()) { Record next = results.next(); if (next.key == FailingSource.FIRST_KEY) { maxValue1 = Math.max(maxValue1, next.value); } else if (next.key == FailingSource.SECOND_KEY) { maxValue2 = Math.max(maxValue2, next.value); } else { throw new Exception("This shouldn't happen: " + next); } } assertThat(maxValue1) .isEqualTo( (FailingSource.LAST_EMITTED_VALUE + 1) * FailingSource.LAST_EMITTED_VALUE / 2); assertThat(maxValue2) .isEqualTo( (FailingSource.LAST_EMITTED_VALUE + 1) * FailingSource.LAST_EMITTED_VALUE); } } /** Test record. */ public static
S5CmdOnMinioITCase
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
{ "start": 10501, "end": 11101 }
class ____ abstract or an interface * @throws InvocationTargetException if an exception is thrown by the constructor * @throws ExceptionInInitializerError if an exception was thrown while initializing the class * @since 2.7 */ public static <T> T newInstanceOf(final Class<T> clazz) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Constructor<T> constructor = clazz.getDeclaredConstructor(); return constructor.newInstance(); } /** * Creates an instance of the provided
is
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/QueryComparingAssociationToNullTest.java
{ "start": 1200, "end": 2309 }
class ____ { @Test public void testQuery(SessionFactoryScope scope) { LocalDate date = LocalDate.now(); scope.inTransaction( session -> { Child child = new Child( 1, "first" ); Parent parent = new Parent( 1, date, child ); session.persist( child ); session.persist( parent ); } ); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT p FROM Parent p WHERE p.child = NULL ", Parent.class ); query.getResultList(); } ); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT p FROM Parent p WHERE p.child = NULL OR p.date = :date ", Parent.class ).setParameter( "date", date ); assertThat(query.getResultList().size()).isEqualTo( 1 ); } ); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT p FROM Parent p WHERE p.child = NULL OR p.date = NULL ", Parent.class ); query.getResultList(); } ); } @Entity(name = "Parent") public static
QueryComparingAssociationToNullTest
java
apache__camel
components/camel-ai/camel-torchserve/src/generated/java/org/apache/camel/component/torchserve/TorchServeComponentConfigurer.java
{ "start": 737, "end": 10626 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private org.apache.camel.component.torchserve.TorchServeConfiguration getOrCreateConfiguration(TorchServeComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.torchserve.TorchServeConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { TorchServeComponent target = (TorchServeComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.torchserve.TorchServeConfiguration.class, value)); return true; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": target.setHealthCheckConsumerEnabled(property(camelContext, boolean.class, value)); return true; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": target.setHealthCheckProducerEnabled(property(camelContext, boolean.class, value)); return true; case "inferenceaddress": case "inferenceAddress": getOrCreateConfiguration(target).setInferenceAddress(property(camelContext, java.lang.String.class, value)); return true; case "inferencekey": case "inferenceKey": getOrCreateConfiguration(target).setInferenceKey(property(camelContext, java.lang.String.class, value)); return true; case "inferenceport": case "inferencePort": getOrCreateConfiguration(target).setInferencePort(property(camelContext, int.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "listlimit": case "listLimit": getOrCreateConfiguration(target).setListLimit(property(camelContext, int.class, value)); return true; case "listnextpagetoken": case "listNextPageToken": getOrCreateConfiguration(target).setListNextPageToken(property(camelContext, java.lang.String.class, value)); return true; case "managementaddress": case "managementAddress": getOrCreateConfiguration(target).setManagementAddress(property(camelContext, java.lang.String.class, value)); return true; case "managementkey": case "managementKey": getOrCreateConfiguration(target).setManagementKey(property(camelContext, java.lang.String.class, value)); return true; case "managementport": case "managementPort": getOrCreateConfiguration(target).setManagementPort(property(camelContext, int.class, value)); return true; case "metricsaddress": case "metricsAddress": getOrCreateConfiguration(target).setMetricsAddress(property(camelContext, java.lang.String.class, value)); return true; case "metricsname": case "metricsName": getOrCreateConfiguration(target).setMetricsName(property(camelContext, java.lang.String.class, value)); return true; case "metricsport": case "metricsPort": getOrCreateConfiguration(target).setMetricsPort(property(camelContext, int.class, value)); return true; case "modelname": case "modelName": getOrCreateConfiguration(target).setModelName(property(camelContext, java.lang.String.class, value)); return true; case "modelversion": case "modelVersion": getOrCreateConfiguration(target).setModelVersion(property(camelContext, java.lang.String.class, value)); return true; case "registeroptions": case "registerOptions": getOrCreateConfiguration(target).setRegisterOptions(property(camelContext, org.apache.camel.component.torchserve.client.model.RegisterOptions.class, value)); return true; case "scaleworkeroptions": case "scaleWorkerOptions": getOrCreateConfiguration(target).setScaleWorkerOptions(property(camelContext, org.apache.camel.component.torchserve.client.model.ScaleWorkerOptions.class, value)); return true; case "unregisteroptions": case "unregisterOptions": getOrCreateConfiguration(target).setUnregisterOptions(property(camelContext, org.apache.camel.component.torchserve.client.model.UnregisterOptions.class, value)); return true; case "url": getOrCreateConfiguration(target).setUrl(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "configuration": return org.apache.camel.component.torchserve.TorchServeConfiguration.class; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return boolean.class; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return boolean.class; case "inferenceaddress": case "inferenceAddress": return java.lang.String.class; case "inferencekey": case "inferenceKey": return java.lang.String.class; case "inferenceport": case "inferencePort": return int.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "listlimit": case "listLimit": return int.class; case "listnextpagetoken": case "listNextPageToken": return java.lang.String.class; case "managementaddress": case "managementAddress": return java.lang.String.class; case "managementkey": case "managementKey": return java.lang.String.class; case "managementport": case "managementPort": return int.class; case "metricsaddress": case "metricsAddress": return java.lang.String.class; case "metricsname": case "metricsName": return java.lang.String.class; case "metricsport": case "metricsPort": return int.class; case "modelname": case "modelName": return java.lang.String.class; case "modelversion": case "modelVersion": return java.lang.String.class; case "registeroptions": case "registerOptions": return org.apache.camel.component.torchserve.client.model.RegisterOptions.class; case "scaleworkeroptions": case "scaleWorkerOptions": return org.apache.camel.component.torchserve.client.model.ScaleWorkerOptions.class; case "unregisteroptions": case "unregisterOptions": return org.apache.camel.component.torchserve.client.model.UnregisterOptions.class; case "url": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { TorchServeComponent target = (TorchServeComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "configuration": return target.getConfiguration(); case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return target.isHealthCheckConsumerEnabled(); case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return target.isHealthCheckProducerEnabled(); case "inferenceaddress": case "inferenceAddress": return getOrCreateConfiguration(target).getInferenceAddress(); case "inferencekey": case "inferenceKey": return getOrCreateConfiguration(target).getInferenceKey(); case "inferenceport": case "inferencePort": return getOrCreateConfiguration(target).getInferencePort(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "listlimit": case "listLimit": return getOrCreateConfiguration(target).getListLimit(); case "listnextpagetoken": case "listNextPageToken": return getOrCreateConfiguration(target).getListNextPageToken(); case "managementaddress": case "managementAddress": return getOrCreateConfiguration(target).getManagementAddress(); case "managementkey": case "managementKey": return getOrCreateConfiguration(target).getManagementKey(); case "managementport": case "managementPort": return getOrCreateConfiguration(target).getManagementPort(); case "metricsaddress": case "metricsAddress": return getOrCreateConfiguration(target).getMetricsAddress(); case "metricsname": case "metricsName": return getOrCreateConfiguration(target).getMetricsName(); case "metricsport": case "metricsPort": return getOrCreateConfiguration(target).getMetricsPort(); case "modelname": case "modelName": return getOrCreateConfiguration(target).getModelName(); case "modelversion": case "modelVersion": return getOrCreateConfiguration(target).getModelVersion(); case "registeroptions": case "registerOptions": return getOrCreateConfiguration(target).getRegisterOptions(); case "scaleworkeroptions": case "scaleWorkerOptions": return getOrCreateConfiguration(target).getScaleWorkerOptions(); case "unregisteroptions": case "unregisterOptions": return getOrCreateConfiguration(target).getUnregisterOptions(); case "url": return getOrCreateConfiguration(target).getUrl(); default: return null; } } }
TorchServeComponentConfigurer
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/rules/QueryRulesetTests.java
{ "start": 1247, "end": 5651 }
class ____ extends ESTestCase { private NamedWriteableRegistry namedWriteableRegistry; @Before public void registerNamedObjects() { SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList()); List<NamedWriteableRegistry.Entry> namedWriteables = searchModule.getNamedWriteables(); namedWriteableRegistry = new NamedWriteableRegistry(namedWriteables); } public final void testRandomSerialization() throws IOException { for (int runs = 0; runs < 10; runs++) { QueryRuleset testInstance = EnterpriseSearchModuleTestUtils.randomQueryRuleset(); assertTransportSerialization(testInstance); assertXContent(testInstance, randomBoolean()); } } public void testToXContent() throws IOException { String content = XContentHelper.stripWhitespace(""" { "ruleset_id": "my_ruleset_id", "rules": [ { "rule_id": "my_query_rule1", "type": "pinned", "criteria": [ {"type": "exact", "metadata": "query_string", "values": ["foo", "bar"]} ], "actions": { "ids": ["id1", "id2"] } }, { "rule_id": "my_query_rule2", "type": "pinned", "criteria": [ {"type": "exact", "metadata": "query_string", "values": ["baz"]} ], "actions": { "ids": ["id3", "id4"] } } ] }"""); QueryRuleset queryRuleset = QueryRuleset.fromXContentBytes("my_ruleset_id", new BytesArray(content), XContentType.JSON); boolean humanReadable = true; BytesReference originalBytes = toShuffledXContent(queryRuleset, XContentType.JSON, ToXContent.EMPTY_PARAMS, humanReadable); QueryRuleset parsed; try (XContentParser parser = createParser(XContentType.JSON.xContent(), originalBytes)) { parsed = QueryRuleset.fromXContent("my_ruleset_id", parser); } assertToXContentEquivalent(originalBytes, toXContent(parsed, XContentType.JSON, humanReadable), XContentType.JSON); } public void testToXContentInvalidQueryRulesetId() throws IOException { String content = XContentHelper.stripWhitespace(""" { "ruleset_id": "my_ruleset_id", "rules": [ { "rule_id": "my_query_rule1", "type": "pinned", "criteria": [ {"type": "exact", "metadata": "query_string", "values": ["foo", "bar"]} ], "actions": { "ids": ["id1", "id2"] } }, { "rule_id": "my_query_rule2", "type": "pinned", "criteria": [ {"type": "exact", "metadata": "query_string", "values": ["baz"]} ], "actions": { "ids": ["id3", "id4"] } } ] }"""); expectThrows( IllegalArgumentException.class, () -> QueryRuleset.fromXContentBytes("not_my_ruleset_id", new BytesArray(content), XContentType.JSON) ); } private void assertXContent(QueryRuleset queryRuleset, boolean humanReadable) throws IOException { BytesReference originalBytes = toShuffledXContent(queryRuleset, XContentType.JSON, ToXContent.EMPTY_PARAMS, humanReadable); QueryRuleset parsed; try (XContentParser parser = createParser(XContentType.JSON.xContent(), originalBytes)) { parsed = QueryRuleset.fromXContent(queryRuleset.id(), parser); } assertToXContentEquivalent(originalBytes, toXContent(parsed, XContentType.JSON, humanReadable), XContentType.JSON); } private void assertTransportSerialization(QueryRuleset testInstance) throws IOException { QueryRuleset deserializedInstance = copyInstance(testInstance); assertNotSame(testInstance, deserializedInstance); assertThat(testInstance, equalTo(deserializedInstance)); } private QueryRuleset copyInstance(QueryRuleset instance) throws IOException { return copyWriteable(instance, namedWriteableRegistry, QueryRuleset::new); } }
QueryRulesetTests
java
redisson__redisson
redisson/src/main/java/org/redisson/api/redisnode/RedisMaster.java
{ "start": 730, "end": 793 }
interface ____ extends RedisNode, RedisMasterAsync { }
RedisMaster
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java
{ "start": 2086, "end": 5935 }
class ____ to be called when a service fails to execute. The mock doesn't support on the provider side, * and it is executed when a non-business exception occurs after a remote service call. */ protected String mock; /** * Merger for result data. */ protected String merger; /** * Cache provider for caching return results. available options: lru, threadlocal, jcache etc. */ protected String cache; /** * Enable JSR303 standard annotation validation for method parameters. */ protected String validation; /** * Customized parameters for configuration. */ protected Map<String, String> parameters; /** * Forks for forking cluster. */ protected Integer forks; public AbstractMethodConfig() {} public AbstractMethodConfig(ModuleModel moduleModel) { super(moduleModel); } @Override @Transient public ModuleModel getScopeModel() { return (ModuleModel) super.getScopeModel(); } @Override @Transient protected ScopeModel getDefaultModel() { return ApplicationModel.defaultModel().getDefaultModule(); } @Override protected void checkScopeModel(ScopeModel scopeModel) { if (!(scopeModel instanceof ModuleModel)) { throw new IllegalArgumentException( "Invalid scope model, expect to be a ModuleModel but got: " + scopeModel); } } @Transient protected ModuleConfigManager getModuleConfigManager() { return getScopeModel().getConfigManager(); } public Integer getForks() { return forks; } public void setForks(Integer forks) { this.forks = forks; } public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } public String getLoadbalance() { return loadbalance; } public void setLoadbalance(String loadbalance) { this.loadbalance = loadbalance; } public Boolean isAsync() { return async; } public void setAsync(Boolean async) { this.async = async; } public Integer getActives() { return actives; } public void setActives(Integer actives) { this.actives = actives; } public Boolean getSent() { return sent; } public void setSent(Boolean sent) { this.sent = sent; } @Parameter(escaped = true) public String getMock() { return mock; } public void setMock(String mock) { this.mock = mock; } /** * Set the property "mock" * * @param mock the value of mock * @since 2.7.6 * @deprecated use {@link #setMock(String)} instead */ @Deprecated public void setMock(Object mock) { if (mock == null) { return; } this.setMock(String.valueOf(mock)); } public String getMerger() { return merger; } public void setMerger(String merger) { this.merger = merger; } public String getCache() { return cache; } public void setCache(String cache) { this.cache = cache; } public String getValidation() { return validation; } public void setValidation(String validation) { this.validation = validation; } public Map<String, String> getParameters() { this.parameters = Optional.ofNullable(this.parameters).orElseGet(HashMap::new); return this.parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } }
name
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/jdk/TypedArrayDeserTest.java
{ "start": 1138, "end": 1346 }
class ____<T> extends LinkedList<T> { } // Mix-in to force wrapper for things like primitive arrays @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.WRAPPER_OBJECT)
TypedListAsWrapper
java
spring-projects__spring-boot
test-support/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/BuildOutput.java
{ "start": 863, "end": 1736 }
class ____ { private final Class<?> testClass; public BuildOutput(Class<?> testClass) { this.testClass = testClass; } /** * Returns the location into which test classes have been built. * @return test classes location */ public File getTestClassesLocation() { try { File location = new File(this.testClass.getProtectionDomain().getCodeSource().getLocation().toURI()); if (location.getPath().endsWith(path("bin", "test")) || location.getPath().endsWith(path("bin", "intTest")) || location.getPath().endsWith(path("build", "classes", "java", "test")) || location.getPath().endsWith(path("build", "classes", "java", "intTest"))) { return location; } throw new IllegalStateException("Unexpected test classes location '" + location + "'"); } catch (URISyntaxException ex) { throw new IllegalStateException("Invalid test
BuildOutput
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/support/BasePoolConfig.java
{ "start": 2182, "end": 6261 }
class ____ { protected boolean testOnCreate = DEFAULT_TEST_ON_CREATE; protected boolean testOnAcquire = DEFAULT_TEST_ON_ACQUIRE; protected boolean testOnRelease = DEFAULT_TEST_ON_RELEASE; protected Builder() { } /** * Enables validation of objects before being returned from the acquire method. Validation is performed by the * {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the pool. If the object fails to * validate, then acquire will fail. * * @return {@code this} {@link Builder}. */ public Builder testOnCreate() { return testOnCreate(true); } /** * Configures whether objects created for the pool will be validated before being returned from the acquire method. * Validation is performed by the {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the * pool. If the object fails to validate, then acquire will fail. * * @param testOnCreate {@code true} if newly created objects should be validated before being returned from the acquire * method. {@code true} to enable test on creation. * * @return {@code this} {@link Builder}. */ public Builder testOnCreate(boolean testOnCreate) { this.testOnCreate = testOnCreate; return this; } /** * Enables validation of objects before being returned from the acquire method. Validation is performed by the * {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the pool. If the object fails to * validate, it will be removed from the pool and destroyed, and a new attempt will be made to borrow an object from the * pool. * * @return {@code this} {@link Builder}. */ public Builder testOnAcquire() { return testOnAcquire(true); } /** * Configures whether objects acquired from the pool will be validated before being returned from the acquire method. * Validation is performed by the {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the * pool. If the object fails to validate, it will be removed from the pool and destroyed, and a new attempt will be made * to borrow an object from the pool. * * @param testOnAcquire {@code true} if objects should be validated before being returned from the acquire method. * @return {@code this} {@link Builder}. */ public Builder testOnAcquire(boolean testOnAcquire) { this.testOnAcquire = testOnAcquire; return this; } /** * Enables validation of objects when they are returned to the pool via the release method. Validation is performed by * the {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the pool. Returning objects * that fail validation are destroyed rather then being returned the pool. * * @return {@code this} {@link Builder}. */ public Builder testOnRelease() { return testOnRelease(true); } /** * Configures whether objects borrowed from the pool will be validated when they are returned to the pool via the * release method. Validation is performed by the {@link AsyncObjectFactory#validate(Object)} method of the factory * associated with the pool. Returning objects that fail validation are destroyed rather then being returned the pool. * * @param testOnRelease {@code true} if objects should be validated on return to the pool via the release method. * @return {@code this} {@link Builder}. */ public Builder testOnRelease(boolean testOnRelease) { this.testOnRelease = testOnRelease; return this; } } }
Builder
java
spring-projects__spring-framework
spring-core/src/testFixtures/java/org/springframework/core/testfixture/codec/AbstractEncoderTests.java
{ "start": 1505, "end": 1765 }
class ____ {@link Encoder} unit tests. Subclasses need to implement * {@link #canEncode()} and {@link #encode()}, possibly using the wide variety of * helper methods like {@link #testEncodeAll}. * * @author Arjen Poutsma * @since 5.1.3 */ public abstract
for
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/extension/Heavyweight.java
{ "start": 579, "end": 1345 }
class ____ implements ParameterResolver, BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { context.getStore(ExtensionContext.Namespace.GLOBAL).put("once", new CloseableOnlyOnceResource()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext context) { return Resource.class.equals(parameterContext.getParameter().getType()); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) { var engineContext = context.getRoot(); var store = engineContext.getStore(ExtensionContext.Namespace.GLOBAL); var resource = store.computeIfAbsent(ResourceValue.class); resource.usages.incrementAndGet(); return resource; }
Heavyweight
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/float_/FloatAssert_usingDefaultComparator_Test.java
{ "start": 1073, "end": 1642 }
class ____ extends FloatAssertBaseTest { @Override protected FloatAssert invoke_api_method() { return assertions.usingComparator(alwaysEqual()) .usingDefaultComparator(); } @Override protected void verify_internal_effects() { assertThat(getObjects(assertions)).isSameAs(Objects.instance()); assertThat(getObjects(assertions).getComparator()).isNull(); assertThat(getFloats(assertions)).isSameAs(Floats.instance()); assertThat(getFloats(assertions).getComparator()).isNull(); } }
FloatAssert_usingDefaultComparator_Test
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/GeneratedStaticClasspathResourcesTest.java
{ "start": 636, "end": 4712 }
class ____ { @RegisterExtension final static QuarkusUnitTest test = new QuarkusUnitTest().withApplicationRoot( (jar) -> jar.add(new StringAsset("quarkus.http.enable-compression=true\n" + "quarkus.http.static-resources.index-page=default.html"), "application.properties")) .addBuildChainCustomizer(new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder buildChainBuilder) { buildChainBuilder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { context.produce(new GeneratedStaticResourceBuildItem( "/default.html", "Hello from Quarkus".getBytes(StandardCharsets.UTF_8))); context.produce(new GeneratedStaticResourceBuildItem("/hello-from-generated-static-resource.html", "GeneratedStaticResourceBuildItem says: Hello from me!".getBytes(StandardCharsets.UTF_8))); context.produce(new GeneratedStaticResourceBuildItem("/static-file.html", "I am from static-html.html".getBytes(StandardCharsets.UTF_8))); context.produce(new GeneratedStaticResourceBuildItem( "/.nojekyll", "{empty}".getBytes(StandardCharsets.UTF_8))); context.produce(new GeneratedStaticResourceBuildItem("/quarkus-openapi-generator/default.html", "An extension to read OpenAPI specifications...".getBytes(StandardCharsets.UTF_8))); } }).produces(GeneratedStaticResourceBuildItem.class).produces(GeneratedResourceBuildItem.class).build(); } }); @Test public void shouldGetStaticFileHtmlPageWhenThereIsAGeneratedStaticResource() { RestAssured.get("/static-file.html").then() .body(Matchers.containsString("I am from static-html.html")) .statusCode(Matchers.is(200)); RestAssured.get("hello-from-generated-static-resource.html").then() .body(Matchers.containsString("GeneratedStaticResourceBuildItem says")) .statusCode(Matchers.is(200)); RestAssured.get("/").then() .body(Matchers.containsString("Hello from Quarkus")) .statusCode(200); } @Test public void shouldCompress() { RestAssured.get("/static-file.html").then() .header("Content-Encoding", "gzip") .statusCode(Matchers.is(200)); } @Test public void shouldGetHiddenFiles() { RestAssured.get("/.nojekyll") .then() .body(Matchers.containsString("{empty}")) .statusCode(200); } @Test public void shouldGetTheIndexPageCorrectly() { RestAssured.get("/quarkus-openapi-generator/") .then() .body(Matchers.containsString("An extension to read OpenAPI specifications...")) .statusCode(200); } @Test public void shouldNotGetWhenPathEndsWithoutSlash() { RestAssured.get("/quarkus-openapi-generator") .then() .statusCode(404); // We are using next() } @Test public void shouldGetAllowHeaderWhenUsingOptions() { RestAssured.options("/quarkus-openapi-generator/") .then() .header("Allow", Matchers.is("HEAD,GET,OPTIONS")) .statusCode(204); } @Test public void shouldGetHeadersFromHeadRequest() { RestAssured.head("/static-file.html") .then() .header("Content-Length", Integer::parseInt, Matchers.greaterThan(0)) .header("Content-Type", Matchers.is("text/html;charset=UTF-8")) .statusCode(200); } }
GeneratedStaticClasspathResourcesTest
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/reflection/property/PropertyTokenizerTest.java
{ "start": 1140, "end": 2988 }
class ____ { @Test void shouldParsePropertySuccessfully() { String fullname = "id"; PropertyTokenizer tokenizer = new PropertyTokenizer(fullname); assertEquals("id", tokenizer.getIndexedName()); assertEquals("id", tokenizer.getName()); assertNull(tokenizer.getChildren()); assertNull(tokenizer.getIndex()); assertFalse(tokenizer.hasNext()); assertNull(tokenizer.getIndex()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(tokenizer::remove) .withMessage("Remove is not supported, as it has no meaning in the context of properties."); } @Test void shouldParsePropertyWhichContainsDelimSuccessfully() { String fullname = "person.id"; PropertyTokenizer tokenizer = new PropertyTokenizer(fullname); assertEquals("person", tokenizer.getIndexedName()); assertEquals("person", tokenizer.getName()); assertTrue(tokenizer.hasNext()); assertEquals("id", tokenizer.getChildren()); assertNull(tokenizer.getIndex()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(tokenizer::remove) .withMessage("Remove is not supported, as it has no meaning in the context of properties."); } @Test void shouldParsePropertyWhichContainsIndexSuccessfully() { String fullname = "array[0]"; PropertyTokenizer tokenizer = new PropertyTokenizer(fullname); assertEquals("array[0]", tokenizer.getIndexedName()); assertEquals("array", tokenizer.getName()); assertEquals("0", tokenizer.getIndex()); assertFalse(tokenizer.hasNext()); assertNull(tokenizer.getChildren()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(tokenizer::remove) .withMessage("Remove is not supported, as it has no meaning in the context of properties."); } }
PropertyTokenizerTest
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3796ClassImportInconsistencyTest.java
{ "start": 1196, "end": 2138 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that classes shared with the Maven core realm are properly imported into the plugin realm. * * @throws Exception in case of failure */ @Test public void testitMNG3796() throws Exception { File testDir = extractResources("/mng-3796"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties pclProps = verifier.loadProperties("target/pcl.properties"); assertNotNull(pclProps.getProperty("org.codehaus.plexus.util.xml.Xpp3Dom")); Properties tcclProps = verifier.loadProperties("target/tccl.properties"); assertEquals(pclProps, tcclProps); } }
MavenITmng3796ClassImportInconsistencyTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/AbstractParameterTool.java
{ "start": 1102, "end": 1231 }
class ____ common utility methods of {@link ParameterTool} and {@link * MultipleParameterTool}. */ @Public public abstract
provides
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/Attribute.java
{ "start": 6373, "end": 9020 }
class ____ contains the attribute to be read. * @param offset index of the first byte of the attribute's content in {@link ClassReader}. The 6 * attribute header bytes (attribute_name_index and attribute_length) are not taken into * account here. * @param length the length of the attribute's content (excluding the 6 attribute header bytes). * @param charBuffer the buffer to be used to call the ClassReader methods requiring a * 'charBuffer' parameter. * @param codeAttributeOffset index of the first byte of content of the enclosing Code attribute * in {@link ClassReader}, or -1 if the attribute to be read is not a Code attribute. The 6 * attribute header bytes (attribute_name_index and attribute_length) are not taken into * account here. * @param labels the labels of the method's code, or {@literal null} if the attribute to be read * is not a Code attribute. Labels defined in the attribute are added to this array, if not * already present. * @return a new {@link Attribute} object corresponding to the specified bytes. */ public static Attribute read( final Attribute attribute, final ClassReader classReader, final int offset, final int length, final char[] charBuffer, final int codeAttributeOffset, final Label[] labels) { return attribute.read(classReader, offset, length, charBuffer, codeAttributeOffset, labels); } /** * Returns the label corresponding to the given bytecode offset by calling {@link * ClassReader#readLabel}. This creates and adds the label to the given array if it is not already * present. Note that this created label may be a {@link Label} subclass instance, if the given * ClassReader overrides {@link ClassReader#readLabel}. Hence {@link #read(ClassReader, int, int, * char[], int, Label[])} must not manually create {@link Label} instances. * * @param bytecodeOffset a bytecode offset in a method. * @param labels the already created labels, indexed by their offset. If a label already exists * for bytecodeOffset this method does not create a new one. Otherwise it stores the new label * in this array. * @return a label for the given bytecode offset. */ public static Label readLabel( final ClassReader classReader, final int bytecodeOffset, final Label[] labels) { return classReader.readLabel(bytecodeOffset, labels); } /** * Calls {@link #write(ClassWriter,byte[],int,int,int)} if it has not already been called and * returns its result or its (cached) previous result. * * @param classWriter the
that
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/HttpSecurityProcessor.java
{ "start": 34078, "end": 47674 }
class ____ extends AuthorizationPolicyStorage GeneratedBeanGizmoAdaptor beanAdaptor = new GeneratedBeanGizmoAdaptor(generatedBeanProducer); var generatedClassName = AuthorizationPolicyStorage.class.getName() + "_Impl"; try (ClassCreator cc = ClassCreator.builder().className(generatedClassName) .superClass(AuthorizationPolicyStorage.class).classOutput(beanAdaptor).build()) { cc.addAnnotation(Singleton.class); // generate matching constructor that calls the super var constructor = cc.getConstructorCreator(new String[] {}); constructor.invokeSpecialMethod(MethodDescriptor.ofConstructor(AuthorizationPolicyStorage.class), constructor.getThis()); var mapDescriptorType = DescriptorUtils.typeToString( ParameterizedType.create(Map.class, Type.create(MethodDescription.class), Type.create(String.class))); if (authZPolicyInstancesItem.methodToPolicyName.isEmpty()) { // generate: // protected Map<MethodDescription, String> getMethodToPolicyName() { Map.of(); } try (var mc = cc.getMethodCreator(MethodDescriptor.ofMethod(AuthorizationPolicyStorage.class, "getMethodToPolicyName", mapDescriptorType))) { var map = mc.invokeStaticInterfaceMethod(MethodDescriptor.ofMethod(Map.class, "of", Map.class)); mc.returnValue(map); } } else { // detected @AuthorizationPolicy annotation instances // generates: // private final Map<MethodDescription, String> methodToPolicyName; var methodToPolicyNameField = cc.getFieldCreator("methodToPolicyName", mapDescriptorType) .setModifiers(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL); // generates: // protected Map<MethodDescription, String> getMethodToPolicyName() { this.methodToPolicyName; } try (var mc = cc.getMethodCreator(MethodDescriptor.ofMethod(AuthorizationPolicyStorage.class, "getMethodToPolicyName", mapDescriptorType))) { var map = mc.readInstanceField(methodToPolicyNameField.getFieldDescriptor(), mc.getThis()); mc.returnValue(map); } // === constructor // initializes 'methodToPolicyName' private field in the constructor // this.methodToPolicyName = new MethodsToPolicyBuilder() // .addMethodToPolicyName(policyName, className, methodName, parameterTypes) // .build(); // create builder var builder = constructor.newInstance( MethodDescriptor.ofConstructor(AuthorizationPolicyStorage.MethodsToPolicyBuilder.class)); var addMethodToPolicyNameType = MethodDescriptor.ofMethod( AuthorizationPolicyStorage.MethodsToPolicyBuilder.class, "addMethodToPolicyName", AuthorizationPolicyStorage.MethodsToPolicyBuilder.class, String.class, String.class, String.class, String[].class); for (var e : authZPolicyInstancesItem.methodToPolicyName.entrySet()) { MethodInfo securedMethod = e.getKey(); String policyNameStr = e.getValue(); // String policyName var policyName = constructor.load(policyNameStr); // String methodName var methodName = constructor.load(securedMethod.name()); // String declaringClassName var declaringClassName = constructor.load(securedMethod.declaringClass().name().toString()); // String[] paramTypes var paramTypes = constructor.marshalAsArray(String[].class, securedMethod.parameterTypes().stream() .map(pt -> pt.name().toString()).map(constructor::load).toArray(ResultHandle[]::new)); // builder.addMethodToPolicyName(policyName, className, methodName, paramTypes) builder = constructor.invokeVirtualMethod(addMethodToPolicyNameType, builder, policyName, declaringClassName, methodName, paramTypes); } // builder.build() var resultMapType = DescriptorUtils .typeToString(ParameterizedType.create(Map.class, TypeVariable.create(MethodDescription.class), TypeVariable.create(String.class))); var buildMethodType = MethodDescriptor.ofMethod(AuthorizationPolicyStorage.MethodsToPolicyBuilder.class, "build", resultMapType); var resultMap = constructor.invokeVirtualMethod(buildMethodType, builder); // assign builder to the private field constructor.writeInstanceField(methodToPolicyNameField.getFieldDescriptor(), constructor.getThis(), resultMap); } // late return from constructor in case we need to write value to the field constructor.returnVoid(); } } } @BuildStep(onlyIf = AlwaysPropagateSecurityIdentity.class) CurrentIdentityAssociationClassBuildItem createCurrentIdentityAssociation() { return new CurrentIdentityAssociationClassBuildItem(DuplicatedContextSecurityIdentityAssociation.class); } @Record(ExecutionTime.STATIC_INIT) @BuildStep(onlyIf = AlwaysPropagateSecurityIdentity.class) IgnoredContextLocalDataKeysBuildItem dontPropagateSecurityIdentityToDuplicateContext(HttpSecurityRecorder recorder) { return new IgnoredContextLocalDataKeysBuildItem(recorder.getSecurityIdentityContextKeySupplier()); } private static Stream<MethodInfo> getPolicyTargetEndpointCandidates(AnnotationTarget target, SecurityTransformer securityTransformer) { if (target.kind() == AnnotationTarget.Kind.METHOD) { var method = target.asMethod(); if (!hasProperEndpointModifiers(method)) { if (method.isSynthetic() && method.name().endsWith(KOTLIN_SUSPEND_IMPL_SUFFIX)) { // ATM there are 2 methods for Kotlin endpoint like this: // @AuthorizationPolicy(name = "suspended") // suspend fun sayHi() = "Hi" // the synthetic method doesn't need to be secured, but it keeps security annotations return Stream.empty(); } throw new RuntimeException(""" Found method annotated with the @AuthorizationPolicy annotation that is not an endpoint: %s#%s """.formatted(method.declaringClass().name().toString(), method.name())); } return Stream.of(method); } return target.asClass().methods().stream() .filter(HttpSecurityProcessor::hasProperEndpointModifiers) .filter(mi -> !securityTransformer.hasSecurityAnnotation(mi)); } private static void validateAuthMechanismAnnotationUsage(Capabilities capabilities, VertxHttpBuildTimeConfig buildTimeConfig, DotName[] annotationNames) { if (buildTimeConfig.auth().proactive() || (capabilities.isMissing(Capability.RESTEASY_REACTIVE) && capabilities.isMissing(Capability.RESTEASY) && capabilities.isMissing(Capability.WEBSOCKETS_NEXT))) { throw new ConfigurationException("Annotations '" + Arrays.toString(annotationNames) + "' can only be used when" + " proactive authentication is disabled and either Quarkus REST, RESTEasy Classic or WebSockets Next" + " extension is present"); } } private static boolean isMtlsClientAuthenticationEnabled(VertxHttpBuildTimeConfig httpBuildTimeConfig) { return !ClientAuth.NONE.equals(httpBuildTimeConfig.tlsClientAuth()); } public static Set<MethodInfo> collectClassMethodsWithoutRbacAnnotation(Collection<ClassInfo> classes, SecurityTransformer securityTransformer) { return classes .stream() .filter(c -> !securityTransformer.hasSecurityAnnotation(c)) .map(ClassInfo::methods) .flatMap(Collection::stream) .filter(HttpSecurityProcessor::hasProperEndpointModifiers) .filter(m -> !securityTransformer.hasSecurityAnnotation(m)) .collect(Collectors.toSet()); } public static Set<MethodInfo> collectMethodsWithoutRbacAnnotation(Collection<MethodInfo> methods, SecurityTransformer securityTransformer) { return methods .stream() .filter(m -> !securityTransformer.hasSecurityAnnotation(m)) .collect(Collectors.toSet()); } public static Set<ClassInfo> collectAnnotatedClasses(Collection<AnnotationInstance> instances, Predicate<ClassInfo> filter) { return instances .stream() .map(AnnotationInstance::target) .filter(target -> target.kind() == AnnotationTarget.Kind.CLASS) .map(AnnotationTarget::asClass) .filter(filter) .collect(Collectors.toSet()); } private static Set<MethodInfo> collectAnnotatedMethods(Collection<AnnotationInstance> instances) { return instances .stream() .map(AnnotationInstance::target) .filter(target -> target.kind() == AnnotationTarget.Kind.METHOD) .map(AnnotationTarget::asMethod) .collect(Collectors.toSet()); } private static boolean hasProperEndpointModifiers(MethodInfo info) { // synthetic methods are not endpoints if (info.isSynthetic()) { return false; } if (!Modifier.isPublic(info.flags())) { return false; } if (info.isConstructor()) { return false; } // instance methods only return !Modifier.isStatic(info.flags()); } private static void addInterceptedEndpoints(List<EagerSecurityInterceptorBindingBuildItem> interceptorBindings, IndexView index, AnnotationTarget.Kind appliesTo, Map<DotName, Map<String, List<MethodInfo>>> result, Map<AnnotationTarget, List<EagerSecurityInterceptorBindingBuildItem>> cache, Predicate<ClassInfo> hasClassLevelSecurity, Map<DotName, Map<String, Set<String>>> classResult) { for (EagerSecurityInterceptorBindingBuildItem interceptorBinding : interceptorBindings) { for (DotName annotationBinding : interceptorBinding.getAnnotationBindings()) { Map<String, List<MethodInfo>> bindingValueToInterceptedMethods = new HashMap<>(); Map<String, Set<String>> bindingValueToInterceptedClasses = new HashMap<>(); for (AnnotationInstance annotation : index.getAnnotations(annotationBinding)) { if (annotation.target().kind() != appliesTo) { continue; } if (annotation.target().kind() == AnnotationTarget.Kind.CLASS) { ClassInfo interceptedClass = annotation.target().asClass(); if (hasClassLevelSecurity.test(interceptedClass)) { // endpoint can only be annotated with one of @Basic, @Form, ... // however combining @CodeFlow and @Tenant is supported var appliedBindings = cache.computeIfAbsent(interceptedClass, a -> new ArrayList<>()); if (appliedBindings.contains(interceptorBinding)) { throw new RuntimeException( "Only one of the '%s' annotations can be applied on the '%s' class".formatted( Arrays.toString(interceptorBinding.getAnnotationBindings()), interceptedClass)); } else { appliedBindings.add(interceptorBinding); } // don't apply security interceptor on individual methods, but on the class-level instead bindingValueToInterceptedClasses .computeIfAbsent(interceptorBinding.getBindingValue(annotation, annotationBinding, interceptedClass), s -> new HashSet<>()) .add(interceptedClass.name().toString()); continue; } for (MethodInfo method : interceptedClass.methods()) { if (hasProperEndpointModifiers(method)) { // avoid situation when resource method is annotated with @Basic,
AuthorizationPolicyStorage_Impl
java
apache__camel
components/camel-aws/camel-aws2-sns/src/test/java/org/apache/camel/component/aws2/sns/AmazonSNSClientMock.java
{ "start": 1715, "end": 3326 }
class ____ implements SnsClient { private static final String DEFAULT_TOPIC_ARN = "arn:aws:sns:us-east-1:541925086079:MyTopic"; public AmazonSNSClientMock() { } @Override public SetTopicAttributesResponse setTopicAttributes(SetTopicAttributesRequest setTopicAttributesRequest) { assertEquals(DEFAULT_TOPIC_ARN, setTopicAttributesRequest.topicArn()); assertEquals("Policy", setTopicAttributesRequest.attributeName()); return SetTopicAttributesResponse.builder().build(); } @Override public SnsServiceClientConfiguration serviceClientConfiguration() { return null; } @Override public CreateTopicResponse createTopic(CreateTopicRequest createTopicRequest) { return CreateTopicResponse.builder().topicArn(DEFAULT_TOPIC_ARN).build(); } @Override public PublishResponse publish(PublishRequest publishRequest) { return PublishResponse.builder().messageId("dcc8ce7a-7f18-4385-bedd-b97984b4363c").build(); } @Override public ListTopicsResponse listTopics(ListTopicsRequest listTopicRequest) { ListTopicsResponse.Builder res = ListTopicsResponse.builder(); Topic topic = Topic.builder().topicArn(DEFAULT_TOPIC_ARN).build(); List<Topic> list = new ArrayList<>(); list.add(topic); res.topics(list); return res.build(); } @Override public String serviceName() { // TODO Auto-generated method stub return null; } @Override public void close() { // TODO Auto-generated method stub } }
AmazonSNSClientMock
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StringFormatWithLiteralTest.java
{ "start": 3994, "end": 4423 }
class ____ { String test() { Integer data = 3; return String.format("Formatting this int: %d", data); } } """) .doTest(); } @Test public void negativeStringFormatWithOneIntegerVariableAndStringLiteral() { compilationHelper .addSourceLines( "ExampleClass.java", """ import java.lang.String; public
ExampleClass
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java
{ "start": 50682, "end": 51096 }
class ____ implements MethodInterceptor { @Override public Object invoke(MethodInvocation mi) throws Throwable { Method m = mi.getMethod(); Object retval = mi.proceed(); assertThat(mi.getMethod()).as("Method invocation has same method on way back").isEqualTo(m); return retval; } } /** * ExposeInvocation must be set to true. */ private static
CheckMethodInvocationIsSameInAndOutInterceptor
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/FilteredClassLoader.java
{ "start": 5362, "end": 5956 }
class ____ implements Predicate<String> { private final Class<?>[] hiddenClasses; private ClassFilter(Class<?>[] hiddenClasses) { this.hiddenClasses = hiddenClasses; } @Override public boolean test(String className) { for (Class<?> hiddenClass : this.hiddenClasses) { if (className.equals(hiddenClass.getName())) { return true; } } return false; } public static ClassFilter of(Class<?>... hiddenClasses) { return new ClassFilter(hiddenClasses); } } /** * Filter to restrict the packages that can be loaded. */ public static final
ClassFilter
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/groups/FieldsOrPropertiesExtractor_extract_Test.java
{ "start": 1307, "end": 5162 }
class ____ { private List<Employee> employees; @BeforeEach public void setUp() { Employee yoda = new Employee(1L, new Name("Yoda"), 800); yoda.surname = new Name("Master", "Jedi"); Employee luke = new Employee(2L, new Name("Luke", "Skywalker"), 26); employees = list(yoda, luke); } @Test void should_extract_field_values_in_absence_of_properties() { // WHEN List<Object> extractedValues = extract(employees, byName("id")); // THEN then(extractedValues).containsOnly(1L, 2L); } @Test void should_extract_null_values_for_null_property_values() { // GIVEN employees.getFirst().setName(null); // WHEN List<Object> extractedValues = extract(employees, byName("name")); // THEN then(extractedValues).containsOnly(null, new Name("Luke", "Skywalker")); } @Test void should_extract_null_values_for_null_nested_property_values() { // GIVEN employees.getFirst().setName(null); // WHEN List<Object> extractedValues = extract(employees, byName("name.first")); // THEN then(extractedValues).containsOnly(null, "Luke"); } @Test void should_extract_null_values_for_null_field_values() { // WHEN List<Object> extractedValues = extract(employees, byName("surname")); // THEN then(extractedValues).containsOnly(new Name("Master", "Jedi"), null); } @Test void should_extract_null_values_for_null_nested_field_values() { // WHEN List<Object> extractedValues = extract(employees, byName("surname.first")); // THEN then(extractedValues).containsOnly("Master", null); } @Test void should_extract_property_values_when_no_public_field_match_given_name() { // WHEN List<Object> extractedValues = extract(employees, byName("age")); // THEN then(extractedValues).containsOnly(800, 26); } @Test void should_extract_pure_property_values() { // WHEN List<Object> extractedValues = extract(employees, byName("adult")); // THEN then(extractedValues).containsOnly(true); } @Test void should_throw_error_when_no_property_nor_public_field_match_given_name() { assertThatExceptionOfType(IntrospectionError.class).isThrownBy(() -> extract(employees, byName("unknown"))); } @Test void should_throw_exception_when_given_name_is_null() { assertThatIllegalArgumentException().isThrownBy(() -> extract(employees, byName((String) null))) .withMessage("The name of the property/field to read should not be null"); } @Test void should_throw_exception_when_given_name_is_empty() { assertThatIllegalArgumentException().isThrownBy(() -> extract(employees, byName(""))) .withMessage("The name of the property/field to read should not be empty"); } @Test void should_fallback_to_field_if_exception_has_been_thrown_on_property_access() { // GIVEN List<Employee> employees = list(new EmployeeWithBrokenName("Name")); // WHEN List<Object> extractedValues = extract(employees, byName("name")); // THEN then(extractedValues).containsOnly(new Name("Name")); } @Test void should_prefer_properties_over_fields() { // GIVEN List<Employee> employees = list(new EmployeeWithOverriddenName("Overridden Name")); // WHEN List<Object> extractedValues = extract(employees, byName("name")); // THEN then(extractedValues).containsOnly(new Name("Overridden Name")); } @Test void should_throw_exception_if_property_cannot_be_extracted_due_to_runtime_exception_during_property_access() { // GIVEN List<Employee> employees = list(new BrokenEmployee()); // WHEN/THEN assertThatExceptionOfType(IntrospectionError.class).isThrownBy(() -> extract(employees, byName("adult"))); } public static
FieldsOrPropertiesExtractor_extract_Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLambdaTest.java
{ "start": 7958, "end": 8691 }
class ____ { private Supplier<String> f() { return () -> "hello "; } private BiFunction<String, String, String> g() { return (a, b) -> a + "hello " + b; } private Runnable h() { return () -> System.err.println(); } void main() { System.err.println(f().get()); System.err.println(g().apply("a", "b")); h().run(); } } """) .addOutputLines( "Test.java", """ import java.util.function.BiFunction; import java.util.function.Supplier;
Test
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/BuildProfileTest.java
{ "start": 6261, "end": 6534 }
class ____ implements Feature { @Override public boolean configure(FeatureContext context) { context.register(ResponseFilter3.class); return true; } } @UnlessBuildProfile("test") @Provider public static
Feature1
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointSedaTest.java
{ "start": 1170, "end": 2735 }
class ____ extends ContextTestSupport { private static String beforeThreadName; private static String afterThreadName; @Test public void testAsyncEndpoint() throws Exception { getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel"); String reply = template.requestBody("direct:start", "Hello Camel", String.class); assertEquals("Bye Camel", reply); assertMockEndpointsSatisfied(); assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.addComponent("async", new MyAsyncComponent()); from("direct:start").to("mock:before").process(new Processor() { public void process(Exchange exchange) { beforeThreadName = Thread.currentThread().getName(); } }).to("async:bye:camel").process(new Processor() { public void process(Exchange exchange) { afterThreadName = Thread.currentThread().getName(); } }).to("seda:foo"); from("seda:foo").to("mock:after").to("mock:result"); } }; } }
AsyncEndpointSedaTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/ComparableAssert.java
{ "start": 1151, "end": 8160 }
interface ____<SELF extends ComparableAssert<SELF, ACTUAL>, ACTUAL extends Comparable<? super ACTUAL>> { /** * Verifies that the actual value is equal to the given one by invoking * <code>{@link Comparable#compareTo(Object)}</code>. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(1.0).isEqualByComparingTo(1.0); * // assertion will pass because 8.0 is equal to 8.00 using {@link BigDecimal#compareTo(BigDecimal)} * assertThat(new BigDecimal(&quot;8.0&quot;)).isEqualByComparingTo(new BigDecimal(&quot;8.00&quot;)); * * // assertion will fail * assertThat(new BigDecimal(1.0)).isEqualByComparingTo(new BigDecimal(2.0));</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is not equal when comparing to the given one. */ SELF isEqualByComparingTo(ACTUAL other); /** * Verifies that the actual value is not equal to the given one by invoking * <code>{@link Comparable#compareTo(Object)}</code>. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new BigDecimal(1.0)).isNotEqualByComparingTo(new BigDecimal(2.0)); * * // assertion will fail * assertThat(1.0).isNotEqualByComparingTo(1.0); * // assertion will fail because 8.0 is equal to 8.00 using {@link BigDecimal#compareTo(BigDecimal)} * assertThat(new BigDecimal(&quot;8.0&quot;)).isNotEqualByComparingTo(new BigDecimal(&quot;8.00&quot;));</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is equal when comparing to the given one. */ SELF isNotEqualByComparingTo(ACTUAL other); /** * Verifies that the actual value is less than the given one. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat('a').isLessThan('b'); * assertThat(BigInteger.ZERO).isLessThan(BigInteger.ONE); * * // assertions will fail * assertThat('a').isLessThan('a'); * assertThat(BigInteger.ONE).isLessThan(BigInteger.ZERO);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is equal to or greater than the given one. */ SELF isLessThan(ACTUAL other); /** * Verifies that the actual value is less than or equal to the given one. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat('a').isLessThanOrEqualTo('b'); * assertThat('a').isLessThanOrEqualTo('a'); * assertThat(BigInteger.ZERO).isLessThanOrEqualTo(BigInteger.ZERO); * * // assertions will fail * assertThat('b').isLessThanOrEqualTo('a'); * assertThat(BigInteger.ONE).isLessThanOrEqualTo(BigInteger.ZERO);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is greater than the given one. */ SELF isLessThanOrEqualTo(ACTUAL other); /** * Verifies that the actual value is greater than the given one. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat('b').isGreaterThan('a'); * assertThat(BigInteger.ONE).isGreaterThan(BigInteger.ZERO); * * // assertions will fail * assertThat('b').isGreaterThan('a'); * assertThat(BigInteger.ZERO).isGreaterThan(BigInteger.ZERO);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is equal to or less than the given one. */ SELF isGreaterThan(ACTUAL other); /** * Verifies that the actual value is greater than or equal to the given one. * <p> * Example: * <pre><code class='java'> // assertions will pass * assertThat('b').isGreaterThanOrEqualTo('a'); * assertThat(BigInteger.ONE).isGreaterThanOrEqualTo(BigInteger.ONE); * * // assertions will fail * assertThat('a').isGreaterThanOrEqualTo('b'); * assertThat(BigInteger.ZERO).isGreaterThanOrEqualTo(BigInteger.ONE);</code></pre> * * @param other the given value to compare the actual value to. * @return {@code this} assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws AssertionError if the actual value is less than the given one. */ SELF isGreaterThanOrEqualTo(ACTUAL other); /** * Verifies that the actual value is in [start, end] range (start included, end included). * <p> * Example: * <pre><code class='java'> // assertions succeed * assertThat('b').isBetween('a', 'c'); * assertThat('a').isBetween('a', 'b'); * assertThat('b').isBetween('a', 'b'); * * // assertions fail * assertThat('a').isBetween('b', 'c'); * assertThat('c').isBetween('a', 'b');</code></pre> * * @param startInclusive the start value (inclusive), expected not to be null. * @param endInclusive the end value (inclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws NullPointerException if start value is {@code null}. * @throws NullPointerException if end value is {@code null}. * @throws AssertionError if the actual value is not in [start, end] range. * * @since 2.5.0 / 3.5.0 */ SELF isBetween(ACTUAL startInclusive, ACTUAL endInclusive); /** * Verifies that the actual value is in ]start, end[ range (start excluded, end excluded). * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat('b').isStrictlyBetween('a', 'c'); * * // assertions fail * assertThat('d').isStrictlyBetween('a', 'c'); * assertThat('a').isStrictlyBetween('b', 'd'); * assertThat('a').isStrictlyBetween('a', 'b'); * assertThat('b').isStrictlyBetween('a', 'b');</code></pre> * * @param startExclusive the start value (exclusive), expected not to be null. * @param endExclusive the end value (exclusive), expected not to be null. * @return this assertion object. * @throws AssertionError if the actual value is {@code null}. * @throws NullPointerException if start value is {@code null}. * @throws NullPointerException if end value is {@code null}. * @throws AssertionError if the actual value is not in ]start, end[ range. * * @since 2.5.0 / 3.5.0 */ SELF isStrictlyBetween(ACTUAL startExclusive, ACTUAL endExclusive); }
ComparableAssert
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdMapping.java
{ "start": 1508, "end": 3734 }
interface ____ extends VirtualModelPart { String PART_NAME = "{natural-id}"; /** * The attribute(s) making up the natural-id. */ List<SingularAttributeMapping> getNaturalIdAttributes(); /** * Whether the natural-id is mutable. * * @apiNote For compound natural-ids, this is true if any of the attributes are mutable. */ boolean isMutable(); @Override default String getPartName() { return PART_NAME; } /** * Access to the natural-id's L2 cache access. Returns null if the natural-id is not * configured for caching */ NaturalIdDataAccess getCacheAccess(); /** * Verify the natural-id value(s) we are about to flush to the database */ void verifyFlushState( Object id, Object[] currentState, Object[] loadedState, SharedSessionContractImplementor session); /** * Given an array of "full entity state", extract the normalized natural id representation * * @param state The attribute state array * * @return The extracted natural id values. This is a normalized */ Object extractNaturalIdFromEntityState(Object[] state); /** * Given an entity instance, extract the normalized natural id representation * * @param entity The entity instance * * @return The extracted natural id values */ Object extractNaturalIdFromEntity(Object entity); /** * Normalize a user-provided natural-id value into the representation Hibernate uses internally * * @param incoming The user-supplied value * @return The normalized, internal representation */ Object normalizeInput(Object incoming); /** * Validates a natural id value(s) for the described natural-id based on the expected internal representation */ void validateInternalForm(Object naturalIdValue); /** * Calculate the hash-code of a natural-id value * * @param value The natural-id value * @return The hash-code */ int calculateHashCode(Object value); /** * Make a loader capable of loading a single entity by natural-id */ NaturalIdLoader<?> makeLoader(EntityMappingType entityDescriptor); /** * Make a loader capable of loading multiple entities by natural-id */ MultiNaturalIdLoader<?> makeMultiLoader(EntityMappingType entityDescriptor); }
NaturalIdMapping
java
apache__camel
components/camel-cxf/camel-cxf-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsHeaderFilterStrategyTest.java
{ "start": 1164, "end": 2413 }
class ____ { @Test public void testFilterContentType() throws Exception { HeaderFilterStrategy filter = new CxfRsHeaderFilterStrategy(); assertTrue(filter.applyFilterToCamelHeaders("content-type", "just a test", null), "Get a wrong filtered result"); assertTrue(filter.applyFilterToCamelHeaders("Content-Type", "just a test", null), "Get a wrong filtered result"); } @Test public void testFilterCamelHeaders() throws Exception { HeaderFilterStrategy filter = new CxfRsHeaderFilterStrategy(); assertTrue(filter.applyFilterToCamelHeaders(Exchange.CHARSET_NAME, "just a test", null), "Get a wrong filtered result"); assertTrue(filter.applyFilterToCamelHeaders(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, "just a test", null), "Get a wrong filtered result"); assertTrue(filter.applyFilterToCamelHeaders("CamelHeader", "just a test", null), "Get a wrong filtered result"); assertTrue(filter.applyFilterToCamelHeaders("CamelResult", "just a test", null), "Get a wrong filtered result"); assertFalse(filter.applyFilterToCamelHeaders("MyWorld", "just a test", null), "Get a wrong filtered result"); } }
CxfRsHeaderFilterStrategyTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JavaInstantGetSecondsGetNanoTest.java
{ "start": 4210, "end": 4631 }
class ____ { public static void foo(Instant instant) { long seconds = instant.getEpochSecond(); } } """) .doTest(); } @Test public void getNanoOnly() { compilationHelper .addSourceLines( "test/TestCase.java", """ package test; import java.time.Instant; public
TestCase
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java
{ "start": 20903, "end": 33629 }
class ____ implements SectionProcessor { static final String NAME = "INodeSection"; @Override public void process() throws IOException { Node headerNode = new Node(); loadNodeChildren(headerNode, "INodeSection fields", "inode"); INodeSection.Builder b = INodeSection.newBuilder(); Long lval = headerNode.removeChildLong(INODE_SECTION_LAST_INODE_ID); if (lval != null) { b.setLastInodeId(lval); } Integer expectedNumINodes = headerNode.removeChildInt(INODE_SECTION_NUM_INODES); if (expectedNumINodes == null) { throw new IOException("Failed to find <numInodes> in INodeSection."); } b.setNumInodes(expectedNumINodes); INodeSection s = b.build(); s.writeDelimitedTo(out); headerNode.verifyNoRemainingKeys("INodeSection"); int actualNumINodes = 0; while (actualNumINodes < expectedNumINodes) { try { expectTag(INODE_SECTION_INODE, false); } catch (IOException e) { throw new IOException("Only found " + actualNumINodes + " <inode> entries out of " + expectedNumINodes, e); } actualNumINodes++; Node inode = new Node(); loadNodeChildren(inode, "INode fields"); INodeSection.INode.Builder inodeBld = processINodeXml(inode); inodeBld.build().writeDelimitedTo(out); } expectTagEnd(INODE_SECTION_NAME); recordSectionLength(SectionName.INODE.name()); } } private INodeSection.INode.Builder processINodeXml(Node node) throws IOException { String type = node.removeChildStr(INODE_SECTION_TYPE); if (type == null) { throw new IOException("INode XML found with no <type> tag."); } INodeSection.INode.Builder inodeBld = INodeSection.INode.newBuilder(); Long id = node.removeChildLong(SECTION_ID); if (id == null) { throw new IOException("<inode> found without <id>"); } inodeBld.setId(id); String name = node.removeChildStr(SECTION_NAME); if (name != null) { inodeBld.setName(ByteString.copyFrom(name, StandardCharsets.UTF_8)); } switch (type) { case "FILE": processFileXml(node, inodeBld); break; case "DIRECTORY": processDirectoryXml(node, inodeBld); break; case "SYMLINK": processSymlinkXml(node, inodeBld); break; default: throw new IOException("INode XML found with unknown <type> " + "tag " + type); } node.verifyNoRemainingKeys("inode"); return inodeBld; } private void processFileXml(Node node, INodeSection.INode.Builder inodeBld) throws IOException { inodeBld.setType(INodeSection.INode.Type.FILE); INodeSection.INodeFile.Builder bld = createINodeFileBuilder(node); inodeBld.setFile(bld); // Will check remaining keys and serialize in processINodeXml } private INodeSection.INodeFile.Builder createINodeFileBuilder(Node node) throws IOException { INodeSection.INodeFile.Builder bld = INodeSection.INodeFile.newBuilder(); Integer ival = node.removeChildInt(SECTION_REPLICATION); if (ival != null) { bld.setReplication(ival); } Long lval = node.removeChildLong(INODE_SECTION_MTIME); if (lval != null) { bld.setModificationTime(lval); } lval = node.removeChildLong(INODE_SECTION_ATIME); if (lval != null) { bld.setAccessTime(lval); } lval = node.removeChildLong(INODE_SECTION_PREFERRED_BLOCK_SIZE); if (lval != null) { bld.setPreferredBlockSize(lval); } String perm = node.removeChildStr(INODE_SECTION_PERMISSION); if (perm != null) { bld.setPermission(permissionXmlToU64(perm)); } Node blocks = node.removeChild(INODE_SECTION_BLOCKS); if (blocks != null) { while (true) { Node block = blocks.removeChild(INODE_SECTION_BLOCK); if (block == null) { break; } bld.addBlocks(createBlockBuilder(block)); } } Node fileUnderConstruction = node.removeChild(INODE_SECTION_FILE_UNDER_CONSTRUCTION); if (fileUnderConstruction != null) { INodeSection.FileUnderConstructionFeature.Builder fb = INodeSection.FileUnderConstructionFeature.newBuilder(); String clientName = fileUnderConstruction.removeChildStr(INODE_SECTION_CLIENT_NAME); if (clientName == null) { throw new IOException("<file-under-construction> found without " + "<clientName>"); } fb.setClientName(clientName); String clientMachine = fileUnderConstruction .removeChildStr(INODE_SECTION_CLIENT_MACHINE); if (clientMachine == null) { throw new IOException("<file-under-construction> found without " + "<clientMachine>"); } fb.setClientMachine(clientMachine); bld.setFileUC(fb); } Node acls = node.removeChild(INODE_SECTION_ACLS); if (acls != null) { bld.setAcl(aclXmlToProto(acls)); } Node xattrs = node.removeChild(INODE_SECTION_XATTRS); if (xattrs != null) { bld.setXAttrs(xattrsXmlToProto(xattrs)); } ival = node.removeChildInt(INODE_SECTION_STORAGE_POLICY_ID); if (ival != null) { bld.setStoragePolicyID(ival); } String blockType = node.removeChildStr(INODE_SECTION_BLOCK_TYPE); if(blockType != null) { switch (blockType) { case "CONTIGUOUS": bld.setBlockType(HdfsProtos.BlockTypeProto.CONTIGUOUS); break; case "STRIPED": bld.setBlockType(HdfsProtos.BlockTypeProto.STRIPED); ival = node.removeChildInt(INODE_SECTION_EC_POLICY_ID); if (ival != null) { bld.setErasureCodingPolicyID(ival); } break; default: throw new IOException("INode XML found with unknown <blocktype> " + blockType); } } return bld; } private HdfsProtos.BlockProto.Builder createBlockBuilder(Node block) throws IOException { HdfsProtos.BlockProto.Builder blockBld = HdfsProtos.BlockProto.newBuilder(); Long id = block.removeChildLong(SECTION_ID); if (id == null) { throw new IOException("<block> found without <id>"); } blockBld.setBlockId(id); Long genstamp = block.removeChildLong(INODE_SECTION_GENSTAMP); if (genstamp == null) { throw new IOException("<block> found without <genstamp>"); } blockBld.setGenStamp(genstamp); Long numBytes = block.removeChildLong(INODE_SECTION_NUM_BYTES); if (numBytes == null) { throw new IOException("<block> found without <numBytes>"); } blockBld.setNumBytes(numBytes); return blockBld; } private void processDirectoryXml(Node node, INodeSection.INode.Builder inodeBld) throws IOException { inodeBld.setType(INodeSection.INode.Type.DIRECTORY); INodeSection.INodeDirectory.Builder bld = createINodeDirectoryBuilder(node); inodeBld.setDirectory(bld); // Will check remaining keys and serialize in processINodeXml } private INodeSection.INodeDirectory.Builder createINodeDirectoryBuilder(Node node) throws IOException { INodeSection.INodeDirectory.Builder bld = INodeSection.INodeDirectory.newBuilder(); Long lval = node.removeChildLong(INODE_SECTION_MTIME); if (lval != null) { bld.setModificationTime(lval); } lval = node.removeChildLong(INODE_SECTION_NS_QUOTA); if (lval != null) { bld.setNsQuota(lval); } lval = node.removeChildLong(INODE_SECTION_DS_QUOTA); if (lval != null) { bld.setDsQuota(lval); } String perm = node.removeChildStr(INODE_SECTION_PERMISSION); if (perm != null) { bld.setPermission(permissionXmlToU64(perm)); } Node acls = node.removeChild(INODE_SECTION_ACLS); if (acls != null) { bld.setAcl(aclXmlToProto(acls)); } Node xattrs = node.removeChild(INODE_SECTION_XATTRS); if (xattrs != null) { bld.setXAttrs(xattrsXmlToProto(xattrs)); } INodeSection.QuotaByStorageTypeFeatureProto.Builder qf = INodeSection.QuotaByStorageTypeFeatureProto.newBuilder(); while (true) { Node typeQuota = node.removeChild(INODE_SECTION_TYPE_QUOTA); if (typeQuota == null) { break; } INodeSection.QuotaByStorageTypeEntryProto.Builder qbld = INodeSection.QuotaByStorageTypeEntryProto.newBuilder(); String type = typeQuota.removeChildStr(INODE_SECTION_TYPE); if (type == null) { throw new IOException("<typeQuota> was missing <type>"); } HdfsProtos.StorageTypeProto storageType = HdfsProtos.StorageTypeProto.valueOf(type); if (storageType == null) { throw new IOException("<typeQuota> had unknown <type> " + type); } qbld.setStorageType(storageType); Long quota = typeQuota.removeChildLong(INODE_SECTION_QUOTA); if (quota == null) { throw new IOException("<typeQuota> was missing <quota>"); } qbld.setQuota(quota); qf.addQuotas(qbld); } bld.setTypeQuotas(qf); return bld; } private void processSymlinkXml(Node node, INodeSection.INode.Builder inodeBld) throws IOException { inodeBld.setType(INodeSection.INode.Type.SYMLINK); INodeSection.INodeSymlink.Builder bld = INodeSection.INodeSymlink.newBuilder(); String perm = node.removeChildStr(INODE_SECTION_PERMISSION); if (perm != null) { bld.setPermission(permissionXmlToU64(perm)); } String target = node.removeChildStr(INODE_SECTION_TARGET); if (target != null) { bld.setTarget(ByteString.copyFrom(target, StandardCharsets.UTF_8)); } Long lval = node.removeChildLong(INODE_SECTION_MTIME); if (lval != null) { bld.setModificationTime(lval); } lval = node.removeChildLong(INODE_SECTION_ATIME); if (lval != null) { bld.setAccessTime(lval); } inodeBld.setSymlink(bld); // Will check remaining keys and serialize in processINodeXml } private INodeSection.AclFeatureProto.Builder aclXmlToProto(Node acls) throws IOException { AclFeatureProto.Builder b = AclFeatureProto.newBuilder(); while (true) { Node acl = acls.removeChild(INODE_SECTION_ACL); if (acl == null) { break; } String val = acl.getVal(); AclEntry entry = AclEntry.parseAclEntry(val, true); int nameId = registerStringId(entry.getName() == null ? EMPTY_STRING : entry.getName()); int v = ((nameId & ACL_ENTRY_NAME_MASK) << ACL_ENTRY_NAME_OFFSET) | (entry.getType().ordinal() << ACL_ENTRY_TYPE_OFFSET) | (entry.getScope().ordinal() << ACL_ENTRY_SCOPE_OFFSET) | (entry.getPermission().ordinal()); b.addEntries(v); } return b; } private INodeSection.XAttrFeatureProto.Builder xattrsXmlToProto(Node xattrs) throws IOException { INodeSection.XAttrFeatureProto.Builder bld = INodeSection.XAttrFeatureProto.newBuilder(); while (true) { Node xattr = xattrs.removeChild(INODE_SECTION_XATTR); if (xattr == null) { break; } INodeSection.XAttrCompactProto.Builder b = INodeSection.XAttrCompactProto.newBuilder(); String ns = xattr.removeChildStr(INODE_SECTION_NS); if (ns == null) { throw new IOException("<xattr> had no <ns> entry."); } int nsIdx = XAttrProtos.XAttrProto. XAttrNamespaceProto.valueOf(ns).ordinal(); String name = xattr.removeChildStr(SECTION_NAME); String valStr = xattr.removeChildStr(INODE_SECTION_VAL); byte[] val = null; if (valStr == null) { String valHex = xattr.removeChildStr(INODE_SECTION_VAL_HEX); if (valHex == null) { throw new IOException("<xattr> had no <val> or <valHex> entry."); } val = new HexBinaryAdapter().unmarshal(valHex); } else { val = valStr.getBytes(StandardCharsets.UTF_8); } b.setValue(ByteString.copyFrom(val)); // The XAttrCompactProto name field uses a fairly complex format // to encode both the string table ID of the xattr name and the // namespace ID. See the protobuf file for details. int nameId = registerStringId(name); int encodedName = (nameId << XATTR_NAME_OFFSET) | ((nsIdx & XATTR_NAMESPACE_MASK) << XATTR_NAMESPACE_OFFSET) | (((nsIdx >> 2) & XATTR_NAMESPACE_EXT_MASK) << XATTR_NAMESPACE_EXT_OFFSET); b.setName(encodedName); xattr.verifyNoRemainingKeys("xattr"); bld.addXAttrs(b); } xattrs.verifyNoRemainingKeys("xattrs"); return bld; } private
INodeSectionProcessor
java
grpc__grpc-java
api/src/test/java/io/grpc/ManagedChannelRegistryTest.java
{ "start": 5865, "end": 6990 }
class ____ extends SocketAddress { } nameResolverRegistry.register(new BaseNameResolverProvider(true, 5, "sc1") { @Override public Collection<Class<? extends SocketAddress>> getProducedSocketAddressTypes() { return Collections.singleton(SocketAddress1.class); } }); nameResolverRegistry.register(new BaseNameResolverProvider(true, 6, "sc2") { @Override public Collection<Class<? extends SocketAddress>> getProducedSocketAddressTypes() { fail("Should not be called"); throw new AssertionError(); } }); ManagedChannelRegistry registry = new ManagedChannelRegistry(); registry.register(new BaseProvider(true, 5) { @Override protected Collection<Class<? extends SocketAddress>> getSupportedSocketAddressTypes() { return Collections.singleton(SocketAddress2.class); } @Override public NewChannelBuilderResult newChannelBuilder( String passedTarget, ChannelCredentials passedCreds) { fail("Should not be called"); throw new AssertionError(); } });
SocketAddress2
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java
{ "start": 63723, "end": 64213 }
enum ____ { /** Ordered output mode, equivalent to {@see AsyncDataStream.OutputMode.ORDERED}. */ ORDERED, /** * Allow unordered output mode, will attempt to use {@see * AsyncDataStream.OutputMode.UNORDERED} when it does not affect the correctness of the * result, otherwise ORDERED will be still used. */ ALLOW_UNORDERED } /** Retry strategy in the case of failure. */ @PublicEvolving public
AsyncOutputMode
java
apache__camel
components/camel-velocity/src/test/java/org/apache/camel/component/velocity/VelocityContentCacheTest.java
{ "start": 1277, "end": 7202 }
class ____ extends CamelTestSupport { @Override public void doPostSetup() { // create a vm file in the classpath as this is the tricky reloading stuff template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Hello $headers.name", Exchange.FILE_NAME, "hello.vm"); } @Override public boolean useJmx() { return true; } @Test public void testNotCached() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:a", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Bye $headers.name", Exchange.FILE_NAME, "hello.vm"); mock.reset(); mock.expectedBodiesReceived("Bye Paris", "Bye World"); template.sendBodyAndHeader("direct:a", "Body", "name", "Paris"); template.sendBodyAndHeader("direct:a", "Body", "name", "World"); mock.assertIsSatisfied(); } @Test public void testCached() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:b", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Bye $headers.name", Exchange.FILE_NAME, "hello.vm"); mock.reset(); // we must expected the original filecontent as the cache is enabled, so its Hello and not Bye mock.expectedBodiesReceived("Hello Paris"); template.sendBodyAndHeader("direct:b", "Body", "name", "Paris"); mock.assertIsSatisfied(); } @Test public void testCachedIsDefault() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:c", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Bye $headers.name", Exchange.FILE_NAME, "hello.vm"); mock.reset(); // we must expected the original filecontent as the cache is enabled, so its Hello and not Bye mock.expectedBodiesReceived("Hello Paris"); template.sendBodyAndHeader("direct:c", "Body", "name", "Paris"); mock.assertIsSatisfied(); } @Test public void testClearCacheViaJmx() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello London"); template.sendBodyAndHeader("direct:b", "Body", "name", "London"); mock.assertIsSatisfied(); // now change content in the file in the classpath and try again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Bye $headers.name", Exchange.FILE_NAME, "hello.vm"); mock.reset(); // we must expected the original filecontent as the cache is enabled, so its Hello and not Bye mock.expectedBodiesReceived("Hello Paris"); template.sendBodyAndHeader("direct:b", "Body", "name", "Paris"); mock.assertIsSatisfied(); // clear the cache via the mbean server MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer(); Set<ObjectName> objNameSet = mbeanServer .queryNames(new ObjectName("org.apache.camel:type=endpoints,name=\"velocity:*contentCache=true*\",*"), null); ObjectName managedObjName = new ArrayList<>(objNameSet).get(0); mbeanServer.invoke(managedObjName, "clearContentCache", null, null); // now change content in the file in the classpath template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Bye $headers.name", Exchange.FILE_NAME, "hello.vm"); mock.reset(); // we expect the update to work now since the cache has been cleared mock.expectedBodiesReceived("Bye Paris"); template.sendBodyAndHeader("direct:b", "Body", "name", "Paris"); mock.assertIsSatisfied(); // change the content in the file again template.sendBodyAndHeader("file://target/test-classes/org/apache/camel/component/velocity?fileExist=Override", "Hello $headers.name", Exchange.FILE_NAME, "hello.vm"); mock.reset(); // we expect the new value to be ignored since the cache was re-established with the prior exchange mock.expectedBodiesReceived("Bye Paris"); template.sendBodyAndHeader("direct:b", "Body", "name", "Paris"); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:a").to("velocity://org/apache/camel/component/velocity/hello.vm?contentCache=false") .to("mock:result"); from("direct:b").to("velocity://org/apache/camel/component/velocity/hello.vm?contentCache=true") .to("mock:result"); from("direct:c").to("velocity://org/apache/camel/component/velocity/hello.vm").to("mock:result"); } }; } }
VelocityContentCacheTest
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/listener/startup/NacosWebStartUp.java
{ "start": 772, "end": 1301 }
class ____ extends AbstractNacosStartUp { public NacosWebStartUp() { super(NacosStartUp.WEB_START_UP_PHASE); } @Override protected String getPhaseNameInStartingInfo() { return "Nacos Server API"; } @Override public void logStarted(Logger logger) { long endTimestamp = System.currentTimeMillis(); long startupCost = endTimestamp - getStartTimestamp(); logger.info("Nacos Server API started successfully in {} ms", startupCost); } }
NacosWebStartUp
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSource.java
{ "start": 2502, "end": 4373 }
class ____ extends AbstractFallbackTransactionAttributeSource implements Serializable { private static final boolean JTA_PRESENT; private static final boolean EJB_3_PRESENT; static { ClassLoader classLoader = AnnotationTransactionAttributeSource.class.getClassLoader(); JTA_PRESENT = ClassUtils.isPresent("jakarta.transaction.Transactional", classLoader); EJB_3_PRESENT = ClassUtils.isPresent("jakarta.ejb.TransactionAttribute", classLoader); } private final Set<TransactionAnnotationParser> annotationParsers; private boolean publicMethodsOnly = true; private @Nullable Set<RollbackRuleAttribute> defaultRollbackRules; /** * Create a default AnnotationTransactionAttributeSource, supporting * public methods that carry the {@code Transactional} annotation * or the EJB3 {@link jakarta.ejb.TransactionAttribute} annotation. */ public AnnotationTransactionAttributeSource() { if (JTA_PRESENT || EJB_3_PRESENT) { this.annotationParsers = CollectionUtils.newLinkedHashSet(3); this.annotationParsers.add(new SpringTransactionAnnotationParser()); if (JTA_PRESENT) { this.annotationParsers.add(new JtaTransactionAnnotationParser()); } if (EJB_3_PRESENT) { this.annotationParsers.add(new Ejb3TransactionAnnotationParser()); } } else { this.annotationParsers = Collections.singleton(new SpringTransactionAnnotationParser()); } } /** * Create a custom AnnotationTransactionAttributeSource, supporting * public methods that carry the {@code Transactional} annotation * or the EJB3 {@link jakarta.ejb.TransactionAttribute} annotation. * @param publicMethodsOnly whether to support public methods that carry * the {@code Transactional} annotation only (typically for use * with proxy-based AOP), or protected/private methods as well * (typically used with AspectJ
AnnotationTransactionAttributeSource
java
quarkusio__quarkus
extensions/amazon-lambda/deployment/src/test/java/io/quarkus/amazon/lambda/deployment/RequestHandlerJandexUtilTest.java
{ "start": 23155, "end": 23379 }
interface ____ extends BaseInterfaceNoDefault { @Override default Byte handleRequest(Float input, Context context) { return input.byteValue(); } } public static
NestedDefaultInterface
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.java
{ "start": 31968, "end": 32549 }
class ____<Z> { public Tuple1<Z>[] field; } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference7() { MyMapper7<Integer> function = new MyMapper7<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of( new TypeHint<PojoWithParameterizedFields4<Integer>>() {})); assertThat(ti).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } public static
PojoWithParameterizedFields4
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmManager.java
{ "start": 5112, "end": 5560 }
class ____ {}", realmId); return classRealm; } catch (DuplicateRealmException e) { realmId = id + '-' + random.nextInt(); } } } } @Override public ClassRealm getMavenApiRealm() { return mavenApiRealm; } @Override public ClassRealm getMaven4ApiRealm() { return maven4ApiRealm; } /** * Creates a new
realm
java
apache__maven
impl/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithProblemMessageAssert.java
{ "start": 1184, "end": 2656 }
class ____ { private final ProjectBuildingResult actual; ProjectBuildingResultWithProblemMessageAssert(ProjectBuildingResult actual) { this.actual = actual; } public static ProjectBuildingResultWithProblemMessageAssert assertThat(ProjectBuildingResult actual) { return new ProjectBuildingResultWithProblemMessageAssert(actual); } public ProjectBuildingResultWithProblemMessageAssert hasProblemMessage(String problemMessage) { assertNotNull(actual); boolean hasMessage = actual.getProblems().stream().anyMatch(p -> p.getMessage().contains(problemMessage)); if (!hasMessage) { String actualMessages = actual.getProblems().stream() .map(ModelProblem::getMessage) .map(m -> "\"" + m + "\"") .collect(joining(", ")); String message = String.format( "Expected ProjectBuildingResult to have problem message containing <%s> but had messages <%s>", problemMessage, actualMessages); assertTrue(false, message); } return this; } // Helper method for backward compatibility static ProjectBuildingResultWithProblemMessageAssert projectBuildingResultWithProblemMessage(String message) { return new ProjectBuildingResultWithProblemMessageAssert(null).hasProblemMessage(message); } }
ProjectBuildingResultWithProblemMessageAssert
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
{ "start": 25151, "end": 27069 }
class ____ { // empty } assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new Object() { // empty }.getClass())); assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(Named.class)); assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new Serializable() { private static final long serialVersionUID = 1L; }.getClass())); assertEquals("java.util.function", ClassUtils.getPackageName(Function.identity().getClass())); } @Test void test_getPackageName_Object() { assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new ClassUtils(), "<null>")); assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new Inner(), "<null>")); assertEquals("<null>", ClassUtils.getPackageName(null, "<null>")); } @Test void test_getPackageName_String() { assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(ClassUtils.class.getName())); assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class.getName())); assertEquals("", ClassUtils.getPackageName((String) null)); assertEquals("", ClassUtils.getPackageName("")); } @Test void test_getShortCanonicalName_Class() { assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(ClassUtils.class)); assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName(ClassUtils[].class)); assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName(ClassUtils[][].class)); assertEquals("int[]", ClassUtils.getShortCanonicalName(int[].class)); assertEquals("int[][]", ClassUtils.getShortCanonicalName(int[][].class)); assertEquals("int[][][][][][][][][][]", ClassUtils.getShortCanonicalName(int[][][][][][][][][][].class)); // Inner types final
Named
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java
{ "start": 10138, "end": 21361 }
class ____ extends TestConnection { private int setExceptionListenerInvocationCounter; @Override public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException { setExceptionListenerInvocationCounter++; // Throw JMSException on first invocation if (setExceptionListenerInvocationCounter == 1) { throw new JMSException("Test JMSException (setExceptionListener())"); } super.setExceptionListener(exceptionListener); } } // Prepare base JMS ConnectionFactory // - createConnection(1st) -> TestConnection, // - createConnection(2nd and next) -> FailingTestConnection FailingTestConnection failingCon = new FailingTestConnection(); AtomicInteger createConnectionMethodCounter = new AtomicInteger(); ConnectionFactory cf = mock(ConnectionFactory.class); given(cf.createConnection()).willAnswer(invocation -> { int methodInvocationCounter = createConnectionMethodCounter.incrementAndGet(); return (methodInvocationCounter >= 4 ? failingCon : new TestConnection()); }); // Prepare SingleConnectionFactory (setReconnectOnException()) // - internal connection exception listener should be registered SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setReconnectOnException(true); Field conField = ReflectionUtils.findField(SingleConnectionFactory.class, "connection"); conField.setAccessible(true); assertThat(scf.isRunning()).isFalse(); // Get connection (1st) Connection con1 = scf.getConnection(); assertThat(createConnectionMethodCounter.get()).isEqualTo(1); assertThat(con1.getExceptionListener()).isNotNull(); assertThat(con1).isSameAs(conField.get(scf)); assertThat(scf.isRunning()).isTrue(); // Get connection again, the same should be returned (shared connection till some problem) Connection con2 = scf.getConnection(); assertThat(createConnectionMethodCounter.get()).isEqualTo(1); assertThat(con2.getExceptionListener()).isNotNull(); assertThat(con2).isSameAs(con1); assertThat(scf.isRunning()).isTrue(); // Explicit stop should reset connection scf.stop(); assertThat(conField.get(scf)).isNull(); assertThat(scf.isRunning()).isFalse(); Connection con3 = scf.getConnection(); assertThat(createConnectionMethodCounter.get()).isEqualTo(2); assertThat(con3.getExceptionListener()).isNotNull(); assertThat(con3).isNotSameAs(con2); assertThat(scf.isRunning()).isTrue(); // Explicit stop-and-restart should refresh connection scf.stop(); assertThat(conField.get(scf)).isNull(); assertThat(scf.isRunning()).isFalse(); scf.start(); assertThat(scf.isRunning()).isTrue(); assertThat(conField.get(scf)).isNotNull(); Connection con4 = scf.getConnection(); assertThat(createConnectionMethodCounter.get()).isEqualTo(3); assertThat(con4.getExceptionListener()).isNotNull(); assertThat(con4).isNotSameAs(con3); // Invoke reset connection to simulate problem with connection // - SCF exception listener should be invoked -> connection should be set to null // - next attempt to invoke getConnection() must create new connection scf.resetConnection(); assertThat(conField.get(scf)).isNull(); // Attempt to get connection again // - JMSException should be returned from FailingTestConnection // - connection should be still null (no new connection without exception listener like before fix) assertThatExceptionOfType(JMSException.class).isThrownBy(() -> scf.getConnection()); assertThat(createConnectionMethodCounter.get()).isEqualTo(4); assertThat(conField.get(scf)).isNull(); // Attempt to get connection again -> FailingTestConnection should be returned // - no JMSException is thrown, exception listener should be present Connection con5 = scf.getConnection(); assertThat(createConnectionMethodCounter.get()).isEqualTo(5); assertThat(con5).isNotNull(); assertThat(con5).isSameAs(failingCon); assertThat(con5.getExceptionListener()).isNotNull(); assertThat(con5).isNotSameAs(con4); scf.destroy(); assertThat(conField.get(scf)).isNull(); assertThat(scf.isRunning()).isFalse(); } @Test void testWithConnectionFactoryAndLocalExceptionListenerWithCleanup() throws JMSException { ConnectionFactory cf = mock(); TestConnection con = new TestConnection(); given(cf.createConnection()).willReturn(con); TestExceptionListener listener0 = new TestExceptionListener(); TestExceptionListener listener1 = new TestExceptionListener(); TestExceptionListener listener2 = new TestExceptionListener(); SingleConnectionFactory scf = new SingleConnectionFactory(cf) { @Override public void onException(JMSException ex) { // no-op } }; scf.setReconnectOnException(true); scf.setExceptionListener(listener0); Connection con1 = scf.createConnection(); con1.setExceptionListener(listener1); assertThat(con1.getExceptionListener()).isSameAs(listener1); Connection con2 = scf.createConnection(); con2.setExceptionListener(listener2); assertThat(con2.getExceptionListener()).isSameAs(listener2); con.getExceptionListener().onException(new JMSException("")); con2.close(); con.getExceptionListener().onException(new JMSException("")); con1.close(); con.getExceptionListener().onException(new JMSException("")); scf.destroy(); // should trigger actual close assertThat(con.getStartCount()).isEqualTo(0); assertThat(con.getCloseCount()).isEqualTo(1); assertThat(listener0.getCount()).isEqualTo(3); assertThat(listener1.getCount()).isEqualTo(2); assertThat(listener2.getCount()).isEqualTo(1); } @Test void testWithConnectionFactoryAndLocalExceptionListenerWithReconnect() throws JMSException { ConnectionFactory cf = mock(); TestConnection con = new TestConnection(); given(cf.createConnection()).willReturn(con); TestExceptionListener listener0 = new TestExceptionListener(); TestExceptionListener listener1 = new TestExceptionListener(); TestExceptionListener listener2 = new TestExceptionListener(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setReconnectOnException(true); scf.setExceptionListener(listener0); Connection con1 = scf.createConnection(); con1.setExceptionListener(listener1); assertThat(con1.getExceptionListener()).isSameAs(listener1); con1.start(); Connection con2 = scf.createConnection(); con2.setExceptionListener(listener2); assertThat(con2.getExceptionListener()).isSameAs(listener2); con.getExceptionListener().onException(new JMSException("")); con2.close(); con1.getMetaData(); con.getExceptionListener().onException(new JMSException("")); con1.close(); scf.destroy(); // should trigger actual close assertThat(con.getStartCount()).isEqualTo(2); assertThat(con.getCloseCount()).isEqualTo(2); assertThat(listener0.getCount()).isEqualTo(2); assertThat(listener1.getCount()).isEqualTo(2); assertThat(listener2.getCount()).isEqualTo(1); } @Test void testCachingConnectionFactory() throws JMSException { ConnectionFactory cf = mock(); Connection con = mock(); Session txSession = mock(); Session nonTxSession = mock(); given(cf.createConnection()).willReturn(con); given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); given(txSession.getTransacted()).willReturn(true); given(con.createSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); Connection con1 = scf.createConnection(); Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE); session1.getTransacted(); session1.close(); // should lead to rollback session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE); session1.close(); con1.start(); Connection con2 = scf.createConnection(); Session session2 = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); session2.close(); session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); session2.commit(); session2.close(); con2.start(); con1.close(); con2.close(); scf.destroy(); // should trigger actual close verify(txSession).commit(); verify(txSession).close(); verify(nonTxSession).close(); verify(con).start(); verify(con).stop(); verify(con).close(); } @Test void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException { QueueConnectionFactory cf = mock(); QueueConnection con = mock(); QueueSession txSession = mock(); QueueSession nonTxSession = mock(); given(cf.createQueueConnection()).willReturn(con); given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); given(txSession.getTransacted()).willReturn(true); given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); Connection con1 = scf.createQueueConnection(); Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE); session1.rollback(); session1.close(); session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE); session1.close(); con1.start(); QueueConnection con2 = scf.createQueueConnection(); Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); session2.close(); session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); session2.getTransacted(); session2.close(); // should lead to rollback con2.start(); con1.close(); con2.close(); scf.destroy(); // should trigger actual close verify(txSession).rollback(); verify(txSession).close(); verify(nonTxSession).close(); verify(con).start(); verify(con).stop(); verify(con).close(); } @Test void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException { TopicConnectionFactory cf = mock(); TopicConnection con = mock(); TopicSession txSession = mock(); TopicSession nonTxSession = mock(); given(cf.createTopicConnection()).willReturn(con); given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); given(txSession.getTransacted()).willReturn(true); given(con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); Connection con1 = scf.createTopicConnection(); Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE); session1.getTransacted(); session1.close(); // should lead to rollback session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE); session1.close(); con1.start(); TopicConnection con2 = scf.createTopicConnection(); Session session2 = con2.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); session2.close(); session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); session2.getTransacted(); session2.close(); con2.start(); con1.close(); con2.close(); scf.destroy(); // should trigger actual close verify(txSession).close(); verify(nonTxSession).close(); verify(con).start(); verify(con).stop(); verify(con).close(); } }
FailingTestConnection
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 44897, "end": 45358 }
class ____ { int BEST = 42; } """) .doTest(TestMode.AST_MATCH); } @Test public void removeSuppressWarnings_twoWarning_removesWarningAndNewArray() { BugCheckerRefactoringTestHelper refactorTestHelper = BugCheckerRefactoringTestHelper.newInstance(RemoveSuppressFromMe.class, getClass()); refactorTestHelper .addInputLines( "in/Test.java", """ public
Test
java
apache__flink
flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/wordcount/util/CLI.java
{ "start": 1451, "end": 5453 }
class ____ extends ExecutionConfig.GlobalJobParameters { public static final String INPUT_KEY = "input"; public static final String OUTPUT_KEY = "output"; public static final String DISCOVERY_INTERVAL = "discovery-interval"; public static final String EXECUTION_MODE = "execution-mode"; public static final String ASYNC_STATE = "async-state"; public static CLI fromArgs(String[] args) throws Exception { MultipleParameterTool params = MultipleParameterTool.fromArgs(args); Path[] inputs = null; if (params.has(INPUT_KEY)) { inputs = params.getMultiParameterRequired(INPUT_KEY).stream() .map(Path::new) .toArray(Path[]::new); } else { System.out.println("Executing example with default input data."); System.out.println("Use --input to specify file input."); } Path output = null; if (params.has(OUTPUT_KEY)) { output = new Path(params.get(OUTPUT_KEY)); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); } Duration watchInterval = null; if (params.has(DISCOVERY_INTERVAL)) { watchInterval = TimeUtils.parseDuration(params.get(DISCOVERY_INTERVAL)); } RuntimeExecutionMode executionMode = ExecutionOptions.RUNTIME_MODE.defaultValue(); if (params.has(EXECUTION_MODE)) { executionMode = RuntimeExecutionMode.valueOf(params.get(EXECUTION_MODE).toUpperCase()); } boolean asyncState = false; if (params.has(ASYNC_STATE)) { asyncState = true; } return new CLI(inputs, output, watchInterval, executionMode, params, asyncState); } private final Path[] inputs; private final Path output; private final Duration discoveryInterval; private final RuntimeExecutionMode executionMode; private final MultipleParameterTool params; private final boolean asyncState; private CLI( Path[] inputs, Path output, Duration discoveryInterval, RuntimeExecutionMode executionMode, MultipleParameterTool params, boolean asyncState) { this.inputs = inputs; this.output = output; this.discoveryInterval = discoveryInterval; this.executionMode = executionMode; this.params = params; this.asyncState = asyncState; } public Optional<Path[]> getInputs() { return Optional.ofNullable(inputs); } public Optional<Duration> getDiscoveryInterval() { return Optional.ofNullable(discoveryInterval); } public Optional<Path> getOutput() { return Optional.ofNullable(output); } public RuntimeExecutionMode getExecutionMode() { return executionMode; } public boolean isAsyncState() { return asyncState; } public OptionalInt getInt(String key) { if (params.has(key)) { return OptionalInt.of(params.getInt(key)); } return OptionalInt.empty(); } @Override public Map<String, String> toMap() { return params.toMap(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } CLI cli = (CLI) o; return Arrays.equals(inputs, cli.inputs) && Objects.equals(output, cli.output) && Objects.equals(discoveryInterval, cli.discoveryInterval) && asyncState == cli.asyncState; } @Override public int hashCode() { int result = Objects.hash(output, discoveryInterval); result = 31 * result + Arrays.hashCode(inputs); return result; } }
CLI
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallFilterConfigSpiForNullDbTypeTest.java
{ "start": 174, "end": 1173 }
class ____ extends TestCase { private DruidDataSource dataSource; private WallFilter wallFilter; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver"); dataSource.setUrl("jdbc:nodb:mem:wall_test;"); dataSource.setFilters("wall"); dataSource.init(); wallFilter = (WallFilter) dataSource.getProxyFilters().get(0); } protected void tearDown() throws Exception { dataSource.close(); } public void test_wallFilter() throws Exception { System.out.println("wallFilter= " + wallFilter); System.out.println("wallFilter.getConfig()= " + wallFilter.getConfig()); System.out.println("wallFilter.getConfig()= " + wallFilter.getProvider().getClass()); assertNull(wallFilter.getConfig()); assertTrue(wallFilter.getProvider() instanceof NullWallProvider); } }
WallFilterConfigSpiForNullDbTypeTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/util/Arrays_nonNullElementsIn_Test.java
{ "start": 961, "end": 1769 }
class ____ { @Test void should_return_empty_Collection_if_given_array_is_null() { assertThat(Arrays.nonNullElementsIn(null)).isEmpty(); } @Test void should_return_an_empty_Collection_if_given_array_has_only_null_elements() { String[] array = new String[] { null }; assertThat(Arrays.nonNullElementsIn(array)).isEmpty(); } @Test void should_return_an_empty_Collection_if_given_array_is_empty() { String[] array = new String[0]; assertThat(Arrays.nonNullElementsIn(array)).isEmpty(); } @Test void should_return_a_Collection_without_null_elements() { String[] array = { "Frodo", null, "Sam", null }; List<String> nonNull = nonNullElementsIn(array); assertThat(nonNull.toArray()).isEqualTo(new String[] { "Frodo", "Sam" }); } }
Arrays_nonNullElementsIn_Test
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySource.java
{ "start": 1221, "end": 4104 }
interface ____ { /** * Return a single {@link ConfigurationProperty} from the source or {@code null} if no * property can be found. * @param name the name of the property * @return the associated object or {@code null}. */ @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name); /** * Returns if the source contains any descendants of the specified name. May return * {@link ConfigurationPropertyState#PRESENT} or * {@link ConfigurationPropertyState#ABSENT} if an answer can be determined or * {@link ConfigurationPropertyState#UNKNOWN} if it's not possible to determine a * definitive answer. * @param name the name to check * @return if the source contains any descendants */ default ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { return ConfigurationPropertyState.UNKNOWN; } /** * Return a filtered variant of this source, containing only names that match the * given {@link Predicate}. * @param filter the filter to match * @return a filtered {@link ConfigurationPropertySource} instance */ default ConfigurationPropertySource filter(Predicate<ConfigurationPropertyName> filter) { return new FilteredConfigurationPropertiesSource(this, filter); } /** * Return a variant of this source that supports name aliases. * @param aliases a function that returns a stream of aliases for any given name * @return a {@link ConfigurationPropertySource} instance supporting name aliases */ default ConfigurationPropertySource withAliases(ConfigurationPropertyNameAliases aliases) { return new AliasedConfigurationPropertySource(this, aliases); } /** * Return a variant of this source that supports a prefix. * @param prefix the prefix for properties in the source * @return a {@link ConfigurationPropertySource} instance supporting a prefix * @since 2.5.0 */ default ConfigurationPropertySource withPrefix(@Nullable String prefix) { return (StringUtils.hasText(prefix)) ? new PrefixedConfigurationPropertySource(this, prefix) : this; } /** * Return the underlying source that is actually providing the properties. * @return the underlying property source or {@code null}. */ default @Nullable Object getUnderlyingSource() { return null; } /** * Return a single new {@link ConfigurationPropertySource} adapted from the given * Spring {@link PropertySource} or {@code null} if the source cannot be adapted. * @param source the Spring property source to adapt * @return an adapted source or {@code null} {@link SpringConfigurationPropertySource} * @since 2.4.0 */ static @Nullable ConfigurationPropertySource from(PropertySource<?> source) { if (source instanceof ConfigurationPropertySourcesPropertySource) { return null; } return SpringConfigurationPropertySource.from(source); } }
ConfigurationPropertySource
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedDetachedMultipleCollection.java
{ "start": 2016, "end": 6347 }
class ____ extends AbstractModifiedFlagsEntityTest { private Long mce1Id = null; private Long mce2Id = null; private Long mcre1Id = null; private Long mcre2Id = null; MultipleCollectionEntity mce1; MultipleCollectionRefEntity1 mcre1; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { // Revision 1 - addition. em.getTransaction().begin(); mce1 = new MultipleCollectionEntity(); mce1.setText( "MultipleCollectionEntity-1-1" ); em.persist( mce1 ); // Persisting entity with empty collections. em.getTransaction().commit(); mce1Id = mce1.getId(); // Revision 2 - update. em.getTransaction().begin(); mce1 = em.find( MultipleCollectionEntity.class, mce1.getId() ); mcre1 = new MultipleCollectionRefEntity1(); mcre1.setText( "MultipleCollectionRefEntity1-1-1" ); mcre1.setMultipleCollectionEntity( mce1 ); mce1.addRefEntity1( mcre1 ); em.persist( mcre1 ); mce1 = em.merge( mce1 ); em.getTransaction().commit(); mcre1Id = mcre1.getId(); // No changes. em.getTransaction().begin(); mce1 = em.find( MultipleCollectionEntity.class, mce1.getId() ); mce1 = em.merge( mce1 ); em.getTransaction().commit(); } ); scope.inEntityManager( em -> { // Revision 3 - updating detached collection. em.getTransaction().begin(); mce1.removeRefEntity1( mcre1 ); mce1 = em.merge( mce1 ); em.getTransaction().commit(); } ); scope.inEntityManager( em -> { // Revision 4 - updating detached entity, no changes to collection attributes. em.getTransaction().begin(); mce1.setRefEntities1( new ArrayList<>() ); mce1.setRefEntities2( new ArrayList<>() ); mce1.setText( "MultipleCollectionEntity-1-2" ); mce1 = em.merge( mce1 ); em.getTransaction().commit(); } ); scope.inEntityManager( em -> { // No changes to detached entity (collections were empty before). em.getTransaction().begin(); mce1.setRefEntities1( new ArrayList<>() ); mce1.setRefEntities2( new ArrayList<>() ); mce1 = em.merge( mce1 ); em.getTransaction().commit(); // Revision 5 - addition. em.getTransaction().begin(); MultipleCollectionEntity mce2 = new MultipleCollectionEntity(); mce2.setText( "MultipleCollectionEntity-2-1" ); MultipleCollectionRefEntity2 mcre2 = new MultipleCollectionRefEntity2(); mcre2.setText( "MultipleCollectionRefEntity2-1-1" ); mcre2.setMultipleCollectionEntity( mce2 ); mce2.addRefEntity2( mcre2 ); em.persist( mce2 ); // Cascade persisting related entity. em.getTransaction().commit(); mce2Id = mce2.getId(); mcre2Id = mcre2.getId(); } ); } @Test public void testHasChanged(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); List list = queryForPropertyHasChanged( auditReader, MultipleCollectionEntity.class, mce1Id, "text" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, MultipleCollectionEntity.class, mce1Id, "refEntities1" ); assertEquals( 3, list.size() ); assertEquals( makeList( 1, 2, 3 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, MultipleCollectionEntity.class, mce1Id, "refEntities2" ); assertEquals( 1, list.size() ); assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, MultipleCollectionRefEntity1.class, mcre1Id, "text" ); assertEquals( 1, list.size() ); assertEquals( makeList( 2 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, MultipleCollectionEntity.class, mce2Id, "text" ); assertEquals( 1, list.size() ); assertEquals( makeList( 5 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, MultipleCollectionEntity.class, mce2Id, "refEntities2" ); assertEquals( 1, list.size() ); assertEquals( makeList( 5 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, MultipleCollectionRefEntity2.class, mcre2Id, "text" ); assertEquals( 1, list.size() ); assertEquals( makeList( 5 ), extractRevisionNumbers( list ) ); } ); } }
HasChangedDetachedMultipleCollection
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-web-proxy/src/main/java/org/apache/hadoop/yarn/server/webproxy/ProxyUtils.java
{ "start": 1603, "end": 1668 }
class ____ implements Hamlet.__ { //Empty } public static
__
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/PushHttpMetricsReporter.java
{ "start": 4794, "end": 7379 }
class ____ with older client jars. This discrepancy force us not to use // `Time.SYSTEM` here as there is no such field in the older Kafka version. currentTimeMillis = System::currentTimeMillis; executor = Executors.newSingleThreadScheduledExecutor(); } PushHttpMetricsReporter(Time mockTime, ScheduledExecutorService mockExecutor) { currentTimeMillis = mockTime::milliseconds; executor = mockExecutor; } @Override public void configure(Map<String, ?> configs) { PushHttpMetricsReporterConfig config = new PushHttpMetricsReporterConfig(CONFIG_DEF, configs); try { url = new URL(config.getString(METRICS_URL_CONFIG)); } catch (MalformedURLException e) { throw new ConfigException("Malformed metrics.url", e); } int period = config.getInteger(METRICS_PERIOD_CONFIG); clientId = config.getString(CLIENT_ID_CONFIG); host = config.getString(METRICS_HOST_CONFIG); if (host == null || host.isEmpty()) { try { host = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { throw new ConfigException("Failed to get canonical hostname", e); } } executor.scheduleAtFixedRate(new HttpReporter(), period, period, TimeUnit.SECONDS); log.info("Configured PushHttpMetricsReporter for {} to report every {} seconds", url, period); } @Override public void init(List<KafkaMetric> initMetrics) { synchronized (lock) { for (KafkaMetric metric : initMetrics) { log.debug("Adding metric {}", metric.metricName()); metrics.put(metric.metricName(), metric); } } } @Override public void metricChange(KafkaMetric metric) { synchronized (lock) { log.debug("Updating metric {}", metric.metricName()); metrics.put(metric.metricName(), metric); } } @Override public void metricRemoval(KafkaMetric metric) { synchronized (lock) { log.debug("Removing metric {}", metric.metricName()); metrics.remove(metric.metricName()); } } @Override public void close() { executor.shutdown(); try { executor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new KafkaException("Interrupted when shutting down PushHttpMetricsReporter", e); } } private
compatible
java
netty__netty
codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicTransportParametersTest.java
{ "start": 1282, "end": 4362 }
class ____ extends AbstractQuicTest { @ParameterizedTest @MethodSource("newSslTaskExecutors") public void testParameters(Executor executor) throws Throwable { Channel server = null; Channel channel = null; Promise<QuicTransportParameters> serverParams = ImmediateEventExecutor.INSTANCE.newPromise(); QuicChannelValidationHandler serverHandler = new QuicChannelValidationHandler() { @Override public void channelActive(ChannelHandlerContext ctx) { super.channelActive(ctx); QuicheQuicChannel channel = (QuicheQuicChannel) ctx.channel(); serverParams.setSuccess(channel.peerTransportParameters()); } }; QuicChannelValidationHandler clientHandler = new QuicChannelValidationHandler(); try { server = QuicTestUtils.newServer(executor, serverHandler, new ChannelInboundHandlerAdapter() { @Override public boolean isSharable() { return true; } }); channel = QuicTestUtils.newClient(executor); QuicChannel quicChannel = QuicTestUtils.newQuicChannelBootstrap(channel) .handler(clientHandler) .streamHandler(new ChannelInboundHandlerAdapter()) .remoteAddress(server.localAddress()) .connect().get(); assertTransportParameters(quicChannel.peerTransportParameters()); assertTransportParameters(serverParams.sync().getNow()); quicChannel.close().sync(); serverHandler.assertState(); clientHandler.assertState(); } finally { QuicTestUtils.closeIfNotNull(channel); QuicTestUtils.closeIfNotNull(server); shutdown(executor); } } private static void assertTransportParameters(@Nullable QuicTransportParameters parameters) { assertNotNull(parameters); assertThat(parameters.maxIdleTimeout()).isGreaterThanOrEqualTo(1L); assertThat(parameters.maxUdpPayloadSize()).isGreaterThanOrEqualTo(1L); assertThat(parameters.initialMaxData()).isGreaterThanOrEqualTo(1L); assertThat(parameters.initialMaxStreamDataBidiLocal()).isGreaterThanOrEqualTo(1L); assertThat(parameters.initialMaxStreamDataBidiRemote()).isGreaterThanOrEqualTo(1L); assertThat(parameters.initialMaxStreamDataUni()).isGreaterThanOrEqualTo(1L); assertThat(parameters.initialMaxStreamsBidi()).isGreaterThanOrEqualTo(1L); assertThat(parameters.initialMaxStreamsUni()).isGreaterThanOrEqualTo(1L); assertThat(parameters.ackDelayExponent()).isGreaterThanOrEqualTo(1L); assertThat(parameters.maxAckDelay()).isGreaterThanOrEqualTo(1L); assertFalse(parameters.disableActiveMigration()); assertThat(parameters.activeConnIdLimit()).isGreaterThanOrEqualTo(1L); assertThat(parameters.maxDatagramFrameSize()).isGreaterThanOrEqualTo(0L); } }
QuicTransportParametersTest
java
spring-projects__spring-boot
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/zip/ZipStringTests.java
{ "start": 1137, "end": 6766 }
class ____ { @ParameterizedTest @EnumSource void hashGeneratesCorrectHashCode(HashSourceType sourceType) throws Exception { testHash(sourceType, true, "abcABC123xyz!"); testHash(sourceType, false, "abcABC123xyz!"); } @ParameterizedTest @EnumSource void hashWhenHasSpecialCharsGeneratesCorrectHashCode(HashSourceType sourceType) throws Exception { testHash(sourceType, true, "special/\u00EB.dat"); } @ParameterizedTest @EnumSource void hashWhenHasCyrillicCharsGeneratesCorrectHashCode(HashSourceType sourceType) throws Exception { testHash(sourceType, true, "\u0432\u0435\u0441\u043D\u0430"); } @ParameterizedTest @EnumSource void hashWhenHasEmojiGeneratesCorrectHashCode(HashSourceType sourceType) throws Exception { testHash(sourceType, true, "\ud83d\udca9"); } @ParameterizedTest @EnumSource void hashWhenOnlyDifferenceIsEndSlashGeneratesSameHashCode(HashSourceType sourceType) throws Exception { testHash(sourceType, "", true, "/".hashCode()); testHash(sourceType, "/", true, "/".hashCode()); testHash(sourceType, "a/b", true, "a/b/".hashCode()); testHash(sourceType, "a/b/", true, "a/b/".hashCode()); } void testHash(HashSourceType sourceType, boolean addSlash, String source) throws Exception { String expected = (addSlash && !source.endsWith("/")) ? source + "/" : source; testHash(sourceType, source, addSlash, expected.hashCode()); } void testHash(HashSourceType sourceType, String source, boolean addEndSlash, int expected) throws Exception { switch (sourceType) { case STRING -> { assertThat(ZipString.hash(source, addEndSlash)).isEqualTo(expected); } case CHAR_SEQUENCE -> { CharSequence charSequence = new StringBuilder(source); assertThat(ZipString.hash(charSequence, addEndSlash)).isEqualTo(expected); } case DATA_BLOCK -> { ByteArrayDataBlock dataBlock = new ByteArrayDataBlock(source.getBytes(StandardCharsets.UTF_8)); assertThat(ZipString.hash(null, dataBlock, 0, (int) dataBlock.size(), addEndSlash)).isEqualTo(expected); } case SINGLE_BYTE_READ_DATA_BLOCK -> { ByteArrayDataBlock dataBlock = new ByteArrayDataBlock(source.getBytes(StandardCharsets.UTF_8), 1); assertThat(ZipString.hash(null, dataBlock, 0, (int) dataBlock.size(), addEndSlash)).isEqualTo(expected); } } } @Test void matchesWhenExactMatchReturnsTrue() throws Exception { assertMatches("one/two/three", "one/two/three", false).isTrue(); } @Test void matchesWhenNotMatchWithSameLengthReturnsFalse() throws Exception { assertMatches("one/two/three", "one/too/three", false).isFalse(); } @Test void matchesWhenExactMatchWithSpecialCharsReturnsTrue() throws Exception { assertMatches("special/\u00EB.dat", "special/\u00EB.dat", false).isTrue(); } @Test void matchesWhenExactMatchWithCyrillicCharsReturnsTrue() throws Exception { assertMatches("\u0432\u0435\u0441\u043D\u0430", "\u0432\u0435\u0441\u043D\u0430", false).isTrue(); } @Test void matchesWhenNoMatchWithCyrillicCharsReturnsFalse() throws Exception { assertMatches("\u0432\u0435\u0441\u043D\u0430", "\u0432\u0435\u0441\u043D\u043D", false).isFalse(); } @Test void matchesWhenExactMatchWithEmojiCharsReturnsTrue() throws Exception { assertMatches("\ud83d\udca9", "\ud83d\udca9", false).isTrue(); } @Test void matchesWithAddSlash() throws Exception { assertMatches("META-INF/MANFIFEST.MF", "META-INF/MANFIFEST.MF", true).isTrue(); assertMatches("one/two/three/", "one/two/three", true).isTrue(); assertMatches("one/two/three", "one/two/three/", true).isFalse(); assertMatches("one/two/three/", "one/too/three", true).isFalse(); assertMatches("one/two/three", "one/too/three/", true).isFalse(); assertMatches("one/two/three//", "one/two/three", true).isFalse(); assertMatches("one/two/three", "one/two/three//", true).isFalse(); } @Test void matchesWhenDataBlockShorterThenCharSequenceReturnsFalse() throws Exception { assertMatches("one/two/thre", "one/two/three", false).isFalse(); } @Test void matchesWhenCharSequenceShorterThanDataBlockReturnsFalse() throws Exception { assertMatches("one/two/three", "one/two/thre", false).isFalse(); } @Test void startsWithWhenStartsWith() throws Exception { assertStartsWith("one/two", "one/").isEqualTo(4); } @Test void startsWithWhenExact() throws Exception { assertStartsWith("one/", "one/").isEqualTo(4); } @Test void startsWithWhenTooShort() throws Exception { assertStartsWith("one/two", "one/two/three/").isEqualTo(-1); } @Test void startsWithWhenDoesNotStartWith() throws Exception { assertStartsWith("one/three/", "one/two/").isEqualTo(-1); } @Test void zipStringWhenMultiCodePointAtBufferBoundary() throws Exception { StringBuilder source = new StringBuilder(); source.append("A".repeat(ZipString.BUFFER_SIZE - 1)); source.append("\u1EFF"); String charSequence = source.toString(); source.append("suffix"); assertStartsWith(source.toString(), charSequence); } private AbstractBooleanAssert<?> assertMatches(String source, CharSequence charSequence, boolean addSlash) throws Exception { ByteArrayDataBlock dataBlock = new ByteArrayDataBlock(source.getBytes(StandardCharsets.UTF_8)); return assertThat(ZipString.matches(null, dataBlock, 0, (int) dataBlock.size(), charSequence, addSlash)); } private AbstractIntegerAssert<?> assertStartsWith(String source, CharSequence charSequence) throws IOException { ByteArrayDataBlock dataBlock = new ByteArrayDataBlock(source.getBytes(StandardCharsets.UTF_8)); return assertThat(ZipString.startsWith(null, dataBlock, 0, (int) dataBlock.size(), charSequence)); }
ZipStringTests
java
netty__netty
buffer/src/main/java/io/netty/buffer/FreeChunkEvent.java
{ "start": 890, "end": 1346 }
class ____ extends AbstractChunkEvent { static final String NAME = "io.netty.FreeChunk"; private static final FreeChunkEvent INSTANCE = new FreeChunkEvent(); /** * Statically check if this event is enabled. */ public static boolean isEventEnabled() { return INSTANCE.isEnabled(); } @Description("Was this chunk pooled, or was it a one-off allocation for a single buffer?") public boolean pooled; }
FreeChunkEvent
java
apache__camel
components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertWithInputAndOutputHeaderTest.java
{ "start": 1052, "end": 2706 }
class ____ extends MyBatisTestSupport { private static final String TEST_CASE_INPUT_HEADER_NAME = "testCaseInputHeader"; private static final String TEST_CASE_OUTPUT_HEADER_NAME = "testCaseOutputHeader"; private static final String RETAINED_BODY = "not an account"; @Test public void testInsert() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).body().isEqualTo(RETAINED_BODY); mock.message(0).header(TEST_CASE_OUTPUT_HEADER_NAME).isEqualTo(1); Account account = new Account(); account.setId(444); account.setFirstName("Willem"); account.setLastName("Jiang"); account.setEmailAddress("Faraway@gmail.com"); template.sendBodyAndHeader("direct:start", RETAINED_BODY, TEST_CASE_INPUT_HEADER_NAME, account); MockEndpoint.assertIsSatisfied(context); // there should be 3 rows now Integer rows = template.requestBody("mybatis:count?statementType=SelectOne", null, Integer.class); assertEquals(3, rows.intValue(), "There should be 3 rows"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .to("mybatis:insertAccount?statementType=Insert&inputHeader=" + TEST_CASE_INPUT_HEADER_NAME + "&outputHeader=" + TEST_CASE_OUTPUT_HEADER_NAME) .to("mock:result"); } }; } }
MyBatisInsertWithInputAndOutputHeaderTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/TestDisable.java
{ "start": 972, "end": 3483 }
class ____ extends TestCase { private MockDriver driver; private DruidDataSource dataSource; protected void setUp() throws Exception { DruidDataSourceStatManager.clear(); driver = new MockDriver(); dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setDriver(driver); dataSource.setInitialSize(1); dataSource.setMaxActive(2); dataSource.setMaxIdle(2); dataSource.setMinIdle(1); dataSource.setMaxWait(500); // 加上最大等待时间,防止出现无限等待导致单测卡死的情况 dataSource.setMinEvictableIdleTimeMillis(300 * 1000); // 300 / 10 dataSource.setTimeBetweenEvictionRunsMillis(180 * 1000); // 180 / 10 dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setValidationQuery("SELECT 1"); dataSource.setFilters("stat"); } protected void tearDown() throws Exception { dataSource.close(); assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); } public void test_close() throws Exception { final int threadCount = 100; Thread[] threads = new Thread[threadCount]; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; ++i) { threads[i] = new Thread("thread-" + i) { public void run() { try { System.out.println("wait for start " + getName()); startLatch.await(); Connection conn = dataSource.getConnection(); System.out.println("getConnection start " + getName()); } catch (DataSourceDisableException e) { // skip } catch (Exception e) { e.printStackTrace(); } finally { endLatch.countDown(); } } }; } startLatch.countDown(); for (int i = 0; i < threadCount; ++i) { threads[i].start(); } Thread.sleep(1000); new Thread("close thread") { public void run() { System.out.println("setEnable " + getName()); dataSource.setEnable(false); } }.start(); endLatch.await(); } }
TestDisable
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/validation/StereotypeOnFieldTest.java
{ "start": 1302, "end": 1533 }
class ____ { @Audited private String auditedField; } @Stereotype @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @
BeanWithStereotypeOnField
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 36213, "end": 36525 }
class ____ an inner class * @since 5.0.5 * @see Class#isMemberClass() * @see #isStaticClass(Class) */ public static boolean isInnerClass(Class<?> clazz) { return (clazz.isMemberClass() && !isStaticClass(clazz)); } /** * Determine if the supplied {@link Class} is a JVM-generated implementation *
is
java
quarkusio__quarkus
extensions/micrometer/deployment/src/main/java/io/quarkus/micrometer/deployment/binder/KafkaBinderProcessor.java
{ "start": 1547, "end": 2365 }
class ____ implements BooleanSupplier { MicrometerConfig mConfig; public boolean getAsBoolean() { return KAFKA_STREAMS_CLASS_CLASS != null && mConfig.isEnabled(mConfig.binder().kafka()); } } @BuildStep(onlyIf = KafkaSupportEnabled.class) AdditionalBeanBuildItem createCDIEventConsumer() { return AdditionalBeanBuildItem.builder() .addBeanClass(KAFKA_EVENT_CONSUMER_CLASS_NAME) .setUnremovable().build(); } @BuildStep(onlyIf = KafkaStreamsSupportEnabled.class) AdditionalBeanBuildItem createKafkaStreamsEventObserver() { return AdditionalBeanBuildItem.builder() .addBeanClass(KAFKA_STREAMS_METRICS_PRODUCER_CLASS_NAME) .setUnremovable().build(); } }
KafkaStreamsSupportEnabled
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/EsqlFunctionRegistry.java
{ "start": 61266, "end": 61398 }
interface ____<T> { T build(Source source, Expression exp, List<Expression> variadic); } protected
UnaryVariadicBuilder
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java
{ "start": 6555, "end": 7264 }
class ____ implements Comparable<ContentChunkInfo> { private final int start; private final int end; ContentChunkInfo(int start, int end) { this.start = start; this.end = end; } public int getStart() { return this.start; } public int getEnd() { return this.end; } @Override public int compareTo(ContentChunkInfo other) { return Integer.compare(this.start, other.start); } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof ContentChunkInfo that && this.start == that.start && this.end == that.end)); } @Override public int hashCode() { return this.start * 31 + this.end; } } }
ContentChunkInfo
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_236.java
{ "start": 1072, "end": 1129 }
class ____ { public Object[] paras; } }
TestPara
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFilterSingleTest.java
{ "start": 994, "end": 1733 }
class ____ extends RxJavaTest { @Test public void error() { Single.error(new TestException()) .filter(Functions.alwaysTrue()) .test() .assertFailure(TestException.class); } @Test public void dispose() { TestHelper.checkDisposed(PublishSubject.create().singleOrError().filter(Functions.alwaysTrue())); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeSingleToMaybe(new Function<Single<Object>, MaybeSource<Object>>() { @Override public MaybeSource<Object> apply(Single<Object> v) throws Exception { return v.filter(Functions.alwaysTrue()); } }); } }
MaybeFilterSingleTest
java
apache__dubbo
dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java
{ "start": 1332, "end": 1883 }
class ____ implements DeclaredTypeDefinitionBuilder { @Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { return isSimpleType(type); } @Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { TypeDefinition td = new TypeDefinition(type.toString()); return td; } @Override public int getPriority() { return MIN_PRIORITY - 1; } }
SimpleTypeDefinitionBuilder
java
mockito__mockito
mockito-integration-tests/extensions-tests/src/test/java/org/mockitousage/plugins/switcher/MyPluginSwitch.java
{ "start": 266, "end": 603 }
class ____ implements PluginSwitch { static List<String> invokedFor = new LinkedList<String>(); public boolean isEnabled(String pluginClassName) { if (!pluginClassName.startsWith("org.mockitousage")) { return false; } invokedFor.add(pluginClassName); return true; } }
MyPluginSwitch
java
spring-projects__spring-boot
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java
{ "start": 2977, "end": 3096 }
class ____ the given {@code rootDirectory}. * @param rootDirectory the root directory to search * @return the main
from
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/parsing/BeanComponentDefinition.java
{ "start": 1320, "end": 4468 }
class ____ extends BeanDefinitionHolder implements ComponentDefinition { private static final BeanDefinition[] EMPTY_BEAN_DEFINITION_ARRAY = new BeanDefinition[0]; private static final BeanReference[] EMPTY_BEAN_REFERENCE_ARRAY = new BeanReference[0]; private final BeanDefinition[] innerBeanDefinitions; private final BeanReference[] beanReferences; /** * Create a new BeanComponentDefinition for the given bean. * @param beanDefinition the BeanDefinition * @param beanName the name of the bean */ public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName) { this(new BeanDefinitionHolder(beanDefinition, beanName)); } /** * Create a new BeanComponentDefinition for the given bean. * @param beanDefinition the BeanDefinition * @param beanName the name of the bean * @param aliases alias names for the bean, or {@code null} if none */ public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName, String @Nullable [] aliases) { this(new BeanDefinitionHolder(beanDefinition, beanName, aliases)); } /** * Create a new BeanComponentDefinition for the given bean. * @param beanDefinitionHolder the BeanDefinitionHolder encapsulating * the bean definition as well as the name of the bean */ public BeanComponentDefinition(BeanDefinitionHolder beanDefinitionHolder) { super(beanDefinitionHolder); List<BeanDefinition> innerBeans = new ArrayList<>(); List<BeanReference> references = new ArrayList<>(); PropertyValues propertyValues = beanDefinitionHolder.getBeanDefinition().getPropertyValues(); for (PropertyValue propertyValue : propertyValues.getPropertyValues()) { Object value = propertyValue.getValue(); if (value instanceof BeanDefinitionHolder beanDefHolder) { innerBeans.add(beanDefHolder.getBeanDefinition()); } else if (value instanceof BeanDefinition beanDef) { innerBeans.add(beanDef); } else if (value instanceof BeanReference beanRef) { references.add(beanRef); } } this.innerBeanDefinitions = innerBeans.toArray(EMPTY_BEAN_DEFINITION_ARRAY); this.beanReferences = references.toArray(EMPTY_BEAN_REFERENCE_ARRAY); } @Override public String getName() { return getBeanName(); } @Override public String getDescription() { return getShortDescription(); } @Override public BeanDefinition[] getBeanDefinitions() { return new BeanDefinition[] {getBeanDefinition()}; } @Override public BeanDefinition[] getInnerBeanDefinitions() { return this.innerBeanDefinitions; } @Override public BeanReference[] getBeanReferences() { return this.beanReferences; } /** * This implementation returns this ComponentDefinition's description. * @see #getDescription() */ @Override public String toString() { return getDescription(); } /** * This implementation expects the other object to be of type BeanComponentDefinition * as well, in addition to the superclass's equality requirements. */ @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof BeanComponentDefinition && super.equals(other))); } }
BeanComponentDefinition
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/consistenthash/Node.java
{ "start": 927, "end": 1042 }
interface ____ { /** * @return the key which will be used for hash mapping */ String getKey(); }
Node
java
apache__camel
components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlProducerInSimpleExpressionTest.java
{ "start": 898, "end": 1506 }
class ____ extends SqlProducerInTest { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // required for the sql component getContext().getComponent("sql", SqlComponent.class).setDataSource(db); from("direct:query") .to("sql:classpath:sql/selectProjectsInSimpleExpression.sql") .to("log:query") .to("mock:query"); } }; } }
SqlProducerInSimpleExpressionTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/cli/util/ComparatorBase.java
{ "start": 957, "end": 1373 }
class ____ { public ComparatorBase() { } /** * Compare method for the comparator class. * @param actual output. can be null * @param expected output. can be null * @return true if expected output compares with the actual output, else * return false. If actual or expected is null, return false */ public abstract boolean compare(String actual, String expected); }
ComparatorBase
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DaprComponentBuilderFactory.java
{ "start": 1832, "end": 20107 }
interface ____ extends ComponentBuilder<DaprComponent> { /** * The Dapr Client. * * The option is a: &lt;code&gt;io.dapr.client.DaprClient&lt;/code&gt; * type. * * Group: common * * @param client the value to set * @return the dsl builder */ default DaprComponentBuilder client(io.dapr.client.DaprClient client) { doSetProperty("client", client); return this; } /** * List of keys for configuration operation. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param configKeys the value to set * @return the dsl builder */ default DaprComponentBuilder configKeys(java.lang.String configKeys) { doSetProperty("configKeys", configKeys); return this; } /** * The name of the Dapr configuration store to interact with, defined in * statestore.yaml config. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param configStore the value to set * @return the dsl builder */ default DaprComponentBuilder configStore(java.lang.String configStore) { doSetProperty("configStore", configStore); return this; } /** * The component configurations. * * The option is a: * &lt;code&gt;org.apache.camel.component.dapr.DaprConfiguration&lt;/code&gt; type. * * Group: common * * @param configuration the value to set * @return the dsl builder */ default DaprComponentBuilder configuration(org.apache.camel.component.dapr.DaprConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * The contentType for the Pub/Sub component to use. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param contentType the value to set * @return the dsl builder */ default DaprComponentBuilder contentType(java.lang.String contentType) { doSetProperty("contentType", contentType); return this; } /** * The Dapr Preview Client. * * The option is a: * &lt;code&gt;io.dapr.client.DaprPreviewClient&lt;/code&gt; type. * * Group: common * * @param previewClient the value to set * @return the dsl builder */ default DaprComponentBuilder previewClient(io.dapr.client.DaprPreviewClient previewClient) { doSetProperty("previewClient", previewClient); return this; } /** * The name of the Dapr Pub/Sub component to use. This identifies which * underlying messaging system Dapr will interact with for publishing or * subscribing to events. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param pubSubName the value to set * @return the dsl builder */ default DaprComponentBuilder pubSubName(java.lang.String pubSubName) { doSetProperty("pubSubName", pubSubName); return this; } /** * The name of the topic to subscribe to. The topic must exist in the * Pub/Sub component configured under the given pubsubName. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param topic the value to set * @return the dsl builder */ default DaprComponentBuilder topic(java.lang.String topic) { doSetProperty("topic", topic); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default DaprComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * The name of the Dapr binding to invoke. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param bindingName the value to set * @return the dsl builder */ default DaprComponentBuilder bindingName(java.lang.String bindingName) { doSetProperty("bindingName", bindingName); return this; } /** * The operation to perform on the binding. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param bindingOperation the value to set * @return the dsl builder */ default DaprComponentBuilder bindingOperation(java.lang.String bindingOperation) { doSetProperty("bindingOperation", bindingOperation); return this; } /** * Concurrency mode to use with state operations. * * The option is a: * &lt;code&gt;io.dapr.client.domain.StateOptions.Concurrency&lt;/code&gt; type. * * Group: producer * * @param concurrency the value to set * @return the dsl builder */ default DaprComponentBuilder concurrency(io.dapr.client.domain.StateOptions.Concurrency concurrency) { doSetProperty("concurrency", concurrency); return this; } /** * Consistency level to use with state operations. * * The option is a: * &lt;code&gt;io.dapr.client.domain.StateOptions.Consistency&lt;/code&gt; type. * * Group: producer * * @param consistency the value to set * @return the dsl builder */ default DaprComponentBuilder consistency(io.dapr.client.domain.StateOptions.Consistency consistency) { doSetProperty("consistency", consistency); return this; } /** * The eTag for optimistic concurrency during state save or delete * operations. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param eTag the value to set * @return the dsl builder */ default DaprComponentBuilder eTag(java.lang.String eTag) { doSetProperty("eTag", eTag); return this; } /** * The name of the event. Event names are case-insensitive. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param eventName the value to set * @return the dsl builder */ default DaprComponentBuilder eventName(java.lang.String eventName) { doSetProperty("eventName", eventName); return this; } /** * The expiry time in seconds for the lock. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: producer * * @param expiryInSeconds the value to set * @return the dsl builder */ default DaprComponentBuilder expiryInSeconds(java.lang.Integer expiryInSeconds) { doSetProperty("expiryInSeconds", expiryInSeconds); return this; } /** * Set true to fetch the workflow instance's inputs, outputs, and custom * status, or false to omit. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param getWorkflowIO the value to set * @return the dsl builder */ default DaprComponentBuilder getWorkflowIO(boolean getWorkflowIO) { doSetProperty("getWorkflowIO", getWorkflowIO); return this; } /** * HTTP method to use when invoking the service. Accepts verbs like GET, * POST, PUT, DELETE, etc. Creates a minimal HttpExtension with no * headers or query params. Takes precedence over verb. * * The option is a: * &lt;code&gt;io.dapr.client.domain.HttpExtension&lt;/code&gt; type. * * Group: producer * * @param httpExtension the value to set * @return the dsl builder */ default DaprComponentBuilder httpExtension(io.dapr.client.domain.HttpExtension httpExtension) { doSetProperty("httpExtension", httpExtension); return this; } /** * The key used to identify the state/secret object within the specified * state/secret store. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param key the value to set * @return the dsl builder */ default DaprComponentBuilder key(java.lang.String key) { doSetProperty("key", key); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default DaprComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * The lock operation to perform on the store. Required for * DaprOperation.lock operation. * * The option is a: * &lt;code&gt;org.apache.camel.component.dapr.LockOperation&lt;/code&gt; type. * * Default: tryLock * Group: producer * * @param lockOperation the value to set * @return the dsl builder */ default DaprComponentBuilder lockOperation(org.apache.camel.component.dapr.LockOperation lockOperation) { doSetProperty("lockOperation", lockOperation); return this; } /** * The lock owner identifier for the lock. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param lockOwner the value to set * @return the dsl builder */ default DaprComponentBuilder lockOwner(java.lang.String lockOwner) { doSetProperty("lockOwner", lockOwner); return this; } /** * The name of the method or route to invoke on the target service. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param methodToInvoke the value to set * @return the dsl builder */ default DaprComponentBuilder methodToInvoke(java.lang.String methodToInvoke) { doSetProperty("methodToInvoke", methodToInvoke); return this; } /** * Reason for suspending/resuming the workflow instance. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param reason the value to set * @return the dsl builder */ default DaprComponentBuilder reason(java.lang.String reason) { doSetProperty("reason", reason); return this; } /** * The resource Id for the lock. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param resourceId the value to set * @return the dsl builder */ default DaprComponentBuilder resourceId(java.lang.String resourceId) { doSetProperty("resourceId", resourceId); return this; } /** * The name of the Dapr secret store to interact with, defined in * local-secret-store.yaml config. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param secretStore the value to set * @return the dsl builder */ default DaprComponentBuilder secretStore(java.lang.String secretStore) { doSetProperty("secretStore", secretStore); return this; } /** * Target service to invoke. Can be a Dapr App ID, a named HTTPEndpoint, * or a FQDN/public URL. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param serviceToInvoke the value to set * @return the dsl builder */ default DaprComponentBuilder serviceToInvoke(java.lang.String serviceToInvoke) { doSetProperty("serviceToInvoke", serviceToInvoke); return this; } /** * The state operation to perform on the state store. Required for * DaprOperation.state operation. * * The option is a: * &lt;code&gt;org.apache.camel.component.dapr.StateOperation&lt;/code&gt; type. * * Default: get * Group: producer * * @param stateOperation the value to set * @return the dsl builder */ default DaprComponentBuilder stateOperation(org.apache.camel.component.dapr.StateOperation stateOperation) { doSetProperty("stateOperation", stateOperation); return this; } /** * The name of the Dapr state store to interact with, defined in * statestore.yaml config. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param stateStore the value to set * @return the dsl builder */ default DaprComponentBuilder stateStore(java.lang.String stateStore) { doSetProperty("stateStore", stateStore); return this; } /** * The lock store name. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param storeName the value to set * @return the dsl builder */ default DaprComponentBuilder storeName(java.lang.String storeName) { doSetProperty("storeName", storeName); return this; } /** * The amount of time to wait for the workflow instance to * start/complete. * * The option is a: &lt;code&gt;java.time.Duration&lt;/code&gt; type. * * Group: producer * * @param timeout the value to set * @return the dsl builder */ default DaprComponentBuilder timeout(java.time.Duration timeout) { doSetProperty("timeout", timeout); return this; } /** * The HTTP verb to use for invoking the method. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: POST * Group: producer * * @param verb the value to set * @return the dsl builder */ default DaprComponentBuilder verb(java.lang.String verb) { doSetProperty("verb", verb); return this; } /** * The FQCN of the
DaprComponentBuilder
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/filter/MethodFilter.java
{ "start": 25005, "end": 25102 }
interface ____ { Object bind(FilterMethodContext context); } private
FilterArgBinder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/C.java
{ "start": 261, "end": 1056 }
class ____ extends AbstractEntity { private static final long serialVersionUID = 1226955752L; @jakarta.persistence.OneToMany(mappedBy = "c") private Set<B> bCollection = new java.util.HashSet<B>(); @jakarta.persistence.OneToMany(mappedBy = "c") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) private Set<D> dCollection = new java.util.HashSet<D>(); public Set<B> getBCollection() { return bCollection; } public void setBCollection(Set<B> bCollection) { this.bCollection = bCollection; } public Set<D> getDCollection() { return dCollection; } public void setDCollection(Set<D> dCollection) { this.dCollection = dCollection; } }
C
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
{ "start": 34998, "end": 35351 }
class ____ extends AbstractFsPathRunner<Void> { FsPathRunner(Op op, Path fspath, Param<?,?>... parameters) { super(op, fspath, parameters); } @Override Void getResponse(HttpURLConnection conn) throws IOException { return null; } } /** * Handle path-based operations with a json response */ abstract
FsPathRunner
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java
{ "start": 5871, "end": 19563 }
class ____ extends AbstractConfiguredSecurityBuilder<Filter, WebSecurity> implements SecurityBuilder<Filter>, ApplicationContextAware, ServletContextAware { private static final boolean USING_ACCESS = ClassUtils .isPresent("org.springframework.security.access.SecurityConfig", null); private final Log logger = LogFactory.getLog(getClass()); private final List<RequestMatcher> ignoredRequests = new ArrayList<>(); private final List<SecurityBuilder<? extends SecurityFilterChain>> securityFilterChainBuilders = new ArrayList<>(); private IgnoredRequestConfigurer ignoredRequestRegistry; private HttpFirewall httpFirewall; private RequestRejectedHandler requestRejectedHandler; private boolean debugEnabled; private WebInvocationPrivilegeEvaluator privilegeEvaluator; private ObservationRegistry observationRegistry = ObservationRegistry.NOOP; private ObjectPostProcessor<FilterChainDecorator> filterChainDecoratorPostProcessor = ObjectPostProcessor .identity(); private HttpServletRequestTransformer privilegeEvaluatorRequestTransformer; private DefaultHttpSecurityExpressionHandler defaultExpressionHandler = new DefaultHttpSecurityExpressionHandler(); private SecurityExpressionHandler<FilterInvocation> expressionHandler = new SecurityExpressionHandlerAdapter( this.defaultExpressionHandler); private Runnable postBuildAction = () -> { }; private ServletContext servletContext; /** * Creates a new instance * @param objectPostProcessor the {@link ObjectPostProcessor} to use * @see WebSecurityConfiguration */ public WebSecurity(ObjectPostProcessor<Object> objectPostProcessor) { super(objectPostProcessor); } /** * <p> * Allows adding {@link RequestMatcher} instances that Spring Security should ignore. * Web Security provided by Spring Security (including the {@link SecurityContext}) * will not be available on {@link HttpServletRequest} that match. Typically the * requests that are registered should be that of only static resources. For requests * that are dynamic, consider mapping the request to allow all users instead. * </p> * * Example Usage: * * <pre> * webSecurityBuilder.ignoring() * // ignore all URLs that start with /resources/ or /static/ * .requestMatchers(&quot;/resources/**&quot;, &quot;/static/**&quot;); * </pre> * * Alternatively this will accomplish the same result: * * <pre> * webSecurityBuilder.ignoring() * // ignore all URLs that start with /resources/ or /static/ * .requestMatchers(&quot;/resources/**&quot;).requestMatchers(&quot;/static/**&quot;); * </pre> * * Multiple invocations of ignoring() are also additive, so the following is also * equivalent to the previous two examples: * * <pre> * webSecurityBuilder.ignoring() * // ignore all URLs that start with /resources/ * .requestMatchers(&quot;/resources/**&quot;); * webSecurityBuilder.ignoring() * // ignore all URLs that start with /static/ * .requestMatchers(&quot;/static/**&quot;); * // now both URLs that start with /resources/ and /static/ will be ignored * </pre> * @return the {@link IgnoredRequestConfigurer} to use for registering request that * should be ignored */ public IgnoredRequestConfigurer ignoring() { return this.ignoredRequestRegistry; } /** * Allows customizing the {@link HttpFirewall}. The default is * {@link StrictHttpFirewall}. * @param httpFirewall the custom {@link HttpFirewall} * @return the {@link WebSecurity} for further customizations */ public WebSecurity httpFirewall(HttpFirewall httpFirewall) { this.httpFirewall = httpFirewall; return this; } /** * Controls debugging support for Spring Security. * @param debugEnabled if true, enables debug support with Spring Security. Default is * false. * @return the {@link WebSecurity} for further customization. * @see EnableWebSecurity#debug() */ public WebSecurity debug(boolean debugEnabled) { this.debugEnabled = debugEnabled; return this; } /** * <p> * Adds builders to create {@link SecurityFilterChain} instances. * </p> * * <p> * Typically this method is invoked automatically within the framework from * {@link WebSecurityConfiguration#springSecurityFilterChain()} * </p> * @param securityFilterChainBuilder the builder to use to create the * {@link SecurityFilterChain} instances * @return the {@link WebSecurity} for further customizations */ public WebSecurity addSecurityFilterChainBuilder( SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder) { this.securityFilterChainBuilders.add(securityFilterChainBuilder); return this; } /** * Set the {@link WebInvocationPrivilegeEvaluator} to be used. If this is not * specified, then a {@link AuthorizationManagerWebInvocationPrivilegeEvaluator} will * be created based on the list of {@link SecurityFilterChain}. * @param privilegeEvaluator the {@link WebInvocationPrivilegeEvaluator} to use * @return the {@link WebSecurity} for further customizations */ public WebSecurity privilegeEvaluator(WebInvocationPrivilegeEvaluator privilegeEvaluator) { this.privilegeEvaluator = privilegeEvaluator; return this; } /** * Set the {@link SecurityExpressionHandler} to be used. If this is not specified, * then a {@link DefaultHttpSecurityExpressionHandler} will be used. * @param expressionHandler the {@link SecurityExpressionHandler} to use * @return the {@link WebSecurity} for further customizations */ public WebSecurity expressionHandler(SecurityExpressionHandler<FilterInvocation> expressionHandler) { Assert.notNull(expressionHandler, "expressionHandler cannot be null"); this.expressionHandler = expressionHandler; return this; } /** * Gets the {@link SecurityExpressionHandler} to be used. * @return the {@link SecurityExpressionHandler} for further customizations */ public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() { return this.expressionHandler; } /** * Gets the {@link WebInvocationPrivilegeEvaluator} to be used. * @return the {@link WebInvocationPrivilegeEvaluator} for further customizations */ public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() { return this.privilegeEvaluator; } /** * Executes the Runnable immediately after the build takes place * @param postBuildAction * @return the {@link WebSecurity} for further customizations */ public WebSecurity postBuildAction(Runnable postBuildAction) { this.postBuildAction = postBuildAction; return this; } /** * Sets the handler to handle * {@link org.springframework.security.web.firewall.RequestRejectedException} * @param requestRejectedHandler * @return the {@link WebSecurity} for further customizations * @since 5.7 */ public WebSecurity requestRejectedHandler(RequestRejectedHandler requestRejectedHandler) { Assert.notNull(requestRejectedHandler, "requestRejectedHandler cannot be null"); this.requestRejectedHandler = requestRejectedHandler; return this; } @Override protected Filter performBuild() { Assert.state(!this.securityFilterChainBuilders.isEmpty(), () -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. " + "Typically this is done by exposing a SecurityFilterChain bean. " + "More advanced users can invoke " + WebSecurity.class.getSimpleName() + ".addSecurityFilterChainBuilder directly"); int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size(); List<SecurityFilterChain> securityFilterChains = new ArrayList<>(chainSize); RequestMatcherDelegatingAuthorizationManager.Builder builder = RequestMatcherDelegatingAuthorizationManager .builder(); boolean mappings = false; for (RequestMatcher ignoredRequest : this.ignoredRequests) { WebSecurity.this.logger.warn("You are asking Spring Security to ignore " + ignoredRequest + ". This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead."); SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(ignoredRequest); securityFilterChains.add(securityFilterChain); builder.add(ignoredRequest, SingleResultAuthorizationManager.permitAll()); mappings = true; } for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : this.securityFilterChainBuilders) { SecurityFilterChain securityFilterChain = securityFilterChainBuilder.build(); securityFilterChains.add(securityFilterChain); mappings = addAuthorizationManager(securityFilterChain, builder) || mappings; } if (this.privilegeEvaluator == null) { AuthorizationManager<HttpServletRequest> authorizationManager = mappings ? builder.build() : SingleResultAuthorizationManager.permitAll(); AuthorizationManagerWebInvocationPrivilegeEvaluator privilegeEvaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator( authorizationManager); privilegeEvaluator.setServletContext(this.servletContext); if (this.privilegeEvaluatorRequestTransformer != null) { privilegeEvaluator.setRequestTransformer(this.privilegeEvaluatorRequestTransformer); } this.privilegeEvaluator = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( List.of(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE, List.of(privilegeEvaluator)))); } FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains); if (this.httpFirewall != null) { filterChainProxy.setFirewall(this.httpFirewall); } if (this.requestRejectedHandler != null) { filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler); } else if (!this.observationRegistry.isNoop()) { CompositeRequestRejectedHandler requestRejectedHandler = new CompositeRequestRejectedHandler( new ObservationMarkingRequestRejectedHandler(this.observationRegistry), new HttpStatusRequestRejectedHandler()); filterChainProxy.setRequestRejectedHandler(requestRejectedHandler); } filterChainProxy.setFilterChainValidator(new WebSecurityFilterChainValidator()); filterChainProxy.setFilterChainDecorator(getFilterChainDecorator()); filterChainProxy.afterPropertiesSet(); Filter result = filterChainProxy; if (this.debugEnabled) { this.logger.warn("\n\n" + "********************************************************************\n" + "********** Security debugging is enabled. *************\n" + "********** This may include sensitive information. *************\n" + "********** Do not use in a production system! *************\n" + "********************************************************************\n\n"); result = new DebugFilter(filterChainProxy); } this.postBuildAction.run(); return result; } private boolean addAuthorizationManager(SecurityFilterChain securityFilterChain, RequestMatcherDelegatingAuthorizationManager.Builder builder) { boolean mappings = false; for (Filter filter : securityFilterChain.getFilters()) { if (USING_ACCESS) { mappings = AccessComponents.addAuthorizationManager(filter, this.servletContext, builder, securityFilterChain); } if (filter instanceof AuthorizationFilter authorization) { AuthorizationManager<HttpServletRequest> authorizationManager = authorization.getAuthorizationManager(); builder.add(securityFilterChain::matches, (authentication, context) -> (AuthorizationDecision) authorizationManager .authorize(authentication, context.getRequest())); mappings = true; } } return mappings; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.defaultExpressionHandler.setApplicationContext(applicationContext); try { this.defaultExpressionHandler.setRoleHierarchy(applicationContext.getBean(RoleHierarchy.class)); } catch (NoSuchBeanDefinitionException ex) { } try { this.defaultExpressionHandler.setPermissionEvaluator(applicationContext.getBean(PermissionEvaluator.class)); } catch (NoSuchBeanDefinitionException ex) { } this.ignoredRequestRegistry = new IgnoredRequestConfigurer(applicationContext); try { this.httpFirewall = applicationContext.getBean(HttpFirewall.class); } catch (NoSuchBeanDefinitionException ex) { } try { this.requestRejectedHandler = applicationContext.getBean(RequestRejectedHandler.class); } catch (NoSuchBeanDefinitionException ex) { } try { this.observationRegistry = applicationContext.getBean(ObservationRegistry.class); } catch (NoSuchBeanDefinitionException ex) { } ResolvableType type = ResolvableType.forClassWithGenerics(ObjectPostProcessor.class, FilterChainDecorator.class); ObjectProvider<ObjectPostProcessor<FilterChainDecorator>> postProcessor = applicationContext .getBeanProvider(type); this.filterChainDecoratorPostProcessor = postProcessor.getIfUnique(ObjectPostProcessor::identity); Class<HttpServletRequestTransformer> requestTransformerClass = HttpServletRequestTransformer.class; this.privilegeEvaluatorRequestTransformer = applicationContext.getBeanProvider(requestTransformerClass) .getIfUnique(PathPatternRequestTransformer::new); } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } FilterChainDecorator getFilterChainDecorator() { return this.filterChainDecoratorPostProcessor.postProcess(new FilterChainProxy.VirtualFilterChainDecorator()); } /** * Allows registering {@link RequestMatcher} instances that should be ignored by * Spring Security. * * @author Rob Winch * @since 3.2 */ public
WebSecurity
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointSettingsSerializableTest.java
{ "start": 5886, "end": 6750 }
class ____ implements StateBackend { private static final long serialVersionUID = -6107964383429395816L; /** Simulate a custom option that is not in the normal classpath. */ @SuppressWarnings("unused") private Serializable customOption; public CustomStateBackend(Serializable customOption) { this.customOption = customOption; } @Override public <K> AbstractKeyedStateBackend<K> createKeyedStateBackend( KeyedStateBackendParameters<K> parameters) { throw new UnsupportedOperationException(); } @Override public OperatorStateBackend createOperatorStateBackend( OperatorStateBackendParameters parameters) { throw new UnsupportedOperationException(); } } private static final
CustomStateBackend
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PahoMqtt5EndpointBuilderFactory.java
{ "start": 90304, "end": 96569 }
interface ____ extends EndpointProducerBuilder { default PahoMqtt5EndpointProducerBuilder basic() { return (PahoMqtt5EndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * To use an existing mqtt client. * * The option is a: * <code>org.eclipse.paho.mqttv5.client.MqttClient</code> type. * * Group: advanced * * @param client the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder client(org.eclipse.paho.mqttv5.client.MqttClient client) { doSetProperty("client", client); return this; } /** * To use an existing mqtt client. * * The option will be converted to a * <code>org.eclipse.paho.mqttv5.client.MqttClient</code> type. * * Group: advanced * * @param client the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder client(String client) { doSetProperty("client", client); return this; } /** * Sets the Custom WebSocket Headers for the WebSocket Connection. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.String&gt;</code> type. * * Group: advanced * * @param customWebSocketHeaders the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder customWebSocketHeaders(Map<java.lang.String, java.lang.String> customWebSocketHeaders) { doSetProperty("customWebSocketHeaders", customWebSocketHeaders); return this; } /** * Sets the Custom WebSocket Headers for the WebSocket Connection. * * The option will be converted to a * <code>java.util.Map&lt;java.lang.String, java.lang.String&gt;</code> * type. * * Group: advanced * * @param customWebSocketHeaders the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder customWebSocketHeaders(String customWebSocketHeaders) { doSetProperty("customWebSocketHeaders", customWebSocketHeaders); return this; } /** * Set the time in seconds that the executor service should wait when * terminating before forcefully terminating. It is not recommended to * change this value unless you are absolutely sure that you need to. * * The option is a: <code>int</code> type. * * Default: 1 * Group: advanced * * @param executorServiceTimeout the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder executorServiceTimeout(int executorServiceTimeout) { doSetProperty("executorServiceTimeout", executorServiceTimeout); return this; } /** * Set the time in seconds that the executor service should wait when * terminating before forcefully terminating. It is not recommended to * change this value unless you are absolutely sure that you need to. * * The option will be converted to a <code>int</code> type. * * Default: 1 * Group: advanced * * @param executorServiceTimeout the value to set * @return the dsl builder */ default AdvancedPahoMqtt5EndpointProducerBuilder executorServiceTimeout(String executorServiceTimeout) { doSetProperty("executorServiceTimeout", executorServiceTimeout); return this; } } /** * Builder for endpoint for the Paho MQTT 5 component. */ public
AdvancedPahoMqtt5EndpointProducerBuilder