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
|
google__dagger
|
javatests/dagger/hilt/android/testing/TestRootModulesTest.java
|
{
"start": 2030,
"end": 2308
}
|
class ____ {
@Provides
@TestQualifier(0)
String provideString() {
return "0";
}
NonStaticModuleNonStaticProvidesDefaultConstructor() {}
}
@Module
@InstallIn(SingletonComponent.class)
public final
|
NonStaticModuleNonStaticProvidesDefaultConstructor
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/mapper/FallbackSyntheticSourceBlockLoader.java
|
{
"start": 11123,
"end": 12261
}
|
interface ____<T> {
/**
* Converts a raw stored value for this field to a value in a format suitable for block loader and adds it to the provided
* accumulator.
* @param value raw decoded value from _ignored_source field (synthetic _source value)
* @param accumulator list containing the result of conversion
*/
void convertValue(Object value, List<T> accumulator);
/**
* Parses one or more complex values using a provided parser and adds them to the provided accumulator.
* @param parser parser of a value from _ignored_source field (synthetic _source value)
* @param accumulator list containing the results of parsing
*/
void parse(XContentParser parser, List<T> accumulator) throws IOException;
void writeToBlock(List<T> values, Builder blockBuilder);
}
/**
* Reader for field types that don't parse arrays (arrays are always treated as multiple values)
* as opposed to field types that treat arrays as special cases (for example point).
* @param <T>
*/
public abstract static
|
Reader
|
java
|
netty__netty
|
codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompCommandDecodeTest.java
|
{
"start": 1443,
"end": 3592
}
|
class ____ {
private EmbeddedChannel channel;
@BeforeEach
public void setUp() {
channel = new EmbeddedChannel(new StompSubframeDecoder(true));
}
@AfterEach
public void tearDown() {
assertFalse(channel.finish());
}
@ParameterizedTest(name = "{index}: testDecodeCommand({0}) = {1}")
@MethodSource("stompCommands")
public void testDecodeCommand(String rawCommand, StompCommand expectedCommand, Boolean valid) {
byte[] frameContent = String.format("%s\n\n\0", rawCommand).getBytes(UTF_8);
ByteBuf incoming = Unpooled.wrappedBuffer(frameContent);
assertTrue(channel.writeInbound(incoming));
StompHeadersSubframe frame = channel.readInbound();
assertNotNull(frame);
assertEquals(expectedCommand, frame.command());
if (valid) {
assertTrue(frame.decoderResult().isSuccess());
StompContentSubframe content = channel.readInbound();
assertSame(LastStompContentSubframe.EMPTY_LAST_CONTENT, content);
content.release();
} else {
assertTrue(frame.decoderResult().isFailure());
assertNull(channel.readInbound());
}
}
public static Collection<Object[]> stompCommands() {
return Arrays.asList(new Object[][] {
{ "STOMP", StompCommand.STOMP, true },
{ "CONNECT", StompCommand.CONNECT, true },
{ "SEND", StompCommand.SEND, true },
{ "SUBSCRIBE", StompCommand.SUBSCRIBE, true },
{ "UNSUBSCRIBE", StompCommand.UNSUBSCRIBE, true },
{ "ACK", StompCommand.ACK, true },
{ "NACK", StompCommand.NACK, true },
{ "BEGIN", StompCommand.BEGIN, true },
{ "ABORT", StompCommand.ABORT, true },
{ "COMMIT", StompCommand.COMMIT, true },
{ "DISCONNECT", StompCommand.DISCONNECT, true },
// invalid commands
{ "INVALID", StompCommand.UNKNOWN, false },
{ "disconnect", StompCommand.UNKNOWN , false }
});
}
}
|
StompCommandDecodeTest
|
java
|
alibaba__nacos
|
console/src/main/java/com/alibaba/nacos/console/controller/v3/naming/ConsoleInstanceController.java
|
{
"start": 2340,
"end": 5811
}
|
class ____ {
private final InstanceProxy instanceProxy;
/**
* Constructs a new ConsoleInstanceController with the provided InstanceProxy.
*
* @param instanceProxy the proxy used for handling instance-related operations
*/
public ConsoleInstanceController(InstanceProxy instanceProxy) {
this.instanceProxy = instanceProxy;
}
/**
* List instances of special service.
*
* @param instanceForm instance list form
* @param pageForm Page form
* @return instances information
*/
@Secured(action = ActionTypes.READ, apiType = ApiType.CONSOLE_API)
@RequestMapping("/list")
public Result<Page<? extends Instance>> getInstanceList(InstanceListForm instanceForm, PageForm pageForm)
throws NacosException {
instanceForm.validate();
Page<? extends Instance> instancePage = instanceProxy.listInstances(instanceForm.getNamespaceId(),
instanceForm.getServiceName(), instanceForm.getGroupName(), instanceForm.getClusterName(),
pageForm.getPageNo(), pageForm.getPageSize());
return Result.success(instancePage);
}
/**
* Update instance.
*/
@CanDistro
@PutMapping
@TpsControl(pointName = "NamingInstanceUpdate", name = "HttpNamingInstanceUpdate")
@Secured(action = ActionTypes.WRITE, apiType = ApiType.CONSOLE_API)
public Result<String> updateInstance(InstanceForm instanceForm) throws NacosException {
// check param
instanceForm.validate();
checkWeight(instanceForm.getWeight());
// build instance
Instance instance = buildInstance(instanceForm);
instanceProxy.updateInstance(instanceForm, instance);
return Result.success("ok");
}
private void checkWeight(Double weight) throws NacosException {
if (weight > com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE
|| weight < com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.WEIGHT_ERROR,
"instance format invalid: The weights range from "
+ com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE + " to "
+ com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE);
}
}
private Instance buildInstance(InstanceForm instanceForm) throws NacosException {
Instance instance = InstanceBuilder.newBuilder().setServiceName(buildCompositeServiceName(instanceForm))
.setIp(instanceForm.getIp()).setClusterName(instanceForm.getClusterName())
.setPort(instanceForm.getPort()).setHealthy(instanceForm.getHealthy())
.setWeight(instanceForm.getWeight()).setEnabled(instanceForm.getEnabled())
.setMetadata(UtilsAndCommons.parseMetadata(instanceForm.getMetadata()))
.setEphemeral(instanceForm.getEphemeral()).build();
if (instanceForm.getEphemeral() == null) {
// register instance by console default is persistent instance.
instance.setEphemeral(false);
}
return instance;
}
private String buildCompositeServiceName(InstanceForm instanceForm) {
return NamingUtils.getGroupedName(instanceForm.getServiceName(), instanceForm.getGroupName());
}
}
|
ConsoleInstanceController
|
java
|
quarkusio__quarkus
|
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/transform/injectionPoint/PrivateFieldInjectionTest.java
|
{
"start": 2949,
"end": 3264
}
|
class ____ extends BaseHarvester {
@Inject
private Head head;
public Head getHead() {
return head;
}
}
// Deliberately not a bean but has private injection point
// this case is not subject to transformation and requires reflection
static
|
CombineHarvester
|
java
|
apache__camel
|
components/camel-jt400/src/main/java/org/apache/camel/component/jt400/Jt400MsgQueueService.java
|
{
"start": 1276,
"end": 3223
}
|
class ____ implements Service {
/**
* Logging tool.
*/
private static final Logger LOG = LoggerFactory.getLogger(Jt400MsgQueueService.class);
/**
* Endpoint which this service connects to.
*/
private final Jt400Endpoint endpoint;
/**
* Message queue object that corresponds to the endpoint of this service (null if stopped).
*/
private MessageQueue queue;
/**
* Creates a {@code Jt400MsgQueueService} that connects to the specified endpoint.
*
* @param endpoint endpoint which this service connects to
*/
Jt400MsgQueueService(Jt400Endpoint endpoint) {
ObjectHelper.notNull(endpoint, "endpoint", this);
this.endpoint = endpoint;
}
@Override
public void start() {
if (queue == null) {
AS400 system = endpoint.getSystem();
queue = new MessageQueue(system, endpoint.getObjectPath());
}
if (!queue.getSystem().isConnected(AS400.COMMAND)) {
LOG.debug("Connecting to {}", endpoint);
try {
queue.getSystem().connectService(AS400.COMMAND);
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
}
@Override
public void stop() {
if (queue != null) {
LOG.debug("Releasing connection to {}", endpoint);
AS400 system = queue.getSystem();
queue = null;
endpoint.releaseSystem(system);
}
}
/**
* Returns the message queue object that this service connects to. Returns {@code null} if the service is stopped.
*
* @return the message queue object that this service connects to, or {@code null} if stopped
*/
public MessageQueue getMsgQueue() {
return queue;
}
@Override
public void close() throws IOException {
stop();
}
}
|
Jt400MsgQueueService
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/Helper.java
|
{
"start": 289,
"end": 909
}
|
class ____ {
public static PersistenceException persistenceException(
PersistenceUnitDescriptor persistenceUnit,
String message) {
return persistenceException( persistenceUnit, message, null );
}
public static PersistenceException persistenceException(
PersistenceUnitDescriptor persistenceUnit,
String message,
Exception cause) {
return new PersistenceException(
getExceptionHeader( persistenceUnit ) + message,
cause
);
}
private static String getExceptionHeader(PersistenceUnitDescriptor persistenceUnit) {
return "[PersistenceUnit: " + persistenceUnit.getName() + "] ";
}
}
|
Helper
|
java
|
bumptech__glide
|
library/src/main/java/com/bumptech/glide/request/target/DrawableThumbnailImageViewTarget.java
|
{
"start": 279,
"end": 774
}
|
class ____ extends ThumbnailImageViewTarget<Drawable> {
public DrawableThumbnailImageViewTarget(ImageView view) {
super(view);
}
/**
* @deprecated Use {@link #waitForLayout()} instead.
*/
@Deprecated
@SuppressWarnings("deprecation")
public DrawableThumbnailImageViewTarget(ImageView view, boolean waitForLayout) {
super(view, waitForLayout);
}
@Override
protected Drawable getDrawable(Drawable resource) {
return resource;
}
}
|
DrawableThumbnailImageViewTarget
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/cluster/topology/DefaultClusterTopologyRefresh.java
|
{
"start": 16489,
"end": 19243
}
|
class ____ {
private final Map<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> connections = new LinkedHashMap<>();
public void addConnection(RedisURI uri, CompletableFuture<StatefulRedisConnection<String, String>> future) {
CompletableFuture<StatefulRedisConnection<String, String>> existing = connections.put(uri, future);
}
@SuppressWarnings("rawtypes")
public CompletableFuture<Void> close() {
CompletableFuture[] futures = connections.values().stream()
.map(it -> it.thenCompose(StatefulConnection::closeAsync).exceptionally(ignore -> null))
.toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
}
public boolean contains(RedisURI uri) {
return connections.containsKey(uri);
}
public <T> CompletableFuture<T> whenComplete(
Function<? super Map<RedisURI, StatefulRedisConnection<String, String>>, ? extends T> mappingFunction) {
int expectedCount = connections.size();
AtomicInteger latch = new AtomicInteger();
CompletableFuture<T> continuation = new CompletableFuture<>();
for (Map.Entry<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> entry : connections
.entrySet()) {
CompletableFuture<StatefulRedisConnection<String, String>> future = entry.getValue();
future.whenComplete((it, ex) -> {
if (latch.incrementAndGet() == expectedCount) {
try {
continuation.complete(mappingFunction.apply(collectConnections()));
} catch (RuntimeException e) {
continuation.completeExceptionally(e);
}
}
});
}
return continuation;
}
protected Map<RedisURI, StatefulRedisConnection<String, String>> collectConnections() {
Map<RedisURI, StatefulRedisConnection<String, String>> activeConnections = new LinkedHashMap<>();
for (Map.Entry<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> entry : connections
.entrySet()) {
CompletableFuture<StatefulRedisConnection<String, String>> future = entry.getValue();
if (future.isDone() && !future.isCompletedExceptionally()) {
activeConnections.put(entry.getKey(), future.join());
}
}
return activeConnections;
}
}
@SuppressWarnings("serial")
static
|
ConnectionTracker
|
java
|
quarkusio__quarkus
|
extensions/reactive-mysql-client/deployment/src/test/java/io/quarkus/reactive/mysql/client/MultipleDataSourcesAndMySQLPoolCreatorsTest.java
|
{
"start": 1521,
"end": 2039
}
|
class ____ {
@Inject
Pool mySQLClient;
public CompletionStage<Void> verify() {
CompletableFuture<Void> cf = new CompletableFuture<>();
mySQLClient.query("SELECT 1").execute(ar -> {
if (ar.failed()) {
cf.completeExceptionally(ar.cause());
} else {
cf.complete(null);
}
});
return cf;
}
}
@ApplicationScoped
static
|
BeanUsingDefaultDataSource
|
java
|
apache__dubbo
|
dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java
|
{
"start": 1374,
"end": 3017
}
|
class ____ {
private Log4jLogEvent event;
@BeforeEach
public void setUp() throws Exception {
event = mock(Log4jLogEvent.class);
when(event.getLoggerName()).thenReturn("logger-name");
when(event.getLevel()).thenReturn(Level.INFO);
when(event.getThreadName()).thenReturn("thread-name");
when(event.getMessage()).thenReturn(new SimpleMessage("message"));
DubboAppender.clear();
DubboAppender.doStop();
}
@AfterEach
public void tearDown() throws Exception {
DubboAppender.clear();
DubboAppender.doStop();
}
@Test
void testAvailable() {
assertThat(DubboAppender.available, is(false));
DubboAppender.doStart();
assertThat(DubboAppender.available, is(true));
DubboAppender.doStop();
assertThat(DubboAppender.available, is(false));
}
@Test
void testAppend() {
DubboAppender appender = new DubboAppender();
assertThat(DubboAppender.logList, hasSize(0));
appender.append(event);
assertThat(DubboAppender.logList, hasSize(0));
DubboAppender.doStart();
appender.append(event);
assertThat(DubboAppender.logList, hasSize(1));
assertThat(DubboAppender.logList.get(0).getLogThread(), equalTo("thread-name"));
}
@Test
void testClear() {
DubboAppender.doStart();
DubboAppender appender = new DubboAppender();
appender.append(event);
assertThat(DubboAppender.logList, hasSize(1));
DubboAppender.clear();
assertThat(DubboAppender.logList, hasSize(0));
}
}
|
DubboAppenderTest
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/web/accept/MissingApiVersionException.java
|
{
"start": 937,
"end": 1111
}
|
class ____ extends ResponseStatusException {
public MissingApiVersionException() {
super(HttpStatus.BAD_REQUEST, "API version is required.");
}
}
|
MissingApiVersionException
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/FunctionAndEnumsTest.java
|
{
"start": 896,
"end": 2651
}
|
class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
EmbeddableThirdLevel embeddableThirdLevel = new EmbeddableThirdLevel( Level.THIRD );
EmbeddableSecondLevel embeddableSecondLevel = new EmbeddableSecondLevel(
Level.SECOND,
embeddableThirdLevel
);
EmbeddableFirstLevel embeddableFirstLevel = new EmbeddableFirstLevel(
Level.FIRST,
embeddableSecondLevel
);
TestEntity testEntity = new TestEntity( 1l, embeddableFirstLevel );
session.persist( testEntity );
}
);
}
@Test
public void testLowerFunction(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
List<String> results = session.createQuery(
"select lower(e.embeddableFirstLevel.embeddableSecondLevel.embeddableThirdLevel.lastLevel) from TestEntity e",
String.class
).list();
assertThat( results.size() ).isEqualTo( 1 );
assertThat( results.get( 0 ) ).isEqualTo( Level.THIRD.name().toLowerCase( Locale.ROOT ) );
results = session.createQuery(
"select lower(e.embeddableFirstLevel.embeddableSecondLevel.anotherLevel) from TestEntity e",
String.class
).list();
assertThat( results.size() ).isEqualTo( 1 );
assertThat( results.get( 0 ) ).isEqualTo( Level.SECOND.name().toLowerCase( Locale.ROOT ) );
results = session.createQuery(
"select lower(e.embeddableFirstLevel.level) from TestEntity e",
String.class
)
.list();
assertThat( results.size() ).isEqualTo( 1 );
assertThat( results.get( 0 ) ).isEqualTo( Level.FIRST.name().toLowerCase( Locale.ROOT ) );
}
);
}
@Entity(name = "TestEntity")
public static
|
FunctionAndEnumsTest
|
java
|
hibernate__hibernate-orm
|
hibernate-agroal/src/main/java/org/hibernate/agroal/internal/AgroalConnectionProvider.java
|
{
"start": 3333,
"end": 9386
}
|
class ____ implements ConnectionProvider, Configurable, Stoppable {
public static final String CONFIG_PREFIX = AGROAL_CONFIG_PREFIX + ".";
@Serial
private static final long serialVersionUID = 1L;
private AgroalDataSource agroalDataSource = null;
// --- Configurable
private static String extractIsolationAsString(Map<String, Object> properties) {
final Integer isolation = ConnectionProviderInitiator.extractIsolation( properties );
return isolation != null
// Agroal resolves transaction isolation from the 'nice' name
? toIsolationNiceName( isolation )
: null;
}
private static void resolveIsolationSetting(Map<String, Object> properties, AgroalConnectionFactoryConfigurationSupplier cf) {
final String isolationString = extractIsolationAsString( properties );
if ( isolationString != null ) {
cf.jdbcTransactionIsolation( TransactionIsolation.valueOf( isolationString ) );
}
}
private static <T> void copyProperty(Map<String, Object> properties, String key, Consumer<T> consumer, Function<String, T> converter) {
final Object value = properties.get( key );
if ( value != null ) {
consumer.accept( converter.apply( value.toString() ) );
}
}
@Override
public void configure(Map<String, Object> properties) throws HibernateException {
CONNECTION_INFO_LOGGER.configureConnectionPool( "Agroal" );
try {
final var config = toStringValuedProperties( properties );
if ( !properties.containsKey( AgroalSettings.AGROAL_MAX_SIZE ) ) {
final String maxSize =
properties.containsKey( JdbcSettings.POOL_SIZE )
? properties.get( JdbcSettings.POOL_SIZE ).toString()
: String.valueOf( 10 );
config.put( AgroalSettings.AGROAL_MAX_SIZE, maxSize );
}
final var agroalProperties = new AgroalPropertiesReader( CONFIG_PREFIX ).readProperties( config );
agroalProperties.modify()
.connectionPoolConfiguration( cp -> cp.connectionFactoryConfiguration( cf -> {
copyProperty( properties, JdbcSettings.DRIVER, cf::connectionProviderClassName, identity() );
copyProperty( properties, JdbcSettings.URL, cf::jdbcUrl, identity() );
copyProperty( properties, JdbcSettings.USER, cf::principal, NamePrincipal::new );
copyProperty( properties, JdbcSettings.PASS, cf::credential, SimplePassword::new );
copyProperty( properties, JdbcSettings.AUTOCOMMIT, cf::autoCommit, Boolean::valueOf );
resolveIsolationSetting( properties, cf );
return cf;
} ) );
agroalDataSource = AgroalDataSource.from( agroalProperties );
}
catch ( Exception e ) {
CONNECTION_INFO_LOGGER.unableToInstantiateConnectionPool( e );
throw new ConnectionProviderConfigurationException(
"Could not configure Agroal: " + e.getMessage(), e );
}
}
private static Map<String,String> toStringValuedProperties(Map<String,Object> properties) {
return properties.entrySet().stream()
.collect( toMap( Map.Entry::getKey, e -> e.getValue().toString() ) );
}
// --- ConnectionProvider
@Override
public Connection getConnection() throws SQLException {
return agroalDataSource == null ? null : agroalDataSource.getConnection();
}
@Override
public void closeConnection(Connection connection) throws SQLException {
connection.close();
}
@Override
public boolean supportsAggressiveRelease() {
// Agroal supports integration with Narayana as the JTA provider, that would enable aggressive release
// That logic is similar with what Hibernate does (however with better performance since it's integrated in the pool)
// and therefore that integration is not leveraged right now.
return false;
}
@Override
public DatabaseConnectionInfo getDatabaseConnectionInfo(Dialect dialect) {
final var poolConfig = agroalDataSource.getConfiguration().connectionPoolConfiguration();
final var connectionConfig = poolConfig.connectionFactoryConfiguration();
try ( var connection = agroalDataSource.getConnection() ) {
final var info = new DatabaseConnectionInfoImpl(
AgroalConnectionProvider.class,
connectionConfig.jdbcUrl(),
// Attempt to resolve the driver name from the dialect,
// in case it wasn't explicitly set and access to the
// database metadata is allowed
connectionConfig.connectionProviderClass() != null
? connectionConfig.connectionProviderClass().toString()
: getDriverName( connection ),
dialect.getClass(),
dialect.getVersion(),
hasSchema( connection ),
hasCatalog( connection ),
getSchema( connection ),
getCatalog( connection ),
Boolean.toString( connectionConfig.autoCommit() ),
connectionConfig.jdbcTransactionIsolation() != null
&& connectionConfig.jdbcTransactionIsolation().isDefined()
? toIsolationNiceName( connectionConfig.jdbcTransactionIsolation().level() )
: toIsolationNiceName( getIsolation( connection ) ),
poolConfig.minSize(),
poolConfig.maxSize(),
getFetchSize( connection )
);
if ( !connection.getAutoCommit() ) {
connection.rollback();
}
return info;
}
catch (SQLException e) {
throw new JDBCConnectionException( "Could not create connection", e );
}
}
@Override
public boolean isUnwrappableAs(Class<?> unwrapType) {
return unwrapType.isAssignableFrom( AgroalConnectionProvider.class )
|| unwrapType.isAssignableFrom( AgroalDataSource.class );
}
@Override
@SuppressWarnings( "unchecked" )
public <T> T unwrap(Class<T> unwrapType) {
if ( unwrapType.isAssignableFrom( AgroalConnectionProvider.class ) ) {
return (T) this;
}
else if ( unwrapType.isAssignableFrom( AgroalDataSource.class ) ) {
return (T) agroalDataSource;
}
else {
throw new UnknownUnwrapTypeException( unwrapType );
}
}
// --- Stoppable
@Override
public void stop() {
if ( agroalDataSource != null ) {
CONNECTION_INFO_LOGGER.cleaningUpConnectionPool(
agroalDataSource.getConfiguration()
.connectionPoolConfiguration()
.connectionFactoryConfiguration()
.jdbcUrl() );
agroalDataSource.close();
}
}
}
|
AgroalConnectionProvider
|
java
|
apache__camel
|
components/camel-resilience4j/src/test/java/org/apache/camel/component/resilience4j/ResilienceRouteFallbackTest.java
|
{
"start": 1190,
"end": 3183
}
|
class ____ extends CamelTestSupport {
@Test
public void testResilience() throws Exception {
test("direct:start");
}
@Test
public void testResilienceWithTimeOut() throws Exception {
test("direct:start.with.timeout.enabled");
}
private void test(String endPointUri) throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Fallback message");
getMockEndpoint("mock:result").expectedPropertyReceived(CircuitBreakerConstants.RESPONSE_SUCCESSFUL_EXECUTION, false);
getMockEndpoint("mock:result").expectedPropertyReceived(CircuitBreakerConstants.RESPONSE_FROM_FALLBACK, true);
getMockEndpoint("mock:result").expectedPropertyReceived(CircuitBreakerConstants.RESPONSE_STATE, "CLOSED");
template.sendBody(endPointUri, "Hello World");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("log:start").circuitBreaker().throwException(new IllegalArgumentException("Forced"))
.onFallback().transform().constant("Fallback message")
.end().to("log:result").to("mock:result");
from("direct:start.with.timeout.enabled").to("log:start.with.timeout.enabled").circuitBreaker()
.resilience4jConfiguration().timeoutEnabled(true).timeoutDuration(2000).end()
.throwException(new TimeoutException("Forced"))
.onFallback()
.process(e -> {
Assertions.assertEquals("CLOSED", e.getProperty(CircuitBreakerConstants.RESPONSE_STATE));
}).transform().constant("Fallback message")
.end().to("log:result").to("mock:result");
}
};
}
}
|
ResilienceRouteFallbackTest
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_1359/Issue1359Mapper.java
|
{
"start": 344,
"end": 510
}
|
interface ____ {
Issue1359Mapper INSTANCE = Mappers.getMapper( Issue1359Mapper.class );
void map(@MappingTarget Target target, Source source);
}
|
Issue1359Mapper
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/RouterHeartbeatResponse.java
|
{
"start": 1208,
"end": 1737
}
|
class ____ {
public static RouterHeartbeatResponse newInstance() throws IOException {
return StateStoreSerializer.newRecord(RouterHeartbeatResponse.class);
}
public static RouterHeartbeatResponse newInstance(boolean status)
throws IOException {
RouterHeartbeatResponse response = newInstance();
response.setStatus(status);
return response;
}
@Public
@Unstable
public abstract boolean getStatus();
@Public
@Unstable
public abstract void setStatus(boolean result);
}
|
RouterHeartbeatResponse
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/physical/local/SpatialDocValuesExtraction.java
|
{
"start": 4971,
"end": 5411
}
|
class ____ described here, and is only determined during local physical planning on each data
* node. This is because the decision to use doc-values is based on the local data node's index configuration, and the local physical plan
* is the only place where this information is available. This also means that the knowledge of the usage of doc-values does not need
* to be serialized between nodes, and is only used locally.
*/
public
|
being
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/annotations/Comment.java
|
{
"start": 2016,
"end": 2189
}
|
interface ____ {
/**
* The text of the comment.
*/
String value();
/**
* The name of the table or column to add the comment to.
*/
String on() default "";
}
|
Comment
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertStartsWith_Test.java
|
{
"start": 1556,
"end": 8219
}
|
class ____ extends DoubleArraysBaseTest {
@Override
protected void initActualArray() {
actual = arrayOf(6d, 8d, 10d, 12d);
}
@Test
void should_throw_error_if_sequence_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_pass_if_actual_and_given_values_are_empty() {
actual = emptyArray();
arrays.assertStartsWith(someInfo(), actual, emptyArray());
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, emptyArray()));
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), null, arrayOf(8d)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual() {
double[] sequence = { 6d, 8d, 10d, 12d, 20d, 22d };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, sequence))
.withMessage(shouldStartWith(actual, sequence).create());
}
@Test
void should_fail_if_actual_does_not_start_with_sequence() {
double[] sequence = { 8d, 10d };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, sequence))
.withMessage(shouldStartWith(actual, sequence).create());
}
@Test
void should_fail_if_actual_starts_with_first_elements_of_sequence_only() {
double[] sequence = { 6d, 20d };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertStartsWith(someInfo(), actual, sequence))
.withMessage(shouldStartWith(actual, sequence).create());
}
@Test
void should_pass_if_actual_starts_with_sequence() {
arrays.assertStartsWith(someInfo(), actual, arrayOf(6d, 8d, 10d));
}
@Test
void should_pass_if_actual_and_sequence_are_equal() {
arrays.assertStartsWith(someInfo(), actual, arrayOf(6d, 8d, 10d, 12d));
}
@Test
void should_throw_error_if_sequence_is_null_whatever_custom_comparison_strategy_is() {
assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual,
emptyArray()));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
null,
arrayOf(-8d)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual_according_to_custom_comparison_strategy() {
double[] sequence = { 6d, -8d, 10d, 12d, 20d, 22d };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual,
sequence))
.withMessage(shouldStartWith(actual, sequence,
absValueComparisonStrategy).create());
}
@Test
void should_fail_if_actual_does_not_start_with_sequence_according_to_custom_comparison_strategy() {
double[] sequence = { -8d, 10d };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual,
sequence))
.withMessage(shouldStartWith(actual, sequence,
absValueComparisonStrategy).create());
}
@Test
void should_fail_if_actual_starts_with_first_elements_of_sequence_only_according_to_custom_comparison_strategy() {
double[] sequence = { 6d, 20d };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(),
actual,
sequence))
.withMessage(shouldStartWith(actual, sequence,
absValueComparisonStrategy).create());
}
@Test
void should_pass_if_actual_starts_with_sequence_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(), actual, arrayOf(6d, -8d, 10d));
}
@Test
void should_pass_if_actual_and_sequence_are_equal_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertStartsWith(someInfo(), actual, arrayOf(6d, -8d, 10d, 12d));
}
}
|
DoubleArrays_assertStartsWith_Test
|
java
|
apache__maven
|
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnup/goals/HelpTest.java
|
{
"start": 1196,
"end": 3511
}
|
class ____ {
private Help help;
@BeforeEach
void setUp() {
help = new Help();
}
private UpgradeContext createMockContext() {
return TestUtils.createMockContext();
}
@Test
void testHelpExecuteReturnsZero() throws Exception {
UpgradeContext context = createMockContext();
int result = help.execute(context);
assertEquals(0, result, "Help goal should return 0 (success)");
}
@Test
void testHelpExecuteDoesNotThrow() throws Exception {
UpgradeContext context = createMockContext();
// Should not throw any exceptions
assertDoesNotThrow(() -> help.execute(context));
}
@Test
void testHelpLogsMessages() throws Exception {
UpgradeContext context = createMockContext();
help.execute(context);
// Verify that logger.info was called multiple times
// We can't easily verify the exact content without capturing the logger output,
// but we can verify that the method executes without errors
Mockito.verify(context.logger, Mockito.atLeastOnce()).info(Mockito.anyString());
}
@Test
void testHelpIncludesPluginsOption() throws Exception {
UpgradeContext context = createMockContext();
help.execute(context);
// Verify that the plugins option is mentioned in the help output
Mockito.verify(context.logger).info(" --plugins Upgrade plugins known to fail with Maven 4");
}
@Test
void testHelpIncludesAllOption() throws Exception {
UpgradeContext context = createMockContext();
help.execute(context);
// Verify that the --all option is mentioned with correct description
Mockito.verify(context.logger)
.info(
" -a, --all Apply all upgrades (equivalent to --model-version 4.1.0 --infer --model --plugins)");
}
@Test
void testHelpIncludesDefaultBehavior() throws Exception {
UpgradeContext context = createMockContext();
help.execute(context);
// Verify that the default behavior is explained
Mockito.verify(context.logger)
.info("Default behavior: --model and --plugins are applied if no other options are specified");
}
}
|
HelpTest
|
java
|
alibaba__nacos
|
console/src/main/java/com/alibaba/nacos/console/handler/impl/inner/core/NamespaceInnerHandler.java
|
{
"start": 1278,
"end": 2751
}
|
class ____ implements NamespaceHandler {
private final NamespaceOperationService namespaceOperationService;
public NamespaceInnerHandler(NamespaceOperationService namespaceOperationService) {
this.namespaceOperationService = namespaceOperationService;
}
@Override
public List<Namespace> getNamespaceList() {
return namespaceOperationService.getNamespaceList();
}
@Override
public Namespace getNamespaceDetail(String namespaceId) throws NacosException {
return namespaceOperationService.getNamespace(namespaceId);
}
@Override
public Boolean createNamespace(String namespaceId, String namespaceName, String namespaceDesc)
throws NacosException {
return namespaceOperationService.createNamespace(namespaceId, namespaceName, namespaceDesc);
}
@Override
public Boolean updateNamespace(NamespaceForm namespaceForm) throws NacosException {
return namespaceOperationService.editNamespace(namespaceForm.getNamespaceId(), namespaceForm.getNamespaceName(),
namespaceForm.getNamespaceDesc());
}
@Override
public Boolean deleteNamespace(String namespaceId) {
return namespaceOperationService.removeNamespace(namespaceId);
}
@Override
public Boolean checkNamespaceIdExist(String namespaceId) {
return namespaceOperationService.namespaceExists(namespaceId);
}
}
|
NamespaceInnerHandler
|
java
|
quarkusio__quarkus
|
extensions/security-jpa-reactive/deployment/src/test/java/io/quarkus/security/jpa/reactive/MultipleEntitiesConfigurationTest.java
|
{
"start": 150,
"end": 700
}
|
class ____ extends JpaSecurityRealmTest {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(testClasses)
.addClass(ExternalRolesUserEntity.class)
.addClass(RoleEntity.class)
.addAsResource("multiple-entities/import.sql", "import.sql")
.addAsResource("multiple-entities/application.properties", "application.properties"));
}
|
MultipleEntitiesConfigurationTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java
|
{
"start": 8936,
"end": 9833
}
|
class ____ extends Restarter {
private @Nullable ClassLoader relaunchClassLoader;
TestableRestarter() {
this(Thread.currentThread(), new String[] {}, false, new MockRestartInitializer());
}
protected TestableRestarter(Thread thread, String[] args, boolean forceReferenceCleanup,
RestartInitializer initializer) {
super(thread, args, forceReferenceCleanup, initializer);
}
@Override
public void restart(FailureHandler failureHandler) {
try {
stop();
start(failureHandler);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
@Override
protected @Nullable Throwable relaunch(ClassLoader classLoader) {
this.relaunchClassLoader = classLoader;
return null;
}
@Override
protected void stop() {
}
@Nullable ClassLoader getRelaunchClassLoader() {
return this.relaunchClassLoader;
}
}
static
|
TestableRestarter
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/active/ActiveResourceManager.java
|
{
"start": 30194,
"end": 31133
}
|
class ____ implements ResourceAllocator {
@Override
public boolean isSupported() {
return true;
}
@Override
public void cleaningUpDisconnectedResource(ResourceID resourceID) {
validateRunsInMainThread();
internalStopWorker(resourceID);
}
@Override
public void declareResourceNeeded(Collection<ResourceDeclaration> resourceDeclarations) {
validateRunsInMainThread();
ActiveResourceManager.this.declareResourceNeeded(resourceDeclarations);
}
}
// ------------------------------------------------------------------------
// Testing
// ------------------------------------------------------------------------
@VisibleForTesting
<T> CompletableFuture<T> runInMainThread(Callable<T> callable, Duration timeout) {
return callAsync(callable, timeout);
}
}
|
ResourceAllocatorImpl
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceTest.java
|
{
"start": 2028,
"end": 2221
}
|
class ____ extends EntityBase {
public Cheese() {
}
public Cheese(Long id, String name) {
super( id, name );
}
}
@Entity(name = "Smell")
@BatchSize(size = 10)
public static
|
Cheese
|
java
|
quarkusio__quarkus
|
integration-tests/maven/src/test/resources-filtered/projects/build-mode-quarkus-profile-override/src/main/java/org/acme/HelloResource.java
|
{
"start": 257,
"end": 443
}
|
class ____ {
@Inject
HelloService service;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello, " + service.name();
}
}
|
HelloResource
|
java
|
quarkusio__quarkus
|
integration-tests/rest-client-reactive-http2/src/main/java/io/quarkus/it/rest/client/http2/GreetingResource.java
|
{
"start": 49,
"end": 181
}
|
class ____ extends AbstractGreetingResource {
@Override
public String hello() {
return "Hello";
}
}
|
GreetingResource
|
java
|
netty__netty
|
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicChannel.java
|
{
"start": 2992,
"end": 3242
}
|
class ____ extends AbstractChannel implements QuicChannel {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(QuicheQuicChannel.class);
private static final String QLOG_FILE_EXTENSION = ".qlog";
|
QuicheQuicChannel
|
java
|
spring-projects__spring-framework
|
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java
|
{
"start": 22486,
"end": 24269
}
|
class ____ implements SockJsRequestHandler {
private static final String IFRAME_CONTENT = """
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SockJS iframe</title>
<script>
document.domain = document.domain;
_sockjs_onload = function(){SockJS.bootstrap_iframe();};
</script>
<script src="%s"></script>
</head>
<body>
<h2>Don't panic!</h2>
<p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>
</body>
</html>""";
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
if (request.getMethod() != HttpMethod.GET) {
sendMethodNotAllowed(response, HttpMethod.GET);
return;
}
String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl());
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder("\"0");
DigestUtils.appendMd5DigestAsHex(contentBytes, builder);
builder.append('"');
String etagValue = builder.toString();
List<String> ifNoneMatch = request.getHeaders().getIfNoneMatch();
if (!CollectionUtils.isEmpty(ifNoneMatch) && ifNoneMatch.get(0).equals(etagValue)) {
response.setStatusCode(HttpStatus.NOT_MODIFIED);
return;
}
response.getHeaders().setContentType(new MediaType("text", "html", StandardCharsets.UTF_8));
response.getHeaders().setContentLength(contentBytes.length);
// No cache in order to check every time if IFrame are authorized
addNoCacheHeaders(response);
response.getHeaders().setETag(etagValue);
response.getBody().write(contentBytes);
}
}
}
|
IframeHandler
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableIgnoreElementsCompletable.java
|
{
"start": 1529,
"end": 2784
}
|
class ____<T> implements FlowableSubscriber<T>, Disposable {
final CompletableObserver downstream;
Subscription upstream;
IgnoreElementsSubscriber(CompletableObserver downstream) {
this.downstream = downstream;
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
s.request(Long.MAX_VALUE);
}
}
@Override
public void onNext(T t) {
// deliberately ignored
}
@Override
public void onError(Throwable t) {
upstream = SubscriptionHelper.CANCELLED;
downstream.onError(t);
}
@Override
public void onComplete() {
upstream = SubscriptionHelper.CANCELLED;
downstream.onComplete();
}
@Override
public void dispose() {
upstream.cancel();
upstream = SubscriptionHelper.CANCELLED;
}
@Override
public boolean isDisposed() {
return upstream == SubscriptionHelper.CANCELLED;
}
}
}
|
IgnoreElementsSubscriber
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/Maps.java
|
{
"start": 138925,
"end": 140136
}
|
class ____<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMap<K, V> {
/**
* Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most
* once on a given map, at the time when {@code entrySet} is first called.
*/
abstract Set<Entry<K, V>> createEntrySet();
@LazyInit private transient @Nullable Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
@LazyInit private transient @Nullable Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
Set<K> createKeySet() {
return new KeySet<>(this);
}
@LazyInit private transient @Nullable Collection<V> values;
@Override
public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = createValues() : result;
}
Collection<V> createValues() {
return new Values<>(this);
}
}
abstract static
|
ViewCachingAbstractMap
|
java
|
alibaba__nacos
|
auth/src/main/java/com/alibaba/nacos/auth/serveridentity/DefaultChecker.java
|
{
"start": 851,
"end": 1386
}
|
class ____ implements ServerIdentityChecker {
private NacosAuthConfig authConfig;
@Override
public void init(NacosAuthConfig authConfigs) {
this.authConfig = authConfigs;
}
@Override
public ServerIdentityResult check(ServerIdentity serverIdentity, Secured secured) {
if (authConfig.getServerIdentityValue().equals(serverIdentity.getIdentityValue())) {
return ServerIdentityResult.success();
}
return ServerIdentityResult.noMatched();
}
}
|
DefaultChecker
|
java
|
apache__kafka
|
trogdor/src/main/java/org/apache/kafka/trogdor/agent/WorkerManager.java
|
{
"start": 20986,
"end": 21870
}
|
class ____ implements Callable<Void> {
private final Worker worker;
HaltWorker(Worker worker) {
this.worker = worker;
}
@Override
public Void call() throws Exception {
String failure = "";
try {
worker.taskWorker.stop(platform);
} catch (Exception exception) {
log.error("{}: worker.stop() exception", nodeName, exception);
failure = exception.getMessage();
}
stateChangeExecutor.submit(new CompleteWorker(worker, failure));
return null;
}
}
public TreeMap<Long, WorkerState> workerStates() throws Exception {
try (ShutdownManager.Reference ref = shutdownManager.takeReference()) {
return stateChangeExecutor.submit(new GetWorkerStates()).get();
}
}
|
HaltWorker
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/tests/deployment/VerticleFactoryTest.java
|
{
"start": 890,
"end": 12231
}
|
class ____ extends VertxTestBase {
@Parameterized.Parameter
public boolean legacy;
@Parameterized.Parameters(name = "{index}: implement new/old verticle factory={0}")
public static List<Object[]> params() {
return Arrays.asList(new Object[] {true}, new Object[] {false});
}
public void setUp() throws Exception {
super.setUp();
// Unregister the factories that are loaded from the classpath
for (VerticleFactory factory : vertx.verticleFactories()) {
vertx.unregisterVerticleFactory(factory);
}
}
@Test
public void testRegister() {
assertTrue(vertx.verticleFactories().isEmpty());
VerticleFactory fact1 = createTestVerticleFactory("foo");
vertx.registerVerticleFactory(fact1);
assertEquals(1, vertx.verticleFactories().size());
assertTrue(vertx.verticleFactories().contains(fact1));
}
@Test
public void testUnregister() {
VerticleFactory fact1 = createTestVerticleFactory("foo");
vertx.registerVerticleFactory(fact1);
assertEquals(1, vertx.verticleFactories().size());
assertTrue(vertx.verticleFactories().contains(fact1));
vertx.unregisterVerticleFactory(fact1);
assertFalse(vertx.verticleFactories().contains(fact1));
assertTrue(vertx.verticleFactories().isEmpty());
}
@Test
public void testRegisterTwice() {
VerticleFactory fact1 = createTestVerticleFactory("foo");
vertx.registerVerticleFactory(fact1);
try {
vertx.registerVerticleFactory(fact1);
fail("Should throw exception");
} catch (IllegalArgumentException e) {
// OK
}
}
@Test
public void testUnregisterTwice() {
VerticleFactory fact1 = createTestVerticleFactory("foo");
vertx.registerVerticleFactory(fact1);
vertx.unregisterVerticleFactory(fact1);
try {
vertx.unregisterVerticleFactory(fact1);
fail("Should throw exception");
} catch (IllegalArgumentException e) {
// OK
}
}
@Test
public void testUnregisterNoFact() {
VerticleFactory fact1 = createTestVerticleFactory("foo");
try {
vertx.unregisterVerticleFactory(fact1);
fail("Should throw exception");
} catch (IllegalArgumentException e) {
// OK
}
}
@Test
public void testRegisterUnregisterTwo() {
VerticleFactory fact1 = createTestVerticleFactory("foo");
VerticleFactory fact2 = createTestVerticleFactory("bar");
vertx.registerVerticleFactory(fact1);
assertEquals(1, vertx.verticleFactories().size());
vertx.registerVerticleFactory(fact2);
assertEquals(2, vertx.verticleFactories().size());
assertTrue(vertx.verticleFactories().contains(fact1));
assertTrue(vertx.verticleFactories().contains(fact2));
vertx.unregisterVerticleFactory(fact1);
assertFalse(vertx.verticleFactories().contains(fact1));
assertEquals(1, vertx.verticleFactories().size());
assertTrue(vertx.verticleFactories().contains(fact2));
vertx.unregisterVerticleFactory(fact2);
assertTrue(vertx.verticleFactories().isEmpty());
assertFalse(vertx.verticleFactories().contains(fact1));
assertFalse(vertx.verticleFactories().contains(fact2));
}
@Test
public void testMatchWithPrefix() {
TestVerticle verticle1 = new TestVerticle();
TestVerticle verticle2 = new TestVerticle();
TestVerticle verticle3 = new TestVerticle();
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle1);
TestVerticleFactory fact2 = createTestVerticleFactory("bb", verticle2);
TestVerticleFactory fact3 = createTestVerticleFactory("cc", verticle3);
vertx.registerVerticleFactory(fact1);
vertx.registerVerticleFactory(fact2);
vertx.registerVerticleFactory(fact3);
String name1 = "aa:myverticle1";
String name2 = "bb:myverticle2";
String name3 = "cc:myverticle3";
vertx.deployVerticle(name1, new DeploymentOptions()).onComplete(onSuccess(ar -> {
assertEquals(name1, fact1.identifier);
assertTrue(verticle1.startCalled);
assertFalse(verticle2.startCalled);
assertFalse(verticle3.startCalled);
assertNull(fact2.identifier);
assertNull(fact3.identifier);
vertx.deployVerticle(name2, new DeploymentOptions()).onComplete(onSuccess(ar2 -> {
assertEquals(name2, fact2.identifier);
assertTrue(verticle2.startCalled);
assertFalse(verticle3.startCalled);
assertNull(fact3.identifier);
vertx.deployVerticle(name3, new DeploymentOptions()).onComplete(onSuccess(ar3 -> {
assertEquals(name3, fact3.identifier);
assertTrue(verticle3.startCalled);
testComplete();
}));
}));
}));
await();
}
@Test
public void testMatchWithSuffix() {
TestVerticle verticle1 = new TestVerticle();
TestVerticle verticle2 = new TestVerticle();
TestVerticle verticle3 = new TestVerticle();
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle1);
TestVerticleFactory fact2 = createTestVerticleFactory("bb", verticle2);
TestVerticleFactory fact3 = createTestVerticleFactory("cc", verticle3);
vertx.registerVerticleFactory(fact1);
vertx.registerVerticleFactory(fact2);
vertx.registerVerticleFactory(fact3);
String name1 = "myverticle1.aa";
String name2 = "myverticle2.bb";
String name3 = "myverticle3.cc";
vertx.deployVerticle(name1, new DeploymentOptions()).onComplete(onSuccess(ar -> {
assertEquals(name1, fact1.identifier);
assertTrue(verticle1.startCalled);
assertFalse(verticle2.startCalled);
assertFalse(verticle3.startCalled);
assertNull(fact2.identifier);
assertNull(fact3.identifier);
vertx.deployVerticle(name2, new DeploymentOptions()).onComplete(onSuccess(ar2 -> {
assertEquals(name2, fact2.identifier);
assertTrue(verticle2.startCalled);
assertFalse(verticle3.startCalled);
assertNull(fact3.identifier);
vertx.deployVerticle(name3, new DeploymentOptions()).onComplete(onSuccess(ar3 -> {
assertEquals(name3, fact3.identifier);
assertTrue(verticle3.startCalled);
testComplete();
}));
}));
}));
await();
}
@Test
public void testNoMatch() {
TestVerticle verticle1 = new TestVerticle();
TestVerticle verticle2 = new TestVerticle();
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle1);
TestVerticleFactory fact2 = createTestVerticleFactory("bb", verticle2);
vertx.registerVerticleFactory(fact1);
vertx.registerVerticleFactory(fact2);
String name1 = "cc:myverticle1";
// If no match it will default to the simple Java verticle factory and then fail with ClassNotFoundException
vertx.deployVerticle(name1, new DeploymentOptions()).onComplete(onFailure(err -> {
assertFalse(verticle1.startCalled);
assertFalse(verticle2.startCalled);
assertTrue(err instanceof ClassNotFoundException);
testComplete();
}));
await();
}
@Test
public void testOrdering() {
TestVerticle verticle = new TestVerticle();
TestVerticleFactory fact2 = createTestVerticleFactory("aa", verticle, 2);
vertx.registerVerticleFactory(fact2);
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle, 1);
vertx.registerVerticleFactory(fact1);
TestVerticleFactory fact3 = createTestVerticleFactory("aa", verticle, 3);
vertx.registerVerticleFactory(fact3);
vertx.deployVerticle("aa:someverticle").onComplete(onSuccess(res -> {
assertEquals("aa:someverticle", fact1.identifier);
assertNull(fact2.identifier);
assertNull(fact3.identifier);
testComplete();
}));
await();
}
@Test
public void testOrderingFailedInCreate() {
TestVerticle verticle = new TestVerticle();
TestVerticleFactory fact2 = createTestVerticleFactory("aa", verticle, 2);
vertx.registerVerticleFactory(fact2);
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle, 1, true);
vertx.registerVerticleFactory(fact1);
TestVerticleFactory fact3 = createTestVerticleFactory("aa", verticle, 3);
vertx.registerVerticleFactory(fact3);
vertx.deployVerticle("aa:someverticle").onComplete(onSuccess(res -> {
assertEquals("aa:someverticle", fact2.identifier);
assertNull(fact1.identifier);
assertNull(fact3.identifier);
testComplete();
}));
await();
}
@Test
public void testOrderingFailedInCreate2() {
TestVerticle verticle = new TestVerticle();
TestVerticleFactory fact2 = createTestVerticleFactory("aa", verticle, 2, true);
vertx.registerVerticleFactory(fact2);
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle, 1, true);
vertx.registerVerticleFactory(fact1);
TestVerticleFactory fact3 = createTestVerticleFactory("aa", verticle, 3);
vertx.registerVerticleFactory(fact3);
vertx.deployVerticle("aa:someverticle").onComplete(onSuccess(res -> {
assertEquals("aa:someverticle", fact3.identifier);
assertNull(fact1.identifier);
assertNull(fact2.identifier);
testComplete();
}));
await();
}
@Test
public void testOrderingFailedInCreateAll() {
TestVerticle verticle = new TestVerticle();
TestVerticleFactory fact2 = createTestVerticleFactory("aa", verticle, 2, true);
vertx.registerVerticleFactory(fact2);
TestVerticleFactory fact1 = createTestVerticleFactory("aa", verticle, 1, true);
vertx.registerVerticleFactory(fact1);
TestVerticleFactory fact3 = createTestVerticleFactory("aa", verticle, 3, true);
vertx.registerVerticleFactory(fact3);
vertx.deployVerticle("aa:someverticle").onComplete(onFailure(err -> {
assertTrue(err instanceof ClassNotFoundException);
assertNull(fact1.identifier);
assertNull(fact2.identifier);
assertNull(fact3.identifier);
testComplete();
}));
await();
}
@Test
public void testDeploymentOnClosedVertxWithCompletionHandler() {
TestVerticle verticle = new TestVerticle();
vertx.close().onComplete(done -> {
vertx.deployVerticle(verticle).onComplete(onFailure(err -> {
testComplete();
}));
});
await();
}
@Test
public void testDeploymentOnClosedVertxWithoutCompletionHandler() {
TestVerticle verticle = new TestVerticle();
vertx.close().onComplete(done -> {
vertx.deployVerticle(verticle);
testComplete();
});
await();
}
TestVerticleFactory createTestVerticleFactory(String prefix) {
return legacy ? new TestVerticleFactory.Vertx4(prefix) : new TestVerticleFactory.Vertx5(prefix);
}
TestVerticleFactory createTestVerticleFactory(String prefix, Verticle verticle) {
return legacy ? new TestVerticleFactory.Vertx4(prefix, verticle) : new TestVerticleFactory.Vertx5(prefix, verticle);
}
TestVerticleFactory createTestVerticleFactory(String prefix, Verticle verticle, int order) {
return legacy ? new TestVerticleFactory.Vertx4(prefix, verticle, order) : new TestVerticleFactory.Vertx5(prefix, verticle, order);
}
TestVerticleFactory createTestVerticleFactory(String prefix, Verticle verticle, int order, boolean failInCreate) {
return legacy ? new TestVerticleFactory.Vertx4(prefix, verticle, order, failInCreate) : new TestVerticleFactory.Vertx5(prefix, verticle, order, failInCreate);
}
abstract static
|
VerticleFactoryTest
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/sources/DefinedFieldMapping.java
|
{
"start": 1165,
"end": 1832
}
|
interface ____ a mapping for the fields of the table schema
* ({@link TableSource#getTableSchema} to fields of the physical produced data type {@link
* TableSource#getProducedDataType()} of a {@link TableSource}.
*
* <p>If a {@link TableSource} does not implement the {@link DefinedFieldMapping} interface, the
* fields of its {@link TableSchema} are mapped to the fields of its produced {@link DataType} by
* name.
*
* <p>If the fields cannot or should not be implicitly mapped by name, an explicit mapping can be
* provided by implementing this interface.
*
* <p>If a mapping is provided, all fields must be explicitly mapped.
*
* @deprecated This
|
provides
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/ContainerElementConstraintsTest.java
|
{
"start": 3196,
"end": 3362
}
|
class ____ {
public void test(Map<String, List<@NotBlank String>> constrainedMap) {
// do nothing
}
}
static
|
MethodParameterTestBean
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/tests/tracing/EventBusTracingTestBase.java
|
{
"start": 925,
"end": 5788
}
|
class ____ extends VertxTestBase {
Vertx vertx1;
Vertx vertx2;
FakeTracer tracer;
@Override
public void setUp() throws Exception {
tracer = new FakeTracer();
super.setUp();
}
@Override
protected VertxTracer getTracer() {
return tracer;
}
@Test
public void testEventBusSendPropagate() throws Exception {
testSend(TracingPolicy.PROPAGATE, true, 2);
}
@Test
public void testEventBusSendIgnore() throws Exception {
testSend(TracingPolicy.IGNORE, true, 0);
}
@Test
public void testEventBusSendAlways() throws Exception {
testSend(TracingPolicy.ALWAYS, false, 2);
}
private void testSend(TracingPolicy policy, boolean create, int expected) throws Exception {
AtomicInteger received = new AtomicInteger();
vertx2.eventBus().consumer("the-address", msg -> {
received.incrementAndGet();
});
Context ctx = vertx1.getOrCreateContext();
ctx.runOnContext(v -> {
if (create) {
tracer.activate(tracer.newTrace());
}
vertx1.eventBus().send("the-address", "ping", new DeliveryOptions().setTracingPolicy(policy));
});
assertWaitUntil(() -> tracer.getFinishedSpans().size() == expected);
assertWaitUntil(() -> received.get() == 1);
List<Span> finishedSpans = tracer.getFinishedSpans();
assertSingleTrace(finishedSpans);
finishedSpans.forEach(span -> {
assertEquals("send", span.operation);
});
}
@Test
public void testEventBusPublishProgagate() throws Exception {
testPublish(TracingPolicy.PROPAGATE, true, 3, true);
}
@Test
public void testEventBusPublishIgnore() throws Exception {
testPublish(TracingPolicy.IGNORE, true, 0, false);
}
@Test
public void testEventBusPublishAlways() throws Exception {
testPublish(TracingPolicy.ALWAYS, false, 3, true);
}
private void testPublish(TracingPolicy policy, boolean create, int expected, boolean singleTrace) throws Exception {
vertx2.eventBus().consumer("the-address", msg -> {
});
vertx2.eventBus().consumer("the-address", msg -> {
});
Context ctx = vertx1.getOrCreateContext();
ctx.runOnContext(v -> {
if (create) {
tracer.activate(tracer.newTrace());
}
vertx1.eventBus().publish("the-address", "ping", new DeliveryOptions().setTracingPolicy(policy));
});
assertWaitUntil(() -> tracer.getFinishedSpans().size() == expected);
List<Span> finishedSpans = tracer.getFinishedSpans();
if (singleTrace) {
assertSingleTrace(finishedSpans);
}
finishedSpans.forEach(span -> {
assertEquals("publish", span.operation);
});
}
@Test
public void testEventBusRequestReplyPropagate() throws Exception {
testRequestReply(TracingPolicy.PROPAGATE, true, false, 2);
}
@Test
public void testEventBusRequestReplyIgnore() throws Exception {
testRequestReply(TracingPolicy.IGNORE, true, false, 0);
}
@Test
public void testEventBusRequestReplyAlways() throws Exception {
testRequestReply(TracingPolicy.ALWAYS, false, false, 2);
}
@Test
public void testEventBusRequestReplyFailurePropagate() throws Exception {
testRequestReply(TracingPolicy.PROPAGATE, true, true, 2);
}
@Test
public void testEventBusRequestReplyFailureIgnore() throws Exception {
testRequestReply(TracingPolicy.IGNORE, true, true, 0);
}
@Test
public void testEventBusRequestReplyFailureAlways() throws Exception {
testRequestReply(TracingPolicy.ALWAYS, false, true, 2);
}
private void testRequestReply(TracingPolicy policy, boolean create, boolean fail, int expected) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
vertx2.eventBus().consumer("the-address", msg -> {
if (fail) {
msg.fail(10, "it failed");
} else {
msg.reply("pong");
}
});
Context ctx = vertx1.getOrCreateContext();
ctx.runOnContext(v -> {
if (create) {
tracer.activate(tracer.newTrace());
}
vertx1.eventBus().request("the-address", "ping", new DeliveryOptions().setTracingPolicy(policy)).onComplete(ar -> {
assertEquals(fail, ar.failed());
vertx1.runOnContext(v2 -> latch.countDown()); // make sure span is finished
});
});
awaitLatch(latch);
List<Span> finishedSpans = tracer.getFinishedSpans();
assertWaitUntil(() -> finishedSpans.size() == expected);
assertSingleTrace(finishedSpans);
finishedSpans.forEach(span -> {
assertEquals("send", span.operation);
assertEquals("vertx-eventbus", span.getTags().get("messaging.system"));
assertEquals("send", span.getTags().get("messaging.operation.name"));
});
}
private void assertSingleTrace(List<Span> spans) {
for (int i = 1; i < spans.size(); i++) {
assertEquals(spans.get(i - 1).traceId, spans.get(i).traceId);
}
}
}
|
EventBusTracingTestBase
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/AbstractMockitoBeanNestedAndTypeHierarchiesWithSuperclassPresentTwiceTests.java
|
{
"start": 1806,
"end": 2137
}
|
class ____ {
@Autowired
ApplicationContext enclosingContext;
@MockitoBean
ExampleService service;
@Test
void topLevelTest() {
assertIsMock(service);
assertThat(enclosingContext.getBeanNamesForType(ExampleService.class)).hasSize(1);
}
abstract
|
AbstractMockitoBeanNestedAndTypeHierarchiesWithSuperclassPresentTwiceTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/component/EmbeddableAndGenericExtendingSerializableMappedSuperclassTest.java
|
{
"start": 2054,
"end": 2312
}
|
class ____<C extends Serializable> {
@Embedded
private C embedded;
public C getEmbedded() {
return embedded;
}
public void setEmbedded(C embedded) {
this.embedded = embedded;
}
}
@Entity(name = "MyEntity")
public static
|
MyMappedSuperclass
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/scheduler/DistributedScheduler.java
|
{
"start": 3426,
"end": 10988
}
|
class ____ extends AbstractRequestInterceptor {
private static final Logger LOG = LoggerFactory
.getLogger(DistributedScheduler.class);
private final static RecordFactory RECORD_FACTORY =
RecordFactoryProvider.getRecordFactory(null);
private OpportunisticContainerContext oppContainerContext =
new OpportunisticContainerContext();
// Mapping of NodeId to NodeTokens. Populated either from RM response or
// generated locally if required.
private Map<NodeId, NMToken> nodeTokens = new HashMap<>();
private ApplicationAttemptId applicationAttemptId;
private OpportunisticContainerAllocator containerAllocator;
private NMTokenSecretManagerInNM nmSecretManager;
private String appSubmitter;
private long rmIdentifier;
public void init(AMRMProxyApplicationContext applicationContext) {
super.init(applicationContext);
initLocal(applicationContext.getNMContext().getNodeStatusUpdater()
.getRMIdentifier(),
applicationContext.getApplicationAttemptId(),
applicationContext.getNMContext().getContainerAllocator(),
applicationContext.getNMContext().getNMTokenSecretManager(),
applicationContext.getUser());
}
@VisibleForTesting
void initLocal(long rmId, ApplicationAttemptId appAttemptId,
OpportunisticContainerAllocator oppContainerAllocator,
NMTokenSecretManagerInNM nmSecretManager, String appSubmitter) {
this.rmIdentifier = rmId;
this.applicationAttemptId = appAttemptId;
this.containerAllocator = oppContainerAllocator;
this.nmSecretManager = nmSecretManager;
this.appSubmitter = appSubmitter;
// Overrides the Generator to decrement container id.
this.oppContainerContext.setContainerIdGenerator(
new OpportunisticContainerAllocator.ContainerIdGenerator() {
@Override
public long generateContainerId() {
return this.containerIdCounter.decrementAndGet();
}
});
}
/**
* Route register call to the corresponding distributed scheduling method viz.
* registerApplicationMasterForDistributedScheduling, and return response to
* the caller after stripping away Distributed Scheduling information.
*
* @param request
* registration request
* @return Allocate Response
* @throws YarnException YarnException
* @throws IOException IOException
*/
@Override
public RegisterApplicationMasterResponse registerApplicationMaster
(RegisterApplicationMasterRequest request) throws YarnException,
IOException {
return registerApplicationMasterForDistributedScheduling(request)
.getRegisterResponse();
}
/**
* Route allocate call to the allocateForDistributedScheduling method and
* return response to the caller after stripping away Distributed Scheduling
* information.
*
* @param request
* allocation request
* @return Allocate Response
* @throws YarnException YarnException
* @throws IOException IOException
*/
@Override
public AllocateResponse allocate(AllocateRequest request) throws
YarnException, IOException {
DistributedSchedulingAllocateRequest distRequest = RECORD_FACTORY
.newRecordInstance(DistributedSchedulingAllocateRequest.class);
distRequest.setAllocateRequest(request);
return allocateForDistributedScheduling(distRequest).getAllocateResponse();
}
@Override
public FinishApplicationMasterResponse finishApplicationMaster
(FinishApplicationMasterRequest request) throws YarnException,
IOException {
return getNextInterceptor().finishApplicationMaster(request);
}
/**
* Adds all the newly allocated Containers to the allocate Response.
* Additionally, in case the NMToken for one of the nodes does not exist, it
* generates one and adds it to the response.
*/
private void updateAllocateResponse(AllocateResponse response,
List<NMToken> nmTokens, List<Container> allocatedContainers) {
List<NMToken> newTokens = new ArrayList<>();
if (allocatedContainers.size() > 0) {
response.getAllocatedContainers().addAll(allocatedContainers);
for (Container alloc : allocatedContainers) {
if (!nodeTokens.containsKey(alloc.getNodeId())) {
newTokens.add(nmSecretManager.generateNMToken(appSubmitter, alloc));
}
}
List<NMToken> retTokens = new ArrayList<>(nmTokens);
retTokens.addAll(newTokens);
response.setNMTokens(retTokens);
}
}
private void updateParameters(
RegisterDistributedSchedulingAMResponse registerResponse) {
Resource incrementResource = registerResponse.getIncrContainerResource();
if (incrementResource == null) {
incrementResource = registerResponse.getMinContainerResource();
}
oppContainerContext.updateAllocationParams(
registerResponse.getMinContainerResource(),
registerResponse.getMaxContainerResource(),
incrementResource,
registerResponse.getContainerTokenExpiryInterval());
oppContainerContext.getContainerIdGenerator()
.resetContainerIdCounter(registerResponse.getContainerIdStart());
setNodeList(registerResponse.getNodesForScheduling());
}
private void setNodeList(List<RemoteNode> nodeList) {
oppContainerContext.updateNodeList(nodeList);
}
@Override
public RegisterDistributedSchedulingAMResponse
registerApplicationMasterForDistributedScheduling(
RegisterApplicationMasterRequest request)
throws YarnException, IOException {
LOG.info("Forwarding registration request to the" +
"Distributed Scheduler Service on YARN RM");
RegisterDistributedSchedulingAMResponse dsResp = getNextInterceptor()
.registerApplicationMasterForDistributedScheduling(request);
updateParameters(dsResp);
return dsResp;
}
@Override
public DistributedSchedulingAllocateResponse allocateForDistributedScheduling(
DistributedSchedulingAllocateRequest request)
throws YarnException, IOException {
// Partition requests to GUARANTEED and OPPORTUNISTIC.
OpportunisticContainerAllocator.PartitionedResourceRequests
partitionedAsks = containerAllocator
.partitionAskList(request.getAllocateRequest().getAskList());
// Allocate OPPORTUNISTIC containers.
List<Container> allocatedContainers =
containerAllocator.allocateContainers(
request.getAllocateRequest().getResourceBlacklistRequest(),
partitionedAsks.getOpportunistic(), applicationAttemptId,
oppContainerContext, rmIdentifier, appSubmitter);
// Prepare request for sending to RM for scheduling GUARANTEED containers.
request.setAllocatedContainers(allocatedContainers);
request.getAllocateRequest().setAskList(partitionedAsks.getGuaranteed());
LOG.debug("Forwarding allocate request to the" +
"Distributed Scheduler Service on YARN RM");
DistributedSchedulingAllocateResponse dsResp =
getNextInterceptor().allocateForDistributedScheduling(request);
// Update host to nodeId mapping
setNodeList(dsResp.getNodesForScheduling());
List<NMToken> nmTokens = dsResp.getAllocateResponse().getNMTokens();
for (NMToken nmToken : nmTokens) {
nodeTokens.put(nmToken.getNodeId(), nmToken);
}
// Check if we have NM tokens for all the allocated containers. If not
// generate one and update the response.
updateAllocateResponse(
dsResp.getAllocateResponse(), nmTokens, allocatedContainers);
return dsResp;
}
}
|
DistributedScheduler
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableWithLatestFromMany.java
|
{
"start": 1380,
"end": 3300
}
|
class ____<T, R> extends AbstractFlowableWithUpstream<T, R> {
@Nullable
final Publisher<?>[] otherArray;
@Nullable
final Iterable<? extends Publisher<?>> otherIterable;
final Function<? super Object[], R> combiner;
public FlowableWithLatestFromMany(@NonNull Flowable<T> source, @NonNull Publisher<?>[] otherArray, Function<? super Object[], R> combiner) {
super(source);
this.otherArray = otherArray;
this.otherIterable = null;
this.combiner = combiner;
}
public FlowableWithLatestFromMany(@NonNull Flowable<T> source, @NonNull Iterable<? extends Publisher<?>> otherIterable, @NonNull Function<? super Object[], R> combiner) {
super(source);
this.otherArray = null;
this.otherIterable = otherIterable;
this.combiner = combiner;
}
@Override
protected void subscribeActual(Subscriber<? super R> s) {
Publisher<?>[] others = otherArray;
int n = 0;
if (others == null) {
others = new Publisher[8];
try {
for (Publisher<?> p : otherIterable) {
if (n == others.length) {
others = Arrays.copyOf(others, n + (n >> 1));
}
others[n++] = p;
}
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, s);
return;
}
} else {
n = others.length;
}
if (n == 0) {
new FlowableMap<>(source, new SingletonArrayFunc()).subscribeActual(s);
return;
}
WithLatestFromSubscriber<T, R> parent = new WithLatestFromSubscriber<>(s, combiner, n);
s.onSubscribe(parent);
parent.subscribe(others, n);
source.subscribe(parent);
}
static final
|
FlowableWithLatestFromMany
|
java
|
apache__maven
|
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/cisupport/CIDetector.java
|
{
"start": 1038,
"end": 1203
}
|
interface ____ {
/**
* Returns non-empty optional with CI information, if CI is detected, empty otherwise.
*/
Optional<CIInfo> detectCI();
}
|
CIDetector
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/NativeQueryAndDiscriminatorTest.java
|
{
"start": 1169,
"end": 2159
}
|
class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
TestEntity e = new TestEntity( 1l, "test", EntityDiscriminator.T );
session.persist( e );
}
);
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testNativeQuery(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
BaseEntity entity = session.createNativeQuery(
"select * from BASE_ENTITY where id = :id",
BaseEntity.class
)
.setParameter( "id", 1l )
.getSingleResult();
assertThat( entity ).isNotNull();
}
);
}
@Entity(name = "BaseEntity")
@Table(name = "BASE_ENTITY")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.CHAR)
@DiscriminatorValue("B")
public static
|
NativeQueryAndDiscriminatorTest
|
java
|
apache__flink
|
flink-table/flink-table-common/src/test/java/org/apache/flink/table/test/InternalDataUtils.java
|
{
"start": 1841,
"end": 7007
}
|
class ____ {
static Object toGenericInternalData(Object object, LogicalType logicalType) {
if (object instanceof RowData) {
return toGenericRow((RowData) object, logicalType);
} else if (object instanceof ArrayData) {
return toGenericArray((ArrayData) object, logicalType);
} else if (object instanceof MapData) {
return toGenericMap((MapData) object, logicalType);
}
return object;
}
static GenericRowData toGenericRow(RowData rowData, LogicalType logicalType) {
final List<LogicalType> fieldTypes = LogicalTypeChecks.getFieldTypes(logicalType);
final GenericRowData row = new GenericRowData(fieldTypes.size());
row.setRowKind(rowData.getRowKind());
for (int i = 0; i < fieldTypes.size(); i++) {
if (rowData.isNullAt(i)) {
row.setField(i, null);
} else {
LogicalType fieldType = fieldTypes.get(i);
RowData.FieldGetter fieldGetter = RowData.createFieldGetter(fieldType, i);
row.setField(
i, toGenericInternalData(fieldGetter.getFieldOrNull(rowData), fieldType));
}
}
return row;
}
static GenericArrayData toGenericArray(ArrayData arrayData, LogicalType logicalType) {
final LogicalType innerElement = ((ArrayType) logicalType).getElementType();
final ArrayData.ElementGetter elementGetter = ArrayData.createElementGetter(innerElement);
final Object[] newArray = new Object[arrayData.size()];
for (int i = 0; i < arrayData.size(); i++) {
if (arrayData.isNullAt(i)) {
newArray[i] = null;
} else {
newArray[i] =
toGenericInternalData(
elementGetter.getElementOrNull(arrayData, i), innerElement);
}
}
return new GenericArrayData(newArray);
}
static GenericMapData toGenericMap(MapData mapData, LogicalType logicalType) {
final LogicalType keyType =
logicalType.is(LogicalTypeRoot.MULTISET)
? ((MultisetType) logicalType).getElementType()
: ((MapType) logicalType).getKeyType();
final LogicalType valueType =
logicalType.is(LogicalTypeRoot.MULTISET)
? new IntType(false)
: ((MapType) logicalType).getValueType();
final ArrayData.ElementGetter keyGetter = ArrayData.createElementGetter(keyType);
final ArrayData.ElementGetter valueGetter = ArrayData.createElementGetter(valueType);
final ArrayData keys = mapData.keyArray();
final ArrayData values = mapData.valueArray();
final LinkedHashMap<Object, Object> newMap = new LinkedHashMap<>();
for (int i = 0; i < mapData.size(); i++) {
Object key = null;
Object value = null;
if (!keys.isNullAt(i)) {
key = toGenericInternalData(keyGetter.getElementOrNull(keys, i), keyType);
}
if (!values.isNullAt(i)) {
value = toGenericInternalData(valueGetter.getElementOrNull(values, i), valueType);
}
newMap.put(key, value);
}
return new GenericMapData(newMap);
}
static Function<RowData, Row> resolveToExternalOrNull(DataType dataType) {
try {
// Create the converter
Method getConverter =
Class.forName("org.apache.flink.table.data.conversion.DataStructureConverters")
.getMethod("getConverter", DataType.class);
Object converter = getConverter.invoke(null, dataType);
// Open the converter
converter
.getClass()
.getMethod("open", ClassLoader.class)
.invoke(converter, Thread.currentThread().getContextClassLoader());
Method toExternalOrNull =
converter.getClass().getMethod("toExternalOrNull", Object.class);
// Return the lambda to invoke the converter
return rowData -> {
try {
return (Row) toExternalOrNull.invoke(converter, rowData);
} catch (IllegalAccessException | InvocationTargetException e) {
Assertions.fail(
"Something went wrong when trying to use the DataStructureConverter from flink-table-runtime",
e);
return null; // For the compiler
}
};
} catch (ClassNotFoundException
| InvocationTargetException
| NoSuchMethodException
| IllegalAccessException e) {
Assertions.fail(
"Error when trying to use the RowData to Row conversion. "
+ "Perhaps you miss flink-table-runtime in your test classpath?",
e);
return null; // For the compiler
}
}
}
|
InternalDataUtils
|
java
|
square__moshi
|
examples/src/main/java/com/squareup/moshi/recipes/CustomAdapterWithDelegate.java
|
{
"start": 1805,
"end": 2194
}
|
class ____ {
@FromJson
@Nullable
Stage fromJson(JsonReader jsonReader, JsonAdapter<Stage> delegate) throws IOException {
String value = jsonReader.nextString();
Stage stage;
if (value.startsWith("in-progress")) {
stage = Stage.IN_PROGRESS;
} else {
stage = delegate.fromJsonValue(value);
}
return stage;
}
}
}
|
StageAdapter
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/TaskManagerLocation.java
|
{
"start": 16927,
"end": 17005
}
|
enum ____ {
RETRIEVE_HOST_NAME,
USE_IP_ONLY
}
}
|
ResolutionMode
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
|
{
"start": 3219,
"end": 29629
}
|
class ____ implements Serializable {
public static final int NO_VERSION_INDX = -66;
private final SessionFactoryImplementor sessionFactory;
private final String name;
private final String rootName;
private final EntityType entityType;
private final int subclassId;
private final IdentifierProperty identifierAttribute;
private final boolean versioned;
private final int propertySpan;
private final int versionPropertyIndex;
private final NonIdentifierAttribute[] properties;
// temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private final String[] propertyNames;
private final Type[] propertyTypes;
private final @Nullable Type[] dirtyCheckablePropertyTypes;
private final boolean[] propertyLaziness;
private final boolean[] propertyUpdateability;
private final boolean[] nonlazyPropertyUpdateability;
private final boolean[] propertyCheckability;
private final boolean[] propertyInsertability;
private final boolean[] propertyNullability;
private final boolean[] propertyVersionability;
private final OnDeleteAction[] propertyOnDeleteActions;
private final CascadeStyle[] cascadeStyles;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// value generations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private final boolean hasPreInsertGeneratedValues;
private final boolean hasPreUpdateGeneratedValues;
private final boolean hasInsertGeneratedValues;
private final boolean hasUpdateGeneratedValues;
private final Generator[] generators;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private final Map<String, Integer> propertyIndexes = new HashMap<>();
private final boolean hasCollections;
private final boolean hasOwnedCollections;
private final BitSet mutablePropertiesIndexes;
private final boolean hasLazyProperties;
private final boolean hasNonIdentifierPropertyNamedId;
private final int[] naturalIdPropertyNumbers;
private final boolean hasImmutableNaturalId;
private final boolean hasCacheableNaturalId;
private boolean lazy; //not final because proxy factory creation can fail
private final boolean hasCascades;
private final boolean hasToOnes;
private final boolean hasCascadePersist;
private final boolean hasCascadeDelete;
private final boolean mutable;
private final boolean isAbstract;
private final boolean selectBeforeUpdate;
private final boolean dynamicUpdate;
private final boolean dynamicInsert;
private final OptimisticLockStyle optimisticLockStyle;
private final boolean polymorphic;
private final String superclass; // superclass entity-name
private final boolean inherited;
private final boolean hasSubclasses;
private final Set<String> subclassEntityNames;
// private final Map<Class<?>,String> entityNameByInheritanceClassMap;
private final BeforeExecutionGenerator versionGenerator;
private final BytecodeEnhancementMetadata bytecodeEnhancementMetadata;
public EntityMetamodel(
PersistentClass persistentClass,
RuntimeModelCreationContext creationContext) {
this( persistentClass, creationContext,
rootName -> creationContext.getOrCreateIdGenerator( rootName, persistentClass ) );
}
/*
* Used by Hibernate Reactive to adapt the id generators
*/
public EntityMetamodel(
PersistentClass persistentClass,
RuntimeModelCreationContext creationContext,
Function<String, Generator> generatorSupplier) {
sessionFactory = creationContext.getSessionFactory();
// Improves performance of EntityKey#equals by avoiding content check in String#equals
name = persistentClass.getEntityName().intern();
rootName = persistentClass.getRootClass().getEntityName().intern();
// Make sure the hashCodes are cached
//noinspection ResultOfMethodCallIgnored
name.hashCode();
//noinspection ResultOfMethodCallIgnored
rootName.hashCode();
entityType = new ManyToOneType( name, creationContext.getTypeConfiguration() );
subclassId = persistentClass.getSubclassId();
identifierAttribute =
buildIdentifierAttribute(
persistentClass,
generatorSupplier.apply( rootName )
);
versioned = persistentClass.isVersioned();
final boolean collectionsInDefaultFetchGroup =
creationContext.getSessionFactoryOptions()
.isCollectionsInDefaultFetchGroupEnabled();
bytecodeEnhancementMetadata =
bytecodeEnhancementMetadata(
persistentClass,
identifierAttribute,
creationContext,
collectionsInDefaultFetchGroup
);
boolean hasLazy = false;
propertySpan = persistentClass.getPropertyClosureSpan();
properties = new NonIdentifierAttribute[propertySpan];
List<Integer> naturalIdNumbers = new ArrayList<>();
// temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
propertyNames = new String[propertySpan];
propertyTypes = new Type[propertySpan];
dirtyCheckablePropertyTypes = new Type[propertySpan];
propertyUpdateability = new boolean[propertySpan];
propertyInsertability = new boolean[propertySpan];
nonlazyPropertyUpdateability = new boolean[propertySpan];
propertyCheckability = new boolean[propertySpan];
propertyNullability = new boolean[propertySpan];
propertyVersionability = new boolean[propertySpan];
propertyLaziness = new boolean[propertySpan];
propertyOnDeleteActions = new OnDeleteAction[propertySpan];
cascadeStyles = new CascadeStyle[propertySpan];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// generated value strategies ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generators = new Generator[propertySpan];
boolean foundPreInsertGeneratedValues = false;
boolean foundPreUpdateGeneratedValues = false;
boolean foundPostInsertGeneratedValues = false;
boolean foundPostUpdateGeneratedValues = false;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final boolean supportsCascadeDelete = creationContext.getDialect().supportsCascadeDelete();
int tempVersionProperty = NO_VERSION_INDX;
boolean foundCascade = false;
boolean foundToOne = false;
boolean foundCascadePersist = false;
boolean foundCascadeDelete = false;
boolean foundCollection = false;
boolean foundOwnedCollection = false;
BitSet mutableIndexes = new BitSet();
boolean foundNonIdentifierPropertyNamedId = false;
boolean foundUpdateableNaturalIdProperty = false;
BeforeExecutionGenerator tempVersionGenerator = null;
final var props = persistentClass.getPropertyClosure();
for ( int i=0; i<props.size(); i++ ) {
final var property = props.get(i);
if ( property == persistentClass.getVersion() ) {
tempVersionProperty = i;
}
final var attribute = buildAttribute( persistentClass, creationContext, property, i );
properties[i] = attribute;
if ( property.isNaturalIdentifier() ) {
verifyNaturalIdProperty( property );
naturalIdNumbers.add( i );
if ( property.isUpdatable() ) {
foundUpdateableNaturalIdProperty = true;
}
}
if ( "id".equals( property.getName() ) ) {
foundNonIdentifierPropertyNamedId = true;
}
// temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final boolean lazy =
isLazy( creationContext, property, collectionsInDefaultFetchGroup, bytecodeEnhancementMetadata );
if ( lazy ) {
hasLazy = true;
}
propertyLaziness[i] = lazy;
propertyNames[i] = attribute.getName();
final var propertyType = attribute.getType();
propertyTypes[i] = propertyType;
if ( attribute.isDirtyCheckable() && !( propertyType instanceof OneToOneType ) ) {
dirtyCheckablePropertyTypes[i] = propertyType;
}
propertyNullability[i] = attribute.isNullable();
propertyUpdateability[i] = attribute.isUpdateable();
propertyInsertability[i] = attribute.isInsertable();
propertyVersionability[i] = attribute.isVersionable();
nonlazyPropertyUpdateability[i] = attribute.isUpdateable() && !lazy;
propertyCheckability[i] = propertyUpdateability[i]
|| propertyType instanceof AssociationType associationType
&& associationType.isAlwaysDirtyChecked();
propertyOnDeleteActions[i] = supportsCascadeDelete ? attribute.getOnDeleteAction() : null;
cascadeStyles[i] = attribute.getCascadeStyle();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// generated value strategies ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final var generator = buildGenerator( name, property, creationContext );
if ( generator != null ) {
final boolean generatedOnExecution = generator.generatedOnExecution();
if ( i == tempVersionProperty && !generatedOnExecution ) {
// when we have an in-memory generator for the version, we
// want to plug it in to the older infrastructure specific
// to version generation, instead of treating it like a
// plain "value" generator for a regular attribute
tempVersionGenerator = (BeforeExecutionGenerator) generator;
}
else {
generators[i] = generator;
final boolean allowMutation = generator.allowMutation();
if ( !allowMutation ) {
propertyCheckability[i] = false;
}
if ( generator.generatesOnInsert() ) {
if ( generatedOnExecution ) {
propertyInsertability[i] = writePropertyValue( (OnExecutionGenerator) generator );
}
foundPostInsertGeneratedValues = foundPostInsertGeneratedValues
|| generatedOnExecution;
foundPreInsertGeneratedValues = foundPreInsertGeneratedValues
|| !generatedOnExecution
|| generator instanceof BeforeExecutionGenerator;
}
else if ( !allowMutation ) {
propertyInsertability[i] = false;
}
if ( generator.generatesOnUpdate() ) {
if ( generatedOnExecution ) {
propertyUpdateability[i] = writePropertyValue( (OnExecutionGenerator) generator );
}
foundPostUpdateGeneratedValues = foundPostInsertGeneratedValues
|| generatedOnExecution;
foundPreUpdateGeneratedValues = foundPreInsertGeneratedValues
|| !generatedOnExecution
|| generator instanceof BeforeExecutionGenerator;
}
else if ( !allowMutation ) {
propertyUpdateability[i] = false;
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ( attribute.isLazy() ) {
hasLazy = true;
}
if ( cascadeStyles[i] != CascadeStyles.NONE ) {
foundCascade = true;
}
if ( cascadeStyles[i].doCascade(CascadingActions.PERSIST)
|| cascadeStyles[i].doCascade(CascadingActions.PERSIST_ON_FLUSH) ) {
foundCascadePersist = true;
}
if ( cascadeStyles[i].doCascade(CascadingActions.REMOVE) ) {
foundCascadeDelete = true;
}
if ( indicatesToOne( propertyType ) ) {
foundToOne = true;
}
if ( indicatesCollection( propertyType ) ) {
foundCollection = true;
}
if ( indicatesOwnedCollection( propertyType, creationContext.getMetadata() ) ) {
foundOwnedCollection = true;
}
// Component types are dirty-tracked as well, so they
// are not exactly mutable for the "maybeDirty" check
if ( propertyType.isMutable()
&& propertyCheckability[i]
&& !( propertyType instanceof ComponentType ) ) {
mutableIndexes.set( i );
}
mapPropertyToIndex( property, i );
}
if ( naturalIdNumbers.isEmpty() ) {
naturalIdPropertyNumbers = null;
hasImmutableNaturalId = false;
hasCacheableNaturalId = false;
}
else {
naturalIdPropertyNumbers = toIntArray( naturalIdNumbers );
hasImmutableNaturalId = !foundUpdateableNaturalIdProperty;
hasCacheableNaturalId = persistentClass.getNaturalIdCacheRegionName() != null;
}
hasPreInsertGeneratedValues = foundPreInsertGeneratedValues;
hasPreUpdateGeneratedValues = foundPreUpdateGeneratedValues;
hasInsertGeneratedValues = foundPostInsertGeneratedValues;
hasUpdateGeneratedValues = foundPostUpdateGeneratedValues;
versionGenerator = tempVersionGenerator;
hasCascades = foundCascade;
hasToOnes = foundToOne;
hasCascadePersist = foundCascadePersist;
hasCascadeDelete = foundCascadeDelete;
hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId;
versionPropertyIndex = tempVersionProperty;
hasLazyProperties = hasLazy;
if ( hasLazyProperties ) {
CORE_LOGGER.lazyPropertyFetchingAvailable( name );
}
lazy = isLazy( persistentClass, bytecodeEnhancementMetadata );
mutable = persistentClass.isMutable();
isAbstract = isAbstract( persistentClass );
selectBeforeUpdate = persistentClass.hasSelectBeforeUpdate();
dynamicUpdate = persistentClass.useDynamicUpdate() || hasMultipleFetchGroups( bytecodeEnhancementMetadata );
dynamicInsert = persistentClass.useDynamicInsert();
polymorphic = persistentClass.isPolymorphic();
inherited = persistentClass.isInherited();
superclass = inherited ? persistentClass.getSuperclass().getEntityName() : null;
hasSubclasses = persistentClass.hasSubclasses();
optimisticLockStyle = persistentClass.getOptimisticLockStyle();
//TODO: move these checks into the Binders
if ( optimisticLockStyle.isAllOrDirty() ) {
if ( !dynamicUpdate ) {
throw new MappingException( "Entity '" + name
+ "' has 'OptimisticLockType." + optimisticLockStyle
+ "' but is not annotated '@DynamicUpdate'" );
}
if ( versionPropertyIndex != NO_VERSION_INDX ) {
throw new MappingException( "Entity '" + name
+ "' has 'OptimisticLockType." + optimisticLockStyle
+ "' but declares a '@Version' field" );
}
}
hasCollections = foundCollection;
hasOwnedCollections = foundOwnedCollection;
mutablePropertiesIndexes = mutableIndexes;
subclassEntityNames = collectSubclassEntityNames( persistentClass );
// HashMap<Class<?>, String> entityNameByInheritanceClassMapLocal = new HashMap<>();
// if ( persistentClass.hasPojoRepresentation() ) {
// entityNameByInheritanceClassMapLocal.put( persistentClass.getMappedClass(), persistentClass.getEntityName() );
// for ( Subclass subclass : persistentClass.getSubclasses() ) {
// entityNameByInheritanceClassMapLocal.put( subclass.getMappedClass(), subclass.getEntityName() );
// }
// }
// entityNameByInheritanceClassMap = toSmallMap( entityNameByInheritanceClassMapLocal );
}
private Set<String> collectSubclassEntityNames(PersistentClass persistentClass) {
final Set<String> entityNames = new LinkedHashSet<>(); // Need deterministic ordering
entityNames.add( name );
for ( var subclass : persistentClass.getSubclasses() ) {
entityNames.add( subclass.getEntityName() );
}
return toSmallSet( entityNames );
}
private static boolean isAbstract(PersistentClass persistentClass) {
final Boolean isAbstract = persistentClass.isAbstract();
if ( isAbstract == null ) {
// legacy behavior (with no abstract attribute specified)
return persistentClass.hasPojoRepresentation()
&& isAbstractClass( persistentClass.getMappedClass() );
}
else {
if ( !isAbstract
&& persistentClass.hasPojoRepresentation()
&& isAbstractClass( persistentClass.getMappedClass() ) ) {
CORE_LOGGER.entityMappedAsNonAbstract( persistentClass.getEntityName() );
}
return isAbstract;
}
}
//TODO: move this down to AbstractEntityPersister
private NonIdentifierAttribute buildAttribute(
PersistentClass persistentClass,
RuntimeModelCreationContext creationContext,
Property property,
int index) {
if ( property == persistentClass.getVersion() ) {
return buildVersionProperty(
(EntityPersister) this,
sessionFactory,
index,
property,
bytecodeEnhancementMetadata.isEnhancedForLazyLoading()
);
}
else {
return buildEntityBasedAttribute(
(EntityPersister) this,
sessionFactory,
index,
property,
bytecodeEnhancementMetadata.isEnhancedForLazyLoading(),
creationContext
);
}
}
private boolean isLazy(PersistentClass persistentClass, BytecodeEnhancementMetadata enhancementMetadata) {
return persistentClass.isLazy()
// TODO: this disables laziness even in non-pojo entity modes:
&& ( !persistentClass.hasPojoRepresentation() || !isFinalClass( persistentClass.getProxyInterface() ) )
|| enhancementMetadata.isEnhancedForLazyLoading();
}
private boolean hasMultipleFetchGroups(BytecodeEnhancementMetadata enhancementMetadata) {
return enhancementMetadata.isEnhancedForLazyLoading()
&& enhancementMetadata.getLazyAttributesMetadata().getFetchGroupNames().size() > 1;
}
private static boolean isLazy(
RuntimeModelCreationContext creationContext,
Property property,
boolean collectionsInDefaultFetchGroupEnabled,
BytecodeEnhancementMetadata enhancementMetadata) {
return !includeInBaseFetchGroup(
property,
enhancementMetadata.isEnhancedForLazyLoading(),
entityName -> {
final var entityBinding =
creationContext.getMetadata().getEntityBinding( entityName );
assert entityBinding != null;
return entityBinding.hasSubclasses();
},
collectionsInDefaultFetchGroupEnabled
);
}
private BytecodeEnhancementMetadata bytecodeEnhancementMetadata(
PersistentClass persistentClass,
IdentifierProperty identifierAttribute,
RuntimeModelCreationContext creationContext,
boolean collectionsInDefaultFetchGroupEnabled) {
if ( persistentClass.hasPojoRepresentation() ) {
final var identifierMapperComponent = persistentClass.getIdentifierMapper();
final CompositeType nonAggregatedCidMapper;
final Set<String> idAttributeNames;
if ( identifierMapperComponent != null ) {
nonAggregatedCidMapper = identifierMapperComponent.getType();
final HashSet<String> propertyNames = new HashSet<>();
for ( var property : identifierMapperComponent.getProperties() ) {
propertyNames.add( property.getName() );
}
idAttributeNames = toSmallSet( unmodifiableSet( propertyNames ) );
}
else {
nonAggregatedCidMapper = null;
idAttributeNames = singleton( identifierAttribute.getName() );
}
return getBytecodeEnhancementMetadataPojo(
persistentClass,
creationContext,
idAttributeNames,
nonAggregatedCidMapper,
collectionsInDefaultFetchGroupEnabled
);
}
else {
return new BytecodeEnhancementMetadataNonPojoImpl( persistentClass.getEntityName() );
}
}
/*
* Used by Hibernate Reactive
*/
protected BytecodeEnhancementMetadata getBytecodeEnhancementMetadataPojo(PersistentClass persistentClass, RuntimeModelCreationContext creationContext, Set<String> idAttributeNames, CompositeType nonAggregatedCidMapper, boolean collectionsInDefaultFetchGroupEnabled) {
return BytecodeEnhancementMetadataPojoImpl.from(
persistentClass,
idAttributeNames,
nonAggregatedCidMapper,
collectionsInDefaultFetchGroupEnabled,
creationContext.getMetadata()
);
}
private static boolean writePropertyValue(OnExecutionGenerator generator) {
final boolean writePropertyValue = generator.writePropertyValue();
// TODO: move this validation somewhere else!
// if ( !writePropertyValue && generator instanceof BeforeExecutionGenerator ) {
// throw new HibernateException( "BeforeExecutionGenerator returned false from OnExecutionGenerator.writePropertyValue()" );
// }
return writePropertyValue;
}
private void verifyNaturalIdProperty(Property property) {
final var value = property.getValue();
if ( value instanceof ManyToOne toOne ) {
if ( toOne.getNotFoundAction() == NotFoundAction.IGNORE ) {
throw new MappingException( "Association '" + propertyName( property )
+ "' marked as '@NaturalId' is also annotated '@NotFound(IGNORE)'"
);
}
}
else if ( value instanceof Component component ) {
for ( var componentProperty : component.getProperties() ) {
verifyNaturalIdProperty( componentProperty );
}
}
}
private String propertyName(Property property) {
return getName() + "." + property.getName();
}
private static Generator buildGenerator(
final String entityName,
final Property mappingProperty,
final RuntimeModelCreationContext context) {
final var generatorCreator = mappingProperty.getValueGeneratorCreator();
if ( generatorCreator != null ) {
final var generator = mappingProperty.createGenerator( context );
if ( generator.generatesSometimes() ) {
return generator;
}
}
if ( mappingProperty.getValue() instanceof Component component ) {
final var builder =
new CompositeGeneratorBuilder( entityName, mappingProperty, context.getDialect() );
for ( var property : component.getProperties() ) {
builder.add( property.createGenerator( context ) );
}
return builder.build();
}
return null;
}
public Generator[] getGenerators() {
return generators;
}
public BeforeExecutionGenerator getVersionGenerator() {
return versionGenerator;
}
private void mapPropertyToIndex(Property property, int i) {
propertyIndexes.put( property.getName(), i );
if ( property.getValue() instanceof Component composite ) {
for ( var subproperty : composite.getProperties() ) {
propertyIndexes.put(
property.getName() + '.' + subproperty.getName(),
i
);
}
}
}
/**
* @return {@code true} if one of the properties belonging to the natural id
* is generated during the execution of an {@code insert} statement
*/
public boolean isNaturalIdentifierInsertGenerated() {
if ( naturalIdPropertyNumbers.length == 0 ) {
throw new IllegalStateException( "Entity '" + name + "' does not have a natural id" );
}
for ( int naturalIdPropertyNumber : naturalIdPropertyNumbers ) {
final var strategy = generators[naturalIdPropertyNumber];
if ( strategy != null
&& strategy.generatesOnInsert()
&& strategy.generatedOnExecution() ) {
return true;
}
}
return false;
}
public int[] getNaturalIdentifierProperties() {
return naturalIdPropertyNumbers;
}
public boolean hasNaturalIdentifier() {
return naturalIdPropertyNumbers!=null;
}
public boolean isNaturalIdentifierCached() {
return hasNaturalIdentifier() && hasCacheableNaturalId;
}
public boolean hasImmutableNaturalId() {
return hasImmutableNaturalId;
}
public Set<String> getSubclassEntityNames() {
return subclassEntityNames;
}
private static boolean indicatesToOne(Type type) {
if ( type.isEntityType() ) {
return true;
}
else if ( type instanceof CompositeType compositeType ) {
for ( var subtype : compositeType.getSubtypes() ) {
if ( indicatesToOne( subtype ) ) {
return true;
}
}
}
return false;
}
private static boolean indicatesCollection(Type type) {
if ( type instanceof CollectionType ) {
return true;
}
else if ( type instanceof CompositeType compositeType ) {
for ( var subtype : compositeType.getSubtypes() ) {
if ( indicatesCollection( subtype ) ) {
return true;
}
}
}
return false;
}
private static boolean indicatesOwnedCollection(Type type, MetadataImplementor metadata) {
if ( type instanceof CollectionType collectionType ) {
return !metadata.getCollectionBinding( collectionType.getRole() ).isInverse();
}
else if ( type instanceof CompositeType compositeType ) {
for ( var subtype : compositeType.getSubtypes() ) {
if ( indicatesOwnedCollection( subtype, metadata ) ) {
return true;
}
}
return false;
}
else {
return false;
}
}
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory;
}
public String getName() {
return name;
}
public String getRootName() {
return rootName;
}
public int getSubclassId() {
return subclassId;
}
public EntityType getEntityType() {
return entityType;
}
public IdentifierProperty getIdentifierProperty() {
return identifierAttribute;
}
public int getPropertySpan() {
return propertySpan;
}
public int getVersionPropertyIndex() {
return versionPropertyIndex;
}
public VersionProperty getVersionProperty() {
return NO_VERSION_INDX == versionPropertyIndex
? null
: (VersionProperty) properties[versionPropertyIndex];
}
public NonIdentifierAttribute[] getProperties() {
return properties;
}
public int getPropertyIndex(String propertyName) {
final Integer index = getPropertyIndexOrNull( propertyName );
if ( index == null ) {
throw new HibernateException( "Unable to resolve property: " + propertyName );
}
return index;
}
public Integer getPropertyIndexOrNull(String propertyName) {
return propertyIndexes.get( propertyName );
}
public boolean hasCollections() {
return hasCollections;
}
public boolean hasOwnedCollections() {
return hasOwnedCollections;
}
public boolean hasMutableProperties() {
return !mutablePropertiesIndexes.isEmpty();
}
public BitSet getMutablePropertiesIndexes() {
return mutablePropertiesIndexes;
}
public boolean hasNonIdentifierPropertyNamedId() {
return hasNonIdentifierPropertyNamedId;
}
public boolean hasLazyProperties() {
return hasLazyProperties;
}
public boolean hasCascades() {
return hasCascades;
}
public boolean hasToOnes() {
return hasToOnes;
}
public boolean hasCascadeDelete() {
return hasCascadeDelete;
}
public boolean hasCascadePersist() {
return hasCascadePersist;
}
public boolean isMutable() {
return mutable;
}
public boolean isSelectBeforeUpdate() {
return selectBeforeUpdate;
}
public boolean isDynamicUpdate() {
return dynamicUpdate;
}
public boolean isDynamicInsert() {
return dynamicInsert;
}
public OptimisticLockStyle getOptimisticLockStyle() {
return optimisticLockStyle;
}
public boolean isPolymorphic() {
return polymorphic;
}
public String getSuperclass() {
return superclass;
}
/**
* @deprecated No longer supported
*/
@Deprecated
public boolean isExplicitPolymorphism() {
return false;
}
public boolean isInherited() {
return inherited;
}
public boolean hasSubclasses() {
return hasSubclasses;
}
public boolean isLazy() {
return lazy;
}
public void setLazy(boolean lazy) {
this.lazy = lazy;
}
public boolean isVersioned() {
return versioned;
}
public boolean isAbstract() {
return isAbstract;
}
// /**
// * Return the entity-name mapped to the given
|
EntityMetamodel
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TestExecutionListenersNestedTests.java
|
{
"start": 2687,
"end": 2964
}
|
class ____ {
@Test
void test() {
assertThat(listeners).containsExactly(FOO);
}
}
@Nested
@TestExecutionListeners(BarTestExecutionListener.class)
@DisabledInAotMode("Does not load an ApplicationContext and thus not supported for AOT processing")
|
InheritedConfigTests
|
java
|
apache__camel
|
components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/ProviderWithoutServletTest.java
|
{
"start": 1439,
"end": 2292
}
|
class ____ extends AbstractProviderServletTest.MockSecurityProvider {
@Override
public boolean requireServletContext() {
return false;
}
@Override
void assertServletContext(ServletRequestContext servletRequestContext) {
assertNull(servletRequestContext);
}
}
@BeforeAll
public static void initProvider() throws Exception {
createSecurtyProviderConfigurationFile(MockSecurityProvider.class);
}
@Test
public void test() throws Exception {
getMockEndpoint("mock:input").expectedHeaderReceived(Exchange.HTTP_METHOD, "GET");
String out = template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class);
assertEquals("user", out);
MockEndpoint.assertIsSatisfied(context);
}
}
|
MockSecurityProvider
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-translate/src/generated/java/org/apache/camel/component/aws2/translate/Translate2EndpointUriFactory.java
|
{
"start": 524,
"end": 3089
}
|
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":label";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(22);
props.add("accessKey");
props.add("autodetectSourceLanguage");
props.add("label");
props.add("lazyStartProducer");
props.add("operation");
props.add("overrideEndpoint");
props.add("pojoRequest");
props.add("profileCredentialsName");
props.add("proxyHost");
props.add("proxyPort");
props.add("proxyProtocol");
props.add("region");
props.add("secretKey");
props.add("sessionToken");
props.add("sourceLanguage");
props.add("targetLanguage");
props.add("translateClient");
props.add("trustAllCertificates");
props.add("uriEndpointOverride");
props.add("useDefaultCredentialsProvider");
props.add("useProfileCredentialsProvider");
props.add("useSessionCredentials");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(3);
secretProps.add("accessKey");
secretProps.add("secretKey");
secretProps.add("sessionToken");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "aws2-translate".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "label", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
|
Translate2EndpointUriFactory
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/LargerThanDefaultFormAttributeMultipartFormInputTest.java
|
{
"start": 2437,
"end": 2680
}
|
class ____ {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String hello(@BeanParam Data data) {
return data.getText();
}
}
public static
|
Resource
|
java
|
quarkusio__quarkus
|
devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/ProjectDescriptor.java
|
{
"start": 156,
"end": 651
}
|
interface ____ {
/**
* Project workspace module
*
* @return workspace module
*/
WorkspaceModule.Mutable getWorkspaceModule();
/**
* Workspace module for a specific module ID (in a multi module project)
*
* @param moduleId module ID
* @return workspace module for a given module ID or null, if the requested module info is not available
*/
WorkspaceModule.Mutable getWorkspaceModuleOrNull(WorkspaceModuleId moduleId);
}
|
ProjectDescriptor
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/errors/TelemetryTooLargeException.java
|
{
"start": 941,
"end": 1086
}
|
class ____ extends ApiException {
public TelemetryTooLargeException(String message) {
super(message);
}
}
|
TelemetryTooLargeException
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ActiveMQEndpointBuilderFactory.java
|
{
"start": 24032,
"end": 25054
}
|
class ____ is
* good enough as subscription name). Only makes sense when listening to
* a topic (pub-sub domain), therefore this method switches the
* pubSubDomain flag as well.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param subscriptionDurable the value to set
* @return the dsl builder
*/
default ActiveMQEndpointConsumerBuilder subscriptionDurable(boolean subscriptionDurable) {
doSetProperty("subscriptionDurable", subscriptionDurable);
return this;
}
/**
* Set whether to make the subscription durable. The durable
* subscription name to be used can be specified through the
* subscriptionName property. Default is false. Set this to true to
* register a durable subscription, typically in combination with a
* subscriptionName value (unless your message listener
|
name
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/keygen/CountryMapper.java
|
{
"start": 961,
"end": 5486
}
|
interface ____ {
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert({ "insert into country (countryname,countrycode) values (#{countryname},#{countrycode})" })
int insertBean(Country country);
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert({ "insert into country (countryname,countrycode) values (#{country.countryname},#{country.countrycode})" })
int insertNamedBean(@Param("country") Country country);
@Options(useGeneratedKeys = true, keyProperty = "country.id")
@Insert({ "insert into country (countryname,countrycode) values (#{country.countryname},#{country.countrycode})" })
int insertNamedBean_keyPropertyWithParamName(@Param("country") Country country);
int insertList(List<Country> countries);
int insertNamedList(@Param("countries") List<Country> countries);
int insertSet(Set<Country> countries);
int insertNamedSet(@Param("countries") Set<Country> countries);
int insertArray(Country[] countries);
int insertNamedArray(@Param("countries") Country[] countries);
@Options(useGeneratedKeys = true, keyProperty = "country.id")
@Insert({ "insert into country (countryname,countrycode) values (#{country.countryname},#{country.countrycode})" })
int insertMultiParams(@Param("country") Country country, @Param("someId") Integer someId);
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert({ "insert into country (countryname,countrycode) values (#{country.countryname},#{country.countrycode})" })
int insertMultiParams_keyPropertyWithoutParamName(@Param("country") Country country, @Param("someId") Integer someId);
@Options(useGeneratedKeys = true, keyProperty = "bogus.id")
@Insert({ "insert into country (countryname,countrycode) values (#{country.countryname},#{country.countrycode})" })
int insertMultiParams_keyPropertyWithWrongParamName(@Param("country") Country country,
@Param("someId") Integer someId);
int insertListAndSomeId(@Param("list") List<Country> countries, @Param("someId") Integer someId);
int insertSetAndSomeId(@Param("collection") Set<Country> countries, @Param("someId") Integer someId);
int insertArrayAndSomeId(@Param("array") Country[] countries, @Param("someId") Integer someId);
int insertList_MultiParams(@Param("countries") List<Country> countries, @Param("someId") Integer someId);
int insertSet_MultiParams(@Param("countries") Set<Country> countries, @Param("someId") Integer someId);
int insertArray_MultiParams(@Param("countries") Country[] countries, @Param("someId") Integer someId);
int insertUndefineKeyProperty(Country country);
@Options(useGeneratedKeys = true, keyProperty = "id,code")
@Insert({ "insert into planet (name) values (#{name})" })
int insertPlanet(Planet planet);
int insertPlanets(List<Planet> planets);
@Options(useGeneratedKeys = true, keyProperty = "planet.id,planet.code")
@Insert({ "insert into planet (name) values (#{planet.name})" })
int insertPlanet_MultiParams(@Param("planet") Planet planet, @Param("someId") Integer someId);
int insertPlanets_MultiParams(@Param("planets") List<Planet> planets, @Param("someId") Integer someId);
@Options(useGeneratedKeys = true, keyProperty = "planet.id,map.code")
@Insert({ "insert into planet (name) values (#{planet.name})" })
int insertAssignKeysToTwoParams(@Param("planet") Planet planet, @Param("map") Map<String, Object> map);
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert({ "insert into country (countryname,countrycode) values ('a','A'), ('b', 'B')" })
int tooManyGeneratedKeys(Country country);
@Options(useGeneratedKeys = true, keyProperty = "country.id")
@Insert({ "insert into country (countryname,countrycode) values ('a','A'), ('b', 'B')" })
int tooManyGeneratedKeysParamMap(@Param("country") Country country, @Param("someId") Integer someId);
int insertWeirdCountries(List<NpeCountry> list);
// If the only parameter has a name 'param2', keyProperty must include the prefix 'param2.'.
@Options(useGeneratedKeys = true, keyProperty = ParamNameResolver.GENERIC_NAME_PREFIX + "2.id")
@Insert({ "insert into country (countryname,countrycode) values (#{param2.countryname},#{param2.countrycode})" })
int singleParamWithATrickyName(@Param(ParamNameResolver.GENERIC_NAME_PREFIX + "2") Country country);
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert({ "insert into country (countryname,countrycode) values (#{countryname},#{countrycode})" })
int insertMap(Map<String, Object> map);
}
|
CountryMapper
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/rawlocal/TestRawlocalContractAppend.java
|
{
"start": 1138,
"end": 1628
}
|
class ____ extends AbstractContractAppendTest {
@Override
protected AbstractFSContract createContract(Configuration conf) {
return new RawlocalFSContract(conf);
}
@Override
public void testRenameFileBeingAppended() throws Throwable {
// Renaming a file while its handle is open is not supported on Windows.
// Thus, this test should be skipped on Windows.
assumeThat(Path.WINDOWS).isFalse();
super.testRenameFileBeingAppended();
}
}
|
TestRawlocalContractAppend
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/string/RTrimEvaluator.java
|
{
"start": 1132,
"end": 4022
}
|
class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(RTrimEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator val;
private final DriverContext driverContext;
private Warnings warnings;
public RTrimEvaluator(Source source, EvalOperator.ExpressionEvaluator val,
DriverContext driverContext) {
this.source = source;
this.val = val;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (BytesRefBlock valBlock = (BytesRefBlock) val.eval(page)) {
BytesRefVector valVector = valBlock.asVector();
if (valVector == null) {
return eval(page.getPositionCount(), valBlock);
}
return eval(page.getPositionCount(), valVector).asBlock();
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += val.baseRamBytesUsed();
return baseRamBytesUsed;
}
public BytesRefBlock eval(int positionCount, BytesRefBlock valBlock) {
try(BytesRefBlock.Builder result = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) {
BytesRef valScratch = new BytesRef();
position: for (int p = 0; p < positionCount; p++) {
switch (valBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
BytesRef val = valBlock.getBytesRef(valBlock.getFirstValueIndex(p), valScratch);
result.appendBytesRef(RTrim.process(val));
}
return result.build();
}
}
public BytesRefVector eval(int positionCount, BytesRefVector valVector) {
try(BytesRefVector.Builder result = driverContext.blockFactory().newBytesRefVectorBuilder(positionCount)) {
BytesRef valScratch = new BytesRef();
position: for (int p = 0; p < positionCount; p++) {
BytesRef val = valVector.getBytesRef(p, valScratch);
result.appendBytesRef(RTrim.process(val));
}
return result.build();
}
}
@Override
public String toString() {
return "RTrimEvaluator[" + "val=" + val + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(val);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static
|
RTrimEvaluator
|
java
|
netty__netty
|
testsuite-jpms/src/test/java/io/netty/testsuite_jpms/test/OCSPTest.java
|
{
"start": 1751,
"end": 4373
}
|
class ____ {
@Test
public void testSimpleQueryTest() throws Exception {
final AtomicBoolean ocspStatus = new AtomicBoolean();
EventLoopGroup eventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
try {
final CountDownLatch latch = new CountDownLatch(1);
final SslContext sslContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
Bootstrap bootstrap = new Bootstrap()
.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslContext.newHandler(ch.alloc(), "netty.io", 443));
pipeline.addLast(new OcspServerCertificateValidator(false));
pipeline.addLast(new SimpleChannelInboundHandler<>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
// NOOP
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof OcspValidationEvent) {
OcspValidationEvent event = (OcspValidationEvent) evt;
ocspStatus.set(event.response().status() == OcspResponse.Status.VALID);
ctx.channel().close();
latch.countDown();
}
}
});
}
});
ChannelFuture channelFuture = bootstrap.connect("netty.io", 443);
channelFuture.sync();
// Wait for maximum of 1 minute for Ocsp validation to happen
latch.await(1, TimeUnit.MINUTES);
assertTrue(ocspStatus.get());
// Wait for Channel to be closed
channelFuture.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
|
OCSPTest
|
java
|
spring-projects__spring-security
|
web/src/test/java/org/springframework/security/web/header/writers/frameoptions/FrameOptionsHeaderWriterTests.java
|
{
"start": 1396,
"end": 4173
}
|
class ____ {
@Mock
private AllowFromStrategy strategy;
private MockHttpServletResponse response;
private MockHttpServletRequest request;
private XFrameOptionsHeaderWriter writer;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test
public void constructorNullMode() {
assertThatIllegalArgumentException().isThrownBy(() -> new XFrameOptionsHeaderWriter((XFrameOptionsMode) null));
}
@Test
public void constructorAllowFromNoAllowFromStrategy() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new XFrameOptionsHeaderWriter(XFrameOptionsMode.ALLOW_FROM));
}
@Test
public void constructorNullAllowFromStrategy() {
assertThatIllegalArgumentException().isThrownBy(() -> new XFrameOptionsHeaderWriter((AllowFromStrategy) null));
}
@Test
public void writeHeadersAllowFromReturnsNull() {
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).isEmpty();
}
@Test
public void writeHeadersAllowFrom() {
String allowFromValue = "https://example.com/";
given(this.strategy.getAllowFromValue(this.request)).willReturn(allowFromValue);
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
.isEqualTo("ALLOW-FROM " + allowFromValue);
}
@Test
public void writeHeadersDeny() {
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
}
@Test
public void writeHeadersSameOrigin() {
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("SAMEORIGIN");
}
@Test
public void writeHeadersTwiceLastWins() {
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
this.writer.writeHeaders(this.request, this.response);
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
}
}
|
FrameOptionsHeaderWriterTests
|
java
|
apache__camel
|
components/camel-huawei/camel-huaweicloud-functiongraph/src/test/java/org/apache/camel/TestConfiguration.java
|
{
"start": 1022,
"end": 2090
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(TestConfiguration.class.getName());
private static Map<String, String> propertyMap;
public TestConfiguration() {
initPropertyMap();
}
public void initPropertyMap() {
Properties properties = null;
if (propertyMap == null) {
propertyMap = new HashMap<>();
String fileName = "testconfiguration.properties";
try {
properties = TestSupport.loadExternalProperties(getClass().getClassLoader(), fileName);
for (String key : properties.stringPropertyNames()) {
propertyMap.put(key, properties.getProperty(key));
}
} catch (Exception e) {
LOG.error("Cannot load property file {}, reason {}", fileName, e.getMessage());
}
}
}
public String getProperty(String key) {
if (propertyMap == null) {
initPropertyMap();
}
return propertyMap.get(key);
}
}
|
TestConfiguration
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/InternalTimersSnapshotReaderWriters.java
|
{
"start": 10455,
"end": 11383
}
|
class ____<K, N>
extends AbstractInternalTimersSnapshotReader<K, N> {
public InternalTimersSnapshotReaderV2(ClassLoader userCodeClassLoader) {
super(userCodeClassLoader);
}
@SuppressWarnings("unchecked")
@Override
protected void restoreKeyAndNamespaceSerializers(
InternalTimersSnapshot<K, N> restoredTimersSnapshot, DataInputView in)
throws IOException {
restoredTimersSnapshot.setKeySerializerSnapshot(
TypeSerializerSnapshot.readVersionedSnapshot(in, userCodeClassLoader));
restoredTimersSnapshot.setNamespaceSerializerSnapshot(
TypeSerializerSnapshot.readVersionedSnapshot(in, userCodeClassLoader));
}
}
/** A {@link TypeSerializer} used to serialize/deserialize a {@link TimerHeapInternalTimer}. */
public static
|
InternalTimersSnapshotReaderV2
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringDoubleLoadBalancerMisconfigurationTest.java
|
{
"start": 1271,
"end": 2247
}
|
class ____ extends ContextTestSupport {
@Override
@BeforeEach
public void setUp() throws Exception {
try {
super.setUp();
fail("Should have thrown exception");
} catch (Exception e) {
FailedToCreateRouteException fe = assertIsInstanceOf(FailedToCreateRouteException.class, e);
IllegalArgumentException ie = assertIsInstanceOf(IllegalArgumentException.class, fe.getCause());
assertTrue(ie.getMessage().startsWith(
"Loadbalancer already configured to: RandomLoadBalancer. Cannot set it to: LoadBalanceType[RoundRobinLoadBalancer"));
}
}
@Test
public void testDummy() {
// noop
}
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/DoubleLoadBalancerMisconfigurationTest.xml");
}
}
|
SpringDoubleLoadBalancerMisconfigurationTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RpcWritable.java
|
{
"start": 3440,
"end": 4816
}
|
class ____ extends RpcWritable {
private Message message;
ProtobufWrapper(Message message) {
this.message = message;
}
Message getMessage() {
return message;
}
@Override
void writeTo(ResponseBuffer out) throws IOException {
int length = message.getSerializedSize();
length += CodedOutputStream.computeUInt32SizeNoTag(length);
out.ensureCapacity(length);
message.writeDelimitedTo(out);
}
@SuppressWarnings("unchecked")
@Override
<T> T readFrom(ByteBuffer bb) throws IOException {
// using the parser with a byte[]-backed coded input stream is the
// most efficient way to deserialize a protobuf. it has a direct
// path to the PB ctor that doesn't create multi-layered streams
// that internally buffer.
CodedInputStream cis = CodedInputStream.newInstance(
bb.array(), bb.position() + bb.arrayOffset(), bb.remaining());
try {
cis.pushLimit(cis.readRawVarint32());
message = message.getParserForType().parseFrom(cis);
cis.checkLastTagWas(0);
} finally {
// advance over the bytes read.
bb.position(bb.position() + cis.getTotalBytesRead());
}
return (T)message;
}
}
/**
* adapter to allow decoding of writables and protobufs from a byte buffer.
*/
public static
|
ProtobufWrapper
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/support/mapper/TemplateRoleNameTests.java
|
{
"start": 2576,
"end": 17287
}
|
class ____ extends ESTestCase {
public void testParseRoles() throws Exception {
final TemplateRoleName role1 = parse("""
{ "template": { "source": "_user_{{username}}" } }""");
assertThat(role1, Matchers.instanceOf(TemplateRoleName.class));
assertThat(role1.getTemplate().utf8ToString(), equalTo("""
{"source":"_user_{{username}}"}"""));
assertThat(role1.getFormat(), equalTo(Format.STRING));
final TemplateRoleName role2 = parse("""
{ "template": "{\\"source\\":\\"{{#tojson}}groups{{/tojson}}\\"}", "format":"json" }""");
assertThat(role2, Matchers.instanceOf(TemplateRoleName.class));
assertThat(role2.getTemplate().utf8ToString(), equalTo("""
{"source":"{{#tojson}}groups{{/tojson}}"}"""));
assertThat(role2.getFormat(), equalTo(Format.JSON));
}
public void testToXContent() throws Exception {
final String json = Strings.format("""
{"template":"{\\"source\\":\\"%s\\"}","format":"%s"}\
""", randomAlphaOfLengthBetween(8, 24), randomFrom(Format.values()).formatName());
assertThat(Strings.toString(parse(json)), equalTo(json));
}
public void testSerializeTemplate() throws Exception {
trySerialize(new TemplateRoleName(new BytesArray(randomAlphaOfLengthBetween(12, 60)), randomFrom(Format.values())));
}
public void testEqualsAndHashCode() throws Exception {
tryEquals(new TemplateRoleName(new BytesArray(randomAlphaOfLengthBetween(12, 60)), randomFrom(Format.values())));
}
public void testEvaluateRoles() throws Exception {
final ScriptService scriptService = new ScriptService(
Settings.EMPTY,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final ExpressionModel model = new ExpressionModel();
model.defineField("username", "hulk");
model.defineField("groups", Arrays.asList("avengers", "defenders", "panthenon"));
final TemplateRoleName plainString = new TemplateRoleName(new BytesArray("""
{ "source":"heroes" }"""), Format.STRING);
assertThat(plainString.getRoleNames(scriptService, model), contains("heroes"));
final TemplateRoleName user = new TemplateRoleName(new BytesArray("""
{ "source":"_user_{{username}}" }"""), Format.STRING);
assertThat(user.getRoleNames(scriptService, model), contains("_user_hulk"));
final TemplateRoleName groups = new TemplateRoleName(new BytesArray("""
{ "source":"{{#tojson}}groups{{/tojson}}" }"""), Format.JSON);
assertThat(groups.getRoleNames(scriptService, model), contains("avengers", "defenders", "panthenon"));
}
private TemplateRoleName parse(String json) throws IOException {
final XContentParser parser = XContentType.JSON.xContent().createParser(XContentParserConfiguration.EMPTY, json);
final TemplateRoleName role = TemplateRoleName.parse(parser);
assertThat(role, notNullValue());
return role;
}
public void trySerialize(TemplateRoleName original) throws Exception {
BytesStreamOutput output = new BytesStreamOutput();
original.writeTo(output);
final StreamInput rawInput = ByteBufferStreamInput.wrap(BytesReference.toBytes(output.bytes()));
final TemplateRoleName serialized = new TemplateRoleName(rawInput);
assertEquals(original, serialized);
}
public void tryEquals(TemplateRoleName original) {
final EqualsHashCodeTestUtils.CopyFunction<TemplateRoleName> copy = rmt -> new TemplateRoleName(rmt.getTemplate(), rmt.getFormat());
final EqualsHashCodeTestUtils.MutateFunction<TemplateRoleName> mutate = rmt -> {
if (randomBoolean()) {
return new TemplateRoleName(rmt.getTemplate(), randomValueOtherThan(rmt.getFormat(), () -> randomFrom(Format.values())));
} else {
final String templateStr = rmt.getTemplate().utf8ToString();
return new TemplateRoleName(
new BytesArray(templateStr.substring(randomIntBetween(1, templateStr.length() / 2))),
rmt.getFormat()
);
}
};
EqualsHashCodeTestUtils.checkEqualsAndHashCode(original, copy, mutate);
}
public void testValidate() {
final ScriptService scriptService = new ScriptService(
Settings.EMPTY,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final TemplateRoleName plainString = new TemplateRoleName(new BytesArray("""
{ "source":"heroes" }"""), Format.STRING);
plainString.validate(scriptService);
final TemplateRoleName user = new TemplateRoleName(new BytesArray("""
{ "source":"_user_{{username}}" }"""), Format.STRING);
user.validate(scriptService);
final TemplateRoleName groups = new TemplateRoleName(new BytesArray("""
{ "source":"{{#tojson}}groups{{/tojson}}" }"""), Format.JSON);
groups.validate(scriptService);
final TemplateRoleName notObject = new TemplateRoleName(new BytesArray("heroes"), Format.STRING);
expectThrows(IllegalArgumentException.class, () -> notObject.validate(scriptService));
final TemplateRoleName invalidField = new TemplateRoleName(new BytesArray("""
{ "foo":"heroes" }"""), Format.STRING);
expectThrows(IllegalArgumentException.class, () -> invalidField.validate(scriptService));
}
public void testValidateWillPassWithEmptyContext() {
final ScriptService scriptService = new ScriptService(
Settings.EMPTY,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final BytesReference template = new BytesArray("""
{ "source":"\
{{username}}/{{dn}}/{{realm}}/{{metadata}}\
{{#realm}}\
{{name}}/{{type}}\
{{/realm}}\
{{#toJson}}groups{{/toJson}}\
{{^groups}}{{.}}{{/groups}}\
{{#metadata}}\
{{#first}}\
<li><strong>{{name}}</strong></li>\
{{/first}}\
{{#link}}\
<li><a href=\\"{{url}}\\">{{name}}</a></li>\
{{/link}}\
{{#toJson}}subgroups{{/toJson}}\
{{something-else}}\
{{/metadata}}" }
""");
final TemplateRoleName templateRoleName = new TemplateRoleName(template, Format.STRING);
templateRoleName.validate(scriptService);
}
public void testValidateWillFailForSyntaxError() {
final ScriptService scriptService = new ScriptService(
Settings.EMPTY,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final BytesReference template = new BytesArray("""
{ "source":" {{#not-closed}} {{other-variable}} " }""");
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new TemplateRoleName(template, Format.STRING).validate(scriptService)
);
assertTrue(e.getCause() instanceof ScriptException);
}
public void testValidateWillCompileButNotExecutePainlessScript() {
final TemplateScript compiledScript = mock(TemplateScript.class);
doThrow(new IllegalStateException("Validate should not execute painless script")).when(compiledScript).execute();
final TemplateScript.Factory scriptFactory = mock(TemplateScript.Factory.class);
when(scriptFactory.newInstance(any())).thenReturn(compiledScript);
final ScriptEngine scriptEngine = mock(ScriptEngine.class);
when(scriptEngine.getType()).thenReturn("painless");
when(scriptEngine.compile(eq("valid"), eq("params.metedata.group"), any(), eq(Map.of()))).thenReturn(scriptFactory);
final ScriptException scriptException = new ScriptException(
"exception",
new IllegalStateException(),
List.of(),
"bad syntax",
"painless"
);
doThrow(scriptException).when(scriptEngine).compile(eq("invalid"), eq("bad syntax"), any(), eq(Map.of()));
final ScriptService scriptService = new ScriptService(
Settings.EMPTY,
Map.of("painless", scriptEngine),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
) {
@Override
protected StoredScriptSource getScriptFromClusterState(ProjectId projectId, String id) {
if ("valid".equals(id)) {
return new StoredScriptSource("painless", "params.metedata.group", Map.of());
} else {
return new StoredScriptSource("painless", "bad syntax", Map.of());
}
}
};
// Validation succeeds if compilation is successful
new TemplateRoleName(new BytesArray("""
{ "id":"valid" }"""), Format.STRING).validate(scriptService);
verify(scriptEngine, times(1)).compile(eq("valid"), eq("params.metedata.group"), any(), eq(Map.of()));
verify(compiledScript, never()).execute();
// Validation fails if compilation fails
final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TemplateRoleName(new BytesArray("""
{ "id":"invalid" }"""), Format.STRING).validate(scriptService));
assertSame(scriptException, e.getCause());
}
public void testValidationWillFailWhenInlineScriptIsNotEnabled() {
final Settings settings = Settings.builder().put("script.allowed_types", ScriptService.ALLOW_NONE).build();
final ScriptService scriptService = new ScriptService(
settings,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final BytesReference inlineScript = new BytesArray("""
{ "source":"" }""");
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new TemplateRoleName(inlineScript, Format.STRING).validate(scriptService)
);
assertThat(e.getMessage(), containsString("[inline]"));
}
public void testValidateWillFailWhenStoredScriptIsNotEnabled() {
final Settings settings = Settings.builder().put("script.allowed_types", ScriptService.ALLOW_NONE).build();
final ScriptService scriptService = new ScriptService(
settings,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final ClusterChangedEvent clusterChangedEvent = mock(ClusterChangedEvent.class);
final ClusterState clusterState = mock(ClusterState.class);
final Metadata metadata = mock(Metadata.class);
final StoredScriptSource storedScriptSource = mock(StoredScriptSource.class);
final ScriptMetadata scriptMetadata = new ScriptMetadata.Builder(null).storeScript("foo", storedScriptSource).build();
final ProjectMetadata project = mock(ProjectMetadata.class);
when(clusterChangedEvent.state()).thenReturn(clusterState);
when(clusterState.metadata()).thenReturn(metadata);
when(project.custom(ScriptMetadata.TYPE)).thenReturn(scriptMetadata);
when(metadata.getProject(any())).thenReturn(project);
when(storedScriptSource.getLang()).thenReturn("mustache");
when(storedScriptSource.getSource()).thenReturn("");
when(storedScriptSource.getOptions()).thenReturn(Collections.emptyMap());
scriptService.applyClusterState(clusterChangedEvent);
final BytesReference storedScript = new BytesArray("""
{ "id":"foo" }""");
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new TemplateRoleName(storedScript, Format.STRING).validate(scriptService)
);
assertThat(e.getMessage(), containsString("[stored]"));
}
public void testValidateWillFailWhenStoredScriptIsNotFound() {
final ScriptService scriptService = new ScriptService(
Settings.EMPTY,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
final ClusterChangedEvent clusterChangedEvent = mock(ClusterChangedEvent.class);
final ClusterState clusterState = mock(ClusterState.class);
final Metadata metadata = mock(Metadata.class);
final ScriptMetadata scriptMetadata = new ScriptMetadata.Builder(null).build();
final ProjectMetadata project = mock(ProjectMetadata.class);
when(clusterChangedEvent.state()).thenReturn(clusterState);
when(clusterState.metadata()).thenReturn(metadata);
when(project.custom(ScriptMetadata.TYPE)).thenReturn(scriptMetadata);
when(metadata.getProject(any())).thenReturn(project);
scriptService.applyClusterState(clusterChangedEvent);
final BytesReference storedScript = new BytesArray("""
{ "id":"foo" }""");
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new TemplateRoleName(storedScript, Format.STRING).validate(scriptService)
);
assertThat(e.getMessage(), containsString("unable to find script"));
}
}
|
TemplateRoleNameTests
|
java
|
apache__spark
|
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/Table.java
|
{
"start": 1866,
"end": 3912
}
|
interface ____ {
/**
* A name to identify this table. Implementations should provide a meaningful name, like the
* database and table name from catalog, or the location of files for this table.
*/
String name();
/**
* An ID of the table that can be used to reliably check if two table objects refer to the same
* metastore entity. If a table is dropped and recreated again with the same name, the new table
* ID must be different. This method must return null if connectors don't support the notion of
* table ID.
*/
default String id() {
return null;
}
/**
* Returns the schema of this table. If the table is not readable and doesn't have a schema, an
* empty schema can be returned here.
* <p>
* @deprecated This is deprecated. Please override {@link #columns} instead.
*/
@Deprecated(since = "3.4.0")
default StructType schema() {
throw QueryCompilationErrors.mustOverrideOneMethodError("columns");
}
/**
* Returns the columns of this table. If the table is not readable and doesn't have a schema, an
* empty array can be returned here.
*/
default Column[] columns() {
return CatalogV2Util.structTypeToV2Columns(schema());
}
/**
* Returns the physical partitioning of this table.
*/
default Transform[] partitioning() {
return new Transform[0];
}
/**
* Returns the string map of table properties.
*/
default Map<String, String> properties() {
return Collections.emptyMap();
}
/**
* Returns the set of capabilities for this table.
*/
Set<TableCapability> capabilities();
/**
* Returns the constraints for this table.
*/
default Constraint[] constraints() { return new Constraint[0]; }
/**
* Returns the version of this table if versioning is supported, null otherwise.
* <p>
* This method must not trigger a refresh of the table metadata. It should return
* the version that corresponds to the current state of this table instance.
*/
default String version() { return null; }
}
|
Table
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiersTest.java
|
{
"start": 4676,
"end": 5180
}
|
class ____ {
private static final FluentLogger logger = register(FluentLogger.forEnclosingClass());
private static <T> T register(T t) {
return t;
}
}
""")
.doTest();
}
// People who do this generally do it for good reason, and for interfaces it's required.
@Test
public void negative_allowsSiblingLoggerUse() {
refactoringHelper()
.addInputLines(
"in/Test.java",
"""
import com.google.common.flogger.FluentLogger;
|
Test
|
java
|
netty__netty
|
transport/src/test/java/io/netty/channel/LoggingHandler.java
|
{
"start": 757,
"end": 842
}
|
class ____ implements ChannelInboundHandler, ChannelOutboundHandler {
|
LoggingHandler
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/mapper/DataStreamTimestampFieldMapper.java
|
{
"start": 1442,
"end": 2118
}
|
class ____ extends MetadataFieldMapper {
public static final String NAME = "_data_stream_timestamp";
public static final String DEFAULT_PATH = "@timestamp";
public static final String TIMESTAMP_VALUE_KEY = "@timestamp._value";
public static final DataStreamTimestampFieldMapper ENABLED_INSTANCE = new DataStreamTimestampFieldMapper(true);
private static final DataStreamTimestampFieldMapper DISABLED_INSTANCE = new DataStreamTimestampFieldMapper(false);
// For now the field shouldn't be useable in searches.
// In the future it should act as an alias to the actual data stream timestamp field.
public static final
|
DataStreamTimestampFieldMapper
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/HdfsServerConstants.java
|
{
"start": 1666,
"end": 3240
}
|
interface ____ {
// Will be set by
// {@code DFSConfigKeys.DFS_NAMENODE_BLOCKPLACEMENTPOLICY_MIN_BLOCKS_FOR_WRITE_KEY}.
int MIN_BLOCKS_FOR_WRITE = 1;
long LEASE_RECOVER_PERIOD = 10 * 1000; // in ms
// We need to limit the length and depth of a path in the filesystem.
// HADOOP-438
// Currently we set the maximum length to 8k characters and the maximum depth
// to 1k.
int MAX_PATH_LENGTH = 8000;
int MAX_PATH_DEPTH = 1000;
// An invalid transaction ID that will never be seen in a real namesystem.
long INVALID_TXID = -12345;
// Number of generation stamps reserved for legacy blocks.
long RESERVED_LEGACY_GENERATION_STAMPS = 1024L * 1024 * 1024 * 1024;
/**
* Current layout version for NameNode.
* Please see {@link NameNodeLayoutVersion.Feature} on adding new layout version.
*/
int NAMENODE_LAYOUT_VERSION
= NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION;
/**
* Current minimum compatible version for NameNode
* Please see {@link NameNodeLayoutVersion.Feature} on adding new layout version.
*/
int MINIMUM_COMPATIBLE_NAMENODE_LAYOUT_VERSION
= NameNodeLayoutVersion.MINIMUM_COMPATIBLE_LAYOUT_VERSION;
/**
* Path components that are reserved in HDFS.
* <p>
* .reserved is only reserved under root ("/").
*/
String[] RESERVED_PATH_COMPONENTS = new String[] {
HdfsConstants.DOT_SNAPSHOT_DIR,
FSDirectory.DOT_RESERVED_STRING
};
byte[] DOT_SNAPSHOT_DIR_BYTES
= DFSUtil.string2Bytes(HdfsConstants.DOT_SNAPSHOT_DIR);
/**
* Type of the node
*/
|
HdfsServerConstants
|
java
|
spring-projects__spring-framework
|
spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContext.java
|
{
"start": 10926,
"end": 11327
}
|
class ____ extends AbstractNamingEnumeration<NameClassPair> {
private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
@Override
protected NameClassPair createObject(String strippedName, Object obj) {
return new NameClassPair(strippedName, obj.getClass().getName());
}
}
private static final
|
NameClassPairEnumeration
|
java
|
spring-projects__spring-framework
|
spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java
|
{
"start": 4373,
"end": 4547
}
|
class ____ extends CustomDateEditor {
public MyDateEditor() {
super(DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN), true);
}
}
public static
|
MyDateEditor
|
java
|
grpc__grpc-java
|
okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/DistinguishedNameParser.java
|
{
"start": 1099,
"end": 11478
}
|
class ____ {
private final String dn;
private final int length;
private int pos;
private int beg;
private int end;
/** Temporary variable to store positions of the currently parsed item. */
private int cur;
/** Distinguished name characters. */
private char[] chars;
public DistinguishedNameParser(X500Principal principal) {
// RFC2253 is used to ensure we get attributes in the reverse
// order of the underlying ASN.1 encoding, so that the most
// significant values of repeated attributes occur first.
this.dn = principal.getName(X500Principal.RFC2253);
this.length = this.dn.length();
}
// gets next attribute type: (ALPHA 1*keychar) / oid
private String nextAT() {
// skip preceding space chars, they can present after
// comma or semicolon (compatibility with RFC 1779)
for (; pos < length && chars[pos] == ' '; pos++) {
}
if (pos == length) {
return null; // reached the end of DN
}
// mark the beginning of attribute type
beg = pos;
// attribute type chars
pos++;
for (; pos < length && chars[pos] != '=' && chars[pos] != ' '; pos++) {
// we don't follow exact BNF syntax here:
// accept any char except space and '='
}
if (pos >= length) {
throw new IllegalStateException("Unexpected end of DN: " + dn);
}
// mark the end of attribute type
end = pos;
// skip trailing space chars between attribute type and '='
// (compatibility with RFC 1779)
if (chars[pos] == ' ') {
for (; pos < length && chars[pos] != '=' && chars[pos] == ' '; pos++) {
}
if (chars[pos] != '=' || pos == length) {
throw new IllegalStateException("Unexpected end of DN: " + dn);
}
}
pos++; //skip '=' char
// skip space chars between '=' and attribute value
// (compatibility with RFC 1779)
for (; pos < length && chars[pos] == ' '; pos++) {
}
// in case of oid attribute type skip its prefix: "oid." or "OID."
// (compatibility with RFC 1779)
if ((end - beg > 4) && (chars[beg + 3] == '.')
&& (chars[beg] == 'O' || chars[beg] == 'o')
&& (chars[beg + 1] == 'I' || chars[beg + 1] == 'i')
&& (chars[beg + 2] == 'D' || chars[beg + 2] == 'd')) {
beg += 4;
}
return new String(chars, beg, end - beg);
}
// gets quoted attribute value: QUOTATION *( quotechar / pair ) QUOTATION
private String quotedAV() {
pos++;
beg = pos;
end = beg;
while (true) {
if (pos == length) {
throw new IllegalStateException("Unexpected end of DN: " + dn);
}
if (chars[pos] == '"') {
// enclosing quotation was found
pos++;
break;
} else if (chars[pos] == '\\') {
chars[end] = getEscaped();
} else {
// shift char: required for string with escaped chars
chars[end] = chars[pos];
}
pos++;
end++;
}
// skip trailing space chars before comma or semicolon.
// (compatibility with RFC 1779)
for (; pos < length && chars[pos] == ' '; pos++) {
}
return new String(chars, beg, end - beg);
}
// gets hex string attribute value: "#" hexstring
@SuppressWarnings("NarrowingCompoundAssignment")
private String hexAV() {
if (pos + 4 >= length) {
// encoded byte array must be not less then 4 c
throw new IllegalStateException("Unexpected end of DN: " + dn);
}
beg = pos; // store '#' position
pos++;
while (true) {
// check for end of attribute value
// looks for space and component separators
if (pos == length || chars[pos] == '+' || chars[pos] == ','
|| chars[pos] == ';') {
end = pos;
break;
}
if (chars[pos] == ' ') {
end = pos;
pos++;
// skip trailing space chars before comma or semicolon.
// (compatibility with RFC 1779)
for (; pos < length && chars[pos] == ' '; pos++) {
}
break;
} else if (chars[pos] >= 'A' && chars[pos] <= 'F') {
chars[pos] += 32; //to low case
}
pos++;
}
// verify length of hex string
// encoded byte array must be not less then 4 and must be even number
int hexLen = end - beg; // skip first '#' char
if (hexLen < 5 || (hexLen & 1) == 0) {
throw new IllegalStateException("Unexpected end of DN: " + dn);
}
// get byte encoding from string representation
byte[] encoded = new byte[hexLen / 2];
for (int i = 0, p = beg + 1; i < encoded.length; p += 2, i++) {
encoded[i] = (byte) getByte(p);
}
return new String(chars, beg, hexLen);
}
// gets string attribute value: *( stringchar / pair )
private String escapedAV() {
beg = pos;
end = pos;
while (true) {
if (pos >= length) {
// the end of DN has been found
return new String(chars, beg, end - beg);
}
switch (chars[pos]) {
case '+':
case ',':
case ';':
// separator char has been found
return new String(chars, beg, end - beg);
case '\\':
// escaped char
chars[end++] = getEscaped();
pos++;
break;
case ' ':
// need to figure out whether space defines
// the end of attribute value or not
cur = end;
pos++;
chars[end++] = ' ';
for (; pos < length && chars[pos] == ' '; pos++) {
chars[end++] = ' ';
}
if (pos == length || chars[pos] == ',' || chars[pos] == '+'
|| chars[pos] == ';') {
// separator char or the end of DN has been found
return new String(chars, beg, cur - beg);
}
break;
default:
chars[end++] = chars[pos];
pos++;
}
}
}
// returns escaped char
private char getEscaped() {
pos++;
if (pos == length) {
throw new IllegalStateException("Unexpected end of DN: " + dn);
}
switch (chars[pos]) {
case '"':
case '\\':
case ',':
case '=':
case '+':
case '<':
case '>':
case '#':
case ';':
case ' ':
case '*':
case '%':
case '_':
//FIXME: escaping is allowed only for leading or trailing space char
return chars[pos];
default:
// RFC doesn't explicitly say that escaped hex pair is
// interpreted as UTF-8 char. It only contains an example of such DN.
return getUTF8();
}
}
// decodes UTF-8 char
// see http://www.unicode.org for UTF-8 bit distribution table
private char getUTF8() {
int res = getByte(pos);
pos++; //FIXME tmp
if (res < 128) { // one byte: 0-7F
return (char) res;
} else if (res >= 192 && res <= 247) {
int count;
if (res <= 223) { // two bytes: C0-DF
count = 1;
res = res & 0x1F;
} else if (res <= 239) { // three bytes: E0-EF
count = 2;
res = res & 0x0F;
} else { // four bytes: F0-F7
count = 3;
res = res & 0x07;
}
int b;
for (int i = 0; i < count; i++) {
pos++;
if (pos == length || chars[pos] != '\\') {
return 0x3F; //FIXME failed to decode UTF-8 char - return '?'
}
pos++;
b = getByte(pos);
pos++; //FIXME tmp
if ((b & 0xC0) != 0x80) {
return 0x3F; //FIXME failed to decode UTF-8 char - return '?'
}
res = (res << 6) + (b & 0x3F);
}
return (char) res;
} else {
return 0x3F; //FIXME failed to decode UTF-8 char - return '?'
}
}
// Returns byte representation of a char pair
// The char pair is composed of DN char in
// specified 'position' and the next char
// According to BNF syntax:
// hexchar = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
// / "a" / "b" / "c" / "d" / "e" / "f"
private int getByte(int position) {
if (position + 1 >= length) {
throw new IllegalStateException("Malformed DN: " + dn);
}
int b1, b2;
b1 = chars[position];
if (b1 >= '0' && b1 <= '9') {
b1 = b1 - '0';
} else if (b1 >= 'a' && b1 <= 'f') {
b1 = b1 - 87; // 87 = 'a' - 10
} else if (b1 >= 'A' && b1 <= 'F') {
b1 = b1 - 55; // 55 = 'A' - 10
} else {
throw new IllegalStateException("Malformed DN: " + dn);
}
b2 = chars[position + 1];
if (b2 >= '0' && b2 <= '9') {
b2 = b2 - '0';
} else if (b2 >= 'a' && b2 <= 'f') {
b2 = b2 - 87; // 87 = 'a' - 10
} else if (b2 >= 'A' && b2 <= 'F') {
b2 = b2 - 55; // 55 = 'A' - 10
} else {
throw new IllegalStateException("Malformed DN: " + dn);
}
return (b1 << 4) + b2;
}
/**
* Parses the DN and returns the most significant attribute value
* for an attribute type, or null if none found.
*
* @param attributeType attribute type to look for (e.g. "ca")
*/
public String findMostSpecific(String attributeType) {
// Initialize internal state.
pos = 0;
beg = 0;
end = 0;
cur = 0;
chars = dn.toCharArray();
String attType = nextAT();
if (attType == null) {
return null;
}
while (true) {
String attValue = "";
if (pos == length) {
return null;
}
switch (chars[pos]) {
case '"':
attValue = quotedAV();
break;
case '#':
attValue = hexAV();
break;
case '+':
case ',':
case ';': // compatibility with RFC 1779: semicolon can separate RDNs
//empty attribute value
break;
default:
attValue = escapedAV();
}
// Values are ordered from most specific to least specific
// due to the RFC2253 formatting. So take the first match
// we see.
if (attributeType.equalsIgnoreCase(attType)) {
return attValue;
}
if (pos >= length) {
return null;
}
if (chars[pos] == ',' || chars[pos] == ';') {
} else if (chars[pos] != '+') {
throw new IllegalStateException("Malformed DN: " + dn);
}
pos++;
attType = nextAT();
if (attType == null) {
throw new IllegalStateException("Malformed DN: " + dn);
}
}
}
}
|
DistinguishedNameParser
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OidcProviderConfigurationTests.java
|
{
"start": 17324,
"end": 17910
}
|
class ____
extends AuthorizationServerConfiguration {
// @formatter:off
@Bean
SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.pushedAuthorizationRequestEndpoint(Customizer.withDefaults())
.oidc(Customizer.withDefaults())
);
return http.build();
}
// @formatter:on
}
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
static
|
AuthorizationServerConfigurationWithPushedAuthorizationRequestEnabled
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GridFsEndpointBuilderFactory.java
|
{
"start": 1562,
"end": 4619
}
|
interface ____
extends
EndpointConsumerBuilder {
default AdvancedGridFsEndpointConsumerBuilder advanced() {
return (AdvancedGridFsEndpointConsumerBuilder) this;
}
/**
* Sets the name of the GridFS bucket within the database. Default is
* fs.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: fs
* Group: common
*
* @param bucket the value to set
* @return the dsl builder
*/
default GridFsEndpointConsumerBuilder bucket(String bucket) {
doSetProperty("bucket", bucket);
return this;
}
/**
* Sets the name of the MongoDB database to target.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: common
*
* @param database the value to set
* @return the dsl builder
*/
default GridFsEndpointConsumerBuilder database(String database) {
doSetProperty("database", database);
return this;
}
/**
* Sets a MongoDB ReadPreference on the Mongo connection. Read
* preferences set directly on the connection will be overridden by this
* setting. The com.mongodb.ReadPreference#valueOf(String) utility
* method is used to resolve the passed readPreference value. Some
* examples for the possible values are nearest, primary or secondary
* etc.
*
* The option is a: <code>com.mongodb.ReadPreference</code> type.
*
* Group: common
*
* @param readPreference the value to set
* @return the dsl builder
*/
default GridFsEndpointConsumerBuilder readPreference(com.mongodb.ReadPreference readPreference) {
doSetProperty("readPreference", readPreference);
return this;
}
/**
* Sets a MongoDB ReadPreference on the Mongo connection. Read
* preferences set directly on the connection will be overridden by this
* setting. The com.mongodb.ReadPreference#valueOf(String) utility
* method is used to resolve the passed readPreference value. Some
* examples for the possible values are nearest, primary or secondary
* etc.
*
* The option will be converted to a
* <code>com.mongodb.ReadPreference</code> type.
*
* Group: common
*
* @param readPreference the value to set
* @return the dsl builder
*/
default GridFsEndpointConsumerBuilder readPreference(String readPreference) {
doSetProperty("readPreference", readPreference);
return this;
}
/**
* Set the WriteConcern for write operations on MongoDB using the
* standard ones. Resolved from the fields of the WriteConcern
|
GridFsEndpointConsumerBuilder
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/type/format/jackson/JacksonXmlFormatMapper.java
|
{
"start": 10225,
"end": 10713
}
|
class ____ extends JsonDeserializer<String[]> {
@Override
public String[] deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException {
final ArrayList<String> result = new ArrayList<>();
JsonToken token;
while ( ( token = jp.nextValue() ) != JsonToken.END_OBJECT ) {
if ( token.isScalarValue() ) {
result.add( jp.getValueAsString() );
}
}
return result.toArray( String[]::new );
}
}
private static
|
StringArrayDeserializer
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/security/HttpUpgradeRedirectOnFailureTest.java
|
{
"start": 1166,
"end": 3505
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Endpoint.class, WSClient.class, TestIdentityProvider.class, TestIdentityController.class,
SecurityTestBase.class)
.addAsResource(
new StringAsset(
"quarkus.websockets-next.server.security.auth-failure-redirect-url=https://quarkus.io\n"),
"application.properties"));
@Inject
Vertx vertx;
@TestHTTPResource("end")
URI endUri;
@BeforeAll
public static void setupUsers() {
TestIdentityController.resetRoles()
.add("admin", "admin", "admin")
.add("user", "user", "user");
}
@Test
public void testRedirectOnFailure() {
// test redirected on failure
RestAssured
.given()
// without this header the client would receive 404
.header("Sec-WebSocket-Key", "foo")
.redirects()
.follow(false)
.get(endUri)
.then()
.statusCode(302)
.header(HttpHeaderNames.LOCATION.toString(), "https://quarkus.io");
try (WSClient client = new WSClient(vertx)) {
client.connect(basicAuth("admin", "admin"), endUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("hello", client.getMessages().get(1).toString());
}
// no redirect as CDI interceptor secures @OnTextMessage
try (WSClient client = new WSClient(vertx)) {
client.connect(basicAuth("user", "user"), endUri);
client.waitForMessages(1);
assertEquals("ready", client.getMessages().get(0).toString());
client.sendAndAwait("hello");
client.waitForMessages(2);
assertEquals("forbidden:user", client.getMessages().get(1).toString());
}
}
@RolesAllowed({ "admin", "user" })
@WebSocket(path = "/end")
public static
|
HttpUpgradeRedirectOnFailureTest
|
java
|
apache__camel
|
components/camel-google/camel-google-calendar/src/test/java/org/apache/camel/component/google/calendar/stream/GoogleCalendarStreamConsumerIT.java
|
{
"start": 1246,
"end": 1892
}
|
class ____ extends AbstractGoogleCalendarStreamTestSupport {
@Test
public void testConsumePrefixedMessages() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
Thread.sleep(10000);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("google-calendar-stream://test?delay=5000&maxResults=5").to("mock:result");
}
};
}
}
|
GoogleCalendarStreamConsumerIT
|
java
|
quarkusio__quarkus
|
extensions/cache/deployment/src/test/java/io/quarkus/cache/test/deployment/CacheConfigTest.java
|
{
"start": 4037,
"end": 4201
}
|
class ____ {
@GET
@CacheResult(cacheName = CACHE_NAME)
public String foo(String key) {
return "bar";
}
}
}
|
TestResource
|
java
|
apache__camel
|
components/camel-huawei/camel-huaweicloud-functiongraph/src/test/java/org/apache/camel/InvokeFunctionFunctionalTest.java
|
{
"start": 1303,
"end": 3987
}
|
class ____ extends CamelTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(InvokeFunctionFunctionalTest.class.getName());
private static final String ACCESS_KEY = "replace_this_with_access_key";
private static final String SECRET_KEY = "replace_this_with_secret_key";
private static final String FUNCTION_NAME = "replace_this_with_function_name";
private static final String FUNCTION_PACKAGE = "replace_this_with_function_package";
private static final String PROJECT_ID = "replace_this_with_project_id";
private static final String REGION = "replace_this_with_region";
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:invoke_function")
.setProperty(FunctionGraphProperties.XCFFLOGTYPE, constant("tail"))
.to("hwcloud-functiongraph:invokeFunction?" +
"accessKey=" + ACCESS_KEY +
"&secretKey=" + SECRET_KEY +
"&functionName=" + FUNCTION_NAME +
"&functionPackage=" + FUNCTION_PACKAGE +
"&projectId=" + PROJECT_ID +
"®ion=" + REGION +
"&ignoreSslVerification=true")
.log("Invoke function successful")
.to("log:LOG?showAll=true")
.to("mock:invoke_function_result");
}
};
}
/**
* The following test cases should be manually enabled to perform test against the actual HuaweiCloud FunctionGraph
* server with real user credentials. To perform this test, manually comment out the @Ignore annotation and enter
* relevant service parameters in the placeholders above (static variables of this test class)
*
* @throws Exception
*/
@Disabled("Manually enable this once you configure the parameters in the placeholders above")
@Test
public void testInvokeFunction() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:invoke_function_result");
mock.expectedMinimumMessageCount(1);
String sampleBody = "replace_with_your_body";
template.sendBody("direct:invoke_function", sampleBody);
Exchange responseExchange = mock.getExchanges().get(0);
mock.assertIsSatisfied();
assertNotNull(responseExchange.getProperty(FunctionGraphProperties.XCFFLOGS));
assertTrue(responseExchange.getProperty(FunctionGraphProperties.XCFFLOGS).toString().length() > 0);
}
}
|
InvokeFunctionFunctionalTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/permission/AclStatus.java
|
{
"start": 1363,
"end": 3236
}
|
class ____ {
private final String owner;
private final String group;
private final boolean stickyBit;
private final List<AclEntry> entries;
private final FsPermission permission;
/**
* Returns the file owner.
*
* @return String file owner
*/
public String getOwner() {
return owner;
}
/**
* Returns the file group.
*
* @return String file group
*/
public String getGroup() {
return group;
}
/**
* Returns the sticky bit.
*
* @return boolean sticky bit
*/
public boolean isStickyBit() {
return stickyBit;
}
/**
* Returns the list of all ACL entries, ordered by their natural ordering.
*
* @return List<AclEntry> unmodifiable ordered list of all ACL entries
*/
public List<AclEntry> getEntries() {
return entries;
}
/**
* Returns the permission set for the path
* @return {@link FsPermission} for the path
*/
public FsPermission getPermission() {
return permission;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (getClass() != o.getClass()) {
return false;
}
AclStatus other = (AclStatus)o;
return Objects.equal(owner, other.owner)
&& Objects.equal(group, other.group)
&& stickyBit == other.stickyBit
&& Objects.equal(entries, other.entries);
}
@Override
public int hashCode() {
return Objects.hashCode(owner, group, stickyBit, entries);
}
@Override
public String toString() {
return new StringBuilder()
.append("owner: ").append(owner)
.append(", group: ").append(group)
.append(", acl: {")
.append("entries: ").append(entries)
.append(", stickyBit: ").append(stickyBit)
.append('}')
.toString();
}
/**
* Builder for creating new Acl instances.
*/
public static
|
AclStatus
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/blocklist/DefaultBlocklistHandler.java
|
{
"start": 1440,
"end": 7345
}
|
class ____ implements BlocklistHandler, AutoCloseable {
private final Logger log;
private final Function<ResourceID, String> taskManagerNodeIdRetriever;
private final BlocklistTracker blocklistTracker;
private final BlocklistContext blocklistContext;
private final Set<BlocklistListener> blocklistListeners = new HashSet<>();
private final Duration timeoutCheckInterval;
private volatile ScheduledFuture<?> timeoutCheckFuture;
private final ComponentMainThreadExecutor mainThreadExecutor;
DefaultBlocklistHandler(
BlocklistTracker blocklistTracker,
BlocklistContext blocklistContext,
Function<ResourceID, String> taskManagerNodeIdRetriever,
Duration timeoutCheckInterval,
ComponentMainThreadExecutor mainThreadExecutor,
Logger log) {
this.blocklistTracker = checkNotNull(blocklistTracker);
this.blocklistContext = checkNotNull(blocklistContext);
this.taskManagerNodeIdRetriever = checkNotNull(taskManagerNodeIdRetriever);
this.timeoutCheckInterval = checkNotNull(timeoutCheckInterval);
this.mainThreadExecutor = checkNotNull(mainThreadExecutor);
this.log = checkNotNull(log);
scheduleTimeoutCheck();
}
private void scheduleTimeoutCheck() {
this.timeoutCheckFuture =
mainThreadExecutor.schedule(
() -> {
removeTimeoutNodes();
scheduleTimeoutCheck();
},
timeoutCheckInterval.toMillis(),
TimeUnit.MILLISECONDS);
}
private void removeTimeoutNodes() {
assertRunningInMainThread();
Collection<BlockedNode> removedNodes =
blocklistTracker.removeTimeoutNodes(System.currentTimeMillis());
if (!removedNodes.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug(
"Remove {} timeout blocked nodes, details {}. "
+ "Total {} blocked nodes currently, details: {}.",
removedNodes.size(),
removedNodes,
blocklistTracker.getAllBlockedNodes().size(),
blocklistTracker.getAllBlockedNodes());
} else {
log.info(
"Remove {} timeout blocked nodes. Total {} blocked nodes currently.",
removedNodes.size(),
blocklistTracker.getAllBlockedNodes().size());
}
blocklistContext.unblockResources(removedNodes);
}
}
private void assertRunningInMainThread() {
mainThreadExecutor.assertRunningInMainThread();
}
@Override
public void addNewBlockedNodes(Collection<BlockedNode> newNodes) {
assertRunningInMainThread();
if (newNodes.isEmpty()) {
return;
}
BlockedNodeAdditionResult result = blocklistTracker.addNewBlockedNodes(newNodes);
Collection<BlockedNode> newlyAddedNodes = result.getNewlyAddedNodes();
Collection<BlockedNode> allNodes =
Stream.concat(newlyAddedNodes.stream(), result.getMergedNodes().stream())
.collect(Collectors.toList());
if (!newlyAddedNodes.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug(
"Newly added {} blocked nodes, details: {}."
+ " Total {} blocked nodes currently, details: {}.",
newlyAddedNodes.size(),
newlyAddedNodes,
blocklistTracker.getAllBlockedNodes().size(),
blocklistTracker.getAllBlockedNodes());
} else {
log.info(
"Newly added {} blocked nodes. Total {} blocked nodes currently.",
newlyAddedNodes.size(),
blocklistTracker.getAllBlockedNodes().size());
}
blocklistListeners.forEach(listener -> listener.notifyNewBlockedNodes(allNodes));
blocklistContext.blockResources(newlyAddedNodes);
} else if (!allNodes.isEmpty()) {
blocklistListeners.forEach(listener -> listener.notifyNewBlockedNodes(allNodes));
}
}
@Override
public boolean isBlockedTaskManager(ResourceID taskManagerId) {
assertRunningInMainThread();
String nodeId = checkNotNull(taskManagerNodeIdRetriever.apply(taskManagerId));
return blocklistTracker.isBlockedNode(nodeId);
}
@Override
public Set<String> getAllBlockedNodeIds() {
assertRunningInMainThread();
return blocklistTracker.getAllBlockedNodeIds();
}
@Override
public void registerBlocklistListener(BlocklistListener blocklistListener) {
assertRunningInMainThread();
checkNotNull(blocklistListener);
if (!blocklistListeners.contains(blocklistListener)) {
blocklistListeners.add(blocklistListener);
Collection<BlockedNode> allBlockedNodes = blocklistTracker.getAllBlockedNodes();
if (!allBlockedNodes.isEmpty()) {
blocklistListener.notifyNewBlockedNodes(allBlockedNodes);
}
}
}
@Override
public void deregisterBlocklistListener(BlocklistListener blocklistListener) {
assertRunningInMainThread();
checkNotNull(blocklistListener);
blocklistListeners.remove(blocklistListener);
}
@Override
public void close() throws Exception {
if (timeoutCheckFuture != null) {
timeoutCheckFuture.cancel(false);
}
}
/** The factory to instantiate {@link DefaultBlocklistHandler}. */
public static
|
DefaultBlocklistHandler
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/FeatureResponseFilter.java
|
{
"start": 264,
"end": 780
}
|
class ____ implements ContainerResponseFilter {
private final String headerName;
private final String headerValue;
public FeatureResponseFilter(String headerName, String headerValue) {
this.headerName = headerName;
this.headerValue = headerValue;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add(headerName, headerValue);
}
}
|
FeatureResponseFilter
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchMetricsManager.java
|
{
"start": 1633,
"end": 13446
}
|
class ____ {
private final Metrics metrics;
private final FetchMetricsRegistry metricsRegistry;
private final Sensor throttleTime;
private final Sensor bytesFetched;
private final Sensor recordsFetched;
private final Sensor fetchLatency;
private final Sensor recordsLag;
private final Sensor recordsLead;
private int assignmentId = 0;
private Set<TopicPartition> assignedPartitions = Collections.emptySet();
public FetchMetricsManager(Metrics metrics, FetchMetricsRegistry metricsRegistry) {
this.metrics = metrics;
this.metricsRegistry = metricsRegistry;
this.throttleTime = new SensorBuilder(metrics, "fetch-throttle-time")
.withAvg(metricsRegistry.fetchThrottleTimeAvg)
.withMax(metricsRegistry.fetchThrottleTimeMax)
.build();
this.bytesFetched = new SensorBuilder(metrics, "bytes-fetched")
.withAvg(metricsRegistry.fetchSizeAvg)
.withMax(metricsRegistry.fetchSizeMax)
.withMeter(metricsRegistry.bytesConsumedRate, metricsRegistry.bytesConsumedTotal)
.build();
this.recordsFetched = new SensorBuilder(metrics, "records-fetched")
.withAvg(metricsRegistry.recordsPerRequestAvg)
.withMeter(metricsRegistry.recordsConsumedRate, metricsRegistry.recordsConsumedTotal)
.build();
this.fetchLatency = new SensorBuilder(metrics, "fetch-latency")
.withAvg(metricsRegistry.fetchLatencyAvg)
.withMax(metricsRegistry.fetchLatencyMax)
.withMeter(new WindowedCount(), metricsRegistry.fetchRequestRate, metricsRegistry.fetchRequestTotal)
.build();
this.recordsLag = new SensorBuilder(metrics, "records-lag")
.withMax(metricsRegistry.recordsLagMax)
.build();
this.recordsLead = new SensorBuilder(metrics, "records-lead")
.withMin(metricsRegistry.recordsLeadMin)
.build();
}
public Sensor throttleTimeSensor() {
return throttleTime;
}
void recordLatency(String node, long requestLatencyMs) {
fetchLatency.record(requestLatencyMs);
if (!node.isEmpty()) {
String nodeTimeName = "node-" + node + ".latency";
Sensor nodeRequestTime = this.metrics.getSensor(nodeTimeName);
if (nodeRequestTime != null)
nodeRequestTime.record(requestLatencyMs);
}
}
void recordBytesFetched(int bytes) {
bytesFetched.record(bytes);
}
void recordRecordsFetched(int records) {
recordsFetched.record(records);
}
void recordBytesFetched(String topic, int bytes) {
String name = topicBytesFetchedMetricName(topic);
maybeRecordDeprecatedBytesFetched(name, topic, bytes);
Sensor bytesFetched = new SensorBuilder(metrics, name, () -> Map.of("topic", topic))
.withAvg(metricsRegistry.topicFetchSizeAvg)
.withMax(metricsRegistry.topicFetchSizeMax)
.withMeter(metricsRegistry.topicBytesConsumedRate, metricsRegistry.topicBytesConsumedTotal)
.build();
bytesFetched.record(bytes);
}
void recordRecordsFetched(String topic, int records) {
String name = topicRecordsFetchedMetricName(topic);
maybeRecordDeprecatedRecordsFetched(name, topic, records);
Sensor recordsFetched = new SensorBuilder(metrics, name, () -> Map.of("topic", topic))
.withAvg(metricsRegistry.topicRecordsPerRequestAvg)
.withMeter(metricsRegistry.topicRecordsConsumedRate, metricsRegistry.topicRecordsConsumedTotal)
.build();
recordsFetched.record(records);
}
void recordPartitionLag(TopicPartition tp, long lag) {
this.recordsLag.record(lag);
String name = partitionRecordsLagMetricName(tp);
maybeRecordDeprecatedPartitionLag(name, tp, lag);
Sensor recordsLag = new SensorBuilder(metrics, name, () -> mkMap(mkEntry("topic", tp.topic()), mkEntry("partition", String.valueOf(tp.partition()))))
.withValue(metricsRegistry.partitionRecordsLag)
.withMax(metricsRegistry.partitionRecordsLagMax)
.withAvg(metricsRegistry.partitionRecordsLagAvg)
.build();
recordsLag.record(lag);
}
void recordPartitionLead(TopicPartition tp, long lead) {
this.recordsLead.record(lead);
String name = partitionRecordsLeadMetricName(tp);
maybeRecordDeprecatedPartitionLead(name, tp, lead);
Sensor recordsLead = new SensorBuilder(metrics, name, () -> mkMap(mkEntry("topic", tp.topic()), mkEntry("partition", String.valueOf(tp.partition()))))
.withValue(metricsRegistry.partitionRecordsLead)
.withMin(metricsRegistry.partitionRecordsLeadMin)
.withAvg(metricsRegistry.partitionRecordsLeadAvg)
.build();
recordsLead.record(lead);
}
/**
* This method is called by the {@link Fetch fetch} logic before it requests fetches in order to update the
* internal set of metrics that are tracked.
*
* @param subscription {@link SubscriptionState} that contains the set of assigned partitions
* @see SubscriptionState#assignmentId()
*/
void maybeUpdateAssignment(SubscriptionState subscription) {
int newAssignmentId = subscription.assignmentId();
if (this.assignmentId != newAssignmentId) {
Set<TopicPartition> newAssignedPartitions = subscription.assignedPartitions();
for (TopicPartition tp : this.assignedPartitions) {
if (!newAssignedPartitions.contains(tp)) {
metrics.removeSensor(partitionRecordsLagMetricName(tp));
metrics.removeSensor(partitionRecordsLeadMetricName(tp));
metrics.removeMetric(partitionPreferredReadReplicaMetricName(tp));
// Remove deprecated metrics.
metrics.removeSensor(deprecatedMetricName(partitionRecordsLagMetricName(tp)));
metrics.removeSensor(deprecatedMetricName(partitionRecordsLeadMetricName(tp)));
metrics.removeMetric(deprecatedPartitionPreferredReadReplicaMetricName(tp));
}
}
for (TopicPartition tp : newAssignedPartitions) {
if (!this.assignedPartitions.contains(tp)) {
maybeRecordDeprecatedPreferredReadReplica(tp, subscription);
MetricName metricName = partitionPreferredReadReplicaMetricName(tp);
metrics.addMetricIfAbsent(
metricName,
null,
(Gauge<Integer>) (config, now) -> subscription.preferredReadReplica(tp, 0L).orElse(-1)
);
}
}
this.assignedPartitions = newAssignedPartitions;
this.assignmentId = newAssignmentId;
}
}
@Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedBytesFetched(String name, String topic, int bytes) {
if (shouldReportDeprecatedMetric(topic)) {
Sensor deprecatedBytesFetched = new SensorBuilder(metrics, deprecatedMetricName(name), () -> topicTags(topic))
.withAvg(metricsRegistry.topicFetchSizeAvg)
.withMax(metricsRegistry.topicFetchSizeMax)
.withMeter(metricsRegistry.topicBytesConsumedRate, metricsRegistry.topicBytesConsumedTotal)
.build();
deprecatedBytesFetched.record(bytes);
}
}
@Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedRecordsFetched(String name, String topic, int records) {
if (shouldReportDeprecatedMetric(topic)) {
Sensor deprecatedRecordsFetched = new SensorBuilder(metrics, deprecatedMetricName(name), () -> topicTags(topic))
.withAvg(metricsRegistry.topicRecordsPerRequestAvg)
.withMeter(metricsRegistry.topicRecordsConsumedRate, metricsRegistry.topicRecordsConsumedTotal)
.build();
deprecatedRecordsFetched.record(records);
}
}
@Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedPartitionLag(String name, TopicPartition tp, long lag) {
if (shouldReportDeprecatedMetric(tp.topic())) {
Sensor deprecatedRecordsLag = new SensorBuilder(metrics, deprecatedMetricName(name), () -> topicPartitionTags(tp))
.withValue(metricsRegistry.partitionRecordsLag)
.withMax(metricsRegistry.partitionRecordsLagMax)
.withAvg(metricsRegistry.partitionRecordsLagAvg)
.build();
deprecatedRecordsLag.record(lag);
}
}
@Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedPartitionLead(String name, TopicPartition tp, double lead) {
if (shouldReportDeprecatedMetric(tp.topic())) {
Sensor deprecatedRecordsLead = new SensorBuilder(metrics, deprecatedMetricName(name), () -> topicPartitionTags(tp))
.withValue(metricsRegistry.partitionRecordsLead)
.withMin(metricsRegistry.partitionRecordsLeadMin)
.withAvg(metricsRegistry.partitionRecordsLeadAvg)
.build();
deprecatedRecordsLead.record(lead);
}
}
@Deprecated // To be removed in Kafka 5.0 release.
private void maybeRecordDeprecatedPreferredReadReplica(TopicPartition tp, SubscriptionState subscription) {
if (shouldReportDeprecatedMetric(tp.topic())) {
MetricName metricName = deprecatedPartitionPreferredReadReplicaMetricName(tp);
metrics.addMetricIfAbsent(
metricName,
null,
(Gauge<Integer>) (config, now) -> subscription.preferredReadReplica(tp, 0L).orElse(-1)
);
}
}
private static String topicBytesFetchedMetricName(String topic) {
return "topic." + topic + ".bytes-fetched";
}
private static String topicRecordsFetchedMetricName(String topic) {
return "topic." + topic + ".records-fetched";
}
private static String partitionRecordsLeadMetricName(TopicPartition tp) {
return tp + ".records-lead";
}
private static String partitionRecordsLagMetricName(TopicPartition tp) {
return tp + ".records-lag";
}
private static String deprecatedMetricName(String name) {
return name + ".deprecated";
}
private static boolean shouldReportDeprecatedMetric(String topic) {
return topic.contains(".");
}
private MetricName partitionPreferredReadReplicaMetricName(TopicPartition tp) {
Map<String, String> metricTags = mkMap(mkEntry("topic", tp.topic()), mkEntry("partition", String.valueOf(tp.partition())));
return this.metrics.metricInstance(metricsRegistry.partitionPreferredReadReplica, metricTags);
}
@Deprecated
private MetricName deprecatedPartitionPreferredReadReplicaMetricName(TopicPartition tp) {
Map<String, String> metricTags = topicPartitionTags(tp);
return this.metrics.metricInstance(metricsRegistry.partitionPreferredReadReplica, metricTags);
}
@Deprecated
static Map<String, String> topicTags(String topic) {
return Map.of("topic", topic.replace('.', '_'));
}
@Deprecated
static Map<String, String> topicPartitionTags(TopicPartition tp) {
return mkMap(mkEntry("topic", tp.topic().replace('.', '_')),
mkEntry("partition", String.valueOf(tp.partition())));
}
}
|
FetchMetricsManager
|
java
|
quarkusio__quarkus
|
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/MessageBundleProcessor.java
|
{
"start": 93614,
"end": 94043
}
|
class ____ implements MessageMethod {
final MethodInfo method;
SimpleMessageMethod(MethodInfo method) {
this.method = method;
}
@Override
public List<Type> parameterTypes() {
return method.parameterTypes();
}
@Override
public MethodDesc descriptor() {
return methodDescOf(method);
}
}
static
|
SimpleMessageMethod
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/streaming/api/runners/python/beam/state/BeamBagStateHandler.java
|
{
"start": 1598,
"end": 5103
}
|
class ____ extends AbstractBeamStateHandler<ListState<byte[]>> {
private static final String MERGE_NAMESPACES_MARK = "merge_namespaces";
@Nullable private final TypeSerializer<?> namespaceSerializer;
/** Reusable InputStream used to holding the elements to be deserialized. */
private final ByteArrayInputStreamWithPos bais;
/** InputStream Wrapper. */
private final DataInputViewStreamWrapper baisWrapper;
public BeamBagStateHandler(@Nullable TypeSerializer<?> namespaceSerializer) {
this.namespaceSerializer = namespaceSerializer;
this.bais = new ByteArrayInputStreamWithPos();
this.baisWrapper = new DataInputViewStreamWrapper(bais);
}
public BeamFnApi.StateResponse.Builder handleGet(
BeamFnApi.StateRequest request, ListState<byte[]> listState) throws Exception {
List<ByteString> byteStrings = convertToByteString(listState);
return BeamFnApi.StateResponse.newBuilder()
.setId(request.getId())
.setGet(
BeamFnApi.StateGetResponse.newBuilder()
.setData(ByteString.copyFrom(byteStrings)));
}
public BeamFnApi.StateResponse.Builder handleAppend(
BeamFnApi.StateRequest request, ListState<byte[]> listState) throws Exception {
if (request.getStateKey()
.getBagUserState()
.getTransformId()
.equals(MERGE_NAMESPACES_MARK)) {
Preconditions.checkNotNull(namespaceSerializer);
// get namespaces to merge
byte[] namespacesBytes = request.getAppend().getData().toByteArray();
bais.setBuffer(namespacesBytes, 0, namespacesBytes.length);
int namespaceCount = baisWrapper.readInt();
Set<Object> namespaces = new HashSet<>();
for (int i = 0; i < namespaceCount; i++) {
namespaces.add(namespaceSerializer.deserialize(baisWrapper));
}
byte[] targetNamespaceByte =
request.getStateKey().getBagUserState().getWindow().toByteArray();
bais.setBuffer(targetNamespaceByte, 0, targetNamespaceByte.length);
Object targetNamespace = namespaceSerializer.deserialize(baisWrapper);
((InternalListState<Object, Object, byte[]>) listState)
.mergeNamespaces(targetNamespace, namespaces);
} else {
// get values
byte[] valueBytes = request.getAppend().getData().toByteArray();
listState.add(valueBytes);
}
return BeamFnApi.StateResponse.newBuilder()
.setId(request.getId())
.setAppend(BeamFnApi.StateAppendResponse.getDefaultInstance());
}
public BeamFnApi.StateResponse.Builder handleClear(
BeamFnApi.StateRequest request, ListState<byte[]> listState) throws Exception {
listState.clear();
return BeamFnApi.StateResponse.newBuilder()
.setId(request.getId())
.setClear(BeamFnApi.StateClearResponse.getDefaultInstance());
}
private static List<ByteString> convertToByteString(ListState<byte[]> listState)
throws Exception {
List<ByteString> ret = new LinkedList<>();
if (listState.get() == null) {
return ret;
}
for (byte[] v : listState.get()) {
ret.add(ByteString.copyFrom(v));
}
return ret;
}
}
|
BeamBagStateHandler
|
java
|
spring-projects__spring-security
|
buildSrc/src/test/resources/samples/showcase/sgbcs-api/src/test/java/api/ApiTest.java
|
{
"start": 57,
"end": 105
}
|
class ____ {
@Test
public void api() {}
}
|
ApiTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/LazyAutoCloseableReference.java
|
{
"start": 1228,
"end": 3131
}
|
class ____<T extends AutoCloseable>
extends LazyAtomicReference<T> implements AutoCloseable {
/** Closed flag. */
private final AtomicBoolean closed = new AtomicBoolean(false);
/**
* Constructor for this instance.
* @param constructor method to invoke to actually construct the inner object.
*/
public LazyAutoCloseableReference(final CallableRaisingIOE<? extends T> constructor) {
super(constructor);
}
/**
* {@inheritDoc}
* @throws IllegalStateException if the reference is closed.
*/
@Override
public synchronized T eval() throws IOException {
checkState(!closed.get(), "Reference is closed");
return super.eval();
}
/**
* Is the reference closed?
* @return true if the reference is closed.
*/
public boolean isClosed() {
return closed.get();
}
/**
* Close the reference value if it is non-null.
* Sets the reference to null afterwards, even on
* a failure.
* @throws Exception failure to close.
*/
@Override
public synchronized void close() throws Exception {
if (closed.getAndSet(true)) {
// already closed
return;
}
final T v = getReference().get();
// check the state.
// A null reference means it has not yet been evaluated,
if (v != null) {
try {
v.close();
} finally {
// set the reference to null, even on a failure.
getReference().set(null);
}
}
}
/**
* Create from a supplier.
* This is not a constructor to avoid ambiguity when a lambda-expression is
* passed in.
* @param supplier supplier implementation.
* @return a lazy reference.
* @param <T> type of reference
*/
public static <T extends AutoCloseable> LazyAutoCloseableReference<T> lazyAutoCloseablefromSupplier(Supplier<T> supplier) {
return new LazyAutoCloseableReference<>(supplier::get);
}
}
|
LazyAutoCloseableReference
|
java
|
spring-projects__spring-boot
|
module/spring-boot-webflux/src/test/java/org/springframework/boot/webflux/observation/autoconfigure/WebFluxObservationAutoConfigurationTests.java
|
{
"start": 2336,
"end": 6432
}
|
class ____ {
private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withBean(SimpleMeterRegistry.class)
.withConfiguration(
AutoConfigurations.of(ObservationAutoConfiguration.class, WebFluxObservationAutoConfiguration.class));
@Test
void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class,
WebFluxAutoConfiguration.class))
.withPropertyValues("management.metrics.web.server.max-uri-tags=2")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSizeLessThanOrEqualTo(2);
assertThat(output).contains("Reached the maximum number of 'uri' tags for 'http.server.requests'");
});
}
@Test
void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomObservationName(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class,
WebFluxAutoConfiguration.class))
.withPropertyValues("management.metrics.web.server.max-uri-tags=2",
"management.observations.http.server.requests.name=my.http.server.requests")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context, "my.http.server.requests");
assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2);
assertThat(output).contains("Reached the maximum number of 'uri' tags for 'my.http.server.requests'");
});
}
@Test
void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class,
WebFluxAutoConfiguration.class))
.withPropertyValues("management.metrics.web.server.max-uri-tags=5")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(3);
assertThat(output)
.doesNotContain("Reached the maximum number of 'uri' tags for 'http.server.requests'");
});
}
@Test
void shouldSupplyDefaultServerRequestObservationConvention() {
this.contextRunner.withPropertyValues("management.observations.http.server.requests.name=some-other-name")
.run((context) -> {
assertThat(context).hasSingleBean(DefaultServerRequestObservationConvention.class);
DefaultServerRequestObservationConvention bean = context
.getBean(DefaultServerRequestObservationConvention.class);
assertThat(bean.getName()).isEqualTo("some-other-name");
});
}
@Test
void shouldBackOffOnCustomServerRequestObservationConvention() {
this.contextRunner
.withBean("customServerRequestObservationConvention", ServerRequestObservationConvention.class,
() -> mock(ServerRequestObservationConvention.class))
.run((context) -> {
assertThat(context).hasBean("customServerRequestObservationConvention");
assertThat(context).hasSingleBean(ServerRequestObservationConvention.class);
});
}
private MeterRegistry getInitializedMeterRegistry(AssertableReactiveWebApplicationContext context) {
return getInitializedMeterRegistry(context, "http.server.requests");
}
private MeterRegistry getInitializedMeterRegistry(AssertableReactiveWebApplicationContext context,
String metricName) {
MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
meterRegistry.timer(metricName, "uri", "/test0").record(Duration.of(500, ChronoUnit.SECONDS));
meterRegistry.timer(metricName, "uri", "/test1").record(Duration.of(500, ChronoUnit.SECONDS));
meterRegistry.timer(metricName, "uri", "/test2").record(Duration.of(500, ChronoUnit.SECONDS));
return meterRegistry;
}
@RestController
static
|
WebFluxObservationAutoConfigurationTests
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/config/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigWithOverridesTests.java
|
{
"start": 1903,
"end": 2109
}
|
class ____ implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> testClass) {
// Checking that the "test class" name ends with "*Tests" ensures that an actual
// test
|
DevResolver
|
java
|
spring-projects__spring-security
|
core/src/main/java/org/springframework/security/authentication/AuthenticationManagerResolver.java
|
{
"start": 833,
"end": 1076
}
|
interface ____<C> {
/**
* Resolve an {@link AuthenticationManager} from a provided context
* @param context
* @return the {@link AuthenticationManager} to use
*/
AuthenticationManager resolve(C context);
}
|
AuthenticationManagerResolver
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/collection/StringMapLobTest.java
|
{
"start": 5113,
"end": 5666
}
|
class ____ {
@Id
private Integer id;
private String name;
@ElementCollection
@Lob
private Map<String, String> embeddedMap = new HashMap<String, String>();
Simple() {
}
Simple(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Map<String,String> getEmbeddedMap() {
return embeddedMap;
}
public void setEmbeddedMap(Map<String,String> embeddedMap) {
this.embeddedMap = embeddedMap;
}
}
}
|
Simple
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/security/HttpSecurityImpl.java
|
{
"start": 23513,
"end": 25867
}
|
class ____ implements HttpSecurityPolicy {
private final BiPredicate<SecurityIdentity, RoutingContext> predicate;
private SimpleHttpSecurityPolicy(BiPredicate<SecurityIdentity, RoutingContext> predicate) {
this.predicate = predicate;
}
@Override
public Uni<CheckResult> checkPermission(RoutingContext request, Uni<SecurityIdentity> identityUni,
AuthorizationRequestContext requestContext) {
return identityUni.onItemOrFailure()
.transform(new BiFunction<SecurityIdentity, Throwable, CheckResult>() {
@Override
public CheckResult apply(SecurityIdentity securityIdentity, Throwable throwable) {
if (securityIdentity == null) {
// shouldn't be possible happen...
return CheckResult.DENY;
}
if (throwable != null) {
LOG.debug("Failed to retrieve SecurityIdentity, denying access", throwable);
return CheckResult.DENY;
}
boolean deny;
try {
deny = !predicate.test(securityIdentity, request);
} catch (Exception e) {
LOG.debug("Failed to check permission, denying access", e);
deny = true;
}
return deny ? CheckResult.DENY : CheckResult.PERMIT;
}
});
}
}
List<HttpPermissionCarrier> getHttpPermissions() {
return List.copyOf(httpPermissions);
}
RolesMapping getRolesMapping() {
return rolesMapping;
}
List<HttpAuthenticationMechanism> getMechanisms() {
return mechanisms.isEmpty() ? List.of() : List.copyOf(mechanisms);
}
ClientAuth getClientAuth() {
return clientAuth;
}
Optional<String> getHttpServerTlsConfigName() {
return httpServerTlsConfigName;
}
CORSConfig getCorsConfig() {
return corsConfig;
}
CSRF getCsrf() {
return csrf;
}
}
|
SimpleHttpSecurityPolicy
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2505/Issue2505Mapper.java
|
{
"start": 804,
"end": 1030
}
|
class ____ {
private Status status;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
}
|
CustomerDTO
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc4Test.java
|
{
"start": 1209,
"end": 2435
}
|
class ____ {
private String a1;
private String a2;
private String a3;
private String a4;
private String a5;
private String a6;
private List<B> bObj;
@Id
@Column(name = "A1", nullable = false, length = 15)
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
@Basic
@Column(name = "A2", nullable = false, length = 15)
public String getA2() {
return a2;
}
public void setA2(String a2) {
this.a2 = a2;
}
@Basic
@Column(name = "A3", nullable = false, length = 15)
public String getA3() {
return a3;
}
public void setA3(String a3) {
this.a3 = a3;
}
@Id
@Column(name = "A4", nullable = false, length = 15)
public String getA4() {
return a4;
}
public void setA4(String a4) {
this.a4 = a4;
}
@Id
@Column(name = "A5", nullable = false, length = 15)
public String getA5() {
return a5;
}
public void setA5(String a5) {
this.a5 = a5;
}
@Id
@Column(name = "A6", nullable = false, length = 15)
public String getA6() {
return a6;
}
public void setA6(String a6) {
this.a6 = a6;
}
@OneToMany(mappedBy = "aObj")
public List<B> getB() {
return bObj;
}
public void setB(List<B> bObj) {
this.bObj = bObj;
}
}
public static
|
A
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/web/service/registry/HttpServiceGroupAdapter.java
|
{
"start": 1011,
"end": 1542
}
|
interface ____<CB> {
/**
* Create a client builder instance.
*/
CB createClientBuilder();
/**
* Return the type of configurer that is compatible with this group.
*/
Class<? extends HttpServiceGroupConfigurer<CB>> getConfigurerType();
/**
* Use the client builder to create an {@link HttpExchangeAdapter} to use to
* initialize the {@link org.springframework.web.service.invoker.HttpServiceProxyFactory}
* for the group.
*/
HttpExchangeAdapter createExchangeAdapter(CB clientBuilder);
}
|
HttpServiceGroupAdapter
|
java
|
spring-projects__spring-security
|
web/src/main/java/org/springframework/security/web/server/context/NoOpServerSecurityContextRepository.java
|
{
"start": 1056,
"end": 1632
}
|
class ____ implements ServerSecurityContextRepository {
private static final NoOpServerSecurityContextRepository INSTANCE = new NoOpServerSecurityContextRepository();
private NoOpServerSecurityContextRepository() {
}
@Override
public Mono<Void> save(ServerWebExchange exchange, @Nullable SecurityContext context) {
return Mono.empty();
}
@Override
public Mono<SecurityContext> load(ServerWebExchange exchange) {
return Mono.empty();
}
public static NoOpServerSecurityContextRepository getInstance() {
return INSTANCE;
}
}
|
NoOpServerSecurityContextRepository
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/convert/NumberToDataSizeConverter.java
|
{
"start": 1140,
"end": 1702
}
|
class ____ implements GenericConverter {
private final StringToDataSizeConverter delegate = new StringToDataSizeConverter();
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Number.class, DataSize.class));
}
@Override
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
return this.delegate.convert((source != null) ? source.toString() : null, TypeDescriptor.valueOf(String.class),
targetType);
}
}
|
NumberToDataSizeConverter
|
java
|
quarkusio__quarkus
|
test-framework/security-jwt/src/test/java/io/quarkus/test/security/jwt/JwtTestSecurityIdentityAugmentorTest.java
|
{
"start": 634,
"end": 3144
}
|
class ____ {
@Test
@JwtSecurity(claims = {
@Claim(key = "exp", value = "123456789"),
@Claim(key = "iat", value = "123456788"),
@Claim(key = "nbf", value = "123456787"),
@Claim(key = "auth_time", value = "123456786"),
@Claim(key = "customlong", value = "123456785", type = ClaimType.LONG),
@Claim(key = "email", value = "user@gmail.com"),
@Claim(key = "email_verified", value = "true"),
@Claim(key = "email_checked", value = "false", type = ClaimType.BOOLEAN),
@Claim(key = "jsonarray_claim", value = "[\"1\", \"2\"]", type = ClaimType.JSON_ARRAY),
@Claim(key = "jsonobject_claim", value = "{\"a\":\"1\", \"b\":\"2\"}", type = ClaimType.JSON_OBJECT)
})
public void testClaimValues() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new Principal() {
@Override
public String getName() {
return "alice";
}
})
.addRole("user")
.build();
JwtTestSecurityIdentityAugmentor augmentor = new JwtTestSecurityIdentityAugmentor();
Annotation[] annotations = JwtTestSecurityIdentityAugmentorTest.class.getMethod("testClaimValues").getAnnotations();
JsonWebToken jwt = (JsonWebToken) augmentor.augment(identity, annotations).getPrincipal();
assertEquals("alice", jwt.getName());
assertEquals(Set.of("user"), jwt.getGroups());
assertEquals(123456789, jwt.getExpirationTime());
assertEquals(123456788, jwt.getIssuedAtTime());
assertEquals(123456787, (Long) jwt.getClaim(Claims.nbf.name()));
assertEquals(123456786, (Long) jwt.getClaim(Claims.auth_time.name()));
assertEquals(123456785, ((JsonNumber) jwt.getClaim("customlong")).longValue());
assertEquals("user@gmail.com", jwt.getClaim(Claims.email));
assertTrue((Boolean) jwt.getClaim(Claims.email_verified.name()));
assertEquals(JsonValue.FALSE, jwt.getClaim("email_checked"));
JsonArray array = jwt.getClaim("jsonarray_claim");
assertEquals("1", array.getString(0));
assertEquals("2", array.getString(1));
JsonObject map = jwt.getClaim("jsonobject_claim");
assertEquals("1", map.getString("a"));
assertEquals("2", map.getString("b"));
}
}
|
JwtTestSecurityIdentityAugmentorTest
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/api/SoftAssertions.java
|
{
"start": 8123,
"end": 8879
}
|
class ____ extends AbstractSoftAssertions implements StandardSoftAssertionsProvider {
/**
* Convenience method for calling {@link SoftAssertionsProvider#assertSoftly} for these assertion types.
* Equivalent to {@code SoftAssertion.assertSoftly(SoftAssertions.class, softly)}.
* @param softly the Consumer containing the code that will make the soft assertions.
* Takes one parameter (the SoftAssertions instance used to make the assertions).
* @throws MultipleFailuresError if possible or SoftAssertionError if any proxied assertion objects threw an {@link AssertionError}
*/
public static void assertSoftly(Consumer<SoftAssertions> softly) {
SoftAssertionsProvider.assertSoftly(SoftAssertions.class, softly);
}
}
|
SoftAssertions
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.