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 | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableBuffer.java | {
"start": 4288,
"end": 6682
} | class ____<T, U extends Collection<? super T>>
extends AtomicBoolean implements Observer<T>, Disposable {
private static final long serialVersionUID = -8223395059921494546L;
final Observer<? super U> downstream;
final int count;
final int skip;
final Supplier<U> bufferSupplier;
Disposable upstream;
final ArrayDeque<U> buffers;
long index;
BufferSkipObserver(Observer<? super U> actual, int count, int skip, Supplier<U> bufferSupplier) {
this.downstream = actual;
this.count = count;
this.skip = skip;
this.bufferSupplier = bufferSupplier;
this.buffers = new ArrayDeque<>();
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void dispose() {
upstream.dispose();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onNext(T t) {
if (index++ % skip == 0) {
U b;
try {
b = ExceptionHelper.nullCheck(bufferSupplier.get(), "The bufferSupplier returned a null Collection.");
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
buffers.clear();
upstream.dispose();
downstream.onError(e);
return;
}
buffers.offer(b);
}
Iterator<U> it = buffers.iterator();
while (it.hasNext()) {
U b = it.next();
b.add(t);
if (count <= b.size()) {
it.remove();
downstream.onNext(b);
}
}
}
@Override
public void onError(Throwable t) {
buffers.clear();
downstream.onError(t);
}
@Override
public void onComplete() {
while (!buffers.isEmpty()) {
downstream.onNext(buffers.poll());
}
downstream.onComplete();
}
}
}
| BufferSkipObserver |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/unsatisfied/UnsatisfiedMatchNoBeanDefininAnnotationTest.java | {
"start": 387,
"end": 1167
} | class ____ {
@RegisterExtension
ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(FooService.class, Consumer.class)
.shouldFail()
.build();
@Test
public void testExceptionThrown() {
Throwable error = container.getFailure();
assertThat(error).rootCause().isInstanceOf(UnsatisfiedResolutionException.class)
.hasMessageContaining("The following classes match by type, but have been skipped during discovery")
.hasMessageContaining(
"io.quarkus.arc.test.injection.unsatisfied.UnsatisfiedMatchNoBeanDefininAnnotationTest$FooService has no bean defining annotation");
}
@Singleton
static | UnsatisfiedMatchNoBeanDefininAnnotationTest |
java | google__guice | extensions/servlet/test/com/google/inject/servlet/ServletModuleTest.java | {
"start": 3148,
"end": 4082
} | class ____ extends DefaultBindingTargetVisitor<Object, Void>
implements ServletModuleTargetVisitor<Object, Void> {
List<LinkedFilterBinding> linkedFilters = Lists.newArrayList();
List<LinkedServletBinding> linkedServlets = Lists.newArrayList();
List<InstanceFilterBinding> instanceFilters = Lists.newArrayList();
List<InstanceServletBinding> instanceServlets = Lists.newArrayList();
@Override
public Void visit(LinkedFilterBinding binding) {
linkedFilters.add(binding);
return null;
}
@Override
public Void visit(InstanceFilterBinding binding) {
instanceFilters.add(binding);
return null;
}
@Override
public Void visit(LinkedServletBinding binding) {
linkedServlets.add(binding);
return null;
}
@Override
public Void visit(InstanceServletBinding binding) {
instanceServlets.add(binding);
return null;
}
}
}
| Visitor |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/WebhookService.java | {
"start": 8877,
"end": 10593
} | class ____ {
private final Map<String, String> hostTokenMap;
public WebhookAccount(Settings settings) {
SecureString validTokenHosts = SETTING_WEBHOOK_HOST_TOKEN_PAIRS.get(settings);
if (Strings.hasText(validTokenHosts)) {
Set<String> hostAndTokens = Strings.commaDelimitedListToSet(validTokenHosts.toString());
Map<String, String> hostAndPortToToken = new HashMap<>(hostAndTokens.size());
for (String hostPortToken : hostAndTokens) {
int equalsIndex = hostPortToken.indexOf('=');
if (equalsIndex == -1) {
// This is an invalid format, and we can skip this token
break;
}
if (equalsIndex + 1 == hostPortToken.length()) {
// This is also invalid, because it ends in a trailing =
break;
}
// The first part becomes the <host>:<port> pair
String hostAndPort = hostPortToken.substring(0, equalsIndex);
// The second part after the '=' is the <token>
String token = hostPortToken.substring(equalsIndex + 1);
hostAndPortToToken.put(hostAndPort, token);
}
this.hostTokenMap = Collections.unmodifiableMap(hostAndPortToToken);
} else {
this.hostTokenMap = Map.of();
}
}
@Override
public String toString() {
return "WebhookAccount[" + this.hostTokenMap.keySet().stream().map(s -> s + "=********") + "]";
}
}
}
| WebhookAccount |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/core/authority/mapping/SimpleAttributes2GrantedAuthoritiesMapper.java | {
"start": 1104,
"end": 1484
} | interface ____ doing a
* one-to-one mapping from roles to Spring Security GrantedAuthorities. Optionally a
* prefix can be added, and the attribute name can be converted to upper or lower case.
* <p>
* By default, the attribute is prefixed with "ROLE_" unless it already starts with
* "ROLE_", and no case conversion is done.
*
* @author Ruud Senden
* @since 2.0
*/
public | by |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/authentication/ott/JdbcOneTimeTokenServiceTests.java | {
"start": 1579,
"end": 6903
} | class ____ {
private static final String USERNAME = "user";
private static final String TOKEN_VALUE = "1234";
private static final String ONE_TIME_TOKEN_SQL_RESOURCE = "org/springframework/security/core/ott/jdbc/one-time-tokens-schema.sql";
private EmbeddedDatabase db;
private JdbcOperations jdbcOperations;
private JdbcOneTimeTokenService oneTimeTokenService;
@BeforeEach
void setUp() {
this.db = createDb();
this.jdbcOperations = new JdbcTemplate(this.db);
this.oneTimeTokenService = new JdbcOneTimeTokenService(this.jdbcOperations);
}
@AfterEach
void tearDown() throws Exception {
this.db.shutdown();
this.oneTimeTokenService.destroy();
}
private static EmbeddedDatabase createDb() {
// @formatter:off
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL)
.setScriptEncoding("UTF-8")
.addScript(ONE_TIME_TOKEN_SQL_RESOURCE)
.build();
// @formatter:on
}
@Test
void constructorWhenJdbcOperationsIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcOneTimeTokenService(null))
.withMessage("jdbcOperations cannot be null");
// @formatter:on
}
@Test
void generateWhenGenerateOneTimeTokenRequestIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.oneTimeTokenService.generate(null))
.withMessage("generateOneTimeTokenRequest cannot be null");
// @formatter:on
}
@Test
void consumeWhenAuthenticationTokenIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.oneTimeTokenService.consume(null))
.withMessage("authenticationToken cannot be null");
// @formatter:on
}
@Test
void generateThenTokenValueShouldBeValidUuidAndProvidedUsernameIsUsed() {
OneTimeToken oneTimeToken = this.oneTimeTokenService.generate(new GenerateOneTimeTokenRequest(USERNAME));
OneTimeToken persistedOneTimeToken = this.oneTimeTokenService
.consume(new OneTimeTokenAuthenticationToken(oneTimeToken.getTokenValue()));
assertThat(persistedOneTimeToken).isNotNull();
assertThat(persistedOneTimeToken.getUsername()).isNotNull();
assertThat(persistedOneTimeToken.getTokenValue()).isNotNull();
assertThat(persistedOneTimeToken.getExpiresAt()).isNotNull();
}
@Test
void consumeWhenTokenExistsThenReturnItself() {
OneTimeToken oneTimeToken = this.oneTimeTokenService.generate(new GenerateOneTimeTokenRequest(USERNAME));
OneTimeTokenAuthenticationToken authenticationToken = new OneTimeTokenAuthenticationToken(
oneTimeToken.getTokenValue());
OneTimeToken consumedOneTimeToken = this.oneTimeTokenService.consume(authenticationToken);
assertThat(consumedOneTimeToken).isNotNull();
assertThat(consumedOneTimeToken.getUsername()).isNotNull();
assertThat(consumedOneTimeToken.getTokenValue()).isNotNull();
assertThat(consumedOneTimeToken.getExpiresAt()).isNotNull();
OneTimeToken persistedOneTimeToken = this.oneTimeTokenService
.consume(new OneTimeTokenAuthenticationToken(consumedOneTimeToken.getTokenValue()));
assertThat(persistedOneTimeToken).isNull();
}
@Test
void consumeWhenTokenDoesNotExistsThenReturnNull() {
OneTimeTokenAuthenticationToken authenticationToken = new OneTimeTokenAuthenticationToken(TOKEN_VALUE);
OneTimeToken consumedOneTimeToken = this.oneTimeTokenService.consume(authenticationToken);
assertThat(consumedOneTimeToken).isNull();
}
@Test
void consumeWhenTokenIsExpiredThenReturnNull() {
GenerateOneTimeTokenRequest request = new GenerateOneTimeTokenRequest(USERNAME);
OneTimeToken generated = this.oneTimeTokenService.generate(request);
OneTimeTokenAuthenticationToken authenticationToken = new OneTimeTokenAuthenticationToken(
generated.getTokenValue());
Clock tenMinutesFromNow = Clock.fixed(Instant.now().plus(10, ChronoUnit.MINUTES), ZoneOffset.UTC);
this.oneTimeTokenService.setClock(tenMinutesFromNow);
OneTimeToken consumed = this.oneTimeTokenService.consume(authenticationToken);
assertThat(consumed).isNull();
}
@Test
void cleanupExpiredTokens() {
Clock clock = mock(Clock.class);
Instant tenMinutesAgo = Instant.now().minus(Duration.ofMinutes(10));
given(clock.instant()).willReturn(tenMinutesAgo);
this.oneTimeTokenService.setClock(clock);
OneTimeToken token1 = this.oneTimeTokenService.generate(new GenerateOneTimeTokenRequest(USERNAME));
OneTimeToken token2 = this.oneTimeTokenService.generate(new GenerateOneTimeTokenRequest(USERNAME));
this.oneTimeTokenService.cleanupExpiredTokens();
OneTimeToken deletedOneTimeToken1 = this.oneTimeTokenService
.consume(new OneTimeTokenAuthenticationToken(token1.getTokenValue()));
OneTimeToken deletedOneTimeToken2 = this.oneTimeTokenService
.consume(new OneTimeTokenAuthenticationToken(token2.getTokenValue()));
assertThat(deletedOneTimeToken1).isNull();
assertThat(deletedOneTimeToken2).isNull();
}
@Test
void setCleanupChronWhenNullThenNoException() {
this.oneTimeTokenService.setCleanupCron(null);
}
@Test
void setCleanupChronWhenAlreadyNullThenNoException() {
this.oneTimeTokenService.setCleanupCron(null);
this.oneTimeTokenService.setCleanupCron(null);
}
}
| JdbcOneTimeTokenServiceTests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/basic/InterceptedMethodInvokerTest.java | {
"start": 934,
"end": 2163
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(MyService.class, MyInterceptorBinding.class, MyInterceptor.class)
.beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> {
MethodInfo method = bean.getImplClazz().firstMethod("hello");
invokers.put(method.name(), factory.createInvoker(bean, method).build());
}))
.build();
@Test
public void test() throws Exception {
InvokerHelper helper = Arc.container().instance(InvokerHelper.class).get();
InstanceHandle<MyService> service = Arc.container().instance(MyService.class);
Invoker<MyService, String> hello = helper.getInvoker("hello");
assertEquals("intercepted: foobar0[a]", hello.invoke(service.get(), new Object[] { 0, List.of("a") }));
// not a contextual reference, not intercepted
assertEquals("foobar1[b]", hello.invoke(new MyService(), new Object[] { 1, List.of("b") }));
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@InterceptorBinding
public @ | InterceptedMethodInvokerTest |
java | elastic__elasticsearch | x-pack/plugin/security/cli/src/main/java/org/elasticsearch/xpack/security/cli/HttpCertificateCommand.java | {
"start": 64653,
"end": 64722
} | class ____ close correctly for a single entry
*/
private | handles |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/resource/EpollProvider.java | {
"start": 3957,
"end": 5155
} | class ____ and supported by your operating system.");
}
/**
* Returns the {@link EventLoopResources} for epoll-backed transport. Check availability with {@link #isAvailable()} prior
* to obtaining the resources.
*
* @return the {@link EventLoopResources}. May be unavailable.
*
* @since 6.0
*/
public static EventLoopResources getResources() {
return EPOLL_RESOURCES;
}
/**
* Apply Keep-Alive options.
*
* @since 6.1
*/
public static void applyKeepAlive(Bootstrap bootstrap, int count, Duration idle, Duration interval) {
bootstrap.option(EpollChannelOption.TCP_KEEPCNT, count);
bootstrap.option(EpollChannelOption.TCP_KEEPIDLE, Math.toIntExact(idle.getSeconds()));
bootstrap.option(EpollChannelOption.TCP_KEEPINTVL, Math.toIntExact(interval.getSeconds()));
}
/**
* Apply TcpUserTimeout options.
*/
public static void applyTcpUserTimeout(Bootstrap bootstrap, Duration timeout) {
bootstrap.option(EpollChannelOption.TCP_USER_TIMEOUT, Math.toIntExact(timeout.toMillis()));
}
/**
* {@link EventLoopResources} for available Epoll.
*/
| path |
java | apache__dubbo | dubbo-demo/dubbo-demo-spring-boot-idl/dubbo-demo-spring-boot-idl-provider/src/main/java/org/apache/dubbo/springboot/idl/demo/provider/GreeterServiceImpl.java | {
"start": 1281,
"end": 2771
} | class ____ implements GreeterService {
private static final Logger LOGGER = LoggerFactory.getLogger(GreeterServiceImpl.class);
@Override
public HelloReply sayHello(HelloRequest request) {
LOGGER.info("Received sayHello request: {}", request.getName());
return toReply("Hello " + request.getName());
}
@Override
public CompletableFuture<HelloReply> sayHelloAsync(HelloRequest request) {
LOGGER.info("Received sayHelloAsync request: {}", request.getName());
HelloReply.newBuilder().setMessage("Hello " + request.getName());
return CompletableFuture.supplyAsync(() ->
HelloReply.newBuilder().setMessage("Hello " + request.getName()).build());
}
@Override
public void sayHelloStream(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
LOGGER.info("Received sayHelloStream request: {}", request.getName());
for (int i = 0; i < 5; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
responseObserver.onError(e);
}
responseObserver.onNext(HelloReply.newBuilder()
.setMessage(i + "# Hello " + request.getName())
.build());
}
responseObserver.onCompleted();
}
private static HelloReply toReply(String message) {
return HelloReply.newBuilder().setMessage(message).build();
}
}
| GreeterServiceImpl |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/console/subpackage/ContainerForInnerTests.java | {
"start": 538,
"end": 693
} | class ____ be named *Tests in order
// for ConsoleLauncherIntegrationTests to pass, but that's not a
// problem since the test method here can never fail.
| must |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/TestVisibleTypeId.java | {
"start": 1943,
"end": 2193
} | class ____ {
public int a = 3;
@JsonTypeId
public String type = "SomeType";
}
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_ARRAY,
property="type")
static | TypeIdFromFieldProperty |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/creation/CommonBuilder.java | {
"start": 730,
"end": 6616
} | interface ____ {
/// Open the session using the specified options.
SharedSessionContract open();
/// Adds a specific connection to be used to the session options.
///
/// @param connection The connection to use.
/// @return {@code this}, for method chaining
CommonBuilder connection(Connection connection);
/// Specifies the connection handling modes for the session.
///
/// @apiNote If [ConnectionAcquisitionMode#IMMEDIATELY] is specified,
/// then the release mode must be [ConnectionReleaseMode#ON_CLOSE].
///
/// @return `this`, for method chaining
///
/// @since 7.0
CommonBuilder connectionHandling(ConnectionAcquisitionMode acquisitionMode, ConnectionReleaseMode releaseMode);
/// Adds a specific interceptor to the session options.
///
/// @param interceptor The interceptor to use.
/// @return `this`, for method chaining
CommonBuilder interceptor(Interceptor interceptor);
/// Specifies that no {@link Interceptor} should be used. This indicates to
/// ignore both (if either) the [interceptor][org.hibernate.cfg.SessionEventSettings#INTERCEPTOR]
/// and [session-scoped interceptor][org.hibernate.cfg.SessionEventSettings#SESSION_SCOPED_INTERCEPTOR]
/// associated with the `SessionFactory`
///
/// @return `this`, for method chaining
///
/// @apiNote Calling [#interceptor(Interceptor)] with `null` has the same effect
CommonBuilder noInterceptor();
/// Specifies that no [session-scoped interceptor][org.hibernate.cfg.SessionEventSettings#SESSION_SCOPED_INTERCEPTOR]
/// should be used for the session. If the `SessionFactory` has a configured
/// [interceptor][org.hibernate.cfg.SessionEventSettings#INTERCEPTOR], it will still be used.
///
/// @return `this`, for method chaining
///
/// @see #noInterceptor
///
/// @apiNote Unlike [#noInterceptor], this operation does not disable use of an
/// [interceptor][org.hibernate.cfg.SessionEventSettings#INTERCEPTOR] associated with the `SessionFactory`.
///
/// @since 7.2
CommonBuilder noSessionInterceptorCreation();
/// Applies the given statement inspection function to the session.
///
/// @param operator An operator which accepts a SQL string, returning
/// a processed SQL string to be used by Hibernate instead. The
/// operator may simply (and usually) return the original SQL.
///
/// @return `this`, for method chaining
CommonBuilder statementInspector(UnaryOperator<String> operator);
/// Signifies that no SQL statement inspector should be used.
///
/// By default, if no inspector is explicitly specified, the
/// inspector associated with the {@link org.hibernate.SessionFactory}, if one, is
/// inherited by the new session.
///
/// @return `this`, for method chaining
///
/// @apiNote Calling [#statementInspector] with `null` has the same effect.
CommonBuilder noStatementInspector();
/// Specify the tenant identifier to be associated with the opened session.
///
/// ```java
/// try (var session = sessionFactory.withOptions()
/// .tenantIdentifier(tenantId)
/// .openSession()) {
/// ...
/// }
/// ```
/// @param tenantIdentifier The tenant identifier.
///
/// @return `this`, for method chaining
CommonBuilder tenantIdentifier(Object tenantIdentifier);
/// Specify a [read-only mode][Session#isDefaultReadOnly]
/// for the session. If a session is created in read-only mode, then
/// [Connection#setReadOnly] is called when a JDBC connection is obtained.
///
/// Furthermore, if read/write replication is in use, then:
/// * a read-only session will connect to a read-only replica, but
/// * a non-read-only session will connect to a writable replica.
///
/// When read/write replication is in use, it's strongly recommended
/// that the session be created with the [initial cache-mode][#initialCacheMode]
/// set to [CacheMode#GET], to avoid writing stale data read from a read-only
/// replica to the second-level cache. Hibernate cannot possibly guarantee that
/// data read from a read-only replica is up to date.
///
/// When read/write replication is in use, it's possible that an item
/// read from the second-level cache might refer to data which does not
/// yet exist in the read-only replica. In this situation, an exception
/// occurs when the association is fetched. To completely avoid this
/// possibility, the [initial cache-mode][#initialCacheMode] must be
/// set to [CacheMode#IGNORE]. However, it's also usually possible to
/// structure data access code in a way which eliminates this possibility.
/// ```java
/// try (var readOnlySession =
/// sessionFactory.withOptions()
/// .readOnly(true)
/// .initialCacheMode(CacheMode.IGNORE)
/// .openSession()) {
/// ...
/// }
/// ```
///
/// If a session is created in read-only mode, then it cannot be
/// changed to read-write mode, and any call to [Session#setDefaultReadOnly(boolean)]
/// with fail. On the other hand, if a session is created in read-write mode, then it
/// may later be switched to read-only mode, but all database access is directed to
/// the writable replica.
///
/// @return `this`, for method chaining
///
/// @see org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider#getReadOnlyConnection(Object)
/// @see org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider#releaseReadOnlyConnection(Object, Connection)
///
/// @since 7.2
@Incubating
CommonBuilder readOnly(boolean readOnly);
/// Specify the initial [CacheMode] for the session.
///
/// @return `this`, for method chaining
///
/// @see SharedSessionContract#getCacheMode()
///
/// @since 7.2
CommonBuilder initialCacheMode(CacheMode cacheMode);
/// Specify the [JDBC time zone][org.hibernate.cfg.JdbcSettings#JDBC_TIME_ZONE]
/// to use for the session.
///
/// @return `this`, for method chaining
CommonBuilder jdbcTimeZone(TimeZone timeZone);
}
| CommonBuilder |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSQLParserTest.java | {
"start": 918,
"end": 2198
} | class ____ extends TestCase {
public void test_1() throws Exception {
String sql = "SELECT employees_seq.nextval FROM DUAL;";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
assertEquals(1, statementList.size());
String text = output(statementList);
System.out.println(text);
}
public void test_2() throws Exception {
String sql = "SELECT LPAD(' ',2*(LEVEL-1)) || last_name org_chart, employee_id, manager_id, job_id FROM employees WHERE job_id != 'FI_MGR' START WITH job_id = 'AD_VP' CONNECT BY PRIOR employee_id = manager_id; ";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
assertEquals(1, statementList.size());
String text = output(statementList);
System.out.println(text);
}
private String output(List<SQLStatement> stmtList) {
StringBuilder out = new StringBuilder();
OracleOutputVisitor visitor = new OracleOutputVisitor(out);
for (SQLStatement stmt : stmtList) {
stmt.accept(visitor);
}
return out.toString();
}
}
| OracleSQLParserTest |
java | alibaba__nacos | ai/src/main/java/com/alibaba/nacos/ai/enums/McpImportResultStatusEnum.java | {
"start": 717,
"end": 1088
} | enum ____ {
/**
* SKIPPED.
*/
SKIPPED("skipped"),
/**
* FAILED.
*/
FAILED("failed"),
/**
* SUCCESS.
*/
SUCCESS("success");
private final String name;
McpImportResultStatusEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| McpImportResultStatusEnum |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/shuffle/ShuffleUtils.java | {
"start": 945,
"end": 1202
} | class ____ {
private ShuffleUtils() {}
/**
* Apply different functions to known and unknown {@link ShuffleDescriptor}s.
*
* <p>Also casts known {@link ShuffleDescriptor}.
*
* @param shuffleDescriptorClass concrete | ShuffleUtils |
java | quarkusio__quarkus | independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/update/ExtensionMapBuilder.java | {
"start": 376,
"end": 1914
} | class ____ {
final Map<String, List<ExtensionUpdateInfoBuilder>> extensionInfo;
final List<ExtensionUpdateInfoBuilder> list = new ArrayList<>();
public ExtensionMapBuilder() {
this.extensionInfo = new LinkedHashMap<>();
}
public ExtensionMapBuilder(int size) {
this.extensionInfo = new LinkedHashMap<>(size);
}
public void add(ExtensionUpdateInfoBuilder e) {
extensionInfo.put(e.currentDep.getArtifact().getArtifactId(), Collections.singletonList(e));
list.add(e);
}
public ExtensionUpdateInfoBuilder get(ArtifactKey key) {
final List<ExtensionUpdateInfoBuilder> list = extensionInfo.get(key.getArtifactId());
if (list == null || list.isEmpty()) {
return null;
}
if (list.size() == 1) {
return list.get(0);
}
for (ExtensionUpdateInfoBuilder e : list) {
final TopExtensionDependency recommendedDep = e.resolveRecommendedDep();
if (e.currentDep.getKey().equals(key)
|| recommendedDep != null && recommendedDep.getKey().equals(key)) {
return e;
}
}
throw new IllegalArgumentException(key + " isn't found in the extension map");
}
public Collection<ExtensionUpdateInfoBuilder> values() {
return list;
}
public int size() {
return extensionInfo.size();
}
public boolean isEmpty() {
return extensionInfo.isEmpty();
}
public static final | ExtensionMapBuilder |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/TransactionCoordinatorFencedException.java | {
"start": 847,
"end": 1190
} | class ____ extends ApiException {
private static final long serialVersionUID = 1L;
public TransactionCoordinatorFencedException(String message) {
super(message);
}
public TransactionCoordinatorFencedException(String message, Throwable cause) {
super(message, cause);
}
}
| TransactionCoordinatorFencedException |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest3.java | {
"start": 1340,
"end": 1938
} | class ____ {
private final int id;
private final String name;
private final Entity obj;
@JSONCreator
public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name,
@JSONField(name = "obj") Entity obj){
this.id = id;
this.name = name;
this.obj = obj;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Entity getObj() {
return obj;
}
}
}
| Entity |
java | apache__camel | components/camel-digitalocean/src/generated/java/org/apache/camel/component/digitalocean/DigitalOceanEndpointConfigurer.java | {
"start": 739,
"end": 5301
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
DigitalOceanEndpoint target = (DigitalOceanEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "digitaloceanclient":
case "digitalOceanClient": target.getConfiguration().setDigitalOceanClient(property(camelContext, com.myjeeva.digitalocean.impl.DigitalOceanClient.class, value)); return true;
case "httpproxyhost":
case "httpProxyHost": target.getConfiguration().setHttpProxyHost(property(camelContext, java.lang.String.class, value)); return true;
case "httpproxypassword":
case "httpProxyPassword": target.getConfiguration().setHttpProxyPassword(property(camelContext, java.lang.String.class, value)); return true;
case "httpproxyport":
case "httpProxyPort": target.getConfiguration().setHttpProxyPort(property(camelContext, java.lang.Integer.class, value)); return true;
case "httpproxyuser":
case "httpProxyUser": target.getConfiguration().setHttpProxyUser(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "oauthtoken":
case "oAuthToken": target.getConfiguration().setOAuthToken(property(camelContext, java.lang.String.class, value)); return true;
case "page": target.getConfiguration().setPage(property(camelContext, java.lang.Integer.class, value)); return true;
case "perpage":
case "perPage": target.getConfiguration().setPerPage(property(camelContext, java.lang.Integer.class, value)); return true;
case "resource": target.getConfiguration().setResource(property(camelContext, org.apache.camel.component.digitalocean.constants.DigitalOceanResources.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "digitaloceanclient":
case "digitalOceanClient": return com.myjeeva.digitalocean.impl.DigitalOceanClient.class;
case "httpproxyhost":
case "httpProxyHost": return java.lang.String.class;
case "httpproxypassword":
case "httpProxyPassword": return java.lang.String.class;
case "httpproxyport":
case "httpProxyPort": return java.lang.Integer.class;
case "httpproxyuser":
case "httpProxyUser": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "oauthtoken":
case "oAuthToken": return java.lang.String.class;
case "page": return java.lang.Integer.class;
case "perpage":
case "perPage": return java.lang.Integer.class;
case "resource": return org.apache.camel.component.digitalocean.constants.DigitalOceanResources.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
DigitalOceanEndpoint target = (DigitalOceanEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "digitaloceanclient":
case "digitalOceanClient": return target.getConfiguration().getDigitalOceanClient();
case "httpproxyhost":
case "httpProxyHost": return target.getConfiguration().getHttpProxyHost();
case "httpproxypassword":
case "httpProxyPassword": return target.getConfiguration().getHttpProxyPassword();
case "httpproxyport":
case "httpProxyPort": return target.getConfiguration().getHttpProxyPort();
case "httpproxyuser":
case "httpProxyUser": return target.getConfiguration().getHttpProxyUser();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "oauthtoken":
case "oAuthToken": return target.getConfiguration().getOAuthToken();
case "page": return target.getConfiguration().getPage();
case "perpage":
case "perPage": return target.getConfiguration().getPerPage();
case "resource": return target.getConfiguration().getResource();
default: return null;
}
}
}
| DigitalOceanEndpointConfigurer |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/search/rank/FieldBasedRerankerIT.java | {
"start": 3216,
"end": 10552
} | class ____ extends RankBuilder {
public static final ParseField FIELD_FIELD = new ParseField("field");
static final ConstructingObjectParser<FieldBasedRankBuilder, Void> PARSER = new ConstructingObjectParser<>(
"field_based_rank",
args -> {
int rankWindowSize = args[0] == null ? DEFAULT_RANK_WINDOW_SIZE : (int) args[0];
String field = (String) args[1];
if (field == null || field.isEmpty()) {
throw new IllegalArgumentException("Field cannot be null or empty");
}
return new FieldBasedRankBuilder(rankWindowSize, field);
}
);
static {
PARSER.declareInt(optionalConstructorArg(), RANK_WINDOW_SIZE_FIELD);
PARSER.declareString(constructorArg(), FIELD_FIELD);
}
protected final String field;
public static FieldBasedRankBuilder fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
public FieldBasedRankBuilder(final int rankWindowSize, final String field) {
super(rankWindowSize);
this.field = field;
}
public FieldBasedRankBuilder(StreamInput in) throws IOException {
super(in);
this.field = in.readString();
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeString(field);
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(FIELD_FIELD.getPreferredName(), field);
}
@Override
public boolean isCompoundBuilder() {
return false;
}
@Override
public Explanation explainHit(Explanation baseExplanation, RankDoc scoreDoc, List<String> queryNames) {
return baseExplanation;
}
@Override
public QueryPhaseRankShardContext buildQueryPhaseShardContext(List<Query> queries, int from) {
return new QueryPhaseRankShardContext(queries, rankWindowSize()) {
@Override
public RankShardResult combineQueryPhaseResults(List<TopDocs> rankResults) {
Map<Integer, RankFeatureDoc> rankDocs = new HashMap<>();
rankResults.forEach(topDocs -> {
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
rankDocs.compute(scoreDoc.doc, (key, value) -> {
if (value == null) {
return new RankFeatureDoc(scoreDoc.doc, scoreDoc.score, scoreDoc.shardIndex);
} else {
value.score = Math.max(scoreDoc.score, rankDocs.get(scoreDoc.doc).score);
return value;
}
});
}
});
RankFeatureDoc[] sortedResults = rankDocs.values().toArray(RankFeatureDoc[]::new);
Arrays.sort(sortedResults, (o1, o2) -> Float.compare(o2.score, o1.score));
return new RankFeatureShardResult(sortedResults);
}
};
}
@Override
public QueryPhaseRankCoordinatorContext buildQueryPhaseCoordinatorContext(int size, int from) {
return new QueryPhaseRankCoordinatorContext(rankWindowSize()) {
@Override
public ScoreDoc[] rankQueryPhaseResults(
List<QuerySearchResult> querySearchResults,
SearchPhaseController.TopDocsStats topDocStats
) {
List<RankFeatureDoc> rankDocs = new ArrayList<>();
for (int i = 0; i < querySearchResults.size(); i++) {
QuerySearchResult querySearchResult = querySearchResults.get(i);
RankFeatureShardResult shardResult = (RankFeatureShardResult) querySearchResult.getRankShardResult();
for (RankFeatureDoc frd : shardResult.rankFeatureDocs) {
frd.shardIndex = i;
rankDocs.add(frd);
}
}
// no support for sort field atm
// should pass needed info to make use of org.elasticsearch.action.search.SearchPhaseController.sortDocs?
rankDocs.sort(Comparator.comparing((RankFeatureDoc doc) -> doc.score).reversed());
RankFeatureDoc[] topResults = rankDocs.stream().limit(rankWindowSize).toArray(RankFeatureDoc[]::new);
assert topDocStats.fetchHits == 0;
topDocStats.fetchHits = topResults.length;
return topResults;
}
};
}
@Override
public RankFeaturePhaseRankShardContext buildRankFeaturePhaseShardContext() {
return new RankFeaturePhaseRankShardContext(field) {
@Override
public RankShardResult buildRankFeatureShardResult(SearchHits hits, int shardId) {
try {
RankFeatureDoc[] rankFeatureDocs = new RankFeatureDoc[hits.getHits().length];
for (int i = 0; i < hits.getHits().length; i++) {
rankFeatureDocs[i] = new RankFeatureDoc(hits.getHits()[i].docId(), hits.getHits()[i].getScore(), shardId);
rankFeatureDocs[i].featureData(List.of(hits.getHits()[i].field(field).getValue().toString()));
}
return new RankFeatureShardResult(rankFeatureDocs);
} catch (Exception ex) {
throw ex;
}
}
};
}
@Override
public RankFeaturePhaseRankCoordinatorContext buildRankFeaturePhaseCoordinatorContext(int size, int from, Client client) {
return new RankFeaturePhaseRankCoordinatorContext(size, from, rankWindowSize(), false) {
@Override
protected void computeScores(RankFeatureDoc[] featureDocs, ActionListener<float[]> scoreListener) {
float[] scores = new float[featureDocs.length];
for (int i = 0; i < featureDocs.length; i++) {
scores[i] = Float.parseFloat(featureDocs[i].featureData.get(0));
}
scoreListener.onResponse(scores);
}
};
}
@Override
protected boolean doEquals(RankBuilder other) {
return other instanceof FieldBasedRankBuilder && Objects.equals(field, ((FieldBasedRankBuilder) other).field);
}
@Override
protected int doHashCode() {
return Objects.hash(field);
}
@Override
public String getWriteableName() {
return "field_based_rank";
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_15_0;
}
}
public static | FieldBasedRankBuilder |
java | google__error-prone | core/src/test/java/com/google/errorprone/scanner/ScannerSupplierTest.java | {
"start": 25715,
"end": 26703
} | class ____ extends Subject {
private final ScannerSupplier actual;
ScannerSupplierSubject(FailureMetadata failureMetadata, ScannerSupplier scannerSupplier) {
super(failureMetadata, scannerSupplier);
this.actual = scannerSupplier;
}
final void hasSeverities(Map<String, SeverityLevel> severities) {
check("severities()").that(actual.severities()).containsExactlyEntriesIn(severities);
}
@SafeVarargs
final void hasEnabledChecks(Class<? extends BugChecker>... bugCheckers) {
check("getEnabledChecks()")
.that(actual.getEnabledChecks())
.containsExactlyElementsIn(getSuppliers(bugCheckers));
}
final MapSubject flagsMap() {
return check("getFlags().getFlagsMap()").that(actual.getFlags().getFlagsMap());
}
}
/** A check missing `@Inject`. */
@SuppressWarnings("InjectOnBugCheckers") // intentional for testing
@BugPattern(summary = "", severity = ERROR)
public static | ScannerSupplierSubject |
java | apache__flink | flink-table/flink-sql-parser/src/main/java/org/apache/calcite/sql/fun/SqlJsonQueryFunction.java | {
"start": 1919,
"end": 2100
} | class ____ copied over from Calcite to support RETURNING clause in JSON_QUERY
* (CALCITE-6365). When upgrading to Calcite 1.38.0 version, please remove the entire class.
*/
public | was |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/NativeJpaQuery.java | {
"start": 1684,
"end": 4726
} | class ____ extends AbstractStringBasedJpaQuery {
private final @Nullable String sqlResultSetMapping;
private final boolean queryForEntity;
/**
* Creates a new {@link NativeJpaQuery} encapsulating the query annotated on the given {@link JpaQueryMethod}.
*
* @param method must not be {@literal null}.
* @param em must not be {@literal null}.
* @param queryString must not be {@literal null} or empty.
* @param countQueryString must not be {@literal null} or empty.
* @param queryConfiguration must not be {@literal null}.
*/
NativeJpaQuery(JpaQueryMethod method, EntityManager em, String queryString, @Nullable String countQueryString,
JpaQueryConfiguration queryConfiguration) {
super(method, em, queryString, countQueryString, queryConfiguration);
MergedAnnotations annotations = MergedAnnotations.from(method.getMethod());
MergedAnnotation<NativeQuery> annotation = annotations.get(NativeQuery.class);
this.sqlResultSetMapping = annotation.isPresent() ? annotation.getString("sqlResultSetMapping") : null;
this.queryForEntity = getQueryMethod().isQueryForEntity();
}
/**
* Creates a new {@link NativeJpaQuery} encapsulating the query annotated on the given {@link JpaQueryMethod}.
*
* @param method must not be {@literal null}.
* @param em must not be {@literal null}.
* @param query must not be {@literal null} .
* @param countQuery can be {@literal null} if not defined.
* @param queryConfiguration must not be {@literal null}.
*/
public NativeJpaQuery(JpaQueryMethod method, EntityManager em, DeclaredQuery query,
@Nullable DeclaredQuery countQuery, JpaQueryConfiguration queryConfiguration) {
super(method, em, query, countQuery, queryConfiguration);
MergedAnnotations annotations = MergedAnnotations.from(method.getMethod());
MergedAnnotation<NativeQuery> annotation = annotations.get(NativeQuery.class);
this.sqlResultSetMapping = annotation.isPresent() ? annotation.getString("sqlResultSetMapping") : null;
this.queryForEntity = getQueryMethod().isQueryForEntity();
}
@Override
protected Query createJpaQuery(QueryProvider declaredQuery, Sort sort, @Nullable Pageable pageable,
ReturnedType returnedType) {
EntityManager em = getEntityManager();
String query = potentiallyRewriteQuery(declaredQuery.getQueryString(), sort, pageable);
if (!ObjectUtils.isEmpty(sqlResultSetMapping)) {
return em.createNativeQuery(query, sqlResultSetMapping);
}
Class<?> type = getTypeToQueryFor(returnedType);
return type == null ? em.createNativeQuery(query) : em.createNativeQuery(query, type);
}
private @Nullable Class<?> getTypeToQueryFor(ReturnedType returnedType) {
Class<?> result = queryForEntity ? returnedType.getDomainType() : null;
if (getQuery().hasConstructorExpression() || getQuery().isDefaultProjection()) {
return result;
}
if (returnedType.isProjecting()) {
if (returnedType.isInterfaceProjection()) {
return Tuple.class;
}
return returnedType.getReturnedType();
}
return result;
}
}
| NativeJpaQuery |
java | netty__netty | resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverChannelStrategy.java | {
"start": 773,
"end": 1496
} | enum ____ {
/**
* Use the same underlying {@link io.netty.channel.Channel} for all queries produced by a single
{@link DnsNameResolver} instance.
*/
ChannelPerResolver,
/**
* Use a new {@link io.netty.channel.Channel} per resolution or per explicit query. As of today this is similar
* to what the {@link io.netty.resolver.DefaultNameResolver} (JDK default) does. As we will need to open and close
* a new socket for each resolution it will come with a performance overhead. That said using this strategy should
* be the most robust and also guard against problems that can arise in kubernetes (or similar) setups.
*/
ChannelPerResolution
}
| DnsNameResolverChannelStrategy |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/stateless/EagerCollectionInStatelessTest.java | {
"start": 2042,
"end": 2230
} | class ____ {
@Id long id = 69L;
@ElementCollection(fetch = EAGER)
Set<String> eager = new HashSet<>();
@ElementCollection
Set<String> lazy = new HashSet<>();
}
}
| WithEagerCollection |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/master/AcknowledgedTransportMasterNodeAction.java | {
"start": 837,
"end": 974
} | class ____ the common case of a {@link TransportMasterNodeAction} that responds with an {@link AcknowledgedResponse}.
*/
public abstract | for |
java | quarkusio__quarkus | extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/cdi/WithSpanInterceptor.java | {
"start": 9684,
"end": 10347
} | class ____ implements SpanNameExtractor<MethodRequest> {
@Override
public String extract(final MethodRequest methodRequest) {
String spanName = null;
for (Annotation annotation : methodRequest.getAnnotationBindings()) {
if (annotation instanceof WithSpan) {
spanName = ((WithSpan) annotation).value();
break;
}
}
if (spanName.isEmpty()) {
spanName = SpanNames.fromMethod(methodRequest.getMethod());
}
return spanName;
}
}
private static final | MethodRequestSpanNameExtractor |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/StackId.java | {
"start": 1019,
"end": 2563
} | class ____ {
private static final String LABEL_NAME = "io.buildpacks.stack.id";
private final @Nullable String value;
StackId(@Nullable String value) {
this.value = value;
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return Objects.equals(this.value, ((StackId) obj).value);
}
boolean hasId() {
return this.value != null;
}
@Override
public int hashCode() {
return Objects.hashCode(this.value);
}
@Override
public String toString() {
return (this.value != null) ? this.value : "<null>";
}
/**
* Factory method to create a {@link StackId} from an {@link Image}.
* @param image the source image
* @return the extracted stack ID
*/
static StackId fromImage(Image image) {
Assert.notNull(image, "'image' must not be null");
return fromImageConfig(image.getConfig());
}
/**
* Factory method to create a {@link StackId} from an {@link ImageConfig}.
* @param imageConfig the source image config
* @return the extracted stack ID
*/
private static StackId fromImageConfig(ImageConfig imageConfig) {
String value = imageConfig.getLabels().get(LABEL_NAME);
return new StackId(value);
}
/**
* Factory method to create a {@link StackId} with a given value.
* @param value the stack ID value
* @return a new stack ID instance
*/
static StackId of(String value) {
Assert.hasText(value, "'value' must not be empty");
return new StackId(value);
}
}
| StackId |
java | google__dagger | javatests/dagger/internal/codegen/ComponentCreatorTest.java | {
"start": 16206,
"end": 16299
} | class ____ {",
" @Component.Builder",
" static abstract | SimpleComponent |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityService.java | {
"start": 2475,
"end": 7129
} | interface ____ {
@PreAuthorize("denyAll")
String preAuthorize();
@Secured("ROLE_ADMIN")
String secured();
@Secured("ROLE_USER")
String securedUser();
@DenyAll
String jsr250();
@PermitAll
String jsr250PermitAll();
@RolesAllowed("ADMIN")
String jsr250RolesAllowed();
@RolesAllowed("USER")
String jsr250RolesAllowedUser();
@Secured({ "ROLE_USER", "RUN_AS_SUPER" })
Authentication runAs();
@PreAuthorize("permitAll")
String preAuthorizePermitAll();
@PreAuthorize("!anonymous")
void preAuthorizeNotAnonymous();
@PreAuthorize("@authz.check(#result)")
void preAuthorizeBean(@P("result") boolean result);
@PreAuthorize("hasRole('ADMIN')")
void preAuthorizeAdmin();
@PreAuthorize("hasRole('USER')")
void preAuthorizeUser();
@PreAuthorize("hasAllRoles('USER', 'ADMIN')")
void hasAllRolesUserAdmin();
@PreAuthorize("hasAllAuthorities('ROLE_USER', 'ROLE_ADMIN')")
void hasAllAuthoritiesRoleUserRoleAdmin();
@PreAuthorize("hasPermission(#object,'read')")
String hasPermission(String object);
@PostAuthorize("hasPermission(#object,'read')")
String postHasPermission(String object);
@PostAuthorize("#o?.contains('grant')")
String postAnnotation(@P("o") String object);
@PreFilter("filterObject == authentication.name")
List<String> preFilterByUsername(List<String> array);
@PostFilter("filterObject == authentication.name")
List<String> postFilterByUsername(List<String> array);
@PreFilter("filterObject.length > 3")
@PreAuthorize("hasRole('ADMIN')")
@Secured("ROLE_USER")
@PostFilter("filterObject.length > 5")
@PostAuthorize("returnObject.size == 2")
List<String> manyAnnotations(List<String> array);
@PreFilter("filterObject != 'DropOnPreFilter'")
@PreAuthorize("#list.remove('DropOnPreAuthorize')")
@Secured("ROLE_SECURED")
@RolesAllowed("JSR250")
@PostAuthorize("#list.remove('DropOnPostAuthorize')")
@PostFilter("filterObject != 'DropOnPostFilter'")
List<String> allAnnotations(List<String> list);
@RequireUserRole
@RequireAdminRole
void repeatedAnnotations();
@PreAuthorize("hasRole('ADMIN')")
@HandleAuthorizationDenied(handlerClass = StarMaskingHandler.class)
String preAuthorizeGetCardNumberIfAdmin(String cardNumber);
@PreAuthorize("hasRole('ADMIN')")
@HandleAuthorizationDenied(handlerClass = StartMaskingHandlerChild.class)
String preAuthorizeWithHandlerChildGetCardNumberIfAdmin(String cardNumber);
@PreAuthorize("hasRole('ADMIN')")
@HandleAuthorizationDenied(handlerClass = StarMaskingHandler.class)
String preAuthorizeThrowAccessDeniedManually();
@PostAuthorize("hasRole('ADMIN')")
@HandleAuthorizationDenied(handlerClass = CardNumberMaskingPostProcessor.class)
String postAuthorizeGetCardNumberIfAdmin(String cardNumber);
@PostAuthorize("hasRole('ADMIN')")
@HandleAuthorizationDenied(handlerClass = PostMaskingPostProcessor.class)
String postAuthorizeThrowAccessDeniedManually();
@PreAuthorize("denyAll()")
@Mask("methodmask")
@HandleAuthorizationDenied(handlerClass = MaskAnnotationHandler.class)
String preAuthorizeDeniedMethodWithMaskAnnotation();
@PreAuthorize("denyAll()")
@HandleAuthorizationDenied(handlerClass = MaskAnnotationHandler.class)
String preAuthorizeDeniedMethodWithNoMaskAnnotation();
@NullDenied(role = "ADMIN")
String postAuthorizeDeniedWithNullDenied();
@PostAuthorize("denyAll()")
@Mask("methodmask")
@HandleAuthorizationDenied(handlerClass = MaskAnnotationPostProcessor.class)
String postAuthorizeDeniedMethodWithMaskAnnotation();
@PostAuthorize("denyAll()")
@HandleAuthorizationDenied(handlerClass = MaskAnnotationPostProcessor.class)
String postAuthorizeDeniedMethodWithNoMaskAnnotation();
@PreAuthorize("hasRole('ADMIN')")
@Mask(expression = "@myMasker.getMask()")
@HandleAuthorizationDenied(handlerClass = MaskAnnotationHandler.class)
String preAuthorizeWithMaskAnnotationUsingBean();
@PostAuthorize("hasRole('ADMIN')")
@Mask(expression = "@myMasker.getMask(returnObject)")
@HandleAuthorizationDenied(handlerClass = MaskAnnotationPostProcessor.class)
String postAuthorizeWithMaskAnnotationUsingBean();
@AuthorizeReturnObject
UserRecordWithEmailProtected getUserRecordWithEmailProtected();
@PreAuthorize("hasRole('ADMIN')")
@HandleAuthorizationDenied(handlerClass = UserFallbackDeniedHandler.class)
UserRecordWithEmailProtected getUserWithFallbackWhenUnauthorized();
@PreAuthorize("@authz.checkResult(#result)")
@PostAuthorize("@authz.checkResult(!#result)")
@HandleAuthorizationDenied(handlerClass = MethodAuthorizationDeniedHandler.class)
String checkCustomResult(boolean result);
@PreAuthorize("@authz.checkManager(#id)")
String checkCustomManager(long id);
| MethodSecurityService |
java | micronaut-projects__micronaut-core | inject-java/src/main/java/io/micronaut/annotation/processing/PublicAbstractMethodVisitor.java | {
"start": 1521,
"end": 1855
} | class ____<R, P> extends PublicMethodVisitor<R, P> {
private final TypeElement classElement;
private final ModelUtils modelUtils;
private final Elements elementUtils;
private final Map<String, List<ExecutableElement>> declaredMethods = new HashMap<>();
/**
* @param classElement The | PublicAbstractMethodVisitor |
java | google__dagger | javatests/dagger/internal/codegen/MissingBindingValidationTest.java | {
"start": 72990,
"end": 73316
} | interface ____ {}");
Source moduleSrc =
CompilerTests.javaSource(
"test.TestModule",
"package test;",
"",
"import dagger.Module;",
"import dagger.Provides;",
"import java.util.Set;",
"",
"@Module",
"public | Baz |
java | quarkusio__quarkus | extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/utils/EntityTypeUtils.java | {
"start": 2753,
"end": 4645
} | class
____ (currentRelationClass.superName() != null) {
currentRelationClass = index.getClassByName(currentRelationClass.superName());
} else {
currentRelationClass = null;
}
}
}
}
if (currentEntityClass.superName() != null) {
currentEntityClass = index.getClassByName(currentEntityClass.superName());
} else {
currentEntityClass = null;
}
}
return fields;
}
public static List<ClassInfo> getListenersByEntityType(IndexView index,
List<ResourceMethodListenerBuildItem> resourceMethodListeners,
String entityTypeName) {
ClassInfo entityClass = index.getClassByName(entityTypeName);
return resourceMethodListeners.stream()
.filter(isCompatibleWithEntityType(index, entityClass))
.map(e -> e.getClassInfo())
.collect(Collectors.toList());
}
private static Predicate<ResourceMethodListenerBuildItem> isCompatibleWithEntityType(IndexView index,
ClassInfo entityClass) {
return e -> {
DotName entityTypeOfListener = e.getEntityType().asClassType().name();
ClassInfo currentEntityClass = entityClass;
while (currentEntityClass != null) {
if (entityTypeOfListener.equals(currentEntityClass.name())) {
return true;
}
if (currentEntityClass.superName() != null) {
currentEntityClass = index.getClassByName(currentEntityClass.superName());
} else {
currentEntityClass = null;
}
}
return false;
};
}
}
| if |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/runner/DefaultDispatcherGatewayServiceFactory.java | {
"start": 1705,
"end": 3673
} | class ____
implements AbstractDispatcherLeaderProcess.DispatcherGatewayServiceFactory {
private final DispatcherFactory dispatcherFactory;
private final RpcService rpcService;
private final PartialDispatcherServices partialDispatcherServices;
DefaultDispatcherGatewayServiceFactory(
DispatcherFactory dispatcherFactory,
RpcService rpcService,
PartialDispatcherServices partialDispatcherServices) {
this.dispatcherFactory = dispatcherFactory;
this.rpcService = rpcService;
this.partialDispatcherServices = partialDispatcherServices;
}
@Override
public AbstractDispatcherLeaderProcess.DispatcherGatewayService create(
DispatcherId fencingToken,
Collection<ExecutionPlan> recoveredJobs,
Collection<JobResult> recoveredDirtyJobResults,
ExecutionPlanWriter executionPlanWriter,
JobResultStore jobResultStore) {
final Dispatcher dispatcher;
try {
dispatcher =
dispatcherFactory.createDispatcher(
rpcService,
fencingToken,
recoveredJobs,
recoveredDirtyJobResults,
(dispatcherGateway, scheduledExecutor, errorHandler) ->
new NoOpDispatcherBootstrap(),
PartialDispatcherServicesWithJobPersistenceComponents.from(
partialDispatcherServices,
executionPlanWriter,
jobResultStore));
} catch (Exception e) {
throw new FlinkRuntimeException("Could not create the Dispatcher rpc endpoint.", e);
}
dispatcher.start();
return DefaultDispatcherGatewayService.from(dispatcher);
}
}
| DefaultDispatcherGatewayServiceFactory |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/health/HealthReporter.java | {
"start": 1623,
"end": 2130
} | interface ____ {
/**
* Gets whether the node is healthy or not.
*
* @return true if node is healthy
*/
boolean isHealthy();
/**
* Returns output from health check. If node is healthy then an empty string
* is returned.
*
* @return output from health check
*/
String getHealthReport();
/**
* Returns time stamp when node health check was last run.
*
* @return timestamp when node health script was last run
*/
long getLastHealthReportTime();
}
| HealthReporter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/JoinedInheritanceEagerTest.java | {
"start": 3896,
"end": 4395
} | class ____ extends BaseEntity {
@OneToMany(fetch = FetchType.LAZY)
private Set<EntityC> attributes;
@ManyToOne(fetch = FetchType.EAGER)
private EntityC relation;
public EntityA() {
}
public EntityA(Long id) {
super( id );
}
public void setRelation(EntityC relation) {
this.relation = relation;
}
public EntityC getRelation() {
return relation;
}
public Set<EntityC> getAttributes() {
return attributes;
}
}
@Entity(name = "EntityB")
public static | EntityA |
java | spring-projects__spring-boot | core/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java | {
"start": 2026,
"end": 19014
} | class ____<C extends ApplicationContext>
extends AbstractAssert<ApplicationContextAssert<C>, C> {
private final @Nullable Throwable startupFailure;
/**
* Create a new {@link ApplicationContextAssert} instance.
* @param applicationContext the source application context
* @param startupFailure the startup failure or {@code null}
*/
ApplicationContextAssert(C applicationContext, @Nullable Throwable startupFailure) {
super(applicationContext, ApplicationContextAssert.class);
Assert.notNull(applicationContext, "'applicationContext' must not be null");
this.startupFailure = startupFailure;
}
/**
* Verifies that the application context contains a bean with the given name.
* <p>
* Example: <pre class="code">
* assertThat(context).hasBean("fooBean"); </pre>
* @param name the name of the bean
* @return {@code this} assertion object.
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context does not contain a bean with the
* given name
*/
public ApplicationContextAssert<C> hasBean(String name) {
if (this.startupFailure != null) {
throwAssertionError(
contextFailedToStartWhenExpecting(this.startupFailure, "to have bean named:%n <%s>", name));
}
if (findBean(name) == null) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto have bean named:%n <%s>%nbut found no such bean", getApplicationContext(),
name));
}
return this;
}
/**
* Verifies that the application context (or ancestors) contains a single bean with
* the given type.
* <p>
* Example: <pre class="code">
* assertThat(context).hasSingleBean(Foo.class); </pre>
* @param type the bean type
* @return {@code this} assertion object.
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context does no beans of the given type
* @throws AssertionError if the application context contains multiple beans of the
* given type
*/
public ApplicationContextAssert<C> hasSingleBean(Class<?> type) {
return hasSingleBean(type, Scope.INCLUDE_ANCESTORS);
}
/**
* Verifies that the application context contains a single bean with the given type.
* <p>
* Example: <pre class="code">
* assertThat(context).hasSingleBean(Foo.class, Scope.NO_ANCESTORS); </pre>
* @param type the bean type
* @param scope the scope of the assertion
* @return {@code this} assertion object.
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context does no beans of the given type
* @throws AssertionError if the application context contains multiple beans of the
* given type
*/
public ApplicationContextAssert<C> hasSingleBean(Class<?> type, Scope scope) {
Assert.notNull(scope, "'scope' must not be null");
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(this.startupFailure,
"to have a single bean of type:%n <%s>", type));
}
String[] names = scope.getBeanNamesForType(getApplicationContext(), type);
if (names.length == 0) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto have a single bean of type:%n <%s>%nbut found no beans of that type",
getApplicationContext(), type));
}
if (names.length > 1) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto have a single bean of type:%n <%s>%nbut found:%n <%s>",
getApplicationContext(), type, names));
}
return this;
}
/**
* Verifies that the application context (or ancestors) does not contain any beans of
* the given type.
* <p>
* Example: <pre class="code">
* assertThat(context).doesNotHaveBean(Foo.class); </pre>
* @param type the bean type
* @return {@code this} assertion object.
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context contains any beans of the given
* type
*/
public ApplicationContextAssert<C> doesNotHaveBean(Class<?> type) {
return doesNotHaveBean(type, Scope.INCLUDE_ANCESTORS);
}
/**
* Verifies that the application context does not contain any beans of the given type.
* <p>
* Example: <pre class="code">
* assertThat(context).doesNotHaveBean(Foo.class, Scope.NO_ANCESTORS); </pre>
* @param type the bean type
* @param scope the scope of the assertion
* @return {@code this} assertion object.
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context contains any beans of the given
* type
*/
public ApplicationContextAssert<C> doesNotHaveBean(Class<?> type, Scope scope) {
Assert.notNull(scope, "'scope' must not be null");
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(this.startupFailure,
"not to have any beans of type:%n <%s>", type));
}
String[] names = scope.getBeanNamesForType(getApplicationContext(), type);
if (names.length > 0) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nnot to have any beans of type:%n <%s>%nbut found:%n <%s>",
getApplicationContext(), type, names));
}
return this;
}
/**
* Verifies that the application context does not contain a beans of the given name.
* <p>
* Example: <pre class="code">
* assertThat(context).doesNotHaveBean("fooBean"); </pre>
* @param name the name of the bean
* @return {@code this} assertion object.
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context contains a beans of the given
* name
*/
public ApplicationContextAssert<C> doesNotHaveBean(String name) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(this.startupFailure,
"not to have any beans of name:%n <%s>", name));
}
try {
Object bean = getApplicationContext().getBean(name);
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nnot to have a bean of name:%n <%s>%nbut found:%n <%s>",
getApplicationContext(), name, bean));
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore
}
return this;
}
/**
* Obtain the beans names of the given type from the application context, the names
* becoming the object array under test.
* <p>
* Example: <pre class="code">
* assertThat(context).getBeanNames(Foo.class).containsOnly("fooBean"); </pre>
* @param <T> the bean type
* @param type the bean type
* @return array assertions for the bean names
* @throws AssertionError if the application context did not start
*/
public <T> AbstractObjectArrayAssert<?, String> getBeanNames(Class<T> type) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(this.startupFailure,
"to get beans names with type:%n <%s>", type));
}
return Assertions.assertThat(getApplicationContext().getBeanNamesForType(type))
.as("Bean names of type <%s> from <%s>", type, getApplicationContext());
}
/**
* Obtain a single bean of the given type from the application context (or ancestors),
* the bean becoming the object under test. If no beans of the specified type can be
* found an assert on {@code null} is returned.
* <p>
* Example: <pre class="code">
* assertThat(context).getBean(Foo.class).isInstanceOf(DefaultFoo.class);
* assertThat(context).getBean(Bar.class).isNull();</pre>
* @param <T> the bean type
* @param type the bean type
* @return bean assertions for the bean, or an assert on {@code null} if the no bean
* is found
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context contains multiple beans of the
* given type
*/
public <T> AbstractObjectAssert<?, T> getBean(Class<T> type) {
return getBean(type, Scope.INCLUDE_ANCESTORS);
}
/**
* Obtain a single bean of the given type from the application context, the bean
* becoming the object under test. If no beans of the specified type can be found an
* assert on {@code null} is returned.
* <p>
* Example: <pre class="code">
* assertThat(context).getBean(Foo.class, Scope.NO_ANCESTORS).isInstanceOf(DefaultFoo.class);
* assertThat(context).getBean(Bar.class, Scope.NO_ANCESTORS).isNull();</pre>
* @param <T> the bean type
* @param type the bean type
* @param scope the scope of the assertion
* @return bean assertions for the bean, or an assert on {@code null} if the no bean
* is found
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context contains multiple beans of the
* given type
*/
public <T> AbstractObjectAssert<?, T> getBean(Class<T> type, Scope scope) {
Assert.notNull(scope, "'scope' must not be null");
if (this.startupFailure != null) {
throwAssertionError(
contextFailedToStartWhenExpecting(this.startupFailure, "to contain bean of type:%n <%s>", type));
}
String[] names = scope.getBeanNamesForType(getApplicationContext(), type);
String name = (names.length > 0) ? getPrimary(names, scope) : null;
if (names.length > 1 && name == null) {
throwAssertionError(
new BasicErrorMessageFactory("%nExpecting:%n <%s>%nsingle bean of type:%n <%s>%nbut found:%n <%s>",
getApplicationContext(), type, names));
}
T bean = (name != null) ? getApplicationContext().getBean(name, type) : null;
return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type, getApplicationContext());
}
private @Nullable String getPrimary(String[] names, Scope scope) {
if (names.length == 1) {
return names[0];
}
String primary = null;
for (String name : names) {
if (isPrimary(name, scope)) {
if (primary != null) {
return null;
}
primary = name;
}
}
return primary;
}
private boolean isPrimary(String name, Scope scope) {
ApplicationContext context = getApplicationContext();
while (context != null) {
if (context instanceof ConfigurableApplicationContext configurableContext) {
ConfigurableListableBeanFactory factory = configurableContext.getBeanFactory();
if (factory.containsBean(name) && factory.getMergedBeanDefinition(name).isPrimary()) {
return true;
}
}
context = (scope != Scope.NO_ANCESTORS) ? context.getParent() : null;
}
return false;
}
/**
* Obtain a single bean of the given name from the application context, the bean
* becoming the object under test. If no bean of the specified name can be found an
* assert on {@code null} is returned.
* <p>
* Example: <pre class="code">
* assertThat(context).getBean("foo").isInstanceOf(Foo.class);
* assertThat(context).getBean("foo").isNull();</pre>
* @param name the name of the bean
* @return bean assertions for the bean, or an assert on {@code null} if the no bean
* is found
* @throws AssertionError if the application context did not start
*/
public AbstractObjectAssert<?, Object> getBean(String name) {
if (this.startupFailure != null) {
throwAssertionError(
contextFailedToStartWhenExpecting(this.startupFailure, "to contain a bean of name:%n <%s>", name));
}
Object bean = findBean(name);
return Assertions.assertThat(bean).as("Bean of name <%s> from <%s>", name, getApplicationContext());
}
/**
* Obtain a single bean of the given name and type from the application context, the
* bean becoming the object under test. If no bean of the specified name can be found
* an assert on {@code null} is returned.
* <p>
* Example: <pre class="code">
* assertThat(context).getBean("foo", Foo.class).isInstanceOf(DefaultFoo.class);
* assertThat(context).getBean("foo", Foo.class).isNull();</pre>
* @param <T> the bean type
* @param name the name of the bean
* @param type the bean type
* @return bean assertions for the bean, or an assert on {@code null} if the no bean
* is found
* @throws AssertionError if the application context did not start
* @throws AssertionError if the application context contains a bean with the given
* name but a different type
*/
@SuppressWarnings("unchecked")
public <T> AbstractObjectAssert<?, T> getBean(String name, Class<T> type) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(this.startupFailure,
"to contain a bean of name:%n <%s> (%s)", name, type));
}
Object bean = findBean(name);
if (bean != null && type != null && !type.isInstance(bean)) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto contain a bean of name:%n <%s> (%s)%nbut found:%n <%s> of type <%s>",
getApplicationContext(), name, type, bean, bean.getClass()));
}
return Assertions.assertThat((T) bean)
.as("Bean of name <%s> and type <%s> from <%s>", name, type, getApplicationContext());
}
private @Nullable Object findBean(String name) {
try {
return getApplicationContext().getBean(name);
}
catch (NoSuchBeanDefinitionException ex) {
return null;
}
}
/**
* Obtain a map bean names and instances of the given type from the application
* context (or ancestors), the map becoming the object under test. If no bean of the
* specified type can be found an assert on an empty {@code map} is returned.
* <p>
* Example: <pre class="code">
* assertThat(context).getBeans(Foo.class).containsKey("foo");
* </pre>
* @param <T> the bean type
* @param type the bean type
* @return bean assertions for the beans, or an assert on an empty {@code map} if the
* no beans are found
* @throws AssertionError if the application context did not start
*/
public <T> MapAssert<String, T> getBeans(Class<T> type) {
return getBeans(type, Scope.INCLUDE_ANCESTORS);
}
/**
* Obtain a map bean names and instances of the given type from the application
* context, the map becoming the object under test. If no bean of the specified type
* can be found an assert on an empty {@code map} is returned.
* <p>
* Example: <pre class="code">
* assertThat(context).getBeans(Foo.class, Scope.NO_ANCESTORS).containsKey("foo");
* </pre>
* @param <T> the bean type
* @param type the bean type
* @param scope the scope of the assertion
* @return bean assertions for the beans, or an assert on an empty {@code map} if the
* no beans are found
* @throws AssertionError if the application context did not start
*/
public <T> MapAssert<String, T> getBeans(Class<T> type, Scope scope) {
Assert.notNull(scope, "'scope' must not be null");
if (this.startupFailure != null) {
throwAssertionError(
contextFailedToStartWhenExpecting(this.startupFailure, "to get beans of type:%n <%s>", type));
}
return Assertions.assertThat(scope.getBeansOfType(getApplicationContext(), type))
.as("Beans of type <%s> from <%s>", type, getApplicationContext());
}
/**
* Obtain the failure that stopped the application context from running, the failure
* becoming the object under test.
* <p>
* Example: <pre class="code">
* assertThat(context).getFailure().containsMessage("missing bean");
* </pre>
* @return assertions on the cause of the failure
* @throws AssertionError if the application context started without a failure
*/
public AbstractThrowableAssert<?, ? extends Throwable> getFailure() {
hasFailed();
return assertThat(this.startupFailure);
}
/**
* Verifies that the application has failed to start.
* <p>
* Example: <pre class="code"> assertThat(context).hasFailed();
* </pre>
* @return {@code this} assertion object.
* @throws AssertionError if the application context started without a failure
*/
public ApplicationContextAssert<C> hasFailed() {
if (this.startupFailure == null) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto have failed%nbut context started successfully", getApplicationContext()));
}
return this;
}
/**
* Verifies that the application has not failed to start.
* <p>
* Example: <pre class="code"> assertThat(context).hasNotFailed();
* </pre>
* @return {@code this} assertion object.
* @throws AssertionError if the application context failed to start
*/
public ApplicationContextAssert<C> hasNotFailed() {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(this.startupFailure, "to have not failed"));
}
return this;
}
protected final C getApplicationContext() {
return this.actual;
}
protected final @Nullable Throwable getStartupFailure() {
return this.startupFailure;
}
private ContextFailedToStart<C> contextFailedToStartWhenExpecting(Throwable startupFailure,
String expectationFormat, Object... arguments) {
return new ContextFailedToStart<>(getApplicationContext(), startupFailure, expectationFormat, arguments);
}
/**
* The scope of an assertion.
*/
public | ApplicationContextAssert |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/ProviderConfigInjectionTest.java | {
"start": 852,
"end": 1360
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class).addClasses(TestResource.class, FooProvider.class)
.addAsResource(new StringAsset("foo=bar"), "application.properties"));
@Test
public void testPropertyInjection() {
RestAssured.when().get("/test").then().body(Matchers.is("bar"));
}
@Path("/test")
public static | ProviderConfigInjectionTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java | {
"start": 19700,
"end": 20550
} | class ____ {
// Isn't public.
void testTest1() {}
// Have checked annotation.
@Test
public void testTest2() {}
@Before
public void testBefore() {}
@After
public void testAfter() {}
@BeforeClass
public void testBeforeClass() {}
@AfterClass
public void testAfterClass() {}
// Has parameters.
public void testTest3(int foo) {}
// Doesn't return void
public int testSomething() {
return 42;
}
}\
""")
.doTest();
}
@Test
public void negativeCase4() {
compilationHelper
.addSourceLines(
"JUnit4TestNotRunNegativeCase4.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import junit.framework.TestCase;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* May be a JUnit 3 test -- has @RunWith annotation on the | JUnit4TestNotRunNegativeCase3 |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java | {
"start": 29263,
"end": 29341
} | interface ____ extends _Label, _FormCtrl {
}
/**
*
*/
public | FormCtrl |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java | {
"start": 7209,
"end": 8171
} | class ____ {
private static final Flux<Long> INTERVAL = testInterval(Duration.ofMillis(1), 50);
private final Sinks.Empty<Void> cancelSink = Sinks.empty();
private Mono<Void> cancellation = cancelSink.asMono();
@GetMapping("/string")
Flux<String> string() {
return INTERVAL.map(l -> "foo " + l);
}
@GetMapping("/person")
Flux<Person> person() {
return INTERVAL.map(l -> new Person("foo " + l));
}
@GetMapping("/event")
Flux<ServerSentEvent<Person>> sse() {
return INTERVAL.take(2).map(l ->
ServerSentEvent.builder(new Person("foo " + l))
.id(Long.toString(l))
.comment("bar " + l)
.build());
}
@GetMapping("/infinite")
Flux<String> infinite() {
return Flux.just(0, 1).map(l -> "foo " + l)
.mergeWith(Flux.never())
.doOnCancel(() -> cancelSink.emitEmpty(Sinks.EmitFailureHandler.FAIL_FAST));
}
}
@Configuration
@EnableWebFlux
@SuppressWarnings("unused")
static | SseController |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/json/JsonAssert.java | {
"start": 1157,
"end": 2357
} | class ____ {
/**
* Create a {@link JsonComparator} from the given {@link JsonCompareMode}.
* @param compareMode the mode to use
* @return a new {@link JsonComparator} instance
* @see JSONCompareMode#STRICT
* @see JSONCompareMode#LENIENT
*/
public static JsonComparator comparator(JsonCompareMode compareMode) {
JSONCompareMode jsonAssertCompareMode = (compareMode != JsonCompareMode.LENIENT ?
JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
return comparator(jsonAssertCompareMode);
}
/**
* Create a new {@link JsonComparator} from the given JSONAssert
* {@link JSONComparator}.
* @param comparator the JSON Assert {@link JSONComparator}
* @return a new {@link JsonComparator} instance
*/
public static JsonComparator comparator(JSONComparator comparator) {
return new JsonAssertJsonComparator(comparator);
}
/**
* Create a new {@link JsonComparator} from the given JSONAssert
* {@link JSONCompareMode}.
* @param mode the JSON Assert {@link JSONCompareMode}
* @return a new {@link JsonComparator} instance
*/
public static JsonComparator comparator(JSONCompareMode mode) {
return new JsonAssertJsonComparator(mode);
}
private static | JsonAssert |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/CaseStatementWithTypeTest.java | {
"start": 4517,
"end": 4731
} | class ____ {
@Id
private Long id;
public SingleParent() {
}
public SingleParent(Long id) {
this.id = id;
}
}
@SuppressWarnings("unused")
@Entity( name = "SingleChildA" )
public static | SingleParent |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/support/GroupedActionListenerTests.java | {
"start": 1182,
"end": 5800
} | class ____ extends ESTestCase {
public void testNotifications() throws InterruptedException {
AtomicReference<Collection<Integer>> resRef = new AtomicReference<>();
ActionListener<Collection<Integer>> result = ActionTestUtils.assertNoFailureListener(resRef::set);
final int groupSize = randomIntBetween(10, 1000);
AtomicInteger count = new AtomicInteger();
GroupedActionListener<Integer> listener = new GroupedActionListener<>(groupSize, result);
int numThreads = randomIntBetween(2, 5);
Thread[] threads = new Thread[numThreads];
CyclicBarrier barrier = new CyclicBarrier(numThreads);
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(() -> {
safeAwait(barrier);
int c;
while ((c = count.incrementAndGet()) <= groupSize) {
listener.onResponse(c - 1);
}
});
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
assertNotNull(resRef.get());
ArrayList<Integer> list = new ArrayList<>(resRef.get());
Collections.sort(list);
assertEquals(groupSize, resRef.get().size());
int expectedValue = 0;
for (int i = 0; i < groupSize; i++) {
assertEquals(Integer.valueOf(expectedValue++), list.get(i));
}
}
public void testFailed() {
AtomicReference<Collection<Integer>> resRef = new AtomicReference<>();
AtomicReference<Exception> excRef = new AtomicReference<>();
ActionListener<Collection<Integer>> result = new ActionListener<Collection<Integer>>() {
@Override
public void onResponse(Collection<Integer> integers) {
resRef.set(integers);
}
@Override
public void onFailure(Exception e) {
excRef.set(e);
}
};
int size = randomIntBetween(3, 4);
GroupedActionListener<Integer> listener = new GroupedActionListener<>(size, result);
listener.onResponse(0);
IOException ioException = new IOException();
RuntimeException rtException = new RuntimeException();
listener.onFailure(rtException);
listener.onFailure(ioException);
if (size == 4) {
listener.onResponse(2);
}
assertNotNull(excRef.get());
assertEquals(rtException, excRef.get());
assertEquals(1, excRef.get().getSuppressed().length);
assertEquals(ioException, excRef.get().getSuppressed()[0]);
assertNull(resRef.get());
listener.onResponse(1);
assertNull(resRef.get());
}
public void testConcurrentFailures() throws InterruptedException {
AtomicReference<Exception> finalException = new AtomicReference<>();
int numGroups = randomIntBetween(10, 100);
GroupedActionListener<Void> listener = new GroupedActionListener<>(numGroups, ActionListener.wrap(r -> {}, finalException::set));
ExecutorService executorService = Executors.newFixedThreadPool(numGroups);
for (int i = 0; i < numGroups; i++) {
executorService.submit(() -> listener.onFailure(new IOException()));
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
Exception exception = finalException.get();
assertNotNull(exception);
assertThat(exception, instanceOf(IOException.class));
assertEquals(numGroups - 1, exception.getSuppressed().length);
}
/*
* It can happen that the same exception causes a grouped listener to be notified of the failure multiple times. Since we suppress
* additional exceptions into the first exception, we have to guard against suppressing into the same exception, which could occur if we
* are notified of with the same failure multiple times. This test verifies that the guard against self-suppression remains.
*/
public void testRepeatNotificationForTheSameException() {
final AtomicReference<Exception> finalException = new AtomicReference<>();
final GroupedActionListener<Void> listener = new GroupedActionListener<>(2, ActionListener.wrap(r -> {}, finalException::set));
final Exception e = new Exception();
// repeat notification for the same exception
listener.onFailure(e);
listener.onFailure(e);
assertThat(finalException.get(), not(nullValue()));
assertThat(finalException.get(), equalTo(e));
}
}
| GroupedActionListenerTests |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/context/router/RouteBuilderMediaTypeTest.java | {
"start": 2057,
"end": 3396
} | class ____ extends Specification {
@Test
void createTest(@Client("/") HttpClient httpClient) {
BlockingHttpClient client = httpClient.toBlocking();
HttpRequest<?> request = HttpRequest.GET("/contact/create").accept(MediaType.TEXT_HTML);
HttpResponse<String> responseHtml = assertDoesNotThrow(() -> client.exchange(request, String.class));
assertTrue(responseHtml.getContentType().isPresent());
assertEquals(MediaType.TEXT_HTML_TYPE, responseHtml.getContentType().get());
String html = responseHtml.body();
assertNotNull(html);
}
@Test
void saveTest(@Client("/") HttpClient httpClient) {
BlockingHttpClient client = httpClient.toBlocking();
HttpRequest<?> request = HttpRequest.POST(UriBuilder.of("/contact").path("save").build(),
Map.of("firstName", "Sergio", "lastName", "del Amo"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
HttpResponse<?> response = assertDoesNotThrow(() -> client.exchange(request, String.class));
assertEquals(HttpStatus.SEE_OTHER, response.getStatus());
assertEquals("/foo", response.getHeaders().get(HttpHeaders.LOCATION));
}
@Requires(property = "spec.name", value = "RouteBuilderMediaTypeSpec")
@Singleton
static | RouteBuilderMediaTypeTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/testutil/IssueKey.java | {
"start": 488,
"end": 612
} | interface ____ {
/**
* The issue number.
*
* @return the issue number
*/
String value();
}
| IssueKey |
java | grpc__grpc-java | okhttp/src/main/java/io/grpc/okhttp/OkHttpServerBuilder.java | {
"start": 2420,
"end": 20669
} | class ____ extends ForwardingServerBuilder<OkHttpServerBuilder> {
private static final Logger log = Logger.getLogger(OkHttpServerBuilder.class.getName());
private static final int DEFAULT_FLOW_CONTROL_WINDOW = 65535;
static final long MAX_CONNECTION_IDLE_NANOS_DISABLED = Long.MAX_VALUE;
private static final long MIN_MAX_CONNECTION_IDLE_NANO = TimeUnit.SECONDS.toNanos(1L);
static final long MAX_CONNECTION_AGE_NANOS_DISABLED = Long.MAX_VALUE;
static final long MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE = Long.MAX_VALUE;
static final int MAX_CONCURRENT_STREAMS = Integer.MAX_VALUE;
private static final long MIN_MAX_CONNECTION_AGE_NANO = TimeUnit.SECONDS.toNanos(1L);
private static final long AS_LARGE_AS_INFINITE = TimeUnit.DAYS.toNanos(1000L);
private static final ObjectPool<Executor> DEFAULT_TRANSPORT_EXECUTOR_POOL =
OkHttpChannelBuilder.DEFAULT_TRANSPORT_EXECUTOR_POOL;
/**
* Always throws, to shadow {@code ServerBuilder.forPort()}.
*
* @deprecated Use {@link #forPort(int, ServerCredentials)} instead
*/
@DoNotCall("Always throws. Use forPort(int, ServerCredentials) instead")
@Deprecated
public static OkHttpServerBuilder forPort(int port) {
throw new UnsupportedOperationException("Use forPort(int, ServerCredentials) instead");
}
/**
* Creates a builder for a server listening on {@code port}.
*/
public static OkHttpServerBuilder forPort(int port, ServerCredentials creds) {
return forPort(new InetSocketAddress(port), creds);
}
/**
* Creates a builder for a server listening on {@code address}.
*/
public static OkHttpServerBuilder forPort(SocketAddress address, ServerCredentials creds) {
HandshakerSocketFactoryResult result = handshakerSocketFactoryFrom(creds);
if (result.error != null) {
throw new IllegalArgumentException(result.error);
}
return new OkHttpServerBuilder(address, result.factory);
}
final ServerImplBuilder serverImplBuilder = new ServerImplBuilder(this::buildTransportServers);
final SocketAddress listenAddress;
final HandshakerSocketFactory handshakerSocketFactory;
TransportTracer.Factory transportTracerFactory = TransportTracer.getDefaultFactory();
ObjectPool<Executor> transportExecutorPool = DEFAULT_TRANSPORT_EXECUTOR_POOL;
ObjectPool<ScheduledExecutorService> scheduledExecutorServicePool =
SharedResourcePool.forResource(GrpcUtil.TIMER_SERVICE);
ServerSocketFactory socketFactory = ServerSocketFactory.getDefault();
long keepAliveTimeNanos = GrpcUtil.DEFAULT_SERVER_KEEPALIVE_TIME_NANOS;
long keepAliveTimeoutNanos = GrpcUtil.DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS;
int flowControlWindow = DEFAULT_FLOW_CONTROL_WINDOW;
int maxInboundMetadataSize = GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE;
int maxInboundMessageSize = GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE;
long maxConnectionIdleInNanos = MAX_CONNECTION_IDLE_NANOS_DISABLED;
boolean permitKeepAliveWithoutCalls;
long permitKeepAliveTimeInNanos = TimeUnit.MINUTES.toNanos(5);
long maxConnectionAgeInNanos = MAX_CONNECTION_AGE_NANOS_DISABLED;
long maxConnectionAgeGraceInNanos = MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE;
int maxConcurrentCallsPerConnection = MAX_CONCURRENT_STREAMS;
OkHttpServerBuilder(
SocketAddress address, HandshakerSocketFactory handshakerSocketFactory) {
this.listenAddress = Preconditions.checkNotNull(address, "address");
this.handshakerSocketFactory =
Preconditions.checkNotNull(handshakerSocketFactory, "handshakerSocketFactory");
}
@Internal
@Override
protected ServerBuilder<?> delegate() {
return serverImplBuilder;
}
// @VisibleForTesting
OkHttpServerBuilder setTransportTracerFactory(TransportTracer.Factory transportTracerFactory) {
this.transportTracerFactory = transportTracerFactory;
return this;
}
/**
* Override the default executor necessary for internal transport use.
*
* <p>The channel does not take ownership of the given executor. It is the caller' responsibility
* to shutdown the executor when appropriate.
*/
public OkHttpServerBuilder transportExecutor(Executor transportExecutor) {
if (transportExecutor == null) {
this.transportExecutorPool = DEFAULT_TRANSPORT_EXECUTOR_POOL;
} else {
this.transportExecutorPool = new FixedObjectPool<>(transportExecutor);
}
return this;
}
/**
* Override the default {@link ServerSocketFactory} used to listen. If the socket factory is not
* set or set to null, a default one will be used.
*/
public OkHttpServerBuilder socketFactory(ServerSocketFactory socketFactory) {
if (socketFactory == null) {
this.socketFactory = ServerSocketFactory.getDefault();
} else {
this.socketFactory = socketFactory;
}
return this;
}
/**
* Sets the time without read activity before sending a keepalive ping. An unreasonably small
* value might be increased, and {@code Long.MAX_VALUE} nano seconds or an unreasonably large
* value will disable keepalive. Defaults to two hours.
*
* @throws IllegalArgumentException if time is not positive
*/
@Override
public OkHttpServerBuilder keepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
Preconditions.checkArgument(keepAliveTime > 0L, "keepalive time must be positive");
keepAliveTimeNanos = timeUnit.toNanos(keepAliveTime);
keepAliveTimeNanos = KeepAliveManager.clampKeepAliveTimeInNanos(keepAliveTimeNanos);
if (keepAliveTimeNanos >= AS_LARGE_AS_INFINITE) {
// Bump keepalive time to infinite. This disables keepalive.
keepAliveTimeNanos = GrpcUtil.KEEPALIVE_TIME_NANOS_DISABLED;
}
return this;
}
/**
* Sets a custom max connection idle time, connection being idle for longer than which will be
* gracefully terminated. Idleness duration is defined since the most recent time the number of
* outstanding RPCs became zero or the connection establishment. An unreasonably small value might
* be increased. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable
* max connection idle.
*/
@Override
public OkHttpServerBuilder maxConnectionIdle(long maxConnectionIdle, TimeUnit timeUnit) {
checkArgument(maxConnectionIdle > 0L, "max connection idle must be positive: %s",
maxConnectionIdle);
maxConnectionIdleInNanos = timeUnit.toNanos(maxConnectionIdle);
if (maxConnectionIdleInNanos >= AS_LARGE_AS_INFINITE) {
maxConnectionIdleInNanos = MAX_CONNECTION_IDLE_NANOS_DISABLED;
}
if (maxConnectionIdleInNanos < MIN_MAX_CONNECTION_IDLE_NANO) {
maxConnectionIdleInNanos = MIN_MAX_CONNECTION_IDLE_NANO;
}
return this;
}
/**
* Sets a custom max connection age, connection lasting longer than which will be gracefully
* terminated. An unreasonably small value might be increased. A random jitter of +/-10% will be
* added to it. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable
* max connection age.
*/
@Override
public OkHttpServerBuilder maxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {
checkArgument(maxConnectionAge > 0L, "max connection age must be positive: %s",
maxConnectionAge);
maxConnectionAgeInNanos = timeUnit.toNanos(maxConnectionAge);
if (maxConnectionAgeInNanos >= AS_LARGE_AS_INFINITE) {
maxConnectionAgeInNanos = MAX_CONNECTION_AGE_NANOS_DISABLED;
}
if (maxConnectionAgeInNanos < MIN_MAX_CONNECTION_AGE_NANO) {
maxConnectionAgeInNanos = MIN_MAX_CONNECTION_AGE_NANO;
}
return this;
}
/**
* Sets a custom grace time for the graceful connection termination. Once the max connection age
* is reached, RPCs have the grace time to complete. RPCs that do not complete in time will be
* cancelled, allowing the connection to terminate. {@code Long.MAX_VALUE} nano seconds or an
* unreasonably large value are considered infinite.
*
* @see #maxConnectionAge(long, TimeUnit)
*/
@Override
public OkHttpServerBuilder maxConnectionAgeGrace(long maxConnectionAgeGrace, TimeUnit timeUnit) {
checkArgument(maxConnectionAgeGrace >= 0L, "max connection age grace must be non-negative: %s",
maxConnectionAgeGrace);
maxConnectionAgeGraceInNanos = timeUnit.toNanos(maxConnectionAgeGrace);
if (maxConnectionAgeGraceInNanos >= AS_LARGE_AS_INFINITE) {
maxConnectionAgeGraceInNanos = MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE;
}
return this;
}
/**
* Sets a time waiting for read activity after sending a keepalive ping. If the time expires
* without any read activity on the connection, the connection is considered dead. An unreasonably
* small value might be increased. Defaults to 20 seconds.
*
* <p>This value should be at least multiple times the RTT to allow for lost packets.
*
* @throws IllegalArgumentException if timeout is not positive
*/
@Override
public OkHttpServerBuilder keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) {
Preconditions.checkArgument(keepAliveTimeout > 0L, "keepalive timeout must be positive");
keepAliveTimeoutNanos = timeUnit.toNanos(keepAliveTimeout);
keepAliveTimeoutNanos = KeepAliveManager.clampKeepAliveTimeoutInNanos(keepAliveTimeoutNanos);
return this;
}
/**
* Specify the most aggressive keep-alive time clients are permitted to configure. The server will
* try to detect clients exceeding this rate and when detected will forcefully close the
* connection. The default is 5 minutes.
*
* <p>Even though a default is defined that allows some keep-alives, clients must not use
* keep-alive without approval from the service owner. Otherwise, they may experience failures in
* the future if the service becomes more restrictive. When unthrottled, keep-alives can cause a
* significant amount of traffic and CPU usage, so clients and servers should be conservative in
* what they use and accept.
*
* @see #permitKeepAliveWithoutCalls(boolean)
*/
@CanIgnoreReturnValue
@Override
public OkHttpServerBuilder permitKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
checkArgument(keepAliveTime >= 0, "permit keepalive time must be non-negative: %s",
keepAliveTime);
permitKeepAliveTimeInNanos = timeUnit.toNanos(keepAliveTime);
return this;
}
/**
* Sets whether to allow clients to send keep-alive HTTP/2 PINGs even if there are no outstanding
* RPCs on the connection. Defaults to {@code false}.
*
* @see #permitKeepAliveTime(long, TimeUnit)
*/
@CanIgnoreReturnValue
@Override
public OkHttpServerBuilder permitKeepAliveWithoutCalls(boolean permit) {
permitKeepAliveWithoutCalls = permit;
return this;
}
/**
* Sets the flow control window in bytes. If not called, the default value is 64 KiB.
*/
public OkHttpServerBuilder flowControlWindow(int flowControlWindow) {
Preconditions.checkState(flowControlWindow > 0, "flowControlWindow must be positive");
this.flowControlWindow = flowControlWindow;
return this;
}
/**
* Provides a custom scheduled executor service.
*
* <p>It's an optional parameter. If the user has not provided a scheduled executor service when
* the channel is built, the builder will use a static thread pool.
*
* @return this
*/
public OkHttpServerBuilder scheduledExecutorService(
ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorServicePool = new FixedObjectPool<>(
Preconditions.checkNotNull(scheduledExecutorService, "scheduledExecutorService"));
return this;
}
/**
* Sets the maximum size of metadata allowed to be received. Defaults to 8 KiB.
*
* <p>The implementation does not currently limit memory usage; this value is checked only after
* the metadata is decoded from the wire. It does prevent large metadata from being passed to the
* application.
*
* @param bytes the maximum size of received metadata
* @return this
* @throws IllegalArgumentException if bytes is non-positive
*/
@Override
public OkHttpServerBuilder maxInboundMetadataSize(int bytes) {
Preconditions.checkArgument(bytes > 0, "maxInboundMetadataSize must be > 0");
this.maxInboundMetadataSize = bytes;
return this;
}
/**
* The maximum number of concurrent calls permitted for each incoming connection. Defaults to no
* limit.
*/
@CanIgnoreReturnValue
public OkHttpServerBuilder maxConcurrentCallsPerConnection(int maxConcurrentCallsPerConnection) {
checkArgument(maxConcurrentCallsPerConnection > 0,
"max must be positive: %s", maxConcurrentCallsPerConnection);
this.maxConcurrentCallsPerConnection = maxConcurrentCallsPerConnection;
return this;
}
/**
* Sets the maximum message size allowed to be received on the server. If not called, defaults to
* defaults to 4 MiB. The default provides protection to servers who haven't considered the
* possibility of receiving large messages while trying to be large enough to not be hit in normal
* usage.
*
* @param bytes the maximum number of bytes a single message can be.
* @return this
* @throws IllegalArgumentException if bytes is negative.
*/
@Override
public OkHttpServerBuilder maxInboundMessageSize(int bytes) {
Preconditions.checkArgument(bytes >= 0, "negative max bytes");
maxInboundMessageSize = bytes;
return this;
}
void setStatsEnabled(boolean value) {
this.serverImplBuilder.setStatsEnabled(value);
}
InternalServer buildTransportServers(
List<? extends ServerStreamTracer.Factory> streamTracerFactories) {
return new OkHttpServer(this, streamTracerFactories, serverImplBuilder.getChannelz());
}
private static final EnumSet<TlsServerCredentials.Feature> understoodTlsFeatures =
EnumSet.of(
TlsServerCredentials.Feature.MTLS, TlsServerCredentials.Feature.CUSTOM_MANAGERS);
static HandshakerSocketFactoryResult handshakerSocketFactoryFrom(ServerCredentials creds) {
if (creds instanceof TlsServerCredentials) {
TlsServerCredentials tlsCreds = (TlsServerCredentials) creds;
Set<TlsServerCredentials.Feature> incomprehensible =
tlsCreds.incomprehensible(understoodTlsFeatures);
if (!incomprehensible.isEmpty()) {
return HandshakerSocketFactoryResult.error(
"TLS features not understood: " + incomprehensible);
}
KeyManager[] km = null;
if (tlsCreds.getKeyManagers() != null) {
km = tlsCreds.getKeyManagers().toArray(new KeyManager[0]);
} else if (tlsCreds.getPrivateKey() != null) {
if (tlsCreds.getPrivateKeyPassword() != null) {
return HandshakerSocketFactoryResult.error("byte[]-based private key with password "
+ "unsupported. Use unencrypted file or KeyManager");
}
try {
km = OkHttpChannelBuilder.createKeyManager(
tlsCreds.getCertificateChain(), tlsCreds.getPrivateKey());
} catch (GeneralSecurityException gse) {
log.log(Level.FINE, "Exception loading private key from credential", gse);
return HandshakerSocketFactoryResult.error(
"Unable to load private key: " + gse.getMessage());
}
} // else don't have a client cert
TrustManager[] tm = null;
if (tlsCreds.getTrustManagers() != null) {
tm = tlsCreds.getTrustManagers().toArray(new TrustManager[0]);
} else if (tlsCreds.getRootCertificates() != null) {
try {
tm = createTrustManager(tlsCreds.getRootCertificates());
} catch (GeneralSecurityException gse) {
log.log(Level.FINE, "Exception loading root certificates from credential", gse);
return HandshakerSocketFactoryResult.error(
"Unable to load root certificates: " + gse.getMessage());
}
} // else use system default
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS", Platform.get().getProvider());
sslContext.init(km, tm, null);
} catch (GeneralSecurityException gse) {
throw new RuntimeException("TLS Provider failure", gse);
}
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
switch (tlsCreds.getClientAuth()) {
case OPTIONAL:
sslSocketFactory = new ClientCertRequestingSocketFactory(sslSocketFactory, false);
break;
case REQUIRE:
sslSocketFactory = new ClientCertRequestingSocketFactory(sslSocketFactory, true);
break;
case NONE:
// NOOP; this is the SSLContext default
break;
default:
return HandshakerSocketFactoryResult.error(
"Unknown TlsServerCredentials.ClientAuth value: " + tlsCreds.getClientAuth());
}
return HandshakerSocketFactoryResult.factory(new TlsServerHandshakerSocketFactory(
new SslSocketFactoryServerCredentials.ServerCredentials(sslSocketFactory)));
} else if (creds instanceof InsecureServerCredentials) {
return HandshakerSocketFactoryResult.factory(new PlaintextHandshakerSocketFactory());
} else if (creds instanceof SslSocketFactoryServerCredentials.ServerCredentials) {
SslSocketFactoryServerCredentials.ServerCredentials factoryCreds =
(SslSocketFactoryServerCredentials.ServerCredentials) creds;
return HandshakerSocketFactoryResult.factory(
new TlsServerHandshakerSocketFactory(factoryCreds));
} else if (creds instanceof ChoiceServerCredentials) {
ChoiceServerCredentials choiceCreds = (ChoiceServerCredentials) creds;
StringBuilder error = new StringBuilder();
for (ServerCredentials innerCreds : choiceCreds.getCredentialsList()) {
HandshakerSocketFactoryResult result = handshakerSocketFactoryFrom(innerCreds);
if (result.error == null) {
return result;
}
error.append(", ");
error.append(result.error);
}
return HandshakerSocketFactoryResult.error(error.substring(2));
} else {
return HandshakerSocketFactoryResult.error(
"Unsupported credential type: " + creds.getClass().getName());
}
}
static final | OkHttpServerBuilder |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/errors/UnhandledOpenFailureLogStrategyTest.java | {
"start": 539,
"end": 1372
} | class ____ {
@RegisterExtension
public static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot(root -> {
root.addClasses(EchoOpenError.class, WSClient.class);
}).overrideConfigKey("quarkus.websockets-next.server.unhandled-failure-strategy", "log");
@Inject
Vertx vertx;
@TestHTTPResource("echo")
URI testUri;
@Test
void testErrorDoesNotCloseConnection() throws InterruptedException {
try (WSClient client = WSClient.create(vertx).connect(testUri)) {
assertTrue(EchoOpenError.OPEN_CALLED.await(5, TimeUnit.SECONDS));
client.sendAndAwait("foo");
client.waitForMessages(1);
assertEquals("foo", client.getLastMessage().toString());
}
}
}
| UnhandledOpenFailureLogStrategyTest |
java | google__dagger | hilt-android/main/java/dagger/hilt/android/internal/managers/ActivityRetainedComponentManager.java | {
"start": 1700,
"end": 1939
} | class ____
implements GeneratedComponentManager<ActivityRetainedComponent> {
/** Entry point for {@link ActivityRetainedComponentBuilder}. */
@EntryPoint
@InstallIn(SingletonComponent.class)
public | ActivityRetainedComponentManager |
java | apache__hadoop | hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/server/dns/BaseServiceRecordProcessor.java | {
"start": 6159,
"end": 7740
} | class ____<T> {
private final ServiceRecord record;
private Name[] names;
private T target;
/**
* Creates a DNS record descriptor.
*
* @param record the associated service record.
*/
public RecordDescriptor(ServiceRecord record) {
this.record = record;
}
/**
* Returns the DNS names associated with the record type and information.
*
* @return the array of names.
*/
public Name[] getNames() {
return names;
}
/**
* Return the target object for the DNS record.
*
* @return the DNS record target.
*/
public T getTarget() {
return target;
}
/**
* Initializes the names and information for this DNS record descriptor.
*
* @param serviceRecord the service record.
* @throws Exception
*/
protected abstract void init(ServiceRecord serviceRecord) throws Exception;
/**
* Returns the service record.
* @return the service record.
*/
public ServiceRecord getRecord() {
return record;
}
/**
* Sets the names associated with the record type and information.
* @param names the names.
*/
public void setNames(Name[] names) {
this.names = names;
}
/**
* Sets the target object associated with the record.
* @param target the target.
*/
public void setTarget(T target) {
this.target = target;
}
}
/**
* A container-based DNS record descriptor.
*
* @param <T> the DNS record type/class.
*/
abstract | RecordDescriptor |
java | netty__netty | codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java | {
"start": 47727,
"end": 51196
} | class ____ extends DefaultChannelConfig {
volatile boolean autoStreamFlowControl = true;
Http2StreamChannelConfig(Channel channel) {
super(channel);
}
@Override
public MessageSizeEstimator getMessageSizeEstimator() {
return FlowControlledFrameSizeEstimator.INSTANCE;
}
@Override
public ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) {
throw new UnsupportedOperationException();
}
@Override
public ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) {
if (!(allocator.newHandle() instanceof RecvByteBufAllocator.ExtendedHandle)) {
throw new IllegalArgumentException("allocator.newHandle() must return an object of type: " +
RecvByteBufAllocator.ExtendedHandle.class);
}
super.setRecvByteBufAllocator(allocator);
return this;
}
@Override
public Map<ChannelOption<?>, Object> getOptions() {
return getOptions(
super.getOptions(),
Http2StreamChannelOption.AUTO_STREAM_FLOW_CONTROL);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getOption(ChannelOption<T> option) {
if (option == Http2StreamChannelOption.AUTO_STREAM_FLOW_CONTROL) {
return (T) Boolean.valueOf(autoStreamFlowControl);
}
return super.getOption(option);
}
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
validate(option, value);
if (option == Http2StreamChannelOption.AUTO_STREAM_FLOW_CONTROL) {
boolean newValue = (Boolean) value;
boolean changed = newValue && !autoStreamFlowControl;
autoStreamFlowControl = (Boolean) value;
if (changed) {
if (channel.isRegistered()) {
final Http2ChannelUnsafe unsafe = (Http2ChannelUnsafe) channel.unsafe();
if (channel.eventLoop().inEventLoop()) {
unsafe.updateLocalWindowIfNeededAndFlush();
} else {
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
unsafe.updateLocalWindowIfNeededAndFlush();
}
});
}
}
}
return true;
}
return super.setOption(option, value);
}
}
private void maybeAddChannelToReadCompletePendingQueue() {
if (!readCompletePending) {
readCompletePending = true;
addChannelToReadCompletePendingQueue();
}
}
protected void flush0(ChannelHandlerContext ctx) {
ctx.flush();
}
protected ChannelFuture write0(ChannelHandlerContext ctx, Object msg) {
ChannelPromise promise = ctx.newPromise();
ctx.write(msg, promise);
return promise;
}
protected abstract boolean isParentReadInProgress();
protected abstract void addChannelToReadCompletePendingQueue();
protected abstract ChannelHandlerContext parentContext();
}
| Http2StreamChannelConfig |
java | elastic__elasticsearch | x-pack/plugin/sql/sql-action/src/test/java/org/elasticsearch/xpack/sql/action/SqlTranslateRequestTests.java | {
"start": 1229,
"end": 4617
} | class ____ extends AbstractXContentSerializingTestCase<TestSqlTranslateRequest> {
public Mode testMode;
@Before
public void setup() {
testMode = randomFrom(Mode.values());
}
@Override
protected TestSqlTranslateRequest createXContextTestInstance(XContentType xContentType) {
SqlTestUtils.assumeXContentJsonOrCbor(xContentType);
return super.createXContextTestInstance(xContentType);
}
@Override
protected TestSqlTranslateRequest createTestInstance() {
return new TestSqlTranslateRequest(
randomAlphaOfLength(10),
emptyList(),
randomFilterOrNull(random()),
randomRuntimeMappings(),
randomZone(),
between(1, Integer.MAX_VALUE),
randomTimeValue(),
randomTimeValue(),
new RequestInfo(testMode)
);
}
@Override
protected Writeable.Reader<TestSqlTranslateRequest> instanceReader() {
return TestSqlTranslateRequest::new;
}
@Override
protected NamedWriteableRegistry getNamedWriteableRegistry() {
SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList());
return new NamedWriteableRegistry(searchModule.getNamedWriteables());
}
@Override
protected NamedXContentRegistry xContentRegistry() {
SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList());
return new NamedXContentRegistry(searchModule.getNamedXContents());
}
@Override
protected TestSqlTranslateRequest doParseInstance(XContentParser parser) {
return SqlTestUtils.clone(TestSqlTranslateRequest.fromXContent(parser), instanceReader(), getNamedWriteableRegistry());
}
@Override
protected TestSqlTranslateRequest mutateInstance(TestSqlTranslateRequest instance) {
@SuppressWarnings("unchecked")
Consumer<SqlTranslateRequest> mutator = randomFrom(
request -> request.query(randomValueOtherThan(request.query(), () -> randomAlphaOfLength(5))),
request -> request.zoneId(randomValueOtherThan(request.zoneId(), ESTestCase::randomZone)),
request -> request.catalog(randomValueOtherThan(request.catalog(), () -> randomAlphaOfLength(10))),
request -> request.fetchSize(randomValueOtherThan(request.fetchSize(), () -> between(1, Integer.MAX_VALUE))),
request -> request.requestTimeout(randomValueOtherThan(request.requestTimeout(), ESTestCase::randomTimeValue)),
request -> request.filter(
randomValueOtherThan(
request.filter(),
() -> request.filter() == null ? randomFilter(random()) : randomFilterOrNull(random())
)
),
request -> request.runtimeMappings(randomValueOtherThan(request.runtimeMappings(), () -> randomRuntimeMappings()))
);
TestSqlTranslateRequest newRequest = new TestSqlTranslateRequest(
instance.query(),
instance.params(),
instance.filter(),
instance.runtimeMappings(),
instance.zoneId(),
instance.fetchSize(),
instance.requestTimeout(),
instance.pageTimeout(),
instance.requestInfo()
);
mutator.accept(newRequest);
return newRequest;
}
}
| SqlTranslateRequestTests |
java | quarkusio__quarkus | extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/MissingP12TrustStoreFromClassPathTest.java | {
"start": 823,
"end": 1629
} | class ____ {
private static final String configuration = """
quarkus.tls.trust-store.p12.path=/certs/missing.p12
quarkus.tls.trust-store.p12.password=password
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.add(new StringAsset(configuration), "application.properties"))
.assertException(t -> {
assertThat(t.getMessage()).contains("default", "P12", "file", "missing.p12", "trust");
});
@Test
void test() throws KeyStoreException, CertificateParsingException {
fail("Should not be called as the extension should fail before.");
}
}
| MissingP12TrustStoreFromClassPathTest |
java | dropwizard__dropwizard | dropwizard-views-freemarker/src/main/java/io/dropwizard/views/freemarker/FreemarkerViewRenderer.java | {
"start": 1182,
"end": 4481
} | class ____ implements CacheLoader<Class<?>, Configuration> {
private final Version incompatibleImprovementsVersion;
private Map<String, String> baseConfig = Collections.emptyMap();
private TemplateLoader(Version incompatibleImprovementsVersion) {
this.incompatibleImprovementsVersion = incompatibleImprovementsVersion;
}
@Override
public Configuration load(@NonNull Class<?> key) throws Exception {
final Configuration configuration = new Configuration(incompatibleImprovementsVersion);
configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(incompatibleImprovementsVersion).build());
configuration.loadBuiltInEncodingMap();
configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
configuration.setClassForTemplateLoading(key, "/");
// setting the outputformat implicitly enables auto escaping
configuration.setOutputFormat(HTMLOutputFormat.INSTANCE);
for (Map.Entry<String, String> entry : baseConfig.entrySet()) {
configuration.setSetting(entry.getKey(), entry.getValue());
}
return configuration;
}
void setBaseConfig(Map<String, String> baseConfig) {
this.baseConfig = baseConfig;
}
}
private final LoadingCache<Class<?>, Configuration> configurationCache;
/**
* @deprecated Use {@link #FreemarkerViewRenderer(Version)} instead.
*/
@Deprecated
public FreemarkerViewRenderer() {
this(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
}
/**
* @param incompatibleImprovementsVersion FreeMarker version number for backward compatible bug fixes and improvements.
* See {@link Configuration#Configuration(Version)} for more information.
*/
public FreemarkerViewRenderer(Version incompatibleImprovementsVersion) {
this.loader = new TemplateLoader(incompatibleImprovementsVersion);
this.configurationCache = Caffeine.newBuilder().build(loader);
}
@Override
public boolean isRenderable(View view) {
return FILE_PATTERN.matcher(view.getTemplateName()).find();
}
@Override
public void render(View view,
Locale locale,
OutputStream output) throws IOException {
final Configuration configuration = configurationCache.get(view.getClass());
if (configuration == null) {
throw new ViewRenderException("Couldn't find view class " + view.getClass());
}
try {
final Charset charset = view.getCharset().orElseGet(() -> Charset.forName(configuration.getEncoding(locale)));
final Template template = configuration.getTemplate(view.getTemplateName(), locale, charset.name());
template.process(view, new OutputStreamWriter(output, template.getEncoding()));
} catch (Exception e) {
throw new ViewRenderException(e);
}
}
@Override
public void configure(Map<String, String> baseConfig) {
this.loader.setBaseConfig(baseConfig);
}
@Override
public String getConfigurationKey() {
return "freemarker";
}
}
| TemplateLoader |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/GroupAuthorizationException.java | {
"start": 847,
"end": 1617
} | class ____ extends AuthorizationException {
private final String groupId;
public GroupAuthorizationException(String message, String groupId) {
super(message);
this.groupId = groupId;
}
public GroupAuthorizationException(String message) {
this(message, null);
}
/**
* Return the group ID that failed authorization. May be null if it is not known
* in the context the exception was raised in.
*
* @return nullable groupId
*/
public String groupId() {
return groupId;
}
public static GroupAuthorizationException forGroupId(String groupId) {
return new GroupAuthorizationException("Not authorized to access group: " + groupId, groupId);
}
}
| GroupAuthorizationException |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/EndpointHelper.java | {
"start": 6551,
"end": 7215
} | class ____ implements Comparator<BaseOptionModel> {
private final String syntax;
EndpointPathComparator(String syntax) {
this.syntax = syntax;
}
@Override
public int compare(BaseOptionModel path1, BaseOptionModel path2) {
int pos1 = syntax != null ? syntax.indexOf(path1.getName()) : -1;
int pos2 = syntax != null ? syntax.indexOf(path2.getName()) : -1;
// use position in syntax to determine the order
if (pos1 != -1 && pos2 != -1) {
return Integer.compare(pos1, pos2);
}
return 0;
}
}
}
| EndpointPathComparator |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authentication/CredentialsExpiredException.java | {
"start": 913,
"end": 1529
} | class ____ extends AccountStatusException {
@Serial
private static final long serialVersionUID = -3306615738048904753L;
/**
* Constructs a <code>CredentialsExpiredException</code> with the specified message.
* @param msg the detail message
*/
public CredentialsExpiredException(String msg) {
super(msg);
}
/**
* Constructs a <code>CredentialsExpiredException</code> with the specified message
* and root cause.
* @param msg the detail message
* @param cause root cause
*/
public CredentialsExpiredException(String msg, Throwable cause) {
super(msg, cause);
}
}
| CredentialsExpiredException |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/support/PropertyBindingSupportPropertiesTest.java | {
"start": 3663,
"end": 3902
} | class ____ {
private Properties works;
public Properties getWorks() {
return works;
}
public void setWorks(Properties works) {
this.works = works;
}
}
public static | Bar |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationFactoryTest.java | {
"start": 2212,
"end": 8460
} | class ____ {
static final String LOGGER_NAME = "org.apache.logging.log4j.test1.Test";
static final String FILE_LOGGER_NAME = "org.apache.logging.log4j.test2.Test";
static final String APPENDER_NAME = "STDOUT";
@TempLoggingDir
private static Path loggingPath;
/**
* Runs various configuration checks on a configured LoggerContext that should match the equivalent configuration in
* {@code log4j-test1.xml}.
*/
static void checkConfiguration(final LoggerContext context) {
final Configuration configuration = context.getConfiguration();
final Map<String, Appender> appenders = configuration.getAppenders();
// these used to be separate tests
assertAll(
() -> assertNotNull(appenders),
() -> assertEquals(3, appenders.size()),
() -> assertNotNull(configuration.getLoggerContext()),
() -> assertEquals(configuration.getRootLogger(), configuration.getLoggerConfig(Strings.EMPTY)),
() -> assertThrows(NullPointerException.class, () -> configuration.getLoggerConfig(null)));
final Logger logger = context.getLogger(LOGGER_NAME);
assertEquals(Level.DEBUG, logger.getLevel());
assertEquals(1, logger.filterCount());
final Iterator<Filter> filterIterator = logger.getFilters();
assertTrue(filterIterator.hasNext());
assertInstanceOf(ThreadContextMapFilter.class, filterIterator.next());
final Appender appender = appenders.get(APPENDER_NAME);
assertInstanceOf(ConsoleAppender.class, appender);
assertEquals(APPENDER_NAME, appender.getName());
}
static void checkFileLogger(final LoggerContext context, final Path logFile) throws IOException {
final long currentThreadId = Thread.currentThread().getId();
final Logger logger = context.getLogger(FILE_LOGGER_NAME);
logger.debug("Greetings from ConfigurationFactoryTest in thread#{}", box(currentThreadId));
final List<String> lines = Files.readAllLines(logFile);
assertEquals(1, lines.size());
assertTrue(lines.get(0).endsWith(Long.toString(currentThreadId)));
}
@Test
@LoggerContextSource("log4j-test1.xml")
void xml(final LoggerContext context) throws IOException {
checkConfiguration(context);
final Path logFile = loggingPath.resolve("test-xml.log");
checkFileLogger(context, logFile);
}
@Test
@LoggerContextSource("log4j-xinclude.xml")
void xinclude(final LoggerContext context) throws IOException {
checkConfiguration(context);
final Path logFile = loggingPath.resolve("test-xinclude.log");
checkFileLogger(context, logFile);
}
@Test
@Tag("json")
@LoggerContextSource("log4j-test1.json")
void json(final LoggerContext context) throws IOException {
checkConfiguration(context);
final Path logFile = loggingPath.resolve("test-json.log");
checkFileLogger(context, logFile);
}
@Test
@Tag("yaml")
@LoggerContextSource("log4j-test1.yaml")
void yaml(final LoggerContext context) throws IOException {
checkConfiguration(context);
final Path logFile = loggingPath.resolve("test-yaml.log");
checkFileLogger(context, logFile);
}
@Test
@LoggerContextSource("log4j-test1.properties")
void properties(final LoggerContext context) throws IOException {
checkConfiguration(context);
final Path logFile = loggingPath.resolve("test-properties.log");
checkFileLogger(context, logFile);
}
@Test
void testGetConfigurationWithNullUris() {
final ConfigurationFactory factory = Mockito.spy(ConfigurationFactory.getInstance());
try (final LoggerContext context = new LoggerContext("test")) {
assertThrows(NullPointerException.class, () -> factory.getConfiguration(context, "test", (List<URI>) null));
}
}
@Test
void testGetConfigurationWithEmptyUris() {
final ConfigurationFactory factory = Mockito.spy(ConfigurationFactory.getInstance());
try (final LoggerContext context = new LoggerContext("test")) {
factory.getConfiguration(context, "test", Collections.emptyList());
Mockito.verify(factory).getConfiguration(Mockito.same(context), Mockito.eq("test"), (URI) Mockito.isNull());
}
}
@Test
void testGetConfigurationWithNullInList() {
final ConfigurationFactory factory = Mockito.spy(ConfigurationFactory.getInstance());
try (final LoggerContext context = new LoggerContext("test")) {
final List<URI> listWithNull = Arrays.asList(URI.create("path:://to/nowhere"), null);
assertThrows(NullPointerException.class, () -> factory.getConfiguration(context, "test", listWithNull));
}
}
@Test
void testGetConfigurationWithSingleUri() throws Exception {
final ConfigurationFactory factory = Mockito.spy(ConfigurationFactory.getInstance());
try (final LoggerContext context = new LoggerContext("test")) {
final URI configLocation =
getClass().getResource("/log4j-test1.xml").toURI();
factory.getConfiguration(context, "test", Collections.singletonList(configLocation));
Mockito.verify(factory)
.getConfiguration(Mockito.same(context), Mockito.eq("test"), Mockito.eq(configLocation));
}
}
@Test
void testGetConfigurationWithMultipleUris() throws Exception {
final ConfigurationFactory factory = ConfigurationFactory.getInstance();
try (final LoggerContext context = new LoggerContext("test")) {
final URI configLocation1 =
getClass().getResource("/log4j-test1.xml").toURI();
final URI configLocation2 =
getClass().getResource("/log4j-xinclude.xml").toURI();
final List<URI> configLocations = Arrays.asList(configLocation1, configLocation2);
final Configuration config = factory.getConfiguration(context, "test", configLocations);
assertInstanceOf(CompositeConfiguration.class, config);
}
}
}
| ConfigurationFactoryTest |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/method/arrayinjection/B.java | {
"start": 784,
"end": 955
} | class ____ {
private List<A> all;
@Inject
void setA(A[] a) {
this.all = Arrays.asList(a);
}
List<A> getAll() {
return this.all;
}
}
| B |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/ReusingBuildFirstHashJoinIterator.java | {
"start": 1866,
"end": 6981
} | class ____<V1, V2, O> extends HashJoinIteratorBase
implements JoinTaskIterator<V1, V2, O> {
protected final MutableHashTable<V1, V2> hashJoin;
private final V1 nextBuildSideObject;
private final V1 tempBuildSideRecord;
protected final TypeSerializer<V2> probeSideSerializer;
private final MemoryManager memManager;
private final MutableObjectIterator<V1> firstInput;
private final MutableObjectIterator<V2> secondInput;
private final boolean probeSideOuterJoin;
private final boolean buildSideOuterJoin;
private volatile boolean running = true;
// --------------------------------------------------------------------------------------------
public ReusingBuildFirstHashJoinIterator(
MutableObjectIterator<V1> firstInput,
MutableObjectIterator<V2> secondInput,
TypeSerializer<V1> serializer1,
TypeComparator<V1> comparator1,
TypeSerializer<V2> serializer2,
TypeComparator<V2> comparator2,
TypePairComparator<V2, V1> pairComparator,
MemoryManager memManager,
IOManager ioManager,
AbstractInvokable ownerTask,
double memoryFraction,
boolean probeSideOuterJoin,
boolean buildSideOuterJoin,
boolean useBitmapFilters)
throws MemoryAllocationException {
this.memManager = memManager;
this.firstInput = firstInput;
this.secondInput = secondInput;
this.probeSideSerializer = serializer2;
if (useBitmapFilters && probeSideOuterJoin) {
throw new IllegalArgumentException(
"Bitmap filter may not be activated for joining with empty build side");
}
this.probeSideOuterJoin = probeSideOuterJoin;
this.buildSideOuterJoin = buildSideOuterJoin;
this.nextBuildSideObject = serializer1.createInstance();
this.tempBuildSideRecord = serializer1.createInstance();
this.hashJoin =
getHashJoin(
serializer1,
comparator1,
serializer2,
comparator2,
pairComparator,
memManager,
ioManager,
ownerTask,
memoryFraction,
useBitmapFilters);
}
// --------------------------------------------------------------------------------------------
@Override
public void open() throws IOException, MemoryAllocationException, InterruptedException {
this.hashJoin.open(this.firstInput, this.secondInput, buildSideOuterJoin);
}
@Override
public void close() {
// close the join
this.hashJoin.close();
// free the memory
final List<MemorySegment> segments = this.hashJoin.getFreedMemory();
this.memManager.release(segments);
}
@Override
public final boolean callWithNextKey(
FlatJoinFunction<V1, V2, O> matchFunction, Collector<O> collector) throws Exception {
if (this.hashJoin.nextRecord()) {
// we have a next record, get the iterators to the probe and build side values
final MutableObjectIterator<V1> buildSideIterator =
this.hashJoin.getBuildSideIterator();
final V2 probeRecord = this.hashJoin.getCurrentProbeRecord();
V1 nextBuildSideRecord = buildSideIterator.next(this.nextBuildSideObject);
if (probeRecord != null && nextBuildSideRecord != null) {
matchFunction.join(nextBuildSideRecord, probeRecord, collector);
while (this.running
&& ((nextBuildSideRecord = buildSideIterator.next(nextBuildSideRecord))
!= null)) {
matchFunction.join(nextBuildSideRecord, probeRecord, collector);
}
} else {
if (probeSideOuterJoin && probeRecord != null && nextBuildSideRecord == null) {
matchFunction.join(null, probeRecord, collector);
}
if (buildSideOuterJoin && probeRecord == null && nextBuildSideRecord != null) {
// call match on the first pair
matchFunction.join(nextBuildSideRecord, null, collector);
while (this.running
&& ((nextBuildSideRecord = buildSideIterator.next(nextBuildSideRecord))
!= null)) {
// call match on the next pair
// make sure we restore the value of the probe side record
matchFunction.join(nextBuildSideRecord, null, collector);
}
}
}
return true;
} else {
return false;
}
}
@Override
public void abort() {
this.running = false;
this.hashJoin.abort();
}
}
| ReusingBuildFirstHashJoinIterator |
java | apache__hadoop | hadoop-cloud-storage-project/hadoop-tos/src/test/java/org/apache/hadoop/fs/tosfs/commit/TestMRJob.java | {
"start": 1223,
"end": 2156
} | class ____ extends MRJobTestBase {
@BeforeAll
public static void beforeClass() throws IOException {
// Create the new configuration and set it to the IT Case.
Configuration newConf = new Configuration();
newConf.set("fs.defaultFS", String.format("tos://%s", TestUtility.bucket()));
// Application in yarn cluster cannot read the environment variables from user bash, so here we
// set it into the config manually.
newConf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key("tos"),
ParseUtils.envAsString(TOS.ENV_TOS_ENDPOINT, false));
newConf.set(TosKeys.FS_TOS_ACCESS_KEY_ID,
ParseUtils.envAsString(TOS.ENV_TOS_ACCESS_KEY_ID, false));
newConf.set(TosKeys.FS_TOS_SECRET_ACCESS_KEY,
ParseUtils.envAsString(TOS.ENV_TOS_SECRET_ACCESS_KEY, false));
MRJobTestBase.setConf(newConf);
// Continue to prepare the IT Case environments.
MRJobTestBase.beforeClass();
}
}
| TestMRJob |
java | apache__camel | components/camel-quartz/src/test/java/org/apache/camel/pollconsumer/quartz/FileConsumerQuartzSchedulerRestartTest.java | {
"start": 1198,
"end": 2543
} | class ____ extends CamelTestSupport {
@TempDir
Path testDirectory;
@Test
public void testQuartzSchedulerRestart() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBodyAndHeader(TestSupport.fileUri(testDirectory), "Hello World", Exchange.FILE_NAME, "hello.txt");
context.getRouteController().startRoute("foo");
MockEndpoint.assertIsSatisfied(context);
context.getRouteController().stopRoute("foo");
MockEndpoint.resetMocks(context);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBodyAndHeader(TestSupport.fileUri(testDirectory), "Bye World", Exchange.FILE_NAME, "bye.txt");
context.getRouteController().startRoute("foo");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(TestSupport.fileUri(testDirectory,
"?scheduler=quartz&scheduler.cron=0/2+*+*+*+*+?&scheduler.triggerGroup=myGroup&scheduler.triggerId=myId"))
.routeId("foo").noAutoStartup()
.to("mock:result");
}
};
}
}
| FileConsumerQuartzSchedulerRestartTest |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/jackson/ContextDataSerializer.java | {
"start": 1284,
"end": 2400
} | class ____ extends StdSerializer<ReadOnlyStringMap> {
private static final long serialVersionUID = 1L;
protected ContextDataSerializer() {
super(ReadOnlyStringMap.class);
}
@Override
public void serialize(
final ReadOnlyStringMap contextData, final JsonGenerator jgen, final SerializerProvider provider)
throws IOException, JsonGenerationException {
jgen.writeStartObject();
contextData.forEach(WRITE_STRING_FIELD_INTO, jgen);
jgen.writeEndObject();
}
private static final TriConsumer<String, Object, JsonGenerator> WRITE_STRING_FIELD_INTO =
(key, value, jsonGenerator) -> {
try {
if (value == null) {
jsonGenerator.writeNullField(key);
} else {
jsonGenerator.writeStringField(key, String.valueOf(value));
}
} catch (final Exception ex) {
throw new IllegalStateException("Problem with key " + key, ex);
}
};
}
| ContextDataSerializer |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/AbstractStructuredLoggingTests.java | {
"start": 1561,
"end": 2853
} | class ____ {
static final Instant EVENT_TIME = Instant.ofEpochMilli(1719910193000L);
private static final JsonMapper JSON_MAPPER = new JsonMapper();
@Mock
@SuppressWarnings("NullAway.Init")
StructuredLoggingJsonMembersCustomizer<?> customizer;
MockStructuredLoggingJsonMembersCustomizerBuilder<?> customizerBuilder = new MockStructuredLoggingJsonMembersCustomizerBuilder<>(
() -> this.customizer);
protected Map<String, Object> map(Object... values) {
assertThat(values.length).isEven();
Map<String, Object> result = new HashMap<>();
for (int i = 0; i < values.length; i += 2) {
result.put(values[i].toString(), values[i + 1]);
}
return result;
}
protected static MutableLogEvent createEvent() {
return createEvent(null);
}
protected static MutableLogEvent createEvent(@Nullable Throwable thrown) {
MutableLogEvent event = new MutableLogEvent();
event.setTimeMillis(EVENT_TIME.toEpochMilli());
event.setLevel(Level.INFO);
event.setThreadName("main");
event.setLoggerName("org.example.Test");
event.setMessage(new SimpleMessage("message"));
event.setThrown(thrown);
return event;
}
protected Map<String, Object> deserialize(String json) {
return JSON_MAPPER.readValue(json, new TypeReference<>() {
});
}
}
| AbstractStructuredLoggingTests |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java | {
"start": 13833,
"end": 14506
} | class ____ extends ESIntegTestCase {
* public void testMethod() {}
* }
* </pre>
* <p>
* If no {@link ClusterScope} annotation is present on an integration test the default scope is {@link Scope#SUITE}
* <p>
* A test cluster creates a set of nodes in the background before the test starts. The number of nodes in the cluster is
* determined at random and can change across tests. The {@link ClusterScope} allows configuring the initial number of nodes
* that are created before the tests start. More information about node configurations and settings in {@link InternalTestCluster}.
* <pre>
* {@literal @}NodeScope(scope=Scope.SUITE, numDataNodes=3)
* public | SomeIT |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/ClassTemplate.java | {
"start": 1472,
"end": 1631
} | class ____ full support for the same lifecycle callbacks and extensions.
*
* <p>{@code @ClassTemplate} may be combined with {@link Nested @Nested}, and a
* | with |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SharedSlot.java | {
"start": 14288,
"end": 14345
} | enum ____ {
ALLOCATED,
RELEASED
}
}
| State |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java | {
"start": 1687,
"end": 5018
} | class ____ extends Http2ChannelDuplexHandler {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(TripleServerConnectionHandler.class);
// Some exceptions are not very useful and add too much noise to the log
private static final Set<String> QUIET_EXCEPTIONS = new HashSet<>();
private static final Set<Class<?>> QUIET_EXCEPTIONS_CLASS = new HashSet<>();
static {
QUIET_EXCEPTIONS.add("NativeIoException");
QUIET_EXCEPTIONS_CLASS.add(IOException.class);
QUIET_EXCEPTIONS_CLASS.add(SocketException.class);
}
private GracefulShutdown gracefulShutdown;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2PingFrame) {
if (((Http2PingFrame) msg).content() == GRACEFUL_SHUTDOWN_PING) {
if (gracefulShutdown == null) {
// this should never happen
logger.warn(
PROTOCOL_FAILED_RESPONSE,
"",
"",
"Received GRACEFUL_SHUTDOWN_PING Ack but gracefulShutdown is null");
} else {
gracefulShutdown.secondGoAwayAndClose(ctx);
}
}
} else if (msg instanceof Http2GoAwayFrame) {
ReferenceCountUtil.release(msg);
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
// reset all active stream on connection close
forEachActiveStream(stream -> {
// ignore remote side close
if (!stream.state().remoteSideOpen()) {
return true;
}
DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(Http2Error.NO_ERROR).stream(stream);
ctx.fireChannelRead(resetFrame);
return true;
});
}
private boolean isQuiteException(Throwable t) {
if (QUIET_EXCEPTIONS_CLASS.contains(t.getClass())) {
return true;
}
return QUIET_EXCEPTIONS.contains(t.getClass().getSimpleName());
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// this may be change in future follow https://github.com/apache/dubbo/pull/8644
if (isQuiteException(cause)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Channel:%s Error", ctx.channel()), cause);
}
} else {
logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Channel:%s Error", ctx.channel()), cause);
}
ctx.close();
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (gracefulShutdown == null) {
gracefulShutdown = new GracefulShutdown(ctx, "app_requested", promise);
}
gracefulShutdown.gracefulShutdown();
}
}
| TripleServerConnectionHandler |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ConsulComponentBuilderFactory.java | {
"start": 1392,
"end": 1863
} | interface ____ {
/**
* Consul (camel-consul)
* Integrate with Consul service discovery and configuration store.
*
* Category: cloud,api
* Since: 2.18
* Maven coordinates: org.apache.camel:camel-consul
*
* @return the dsl builder
*/
static ConsulComponentBuilder consul() {
return new ConsulComponentBuilderImpl();
}
/**
* Builder for the Consul component.
*/
| ConsulComponentBuilderFactory |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/proxy/TrustedXForwarderProxiesHostnameFailureTest.java | {
"start": 180,
"end": 479
} | class ____ extends AbstractTrustedXForwarderProxiesTest {
@RegisterExtension
static final QuarkusUnitTest config = createTrustedProxyUnitTest("quarkus.io");
@Test
public void testHeadersAreIgnored() {
assertRequestFailure();
}
}
| TrustedXForwarderProxiesHostnameFailureTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/monitor/os/OsStats.java | {
"start": 14885,
"end": 22527
} | class ____ implements Writeable, ToXContentFragment {
private final String cpuAcctControlGroup;
private final BigInteger cpuAcctUsageNanos;
private final String cpuControlGroup;
private final long cpuCfsPeriodMicros;
private final long cpuCfsQuotaMicros;
private final CpuStat cpuStat;
private final String memoryControlGroup;
private final String memoryLimitInBytes;
private final String memoryUsageInBytes;
/**
* The control group for the {@code cpuacct} subsystem.
*
* @return the control group
*/
public String getCpuAcctControlGroup() {
return cpuAcctControlGroup;
}
/**
* The total CPU time consumed by all tasks in the
* {@code cpuacct} control group from
* {@link Cgroup#cpuAcctControlGroup}.
*
* @return the total CPU time in nanoseconds
*/
public BigInteger getCpuAcctUsageNanos() {
return cpuAcctUsageNanos;
}
/**
* The control group for the {@code cpu} subsystem.
*
* @return the control group
*/
public String getCpuControlGroup() {
return cpuControlGroup;
}
/**
* The period of time for how frequently the control group from
* {@link Cgroup#cpuControlGroup} has its access to CPU
* resources reallocated.
*
* @return the period of time in microseconds
*/
public long getCpuCfsPeriodMicros() {
return cpuCfsPeriodMicros;
}
/**
* The total amount of time for which all tasks in the control
* group from {@link Cgroup#cpuControlGroup} can run in one
* period as represented by {@link Cgroup#cpuCfsPeriodMicros}.
*
* @return the total amount of time in microseconds
*/
public long getCpuCfsQuotaMicros() {
return cpuCfsQuotaMicros;
}
/**
* The CPU time statistics. See {@link CpuStat}.
*
* @return the CPU time statistics.
*/
public CpuStat getCpuStat() {
return cpuStat;
}
/**
* The control group for the {@code memory} subsystem.
*
* @return the control group
*/
public String getMemoryControlGroup() {
return memoryControlGroup;
}
/**
* The maximum amount of user memory (including file cache).
* This is stored as a <code>String</code> because the value can be too big to fit in a
* <code>long</code>. (The alternative would have been <code>BigInteger</code> but then
* it would not be possible to index the OS stats document into Elasticsearch without
* losing information, as <code>BigInteger</code> is not a supported Elasticsearch type.)
*
* @return the maximum amount of user memory (including file cache).
*/
public String getMemoryLimitInBytes() {
return memoryLimitInBytes;
}
/**
* The total current memory usage by processes in the cgroup (in bytes).
* This is stored as a <code>String</code> for consistency with <code>memoryLimitInBytes</code>.
*
* @return the total current memory usage by processes in the cgroup (in bytes).
*/
public String getMemoryUsageInBytes() {
return memoryUsageInBytes;
}
public Cgroup(
final String cpuAcctControlGroup,
final BigInteger cpuAcctUsageNanos,
final String cpuControlGroup,
final long cpuCfsPeriodMicros,
final long cpuCfsQuotaMicros,
final CpuStat cpuStat,
final String memoryControlGroup,
final String memoryLimitInBytes,
final String memoryUsageInBytes
) {
this.cpuAcctControlGroup = Objects.requireNonNull(cpuAcctControlGroup);
this.cpuAcctUsageNanos = cpuAcctUsageNanos;
this.cpuControlGroup = Objects.requireNonNull(cpuControlGroup);
this.cpuCfsPeriodMicros = cpuCfsPeriodMicros;
this.cpuCfsQuotaMicros = cpuCfsQuotaMicros;
this.cpuStat = Objects.requireNonNull(cpuStat);
this.memoryControlGroup = memoryControlGroup;
this.memoryLimitInBytes = memoryLimitInBytes;
this.memoryUsageInBytes = memoryUsageInBytes;
}
Cgroup(final StreamInput in) throws IOException {
cpuAcctControlGroup = in.readString();
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_17_0)) {
cpuAcctUsageNanos = in.readBigInteger();
} else {
cpuAcctUsageNanos = BigInteger.valueOf(in.readLong());
}
cpuControlGroup = in.readString();
cpuCfsPeriodMicros = in.readLong();
cpuCfsQuotaMicros = in.readLong();
cpuStat = new CpuStat(in);
memoryControlGroup = in.readOptionalString();
memoryLimitInBytes = in.readOptionalString();
memoryUsageInBytes = in.readOptionalString();
}
@Override
public void writeTo(final StreamOutput out) throws IOException {
out.writeString(cpuAcctControlGroup);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_17_0)) {
out.writeBigInteger(cpuAcctUsageNanos);
} else {
out.writeLong(cpuAcctUsageNanos.longValue());
}
out.writeString(cpuControlGroup);
out.writeLong(cpuCfsPeriodMicros);
out.writeLong(cpuCfsQuotaMicros);
cpuStat.writeTo(out);
out.writeOptionalString(memoryControlGroup);
out.writeOptionalString(memoryLimitInBytes);
out.writeOptionalString(memoryUsageInBytes);
}
@Override
public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException {
builder.startObject("cgroup");
{
builder.startObject("cpuacct");
{
builder.field("control_group", cpuAcctControlGroup);
builder.field("usage_nanos", cpuAcctUsageNanos);
}
builder.endObject();
builder.startObject("cpu");
{
builder.field("control_group", cpuControlGroup);
builder.field("cfs_period_micros", cpuCfsPeriodMicros);
builder.field("cfs_quota_micros", cpuCfsQuotaMicros);
cpuStat.toXContent(builder, params);
}
builder.endObject();
if (memoryControlGroup != null) {
builder.startObject("memory");
{
builder.field("control_group", memoryControlGroup);
if (memoryLimitInBytes != null) {
builder.field("limit_in_bytes", memoryLimitInBytes);
}
if (memoryUsageInBytes != null) {
builder.field("usage_in_bytes", memoryUsageInBytes);
}
}
builder.endObject();
}
}
builder.endObject();
return builder;
}
/**
* Encapsulates CPU time statistics.
*/
public static | Cgroup |
java | apache__spark | common/network-yarn/src/main/java/org/apache/spark/network/yarn/YarnShuffleServiceMetrics.java | {
"start": 1297,
"end": 5783
} | class ____ implements MetricsSource {
private final String metricsNamespace;
private final MetricSet metricSet;
YarnShuffleServiceMetrics(String metricsNamespace, MetricSet metricSet) {
this.metricsNamespace = metricsNamespace;
this.metricSet = metricSet;
}
/**
* Get metrics from the source
*
* @param collector to contain the resulting metrics snapshot
* @param all if true, return all metrics even if unchanged.
*/
@Override
public void getMetrics(MetricsCollector collector, boolean all) {
MetricsRecordBuilder metricsRecordBuilder = collector.addRecord(metricsNamespace);
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
collectMetric(metricsRecordBuilder, entry.getKey(), entry.getValue());
}
}
/**
* The metric types used in
* {@link org.apache.spark.network.shuffle.ExternalBlockHandler.ShuffleMetrics}.
* Visible for testing.
*/
public static void collectMetric(
MetricsRecordBuilder metricsRecordBuilder, String name, Metric metric) {
if (metric instanceof Timer t) {
// Timer records both the operations count and delay
// Snapshot inside the Timer provides the information for the operation delay
Snapshot snapshot = t.getSnapshot();
metricsRecordBuilder
.addCounter(new ShuffleServiceMetricsInfo(name + "_count", "Count of timer " + name),
t.getCount())
.addGauge(
new ShuffleServiceMetricsInfo(name + "_rate15", "15 minute rate of timer " + name),
t.getFifteenMinuteRate())
.addGauge(
new ShuffleServiceMetricsInfo(name + "_rate5", "5 minute rate of timer " + name),
t.getFiveMinuteRate())
.addGauge(
new ShuffleServiceMetricsInfo(name + "_rate1", "1 minute rate of timer " + name),
t.getOneMinuteRate())
.addGauge(new ShuffleServiceMetricsInfo(name + "_rateMean", "Mean rate of timer " + name),
t.getMeanRate())
.addGauge(
getShuffleServiceMetricsInfoForGenericValue(name, "max"), snapshot.getMax())
.addGauge(
getShuffleServiceMetricsInfoForGenericValue(name, "min"), snapshot.getMin())
.addGauge(
getShuffleServiceMetricsInfoForGenericValue(name, "mean"), snapshot.getMean())
.addGauge(
getShuffleServiceMetricsInfoForGenericValue(name, "stdDev"), snapshot.getStdDev());
for (int percentileThousands : new int[] { 10, 50, 250, 500, 750, 950, 980, 990, 999 }) {
String percentileStr = switch (percentileThousands) {
case 10 -> "1stPercentile";
case 999 -> "999thPercentile";
default -> String.format("%dthPercentile", percentileThousands / 10);
};
metricsRecordBuilder.addGauge(
getShuffleServiceMetricsInfoForGenericValue(name, percentileStr),
snapshot.getValue(percentileThousands / 1000.0));
}
} else if (metric instanceof Meter m) {
metricsRecordBuilder
.addCounter(new ShuffleServiceMetricsInfo(name + "_count", "Count of meter " + name),
m.getCount())
.addGauge(
new ShuffleServiceMetricsInfo(name + "_rate15", "15 minute rate of meter " + name),
m.getFifteenMinuteRate())
.addGauge(
new ShuffleServiceMetricsInfo(name + "_rate5", "5 minute rate of meter " + name),
m.getFiveMinuteRate())
.addGauge(
new ShuffleServiceMetricsInfo(name + "_rate1", "1 minute rate of meter " + name),
m.getOneMinuteRate())
.addGauge(new ShuffleServiceMetricsInfo(name + "_rateMean", "Mean rate of meter " + name),
m.getMeanRate());
} else if (metric instanceof Gauge gauge) {
final Object gaugeValue = gauge.getValue();
if (gaugeValue instanceof Integer integer) {
metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfoForGauge(name), integer);
} else if (gaugeValue instanceof Long longVal) {
metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfoForGauge(name), longVal);
} else if (gaugeValue instanceof Float floatVal) {
metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfoForGauge(name), floatVal);
} else if (gaugeValue instanceof Double doubleVal) {
metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfoForGauge(name), doubleVal);
} else {
throw new IllegalStateException(
"Not supported | YarnShuffleServiceMetrics |
java | alibaba__druid | druid-spring-boot-3-starter/src/test/java/com/alibaba/druid/spring/boot3/demo/web/DruidStatController.java | {
"start": 250,
"end": 558
} | class ____ {
@GetMapping("/durid/stat")
public Object druidStat() {
// DruidStatManagerFacade#getDataSourceStatDataList 该方法可以获取所有数据源的监控数据,除此之外 DruidStatManagerFacade 还提供了一些其他方法,你可以按需选择使用。
return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
}
}
| DruidStatController |
java | apache__camel | components/camel-ai/camel-langchain4j-agent-api/src/main/java/org/apache/camel/component/langchain4j/agent/api/AgentConfiguration.java | {
"start": 8836,
"end": 8982
} | class ____ into a list of loaded classes.
*
* <p>
* This utility method takes a string containing comma-separated fully qualified | names |
java | apache__logging-log4j2 | log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/ConcurrentAsyncLoggerToFileBenchmark.java | {
"start": 6058,
"end": 6296
} | class ____ implements AsyncQueueFullPolicy {
@Override
public EventRoute getRoute(final long backgroundThreadId, final Level level) {
return EventRoute.SYNCHRONOUS;
}
}
}
| SynchronousAsyncQueueFullPolicy |
java | micronaut-projects__micronaut-core | http-client-core/src/main/java/io/micronaut/http/client/exceptions/HttpClientErrorDecoder.java | {
"start": 945,
"end": 1065
} | interface ____ decoding the error from a server respponse.
*
* @author graemerocher
* @since 1.0
*/
@Internal
public | for |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskCurrentAttemptDetailsHandlerTest.java | {
"start": 2902,
"end": 8918
} | class ____ {
@Test
void testHandleRequest() throws Exception {
// Prepare the execution graph.
final JobID jobID = new JobID();
final JobVertexID jobVertexID = new JobVertexID();
// The testing subtask.
final long deployingTs = System.currentTimeMillis() - 1024;
final long finishedTs = System.currentTimeMillis();
final long bytesIn = 1L;
final long bytesOut = 10L;
final long recordsIn = 20L;
final long recordsOut = 30L;
final long accumulateIdleTime = 40L;
final long accumulateBusyTime = 50L;
final long accumulateBackPressuredTime = 60L;
final IOMetrics ioMetrics =
new IOMetrics(
bytesIn,
bytesOut,
recordsIn,
recordsOut,
accumulateIdleTime,
accumulateBusyTime,
accumulateBackPressuredTime);
final long[] timestamps = new long[ExecutionState.values().length];
final long[] endTimestamps = new long[ExecutionState.values().length];
timestamps[ExecutionState.DEPLOYING.ordinal()] = deployingTs;
endTimestamps[ExecutionState.DEPLOYING.ordinal()] = deployingTs + 10;
final ExecutionState expectedState = ExecutionState.FINISHED;
timestamps[expectedState.ordinal()] = finishedTs;
final LocalTaskManagerLocation assignedResourceLocation = new LocalTaskManagerLocation();
final AllocationID allocationID = new AllocationID();
final int subtaskIndex = 1;
final int attempt = 2;
final ArchivedExecution execution =
new ArchivedExecution(
new StringifiedAccumulatorResult[0],
ioMetrics,
createExecutionAttemptId(jobVertexID, subtaskIndex, attempt),
expectedState,
null,
assignedResourceLocation,
allocationID,
timestamps,
endTimestamps);
final ArchivedExecutionVertex executionVertex =
new ArchivedExecutionVertex(
subtaskIndex,
"Test archived execution vertex",
execution,
new ExecutionHistory(0));
// Instance the handler.
final RestHandlerConfiguration restHandlerConfiguration =
RestHandlerConfiguration.fromConfiguration(new Configuration());
final MetricFetcher metricFetcher =
new MetricFetcherImpl<>(
() -> null,
address -> null,
Executors.directExecutor(),
Duration.ofMillis(1000L),
MetricOptions.METRIC_FETCHER_UPDATE_INTERVAL.defaultValue().toMillis());
final SubtaskCurrentAttemptDetailsHandler handler =
new SubtaskCurrentAttemptDetailsHandler(
() -> null,
Duration.ofMillis(100),
Collections.emptyMap(),
SubtaskCurrentAttemptDetailsHeaders.getInstance(),
new DefaultExecutionGraphCache(
restHandlerConfiguration.getTimeout(),
Duration.ofMillis(restHandlerConfiguration.getRefreshInterval())),
Executors.directExecutor(),
metricFetcher);
final HashMap<String, String> receivedPathParameters = new HashMap<>(2);
receivedPathParameters.put(JobIDPathParameter.KEY, jobID.toString());
receivedPathParameters.put(JobVertexIdPathParameter.KEY, jobVertexID.toString());
final HandlerRequest<EmptyRequestBody> request =
HandlerRequest.resolveParametersAndCreate(
EmptyRequestBody.getInstance(),
new SubtaskMessageParameters(),
receivedPathParameters,
Collections.emptyMap(),
Collections.emptyList());
// Handle request.
final SubtaskExecutionAttemptDetailsInfo detailsInfo =
handler.handleRequest(request, executionVertex);
// Verify
final IOMetricsInfo ioMetricsInfo =
new IOMetricsInfo(
bytesIn,
true,
bytesOut,
true,
recordsIn,
true,
recordsOut,
true,
accumulateBackPressuredTime,
accumulateIdleTime,
accumulateBusyTime);
final Map<ExecutionState, Long> statusDuration = new HashMap<>();
statusDuration.put(ExecutionState.CREATED, -1L);
statusDuration.put(ExecutionState.SCHEDULED, -1L);
statusDuration.put(ExecutionState.DEPLOYING, 10L);
statusDuration.put(ExecutionState.INITIALIZING, -1L);
statusDuration.put(ExecutionState.RUNNING, -1L);
final SubtaskExecutionAttemptDetailsInfo expectedDetailsInfo =
new SubtaskExecutionAttemptDetailsInfo(
subtaskIndex,
expectedState,
attempt,
assignedResourceLocation.getEndpoint(),
deployingTs,
finishedTs,
finishedTs - deployingTs,
ioMetricsInfo,
assignedResourceLocation.getResourceID().getResourceIdString(),
statusDuration,
null);
assertThat(detailsInfo).isEqualTo(expectedDetailsInfo);
}
}
| SubtaskCurrentAttemptDetailsHandlerTest |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/reflection/factory/ObjectFactory.java | {
"start": 860,
"end": 2116
} | interface ____ {
/**
* Sets configuration properties.
*
* @param properties
* configuration properties
*/
default void setProperties(Properties properties) {
// NOP
}
/**
* Creates a new object with default constructor.
*
* @param <T>
* the generic type
* @param type
* Object type
*
* @return the t
*/
<T> T create(Class<T> type);
/**
* Creates a new object with the specified constructor and params.
*
* @param <T>
* the generic type
* @param type
* Object type
* @param constructorArgTypes
* Constructor argument types
* @param constructorArgs
* Constructor argument values
*
* @return the t
*/
<T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);
/**
* Returns true if this object can have a set of other objects. It's main purpose is to support
* non-java.util.Collection objects like Scala collections.
*
* @param <T>
* the generic type
* @param type
* Object type
*
* @return whether it is a collection or not
*
* @since 3.1.0
*/
<T> boolean isCollection(Class<T> type);
}
| ObjectFactory |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java | {
"start": 1391,
"end": 1582
} | class ____ {
/**
* Create a new BeanShell-scripted object from the given script source.
* <p>With this {@code createBshObject} variant, the script needs to
* declare a full | BshScriptUtils |
java | netty__netty | codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicChannel.java | {
"start": 81837,
"end": 86956
} | class ____ implements Runnable {
private ScheduledFuture<?> timeoutFuture;
@Override
public void run() {
QuicheQuicConnection conn = connection;
if (conn.isFreed()) {
return;
}
if (!freeIfClosed()) {
long connAddr = conn.address();
timeoutFuture = null;
// Notify quiche there was a timeout.
Quiche.quiche_conn_on_timeout(connAddr);
if (!freeIfClosed()) {
// We need to call connectionSend when a timeout was triggered.
// See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.send.
if (connectionSend(conn) != SendResult.NONE) {
flushParent();
}
boolean closed = freeIfClosed();
if (!closed) {
// The connection is alive, reschedule.
scheduleTimeout();
}
}
}
}
// Schedule timeout.
// See https://docs.rs/quiche/0.6.0/quiche/#generating-outgoing-packets
void scheduleTimeout() {
QuicheQuicConnection conn = connection;
if (conn.isFreed()) {
cancel();
return;
}
if (conn.isClosed()) {
cancel();
unsafe().close(newPromise());
return;
}
long nanos = Quiche.quiche_conn_timeout_as_nanos(conn.address());
if (nanos < 0 || nanos == Long.MAX_VALUE) {
// No timeout needed.
cancel();
return;
}
if (timeoutFuture == null) {
timeoutFuture = eventLoop().schedule(this,
nanos, TimeUnit.NANOSECONDS);
} else {
long remaining = timeoutFuture.getDelay(TimeUnit.NANOSECONDS);
if (remaining <= 0) {
// This means the timer already elapsed. In this case just cancel the future and call run()
// directly. This will ensure we correctly call quiche_conn_on_timeout() etc.
cancel();
run();
} else if (remaining > nanos) {
// The new timeout is smaller then what was scheduled before. Let's cancel the old timeout
// and schedule a new one.
cancel();
timeoutFuture = eventLoop().schedule(this, nanos, TimeUnit.NANOSECONDS);
}
}
}
void cancel() {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
timeoutFuture = null;
}
}
}
@Override
public Future<QuicConnectionStats> collectStats(Promise<QuicConnectionStats> promise) {
if (eventLoop().inEventLoop()) {
collectStats0(promise);
} else {
eventLoop().execute(() -> collectStats0(promise));
}
return promise;
}
private void collectStats0(Promise<QuicConnectionStats> promise) {
QuicheQuicConnection conn = connection;
if (conn.isFreed()) {
promise.setSuccess(statsAtClose);
return;
}
collectStats0(connection, promise);
}
@Nullable
private QuicConnectionStats collectStats0(QuicheQuicConnection connection, Promise<QuicConnectionStats> promise) {
final long[] stats = Quiche.quiche_conn_stats(connection.address());
if (stats == null) {
promise.setFailure(new IllegalStateException("native quiche_conn_stats(...) failed"));
return null;
}
final QuicheQuicConnectionStats connStats =
new QuicheQuicConnectionStats(stats);
promise.setSuccess(connStats);
return connStats;
}
@Override
public Future<QuicConnectionPathStats> collectPathStats(int pathIdx, Promise<QuicConnectionPathStats> promise) {
if (eventLoop().inEventLoop()) {
collectPathStats0(pathIdx, promise);
} else {
eventLoop().execute(() -> collectPathStats0(pathIdx, promise));
}
return promise;
}
private void collectPathStats0(int pathIdx, Promise<QuicConnectionPathStats> promise) {
QuicheQuicConnection conn = connection;
if (conn.isFreed()) {
promise.setFailure(new IllegalStateException("Connection is closed"));
return;
}
final Object[] stats = Quiche.quiche_conn_path_stats(connection.address(), pathIdx);
if (stats == null) {
promise.setFailure(new IllegalStateException("native quiche_conn_path_stats(...) failed"));
return;
}
promise.setSuccess(new QuicheQuicConnectionPathStats(stats));
}
@Override
public QuicTransportParameters peerTransportParameters() {
return connection.peerParameters();
}
}
| TimeoutHandler |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java | {
"start": 17877,
"end": 18126
} | class ____ {
@Bean
TestEndpoint testEndpointTwo() {
return new TestEndpoint();
}
@Bean
TestEndpoint testEndpointOne() {
return new TestEndpoint();
}
}
@Configuration(proxyBeanMethods = false)
static | ClashingEndpointConfiguration |
java | spring-projects__spring-security | buildSrc/src/test/java/org/springframework/gradle/xsd/CreateVersionlessXsdTaskTests.java | {
"start": 997,
"end": 3142
} | class ____ {
@Test
void xsdCreateWhenValid() {
File file = new File("spring-security-2.0.xsd");
XsdFileMajorMinorVersion xsdFile = XsdFileMajorMinorVersion.create(file);
assertThat(xsdFile).isNotNull();
assertThat(xsdFile.getFile()).isEqualTo(file);
assertThat(xsdFile.getVersion().getMajor()).isEqualTo(2);
assertThat(xsdFile.getVersion().getMinor()).isEqualTo(0);
}
@Test
void xsdCreateWhenPatchReleaseThenNull() {
File file = new File("spring-security-2.0.1.xsd");
XsdFileMajorMinorVersion xsdFile = XsdFileMajorMinorVersion.create(file);
assertThat(xsdFile).isNull();
}
@Test
void xsdCreateWhenNotXsdFileThenNull() {
File file = new File("spring-security-2.0.txt");
XsdFileMajorMinorVersion xsdFile = XsdFileMajorMinorVersion.create(file);
assertThat(xsdFile).isNull();
}
@Test
void xsdCreateWhenNotStartWithSpringSecurityThenNull() {
File file = new File("spring-securityNO-2.0.xsd");
XsdFileMajorMinorVersion xsdFile = XsdFileMajorMinorVersion.create(file);
assertThat(xsdFile).isNull();
}
@Test
void isGreaterWhenMajorLarger() {
MajorMinorVersion larger = new MajorMinorVersion(2,0);
MajorMinorVersion smaller = new MajorMinorVersion(1,0);
assertThat(larger.isGreaterThan(smaller)).isTrue();
assertThat(smaller.isGreaterThan(larger)).isFalse();
}
@Test
void isGreaterWhenMinorLarger() {
MajorMinorVersion larger = new MajorMinorVersion(1,1);
MajorMinorVersion smaller = new MajorMinorVersion(1,0);
assertThat(larger.isGreaterThan(smaller)).isTrue();
assertThat(smaller.isGreaterThan(larger)).isFalse();
}
@Test
void isGreaterWhenMajorAndMinorLarger() {
MajorMinorVersion larger = new MajorMinorVersion(2,1);
MajorMinorVersion smaller = new MajorMinorVersion(1,0);
assertThat(larger.isGreaterThan(smaller)).isTrue();
assertThat(smaller.isGreaterThan(larger)).isFalse();
}
@Test
void isGreaterWhenSame() {
MajorMinorVersion first = new MajorMinorVersion(1,0);
MajorMinorVersion second = new MajorMinorVersion(1,0);
assertThat(first.isGreaterThan(second)).isFalse();
assertThat(second.isGreaterThan(first)).isFalse();
}
}
| CreateVersionlessXsdTaskTests |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/util/SingleElementIterator.java | {
"start": 1072,
"end": 2003
} | class ____<E> implements Iterator<E>, Iterable<E> {
private E current;
private boolean available = false;
/**
* Resets the element. After this call, the iterator has one element available, which is the
* given element.
*
* @param current The element to make available to the iterator.
*/
public void set(E current) {
this.current = current;
this.available = true;
}
@Override
public boolean hasNext() {
return available;
}
@Override
public E next() {
if (available) {
available = false;
return current;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<E> iterator() {
available = true;
return this;
}
}
| SingleElementIterator |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DefaultMessageHandlerMethodFactoryTests.java | {
"start": 2127,
"end": 8062
} | class ____ {
private final SampleBean sample = new SampleBean();
@Test
void customConversion() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
GenericConversionService conversionService = new GenericConversionService();
conversionService.addConverter(SampleBean.class, String.class, source -> "foo bar");
instance.setConversionService(conversionService);
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "simpleString", String.class);
invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
assertMethodInvocation(sample, "simpleString");
}
@Test
void customConversionServiceFailure() {
DefaultMessageHandlerMethodFactory instance = createInstance();
GenericConversionService conversionService = new GenericConversionService();
assertThat(conversionService.canConvert(Integer.class, String.class)).as("conversion service should fail to convert payload").isFalse();
instance.setConversionService(conversionService);
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "simpleString", String.class);
assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() ->
invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build()));
}
@Test
void customMessageConverterFailure() {
DefaultMessageHandlerMethodFactory instance = createInstance();
MessageConverter messageConverter = new ByteArrayMessageConverter();
instance.setMessageConverter(messageConverter);
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "simpleString", String.class);
assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() ->
invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build()));
}
@Test
void customArgumentResolver() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<>();
customResolvers.add(new CustomHandlerMethodArgumentResolver());
instance.setCustomArgumentResolvers(customResolvers);
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "customArgumentResolver", Locale.class);
invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build());
assertMethodInvocation(sample, "customArgumentResolver");
}
@Test
void overrideArgumentResolvers() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<>();
customResolvers.add(new CustomHandlerMethodArgumentResolver());
instance.setArgumentResolvers(customResolvers);
instance.afterPropertiesSet();
Message<String> message = MessageBuilder.withPayload("sample").build();
// This will work as the local resolver is set
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "customArgumentResolver", Locale.class);
invocableHandlerMethod.invoke(message);
assertMethodInvocation(sample, "customArgumentResolver");
// This won't work as no resolver is known for the payload
InvocableHandlerMethod invocableHandlerMethod2 =
createInvocableHandlerMethod(instance, "simpleString", String.class);
assertThatExceptionOfType(MethodArgumentResolutionException.class).isThrownBy(() ->
invocableHandlerMethod2.invoke(message)).withMessageContaining("No suitable resolver");
}
@Test
void noValidationByDefault() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "payloadValidation", String.class);
invocableHandlerMethod.invoke(MessageBuilder.withPayload("failure").build());
assertMethodInvocation(sample, "payloadValidation");
}
@Test
void customValidation() {
DefaultMessageHandlerMethodFactory instance = createInstance();
instance.setValidator(new Validator() {
@Override
public boolean supports(Class<?> clazz) {
return String.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
String value = (String) target;
if ("failure".equals(value)) {
errors.reject("not a valid value");
}
}
});
instance.afterPropertiesSet();
InvocableHandlerMethod invocableHandlerMethod =
createInvocableHandlerMethod(instance, "payloadValidation", String.class);
assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() ->
invocableHandlerMethod.invoke(MessageBuilder.withPayload("failure").build()));
}
private void assertMethodInvocation(SampleBean bean, String methodName) {
assertThat((boolean) bean.invocations.get(methodName)).as("Method " + methodName + " should have been invoked").isTrue();
}
private InvocableHandlerMethod createInvocableHandlerMethod(
DefaultMessageHandlerMethodFactory factory, String methodName, Class<?>... parameterTypes) {
return factory.createInvocableHandlerMethod(sample, getListenerMethod(methodName, parameterTypes));
}
private DefaultMessageHandlerMethodFactory createInstance() {
DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setBeanFactory(new StaticListableBeanFactory());
return factory;
}
private Method getListenerMethod(String methodName, Class<?>... parameterTypes) {
Method method = ReflectionUtils.findMethod(SampleBean.class, methodName, parameterTypes);
assertThat(("no method found with name " + methodName + " and parameters " + Arrays.toString(parameterTypes))).isNotNull();
return method;
}
static | DefaultMessageHandlerMethodFactoryTests |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/plugin/PluginRealmCache.java | {
"start": 1503,
"end": 1571
} | interface ____ {
/**
* CacheRecord
*/
| PluginRealmCache |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/binding/ComponentDescriptor.java | {
"start": 21346,
"end": 30704
} | class ____ implements ClearableCache {
private final XProcessingEnv processingEnv;
private final BindingFactory bindingFactory;
private final DependencyRequestFactory dependencyRequestFactory;
private final ModuleDescriptor.Factory moduleDescriptorFactory;
private final InjectionAnnotations injectionAnnotations;
private final DaggerSuperficialValidation superficialValidation;
private final Map<XTypeElement, ComponentDescriptor> cache = new HashMap<>();
@Inject
Factory(
XProcessingEnv processingEnv,
BindingFactory bindingFactory,
DependencyRequestFactory dependencyRequestFactory,
ModuleDescriptor.Factory moduleDescriptorFactory,
InjectionAnnotations injectionAnnotations,
DaggerSuperficialValidation superficialValidation) {
this.processingEnv = processingEnv;
this.bindingFactory = bindingFactory;
this.dependencyRequestFactory = dependencyRequestFactory;
this.moduleDescriptorFactory = moduleDescriptorFactory;
this.injectionAnnotations = injectionAnnotations;
this.superficialValidation = superficialValidation;
}
/** Returns a descriptor for a root component type. */
public ComponentDescriptor rootComponentDescriptor(XTypeElement typeElement) {
Optional<ComponentAnnotation> annotation =
rootComponentAnnotation(typeElement, superficialValidation);
checkArgument(annotation.isPresent(), "%s must have a component annotation", typeElement);
return create(typeElement, annotation.get());
}
/** Returns a descriptor for a subcomponent type. */
public ComponentDescriptor subcomponentDescriptor(XTypeElement typeElement) {
Optional<ComponentAnnotation> annotation =
subcomponentAnnotation(typeElement, superficialValidation);
checkArgument(annotation.isPresent(), "%s must have a subcomponent annotation", typeElement);
return create(typeElement, annotation.get());
}
/**
* Returns a descriptor for a fictional component based on a module type in order to validate
* its bindings.
*/
public ComponentDescriptor moduleComponentDescriptor(XTypeElement typeElement) {
Optional<ModuleAnnotation> annotation = moduleAnnotation(typeElement, superficialValidation);
checkArgument(annotation.isPresent(), "%s must have a module annotation", typeElement);
return create(typeElement, ComponentAnnotation.fromModuleAnnotation(annotation.get()));
}
private ComponentDescriptor create(
XTypeElement typeElement, ComponentAnnotation componentAnnotation) {
return reentrantComputeIfAbsent(
cache, typeElement, unused -> createUncached(typeElement, componentAnnotation));
}
private ComponentDescriptor createUncached(
XTypeElement typeElement, ComponentAnnotation componentAnnotation) {
ImmutableSet<ComponentRequirement> componentDependencies =
componentAnnotation.dependencyTypes().stream()
.map(ComponentRequirement::forDependency)
.collect(toImmutableSet());
// Start with the component's modules. For fictional components built from a module, start
// with that module.
ImmutableSet<XTypeElement> modules =
componentAnnotation.isRealComponent()
? componentAnnotation.modules()
: ImmutableSet.of(typeElement);
ImmutableSet<ModuleDescriptor> transitiveModules =
moduleDescriptorFactory.transitiveModules(modules);
ImmutableSet.Builder<ComponentMethodDescriptor> componentMethodsBuilder =
ImmutableSet.builder();
ImmutableBiMap.Builder<ComponentMethodDescriptor, ComponentDescriptor>
subcomponentsByFactoryMethod = ImmutableBiMap.builder();
ImmutableMap.Builder<ComponentMethodDescriptor, ComponentDescriptor>
subcomponentsByBuilderMethod = ImmutableBiMap.builder();
if (componentAnnotation.isRealComponent()) {
for (XMethodElement componentMethod : getAllUnimplementedMethods(typeElement)) {
ComponentMethodDescriptor componentMethodDescriptor =
getDescriptorForComponentMethod(componentAnnotation, typeElement, componentMethod);
componentMethodsBuilder.add(componentMethodDescriptor);
componentMethodDescriptor
.subcomponent()
.ifPresent(
subcomponent -> {
// If the dependency request is present, that means the method returns the
// subcomponent factory.
if (componentMethodDescriptor.dependencyRequest().isPresent()) {
subcomponentsByBuilderMethod.put(componentMethodDescriptor, subcomponent);
} else {
subcomponentsByFactoryMethod.put(componentMethodDescriptor, subcomponent);
}
});
}
}
// Validation should have ensured that this set will have at most one element.
ImmutableSet<XTypeElement> enclosedCreators =
enclosedAnnotatedTypes(typeElement, creatorAnnotationsFor(componentAnnotation));
Optional<ComponentCreatorDescriptor> creatorDescriptor =
enclosedCreators.isEmpty()
? Optional.empty()
: Optional.of(
ComponentCreatorDescriptor.create(
getOnlyElement(enclosedCreators), dependencyRequestFactory));
ImmutableSet<Scope> scopes = injectionAnnotations.getScopes(typeElement);
if (componentAnnotation.isProduction()) {
scopes =
ImmutableSet.<Scope>builder()
.addAll(scopes).add(productionScope(processingEnv))
.build();
}
ImmutableSet<ComponentDescriptor> subcomponentsFromModules =
transitiveModules.stream()
.flatMap(transitiveModule -> transitiveModule.subcomponentDeclarations().stream())
.map(SubcomponentDeclaration::subcomponentType)
.map(this::subcomponentDescriptor)
.collect(toImmutableSet());
ComponentDescriptor componentDescriptor =
new AutoValue_ComponentDescriptor(
componentAnnotation,
typeElement,
componentDependencies,
transitiveModules,
scopes,
subcomponentsFromModules,
subcomponentsByFactoryMethod.buildOrThrow(),
subcomponentsByBuilderMethod.buildOrThrow(),
componentMethodsBuilder.build(),
creatorDescriptor);
componentDescriptor.bindingFactory = bindingFactory;
return componentDescriptor;
}
private ComponentMethodDescriptor getDescriptorForComponentMethod(
ComponentAnnotation componentAnnotation,
XTypeElement componentElement,
XMethodElement componentMethod) {
ComponentMethodDescriptor.Builder descriptor =
ComponentMethodDescriptor.builder(componentMethod);
XMethodType resolvedComponentMethod = componentMethod.asMemberOf(componentElement.getType());
XType returnType = resolvedComponentMethod.getReturnType();
if (isDeclared(returnType)
&& !injectionAnnotations.getQualifier(componentMethod).isPresent()) {
XTypeElement returnTypeElement = returnType.getTypeElement();
if (hasAnyAnnotation(returnTypeElement, subcomponentAnnotations())) {
// It's a subcomponent factory method. There is no dependency request, and there could be
// any number of parameters. Just return the descriptor.
return descriptor.subcomponent(subcomponentDescriptor(returnTypeElement)).build();
}
if (isSubcomponentCreator(returnTypeElement)) {
descriptor.subcomponent(
subcomponentDescriptor(returnTypeElement.getEnclosingTypeElement()));
}
}
switch (componentMethod.getParameters().size()) {
case 0:
checkArgument(
!isVoid(returnType), "component method cannot be void: %s", componentMethod);
descriptor.dependencyRequest(
componentAnnotation.isProduction()
? dependencyRequestFactory.forComponentProductionMethod(
componentMethod, resolvedComponentMethod)
: dependencyRequestFactory.forComponentProvisionMethod(
componentMethod, resolvedComponentMethod));
break;
case 1:
checkArgument(
isVoid(returnType)
// TODO(bcorso): Replace this with isSameType()?
|| returnType
.getTypeName()
.equals(resolvedComponentMethod.getParameterTypes().get(0).getTypeName()),
"members injection method must return void or parameter type: %s",
componentMethod);
descriptor.dependencyRequest(
dependencyRequestFactory.forComponentMembersInjectionMethod(
componentMethod, resolvedComponentMethod));
break;
default:
throw new IllegalArgumentException(
"component method has too many parameters: " + componentMethod);
}
return descriptor.build();
}
@Override
public void clearCache() {
cache.clear();
}
}
}
| Factory |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/intg/AdditionalMappingContributorTests.java | {
"start": 7591,
"end": 7706
} | class ____ {
@Id
private Integer id;
private String name;
}
@SuppressWarnings("unused")
public static | Entity4 |
java | apache__camel | components/camel-reactive-streams/src/test/java/org/apache/camel/component/reactive/streams/BeanCallTest.java | {
"start": 1514,
"end": 8922
} | class ____ extends BaseReactiveTest {
@Test
public void beanCallTest() throws Exception {
new RouteBuilder() {
@Override
public void configure() {
onException(Throwable.class).to("direct:handle").handled(true);
from("direct:num")
.bean(BeanCallTest.this, "processBody")
.process(new UnwrapStreamProcessor()) // Can be removed?
.to("mock:endpoint");
from("direct:handle")
.setBody().constant("ERR")
.to("mock:endpoint");
}
}.addRoutesToCamelContext(context);
MockEndpoint mock = getMockEndpoint("mock:endpoint");
mock.expectedMessageCount(1);
context.start();
template.sendBody("direct:num", 1);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
assertEquals("HelloBody 1", exchange.getIn().getBody());
}
@Test
public void beanCallWithErrorTest() throws Exception {
new RouteBuilder() {
@Override
public void configure() {
onException(Throwable.class).to("direct:handle").handled(true);
from("direct:num")
.bean(BeanCallTest.this, "processBodyWrongType")
.process(new UnwrapStreamProcessor()) // Can be removed?
.to("mock:endpoint");
from("direct:handle")
.setBody().constant("ERR")
.to("mock:endpoint");
}
}.addRoutesToCamelContext(context);
MockEndpoint mock = getMockEndpoint("mock:endpoint");
mock.expectedMessageCount(1);
context.start();
template.sendBody("direct:num", 1);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
assertEquals("ERR", exchange.getIn().getBody());
}
@Test
public void beanCallHeaderMappingTest() throws Exception {
new RouteBuilder() {
@Override
public void configure() {
onException(Throwable.class).to("direct:handle").handled(true);
from("direct:num")
.bean(BeanCallTest.this, "processHeader")
.process(new UnwrapStreamProcessor()) // Can be removed?
.to("mock:endpoint");
from("direct:handle")
.setBody().constant("ERR")
.to("mock:endpoint");
}
}.addRoutesToCamelContext(context);
MockEndpoint mock = getMockEndpoint("mock:endpoint");
mock.expectedMessageCount(1);
context.start();
template.sendBodyAndHeader("direct:num", 1, "myheader", 2);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
assertEquals("HelloHeader 2", exchange.getIn().getBody());
}
@Test
public void beanCallEmptyPublisherTest() throws Exception {
new RouteBuilder() {
@Override
public void configure() {
onException(Throwable.class).to("direct:handle").handled(true);
from("direct:num")
.bean(BeanCallTest.this, "processBodyEmpty")
.process(new UnwrapStreamProcessor()) // Can be removed?
.to("mock:endpoint");
from("direct:handle")
.setBody().constant("ERR")
.to("mock:endpoint");
}
}.addRoutesToCamelContext(context);
MockEndpoint mock = getMockEndpoint("mock:endpoint");
mock.expectedMessageCount(1);
context.start();
template.sendBody("direct:num", 1);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
Object body = exchange.getIn().getBody();
assertEquals(1, body); // unchanged
}
@Test
public void beanCallTwoElementsTest() throws Exception {
new RouteBuilder() {
@Override
public void configure() {
onException(Throwable.class).to("direct:handle").handled(true);
from("direct:num")
.bean(BeanCallTest.this, "processBodyTwoItems")
.process(new UnwrapStreamProcessor()) // Can be removed?
.to("mock:endpoint");
from("direct:handle")
.setBody().constant("ERR")
.to("mock:endpoint");
}
}.addRoutesToCamelContext(context);
MockEndpoint mock = getMockEndpoint("mock:endpoint");
mock.expectedMessageCount(1);
context.start();
template.sendBody("direct:num", 1);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
Object body = exchange.getIn().getBody();
assertTrue(body instanceof Collection);
@SuppressWarnings("unchecked")
List<String> data = new LinkedList<>((Collection<String>) body);
assertListSize(data, 2);
assertEquals("HelloBody 1", data.get(0));
assertEquals("HelloBody 1", data.get(1));
}
@Test
public void beanCallStdReturnTypeTest() throws Exception {
new RouteBuilder() {
@Override
public void configure() {
onException(Throwable.class).to("direct:handle").handled(true);
from("direct:num")
.bean(BeanCallTest.this, "processBodyStd")
.process(new UnwrapStreamProcessor()) // Can be removed?
.to("mock:endpoint");
from("direct:handle")
.setBody().constant("ERR")
.to("mock:endpoint");
}
}.addRoutesToCamelContext(context);
MockEndpoint mock = getMockEndpoint("mock:endpoint");
mock.expectedMessageCount(1);
context.start();
template.sendBody("direct:num", 1);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
Object body = exchange.getIn().getBody();
assertEquals("Hello", body);
}
public Publisher<String> processBody(Publisher<Integer> data) {
return Flowable.fromPublisher(data)
.map(l -> "HelloBody " + l);
}
public Publisher<String> processBodyWrongType(Publisher<BeanCallTest> data) {
return Flowable.fromPublisher(data)
.map(l -> "HelloBody " + l);
}
public Publisher<String> processHeader(@Header("myheader") Publisher<Integer> data) {
return Flowable.fromPublisher(data)
.map(l -> "HelloHeader " + l);
}
public Publisher<String> processBodyTwoItems(Publisher<Integer> data) {
return Flowable.fromPublisher(data).mergeWith(data)
.map(l -> "HelloBody " + l);
}
public Publisher<String> processBodyEmpty(Publisher<Integer> data) {
return Flowable.empty();
}
public String processBodyStd(Publisher<Integer> data) {
return "Hello";
}
@Override
public boolean isUseRouteBuilder() {
return false;
}
}
| BeanCallTest |
java | apache__camel | components/camel-debezium/camel-debezium-oracle/src/main/java/org/apache/camel/component/debezium/oracle/DebeziumOracleComponent.java | {
"start": 1261,
"end": 2288
} | class ____ extends DebeziumComponent<OracleConnectorEmbeddedDebeziumConfiguration> {
@Metadata
private OracleConnectorEmbeddedDebeziumConfiguration configuration = new OracleConnectorEmbeddedDebeziumConfiguration();
public DebeziumOracleComponent() {
}
public DebeziumOracleComponent(final CamelContext context) {
super(context);
}
/**
* Allow pre-configured Configurations to be set.
*/
@Override
public OracleConnectorEmbeddedDebeziumConfiguration getConfiguration() {
return configuration;
}
@Override
public void setConfiguration(OracleConnectorEmbeddedDebeziumConfiguration configuration) {
this.configuration = configuration;
}
@Override
protected DebeziumEndpoint<OracleConnectorEmbeddedDebeziumConfiguration> initializeDebeziumEndpoint(
String uri, OracleConnectorEmbeddedDebeziumConfiguration configuration) {
return new DebeziumOracleEndpoint(uri, this, configuration);
}
}
| DebeziumOracleComponent |
java | google__auto | common/src/test/java/com/google/auto/common/OverridesTest.java | {
"start": 4926,
"end": 5185
} | class ____ implements One {
@Override
public void m() {}
@Override
public void m(String x) {}
@Override
public void n() {}
@Override
public Number number() {
return 0;
}
}
static | ChildOfOne |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java | {
"start": 23148,
"end": 23232
} | class ____ implements PrototypeInterface {
}
@Configuration
static | AbstractPrototype |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java | {
"start": 3317,
"end": 3501
} | class ____ {
@Bean
ResourceConfigCustomizer customizer() {
return (config) -> config.register(TestEndpoint.class);
}
@Path("/test")
public static | ResourceConfigConfiguration |
java | apache__flink | flink-metrics/flink-metrics-core/src/main/java/org/apache/flink/metrics/MetricType.java | {
"start": 947,
"end": 1016
} | enum ____ {
COUNTER,
METER,
GAUGE,
HISTOGRAM
}
| MetricType |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/AclEntryStatusFormat.java | {
"start": 1379,
"end": 4417
} | enum ____ implements LongBitFormat.Enum {
PERMISSION(null, 3),
TYPE(PERMISSION.BITS, 2),
SCOPE(TYPE.BITS, 1),
NAME(SCOPE.BITS, 24);
private static final FsAction[] FSACTION_VALUES = FsAction.values();
private static final AclEntryScope[] ACL_ENTRY_SCOPE_VALUES =
AclEntryScope.values();
private static final AclEntryType[] ACL_ENTRY_TYPE_VALUES =
AclEntryType.values();
private final LongBitFormat BITS;
private AclEntryStatusFormat(LongBitFormat previous, int length) {
BITS = new LongBitFormat(name(), previous, length, 0);
}
static AclEntryScope getScope(int aclEntry) {
int ordinal = (int) SCOPE.BITS.retrieve(aclEntry);
return ACL_ENTRY_SCOPE_VALUES[ordinal];
}
static AclEntryType getType(int aclEntry) {
int ordinal = (int) TYPE.BITS.retrieve(aclEntry);
return ACL_ENTRY_TYPE_VALUES[ordinal];
}
static FsAction getPermission(int aclEntry) {
int ordinal = (int) PERMISSION.BITS.retrieve(aclEntry);
return FSACTION_VALUES[ordinal];
}
static String getName(int aclEntry) {
return getName(aclEntry, null);
}
static String getName(int aclEntry,
SerialNumberManager.StringTable stringTable) {
SerialNumberManager snm = getSerialNumberManager(getType(aclEntry));
if (snm != null) {
int nid = (int)NAME.BITS.retrieve(aclEntry);
return snm.getString(nid, stringTable);
}
return null;
}
static int toInt(AclEntry aclEntry) {
long aclEntryInt = 0;
aclEntryInt = SCOPE.BITS
.combine(aclEntry.getScope().ordinal(), aclEntryInt);
aclEntryInt = TYPE.BITS.combine(aclEntry.getType().ordinal(), aclEntryInt);
aclEntryInt = PERMISSION.BITS.combine(aclEntry.getPermission().ordinal(),
aclEntryInt);
SerialNumberManager snm = getSerialNumberManager(aclEntry.getType());
if (snm != null) {
int nid = snm.getSerialNumber(aclEntry.getName());
aclEntryInt = NAME.BITS.combine(nid, aclEntryInt);
}
return (int) aclEntryInt;
}
static AclEntry toAclEntry(int aclEntry) {
return toAclEntry(aclEntry, null);
}
static AclEntry toAclEntry(int aclEntry,
SerialNumberManager.StringTable stringTable) {
return new AclEntry.Builder()
.setScope(getScope(aclEntry))
.setType(getType(aclEntry))
.setPermission(getPermission(aclEntry))
.setName(getName(aclEntry, stringTable))
.build();
}
public static int[] toInt(List<AclEntry> aclEntries) {
int[] entries = new int[aclEntries.size()];
for (int i = 0; i < entries.length; i++) {
entries[i] = toInt(aclEntries.get(i));
}
return entries;
}
private static SerialNumberManager getSerialNumberManager(AclEntryType type) {
switch (type) {
case USER:
return SerialNumberManager.USER;
case GROUP:
return SerialNumberManager.GROUP;
default:
return null;
}
}
@Override
public int getLength() {
return BITS.getLength();
}
} | AclEntryStatusFormat |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/stream/compact/CompactReader.java | {
"start": 1047,
"end": 1242
} | interface ____<T> extends Closeable {
/** Read a record, return null if no more record. */
T read() throws IOException;
/** Factory to create {@link CompactReader}. */
| CompactReader |
java | elastic__elasticsearch | modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/PainlessExtension.java | {
"start": 611,
"end": 711
} | interface ____ {
Map<ScriptContext<?>, List<Whitelist>> getContextWhitelists();
}
| PainlessExtension |
java | google__guice | core/src/com/google/inject/multibindings/OptionalBinder.java | {
"start": 5322,
"end": 5705
} | class ____ extends AbstractModule {
* protected void configure() {
* bind(Key.get(String.class, LookupUrl.class)).toInstance(CUSTOM_LOOKUP_URL);
* }
* }</code></pre>
*
* ... would generate an error, because both the framework and the user are trying to bind
* {@code @LookupUrl String}.
*
* @author sameb@google.com (Sam Berlin)
* @since 4.0
*/
public | UserLookupModule |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromArray.java | {
"start": 3065,
"end": 5289
} | class ____<T> extends BaseArraySubscription<T> {
private static final long serialVersionUID = 2587302975077663557L;
final Subscriber<? super T> downstream;
ArraySubscription(Subscriber<? super T> actual, T[] array) {
super(array);
this.downstream = actual;
}
@Override
void fastPath() {
T[] arr = array;
int f = arr.length;
Subscriber<? super T> a = downstream;
for (int i = index; i != f; i++) {
if (cancelled) {
return;
}
T t = arr[i];
if (t == null) {
a.onError(new NullPointerException("The element at index " + i + " is null"));
return;
} else {
a.onNext(t);
}
}
if (cancelled) {
return;
}
a.onComplete();
}
@Override
void slowPath(long r) {
long e = 0;
T[] arr = array;
int f = arr.length;
int i = index;
Subscriber<? super T> a = downstream;
for (;;) {
while (e != r && i != f) {
if (cancelled) {
return;
}
T t = arr[i];
if (t == null) {
a.onError(new NullPointerException("The element at index " + i + " is null"));
return;
} else {
a.onNext(t);
}
e++;
i++;
}
if (i == f) {
if (!cancelled) {
a.onComplete();
}
return;
}
r = get();
if (e == r) {
index = i;
r = addAndGet(-e);
if (r == 0L) {
return;
}
e = 0L;
}
}
}
}
static final | ArraySubscription |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.