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
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/DeclarationOrderIndependenceTests.java
{ "start": 3522, "end": 3711 }
class ____ implements TopsyTurvyTarget { private int x = 5; @Override public void doSomething() { this.x = 10; } @Override public int getX() { return x; } }
TopsyTurvyTargetImpl
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/transformer/TypeConverterTransformer.java
{ "start": 1397, "end": 3023 }
class ____ extends Transformer { private static final Logger LOG = LoggerFactory.getLogger(TypeConverterTransformer.class); private DataType dataType; private Class<?> type; public TypeConverterTransformer(DataType type) { super(type.getFullName()); this.dataType = type; } public TypeConverterTransformer(Class<?> type) { super("java:" + type.getName()); this.type = type; } @Override public void transform(Message message, DataType from, DataType to) { if (message == null || message.getBody() == null) { return; } try { if (dataType != null) { if (DataType.isJavaType(dataType) && dataType.getName() != null) { CamelContext context = message.getExchange().getContext(); type = context.getClassResolver().resolveMandatoryClass(dataType.getName()); } } if (type != null && !type.isAssignableFrom(message.getBody().getClass())) { LOG.debug("Converting to '{}'", type.getName()); message.setBody(message.getMandatoryBody(type)); } } catch (InvalidPayloadException | ClassNotFoundException e) { throw new CamelExecutionException( String.format("Failed to convert body to '%s' content using type conversion for %s", getName(), ObjectHelper.name(type)), message.getExchange(), e); } } public Class<?> getType() { return type; } }
TypeConverterTransformer
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/action/PutConnectorActionTests.java
{ "start": 583, "end": 2663 }
class ____ extends ESTestCase { public void testValidate_WhenConnectorIdAndIndexNamePresent_ExpectNoValidationError() { PutConnectorAction.Request request = new PutConnectorAction.Request( randomAlphaOfLength(10), randomAlphaOfLength(10), randomAlphaOfLength(10), false, randomAlphaOfLength(10), randomAlphaOfLength(10), randomAlphaOfLength(10) ); ActionRequestValidationException exception = request.validate(); assertThat(exception, nullValue()); } public void testValidate_WrongIndexNamePresentForManagedConnector_ExpectValidationError() { PutConnectorAction.Request requestWithIllegalIndexName = new PutConnectorAction.Request( randomAlphaOfLength(10), randomAlphaOfLength(10), "wrong-prefix-" + randomAlphaOfLength(10), true, randomAlphaOfLength(10), randomAlphaOfLength(10), randomAlphaOfLength(10) ); ActionRequestValidationException exception = requestWithIllegalIndexName.validate(); assertThat(exception, notNullValue()); assertThat( exception.getMessage(), containsString("Index attached to an Elastic-managed connector must start with the prefix: [content-]") ); } public void testValidate_WhenMalformedIndexName_ExpectValidationError() { PutConnectorAction.Request requestWithMissingConnectorId = new PutConnectorAction.Request( randomAlphaOfLength(10), randomAlphaOfLength(10), "_illegal-index-name", randomBoolean(), randomAlphaOfLength(10), randomAlphaOfLength(10), randomAlphaOfLength(10) ); ActionRequestValidationException exception = requestWithMissingConnectorId.validate(); assertThat(exception, notNullValue()); assertThat(exception.getMessage(), containsString("Invalid index name [_illegal-index-name]")); } }
PutConnectorActionTests
java
apache__camel
components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/internal/BoxGroupsManagerApiMethod.java
{ "start": 667, "end": 3229 }
enum ____ implements ApiMethod { ADD_GROUP_MEMBERSHIP( com.box.sdk.BoxGroupMembership.class, "addGroupMembership", arg("groupId", String.class), arg("userId", String.class), arg("role", com.box.sdk.BoxGroupMembership.GroupRole.class)), CREATE_GROUP( com.box.sdk.BoxGroup.class, "createGroup", arg("name", String.class), arg("provenance", String.class), arg("externalSyncIdentifier", String.class), arg("description", String.class), arg("invitabilityLevel", String.class), arg("memberViewabilityLevel", String.class)), DELETE_GROUP( void.class, "deleteGroup", arg("groupId", String.class)), DELETE_GROUP_MEMBERSHIP( void.class, "deleteGroupMembership", arg("groupMembershipId", String.class)), GET_ALL_GROUPS( java.util.Collection.class, "getAllGroups"), GET_GROUP_INFO( com.box.sdk.BoxGroup.Info.class, "getGroupInfo", arg("groupId", String.class)), GET_GROUP_MEMBERSHIP_INFO( com.box.sdk.BoxGroupMembership.Info.class, "getGroupMembershipInfo", arg("groupMembershipId", String.class)), GET_GROUP_MEMBERSHIPS( java.util.Collection.class, "getGroupMemberships", arg("groupId", String.class)), UPDATE_GROUP_INFO( com.box.sdk.BoxGroup.class, "updateGroupInfo", arg("groupId", String.class), arg("groupInfo", com.box.sdk.BoxGroup.Info.class)), UPDATE_GROUP_MEMBERSHIP_INFO( com.box.sdk.BoxGroupMembership.class, "updateGroupMembershipInfo", arg("groupMembershipId", String.class), arg("info", com.box.sdk.BoxGroupMembership.Info.class)); private final ApiMethod apiMethod; BoxGroupsManagerApiMethod(Class<?> resultType, String name, ApiMethodArg... args) { this.apiMethod = new ApiMethodImpl(BoxGroupsManager.class, resultType, name, args); } @Override public String getName() { return apiMethod.getName(); } @Override public Class<?> getResultType() { return apiMethod.getResultType(); } @Override public List<String> getArgNames() { return apiMethod.getArgNames(); } @Override public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); } @Override public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); } @Override public Method getMethod() { return apiMethod.getMethod(); } }
BoxGroupsManagerApiMethod
java
spring-projects__spring-boot
module/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/ConcurrentKafkaListenerContainerFactoryConfigurerTests.java
{ "start": 1382, "end": 3297 }
class ____ { private ConcurrentKafkaListenerContainerFactoryConfigurer configurer; private ConcurrentKafkaListenerContainerFactory<Object, Object> factory; private ConsumerFactory<Object, Object> consumerFactory; private KafkaProperties properties; @BeforeEach @SuppressWarnings("unchecked") void setUp() { this.configurer = new ConcurrentKafkaListenerContainerFactoryConfigurer(); this.properties = new KafkaProperties(); this.configurer.setKafkaProperties(this.properties); this.factory = spy(new ConcurrentKafkaListenerContainerFactory<>()); this.consumerFactory = mock(ConsumerFactory.class); } @Test void shouldApplyThreadNameSupplier() { Function<MessageListenerContainer, String> function = (container) -> "thread-1"; this.configurer.setThreadNameSupplier(function); this.configurer.configure(this.factory, this.consumerFactory); then(this.factory).should().setThreadNameSupplier(function); } @Test void shouldApplyChangeConsumerThreadName() { this.properties.getListener().setChangeConsumerThreadName(true); this.configurer.configure(this.factory, this.consumerFactory); then(this.factory).should().setChangeConsumerThreadName(true); } @Test void shouldApplyListenerTaskExecutor() { SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); this.configurer.setListenerTaskExecutor(executor); this.configurer.configure(this.factory, this.consumerFactory); assertThat(this.factory.getContainerProperties().getListenerTaskExecutor()).isEqualTo(executor); } @Test void shouldApplyAuthExceptionRetryInterval() { this.properties.getListener().setAuthExceptionRetryInterval(Duration.ofSeconds(10)); this.configurer.configure(this.factory, this.consumerFactory); assertThat(this.factory.getContainerProperties().getAuthExceptionRetryInterval()) .isEqualTo(Duration.ofSeconds(10)); } }
ConcurrentKafkaListenerContainerFactoryConfigurerTests
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringResequencerTest.java
{ "start": 1036, "end": 1279 }
class ____ extends ResequencerTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/resequencer.xml"); } }
SpringResequencerTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/DataVerifier.java
{ "start": 2850, "end": 2977 }
class ____ to hold the chunks same and different for buffered reads * and the resultant verification */ private static
used
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/model/internal/TableDeleteStandard.java
{ "start": 520, "end": 1779 }
class ____ extends AbstractTableDelete { private final String whereFragment; public TableDeleteStandard( MutatingTableReference mutatingTable, MutationTarget<?> mutationTarget, String sqlComment, List<ColumnValueBinding> keyRestrictionBindings, List<ColumnValueBinding> optLockRestrictionBindings, List<ColumnValueParameter> parameters) { this( mutatingTable, mutationTarget, sqlComment, keyRestrictionBindings, optLockRestrictionBindings, parameters, null ); } public TableDeleteStandard( MutatingTableReference mutatingTable, MutationTarget<?> mutationTarget, String sqlComment, List<ColumnValueBinding> keyRestrictionBindings, List<ColumnValueBinding> optLockRestrictionBindings, List<ColumnValueParameter> parameters, String whereFragment) { super( mutatingTable, mutationTarget, sqlComment, keyRestrictionBindings, optLockRestrictionBindings, parameters ); this.whereFragment = whereFragment; } public String getWhereFragment() { return whereFragment; } @Override public boolean isCustomSql() { return false; } @Override public boolean isCallable() { return false; } @Override public void accept(SqlAstWalker walker) { walker.visitStandardTableDelete( this ); } }
TableDeleteStandard
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerNoWebMvcTests.java
{ "start": 1630, "end": 2868 }
class ____ { ConfigurableApplicationContext context; @AfterEach public void teardown() { if (this.context != null) { this.context.close(); } } @Test public void missingDispatcherServletPreventsCsrfRequestDataValueProcessor() { loadContext(EnableWebConfig.class); assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue(); } @Test public void findDispatcherServletPreventsCsrfRequestDataValueProcessor() { loadContext(EnableWebMvcConfig.class); assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue(); } @Test public void overrideCsrfRequestDataValueProcessor() { loadContext(EnableWebOverrideRequestDataConfig.class); assertThat(this.context.getBean(RequestDataValueProcessor.class).getClass()) .isNotEqualTo(CsrfRequestDataValueProcessor.class); } private void loadContext(Class<?> configs) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(configs); annotationConfigApplicationContext.refresh(); this.context = annotationConfigApplicationContext; } @Configuration @EnableWebSecurity static
CsrfConfigurerNoWebMvcTests
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/async/DefaultAsyncQueueFullPolicy.java
{ "start": 1241, "end": 2064 }
class ____ implements AsyncQueueFullPolicy { @Override public EventRoute getRoute(final long backgroundThreadId, final Level level) { // LOG4J2-471: prevent deadlock when RingBuffer is full and object // being logged calls Logger.log() from its toString() method final Thread currentThread = Thread.currentThread(); if (currentThread.getId() == backgroundThreadId // Threads owned by log4j are most likely to result in // deadlocks because they generally consume events. // This prevents deadlocks between AsyncLoggerContext // disruptors. || currentThread instanceof Log4jThread) { return EventRoute.SYNCHRONOUS; } return EventRoute.ENQUEUE; } }
DefaultAsyncQueueFullPolicy
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/a/Simple.java
{ "start": 308, "end": 388 }
class ____ implements Serializable { @Id String ssn; @Id String name; }
Simple
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/RestSqlTranslateAction.java
{ "start": 1320, "end": 2770 }
class ____ extends BaseRestHandler { private final CrossProjectModeDecider crossProjectModeDecider; public RestSqlTranslateAction(Settings settings) { this.crossProjectModeDecider = new CrossProjectModeDecider(settings); } @Override public List<Route> routes() { return List.of(new Route(GET, SQL_TRANSLATE_REST_ENDPOINT), new Route(POST, SQL_TRANSLATE_REST_ENDPOINT)); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { SqlTranslateRequest sqlRequest; try (XContentParser parser = request.contentOrSourceParamParser()) { sqlRequest = SqlTranslateRequest.fromXContent(parser); } String routingParam = request.param("project_routing"); if (routingParam != null) { // takes precedence on the parameter in the body sqlRequest.projectRouting(routingParam); } if (sqlRequest.projectRouting() != null && crossProjectModeDecider.crossProjectEnabled() == false) { throw new InvalidArgumentException("[project_routing] is only allowed when cross-project search is enabled"); } return channel -> client.executeLocally(SqlTranslateAction.INSTANCE, sqlRequest, new RestToXContentListener<>(channel)); } @Override public String getName() { return "xpack_sql_translate_action"; } }
RestSqlTranslateAction
java
spring-projects__spring-boot
build-plugin/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java
{ "start": 5275, "end": 6931 }
class ____ that * contains a 'main' method will be used. * * @since 1.0.0 */ @Parameter(property = "spring-boot.run.main-class") private @Nullable String mainClass; /** * Additional classpath elements that should be added to the classpath. An element can * be a directory with classes and resources or a jar file. * * @since 3.2.0 */ @Parameter(property = "spring-boot.run.additional-classpath-elements") @SuppressWarnings("NullAway") // maven-maven-plugin can't handle annotated arrays private String[] additionalClasspathElements; /** * Directory containing the classes and resource files that should be used to run the * application. * * @since 1.0.0 */ @Parameter(defaultValue = "${project.build.outputDirectory}", required = true) @SuppressWarnings("NullAway.Init") private File classesDirectory; /** * Skip the execution. * * @since 1.3.2 */ @Parameter(property = "spring-boot.run.skip", defaultValue = "false") private boolean skip; protected AbstractRunMojo(ToolchainManager toolchainManager) { this.toolchainManager = toolchainManager; } @Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip) { getLog().debug("skipping run as per configuration."); return; } run(determineMainClass()); } private String determineMainClass() throws MojoExecutionException { if (this.mainClass != null) { return this.mainClass; } return SpringBootApplicationClassFinder.findSingleClass(getClassesDirectories()); } /** * Returns the directories that contain the application's classes and resources. When * the application's main
found
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/transform/impl/InterceptFieldEnabled.java
{ "start": 676, "end": 837 }
interface ____ { void setInterceptFieldCallback(InterceptFieldCallback callback); InterceptFieldCallback getInterceptFieldCallback(); }
InterceptFieldEnabled
java
quarkusio__quarkus
integration-tests/jpa-postgresql-withxml/src/test/java/io/quarkus/it/jpa/postgresql/JPAFunctionalityInGraalITCase.java
{ "start": 341, "end": 1027 }
class ____ extends JPAFunctionalityTest { @Test public void verifyJDKXMLParsersAreIncluded() { final ClassInclusionReport report = ClassInclusionReport.load(); //The following classes should be included in this applications; //if not, that would be a sign that this test has become too weak //to identify the well working of the exclusions. report.assertContains(org.postgresql.jdbc.PgSQLXML.class); report.assertContains(UUIDJdbcType.class); // And finally verify we included "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl" which is // the fallback implementation
JPAFunctionalityInGraalITCase
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/ControlledClock.java
{ "start": 837, "end": 1771 }
class ____ implements Clock { private long time = -1; private final Clock actualClock; // Convenience for getting a controlled clock with overridden time public ControlledClock() { this(SystemClock.getInstance()); setTime(0); } public ControlledClock(Clock actualClock) { this.actualClock = actualClock; } public synchronized void setTime(long time) { this.time = time; } public synchronized void reset() { time = -1; } public synchronized void tickSec(int seconds) { tickMsec(seconds * 1000L); } public synchronized void tickMsec(long millisec) { if (time == -1) { throw new IllegalStateException("ControlledClock setTime should be " + "called before incrementing time"); } time = time + millisec; } @Override public synchronized long getTime() { if (time != -1) { return time; } return actualClock.getTime(); } }
ControlledClock
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/event/SmartApplicationListener.java
{ "start": 1288, "end": 2398 }
interface ____ extends ApplicationListener<ApplicationEvent>, Ordered { /** * Determine whether this listener actually supports the given event type. * @param eventType the event type (never {@code null}) */ boolean supportsEventType(Class<? extends ApplicationEvent> eventType); /** * Determine whether this listener actually supports the given source type. * <p>The default implementation always returns {@code true}. * @param sourceType the source type, or {@code null} if no source */ default boolean supportsSourceType(@Nullable Class<?> sourceType) { return true; } /** * Determine this listener's order in a set of listeners for the same event. * <p>The default implementation returns {@link #LOWEST_PRECEDENCE}. */ @Override default int getOrder() { return LOWEST_PRECEDENCE; } /** * Return an optional identifier for the listener. * <p>The default value is an empty String. * @since 5.3.5 * @see EventListener#id * @see ApplicationEventMulticaster#removeApplicationListeners */ default String getListenerId() { return ""; } }
SmartApplicationListener
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/DateParser.java
{ "start": 1419, "end": 4780 }
interface ____ { /** * Gets the locale used by this parser. * * @return the locale */ Locale getLocale(); /** * Gets the pattern used by this parser. * * @return the pattern, {@link java.text.SimpleDateFormat} compatible. */ String getPattern(); /** * Gets the time zone used by this parser. * * <p> * The default {@link TimeZone} used to create a {@link Date} when the {@link TimeZone} is not specified by * the format pattern. * </p> * * @return the time zone */ TimeZone getTimeZone(); /** * Equivalent to DateFormat.parse(String). * * See {@link java.text.DateFormat#parse(String)} for more information. * @param source A {@link String} whose beginning should be parsed. * @return A {@link Date} parsed from the string. * @throws ParseException if the beginning of the specified string cannot be parsed. */ Date parse(String source) throws ParseException; /** * Equivalent to DateFormat.parse(String, ParsePosition). * * See {@link java.text.DateFormat#parse(String, ParsePosition)} for more information. * * @param source A {@link String}, part of which should be parsed. * @param pos A {@link ParsePosition} object with index and error index information * as described above. * @return A {@link Date} parsed from the string. In case of error, returns null. * @throws NullPointerException if text or pos is null. */ Date parse(String source, ParsePosition pos); /** * Parses a formatted date string according to the format. Updates the Calendar with parsed fields. * Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. * Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to * the offset of the source text which does not match the supplied format. * * @param source The text to parse. * @param pos On input, the position in the source to start parsing, on output, updated position. * @param calendar The calendar into which to set parsed fields. * @return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated) * @throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is * out of range. * * @since 3.5 */ boolean parse(String source, ParsePosition pos, Calendar calendar); /** * Parses text from a string to produce a Date. * * @param source A {@link String} whose beginning should be parsed. * @return a {@link java.util.Date} object. * @throws ParseException if the beginning of the specified string cannot be parsed. * @see java.text.DateFormat#parseObject(String) */ Object parseObject(String source) throws ParseException; /** * Parses a date/time string according to the given parse position. * * @param source A {@link String} whose beginning should be parsed. * @param pos the parse position. * @return a {@link java.util.Date} object. * @see java.text.DateFormat#parseObject(String, ParsePosition) */ Object parseObject(String source, ParsePosition pos); }
DateParser
java
alibaba__druid
core/src/main/java/com/alibaba/druid/filter/FilterManager.java
{ "start": 1095, "end": 5840 }
class ____ { private static final Log LOG = LogFactory.getLog(FilterManager.class); private static final ConcurrentHashMap<String, String> aliasMap = new ConcurrentHashMap<String, String>(16, 0.75f, 1); static { try { Properties filterProperties = loadFilterConfig(); for (Map.Entry<Object, Object> entry : filterProperties.entrySet()) { String key = (String) entry.getKey(); if (key.startsWith("druid.filters.")) { String name = key.substring("druid.filters.".length()); aliasMap.put(name, (String) entry.getValue()); } } } catch (Throwable e) { LOG.error("load filter config error", e); } } public static final String getFilter(String alias) { if (alias == null) { return null; } String filter = aliasMap.get(alias); if (filter == null && alias.length() < 128) { filter = alias; } return filter; } public static Properties loadFilterConfig() throws IOException { Properties filterProperties = new Properties(); loadFilterConfig(filterProperties, ClassLoader.getSystemClassLoader()); loadFilterConfig(filterProperties, FilterManager.class.getClassLoader()); loadFilterConfig(filterProperties, Thread.currentThread().getContextClassLoader()); return filterProperties; } private static void loadFilterConfig(Properties filterProperties, ClassLoader classLoader) throws IOException { if (classLoader == null) { return; } for (Enumeration<URL> e = classLoader.getResources("META-INF/druid-filter.properties"); e.hasMoreElements(); ) { URL url = e.nextElement(); Properties property = new Properties(); InputStream is = null; try { is = url.openStream(); property.load(is); } finally { JdbcUtils.close(is); } filterProperties.putAll(property); } } public static void loadFilter(List<Filter> filters, String filterName) throws SQLException { if (filterName.length() == 0) { return; } String filterClassNames = getFilter(filterName); if (filterClassNames != null) { for (String filterClassName : filterClassNames.split(",")) { if (existsFilter(filters, filterClassName)) { continue; } Class<?> filterClass = Utils.loadClass(filterClassName); if (filterClass == null) { LOG.error("load filter error, filter not found : " + filterClassName); continue; } Filter filter; try { filter = (Filter) filterClass.newInstance(); } catch (ClassCastException e) { LOG.error("load filter error.", e); continue; } catch (NoSuchFieldError e) { LOG.error("load filter error.", e); continue; } catch (InstantiationException e) { throw new SQLException("load managed jdbc driver event listener error. " + filterName, e); } catch (IllegalAccessException e) { throw new SQLException("load managed jdbc driver event listener error. " + filterName, e); } catch (RuntimeException e) { throw new SQLException("load managed jdbc driver event listener error. " + filterName, e); } filters.add(filter); } return; } if (existsFilter(filters, filterName)) { return; } Class<?> filterClass = Utils.loadClass(filterName); if (filterClass == null) { LOG.error("load filter error, filter not found : " + filterName); return; } try { Filter filter = (Filter) filterClass.newInstance(); filters.add(filter); } catch (Exception e) { throw new SQLException("load managed jdbc driver event listener error. " + filterName, e); } } private static boolean existsFilter(List<Filter> filterList, String filterClassName) { for (Filter filter : filterList) { String itemFilterClassName = filter.getClass().getName(); if (itemFilterClassName.equalsIgnoreCase(filterClassName)) { return true; } } return false; } }
FilterManager
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDatagramChannelTest.java
{ "start": 4132, "end": 4467 }
class ____ extends ChannelInboundHandlerAdapter { private volatile SocketAddress localAddress; @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { this.localAddress = ctx.channel().localAddress(); super.channelRegistered(ctx); } } }
TestHandler
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/rest/FromRestGetEndPathTest.java
{ "start": 1153, "end": 3286 }
class ____ extends FromRestGetTest { @Override @Test public void testFromRestModel() throws Exception { assertEquals(getExpectedNumberOfRoutes(), context.getRoutes().size()); assertEquals(2, context.getRestDefinitions().size()); RestDefinition rest = context.getRestDefinitions().get(0); assertNotNull(rest); assertEquals("/say/hello", rest.getPath()); assertEquals(1, rest.getVerbs().size()); ToDefinition to = assertIsInstanceOf(ToDefinition.class, rest.getVerbs().get(0).getTo()); assertEquals("direct:hello", to.getUri()); rest = context.getRestDefinitions().get(1); assertNotNull(rest); assertEquals("/say/bye", rest.getPath()); assertEquals(2, rest.getVerbs().size()); assertEquals("application/json", rest.getVerbs().get(0).getConsumes()); to = rest.getVerbs().get(0).getTo(); assertEquals("direct:bye", to.getUri()); // the rest becomes routes and the input is a seda endpoint created by // the DummyRestConsumerFactory getMockEndpoint("mock:update").expectedMessageCount(1); template.sendBody("seda:post-say-bye", "I was here"); assertMockEndpointsSatisfied(); String out = template.requestBody("seda:get-say-hello", "Me", String.class); assertEquals("Hello World", out); String out2 = template.requestBody("seda:get-say-bye", "Me", String.class); assertEquals("Bye World", out2); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { restConfiguration().host("localhost"); rest("/say/hello").get().to("direct:hello"); rest("/say/bye") .get().consumes("application/json").to("direct:bye") .post().to("mock:update"); from("direct:hello").transform().constant("Hello World"); from("direct:bye").transform().constant("Bye World"); } }; } }
FromRestGetEndPathTest
java
square__retrofit
retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/FlowableWithSchedulerTest.java
{ "start": 1184, "end": 2778 }
interface ____ { @GET("/") Flowable<String> body(); @GET("/") Flowable<Response<String>> response(); @GET("/") Flowable<Result<String>> result(); } private final TestScheduler scheduler = new TestScheduler(); private Service service; @Before public void setUp() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new StringConverterFactory()) .addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(scheduler)) .build(); service = retrofit.create(Service.class); } @Test public void bodyUsesScheduler() { server.enqueue(new MockResponse()); RecordingSubscriber<Object> subscriber = subscriberRule.create(); service.body().subscribe(subscriber); subscriber.assertNoEvents(); scheduler.triggerActions(); subscriber.assertAnyValue().assertComplete(); } @Test public void responseUsesScheduler() { server.enqueue(new MockResponse()); RecordingSubscriber<Object> subscriber = subscriberRule.create(); service.response().subscribe(subscriber); subscriber.assertNoEvents(); scheduler.triggerActions(); subscriber.assertAnyValue().assertComplete(); } @Test public void resultUsesScheduler() { server.enqueue(new MockResponse()); RecordingSubscriber<Object> subscriber = subscriberRule.create(); service.result().subscribe(subscriber); subscriber.assertNoEvents(); scheduler.triggerActions(); subscriber.assertAnyValue().assertComplete(); } }
Service
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/logging/JULBridgeTests.java
{ "start": 1200, "end": 6307 }
class ____ extends ESTestCase { private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(""); private static java.util.logging.Level savedLevel; private static Handler[] savedHandlers; @BeforeClass public static void saveLoggerState() { savedLevel = logger.getLevel(); savedHandlers = logger.getHandlers(); } @Before public void resetLogger() { logger.setLevel(java.util.logging.Level.ALL); for (var existingHandler : logger.getHandlers()) { logger.removeHandler(existingHandler); } } @AfterClass public static void restoreLoggerState() { logger.setLevel(savedLevel); for (var existingHandler : logger.getHandlers()) { logger.removeHandler(existingHandler); } for (var savedHandler : savedHandlers) { logger.addHandler(savedHandler); } } private void assertLogged(Runnable loggingCode, LoggingExpectation... expectations) { Logger testLogger = LogManager.getLogger(""); Level savedLevel = testLogger.getLevel(); try (var mockLog = MockLog.capture("")) { Loggers.setLevel(testLogger, Level.ALL); for (var expectation : expectations) { mockLog.addExpectation(expectation); } loggingCode.run(); mockLog.assertAllExpectationsMatched(); } finally { Loggers.setLevel(testLogger, savedLevel); } } private void assertMessage(String msg, java.util.logging.Level julLevel, Level expectedLevel) { assertLogged(() -> logger.log(julLevel, msg), new SeenEventExpectation(msg, "", expectedLevel, msg)); } private static java.util.logging.Level julLevel(int value) { return java.util.logging.Level.parse(Integer.toString(value)); } public void testInstallRemovesExistingHandlers() { logger.addHandler(new ConsoleHandler()); JULBridge.install(); assertThat(logger.getHandlers(), arrayContaining(instanceOf(JULBridge.class))); } public void testKnownLevels() { JULBridge.install(); assertMessage("off msg", java.util.logging.Level.OFF, Level.OFF); assertMessage("severe msg", java.util.logging.Level.SEVERE, Level.ERROR); assertMessage("warning msg", java.util.logging.Level.WARNING, Level.WARN); assertMessage("info msg", java.util.logging.Level.INFO, Level.INFO); assertMessage("fine msg", java.util.logging.Level.FINE, Level.DEBUG); assertMessage("finest msg", java.util.logging.Level.FINEST, Level.TRACE); } public void testCustomLevels() { JULBridge.install(); assertMessage("smallest level", julLevel(Integer.MIN_VALUE), Level.ALL); assertMessage("largest level", julLevel(Integer.MAX_VALUE), Level.OFF); assertMessage("above severe", julLevel(java.util.logging.Level.SEVERE.intValue() + 1), Level.ERROR); assertMessage("above warning", julLevel(java.util.logging.Level.WARNING.intValue() + 1), Level.WARN); assertMessage("above info", julLevel(java.util.logging.Level.INFO.intValue() + 1), Level.INFO); assertMessage("above fine", julLevel(java.util.logging.Level.FINE.intValue() + 1), Level.DEBUG); assertMessage("above finest", julLevel(java.util.logging.Level.FINEST.intValue() + 1), Level.TRACE); } public void testThrowable() { JULBridge.install(); java.util.logging.Logger logger = java.util.logging.Logger.getLogger(""); assertLogged(() -> logger.log(java.util.logging.Level.SEVERE, "error msg", new Exception("some error")), new LoggingExpectation() { boolean matched = false; @Override public void match(LogEvent event) { Throwable thrown = event.getThrown(); matched = event.getLoggerName().equals("") && event.getMessage().getFormattedMessage().equals("error msg") && thrown != null && thrown.getMessage().equals("some error"); } @Override public void assertMatched() { assertThat("expected to see error message but did not", matched, equalTo(true)); } }); } public void testChildLogger() { JULBridge.install(); java.util.logging.Logger childLogger = java.util.logging.Logger.getLogger("foo"); assertLogged(() -> childLogger.info("child msg"), new SeenEventExpectation("child msg", "foo", Level.INFO, "child msg")); } public void testNullMessage() { JULBridge.install(); assertLogged(() -> logger.info((String) null), new SeenEventExpectation("null msg", "", Level.INFO, "<null message>")); } public void testFormattedMessage() { JULBridge.install(); assertLogged( () -> logger.log(java.util.logging.Level.INFO, "{0}", "a var"), new SeenEventExpectation("formatted msg", "", Level.INFO, "a var") ); } }
JULBridgeTests
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/huggingface/completion/HuggingFaceChatCompletionServiceSettings.java
{ "start": 1745, "end": 1933 }
class ____ the settings required to configure a Hugging Face chat completion service, including the model ID, URL, maximum input * tokens, and rate limit settings. * </p> */ public
contains
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/builder/AdviceWithBuilder.java
{ "start": 1075, "end": 8742 }
class ____<T extends ProcessorDefinition<?>> { private final AdviceWithRouteBuilder builder; private final String id; private final String toString; private final String toUri; private final Class<T> type; private boolean selectFirst; private boolean selectLast; private int selectFrom = -1; private int selectTo = -1; private int maxDeep = -1; public AdviceWithBuilder(AdviceWithRouteBuilder builder, String id, String toString, String toUri, Class<T> type) { this.builder = builder; this.id = id; this.toString = toString; this.toUri = toUri; this.type = type; if (id == null && toString == null && toUri == null && type == null) { throw new IllegalArgumentException("Either id, toString, toUri or type must be specified"); } } /** * Will only apply the first node matched. * * @return the builder to build the nodes. */ public AdviceWithBuilder<T> selectFirst() { selectFirst = true; selectLast = false; return this; } /** * Will only apply the last node matched. * * @return the builder to build the nodes. */ public AdviceWithBuilder<T> selectLast() { selectLast = true; selectFirst = false; return this; } /** * Will only apply the n'th node matched. * * @param index index of node to match (is 0-based) * @return the builder to build the nodes. */ public AdviceWithBuilder<T> selectIndex(int index) { if (index < 0) { throw new IllegalArgumentException("Index must be a non negative number, was: " + index); } selectFrom = index; selectTo = index; return this; } /** * Will only apply the node in the index range matched. * * @param from from index of node to start matching (inclusive) * @param to to index of node to stop matching (inclusive) * @return the builder to build the nodes. */ public AdviceWithBuilder<T> selectRange(int from, int to) { if (from < 0) { throw new IllegalArgumentException("From must be a non negative number, was: " + from); } if (from > to) { throw new IllegalArgumentException("From must be equal or lower than to. from: " + from + ", to: " + to); } selectFrom = from; selectTo = to; return this; } /** * Will only apply for nodes maximum levels deep. * <p/> * The first level is <tt>1</tt>, and level <tt>2</tt> is the children of the first level nodes, and so on. * <p/> * Use zero or negative value for unbounded level. * * @param maxDeep the maximum levels to traverse deep in the Camel route tree. * @return the builder to build the nodes. */ public AdviceWithBuilder<T> maxDeep(int maxDeep) { if (maxDeep == 0) { // disable it this.maxDeep = -1; } else { this.maxDeep = maxDeep; } return this; } /** * Replaces the matched node(s) with the following nodes. * * @return the builder to build the nodes. */ public ProcessorDefinition<?> replace() { RouteDefinition route = builder.getOriginalRoute(); AdviceWithDefinition answer = new AdviceWithDefinition(); if (id != null) { builder.getAdviceWithTasks().add( AdviceWithTasks.replaceById(route, id, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toString != null) { builder.getAdviceWithTasks().add(AdviceWithTasks.replaceByToString(route, toString, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toUri != null) { builder.getAdviceWithTasks().add(AdviceWithTasks.replaceByToUri(route, toUri, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (type != null) { builder.getAdviceWithTasks().add( AdviceWithTasks.replaceByType(route, type, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } return answer; } /** * Removes the matched node(s) */ public void remove() { RouteDefinition route = builder.getOriginalRoute(); if (id != null) { builder.getAdviceWithTasks() .add(AdviceWithTasks.removeById(route, id, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toString != null) { builder.getAdviceWithTasks().add( AdviceWithTasks.removeByToString(route, toString, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toUri != null) { builder.getAdviceWithTasks() .add(AdviceWithTasks.removeByToUri(route, toUri, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (type != null) { builder.getAdviceWithTasks() .add(AdviceWithTasks.removeByType(route, type, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } } /** * Insert the following node(s) <b>before</b> the matched node(s) * * @return the builder to build the nodes. */ public ProcessorDefinition<?> before() { RouteDefinition route = builder.getOriginalRoute(); AdviceWithDefinition answer = new AdviceWithDefinition(); if (id != null) { builder.getAdviceWithTasks() .add(AdviceWithTasks.beforeById(route, id, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toString != null) { builder.getAdviceWithTasks().add(AdviceWithTasks.beforeByToString(route, toString, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toUri != null) { builder.getAdviceWithTasks().add(AdviceWithTasks.beforeByToUri(route, toUri, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (type != null) { builder.getAdviceWithTasks().add( AdviceWithTasks.beforeByType(route, type, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } return answer; } /** * Insert the following node(s) <b>after</b> the matched node(s) * * @return the builder to build the nodes. */ public ProcessorDefinition<?> after() { RouteDefinition route = builder.getOriginalRoute(); AdviceWithDefinition answer = new AdviceWithDefinition(); if (id != null) { builder.getAdviceWithTasks() .add(AdviceWithTasks.afterById(route, id, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toString != null) { builder.getAdviceWithTasks().add(AdviceWithTasks.afterByToString(route, toString, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (toUri != null) { builder.getAdviceWithTasks().add( AdviceWithTasks.afterByToUri(route, toUri, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } else if (type != null) { builder.getAdviceWithTasks().add( AdviceWithTasks.afterByType(route, type, answer, selectFirst, selectLast, selectFrom, selectTo, maxDeep)); } return answer; } }
AdviceWithBuilder
java
apache__dubbo
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java
{ "start": 2114, "end": 11863 }
class ____ { private final Protocol tProtocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("tri"); private final Protocol protocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("rest"); private final ProxyFactory proxy = ApplicationModel.defaultModel() .getExtensionLoader(ProxyFactory.class) .getAdaptiveExtension(); private static URL getUrl() { return URL.valueOf("tri://127.0.0.1:" + NetUtils.getAvailablePort() + "/rest?interface=" + SpringRestDemoService.class.getName()); } private static final String SERVER = "netty4"; private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @AfterEach public void tearDown() { tProtocol.destroy(); protocol.destroy(); FrameworkModel.destroyAll(); } public SpringRestDemoService getServerImpl() { return new SpringDemoServiceImpl(); } public Class<SpringRestDemoService> getServerClass() { return SpringRestDemoService.class; } public Exporter<SpringRestDemoService> getExport(URL url, SpringRestDemoService server) { url = url.addParameter(SERVER_KEY, SERVER); return tProtocol.export(proxy.getInvoker(server, getServerClass(), url)); } @Test void testRestProtocol() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "tri://127.0.0.1:" + port + "/?version=1.0.0&interface=" + SpringRestDemoService.class.getName()); SpringRestDemoService server = getServerImpl(); url = this.registerProvider(url, server, getServerClass()); Exporter<SpringRestDemoService> exporter = getExport(url, server); Invoker<SpringRestDemoService> invoker = protocol.refer(SpringRestDemoService.class, url); Assertions.assertFalse(server.isCalled()); SpringRestDemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); String header = client.testHeader("header"); Assertions.assertEquals("header", header); String headerInt = client.testHeaderInt(1); Assertions.assertEquals("1", headerInt); invoker.destroy(); exporter.unexport(); } @Test void testRestProtocolWithContextPath() { SpringRestDemoService server = getServerImpl(); Assertions.assertFalse(server.isCalled()); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "tri://127.0.0.1:" + port + "/a/b/c?version=1.0.0&interface=" + SpringRestDemoService.class.getName()); url = this.registerProvider(url, server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(url, server); url = URL.valueOf("rest://127.0.0.1:" + port + "/a/b/c/?version=1.0.0&interface=" + SpringRestDemoService.class.getName()); Invoker<SpringRestDemoService> invoker = protocol.refer(SpringRestDemoService.class, url); SpringRestDemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); invoker.destroy(); exporter.unexport(); } @Test void testExport() { SpringRestDemoService server = getServerImpl(); URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); RpcContext.getClientAttachment().setAttachment("timeout", "200"); Exporter<SpringRestDemoService> exporter = getExport(url, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url)); Integer echoString = demoService.hello(1, 2); assertThat(echoString, is(3)); exporter.unexport(); } @Test void testNettyServer() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); Integer echoString = demoService.hello(10, 10); assertThat(echoString, is(20)); exporter.unexport(); } @Test void testInvoke() { SpringRestDemoService server = getServerImpl(); URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(url, server); RpcInvocation rpcInvocation = new RpcInvocation( "hello", SpringRestDemoService.class.getName(), "", new Class[] {Integer.class, Integer.class}, new Integer[] {2, 3}); Result result = exporter.getInvoker().invoke(rpcInvocation); assertThat(result.getValue(), CoreMatchers.<Object>is(5)); } @Test void testFilter() { SpringRestDemoService server = getServerImpl(); URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(url, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url)); Integer result = demoService.hello(1, 2); assertThat(result, is(3)); exporter.unexport(); } @Test void testDefaultPort() { assertThat(protocol.getDefaultPort(), is(80)); } @Test void testFormConsumerParser() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); User user = new User(); user.setAge(18); user.setName("dubbo"); user.setId(404l); String name = demoService.testFormBody(user); Assertions.assertEquals("dubbo", name); LinkedMultiValueMap<String, String> forms = new LinkedMultiValueMap<>(); forms.put("form", Arrays.asList("F1")); Assertions.assertEquals(Arrays.asList("F1"), demoService.testFormMapBody(forms)); exporter.unexport(); } @Test void testPrimitive() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); Integer result = demoService.primitiveInt(1, 2); Long resultLong = demoService.primitiveLong(1, 2l); long resultByte = demoService.primitiveByte((byte) 1, 2l); long resultShort = demoService.primitiveShort((short) 1, 2l, 1); assertThat(result, is(3)); assertThat(resultShort, is(3l)); assertThat(resultLong, is(3l)); assertThat(resultByte, is(3l)); exporter.unexport(); } @Test void testExceptionHandler() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); String result = demoService.error(); assertThat(result, is("ok")); exporter.unexport(); } @Test void testProxyDoubleCheck() { ProxyCreatorSupport proxyCreatorSupport = new ProxyCreatorSupport(); AdvisedSupport advisedSupport = new AdvisedSupport(); advisedSupport.setTarget(getServerImpl()); AopProxy aopProxy = proxyCreatorSupport.getAopProxyFactory().createAopProxy(advisedSupport); Object proxy = aopProxy.getProxy(); SpringRestDemoService server = (SpringRestDemoService) proxy; URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); Integer result = demoService.primitiveInt(1, 2); Long resultLong = demoService.primitiveLong(1, 2l); long resultByte = demoService.primitiveByte((byte) 1, 2l); long resultShort = demoService.primitiveShort((short) 1, 2l, 1); assertThat(result, is(3)); assertThat(resultShort, is(3l)); assertThat(resultLong, is(3l)); assertThat(resultByte, is(3l)); exporter.unexport(); } private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } }
SpringMvcRestProtocolTest
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/PainlessParser.java
{ "start": 106649, "end": 109913 }
class ____ extends UnarynotaddsubContext { public ChainContext chain() { return getRuleContext(ChainContext.class, 0); } public TerminalNode INCR() { return getToken(PainlessParser.INCR, 0); } public TerminalNode DECR() { return getToken(PainlessParser.DECR, 0); } public PostContext(UnarynotaddsubContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof PainlessParserVisitor) return ((PainlessParserVisitor<? extends T>) visitor).visitPost(this); else return visitor.visitChildren(this); } } public final UnarynotaddsubContext unarynotaddsub() throws RecognitionException { UnarynotaddsubContext _localctx = new UnarynotaddsubContext(_ctx, getState()); enterRule(_localctx, 38, RULE_unarynotaddsub); int _la; try { setState(339); _errHandler.sync(this); switch (getInterpreter().adaptivePredict(_input, 28, _ctx)) { case 1: _localctx = new ReadContext(_localctx); enterOuterAlt(_localctx, 1); { setState(332); chain(); } break; case 2: _localctx = new PostContext(_localctx); enterOuterAlt(_localctx, 2); { setState(333); chain(); setState(334); _la = _input.LA(1); if (!(_la == INCR || _la == DECR)) { _errHandler.recoverInline(this); } else { if (_input.LA(1) == Token.EOF) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } break; case 3: _localctx = new NotContext(_localctx); enterOuterAlt(_localctx, 3); { setState(336); _la = _input.LA(1); if (!(_la == BOOLNOT || _la == BWNOT)) { _errHandler.recoverInline(this); } else { if (_input.LA(1) == Token.EOF) matchedEOF = true; _errHandler.reportMatch(this); consume(); } setState(337); unary(); } break; case 4: _localctx = new CastContext(_localctx); enterOuterAlt(_localctx, 4); { setState(338); castexpression(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
PostContext
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java
{ "start": 3171, "end": 4875 }
interface ____(IntroductionInterceptor.class); suppressInterface(DynamicIntroductionAdvice.class); } /** * Subclasses may need to override this if they want to perform custom * behaviour in around advice. However, subclasses should invoke this * method, which handles introduced interfaces and forwarding to the target. */ @Override public @Nullable Object invoke(MethodInvocation mi) throws Throwable { if (isMethodOnIntroducedInterface(mi)) { // Using the following method rather than direct reflection, we // get correct handling of InvocationTargetException // if the introduced method throws an exception. Object retVal = AopUtils.invokeJoinpointUsingReflection(this.delegate, mi.getMethod(), mi.getArguments()); // Massage return value if possible: if the delegate returned itself, // we really want to return the proxy. if (retVal == this.delegate && mi instanceof ProxyMethodInvocation pmi) { Object proxy = pmi.getProxy(); if (mi.getMethod().getReturnType().isInstance(proxy)) { retVal = proxy; } } return retVal; } return doProceed(mi); } /** * Proceed with the supplied {@link org.aopalliance.intercept.MethodInterceptor}. * Subclasses can override this method to intercept method invocations on the * target object which is useful when an introduction needs to monitor the object * that it is introduced into. This method is <strong>never</strong> called for * {@link MethodInvocation MethodInvocations} on the introduced interfaces. */ protected @Nullable Object doProceed(MethodInvocation mi) throws Throwable { // If we get here, just pass the invocation on. return mi.proceed(); } }
suppressInterface
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/LambdaTestUtils.java
{ "start": 2916, "end": 13527 }
interface ____ { /** * Create an exception (or throw one, if desired). * @param timeoutMillis timeout which has arisen * @param caught any exception which was caught; may be null * @return an exception which will then be thrown * @throws Exception if the handler wishes to raise an exception * that way. */ Throwable evaluate(int timeoutMillis, Throwable caught) throws Throwable; } /** * Wait for a condition to be met, with a retry policy returning the * sleep time before the next attempt is made. If, at the end * of the timeout period, the condition is still false (or failing with * an exception), the timeout handler is invoked, passing in the timeout * and any exception raised in the last invocation. The exception returned * by this timeout handler is then rethrown. * <p> * Example: Wait 30s for a condition to be met, with a sleep of 30s * between each probe. * If the operation is failing, then, after 30s, the timeout handler * is called. This returns the exception passed in (if any), * or generates a new one. * <pre> * await( * 30 * 1000, * () -> { return 0 == filesystem.listFiles(new Path("/")).length); }, * () -> 500), * (timeout, ex) -> ex != null ? ex : new TimeoutException("timeout")); * </pre> * * @param timeoutMillis timeout in milliseconds. * Can be zero, in which case only one attempt is made. * @param check predicate to evaluate * @param retry retry escalation logic * @param timeoutHandler handler invoked on timeout; * the returned exception will be thrown * @return the number of iterations before the condition was satisfied * @throws Exception the exception returned by {@code timeoutHandler} on * timeout * @throws FailFastException immediately if the evaluated operation raises it * @throws InterruptedException if interrupted. */ public static int await(int timeoutMillis, Callable<Boolean> check, Callable<Integer> retry, TimeoutHandler timeoutHandler) throws Exception { Preconditions.checkArgument(timeoutMillis >= 0, "timeoutMillis must be >= 0"); Preconditions.checkNotNull(timeoutHandler); long endTime = Time.now() + timeoutMillis; Throwable ex = null; boolean running = true; int iterations = 0; while (running) { iterations++; try { if (check.call()) { return iterations; } // the probe failed but did not raise an exception. Reset any // exception raised by a previous probe failure. ex = null; } catch (InterruptedException | FailFastException | VirtualMachineError e) { throw e; } catch (Throwable e) { LOG.debug("eventually() iteration {}", iterations, e); ex = e; } running = Time.now() < endTime; if (running) { int sleeptime = retry.call(); if (sleeptime >= 0) { Thread.sleep(sleeptime); } else { running = false; } } } // timeout Throwable evaluate; try { evaluate = timeoutHandler.evaluate(timeoutMillis, ex); if (evaluate == null) { // bad timeout handler logic; fall back to GenerateTimeout so the // underlying problem isn't lost. LOG.error("timeout handler {} did not throw an exception ", timeoutHandler); evaluate = new GenerateTimeout().evaluate(timeoutMillis, ex); } } catch (Throwable throwable) { evaluate = throwable; } return raise(evaluate); } /** * Simplified {@link #await(int, Callable, Callable, TimeoutHandler)} * operation with a fixed interval * and {@link GenerateTimeout} handler to generate a {@code TimeoutException}. * <p> * Example: await for probe to succeed: * <pre> * await( * 30 * 1000, 500, * () -> { return 0 == filesystem.listFiles(new Path("/")).length); }); * </pre> * * @param timeoutMillis timeout in milliseconds. * Can be zero, in which case only one attempt is made. * @param intervalMillis interval in milliseconds between checks * @param check predicate to evaluate * @return the number of iterations before the condition was satisfied * @throws Exception returned by {@code failure} on timeout * @throws FailFastException immediately if the evaluated operation raises it * @throws InterruptedException if interrupted. */ public static int await(int timeoutMillis, int intervalMillis, Callable<Boolean> check) throws Exception { return await(timeoutMillis, check, new FixedRetryInterval(intervalMillis), new GenerateTimeout()); } /** * Repeatedly execute a closure until it returns a value rather than * raise an exception. * Exceptions are caught and, with one exception, * trigger a sleep and retry. This is similar of ScalaTest's * {@code eventually(timeout, closure)} operation, though that lacks * the ability to fail fast if the inner closure has determined that * a failure condition is non-recoverable. * <p> * Example: spin until an the number of files in a filesystem is non-zero, * returning the files found. * The sleep interval backs off by 500 ms each iteration to a maximum of 5s. * <pre> * FileStatus[] files = eventually( 30 * 1000, * () -> { * FileStatus[] f = filesystem.listFiles(new Path("/")); * assertEquals(0, f.length); * return f; * }, * new ProportionalRetryInterval(500, 5000)); * </pre> * This allows for a fast exit, yet reduces probe frequency over time. * * @param <T> return type * @param timeoutMillis timeout in milliseconds. * Can be zero, in which case only one attempt is made before failing. * @param eval expression to evaluate * @param retry retry interval generator * @return result of the first successful eval call * @throws Exception the last exception thrown before timeout was triggered * @throws FailFastException if raised -without any retry attempt. * @throws InterruptedException if interrupted during the sleep operation. * @throws OutOfMemoryError you've run out of memory. */ public static <T> T eventually(int timeoutMillis, Callable<T> eval, Callable<Integer> retry) throws Exception { Preconditions.checkArgument(timeoutMillis >= 0, "timeoutMillis must be >= 0"); long endTime = Time.now() + timeoutMillis; Throwable ex; boolean running; int sleeptime; int iterations = 0; do { iterations++; try { return eval.call(); } catch (InterruptedException | FailFastException | VirtualMachineError e) { // these two exceptions trigger an immediate exit throw e; } catch (Throwable e) { LOG.debug("evaluate() iteration {}", iterations, e); ex = e; } running = Time.now() < endTime; if (running && (sleeptime = retry.call()) >= 0) { Thread.sleep(sleeptime); } } while (running); // timeout. Throw the last exception raised return raise(ex); } /** * Take the throwable and raise it as an exception or an error, depending * upon its type. This allows callers to declare that they only throw * Exception (i.e. can be invoked by Callable) yet still rethrow a * previously caught Throwable. * @param throwable Throwable to rethrow * @param <T> expected return type * @return never * @throws Exception if throwable is an Exception * @throws Error if throwable is not an Exception */ private static <T> T raise(Throwable throwable) throws Exception { if (throwable instanceof Exception) { throw (Exception) throwable; } else { throw (Error) throwable; } } /** * Variant of {@link #eventually(int, Callable, Callable)} method for * void lambda expressions. * @param timeoutMillis timeout in milliseconds. * Can be zero, in which case only one attempt is made before failing. * @param eval expression to evaluate * @param retry retry interval generator * @throws Exception the last exception thrown before timeout was triggered * @throws FailFastException if raised -without any retry attempt. * @throws InterruptedException if interrupted during the sleep operation. */ public static void eventually(int timeoutMillis, VoidCallable eval, Callable<Integer> retry) throws Exception { eventually(timeoutMillis, new VoidCaller(eval), retry); } /** * Simplified {@link #eventually(int, Callable, Callable)} method * with a fixed interval. * <p> * Example: wait 30s until an assertion holds, sleeping 1s between each * check. * <pre> * eventually( 30 * 1000, 1000, * () -> { assertEquals(0, filesystem.listFiles(new Path("/")).length); } * ); * </pre> * * @param timeoutMillis timeout in milliseconds. * Can be zero, in which case only one attempt is made before failing. * @param intervalMillis interval in milliseconds * @param eval expression to evaluate * @return result of the first successful invocation of {@code eval()} * @throws Exception the last exception thrown before timeout was triggered * @throws FailFastException if raised -without any retry attempt. * @throws InterruptedException if interrupted during the sleep operation. */ public static <T> T eventually(int timeoutMillis, int intervalMillis, Callable<T> eval) throws Exception { return eventually(timeoutMillis, eval, new FixedRetryInterval(intervalMillis)); } /** /** * Variant of {@link #eventually(int, int, Callable)} method for * void lambda expressions. * @param timeoutMillis timeout in milliseconds. * Can be zero, in which case only one attempt is made before failing. * @param intervalMillis interval in milliseconds * @param eval expression to evaluate * @throws Exception the last exception thrown before timeout was triggered * @throws FailFastException if raised -without any retry attempt. * @throws InterruptedException if interrupted during the sleep operation. */ public static void eventually(int timeoutMillis, int intervalMillis, VoidCallable eval) throws Exception { eventually(timeoutMillis, eval, new FixedRetryInterval(intervalMillis)); } /** * Intercept an exception; throw an {@code AssertionError} if one not raised. * The caught exception is rethrown if it is of the wrong
TimeoutHandler
java
apache__flink
flink-tests/src/test/java/org/apache/flink/api/functions/ClosureCleanerITCase.java
{ "start": 5615, "end": 6541 }
class ____ { private NonSerializable nonSer = new NonSerializable(); public void run(String resultPath) throws Exception { NonSerializable nonSer2 = new NonSerializable(); int x = 5; StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); DataStreamSource<Long> nums = env.fromSequence(1, 4); nums.map(num -> num + x) .setParallelism(1) .fullWindowPartition() .reduce((ReduceFunction<Long>) Long::sum) .sinkTo( FileSink.forRowFormat( new Path(resultPath), new SimpleStringEncoder<Long>()) .build()); env.execute(); } } }
TestClassWithoutFieldAccess
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java
{ "start": 1378, "end": 3923 }
class ____ { @Test void test() { // set KeepRunningOnSpringClosed flag for next spring context DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setKeepRunningOnSpringClosed(true); }); ClassPathXmlApplicationContext providerContext = null; try { String resourcePath = "org/apache/dubbo/config/spring"; providerContext = new ClassPathXmlApplicationContext( resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); providerContext.start(); // Expect 1: dubbo application state is STARTED after spring context start finish. // No need check and wait DubboStateListener dubboStateListener = providerContext.getBean(DubboStateListener.class); Assertions.assertEquals(DeployState.COMPLETION, dubboStateListener.getState()); ModuleModel moduleModel = providerContext.getBean(ModuleModel.class); ModuleDeployer moduleDeployer = moduleModel.getDeployer(); Assertions.assertTrue(moduleDeployer.isCompletion()); ApplicationDeployer applicationDeployer = moduleModel.getApplicationModel().getDeployer(); Assertions.assertEquals(DeployState.COMPLETION, applicationDeployer.getState()); Assertions.assertTrue(applicationDeployer.isCompletion()); Assertions.assertTrue(applicationDeployer.isStarted()); Assertions.assertFalse(applicationDeployer.isStopped()); Assertions.assertNotNull(DubboSpringInitializer.findBySpringContext(providerContext)); // close spring context providerContext.close(); // Expect 2: dubbo application will not be destroyed after closing spring context cause // setKeepRunningOnSpringClosed(true) Assertions.assertEquals(DeployState.COMPLETION, applicationDeployer.getState()); Assertions.assertTrue(applicationDeployer.isCompletion()); Assertions.assertTrue(applicationDeployer.isStarted()); Assertions.assertFalse(applicationDeployer.isStopped()); Assertions.assertNull(DubboSpringInitializer.findBySpringContext(providerContext)); } finally { DubboBootstrap.getInstance().stop(); SysProps.clear(); if (providerContext != null) { providerContext.close(); } } } }
KeepRunningOnSpringClosedTest
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/CompletableEventReaperTest.java
{ "start": 1627, "end": 9155 }
class ____ { private final LogContext logContext = new LogContext(); private final Time time = new MockTime(); private final CompletableEventReaper reaper = new CompletableEventReaper(logContext); @Test public void testExpired() { // Add a new event to the reaper. long timeoutMs = 100; UnsubscribeEvent event = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); reaper.add(event); // Without any time passing, we check the reaper and verify that the event is not done amd is still // being tracked. assertEquals(0, reaper.reap(time.milliseconds())); assertFalse(event.future().isDone()); assertEquals(1, reaper.size()); // Sleep for at least 1 ms. *more* than the timeout so that the event is considered expired. time.sleep(timeoutMs + 1); // However, until we actually invoke the reaper, the event isn't complete and is still being tracked. assertFalse(event.future().isDone()); assertEquals(1, reaper.size()); // Call the reaper and validate that the event is now "done" (expired), the correct exception type is // thrown, and the event is no longer tracked. assertEquals(1, reaper.reap(time.milliseconds())); assertTrue(event.future().isDone()); assertThrows(TimeoutException.class, () -> ConsumerUtils.getResult(event.future())); assertEquals(0, reaper.size()); } @Test public void testCompleted() { // Add a new event to the reaper. long timeoutMs = 100; UnsubscribeEvent event = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); reaper.add(event); // Without any time passing, we check the reaper and verify that the event is not done amd is still // being tracked. assertEquals(0, reaper.reap(time.milliseconds())); assertFalse(event.future().isDone()); assertEquals(1, reaper.size()); // We'll cause the event to be completed normally. Note that because we haven't called the reaper, the // event is still being tracked. event.future().complete(null); assertTrue(event.future().isDone()); assertEquals(1, reaper.size()); // To ensure we don't accidentally expire an event that completed normally, sleep past the timeout. time.sleep(timeoutMs + 1); // Call the reaper and validate that the event is not considered expired, but is still no longer tracked. assertEquals(0, reaper.reap(time.milliseconds())); assertTrue(event.future().isDone()); assertNull(ConsumerUtils.getResult(event.future())); assertEquals(0, reaper.size()); } @Test public void testCompletedAndExpired() { // Add two events to the reaper. One event will be completed, the other we will let expire. long timeoutMs = 100; UnsubscribeEvent event1 = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); UnsubscribeEvent event2 = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); reaper.add(event1); reaper.add(event2); // Without any time passing, we check the reaper and verify that the event is not done amd is still // being tracked. assertEquals(0, reaper.reap(time.milliseconds())); assertFalse(event1.future().isDone()); assertFalse(event2.future().isDone()); assertEquals(2, reaper.size()); // We'll cause the first event to be completed normally, but then sleep past the timer deadline. event1.future().complete(null); assertTrue(event1.future().isDone()); time.sleep(timeoutMs + 1); // Though the first event is completed, it's still being tracked, along with the second expired event. assertEquals(2, reaper.size()); // Validate that the first (completed) event is not expired, but the second one is expired. In either case, // both should be completed and neither should be tracked anymore. assertEquals(1, reaper.reap(time.milliseconds())); assertTrue(event1.future().isDone()); assertTrue(event2.future().isDone()); assertNull(ConsumerUtils.getResult(event1.future())); assertThrows(TimeoutException.class, () -> ConsumerUtils.getResult(event2.future())); assertEquals(0, reaper.size()); } @Test public void testIncompleteQueue() { long timeoutMs = 100; UnsubscribeEvent event1 = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); UnsubscribeEvent event2 = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); Collection<CompletableApplicationEvent<?>> queue = new ArrayList<>(); queue.add(event1); queue.add(event2); // Complete one of our events, just to make sure it isn't inadvertently canceled. event1.future().complete(null); // In this test, our events aren't tracked in the reaper, just in the queue. assertEquals(0, reaper.size()); assertEquals(2, queue.size()); // Go ahead and reap the incomplete from the queue. assertEquals(1, reaper.reap(queue)); // The first event was completed, so we didn't expire it in the reaper. assertTrue(event1.future().isDone()); assertFalse(event1.future().isCancelled()); assertNull(ConsumerUtils.getResult(event1.future())); // The second event was incomplete, so it was expired. assertTrue(event2.future().isCompletedExceptionally()); assertThrows(TimeoutException.class, () -> ConsumerUtils.getResult(event2.future())); // Because the events aren't tracked in the reaper *and* the queue is cleared as part of the // cancellation process, our data structures should both be the same as above. assertEquals(0, reaper.size()); assertEquals(0, queue.size()); } @Test public void testIncompleteTracked() { // This queue is just here to test the case where the queue is empty. Collection<CompletableApplicationEvent<?>> queue = new ArrayList<>(); // Add two events for the reaper to track. long timeoutMs = 100; UnsubscribeEvent event1 = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); UnsubscribeEvent event2 = new UnsubscribeEvent(calculateDeadlineMs(time.milliseconds(), timeoutMs)); reaper.add(event1); reaper.add(event2); // Complete one of our events, just to make sure it isn't inadvertently canceled. event1.future().complete(null); // In this test, our events are tracked exclusively in the reaper, not the queue. assertEquals(2, reaper.size()); // Go ahead and reap the incomplete events. Both sets should be zero after that. assertEquals(1, reaper.reap(queue)); assertEquals(0, reaper.size()); assertEquals(0, queue.size()); // The first event was completed, so we didn't cancel it in the reaper. assertTrue(event1.future().isDone()); assertNull(ConsumerUtils.getResult(event1.future())); // The second event was incomplete, so it was canceled. assertTrue(event2.future().isCompletedExceptionally()); assertThrows(TimeoutException.class, () -> ConsumerUtils.getResult(event2.future())); } }
CompletableEventReaperTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/Country.java
{ "start": 527, "end": 1100 }
class ____ implements Serializable { private Integer id; private String name; private List<State> states; @Id @GeneratedValue public Integer getId() { return id; } public String getName() { return name; } public void setId(Integer integer) { id = integer; } public void setName(String string) { name = string; } @OneToMany(fetch = FetchType.LAZY) @Cascade(org.hibernate.annotations.CascadeType.ALL) @Immutable public List<State> getStates() { return states; } public void setStates(List<State> states) { this.states = states; } }
Country
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/tasks/BanFailureLoggingTests.java
{ "start": 9274, "end": 9964 }
class ____ implements TaskAwareRequest { @Override public void setParentTask(TaskId taskId) { fail("setParentTask should not be called"); } @Override public void setRequestId(long requestId) { fail("setRequestId should not be called"); } @Override public TaskId getParentTask() { return TaskId.EMPTY_TASK_ID; } @Override public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) { return new CancellableTask(id, type, action, "", parentTaskId, headers); } } private static
ParentRequest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/ProactiveAuthPermissionCheckerRestMultiTest.java
{ "start": 289, "end": 628 }
class ____ extends AbstractPermissionCheckerRestMultiTest { @RegisterExtension static QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar.addClasses(TestResource.class, TestIdentityController.class, TestIdentityProvider.class)); }
ProactiveAuthPermissionCheckerRestMultiTest
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/checkreturnvalue/Api.java
{ "start": 6245, "end": 12107 }
class ____ must start with a valid character"); return type; } String methodName() { StringBuilder buffer = new StringBuilder(api.length() - position); boolean isConstructor = false; boolean finishedConstructor = false; // match "<init>", or otherwise a normal method name token: do { char next = nextLookingFor('('); switch (next) { case '(' -> { // We've hit the end of the method name, break out. break token; } case '<' -> { // Starting a constructor check(!isConstructor, api, "Only one '<' is allowed"); check(buffer.length() == 0, api, "'<' must come directly after '#'"); isConstructor = true; } case '>' -> { check(isConstructor, api, "'<' must come before '>'"); check(!finishedConstructor, api, "Only one '>' is allowed"); finishedConstructor = true; } case '-' -> { // OK, see https://kotlinlang.org/docs/inline-classes.html#mangling. } default -> checkArgument( isJavaIdentifierPart(next), "Unable to parse '%s' because '%s' is not a valid identifier", api, next); } buffer.append(next); } while (true); String methodName = buffer.toString(); if (isConstructor) { check(finishedConstructor, api, "found '<' without closing '>"); // Must be "<init>" exactly checkArgument( methodName.equals("<init>"), "Unable to parse '%s' because %s is an invalid method name", api, methodName); } else { check(!methodName.isEmpty(), api, "method name cannot be empty"); check( isJavaIdentifierStart(methodName.charAt(0)), api, "the method name must start with a valid character"); } return methodName; } ImmutableList<String> parameters() { // Text until the next ',' or ')' represents the parameter type. // If the first token is ')', then we have an empty parameter list. StringBuilder buffer = new StringBuilder(api.length() - position); ImmutableList.Builder<String> paramBuilder = ImmutableList.builder(); boolean emptyList = true; paramList: do { char next = nextLookingFor(')'); switch (next) { case ')' -> { if (emptyList) { return ImmutableList.of(); } // We've hit the end of the whole list, bail out. paramBuilder.add(consumeParam(buffer)); break paramList; } case ',' -> // We've hit the middle of a parameter, consume it paramBuilder.add(consumeParam(buffer)); case '[', ']', '.' -> // . characters are separators, [ and ] are array characters, they're checked @ the // end buffer.append(next); default -> { checkArgument( isJavaIdentifierPart(next), "Unable to parse '%s' because '%s' is not a valid identifier", api, next); emptyList = false; buffer.append(next); } } } while (true); return paramBuilder.build(); } private String consumeParam(StringBuilder buffer) { String parameter = buffer.toString(); buffer.setLength(0); // reset the buffer check(!parameter.isEmpty(), api, "parameters cannot be empty"); check( isJavaIdentifierStart(parameter.charAt(0)), api, "parameters must start with a valid character"); // Array specs must be in balanced pairs at the *end* of the parameter. boolean parsingArrayStart = false; boolean hasArraySpecifiers = false; for (int k = 1; k < parameter.length(); k++) { char c = parameter.charAt(k); switch (c) { case '[' -> { check(!parsingArrayStart, api, "multiple consecutive ["); hasArraySpecifiers = true; parsingArrayStart = true; } case ']' -> { check(parsingArrayStart, api, "unbalanced ] in array type"); parsingArrayStart = false; } default -> check( !hasArraySpecifiers, api, "types with array specifiers should end in those specifiers"); } } check(!parsingArrayStart, api, "[ without closing ] at the end of a parameter type"); return parameter; } // skip whitespace characters and give the next non-whitespace character. If we hit the end // without a non-whitespace character, throw expecting the delimiter. private char nextLookingFor(char delimiter) { char next; do { position++; checkArgument( position < api.length(), "Could not parse '%s' as it must contain an '%s'", api, delimiter); next = api.charAt(position); } while (!assumeNoWhitespace && whitespace().matches(next)); return next; } void ensureNoMoreCharacters() { if (assumeNoWhitespace) { return; } while (++position < api.length()) { check(whitespace().matches(api.charAt(position)), api, "it should end in ')'"); } } // The @CompileTimeConstant is for performance - reason should be constant and not eagerly // constructed. private static void check(boolean condition, String api, @CompileTimeConstant String reason) { checkArgument(condition, "Unable to parse '%s' because %s", api, reason); } } }
name
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/groovy/GroovyBeanDefinitionReaderTests.java
{ "start": 26588, "end": 27145 }
class ____ { String name; String leader; KnightsOfTheRoundTable(String n) { this.name = n; } HolyGrailQuest quest; void embarkOnQuest() { quest.start(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLeader() { return leader; } public void setLeader(String leader) { this.leader = leader; } public HolyGrailQuest getQuest() { return quest; } public void setQuest(HolyGrailQuest quest) { this.quest = quest; } } // simple bean
KnightsOfTheRoundTable
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityBasedAttribute.java
{ "start": 486, "end": 1011 }
class ____ extends AbstractNonIdentifierAttribute { protected AbstractEntityBasedAttribute( EntityPersister source, SessionFactoryImplementor sessionFactory, int attributeNumber, String attributeName, Type attributeType, BaselineAttributeInformation attributeInformation) { super( source, sessionFactory, attributeNumber, attributeName, attributeType, attributeInformation ); } @Override public EntityPersister getSource() { return (EntityPersister) super.getSource(); } }
AbstractEntityBasedAttribute
java
alibaba__nacos
client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java
{ "start": 5377, "end": 26360 }
class ____ implements Closeable { private static final Logger LOGGER = LogUtils.logger(ClientWorker.class); private static final String NOTIFY_HEADER = "notify"; private static final String TAG_PARAM = "tag"; private static final String APP_NAME_PARAM = "appName"; private static final String BETAIPS_PARAM = "betaIps"; private static final String TYPE_PARAM = "type"; private static final String ENCRYPTED_DATA_KEY_PARAM = "encryptedDataKey"; /** * groupKey -> cacheData. */ private final AtomicReference<Map<String, CacheData>> cacheMap = new AtomicReference<>(new HashMap<>()); private final DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager(); private ConfigFuzzyWatchGroupKeyHolder configFuzzyWatchGroupKeyHolder; private Map<String, String> appLabels = new HashMap<>(); private final ConfigFilterChainManager configFilterChainManager; private final String uuid = UUID.randomUUID().toString(); private long requestTimeout; private final ConfigRpcTransportClient agent; private boolean enableRemoteSyncConfig = false; private static final int MIN_THREAD_NUM = 2; private static final int THREAD_MULTIPLE = 1; private boolean enableClientMetrics = true; /** * index(taskId)-> total cache count for this taskId. */ private final List<AtomicInteger> taskIdCacheCountList = new ArrayList<>(); /** * Add listeners for data. * * @param dataId dataId of data * @param group group of data * @param listeners listeners */ public void addListeners(String dataId, String group, List<? extends Listener> listeners) throws NacosException { group = blank2defaultGroup(group); CacheData cache = addCacheDataIfAbsent(dataId, group); synchronized (cache) { for (Listener listener : listeners) { cache.addListener(listener); } cache.setDiscard(false); cache.setConsistentWithServer(false); // make sure cache exists in cacheMap if (getCache(dataId, group) != cache) { putCache(GroupKey.getKey(dataId, group), cache); } agent.notifyListenConfig(); } } /** * Add listeners for tenant. * * @param dataId dataId of data * @param group group of data * @param listeners listeners * @throws NacosException nacos exception */ public void addTenantListeners(String dataId, String group, List<? extends Listener> listeners) throws NacosException { group = blank2defaultGroup(group); String tenant = agent.getTenant(); CacheData cache = addCacheDataIfAbsent(dataId, group, tenant); synchronized (cache) { for (Listener listener : listeners) { cache.addListener(listener); } cache.setDiscard(false); cache.setConsistentWithServer(false); // ensure cache present in cacheMap if (getCache(dataId, group, tenant) != cache) { putCache(GroupKey.getKeyTenant(dataId, group, tenant), cache); } agent.notifyListenConfig(); } } /** * Add listeners for tenant with content. * * @param dataId dataId of data * @param group group of data * @param content content * @param encryptedDataKey encryptedDataKey * @param listeners listeners * @throws NacosException nacos exception */ public void addTenantListenersWithContent(String dataId, String group, String content, String encryptedDataKey, List<? extends Listener> listeners) throws NacosException { group = blank2defaultGroup(group); String tenant = agent.getTenant(); CacheData cache = addCacheDataIfAbsent(dataId, group, tenant); synchronized (cache) { cache.setEncryptedDataKey(encryptedDataKey); cache.setContent(content); for (Listener listener : listeners) { cache.addListener(listener); } cache.setDiscard(false); cache.setConsistentWithServer(false); // make sure cache exists in cacheMap if (getCache(dataId, group, tenant) != cache) { putCache(GroupKey.getKeyTenant(dataId, group, tenant), cache); } agent.notifyListenConfig(); } } /** * Remove listener. * * @param dataId dataId of data * @param group group of data * @param listener listener */ public void removeListener(String dataId, String group, Listener listener) { group = blank2defaultGroup(group); CacheData cache = getCache(dataId, group); if (null != cache) { synchronized (cache) { cache.removeListener(listener); if (cache.getListeners().isEmpty()) { cache.setConsistentWithServer(false); cache.setDiscard(true); agent.removeCache(dataId, group); } } } } /** * Remove listeners for tenant. * * @param dataId dataId of data * @param group group of data * @param listener listener */ public void removeTenantListener(String dataId, String group, Listener listener) { group = blank2defaultGroup(group); String tenant = agent.getTenant(); CacheData cache = getCache(dataId, group, tenant); if (null != cache) { synchronized (cache) { cache.removeListener(listener); if (cache.getListeners().isEmpty()) { cache.setConsistentWithServer(false); cache.setDiscard(true); agent.removeCache(dataId, group); } } } } /** * Adds a list of fuzzy listen listeners for the specified data ID pattern and group. * * @param dataIdPattern The pattern of the data ID to listen for. * @param groupPattern The group of the configuration. * @param fuzzyWatchEventWatcher The configFuzzyWatcher to add. * @throws NacosException If an error occurs while adding the listeners. */ public ConfigFuzzyWatchContext addTenantFuzzyWatcher(String dataIdPattern, String groupPattern, FuzzyWatchEventWatcher fuzzyWatchEventWatcher) { return configFuzzyWatchGroupKeyHolder.registerFuzzyWatcher(dataIdPattern, groupPattern, fuzzyWatchEventWatcher); } /** * Removes a fuzzy listen listener for the specified data ID pattern, group, and listener. * * @param dataIdPattern The pattern of the data ID. * @param group The group of the configuration. * @param watcher The listener to remove. * @throws NacosException If an error occurs while removing the listener. */ public void removeFuzzyListenListener(String dataIdPattern, String group, FuzzyWatchEventWatcher watcher) { configFuzzyWatchGroupKeyHolder.removeFuzzyWatcher(dataIdPattern, group, watcher); } void removeCache(String dataId, String group, String tenant) { String groupKey = GroupKey.getKeyTenant(dataId, group, tenant); synchronized (cacheMap) { Map<String, CacheData> copy = new HashMap<>(cacheMap.get()); CacheData remove = copy.remove(groupKey); if (remove != null) { decreaseTaskIdCount(remove.getTaskId()); } cacheMap.set(copy); } LOGGER.info("[{}] [unsubscribe] {}", agent.getName(), groupKey); if (enableClientMetrics) { try { MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size()); } catch (Throwable t) { LOGGER.error("Failed to update metrics for listen config count", t); } } } /** * remove config. * * @param dataId dataId. * @param group group. * @param tenant tenant. * @param tag tag. * @return success or not. * @throws NacosException exception to throw. */ public boolean removeConfig(String dataId, String group, String tenant, String tag) throws NacosException { return agent.removeConfig(dataId, group, tenant, tag); } /** * publish config. * * @param dataId dataId. * @param group group. * @param tenant tenant. * @param appName appName. * @param tag tag. * @param betaIps betaIps. * @param content content. * @param casMd5 casMd5. * @param type type. * @return success or not. * @throws NacosException exception throw. */ public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, String betaIps, String content, String encryptedDataKey, String casMd5, String type) throws NacosException { return agent.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, encryptedDataKey, casMd5, type); } /** * Add cache data if absent. * * @param dataId data id if data * @param group group of data * @return cache data */ public CacheData addCacheDataIfAbsent(String dataId, String group) { CacheData cache = getCache(dataId, group); if (null != cache) { return cache; } String key = GroupKey.getKey(dataId, group); cache = new CacheData(configFilterChainManager, agent.getName(), dataId, group); synchronized (cacheMap) { CacheData cacheFromMap = getCache(dataId, group); // multiple listeners on the same dataid+group and race condition,so double check again //other listener thread beat me to set to cacheMap if (null != cacheFromMap) { cache = cacheFromMap; //reset so that server not hang this check cache.setInitializing(true); } else { int taskId = calculateTaskId(); increaseTaskIdCount(taskId); cache.setTaskId(taskId); } Map<String, CacheData> copy = new HashMap<>(cacheMap.get()); copy.put(key, cache); cacheMap.set(copy); } LOGGER.info("[{}] [subscribe] {}", agent.getName(), key); if (enableClientMetrics) { try { MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size()); } catch (Throwable t) { LOGGER.error("Failed to update metrics for listen config count", t); } } return cache; } /** * Add cache data if absent. * * @param dataId data id if data * @param group group of data * @param tenant tenant of data * @return cache data */ public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) throws NacosException { CacheData cache = getCache(dataId, group, tenant); if (null != cache) { return cache; } String key = GroupKey.getKeyTenant(dataId, group, tenant); synchronized (cacheMap) { CacheData cacheFromMap = getCache(dataId, group, tenant); // multiple listeners on the same dataid+group and race condition,so // double check again // other listener thread beat me to set to cacheMap if (null != cacheFromMap) { cache = cacheFromMap; // reset so that server not hang this check cache.setInitializing(true); } else { cache = new CacheData(configFilterChainManager, agent.getName(), dataId, group, tenant); int taskId = calculateTaskId(); increaseTaskIdCount(taskId); cache.setTaskId(taskId); // fix issue # 1317 if (enableRemoteSyncConfig) { ConfigResponse response = getServerConfig(dataId, group, tenant, requestTimeout, false); cache.setEncryptedDataKey(response.getEncryptedDataKey()); cache.setContent(response.getContent()); } } Map<String, CacheData> copy = new HashMap<>(this.cacheMap.get()); copy.put(key, cache); cacheMap.set(copy); } LOGGER.info("[{}] [subscribe] {}", agent.getName(), key); if (enableClientMetrics) { try { MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size()); } catch (Throwable t) { LOGGER.error("Failed to update metrics for listen config count", t); } } return cache; } /** * Put cache. * * @param key groupKey * @param cache cache */ private void putCache(String key, CacheData cache) { synchronized (cacheMap) { Map<String, CacheData> copy = new HashMap<>(this.cacheMap.get()); copy.put(key, cache); cacheMap.set(copy); } } private void increaseTaskIdCount(int taskId) { taskIdCacheCountList.get(taskId).incrementAndGet(); } private void decreaseTaskIdCount(int taskId) { taskIdCacheCountList.get(taskId).decrementAndGet(); } private int calculateTaskId() { int perTaskSize = (int) ParamUtil.getPerTaskConfigSize(); for (int index = 0; index < taskIdCacheCountList.size(); index++) { if (taskIdCacheCountList.get(index).get() < perTaskSize) { return index; } } taskIdCacheCountList.add(new AtomicInteger(0)); return taskIdCacheCountList.size() - 1; } public CacheData getCache(String dataId, String group) { return getCache(dataId, group, TenantUtil.getUserTenantForAcm()); } public CacheData getCache(String dataId, String group, String tenant) { if (null == dataId || null == group) { throw new IllegalArgumentException(); } return cacheMap.get().get(GroupKey.getKeyTenant(dataId, group, tenant)); } public ConfigResponse getServerConfig(String dataId, String group, String tenant, long readTimeout, boolean notify) throws NacosException { if (StringUtils.isBlank(group)) { group = Constants.DEFAULT_GROUP; } return agent.queryConfig(dataId, group, tenant, readTimeout, notify); } private String blank2defaultGroup(String group) { return StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group.trim(); } @SuppressWarnings("PMD.ThreadPoolCreationRule") public ClientWorker(final ConfigFilterChainManager configFilterChainManager, ConfigServerListManager serverListManager, final NacosClientProperties properties) throws NacosException { this.configFilterChainManager = configFilterChainManager; init(properties); agent = new ConfigRpcTransportClient(properties, serverListManager); configFuzzyWatchGroupKeyHolder = new ConfigFuzzyWatchGroupKeyHolder(agent, uuid); ThreadPoolExecutor executor = instantiateClientExecutor(properties); agent.setExecutor(executor); agent.start(); configFuzzyWatchGroupKeyHolder.start(); } void initAppLabels(Properties properties) { this.appLabels = ConnLabelsUtils.addPrefixForEachKey(defaultLabelsCollectorManager.getLabels(properties), APP_CONN_PREFIX); } private ThreadPoolExecutor instantiateClientExecutor(final NacosClientProperties properties) { int workerThreadCount = initWorkerThreadCount(properties); return new ThreadPoolExecutor(workerThreadCount, workerThreadCount * 2, 60 * 5, TimeUnit.SECONDS, // when corePoolSize is not enough, task will not wait in queue, because SynchronousQueue 0 capacity // will create new thread to execute task util maximumPoolSize is reached new SynchronousQueue<>(), new NameThreadFactory("com.alibaba.nacos.client.executor"), // CallerRunsPolicy ensures that tasks are not lost new ThreadPoolExecutor.CallerRunsPolicy() ); } private int initWorkerThreadCount(NacosClientProperties properties) { int count = ThreadUtils.getSuitableThreadCount(THREAD_MULTIPLE); if (properties == null) { return count; } count = Math.min(count, properties.getInteger(PropertyKeyConst.CLIENT_WORKER_MAX_THREAD_COUNT, count)); count = Math.max(count, MIN_THREAD_NUM); return properties.getInteger(PropertyKeyConst.CLIENT_WORKER_THREAD_COUNT, count); } private void init(NacosClientProperties properties) { requestTimeout = ConvertUtils.toLong(properties.getProperty(PropertyKeyConst.CONFIG_REQUEST_TIMEOUT, "-1")); this.enableRemoteSyncConfig = Boolean.parseBoolean( properties.getProperty(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG)); this.enableClientMetrics = Boolean.parseBoolean( properties.getProperty(PropertyKeyConst.ENABLE_CLIENT_METRICS, "true")); initAppLabels(properties.getProperties(SourceType.PROPERTIES)); } Map<String, Object> getMetrics(List<ClientConfigMetricRequest.MetricsKey> metricsKeys) { Map<String, Object> metric = new HashMap<>(16); metric.put("listenConfigSize", String.valueOf(this.cacheMap.get().size())); metric.put("clientVersion", VersionUtils.getFullClientVersion()); metric.put("snapshotDir", LocalConfigInfoProcessor.LOCAL_SNAPSHOT_PATH); metric.put("addressUrl", agent.serverListManager.getAddressSource()); metric.put("isFixedServer", agent.serverListManager.isFixed()); metric.put("serverUrls", agent.serverListManager.getUrlString()); Map<ClientConfigMetricRequest.MetricsKey, Object> metricValues = getMetricsValue(metricsKeys); metric.put("metricValues", metricValues); Map<String, Object> metrics = new HashMap<>(1); metrics.put(uuid, JacksonUtils.toJson(metric)); return metrics; } private Map<ClientConfigMetricRequest.MetricsKey, Object> getMetricsValue( List<ClientConfigMetricRequest.MetricsKey> metricsKeys) { if (metricsKeys == null) { return null; } Map<ClientConfigMetricRequest.MetricsKey, Object> values = new HashMap<>(16); for (ClientConfigMetricRequest.MetricsKey metricsKey : metricsKeys) { if (ClientConfigMetricRequest.MetricsKey.CACHE_DATA.equals(metricsKey.getType())) { CacheData cacheData = cacheMap.get().get(metricsKey.getKey()); values.putIfAbsent(metricsKey, cacheData == null ? null : cacheData.getContent() + ":" + cacheData.getMd5()); } if (ClientConfigMetricRequest.MetricsKey.SNAPSHOT_DATA.equals(metricsKey.getType())) { String[] configStr = GroupKey.parseKey(metricsKey.getKey()); String snapshot = LocalConfigInfoProcessor.getSnapshot(agent.getName(), configStr[0], configStr[1], configStr[2]); values.putIfAbsent(metricsKey, snapshot == null ? null : snapshot + ":" + MD5Utils.md5Hex(snapshot, ENCODE)); } } return values; } @Override public void shutdown() throws NacosException { String className = this.getClass().getName(); LOGGER.info("{} do shutdown begin", className); if (configFuzzyWatchGroupKeyHolder != null) { configFuzzyWatchGroupKeyHolder.shutdown(); // help gc configFuzzyWatchGroupKeyHolder = null; } if (agent != null) { agent.shutdown(); } LOGGER.info("{} do shutdown stop", className); } /** * check if it has any connectable server endpoint. * * @return true: that means has atleast one connected rpc client. flase: that means does not have any connected rpc * client. */ public boolean isHealthServer() { return agent.isHealthServer(); } public
ClientWorker
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeduplicate.java
{ "start": 12560, "end": 14945 }
class ____ { protected final ReadableConfig config; protected final InternalTypeInfo<RowData> rowTypeInfo; protected final TypeSerializer<RowData> typeSerializer; protected final boolean keepLastRow; protected final boolean outputInsertOnly; protected final boolean generateUpdateBefore; protected final long stateRetentionTime; protected DeduplicateOperatorTranslator( ReadableConfig config, InternalTypeInfo<RowData> rowTypeInfo, TypeSerializer<RowData> typeSerializer, boolean keepLastRow, boolean outputInsertOnly, boolean generateUpdateBefore, long stateRetentionTime) { this.config = config; this.rowTypeInfo = rowTypeInfo; this.typeSerializer = typeSerializer; this.keepLastRow = keepLastRow; this.outputInsertOnly = outputInsertOnly; this.generateUpdateBefore = generateUpdateBefore; this.stateRetentionTime = stateRetentionTime; } protected boolean generateInsert() { return config.get(TABLE_EXEC_DEDUPLICATE_INSERT_UPDATE_AFTER_SENSITIVE_ENABLED); } protected boolean isMiniBatchEnabled() { return config.get(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED); } protected boolean isCompactChanges() { return config.get(TABLE_EXEC_DEDUPLICATE_MINIBATCH_COMPACT_CHANGES_ENABLED); } protected boolean isAsyncStateEnabled() { return config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_STATE_ENABLED); } protected long getMiniBatchSize() { if (isMiniBatchEnabled()) { long size = config.get(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE); checkArgument( size > 0, ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE.key() + " should be greater than 0."); return size; } else { return -1; } } abstract OneInputStreamOperator<RowData, RowData> createDeduplicateOperator(); } /** Translator to create event time deduplicate operator. */ private static
DeduplicateOperatorTranslator
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java
{ "start": 1635, "end": 1775 }
class ____ provide base functionality for easy stored procedure calls * based on configuration options and database meta-data. * * <p>This
to
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/Consumer.java
{ "start": 319, "end": 1703 }
class ____<K> { final K group; final K name; private Consumer(K group, K name) { this.group = group; this.name = name; } /** * Create a new consumer. * * @param group name of the consumer group, must not be {@code null} or empty. * @param name name of the consumer, must not be {@code null} or empty. * @return the consumer {@link Consumer} object. */ public static <K> Consumer<K> from(K group, K name) { LettuceAssert.notNull(group, "Group must not be null"); LettuceAssert.notNull(name, "Name must not be null"); return new Consumer<>(group, name); } /** * @return name of the group. */ public K getGroup() { return group; } /** * @return name of the consumer. */ public K getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Consumer)) return false; Consumer<?> consumer = (Consumer<?>) o; return Objects.equals(group, consumer.group) && Objects.equals(name, consumer.name); } @Override public int hashCode() { return Objects.hash(group, name); } @Override public String toString() { return String.format("%s:%s", group, name); } }
Consumer
java
quarkusio__quarkus
extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/ListMethodImplementor.java
{ "start": 2717, "end": 19286 }
class ____ extends StandardMethodImplementor { private static final String METHOD_NAME = "list"; private static final String RESOURCE_METHOD_NAME = "list"; private static final String EXCEPTION_MESSAGE = "Failed to list the entities"; private static final String REL = "list"; private final PaginationImplementor paginationImplementor = new PaginationImplementor(); private final SortImplementor sortImplementor = new SortImplementor(); private final QueryImplementor queryImplementor = new QueryImplementor(); public ListMethodImplementor(Capabilities capabilities) { super(capabilities); } /** * Generate JAX-RS GET method. * * The RESTEasy Classic version exposes {@link RestDataResource#list(Page, Sort)} * and the generated pseudocode with enabled pagination is shown below. If pagination is disabled pageIndex and pageSize * query parameters are skipped and null {@link Page} instance is used. * * <pre> * {@code * &#64;GET * &#64;Path("") * &#64;Produces({"application/json"}) * &#64;LinkResource( * rel = "list", * entityClassName = "com.example.Entity" * ) * public Response list(&#64;QueryParam("page") &#64;DefaultValue("0") int pageIndex, * &#64;QueryParam("size") &#64;DefaultValue("20") int pageSize, * &#64;QueryParam("sort") List<String> sortQuery) { * Page page = Page.of(pageIndex, pageSize); * Sort sort = ...; // Build a sort instance from String entries of sortQuery * try { * List<Entity> entities = resource.getAll(page, sort); * // Get the page count, and build first, last, next, previous page instances * Response.ResponseBuilder responseBuilder = Response.status(200); * responseBuilder.entity(entities); * // Add headers with first, last, next and previous page URIs if they exist * return responseBuilder.build(); * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> * * The RESTEasy Reactive version exposes {@link io.quarkus.rest.data.panache.ReactiveRestDataResource#list(Page, Sort)} * and the generated code looks more or less like this: * * <pre> * {@code * &#64;GET * &#64;Path("") * &#64;Produces({"application/json"}) * &#64;LinkResource( * rel = "list", * entityClassName = "com.example.Entity" * ) * public Uni<Response> list(&#64;QueryParam("page") &#64;DefaultValue("0") int pageIndex, * &#64;QueryParam("size") &#64;DefaultValue("20") int pageSize, * &#64;QueryParam("sort") List<String> sortQuery) { * Page page = Page.of(pageIndex, pageSize); * Sort sort = ...; // Build a sort instance from String entries of sortQuery * try { * return resource.getAll(page, sort).map(entities -> { * // Get the page count, and build first, last, next, previous page instances * Response.ResponseBuilder responseBuilder = Response.status(200); * responseBuilder.entity(entities); * // Add headers with first, last, next and previous page URIs if they exist * return responseBuilder.build(); * }); * * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> */ @Override protected void implementInternal(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { if (resourceProperties.isPaged()) { implementPaged(classCreator, resourceMetadata, resourceProperties, resourceField); } else { implementNotPaged(classCreator, resourceMetadata, resourceProperties, resourceField); } } @Override protected String getResourceMethodName() { return RESOURCE_METHOD_NAME; } protected String getMethodName() { return METHOD_NAME; } @Override protected void addProducesJsonAnnotation(AnnotatedElement element, ResourceProperties properties) { super.addProducesAnnotation(element, APPLICATION_JSON); } protected void returnValueWithLinks(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, ResultHandle value, ResultHandle links) { creator.returnValue(responseImplementor.ok(creator, value, links)); } protected void returnValue(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, ResultHandle value) { creator.returnValue(responseImplementor.ok(creator, value)); } private void implementPaged(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { // Method parameters: sort strings, page index, page size, uri info Collection<SignatureMethodCreator.Parameter> compatibleFieldsForQuery = getFieldsToQuery(resourceMetadata); List<SignatureMethodCreator.Parameter> parameters = new ArrayList<>(); parameters.add(param("sort", List.class, parameterizedType(classType(List.class), classType(String.class)))); parameters.add(param("page", int.class, intType())); parameters.add(param("size", int.class, intType())); parameters.add(param("uriInfo", UriInfo.class)); parameters.add(param("namedQuery", String.class)); for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { parameters.add(param( param.getName().replace(".", "__"), param.getClazz())); } MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(getMethodName(), classCreator, isNotReactivePanache() ? responseType(resourceMetadata.getEntityType()) : uniType(resourceMetadata.getEntityType()), parameters.toArray(new SignatureMethodCreator.Parameter[0])); // Add method annotations addGetAnnotation(methodCreator); addPathAnnotation(methodCreator, resourceProperties.getPath(RESOURCE_METHOD_NAME)); addProducesJsonAnnotation(methodCreator, resourceProperties); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, RestResponse.Status.OK, resourceMetadata.getEntityType(), true); addSecurityAnnotations(methodCreator, resourceProperties); addSortQueryParamValidatorAnnotation(methodCreator); addQueryParamAnnotation(methodCreator.getParameterAnnotations(0), "sort"); addQueryParamAnnotation(methodCreator.getParameterAnnotations(1), "page"); addDefaultValueAnnotation(methodCreator.getParameterAnnotations(1), Integer.toString(DEFAULT_PAGE_INDEX)); addQueryParamAnnotation(methodCreator.getParameterAnnotations(2), "size"); addDefaultValueAnnotation(methodCreator.getParameterAnnotations(2), Integer.toString(DEFAULT_PAGE_SIZE)); addContextAnnotation(methodCreator.getParameterAnnotations(3)); addQueryParamAnnotation(methodCreator.getParameterAnnotations(4), "namedQuery"); Map<String, ResultHandle> fieldValues = new HashMap<>(); int index = 5; for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { addQueryParamAnnotation(methodCreator.getParameterAnnotations(index), param.getName()); fieldValues.put(param.getName(), methodCreator.getMethodParam(index)); index++; } ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis()); ResultHandle sortQuery = methodCreator.getMethodParam(0); ResultHandle sort = sortImplementor.getSort(methodCreator, sortQuery); ResultHandle pageIndex = methodCreator.getMethodParam(1); ResultHandle pageSize = methodCreator.getMethodParam(2); ResultHandle page = paginationImplementor.getPage(methodCreator, pageIndex, pageSize); ResultHandle uriInfo = methodCreator.getMethodParam(3); ResultHandle namedQuery = methodCreator.getMethodParam(4); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle pageCount = pageCount(tryBlock, resourceMetadata, resource, page, namedQuery, fieldValues, int.class); ResultHandle links = paginationImplementor.getLinks(tryBlock, uriInfo, page, pageCount, fieldValues, namedQuery); ResultHandle entities = list(tryBlock, resourceMetadata, resource, page, sort, namedQuery, fieldValues); // Return response returnValueWithLinks(tryBlock, resourceMetadata, resourceProperties, entities, links); tryBlock.close(); } else { ResultHandle uniPageCount = pageCount(methodCreator, resourceMetadata, resource, page, namedQuery, fieldValues, Uni.class); methodCreator.returnValue(UniImplementor.flatMap(methodCreator, uniPageCount, EXCEPTION_MESSAGE, (body, pageCount) -> { ResultHandle pageCountAsInt = body.checkCast(pageCount, Integer.class); ResultHandle links = paginationImplementor.getLinks(body, uriInfo, page, pageCountAsInt, fieldValues, namedQuery); ResultHandle uniEntities = list(body, resourceMetadata, resource, page, sort, namedQuery, fieldValues); body.returnValue(UniImplementor.map(body, uniEntities, EXCEPTION_MESSAGE, (listBody, list) -> returnValueWithLinks(listBody, resourceMetadata, resourceProperties, list, links))); })); } methodCreator.close(); } private Collection<SignatureMethodCreator.Parameter> getFieldsToQuery(ResourceMetadata resourceMetadata) { return resourceMetadata.getFields().entrySet() .stream() .filter(e -> isFieldTypeCompatibleForQueryParam(e.getValue())) // we need to map primitive types to classes to make the fields nullable .map(e -> param(e.getKey(), primitiveToClass(e.getValue().name().toString()))) .collect(Collectors.toList()); } private void implementNotPaged(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceFieldDescriptor) { Collection<SignatureMethodCreator.Parameter> compatibleFieldsForQuery = getFieldsToQuery(resourceMetadata); List<SignatureMethodCreator.Parameter> parameters = new ArrayList<>(); parameters.add(param("sort", List.class, parameterizedType(classType(List.class), classType(String.class)))); parameters.add(param("namedQuery", String.class)); for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { parameters.add(param( param.getName().replace(".", "__"), param.getClazz())); } MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(getMethodName(), classCreator, isNotReactivePanache() ? responseType(resourceMetadata.getEntityType()) : uniType(resourceMetadata.getEntityType()), parameters.toArray(new SignatureMethodCreator.Parameter[0])); // Add method annotations addGetAnnotation(methodCreator); addPathAnnotation(methodCreator, resourceProperties.getPath(RESOURCE_METHOD_NAME)); addProducesJsonAnnotation(methodCreator, resourceProperties); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, RestResponse.Status.OK, resourceMetadata.getEntityType(), true); addSecurityAnnotations(methodCreator, resourceProperties); addQueryParamAnnotation(methodCreator.getParameterAnnotations(0), "sort"); addQueryParamAnnotation(methodCreator.getParameterAnnotations(1), "namedQuery"); Map<String, ResultHandle> fieldValues = new HashMap<>(); int index = 2; for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { addQueryParamAnnotation(methodCreator.getParameterAnnotations(index), param.getName()); fieldValues.put(param.getName(), methodCreator.getMethodParam(index)); index++; } ResultHandle sortQuery = methodCreator.getMethodParam(0); ResultHandle namedQuery = methodCreator.getMethodParam(1); ResultHandle sort = sortImplementor.getSort(methodCreator, sortQuery); ResultHandle resource = methodCreator.readInstanceField(resourceFieldDescriptor, methodCreator.getThis()); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle entities = list(tryBlock, resourceMetadata, resource, null, sort, namedQuery, fieldValues); returnValue(tryBlock, resourceMetadata, resourceProperties, entities); tryBlock.close(); } else { ResultHandle uniEntities = list(methodCreator, resourceMetadata, resource, methodCreator.loadNull(), sort, namedQuery, fieldValues); methodCreator.returnValue(UniImplementor.map(methodCreator, uniEntities, EXCEPTION_MESSAGE, (body, entities) -> returnValue(body, resourceMetadata, resourceProperties, entities))); } methodCreator.close(); } private ResultHandle pageCount(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResultHandle resource, ResultHandle page, ResultHandle namedQuery, Map<String, ResultHandle> fieldValues, Object returnType) { AssignableResultHandle query = queryImplementor.getQuery(creator, namedQuery, fieldValues); ResultHandle dataParams = queryImplementor.getDataParams(creator, fieldValues); return creator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), Constants.PAGE_COUNT_METHOD_PREFIX + RESOURCE_METHOD_NAME, returnType, Page.class, String.class, Map.class), resource, page, query, dataParams); } public ResultHandle list(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResultHandle resource, ResultHandle page, ResultHandle sort, ResultHandle namedQuery, Map<String, ResultHandle> fieldValues) { AssignableResultHandle query = queryImplementor.getQuery(creator, namedQuery, fieldValues); ResultHandle dataParams = queryImplementor.getDataParams(creator, fieldValues); return creator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), "list", isNotReactivePanache() ? List.class : Uni.class, Page.class, Sort.class, String.class, Map.class), resource, page == null ? creator.loadNull() : page, sort, query, dataParams); } private boolean isFieldTypeCompatibleForQueryParam(Type fieldType) { return fieldType.name().equals(STRING) || fieldType.name().equals(BOOLEAN) || fieldType.name().equals(CHARACTER) || fieldType.name().equals(DOUBLE) || fieldType.name().equals(SHORT) || fieldType.name().equals(FLOAT) || fieldType.name().equals(INTEGER) || fieldType.name().equals(LONG) || fieldType.name().equals(BYTE) || fieldType.kind() == Type.Kind.PRIMITIVE; } }
ListMethodImplementor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericMappedSuperclassPropertyUpdateTest.java
{ "start": 2646, "end": 3906 }
class ____ { final CriteriaUpdate<SpecificEntity> query; final Root<SpecificEntity> root; final Long id; final SpecificEntity relative; UpdateContext(CriteriaUpdate<SpecificEntity> query, Root<SpecificEntity> root, Long id, SpecificEntity relative) { this.query = query; this.root = root; this.id = id; this.relative = relative; } } static Stream<Arguments> criteriaUpdateFieldSetters() { Consumer<UpdateContext> updateUsingPath = context -> context.query.set( context.root.get( GenericMappedSuperclassPropertyUpdateTest_.SpecificEntity_.relative ), context.relative ); Consumer<UpdateContext> updateUsingSingularAttribute = context -> context.query.set( GenericMappedSuperclassPropertyUpdateTest_.SpecificEntity_.relative, context.relative ); Consumer<UpdateContext> updateUsingName = context -> context.query.set( GenericMappedSuperclassPropertyUpdateTest_.SpecificEntity_.RELATIVE, context.relative ); return Stream.of( Arguments.of( updateUsingPath ), Arguments.of( updateUsingSingularAttribute ), Arguments.of( updateUsingName ) ); } @Override public void injectSessionFactoryScope(SessionFactoryScope scope) { this.scope = scope; } @MappedSuperclass public abstract static
UpdateContext
java
processing__processing4
java/src/processing/mode/java/lsp/PdeAdapter.java
{ "start": 1607, "end": 13711 }
class ____ { File rootPath; LanguageClient client; JavaMode javaMode; File pdeFile; Sketch sketch; CompletionGenerator completionGenerator; PreprocService preprocService; ErrorChecker errorChecker; CompletableFuture<PreprocSketch> cps; CompletionGenerator suggestionGenerator; Set<URI> prevDiagnosticReportUris = new HashSet<>(); PreprocSketch ps; PdeAdapter(File rootPath, LanguageClient client) { this.rootPath = rootPath; this.client = client; Base.locateSketchbookFolder(); File location = Platform.getContentFile("modes/java"); ModeContribution mc = ModeContribution.load(null, location, JavaMode.class.getName()); if (mc == null) { // Shouldn't be possible but IntelliJ is complaining about it, // and we may run into path issues when running externally [fry 221126] throw new RuntimeException("Could not load Java Mode from " + location); } javaMode = (JavaMode) mc.getMode(); pdeFile = new File(rootPath, rootPath.getName() + ".pde"); sketch = new Sketch(pdeFile.toString(), javaMode); completionGenerator = new CompletionGenerator(javaMode); preprocService = new PreprocService(javaMode, sketch); errorChecker = new ErrorChecker(this::updateProblems, preprocService); cps = CompletableFutures.computeAsync(_x -> { throw new RuntimeException("unreachable"); }); suggestionGenerator = new CompletionGenerator(javaMode); notifySketchChanged(); } static Optional<File> uriToPath(URI uri) { try { return Optional.of(new File(uri)); } catch (Exception e) { return Optional.empty(); } } static URI pathToUri(File path) { return path.toURI(); } static Offset toLineCol(String s, int offset) { int line = (int)s.substring(0, offset).chars().filter(c -> c == '\n').count(); int col = offset - s.substring(0, offset).lastIndexOf('\n'); return new Offset(line, col); } static Offset toLineEndCol(String s, int offset) { Offset before = toLineCol(s, offset); return new Offset(before.line, Integer.MAX_VALUE); } /** * Converts a tabOffset to a position within a tab * @param program current code(text) from a tab * @param tabOffset character offset inside a tab * @return Position(line and col) within the tab */ static Position toPosition(String program, int tabOffset){ Offset offset = toLineCol(program, tabOffset); return new Position(offset.line, offset.col-1); } /** * Converts a range (start to end offset) to a location. * @param program current code(text) from a tab * @param startTabOffset starting character offset inside a tab * @param stopTabOffset ending character offset inside a tab * @param uri uri from a tab * @return Range inside a file */ static Location toLocation( String program, int startTabOffset, int stopTabOffset, URI uri ){ Position startPos = toPosition(program, startTabOffset); Position stopPos = toPosition(program, stopTabOffset); Range range = new Range(startPos, stopPos); return new Location(uri.toString(), range); } static void init() { Base.setCommandLine(); Platform.init(); Preferences.init(); } void notifySketchChanged() { CompletableFuture<PreprocSketch> cps = new CompletableFuture<>(); this.cps = cps; preprocService.notifySketchChanged(); errorChecker.notifySketchChanged(); preprocService.whenDone(cps::complete); try { ps = cps.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } Optional<SketchCode> findCodeByUri(URI uri) { return PdeAdapter.uriToPath(uri) .flatMap(path -> Arrays.stream(sketch.getCode()) .filter(code -> code.getFile().equals(path)) .findFirst() ); } /** * Looks for the tab number for a given text * @param code text(code) from a tab * @return tabIndex where the code belongs to, or empty */ public Optional<Integer> findTabIndex(SketchCode code){ int tabsCount = sketch.getCodeCount(); java.util.OptionalInt optionalTabIndex; optionalTabIndex = IntStream.range(0, tabsCount) .filter(i -> sketch.getCode(i).equals(code)) .findFirst(); if(optionalTabIndex.isEmpty()){ return Optional.empty(); } return Optional.of(optionalTabIndex.getAsInt()); } /** * Looks for the javaOffset, this offset is the character position inside the * full java file. The position can be used by the AST to find a node. * @param uri uri of the file(tab) where to look * @param line line number * @param col column number * @return character offset within the full AST */ public Optional<Integer> findJavaOffset(URI uri, int line, int col){ Optional<SketchCode> optionalCode = findCodeByUri(uri); if(optionalCode.isEmpty()){ System.out.println("couldn't find sketch code"); return Optional.empty(); } SketchCode code = optionalCode.get(); Optional<Integer> optionalTabIndex = findTabIndex(code); if (optionalTabIndex.isEmpty()){ System.out.println("couldn't find tab index"); return Optional.empty(); } int tabIndex = optionalTabIndex.get(); String[] codeLines = copyOfRange(code.getProgram().split("\n"), 0,line); String codeString = String.join("\n", codeLines); int tabOffset = codeString.length() + col; return Optional.of(ps.tabOffsetToJavaOffset(tabIndex, tabOffset)); } void updateProblems(List<Problem> problems) { Map<URI, List<Diagnostic>> dias = problems.stream() .map(prob -> { SketchCode code = sketch.getCode(prob.getTabIndex()); int startOffset = prob.getStartOffset(); int endOffset = prob.getStopOffset(); Position startPosition = new Position( prob.getLineNumber(), PdeAdapter .toLineCol(code.getProgram(), startOffset) .col - 1 ); Position stopPosition; if (endOffset == -1) { stopPosition = new Position( prob.getLineNumber(), PdeAdapter .toLineEndCol(code.getProgram(), startOffset) .col - 1 ); } else { stopPosition = new Position( prob.getLineNumber(), PdeAdapter .toLineCol(code.getProgram(), endOffset) .col - 1 ); } Diagnostic dia = new Diagnostic( new Range(startPosition, stopPosition), prob.getMessage() ); dia.setSeverity( prob.isError() ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning ); return new AbstractMap.SimpleEntry<>( PdeAdapter.pathToUri(code.getFile()), dia ); }) .collect(Collectors.groupingBy( AbstractMap.SimpleEntry::getKey, Collectors.mapping( AbstractMap.SimpleEntry::getValue, Collectors.toList() ) )); for (Map.Entry<URI, List<Diagnostic>> entry : dias.entrySet()) { PublishDiagnosticsParams params = new PublishDiagnosticsParams(); params.setUri(entry.getKey().toString()); params.setDiagnostics(entry.getValue()); client.publishDiagnostics(params); } for (URI uri : prevDiagnosticReportUris) { if (!dias.containsKey(uri)) { PublishDiagnosticsParams params = new PublishDiagnosticsParams(); params.setUri(uri.toString()); params.setDiagnostics(Collections.emptyList()); client.publishDiagnostics(params); } } prevDiagnosticReportUris = dias.keySet(); } CompletionItem convertCompletionCandidate(CompletionCandidate c) { CompletionItem item = new CompletionItem(); item.setLabel(c.getElementName()); item.setInsertTextFormat(InsertTextFormat.Snippet); String insert = c.getCompletionString(); if (insert.contains("( )")) { insert = insert.replace("( )", "($1)"); } else if (insert.contains(",")) { int n = 1; char[] chs = insert.replace("(,", "($1,").toCharArray(); //insert = ""; StringBuilder newInsert = new StringBuilder(); for (char ch : chs) { if (ch == ',') { n += 1; //insert += ",$" + n; newInsert.append(",$").append(n); } //insert += ch; newInsert.append(ch); } insert = newInsert.toString(); } item.setInsertText(insert); CompletionItemKind kind = switch (c.getType()) { case 0 -> // PREDEF_CLASS CompletionItemKind.Class; case 1 -> // PREDEF_FIELD CompletionItemKind.Constant; case 2 -> // PREDEF_METHOD CompletionItemKind.Function; case 3 -> // LOCAL_CLASS CompletionItemKind.Class; case 4 -> // LOCAL_METHOD CompletionItemKind.Method; case 5 -> // LOCAL_FIELD CompletionItemKind.Field; case 6 -> // LOCAL_VARIABLE CompletionItemKind.Variable; default -> throw new IllegalArgumentException("Unknown completion type: " + c.getType()); }; item.setKind(kind); item.setDetail(Jsoup.parse(c.getLabel()).text()); return item; } Optional<String> parsePhrase(String text) { return Optional.ofNullable(JavaTextArea.parsePhrase(text)); } List<CompletionCandidate> filterPredictions( List<CompletionCandidate> candidates ) { return Collections.list(CompletionGenerator.filterPredictions(candidates).elements()); } CompletableFuture<List<CompletionItem>> generateCompletion( URI uri, int line, int col ) { return cps.thenApply(ps -> { Optional<List<CompletionItem>> result = findCodeByUri(uri) .flatMap(code -> { int codeIndex = IntStream.range(0, sketch.getCodeCount()) .filter(i -> sketch.getCode(i).equals(code)) .findFirst() .getAsInt(); int lineStartOffset = String.join( "\n", Arrays.copyOfRange(code.getProgram().split("\n"), 0, line + 1) ) .length(); int lineNumber = ps.tabOffsetToJavaLine(codeIndex, lineStartOffset); String text = code.getProgram() .split("\n")[line] // TODO: 範囲外のエラー処理 .substring(0, col); return parsePhrase(text) .map(phrase -> { System.out.println("phrase: " + phrase); System.out.println("lineNumber: " + lineNumber); return Optional.ofNullable( suggestionGenerator .preparePredictions(ps, phrase, lineNumber) ) .filter(x -> !x.isEmpty()) .map(candidates -> { Collections.sort(candidates); System.out.println("candidates: " + candidates); List<CompletionCandidate> filtered = filterPredictions(candidates); System.out.println("filtered: " + filtered); return filtered.stream() .map(this::convertCompletionCandidate) .collect(Collectors.toList()); }); }) .orElse(Optional.empty()); }); return result.orElse(Collections.emptyList()); }); } void onChange(URI uri, String text) { findCodeByUri(uri) .ifPresent(code -> { code.setProgram(text); notifySketchChanged(); }); } Optional<TextEdit> format(URI uri) { return findCodeByUri(uri) .map(SketchCode::getProgram) .map(code -> { String newCode = new AutoFormat().format(code); Offset end = PdeAdapter.toLineCol(code, code.length()); return new TextEdit( new Range( new Position(0, 0), new Position(end.line, end.col) ), newCode ); }); } static
PdeAdapter
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java
{ "start": 46306, "end": 53305 }
class ____ a matching constructor). * * @apiNote We don't want to hoist this into {@linkplain #verifySelectionType} * itself because this can only happen for the root non-compound case, and we * want to avoid the try/catch otherwise */ private static void verifySingularSelectionType( Class<?> expectedResultClass, JpaCompliance jpaCompliance, SqmSelectableNode<?> selectableNode) { try { verifySelectionType( expectedResultClass, jpaCompliance, selectableNode ); } catch (QueryTypeMismatchException mismatchException) { // Check for special case of a single selection item and implicit instantiation. // See if the selected type can be used to instantiate the expected-type final var javaTypeDescriptor = selectableNode.getJavaTypeDescriptor(); if ( javaTypeDescriptor != null ) { // ignore the exception if the expected type has a constructor accepting the selected item type if ( hasMatchingConstructor( expectedResultClass, javaTypeDescriptor.getJavaTypeClass() ) ) { // ignore it } else { throw mismatchException; } } } } private static <T> boolean hasMatchingConstructor(Class<T> expectedResultClass, Class<?> selectedJavaType) { try { expectedResultClass.getDeclaredConstructor( selectedJavaType ); return true; } catch (NoSuchMethodException e) { return false; } } private static <T> void verifySelectionType( Class<T> expectedResultClass, JpaCompliance jpaCompliance, SqmSelectableNode<?> selection) { // special case for parameters in the select list if ( selection instanceof SqmParameter<?> sqmParameter ) { final var nodeType = sqmParameter.getExpressible(); // we may not yet know a selection type if ( nodeType == null || nodeType.getExpressibleJavaType() == null ) { // we can't verify the result type up front return; } } if ( !jpaCompliance.isJpaQueryComplianceEnabled() ) { verifyResultType( expectedResultClass, selection ); } } /** * Any query result can be represented as a {@link Tuple}, {@link List}, or {@link Map}, * simply by repackaging the result tuple. Also, any query result is assignable to * {@code Object}, or can be returned as an instance of {@code Object[]}. * * @see ConcreteSqmSelectQueryPlan#determineRowTransformer * @see org.hibernate.query.sql.internal.NativeQueryImpl#determineTupleTransformerForResultType */ public static boolean isResultTypeAlwaysAllowed(Class<?> expectedResultClass) { return expectedResultClass == null || expectedResultClass == Object.class || expectedResultClass == Object[].class || expectedResultClass == List.class || expectedResultClass == Map.class || expectedResultClass == Tuple.class; } protected static void verifyResultType(Class<?> resultClass, SqmSelectableNode<?> selectableNode) { final var selectionExpressible = selectableNode.getExpressible(); final var javaType = selectionExpressible == null ? selectableNode.getNodeJavaType() // for SqmDynamicInstantiation : selectionExpressible.getExpressibleJavaType(); if ( javaType != null ) { final var javaTypeClass = javaType.getJavaTypeClass(); if ( javaTypeClass != Object.class ) { if ( !isValid( resultClass, selectionExpressible, javaTypeClass, javaType ) ) { throwQueryTypeMismatchException( resultClass, selectionExpressible, javaTypeClass ); } } } } private static boolean isValid( Class<?> resultClass, SqmExpressible<?> selectionExpressible, Class<?> selectionExpressibleJavaTypeClass, JavaType<?> selectionExpressibleJavaType) { return resultClass.isAssignableFrom( selectionExpressibleJavaTypeClass ) || selectionExpressibleJavaType instanceof final PrimitiveJavaType<?> primitiveJavaType && primitiveJavaType.getPrimitiveClass() == resultClass || isMatchingDateType( selectionExpressibleJavaTypeClass, resultClass, selectionExpressible ) || isEntityIdType( selectionExpressible, resultClass ); } private static boolean isEntityIdType(SqmExpressible<?> selectionExpressible, Class<?> resultClass) { if ( selectionExpressible instanceof IdentifiableDomainType<?> identifiableDomainType ) { return resultClass.isAssignableFrom( identifiableDomainType.getIdType().getJavaType() ); } else if ( selectionExpressible instanceof EntitySqmPathSource<?> entityPath ) { return resultClass.isAssignableFrom( entityPath.getPathType().getIdType().getJavaType() ); } else { return false; } } // Special case for date because we always report java.util.Date as expression type // But the expected resultClass could be a subtype of that, so we need to check the JdbcType private static boolean isMatchingDateType( Class<?> javaTypeClass, Class<?> resultClass, SqmExpressible<?> sqmExpressible) { return javaTypeClass == Date.class && isMatchingDateJdbcType( resultClass, getJdbcType( sqmExpressible ) ); } private static JdbcType getJdbcType(SqmExpressible<?> sqmExpressible) { if ( sqmExpressible instanceof BasicDomainType<?> basicDomainType ) { return basicDomainType.getJdbcType(); } else if ( sqmExpressible instanceof SqmPathSource<?> pathSource ) { if ( pathSource.getPathType() instanceof BasicDomainType<?> basicDomainType ) { return basicDomainType.getJdbcType(); } } return null; } private static boolean isMatchingDateJdbcType(Class<?> resultClass, JdbcType jdbcType) { if ( jdbcType != null ) { return switch ( jdbcType.getDefaultSqlTypeCode() ) { case Types.DATE -> resultClass.isAssignableFrom(java.sql.Date.class); case Types.TIME -> resultClass.isAssignableFrom(java.sql.Time.class); case Types.TIMESTAMP -> resultClass.isAssignableFrom(java.sql.Timestamp.class); default -> false; }; } else { return false; } } private static void throwQueryTypeMismatchException( Class<?> resultClass, @Nullable SqmExpressible<?> sqmExpressible, @Nullable Class<?> javaTypeClass) { throw new QueryTypeMismatchException( String.format( Locale.ROOT, "Incorrect query result type: query produces '%s' but type '%s' was given", sqmExpressible == null ? javaTypeClass.getName() : sqmExpressible.getTypeName(), resultClass.getName() ) ); } public static Set<ParameterExpression<?>> getParameters(SqmStatement<?> statement) { final var parameters = statement.getSqmParameters(); return switch ( parameters.size() ) { case 0 -> emptySet(); case 1 -> { final var parameter = parameters.iterator().next(); yield parameter instanceof ValueBindJpaCriteriaParameter ? emptySet() : singleton( parameter ); } default -> { final Set<ParameterExpression<?>> parameterExpressions = new HashSet<>( parameters.size() ); for ( var parameter : parameters ) { if ( !(parameter instanceof ValueBindJpaCriteriaParameter) ) { parameterExpressions.add( parameter ); } } yield unmodifiableSet( parameterExpressions ); } }; } }
has
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/SchedulingPolicy.java
{ "start": 4701, "end": 8544 }
class ____ found!"); } } if (!SchedulingPolicy.class.isAssignableFrom(clazz)) { throw new AllocationConfigurationException(policy + " does not extend SchedulingPolicy"); } return getInstance(clazz); } /** * Initialize the scheduling policy with cluster resources. * @deprecated Since it doesn't track cluster resource changes, replaced by * {@link #initialize(FSContext)}. * * @param clusterCapacity cluster resources */ @Deprecated public void initialize(Resource clusterCapacity) {} /** * Initialize the scheduling policy with a {@link FSContext} object, which has * a pointer to the cluster resources among other information. * * @param fsContext a {@link FSContext} object which has a pointer to the * cluster resources */ public void initialize(FSContext fsContext) {} /** * The {@link ResourceCalculator} returned by this method should be used * for any calculations involving resources. * * @return ResourceCalculator instance to use */ public abstract ResourceCalculator getResourceCalculator(); /** * @return returns the name of {@link SchedulingPolicy} */ public abstract String getName(); /** * The comparator returned by this method is to be used for sorting the * {@link Schedulable}s in that queue. * * @return the comparator to sort by */ public abstract Comparator<Schedulable> getComparator(); /** * Computes and updates the shares of {@link Schedulable}s as per * the {@link SchedulingPolicy}, to be used later for scheduling decisions. * The shares computed are instantaneous and only consider queues with * running applications. * * @param schedulables {@link Schedulable}s whose shares are to be updated * @param totalResources Total {@link Resource}s in the cluster */ public abstract void computeShares( Collection<? extends Schedulable> schedulables, Resource totalResources); /** * Computes and updates the steady shares of {@link FSQueue}s as per the * {@link SchedulingPolicy}. The steady share does not differentiate * between queues with and without running applications under them. The * steady share is not used for scheduling, it is displayed on the Web UI * for better visibility. * * @param queues {@link FSQueue}s whose shares are to be updated * @param totalResources Total {@link Resource}s in the cluster */ public abstract void computeSteadyShares( Collection<? extends FSQueue> queues, Resource totalResources); /** * Check if the resource usage is over the fair share under this policy. * * @param usage {@link Resource} the resource usage * @param fairShare {@link Resource} the fair share * @return true if check passes (is over) or false otherwise */ public abstract boolean checkIfUsageOverFairShare( Resource usage, Resource fairShare); /** * Get headroom by calculating the min of {@code clusterAvailable} and * ({@code queueFairShare} - {@code queueUsage}) resources that are * applicable to this policy. For eg if only memory then leave other * resources such as CPU to same as {@code clusterAvailable}. * * @param queueFairShare fairshare in the queue * @param queueUsage resources used in the queue * @param maxAvailable available resource in cluster for this queue * @return calculated headroom */ public abstract Resource getHeadroom(Resource queueFairShare, Resource queueUsage, Resource maxAvailable); /** * Check whether the policy of a child queue is allowed. * * @param childPolicy the policy of child queue * @return true if the child policy is allowed; false otherwise */ public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) { return true; } }
not
java
alibaba__druid
core/src/test/java/com/alibaba/druid/sql/dialect/hive/parser/HiveStatementParserTest.java
{ "start": 230, "end": 786 }
class ____ extends TestCase { /** * 验证add jar类型SQL可以正常解析 * 例子: add jar hdfs:///hadoop/parser.h.file */ @Test public void testAddJarStatement() { String s = "add jar hdfs:///hadoop/parser.h.file"; HiveStatementParser hiveStatementParser = new HiveStatementParser(s); SQLStatement sqlStatement = hiveStatementParser.parseAdd(); assertTrue(sqlStatement instanceof HiveAddJarStatement); assertEquals("ADD JAR hdfs:///hadoop/parser.h.file", sqlStatement.toString()); } }
HiveStatementParserTest
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java
{ "start": 150212, "end": 151339 }
class ____ extends BooleanExpressionContext { public TerminalNode NOT() { return getToken(SqlBaseParser.NOT, 0); } public BooleanExpressionContext booleanExpression() { return getRuleContext(BooleanExpressionContext.class, 0); } public LogicalNotContext(BooleanExpressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterLogicalNot(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitLogicalNot(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitLogicalNot(this); else return visitor.visitChildren(this); } } @SuppressWarnings("CheckReturnValue") public static
LogicalNotContext
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithProbePortTest.java
{ "start": 655, "end": 2985 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("kubernetes-with-probe-port") .setApplicationVersion("0.1-SNAPSHOT") .overrideConfigKey("quarkus.kubernetes.readiness-probe.http-action-port", "9191") .setLogFileName("k8s.log") .setForcedDependencies(List.of( Dependency.of("io.quarkus", "quarkus-kubernetes", Version.getVersion()), Dependency.of("io.quarkus", "quarkus-smallrye-health", Version.getVersion()))); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml")); List<HasMetadata> kubernetesList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("kubernetes.yml")); assertThat(kubernetesList.get(0)).isInstanceOfSatisfying(Deployment.class, d -> { assertThat(d.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("kubernetes-with-probe-port"); }); assertThat(d.getSpec()).satisfies(deploymentSpec -> { assertThat(deploymentSpec.getTemplate()).satisfies(t -> { assertThat(t.getSpec()).satisfies(podSpec -> { assertThat(podSpec.getContainers()).singleElement() .satisfies(container -> { assertThat(container.getReadinessProbe()).isNotNull().satisfies(p -> { assertEquals(p.getHttpGet().getPort().getIntVal(), 9191); assertEquals(p.getHttpGet().getScheme(), "HTTP"); }); }); }); }); }); }); } }
KubernetesWithProbePortTest
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/MockAlternativeKeyProvider.java
{ "start": 9669, "end": 9921 }
class ____ extends MockSignature { public MockSha256WithEcdsaSignature() throws NoSuchAlgorithmException, NoSuchProviderException { super("SHA256withECDSA", "SunEC"); } } public static final
MockSha256WithEcdsaSignature
java
apache__flink
flink-core/src/test/java/org/apache/flink/core/fs/LimitedConnectionsFileSystemTest.java
{ "start": 24638, "end": 24959 }
class ____ extends CheckedThread { private final OneShotLatch waiter = new OneShotLatch(); public void waitTillWokenUp() throws InterruptedException { waiter.await(); } public void wakeup() { waiter.trigger(); } } private static final
BlockingThread
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/JGroupsRaftEndpointBuilderFactory.java
{ "start": 9179, "end": 9552 }
interface ____ extends EndpointProducerBuilder { default AdvancedJGroupsRaftEndpointProducerBuilder advanced() { return (AdvancedJGroupsRaftEndpointProducerBuilder) this; } } /** * Advanced builder for endpoint producers for the JGroups raft component. */ public
JGroupsRaftEndpointProducerBuilder
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/HAProxyMessageCompletionHandler.java
{ "start": 615, "end": 3946 }
class ____ extends MessageToMessageDecoder<HAProxyMessage> { //Public because its used in tests public static final IOException UNSUPPORTED_PROTOCOL_EXCEPTION = new IOException("Unsupported HA PROXY transport protocol"); private static final Logger log = LoggerFactory.getLogger(HAProxyMessageCompletionHandler.class); private static final boolean proxyProtocolCodecFound; static { boolean proxyProtocolCodecCheck = true; try { Class.forName("io.netty.handler.codec.haproxy.HAProxyMessageDecoder"); } catch (Throwable ex) { proxyProtocolCodecCheck = false; } proxyProtocolCodecFound = proxyProtocolCodecCheck; } public static boolean canUseProxyProtocol(boolean requested) { if (requested && !proxyProtocolCodecFound) log.warn("Proxy protocol support could not be enabled. Make sure that netty-codec-haproxy is included in your classpath"); return proxyProtocolCodecFound && requested; } private final Promise<Channel> promise; public HAProxyMessageCompletionHandler(Promise<Channel> promise) { this.promise = promise; } @Override protected void decode(ChannelHandlerContext ctx, HAProxyMessage msg, List<Object> out) { HAProxyProxiedProtocol protocol = msg.proxiedProtocol(); //UDP over IPv4, UDP over IPv6 and UNIX datagram are not supported. Close the connection and fail the promise if (protocol.transportProtocol().equals(HAProxyProxiedProtocol.TransportProtocol.DGRAM)) { ctx.close(); promise.tryFailure(UNSUPPORTED_PROTOCOL_EXCEPTION); } else { /* UNKNOWN: the connection is forwarded for an unknown, unspecified or unsupported protocol. The sender should use this family when sending LOCAL commands or when dealing with unsupported protocol families. The receiver is free to accept the connection anyway and use the real endpoint addresses or to reject it */ if (!protocol.equals(HAProxyProxiedProtocol.UNKNOWN)) { if (msg.sourceAddress() != null) { ctx.channel().attr(ConnectionBase.REMOTE_ADDRESS_OVERRIDE) .set(createAddress(protocol, msg.sourceAddress(), msg.sourcePort())); } if (msg.destinationAddress() != null) { ctx.channel().attr(ConnectionBase.LOCAL_ADDRESS_OVERRIDE) .set(createAddress(protocol, msg.destinationAddress(), msg.destinationPort())); } } ctx.pipeline().remove(this); promise.setSuccess(ctx.channel()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { promise.tryFailure(cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == IdleState.ALL_IDLE) { ctx.close(); } else { ctx.fireUserEventTriggered(evt); } } private SocketAddress createAddress(HAProxyProxiedProtocol protocol, String sourceAddress, int port) { switch (protocol) { case TCP4: case TCP6: return SocketAddress.inetSocketAddress(port, sourceAddress); case UNIX_STREAM: return SocketAddress.domainSocketAddress(sourceAddress); default: throw new IllegalStateException("Should never happen"); } } }
HAProxyMessageCompletionHandler
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/json/JobVertexIDSerializer.java
{ "start": 1271, "end": 1679 }
class ____ extends StdSerializer<JobVertexID> { private static final long serialVersionUID = -2339350570828548335L; public JobVertexIDSerializer() { super(JobVertexID.class); } @Override public void serialize(JobVertexID value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(value.toString()); } }
JobVertexIDSerializer
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/test/java/org/apache/flink/api/java/hadoop/mapred/wrapper/HadoopInputSplitTest.java
{ "start": 6042, "end": 6592 }
class ____ extends FileSplit implements Configurable { private Configuration conf; public ConfigurableFileSplit() {} private ConfigurableFileSplit(Path file, long start, long length, String[] hosts) { super(file, start, length, hosts); } @Override public void setConf(Configuration configuration) { this.conf = configuration; } @Override public Configuration getConf() { return conf; } } private static
ConfigurableFileSplit
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/literal/AbstractCriteriaLiteralHandlingModeTest.java
{ "start": 3395, "end": 3554 }
class ____ { @Id private Integer id; private String name; } protected String bookName() { return "Vlad's High-Performance Java Persistence"; } }
Book
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapred/utils/HadoopUtils.java
{ "start": 1219, "end": 1294 }
class ____ work with Apache Hadoop MapRed classes. */ @Internal public final
to
java
spring-projects__spring-framework
spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java
{ "start": 3153, "end": 8499 }
class ____ extends AbstractMarshallerTests<Jaxb2Marshaller> { private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb.test"; private Flights flights; @Override protected Jaxb2Marshaller createMarshaller() throws Exception { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath(CONTEXT_PATH); marshaller.afterPropertiesSet(); return marshaller; } @Override protected Object createFlights() { FlightType flight = new FlightType(); flight.setNumber(42L); flights = new Flights(); flights.getFlight().add(flight); return flights; } @Test void marshalSAXResult() throws Exception { ContentHandler contentHandler = mock(); SAXResult result = new SAXResult(contentHandler); marshaller.marshal(flights, result); InOrder ordered = inOrder(contentHandler); ordered.verify(contentHandler).setDocumentLocator(isA(Locator.class)); ordered.verify(contentHandler).startDocument(); ordered.verify(contentHandler).startPrefixMapping("", "http://samples.springframework.org/flight"); ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("flights"), isA(Attributes.class)); ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("flight"), isA(Attributes.class)); ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("number"), isA(Attributes.class)); ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2)); ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "number"); ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "flight"); ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "flights"); ordered.verify(contentHandler).endPrefixMapping(""); ordered.verify(contentHandler).endDocument(); } @Test void lazyInit() throws Exception { marshaller = new Jaxb2Marshaller(); marshaller.setContextPath(CONTEXT_PATH); marshaller.setLazyInit(true); marshaller.afterPropertiesSet(); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); marshaller.marshal(flights, result); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING, ev); } @Test void properties() throws Exception { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath(CONTEXT_PATH); marshaller.setMarshallerProperties( Collections.singletonMap(jakarta.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE)); marshaller.afterPropertiesSet(); } @Test void noContextPathOrClassesToBeBound() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); assertThatIllegalArgumentException().isThrownBy(marshaller::afterPropertiesSet); } @Test void testInvalidContextPath() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("ab"); assertThatExceptionOfType(UncategorizedMappingException.class).isThrownBy(marshaller::afterPropertiesSet); } @Test void marshalInvalidClass() throws Exception { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(FlightType.class); marshaller.afterPropertiesSet(); Result result = new StreamResult(new StringWriter()); Flights flights = new Flights(); assertThatExceptionOfType(XmlMappingException.class).isThrownBy(() -> marshaller.marshal(flights, result)); } @Test void supportsContextPath() throws Exception { testSupports(); } @Test void supportsClassesToBeBound() throws Exception { marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Flights.class, FlightType.class); marshaller.afterPropertiesSet(); testSupports(); } @Test void supportsPackagesToScan() throws Exception { marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan(CONTEXT_PATH); marshaller.afterPropertiesSet(); testSupports(); } private void testSupports() throws Exception { assertThat(marshaller.supports(Flights.class)).as("Jaxb2Marshaller does not support Flights class").isTrue(); assertThat(marshaller.supports((Type)Flights.class)).as("Jaxb2Marshaller does not support Flights generic type").isTrue(); assertThat(marshaller.supports(FlightType.class)).as("Jaxb2Marshaller supports FlightType class").isFalse(); assertThat(marshaller.supports((Type)FlightType.class)).as("Jaxb2Marshaller supports FlightType type").isFalse(); Method method = ObjectFactory.class.getDeclaredMethod("createFlight", FlightType.class); assertThat(marshaller.supports(method.getGenericReturnType())).as("Jaxb2Marshaller does not support JAXBElement<FlightsType>").isTrue(); marshaller.setSupportJaxbElementClass(true); JAXBElement<FlightType> flightTypeJAXBElement = new JAXBElement<>(new QName("https://springframework.org", "flight"), FlightType.class, new FlightType()); assertThat(marshaller.supports(flightTypeJAXBElement.getClass())).as("Jaxb2Marshaller does not support JAXBElement<FlightsType>").isTrue(); assertThat(marshaller.supports(DummyRootElement.class)).as("Jaxb2Marshaller supports
Jaxb2MarshallerTests
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java
{ "start": 17459, "end": 17890 }
class ____ extends MockHttpOutputMessage implements StreamingHttpOutputMessage { private boolean repeatable; public boolean wasRepeatable() { return this.repeatable; } @Override public void setBody(Body body) { try { this.repeatable = body.repeatable(); body.writeTo(getBody()); } catch (IOException ex) { throw new RuntimeException(ex); } } } private static
StreamingMockHttpOutputMessage
java
google__auto
value/src/main/java/com/google/auto/value/extension/toprettystring/processor/Annotations.java
{ "start": 1043, "end": 1675 }
class ____ { static Optional<AnnotationMirror> getAnnotationMirror(Element element, String annotationName) { for (AnnotationMirror annotation : element.getAnnotationMirrors()) { TypeElement annotationElement = MoreTypes.asTypeElement(annotation.getAnnotationType()); if (annotationElement.getQualifiedName().contentEquals(annotationName)) { return Optional.of(annotation); } } return Optional.empty(); } static Optional<AnnotationMirror> toPrettyStringAnnotation(Element element) { return getAnnotationMirror(element, TO_PRETTY_STRING_NAME); } private Annotations() {} }
Annotations
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/stream/multijoin/StreamingTwoWayNonEquiJoinOperatorTest.java
{ "start": 12103, "end": 13534 }
class ____ extends AbstractRichFunction implements JoinCondition { private final int leftInputIndex; // Index of the row for the left side of '>' in inputs[] private final int leftAmountFieldIndex; // Field index of amount in the left side row private final int rightInputIndex; // Index of the row for the right side of '>' in inputs[] private final int rightAmountFieldIndex; // Field index of amount in the right side row public AmountGreaterThanConditionImpl( int leftInputIndex, int leftAmountFieldIndex, int rightInputIndex, int rightAmountFieldIndex) { this.leftInputIndex = leftInputIndex; this.leftAmountFieldIndex = leftAmountFieldIndex; this.rightInputIndex = rightInputIndex; this.rightAmountFieldIndex = rightAmountFieldIndex; } @Override public boolean apply(RowData left, RowData right) { if (left == null || right == null) { return false; } if (left.isNullAt(leftAmountFieldIndex) || right.isNullAt(rightAmountFieldIndex)) { return false; } return left.getLong(leftAmountFieldIndex) > right.getLong(rightAmountFieldIndex); } } /** Condition for u.user_id = o.user_id. */ private static
AmountGreaterThanConditionImpl
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/readonly/AddIndexBlockResponse.java
{ "start": 5895, "end": 7546 }
class ____ implements Writeable, ToXContentFragment { private final int id; private final Failure[] failures; public AddBlockShardResult(final int id, final Failure[] failures) { this.id = id; this.failures = failures; } AddBlockShardResult(final StreamInput in) throws IOException { this.id = in.readVInt(); this.failures = in.readOptionalArray(Failure::readFailure, Failure[]::new); } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeVInt(id); out.writeOptionalArray(failures); } public boolean hasFailures() { return CollectionUtils.isEmpty(failures) == false; } public int getId() { return id; } public Failure[] getFailures() { return failures; } @Override public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { builder.startObject(); { builder.field("id", String.valueOf(id)); builder.startArray("failures"); if (failures != null) { for (Failure failure : failures) { failure.toXContent(builder, params); } } builder.endArray(); } return builder.endObject(); } @Override public String toString() { return Strings.toString(this); } public static
AddBlockShardResult
java
quarkusio__quarkus
extensions/infinispan-client/runtime/src/main/java/io/quarkus/infinispan/client/runtime/InfinispanRecorder.java
{ "start": 2912, "end": 3424 }
class ____<T> implements Supplier<T> { private final Function<InfinispanClientProducer, T> producer; InfinispanClientSupplier(Function<InfinispanClientProducer, T> producer) { this.producer = producer; } @Override public T get() { InfinispanClientProducer infinispanClientProducer = Arc.container().instance(InfinispanClientProducer.class).get(); return producer.apply(infinispanClientProducer); } } }
InfinispanClientSupplier
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/process/ProcessResultsParserTests.java
{ "start": 910, "end": 3566 }
class ____ extends ESTestCase { public void testParse_GivenEmptyArray() throws IOException { String json = "[]"; try (InputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) { ProcessResultsParser<TestResult> parser = new ProcessResultsParser<>(TestResult.PARSER, NamedXContentRegistry.EMPTY); assertFalse(parser.parseResults(inputStream).hasNext()); } } public void testParse_GivenUnknownObject() throws IOException { String json = "[{\"unknown\":{\"id\": 18}}]"; try (InputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) { ProcessResultsParser<TestResult> parser = new ProcessResultsParser<>(TestResult.PARSER, NamedXContentRegistry.EMPTY); XContentParseException e = expectThrows( XContentParseException.class, () -> parser.parseResults(inputStream).forEachRemaining(a -> {}) ); assertEquals("[1:3] [test_result] unknown field [unknown]", e.getMessage()); } } public void testParse_GivenArrayContainsAnotherArray() throws IOException { String json = "[[]]"; try (InputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) { ProcessResultsParser<TestResult> parser = new ProcessResultsParser<>(TestResult.PARSER, NamedXContentRegistry.EMPTY); ElasticsearchParseException e = expectThrows( ElasticsearchParseException.class, () -> parser.parseResults(inputStream).forEachRemaining(a -> {}) ); assertEquals("unexpected token [START_ARRAY]", e.getMessage()); } } public void testParseResults() throws IOException { String input = """ [{"field_1": "a", "field_2": 1.0}, {"field_1": "b", "field_2": 2.0}, {"field_1": "c", "field_2": 3.0}]"""; try (InputStream inputStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) { ProcessResultsParser<TestResult> parser = new ProcessResultsParser<>(TestResult.PARSER, NamedXContentRegistry.EMPTY); Iterator<TestResult> testResultIterator = parser.parseResults(inputStream); List<TestResult> parsedResults = new ArrayList<>(); while (testResultIterator.hasNext()) { parsedResults.add(testResultIterator.next()); } assertThat(parsedResults, contains(new TestResult("a", 1.0), new TestResult("b", 2.0), new TestResult("c", 3.0))); } } private static
ProcessResultsParserTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/BootstrapUtilsTests.java
{ "start": 8908, "end": 9046 }
class ____ {} @org.springframework.test.context.web.WebAppConfiguration static
LocalDeclarationAndMetaAnnotatedBootstrapWithAnnotationClass
java
apache__camel
test-infra/camel-test-infra-pinecone/src/test/java/org/apache/camel/test/infra/pinecone/services/PineconeService.java
{ "start": 1047, "end": 1141 }
interface ____ extends TestService, PineconeInfraService, ContainerTestService { }
PineconeService
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumDb2EndpointBuilderFactory.java
{ "start": 99796, "end": 100138 }
class ____ extends AbstractEndpointBuilder implements DebeziumDb2EndpointBuilder, AdvancedDebeziumDb2EndpointBuilder { public DebeziumDb2EndpointBuilderImpl(String path) { super(componentName, path); } } return new DebeziumDb2EndpointBuilderImpl(path); } }
DebeziumDb2EndpointBuilderImpl
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/GrpcXdsClientImplDataTest.java
{ "start": 100381, "end": 170242 }
class ____ implements PluginConfig { @Override public String typeUrl() { return "type.googleapis.com/google.protobuf.Empty"; } } ClusterSpecifierPluginRegistry registry = ClusterSpecifierPluginRegistry.newRegistry(); registry.register(new ClusterSpecifierPlugin() { @Override public String[] typeUrls() { return new String[] { "type.googleapis.com/google.protobuf.Empty", }; } @Override public ConfigOrError<? extends PluginConfig> parsePlugin(Message rawProtoMessage) { return ConfigOrError.fromConfig(new TestPluginConfig()); } }); com.github.xds.type.v3.TypedStruct typedStruct = com.github.xds.type.v3.TypedStruct.newBuilder() .setTypeUrl("type.googleapis.com/google.protobuf.Empty") .setValue(Struct.newBuilder()) .build(); io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin pluginProto = io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin.newBuilder() .setExtension(TypedExtensionConfig.newBuilder() .setTypedConfig(Any.pack(typedStruct))) .build(); PluginConfig pluginConfig = XdsRouteConfigureResource .parseClusterSpecifierPlugin(pluginProto, registry); assertThat(pluginConfig).isInstanceOf(TestPluginConfig.class); } @Test public void parseClusterSpecifierPlugin_unregisteredPlugin() throws Exception { ClusterSpecifierPluginRegistry registry = ClusterSpecifierPluginRegistry.newRegistry(); io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin pluginProto = io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin.newBuilder() .setExtension(TypedExtensionConfig.newBuilder() .setTypedConfig(Any.pack(StringValue.of("unregistered")))) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsRouteConfigureResource.parseClusterSpecifierPlugin(pluginProto, registry)); assertThat(e).hasMessageThat().isEqualTo( "Unsupported ClusterSpecifierPlugin type: type.googleapis.com/google.protobuf.StringValue"); } @Test public void parseClusterSpecifierPlugin_unregisteredPlugin_optional() throws ResourceInvalidException { ClusterSpecifierPluginRegistry registry = ClusterSpecifierPluginRegistry.newRegistry(); io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin pluginProto = io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin.newBuilder() .setExtension(TypedExtensionConfig.newBuilder() .setTypedConfig(Any.pack(StringValue.of("unregistered")))) .setIsOptional(true) .build(); PluginConfig pluginConfig = XdsRouteConfigureResource .parseClusterSpecifierPlugin(pluginProto, registry); assertThat(pluginConfig).isNull(); } @Test public void parseClusterSpecifierPlugin_brokenPlugin() { ClusterSpecifierPluginRegistry registry = ClusterSpecifierPluginRegistry.newRegistry(); Any failingAny = Any.newBuilder() .setTypeUrl("type.googleapis.com/xds.type.v3.TypedStruct") .setValue(ByteString.copyFromUtf8("fail")) .build(); TypedExtensionConfig brokenPlugin = TypedExtensionConfig.newBuilder() .setName("bad-plugin-1") .setTypedConfig(failingAny) .build(); try { XdsRouteConfigureResource.parseClusterSpecifierPlugin( io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin.newBuilder() .setExtension(brokenPlugin) .build(), registry); fail("Expected ResourceInvalidException"); } catch (ResourceInvalidException e) { assertThat(e).hasMessageThat() .startsWith("ClusterSpecifierPlugin [bad-plugin-1] contains invalid proto"); } } @Test public void parseClusterSpecifierPlugin_brokenPlugin_optional() { ClusterSpecifierPluginRegistry registry = ClusterSpecifierPluginRegistry.newRegistry(); Any failingAny = Any.newBuilder() .setTypeUrl("type.googleapis.com/xds.type.v3.TypedStruct") .setValue(ByteString.copyFromUtf8("fail")) .build(); TypedExtensionConfig brokenPlugin = TypedExtensionConfig.newBuilder() .setName("bad-plugin-1") .setTypedConfig(failingAny) .build(); // Despite being optional, still should fail. try { XdsRouteConfigureResource.parseClusterSpecifierPlugin( io.envoyproxy.envoy.config.route.v3.ClusterSpecifierPlugin.newBuilder() .setIsOptional(true) .setExtension(brokenPlugin) .build(), registry); fail("Expected ResourceInvalidException"); } catch (ResourceInvalidException e) { assertThat(e).hasMessageThat() .startsWith("ClusterSpecifierPlugin [bad-plugin-1] contains invalid proto"); } } @Test public void parseCluster_ringHashLbPolicy_defaultLbConfig() throws ResourceInvalidException { Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.RING_HASH) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); LbConfig lbConfig = ServiceConfigUtil.unwrapLoadBalancingConfig(update.lbPolicyConfig()); assertThat(lbConfig.getPolicyName()).isEqualTo("ring_hash_experimental"); } @Test public void parseCluster_leastRequestLbPolicy_defaultLbConfig() throws ResourceInvalidException { XdsClusterResource.enableLeastRequest = true; Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.LEAST_REQUEST) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); LbConfig lbConfig = ServiceConfigUtil.unwrapLoadBalancingConfig(update.lbPolicyConfig()); assertThat(lbConfig.getPolicyName()).isEqualTo("wrr_locality_experimental"); List<LbConfig> childConfigs = ServiceConfigUtil.unwrapLoadBalancingConfigList( JsonUtil.getListOfObjects(lbConfig.getRawConfigValue(), "childPolicy")); assertThat(childConfigs.get(0).getPolicyName()).isEqualTo("least_request_experimental"); } @Test public void parseCluster_WrrLbPolicy_defaultLbConfig() throws ResourceInvalidException { LoadBalancingPolicy wrrConfig = LoadBalancingPolicy.newBuilder().addPolicies( LoadBalancingPolicy.Policy.newBuilder() .setTypedExtensionConfig(TypedExtensionConfig.newBuilder() .setName("backend") .setTypedConfig( Any.pack(ClientSideWeightedRoundRobin.newBuilder() .setBlackoutPeriod(Duration.newBuilder().setSeconds(17).build()) .setEnableOobLoadReport( BoolValue.newBuilder().setValue(true).build()) .setErrorUtilizationPenalty( FloatValue.newBuilder().setValue(1.75F).build()) .build())) .build()) .build()) .build(); Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLoadBalancingPolicy( LoadBalancingPolicy.newBuilder().addPolicies( LoadBalancingPolicy.Policy.newBuilder() .setTypedExtensionConfig( TypedExtensionConfig.newBuilder() .setTypedConfig( Any.pack(WrrLocality.newBuilder() .setEndpointPickingPolicy(wrrConfig) .build())) .build()) .build()) .build()) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); LbConfig lbConfig = ServiceConfigUtil.unwrapLoadBalancingConfig(update.lbPolicyConfig()); assertThat(lbConfig.getPolicyName()).isEqualTo("wrr_locality_experimental"); List<LbConfig> childConfigs = ServiceConfigUtil.unwrapLoadBalancingConfigList( JsonUtil.getListOfObjects(lbConfig.getRawConfigValue(), "childPolicy")); assertThat(childConfigs.get(0).getPolicyName()).isEqualTo("weighted_round_robin"); WeightedRoundRobinLoadBalancerConfig result = (WeightedRoundRobinLoadBalancerConfig) new WeightedRoundRobinLoadBalancerProvider().parseLoadBalancingPolicyConfig( childConfigs.get(0).getRawConfigValue()).getConfig(); assertThat(result.blackoutPeriodNanos).isEqualTo(17_000_000_000L); assertThat(result.enableOobLoadReport).isTrue(); assertThat(result.oobReportingPeriodNanos).isEqualTo(10_000_000_000L); assertThat(result.weightUpdatePeriodNanos).isEqualTo(1_000_000_000L); assertThat(result.weightExpirationPeriodNanos).isEqualTo(180_000_000_000L); assertThat(result.errorUtilizationPenalty).isEqualTo(1.75F); } @Test public void parseCluster_transportSocketMatches_exception() throws ResourceInvalidException { Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .addTransportSocketMatches( Cluster.TransportSocketMatch.newBuilder().setName("match1").build()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.processCluster(cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry())); assertThat(e).hasMessageThat().isEqualTo( "Cluster cluster-foo.googleapis.com: transport-socket-matches not supported."); } @Test public void parseCluster_validateEdsSourceConfig() throws ResourceInvalidException { Cluster cluster1 = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .build(); XdsClusterResource.processCluster(cluster1, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); Cluster cluster2 = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setSelf(SelfConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .build(); XdsClusterResource.processCluster(cluster2, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); Cluster cluster3 = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setPathConfigSource(PathConfigSource.newBuilder().setPath("foo-path"))) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.processCluster(cluster3, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry())); assertThat(e).hasMessageThat().isEqualTo( "Cluster cluster-foo.googleapis.com: field eds_cluster_config must be set to indicate to" + " use EDS over ADS or self ConfigSource"); } @Test public void processCluster_parsesMetadata() throws ResourceInvalidException, InvalidProtocolBufferException { MetadataRegistry metadataRegistry = MetadataRegistry.getInstance(); MetadataValueParser testParser = new MetadataValueParser() { @Override public String getTypeUrl() { return "type.googleapis.com/test.Type"; } @Override public Object parse(Any value) { assertThat(value.getValue().toStringUtf8()).isEqualTo("test"); return value.getValue().toStringUtf8() + "_processed"; } }; metadataRegistry.registerParser(testParser); Any typedFilterMetadata = Any.newBuilder() .setTypeUrl("type.googleapis.com/test.Type") .setValue(ByteString.copyFromUtf8("test")) .build(); Struct filterMetadata = Struct.newBuilder() .putFields("key1", Value.newBuilder().setStringValue("value1").build()) .putFields("key2", Value.newBuilder().setNumberValue(42).build()) .build(); Metadata metadata = Metadata.newBuilder() .putTypedFilterMetadata("TYPED_FILTER_METADATA", typedFilterMetadata) .putFilterMetadata("FILTER_METADATA", filterMetadata) .build(); Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .setMetadata(metadata) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); ImmutableMap<String, Object> expectedParsedMetadata = ImmutableMap.of( "TYPED_FILTER_METADATA", "test_processed", "FILTER_METADATA", ImmutableMap.of( "key1", "value1", "key2", 42.0)); assertThat(update.parsedMetadata()).isEqualTo(expectedParsedMetadata); metadataRegistry.removeParser(testParser); } @Test public void processCluster_parsesAudienceMetadata() throws Exception { MetadataRegistry.getInstance(); Audience audience = Audience.newBuilder() .setUrl("https://example.com") .build(); Any audienceMetadata = Any.newBuilder() .setTypeUrl("type.googleapis.com/envoy.extensions.filters.http.gcp_authn.v3.Audience") .setValue(audience.toByteString()) .build(); Struct filterMetadata = Struct.newBuilder() .putFields("key1", Value.newBuilder().setStringValue("value1").build()) .putFields("key2", Value.newBuilder().setNumberValue(42).build()) .build(); Metadata metadata = Metadata.newBuilder() .putTypedFilterMetadata("AUDIENCE_METADATA", audienceMetadata) .putFilterMetadata("FILTER_METADATA", filterMetadata) .build(); Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .setMetadata(metadata) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); ImmutableMap<String, Object> expectedParsedMetadata = ImmutableMap.of( "AUDIENCE_METADATA", "https://example.com", "FILTER_METADATA", ImmutableMap.of( "key1", "value1", "key2", 42.0)); assertThat(update.parsedMetadata().get("FILTER_METADATA")) .isEqualTo(expectedParsedMetadata.get("FILTER_METADATA")); assertThat(update.parsedMetadata().get("AUDIENCE_METADATA")) .isInstanceOf(AudienceWrapper.class); } @Test public void processCluster_parsesAddressMetadata() throws Exception { // Create an Address message Address address = Address.newBuilder() .setSocketAddress(SocketAddress.newBuilder() .setAddress("192.168.1.1") .setPortValue(8080) .build()) .build(); // Wrap the Address in Any Any addressMetadata = Any.newBuilder() .setTypeUrl("type.googleapis.com/envoy.config.core.v3.Address") .setValue(address.toByteString()) .build(); Struct filterMetadata = Struct.newBuilder() .putFields("key1", Value.newBuilder().setStringValue("value1").build()) .putFields("key2", Value.newBuilder().setNumberValue(42).build()) .build(); Metadata metadata = Metadata.newBuilder() .putTypedFilterMetadata("ADDRESS_METADATA", addressMetadata) .putFilterMetadata("FILTER_METADATA", filterMetadata) .build(); Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .setMetadata(metadata) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); ImmutableMap<String, Object> expectedParsedMetadata = ImmutableMap.of( "ADDRESS_METADATA", new InetSocketAddress("192.168.1.1", 8080), "FILTER_METADATA", ImmutableMap.of( "key1", "value1", "key2", 42.0)); assertThat(update.parsedMetadata()).isEqualTo(expectedParsedMetadata); } @Test public void processCluster_metadataKeyCollision_resolvesToTypedMetadata() throws Exception { MetadataRegistry metadataRegistry = MetadataRegistry.getInstance(); MetadataValueParser testParser = new MetadataValueParser() { @Override public String getTypeUrl() { return "type.googleapis.com/test.Type"; } @Override public Object parse(Any value) { return "typedMetadataValue"; } }; metadataRegistry.registerParser(testParser); Any typedFilterMetadata = Any.newBuilder() .setTypeUrl("type.googleapis.com/test.Type") .setValue(ByteString.copyFromUtf8("test")) .build(); Struct filterMetadata = Struct.newBuilder() .putFields("key1", Value.newBuilder().setStringValue("filterMetadataValue").build()) .build(); Metadata metadata = Metadata.newBuilder() .putTypedFilterMetadata("key1", typedFilterMetadata) .putFilterMetadata("key1", filterMetadata) .build(); Cluster cluster = Cluster.newBuilder() .setName("cluster-foo.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-foo.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .setMetadata(metadata) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); ImmutableMap<String, Object> expectedParsedMetadata = ImmutableMap.of( "key1", "typedMetadataValue"); assertThat(update.parsedMetadata()).isEqualTo(expectedParsedMetadata); metadataRegistry.removeParser(testParser); } @Test public void parseNonAggregateCluster_withHttp11ProxyTransportSocket() throws Exception { XdsClusterResource.isEnabledXdsHttpConnect = true; Http11ProxyUpstreamTransport http11ProxyUpstreamTransport = Http11ProxyUpstreamTransport.newBuilder() .setTransportSocket(TransportSocket.getDefaultInstance()) .build(); TransportSocket transportSocket = TransportSocket.newBuilder() .setName(TRANSPORT_SOCKET_NAME_HTTP11_PROXY) .setTypedConfig(Any.pack(http11ProxyUpstreamTransport)) .build(); Cluster cluster = Cluster.newBuilder() .setName("cluster-http11-proxy.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder().setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-http11-proxy.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .setTransportSocket(transportSocket) .build(); CdsUpdate result = XdsClusterResource.processCluster(cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); assertThat(result).isNotNull(); assertThat(result.isHttp11ProxyAvailable()).isTrue(); } @Test public void processCluster_parsesOrcaLrsPropagationMetrics() throws ResourceInvalidException { LoadStatsManager2.isEnabledOrcaLrsPropagation = true; ImmutableList<String> metricSpecs = ImmutableList.of( "cpu_utilization", "named_metrics.foo", "unknown_metric_spec" ); Cluster cluster = Cluster.newBuilder() .setName("cluster-orca.googleapis.com") .setType(DiscoveryType.EDS) .setEdsClusterConfig( EdsClusterConfig.newBuilder() .setEdsConfig( ConfigSource.newBuilder().setAds(AggregatedConfigSource.getDefaultInstance())) .setServiceName("service-orca.googleapis.com")) .setLbPolicy(LbPolicy.ROUND_ROBIN) .addAllLrsReportEndpointMetrics(metricSpecs) .build(); CdsUpdate update = XdsClusterResource.processCluster( cluster, null, LRS_SERVER_INFO, LoadBalancerRegistry.getDefaultRegistry()); BackendMetricPropagation propagationConfig = update.backendMetricPropagation(); assertThat(propagationConfig).isNotNull(); assertThat(propagationConfig.propagateCpuUtilization).isTrue(); assertThat(propagationConfig.propagateMemUtilization).isFalse(); assertThat(propagationConfig.shouldPropagateNamedMetric("foo")).isTrue(); assertThat(propagationConfig.shouldPropagateNamedMetric("bar")).isFalse(); assertThat(propagationConfig.shouldPropagateNamedMetric("unknown_metric_spec")) .isFalse(); LoadStatsManager2.isEnabledOrcaLrsPropagation = false; } @Test public void parseServerSideListener_invalidTrafficDirection() throws ResourceInvalidException { Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.OUTBOUND) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat() .isEqualTo("Listener listener1 with invalid traffic direction: OUTBOUND"); } @Test public void parseServerSideListener_noTrafficDirection() throws ResourceInvalidException { Listener listener = Listener.newBuilder() .setName("listener1") .build(); XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)); } @Test public void parseServerSideListener_listenerFiltersPresent() throws ResourceInvalidException { Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .addListenerFilters(ListenerFilter.newBuilder().build()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener(listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat() .isEqualTo("Listener listener1 cannot have listener_filters"); } @Test public void parseServerSideListener_useOriginalDst() throws ResourceInvalidException { Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .setUseOriginalDst(BoolValue.of(true)) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener(listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat() .isEqualTo("Listener listener1 cannot have use_original_dst set to true"); } @Test public void parseServerSideListener_emptyAddress() throws ResourceInvalidException { Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .setAddress(Address.newBuilder() .setSocketAddress( SocketAddress.newBuilder())) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat().isEqualTo("Invalid address: Empty address is not allowed."); } @Test public void parseServerSideListener_namedPort() throws ResourceInvalidException { Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .setAddress(Address.newBuilder() .setSocketAddress( SocketAddress.newBuilder() .setAddress("172.14.14.5").setNamedPort(""))) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat().isEqualTo("NAMED_PORT is not supported in gRPC."); } @Test public void parseServerSideListener_nonUniqueFilterChainMatch() throws ResourceInvalidException { Filter filter1 = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-1").setTypedConfig( Any.pack(Router.newBuilder().build())).setIsOptional(true).build()); FilterChainMatch filterChainMatch1 = FilterChainMatch.newBuilder() .addAllSourcePorts(Arrays.asList(80, 8080)) .addAllPrefixRanges(Arrays.asList(CidrRange.newBuilder().setAddressPrefix("192.168.0.0") .setPrefixLen(UInt32Value.of(16)).build(), CidrRange.newBuilder().setAddressPrefix("10.0.0.0").setPrefixLen(UInt32Value.of(8)) .build())) .build(); FilterChain filterChain1 = FilterChain.newBuilder() .setName("filter-chain-1") .setFilterChainMatch(filterChainMatch1) .addFilters(filter1) .build(); Filter filter2 = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-2").setTypedConfig( Any.pack(Router.newBuilder().build())).setIsOptional(true).build()); FilterChainMatch filterChainMatch2 = FilterChainMatch.newBuilder() .addAllSourcePorts(Arrays.asList(443, 8080)) .addAllPrefixRanges(Arrays.asList( CidrRange.newBuilder().setAddressPrefix("2001:DB8::8:800:200C:417A") .setPrefixLen(UInt32Value.of(60)).build(), CidrRange.newBuilder().setAddressPrefix("192.168.0.0") .setPrefixLen(UInt32Value.of(16)).build())) .build(); FilterChain filterChain2 = FilterChain.newBuilder() .setName("filter-chain-2") .setFilterChainMatch(filterChainMatch2) .addFilters(filter2) .build(); Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .addAllFilterChains(Arrays.asList(filterChain1, filterChain2)) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat() .startsWith("FilterChainMatch must be unique. Found duplicate:"); } @Test public void parseServerSideListener_nonUniqueFilterChainMatch_sameFilter() throws ResourceInvalidException { Filter filter1 = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-1").setTypedConfig( Any.pack(Router.newBuilder().build())).setIsOptional(true).build()); FilterChainMatch filterChainMatch1 = FilterChainMatch.newBuilder() .addAllSourcePorts(Arrays.asList(80, 8080)) .addAllPrefixRanges(Arrays.asList( CidrRange.newBuilder().setAddressPrefix("10.0.0.0").setPrefixLen(UInt32Value.of(8)) .build())) .build(); FilterChain filterChain1 = FilterChain.newBuilder() .setName("filter-chain-1") .setFilterChainMatch(filterChainMatch1) .addFilters(filter1) .build(); Filter filter2 = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-2").setTypedConfig( Any.pack(Router.newBuilder().build())).setIsOptional(true).build()); FilterChainMatch filterChainMatch2 = FilterChainMatch.newBuilder() .addAllSourcePorts(Arrays.asList(443, 8080)) .addAllPrefixRanges(Arrays.asList( CidrRange.newBuilder().setAddressPrefix("192.168.0.0") .setPrefixLen(UInt32Value.of(16)).build(), CidrRange.newBuilder().setAddressPrefix("192.168.0.0") .setPrefixLen(UInt32Value.of(16)).build())) .build(); FilterChain filterChain2 = FilterChain.newBuilder() .setName("filter-chain-2") .setFilterChainMatch(filterChainMatch2) .addFilters(filter2) .build(); Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .addAllFilterChains(Arrays.asList(filterChain1, filterChain2)) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat() .startsWith("FilterChainMatch must be unique. Found duplicate:"); } @Test public void parseServerSideListener_uniqueFilterChainMatch() throws ResourceInvalidException { Filter filter1 = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-1").setTypedConfig( Any.pack(Router.newBuilder().build())).setIsOptional(true).build()); FilterChainMatch filterChainMatch1 = FilterChainMatch.newBuilder() .addAllSourcePorts(Arrays.asList(80, 8080)) .addAllPrefixRanges(Arrays.asList(CidrRange.newBuilder().setAddressPrefix("192.168.0.0") .setPrefixLen(UInt32Value.of(16)).build(), CidrRange.newBuilder().setAddressPrefix("10.0.0.0").setPrefixLen(UInt32Value.of(8)) .build())) .setSourceType(FilterChainMatch.ConnectionSourceType.EXTERNAL) .build(); FilterChain filterChain1 = FilterChain.newBuilder() .setName("filter-chain-1") .setFilterChainMatch(filterChainMatch1) .addFilters(filter1) .build(); Filter filter2 = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-2").setTypedConfig( Any.pack(Router.newBuilder().build())).setIsOptional(true).build()); FilterChainMatch filterChainMatch2 = FilterChainMatch.newBuilder() .addAllSourcePorts(Arrays.asList(443, 8080)) .addAllPrefixRanges(Arrays.asList( CidrRange.newBuilder().setAddressPrefix("2001:DB8::8:800:200C:417A") .setPrefixLen(UInt32Value.of(60)).build(), CidrRange.newBuilder().setAddressPrefix("192.168.0.0") .setPrefixLen(UInt32Value.of(16)).build())) .setSourceType(FilterChainMatch.ConnectionSourceType.ANY) .build(); FilterChain filterChain2 = FilterChain.newBuilder() .setName("filter-chain-2") .setFilterChainMatch(filterChainMatch2) .addFilters(filter2) .build(); Listener listener = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .addAllFilterChains(Arrays.asList(filterChain1, filterChain2)) .build(); XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)); } @Test public void parseFilterChain_noHcm() throws ResourceInvalidException { FilterChain filterChain = FilterChain.newBuilder() .setName("filter-chain-foo") .setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseFilterChain( filterChain, "filter-chain-foo", null, filterRegistry, null, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat().isEqualTo( "FilterChain filter-chain-foo should contain exact one HttpConnectionManager filter"); } @Test public void parseFilterChain_duplicateFilter() throws ResourceInvalidException { Filter filter = buildHttpConnectionManagerFilter( HttpFilter.newBuilder().setName("http-filter-foo").setIsOptional(true).build()); FilterChain filterChain = FilterChain.newBuilder() .setName("filter-chain-foo") .setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance()) .addAllFilters(Arrays.asList(filter, filter)) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseFilterChain( filterChain, "filter-chain-foo", null, filterRegistry, null, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat().isEqualTo( "FilterChain filter-chain-foo should contain exact one HttpConnectionManager filter"); } @Test public void parseFilterChain_filterMissingTypedConfig() throws ResourceInvalidException { Filter filter = Filter.newBuilder().setName("envoy.http_connection_manager").build(); FilterChain filterChain = FilterChain.newBuilder() .setName("filter-chain-foo") .setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance()) .addFilters(filter) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseFilterChain( filterChain, "filter-chain-foo", null, filterRegistry, null, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat().isEqualTo( "FilterChain filter-chain-foo contains filter envoy.http_connection_manager " + "without typed_config"); } @Test public void parseFilterChain_unsupportedFilter() throws ResourceInvalidException { Filter filter = Filter.newBuilder() .setName("unsupported") .setTypedConfig(Any.newBuilder().setTypeUrl("unsupported-type-url")) .build(); FilterChain filterChain = FilterChain.newBuilder() .setName("filter-chain-foo") .setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance()) .addFilters(filter) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseFilterChain( filterChain, "filter-chain-foo", null, filterRegistry, null, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat().isEqualTo( "FilterChain filter-chain-foo contains filter unsupported with unsupported " + "typed_config type unsupported-type-url"); } @Test public void parseFilterChain_noName() throws ResourceInvalidException { FilterChain filterChain0 = FilterChain.newBuilder() .setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .addFilters(buildHttpConnectionManagerFilter( HttpFilter.newBuilder() .setName("http-filter-foo") .setIsOptional(true) .setTypedConfig(Any.pack(Router.newBuilder().build())) .build())) .build(); FilterChain filterChain1 = FilterChain.newBuilder() .setFilterChainMatch( FilterChainMatch.newBuilder().addAllSourcePorts(Arrays.asList(443, 8080))) .addFilters(buildHttpConnectionManagerFilter( HttpFilter.newBuilder() .setName("http-filter-bar") .setTypedConfig(Any.pack(Router.newBuilder().build())) .setIsOptional(true) .build())) .build(); Listener listenerProto = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .addAllFilterChains(Arrays.asList(filterChain0, filterChain1)) .setDefaultFilterChain(filterChain0) .build(); EnvoyServerProtoData.Listener listener = XdsListenerResource.parseServerSideListener( listenerProto, null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(listener.filterChains().get(0).name()).isEqualTo("chain_0"); assertThat(listener.filterChains().get(1).name()).isEqualTo("chain_1"); assertThat(listener.defaultFilterChain().name()).isEqualTo("chain_default"); } @Test public void parseFilterChain_duplicateName() throws ResourceInvalidException { FilterChain filterChain0 = FilterChain.newBuilder() .setName("filter_chain") .setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .addFilters(buildHttpConnectionManagerFilter( HttpFilter.newBuilder() .setName("http-filter-foo") .setIsOptional(true) .setTypedConfig(Any.pack(Router.newBuilder().build())) .build())) .build(); FilterChain filterChain1 = FilterChain.newBuilder() .setName("filter_chain") .setFilterChainMatch( FilterChainMatch.newBuilder().addAllSourcePorts(Arrays.asList(443, 8080))) .addFilters(buildHttpConnectionManagerFilter( HttpFilter.newBuilder() .setName("http-filter-bar") .setTypedConfig(Any.pack(Router.newBuilder().build())) .setIsOptional(true) .build())) .build(); Listener listenerProto = Listener.newBuilder() .setName("listener1") .setTrafficDirection(TrafficDirection.INBOUND) .addAllFilterChains(Arrays.asList(filterChain0, filterChain1)) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.parseServerSideListener( listenerProto, null, filterRegistry, null, getXdsResourceTypeArgs(true))); assertThat(e).hasMessageThat() .isEqualTo("Filter chain names must be unique. Found duplicate: filter_chain"); } @Test public void validateCommonTlsContext_tlsParams() { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setTlsParams(TlsParameters.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo("common-tls-context with tls_params is not supported"); } @Test public void validateCommonTlsContext_customHandshaker() { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCustomHandshaker(TypedExtensionConfig.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo( "common-tls-context with custom_handshaker is not supported"); } @Test public void validateCommonTlsContext_validationContext() { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setValidationContext(CertificateValidationContext.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo( "ca_certificate_provider_instance or system_root_certs is required " + "in upstream-tls-context"); } @Test public void validateCommonTlsContext_validationContextSdsSecretConfig() { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setValidationContextSdsSecretConfig(SdsSecretConfig.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo( "common-tls-context with validation_context_sds_secret_config is not supported"); } @Test public void validateCommonTlsContext_tlsCertificateProviderInstance_isRequiredForServer() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, true)); assertThat(e).hasMessageThat().isEqualTo( "tls_certificate_provider_instance is required in downstream-tls-context"); } @Test public void validateCommonTlsContext_tlsNewCertificateProviderInstance() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setTlsCertificateProviderInstance( CertificateProviderPluginInstance.newBuilder().setInstanceName("name1")) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), true); } @Test @SuppressWarnings("deprecation") public void validateCommonTlsContext_tlsDeprecatedCertificateProviderInstance() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setTlsCertificateCertificateProviderInstance( CommonTlsContext.CertificateProviderInstance.newBuilder().setInstanceName("name1")) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), true); } @Test public void validateCommonTlsContext_tlsCertificateProviderInstance() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setTlsCertificateProviderInstance( CertificateProviderPluginInstance.newBuilder().setInstanceName("name1")) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), true); } @Test public void validateCommonTlsContext_tlsCertificateProviderInstance_absentInBootstrapFile() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setTlsCertificateProviderInstance( CertificateProviderPluginInstance.newBuilder().setInstanceName("bad-name")) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), true)); assertThat(e).hasMessageThat().isEqualTo( "CertificateProvider instance name 'bad-name' not defined in the bootstrap file."); } @Test public void validateCommonTlsContext_validationContextProviderInstance() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance(CertificateProviderPluginInstance.newBuilder() .setInstanceName("name1")))) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), false); } @Test public void validateCommonTlsContext_combinedValidationContextSystemRootCerts_envVarNotSet_throws() { XdsClusterResource.enableSystemRootCerts = false; CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext( CertificateValidationContext.newBuilder() .setSystemRootCerts( CertificateValidationContext.SystemRootCerts.newBuilder().build()) .build() ) .build()) .build(); try { XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of(), false); fail("Expected exception"); } catch (ResourceInvalidException ex) { assertThat(ex.getMessage()).isEqualTo( "ca_certificate_provider_instance or system_root_certs is required in" + " upstream-tls-context"); } } @Test public void validateCommonTlsContext_combinedValidationContextSystemRootCerts() throws ResourceInvalidException { XdsClusterResource.enableSystemRootCerts = true; CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext( CertificateValidationContext.newBuilder() .setSystemRootCerts( CertificateValidationContext.SystemRootCerts.newBuilder().build()) .build() ) .build()) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of(), false); } @Test @SuppressWarnings("deprecation") public void validateCommonTlsContext_combinedValidationContextDeprecatedCertProvider() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setTlsCertificateProviderInstance( CertificateProviderPluginInstance.newBuilder().setInstanceName("cert1")) .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setValidationContextCertificateProviderInstance( CommonTlsContext.CertificateProviderInstance.newBuilder() .setInstanceName("root1")) .build()) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of("cert1", "root1"), true); } @Test public void validateCommonTlsContext_validationContextSystemRootCerts_envVarNotSet_throws() { XdsClusterResource.enableSystemRootCerts = false; CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setValidationContext( CertificateValidationContext.newBuilder() .setSystemRootCerts( CertificateValidationContext.SystemRootCerts.newBuilder().build()) .build()) .build(); try { XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of(), false); fail("Expected exception"); } catch (ResourceInvalidException ex) { assertThat(ex.getMessage()).isEqualTo( "ca_certificate_provider_instance or system_root_certs is required in " + "upstream-tls-context"); } } @Test public void validateCommonTlsContext_validationContextSystemRootCerts() throws ResourceInvalidException { XdsClusterResource.enableSystemRootCerts = true; CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setValidationContext( CertificateValidationContext.newBuilder() .setSystemRootCerts( CertificateValidationContext.SystemRootCerts.newBuilder().build()) .build()) .build(); XdsClusterResource .validateCommonTlsContext(commonTlsContext, ImmutableSet.of(), false); } @Test public void validateCommonTlsContext_validationContextProviderInstance_absentInBootstrapFile() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance(CertificateProviderPluginInstance.newBuilder() .setInstanceName("bad-name")))) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), false)); assertThat(e).hasMessageThat().isEqualTo( "ca_certificate_provider_instance name 'bad-name' not defined in the bootstrap file."); } @Test public void validateCommonTlsContext_tlsCertificatesCount() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .addTlsCertificates(TlsCertificate.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo("tls_certificate_provider_instance is unset"); } @Test public void validateCommonTlsContext_tlsCertificateSdsSecretConfigsCount() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .addTlsCertificateSdsSecretConfigs(SdsSecretConfig.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo( "tls_certificate_provider_instance is unset"); } @Test public void validateCommonTlsContext_combinedValidationContext_isRequiredForClient() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo( "ca_certificate_provider_instance or system_root_certs is required " + "in upstream-tls-context"); } @Test public void validateCommonTlsContext_combinedValidationContextWithoutCertProviderInstance() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false)); assertThat(e).hasMessageThat().isEqualTo( "ca_certificate_provider_instance or system_root_certs is required in " + "upstream-tls-context"); } @Test @SuppressWarnings("deprecation") public void validateCommonTlsContext_combinedValContextWithDefaultValContextForServer() throws ResourceInvalidException, InvalidProtocolBufferException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .addMatchSubjectAltNames(StringMatcher.newBuilder().setExact("foo.com").build()) .build())) .setTlsCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), true)); assertThat(e).hasMessageThat().isEqualTo( "match_subject_alt_names only allowed in upstream_tls_context"); } @Test public void validateCommonTlsContext_combinedValContextWithDefaultValContextVerifyCertSpki() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .addVerifyCertificateSpki("foo"))) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false)); assertThat(e).hasMessageThat().isEqualTo( "verify_certificate_spki in default_validation_context is not supported"); } @Test public void validateCommonTlsContext_combinedValContextWithDefaultValContextVerifyCertHash() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .addVerifyCertificateHash("foo"))) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false)); assertThat(e).hasMessageThat().isEqualTo( "verify_certificate_hash in default_validation_context is not supported"); } @Test public void validateCommonTlsContext_combinedValContextDfltValContextRequireSignedCertTimestamp() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .setRequireSignedCertificateTimestamp(BoolValue.of(true)))) .setTlsCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false)); assertThat(e).hasMessageThat().isEqualTo( "require_signed_certificate_timestamp in default_validation_context is not " + "supported"); } @Test public void validateCommonTlsContext_combinedValidationContextWithDefaultValidationContextCrl() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .setCrl(DataSource.getDefaultInstance()))) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false)); assertThat(e).hasMessageThat().isEqualTo("crl in default_validation_context is not supported"); } @Test public void validateCommonTlsContext_combinedValContextWithDfltValContextCustomValidatorConfig() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()) .setCustomValidatorConfig(TypedExtensionConfig.getDefaultInstance()))) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false)); assertThat(e).hasMessageThat().isEqualTo( "custom_validator_config in default_validation_context is not supported"); } @Test public void validateDownstreamTlsContext_noCommonTlsContext() throws ResourceInvalidException { DownstreamTlsContext downstreamTlsContext = DownstreamTlsContext.getDefaultInstance(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, null)); assertThat(e).hasMessageThat().isEqualTo( "common-tls-context is required in downstream-tls-context"); } @Test public void validateDownstreamTlsContext_hasRequireSni() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()))) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .build(); DownstreamTlsContext downstreamTlsContext = DownstreamTlsContext.newBuilder() .setCommonTlsContext(commonTlsContext) .setRequireSni(BoolValue.of(true)) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, ImmutableSet.of(""))); assertThat(e).hasMessageThat().isEqualTo( "downstream-tls-context with require-sni is not supported"); } @Test public void validateDownstreamTlsContext_hasOcspStaplePolicy() throws ResourceInvalidException { CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() .setCombinedValidationContext( CommonTlsContext.CombinedCertificateValidationContext.newBuilder() .setDefaultValidationContext(CertificateValidationContext.newBuilder() .setCaCertificateProviderInstance( CertificateProviderPluginInstance.getDefaultInstance()))) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .build(); DownstreamTlsContext downstreamTlsContext = DownstreamTlsContext.newBuilder() .setCommonTlsContext(commonTlsContext) .setOcspStaplePolicy(DownstreamTlsContext.OcspStaplePolicy.STRICT_STAPLING) .build(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, ImmutableSet.of(""))); assertThat(e).hasMessageThat().isEqualTo( "downstream-tls-context with ocsp_staple_policy value STRICT_STAPLING is not supported"); } @Test public void validateUpstreamTlsContext_noCommonTlsContext() throws ResourceInvalidException { UpstreamTlsContext upstreamTlsContext = UpstreamTlsContext.getDefaultInstance(); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () -> XdsClusterResource.validateUpstreamTlsContext(upstreamTlsContext, null)); assertThat(e).hasMessageThat().isEqualTo( "common-tls-context is required in upstream-tls-context"); } @Test public void validateResourceName() { String traditionalResource = "cluster1.google.com"; assertThat(XdsClient.isResourceNameValid(traditionalResource, XdsClusterResource.getInstance().typeUrl())) .isTrue(); String invalidPath = "xdstp:/abc/efg"; assertThat(XdsClient.isResourceNameValid(invalidPath, XdsClusterResource.getInstance().typeUrl())).isFalse(); String invalidPath2 = "xdstp:///envoy.config.route.v3.RouteConfiguration"; assertThat(XdsClient.isResourceNameValid(invalidPath2, XdsRouteConfigureResource.getInstance().typeUrl())).isFalse(); String typeMatch = "xdstp:///envoy.config.route.v3.RouteConfiguration/foo/route1"; assertThat(XdsClient.isResourceNameValid(typeMatch, XdsListenerResource.getInstance().typeUrl())).isFalse(); assertThat(XdsClient.isResourceNameValid(typeMatch, XdsRouteConfigureResource.getInstance().typeUrl())).isTrue(); } @Test public void canonifyResourceName() { String traditionalResource = "cluster1.google.com"; assertThat(XdsClient.canonifyResourceName(traditionalResource)) .isEqualTo(traditionalResource); assertThat(XdsClient.canonifyResourceName(traditionalResource)) .isEqualTo(traditionalResource); assertThat(XdsClient.canonifyResourceName(traditionalResource)) .isEqualTo(traditionalResource); assertThat(XdsClient.canonifyResourceName(traditionalResource)) .isEqualTo(traditionalResource); String withNoQueries = "xdstp:///envoy.config.route.v3.RouteConfiguration/foo/route1"; assertThat(XdsClient.canonifyResourceName(withNoQueries)).isEqualTo(withNoQueries); String withOneQueries = "xdstp:///envoy.config.route.v3.RouteConfiguration/foo/route1?name=foo"; assertThat(XdsClient.canonifyResourceName(withOneQueries)).isEqualTo(withOneQueries); String withTwoQueries = "xdstp:///envoy.config.route.v3.RouteConfiguration/id/route1?b=1&a=1"; String expectedCanonifiedName = "xdstp:///envoy.config.route.v3.RouteConfiguration/id/route1?a=1&b=1"; assertThat(XdsClient.canonifyResourceName(withTwoQueries)) .isEqualTo(expectedCanonifiedName); } /** * Tests compliance with RFC 3986 section 3.3 * https://datatracker.ietf.org/doc/html/rfc3986#section-3.3 . */ @Test public void percentEncodePath() { String unreserved = "aAzZ09-._~"; assertThat(XdsClient.percentEncodePath(unreserved)).isEqualTo(unreserved); String subDelims = "!$&'(*+,;/="; assertThat(XdsClient.percentEncodePath(subDelims)).isEqualTo(subDelims); String colonAndAt = ":@"; assertThat(XdsClient.percentEncodePath(colonAndAt)).isEqualTo(colonAndAt); String needBeEncoded = "?#[]"; assertThat(XdsClient.percentEncodePath(needBeEncoded)).isEqualTo("%3F%23%5B%5D"); String ipv4 = "0.0.0.0:8080"; assertThat(XdsClient.percentEncodePath(ipv4)).isEqualTo(ipv4); String ipv6 = "[::1]:8080"; assertThat(XdsClient.percentEncodePath(ipv6)).isEqualTo("%5B::1%5D:8080"); } private static Filter buildHttpConnectionManagerFilter(HttpFilter... httpFilters) { return Filter.newBuilder() .setName("envoy.http_connection_manager") .setTypedConfig( Any.pack( HttpConnectionManager.newBuilder() .setRds( Rds.newBuilder() .setRouteConfigName("route-config.googleapis.com") .setConfigSource( ConfigSource.newBuilder() .setAds(AggregatedConfigSource.getDefaultInstance()))) .addAllHttpFilters(Arrays.asList(httpFilters)) .build(), "type.googleapis.com")) .build(); } private XdsResourceType.Args getXdsResourceTypeArgs(boolean isTrustedServer) { return new XdsResourceType.Args( ServerInfo.create("http://td", "", false, isTrustedServer, false), "1.0", null, null, null, null ); } }
TestPluginConfig
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonDequeTest.java
{ "start": 364, "end": 6378 }
class ____ extends RedisDockerTest { @Test public void testAddIfExists() { RDeque<Integer> deque1 = redisson.getDeque("deque1"); deque1.add(1); deque1.add(2); deque1.add(3); deque1.addFirstIfExists(4, 5); assertThat(deque1).containsExactly(5, 4, 1, 2, 3); } @Test public void testMove() { RDeque<Integer> deque1 = redisson.getDeque("deque1"); RDeque<Integer> deque2 = redisson.getDeque("deque2"); deque1.add(1); deque1.add(2); deque1.add(3); deque2.add(4); deque2.add(5); deque2.add(6); Integer r1 = deque1.move(DequeMoveArgs.pollFirst().addLastTo(deque2.getName())); assertThat(r1).isEqualTo(1); assertThat(deque1).containsExactly(2, 3); assertThat(deque2).containsExactly(4, 5, 6, 1); Integer r2 = deque2.move(DequeMoveArgs.pollLast().addFirstTo(deque1.getName())); assertThat(r2).isEqualTo(1); assertThat(deque1).containsExactly(1, 2, 3); assertThat(deque2).containsExactly(4, 5, 6); } @Test public void testRemoveLastOccurrence() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); queue1.addFirst(3); queue1.addFirst(1); queue1.addFirst(2); queue1.addFirst(3); queue1.removeLastOccurrence(3); assertThat(queue1).containsExactly(3, 2, 1); } @Test public void testRemoveFirstOccurrence() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); queue1.addFirst(3); queue1.addFirst(1); queue1.addFirst(2); queue1.addFirst(3); queue1.removeFirstOccurrence(3); assertThat(queue1).containsExactly(2, 1, 3); } @Test public void testRemoveLast() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); queue1.addFirst(1); queue1.addFirst(2); queue1.addFirst(3); Assertions.assertEquals(1, (int)queue1.removeLast()); Assertions.assertEquals(2, (int)queue1.removeLast()); Assertions.assertEquals(3, (int)queue1.removeLast()); } @Test public void testRemoveFirst() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); queue1.addFirst(1); queue1.addFirst(2); queue1.addFirst(3); Assertions.assertEquals(3, (int)queue1.removeFirst()); Assertions.assertEquals(2, (int)queue1.removeFirst()); Assertions.assertEquals(1, (int)queue1.removeFirst()); } @Test public void testPeek() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); Assertions.assertNull(queue1.peekFirst()); Assertions.assertNull(queue1.peekLast()); queue1.addFirst(2); Assertions.assertEquals(2, (int)queue1.peekFirst()); Assertions.assertEquals(2, (int)queue1.peekLast()); } @Test public void testPollLastAndOfferFirstTo() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); queue1.addFirst(3); queue1.addFirst(2); queue1.addFirst(1); RDeque<Integer> queue2 = redisson.getDeque("deque2"); queue2.addFirst(6); queue2.addFirst(5); queue2.addFirst(4); queue1.pollLastAndOfferFirstTo(queue2.getName()); assertThat(queue2).containsExactly(3, 4, 5, 6); } @Test public void testAddFirstOrigin() { Deque<Integer> queue = new ArrayDeque<Integer>(); queue.addFirst(1); queue.addFirst(2); queue.addFirst(3); assertThat(queue).containsExactly(3, 2, 1); } @Test public void testAddFirstLastMulti() { RDeque<Integer> queue = redisson.getDeque("deque"); queue.addAll(Arrays.asList(1, 2, 3, 4)); queue.addFirst(0, 1, 0); queue.addLast(10, 20, 10); assertThat(queue).containsExactly(0, 1, 0, 1, 2, 3, 4, 10, 20, 10); } @Test public void testAddFirst() { RDeque<Integer> queue = redisson.getDeque("deque"); queue.addFirst(1); queue.addFirst(2); queue.addFirst(3); assertThat(queue).containsExactly(3, 2, 1); } @Test public void testAddLastOrigin() { Deque<Integer> queue = new ArrayDeque<Integer>(); queue.addLast(1); queue.addLast(2); queue.addLast(3); assertThat(queue).containsExactly(1, 2, 3); } @Test public void testAddLast() { RDeque<Integer> queue = redisson.getDeque("deque"); queue.addLast(1); queue.addLast(2); queue.addLast(3); assertThat(queue).containsExactly(1, 2, 3); } @Test public void testOfferFirstOrigin() { Deque<Integer> queue = new ArrayDeque<Integer>(); queue.offerFirst(1); queue.offerFirst(2); queue.offerFirst(3); assertThat(queue).containsExactly(3, 2, 1); } @Test public void testOfferFirst() { RDeque<Integer> queue = redisson.getDeque("deque"); queue.offerFirst(1); queue.offerFirst(2); queue.offerFirst(3); assertThat(queue).containsExactly(3, 2, 1); } @Test public void testOfferLastOrigin() { Deque<Integer> queue = new ArrayDeque<Integer>(); queue.offerLast(1); queue.offerLast(2); queue.offerLast(3); assertThat(queue).containsExactly(1, 2, 3); Assertions.assertEquals((Integer)1, queue.poll()); } @Test public void testDescendingIteratorOrigin() { final Deque<Integer> queue = new ArrayDeque<Integer>(); queue.addAll(Arrays.asList(1, 2, 3)); assertThat(queue.descendingIterator()).toIterable().containsExactly(3, 2, 1); } @Test public void testDescendingIterator() { final RDeque<Integer> queue = redisson.getDeque("deque"); queue.addAll(Arrays.asList(1, 2, 3)); assertThat(queue.descendingIterator()).toIterable().containsExactly(3, 2, 1); } }
RedissonDequeTest
java
apache__camel
components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/internal/BoxCollaborationsManagerApiMethod.java
{ "start": 683, "end": 2803 }
enum ____ implements ApiMethod { ADD_FOLDER_COLLABORATION( com.box.sdk.BoxCollaboration.class, "addFolderCollaboration", arg("folderId", String.class), arg("collaborator", com.box.sdk.BoxCollaborator.class), arg("role", com.box.sdk.BoxCollaboration.Role.class)), ADD_FOLDER_COLLABORATION_BY_EMAIL( com.box.sdk.BoxCollaboration.class, "addFolderCollaborationByEmail", arg("folderId", String.class), arg("email", String.class), arg("role", com.box.sdk.BoxCollaboration.Role.class)), DELETE_COLLABORATION( void.class, "deleteCollaboration", arg("collaborationId", String.class)), GET_COLLABORATION_INFO( com.box.sdk.BoxCollaboration.Info.class, "getCollaborationInfo", arg("collaborationId", String.class)), GET_FOLDER_COLLABORATIONS( java.util.Collection.class, "getFolderCollaborations", arg("folderId", String.class)), GET_PENDING_COLLABORATIONS( java.util.Collection.class, "getPendingCollaborations"), UPDATE_COLLABORATION_INFO( com.box.sdk.BoxCollaboration.class, "updateCollaborationInfo", arg("collaborationId", String.class), arg("info", com.box.sdk.BoxCollaboration.Info.class)); private final ApiMethod apiMethod; BoxCollaborationsManagerApiMethod(Class<?> resultType, String name, ApiMethodArg... args) { this.apiMethod = new ApiMethodImpl(BoxCollaborationsManager.class, resultType, name, args); } @Override public String getName() { return apiMethod.getName(); } @Override public Class<?> getResultType() { return apiMethod.getResultType(); } @Override public List<String> getArgNames() { return apiMethod.getArgNames(); } @Override public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); } @Override public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); } @Override public Method getMethod() { return apiMethod.getMethod(); } }
BoxCollaborationsManagerApiMethod
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/secured/JwtResponseParser.java
{ "start": 1129, "end": 2585 }
class ____ { private static final String[] JSON_PATHS = new String[] {"/access_token", "/id_token"}; private static final int MAX_RESPONSE_BODY_LENGTH = 1000; public String parseJwt(String responseBody) throws JwtRetrieverException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = mapper.readTree(responseBody); } catch (IOException e) { throw new JwtRetrieverException(e); } for (String jsonPath : JSON_PATHS) { JsonNode node = rootNode.at(jsonPath); if (node != null && !node.isMissingNode()) { String value = node.textValue(); if (!Utils.isBlank(value)) { return value.trim(); } } } // Only grab the first N characters so that if the response body is huge, we don't blow up. String snippet = responseBody; if (snippet.length() > MAX_RESPONSE_BODY_LENGTH) { int actualLength = responseBody.length(); String s = responseBody.substring(0, MAX_RESPONSE_BODY_LENGTH); snippet = String.format("%s (trimmed to first %d characters out of %d total)", s, MAX_RESPONSE_BODY_LENGTH, actualLength); } throw new JwtRetrieverException(String.format("The token endpoint response did not contain a valid JWT. Response: (%s)", snippet)); } }
JwtResponseParser
java
quarkusio__quarkus
extensions/cache/runtime/src/main/java/io/quarkus/cache/runtime/CacheInvalidateAllInterceptor.java
{ "start": 593, "end": 3855 }
class ____ extends CacheInterceptor { private static final Logger LOGGER = Logger.getLogger(CacheInvalidateAllInterceptor.class); private static final String INTERCEPTOR_BINDINGS_ERROR_MSG = "The Quarkus cache extension is not working properly (CacheInvalidateAll interceptor bindings retrieval failed), please create a GitHub issue in the Quarkus repository to help the maintainers fix this bug"; @AroundInvoke public Object intercept(InvocationContext invocationContext) throws Exception { CacheInterceptionContext<CacheInvalidateAll> interceptionContext = getInterceptionContext(invocationContext, CacheInvalidateAll.class, false); if (interceptionContext.getInterceptorBindings().isEmpty()) { // This should never happen. LOGGER.warn(INTERCEPTOR_BINDINGS_ERROR_MSG); return invocationContext.proceed(); } ReturnType returnType = determineReturnType(invocationContext.getMethod().getReturnType()); if (returnType == ReturnType.NonAsync) { return invalidateAllBlocking(invocationContext, interceptionContext); } else { return invalidateAllNonBlocking(invocationContext, interceptionContext, returnType); } } private Object invalidateAllNonBlocking(InvocationContext invocationContext, CacheInterceptionContext<CacheInvalidateAll> interceptionContext, ReturnType returnType) { LOGGER.trace("Invalidating all cache entries in a non-blocking way"); var uni = Multi.createFrom().iterable(interceptionContext.getInterceptorBindings()) .onItem().transformToUniAndMerge(new Function<CacheInvalidateAll, Uni<? extends Void>>() { @Override public Uni<Void> apply(CacheInvalidateAll binding) { return invalidateAll(binding); } }) .onItem().ignoreAsUni() .onItem().transformToUni(new Function<Object, Uni<?>>() { @Override public Uni<?> apply(Object ignored) { try { return asyncInvocationResultToUni(invocationContext.proceed(), returnType); } catch (Exception e) { throw new CacheException(e); } } }); return createAsyncResult(uni, returnType); } private Object invalidateAllBlocking(InvocationContext invocationContext, CacheInterceptionContext<CacheInvalidateAll> interceptionContext) throws Exception { LOGGER.trace("Invalidating all cache entries in a blocking way"); for (CacheInvalidateAll binding : interceptionContext.getInterceptorBindings()) { invalidateAll(binding).await().indefinitely(); } return invocationContext.proceed(); } private Uni<Void> invalidateAll(CacheInvalidateAll binding) { Cache cache = cacheManager.getCache(binding.cacheName()).get(); LOGGER.debugf("Invalidating all entries from cache [%s]", binding.cacheName()); return cache.invalidateAll(); } }
CacheInvalidateAllInterceptor
java
quarkusio__quarkus
integration-tests/logging-min-level-set/src/test/java/io/quarkus/it/logging/minlevel/set/SetRuntimeLogLevels.java
{ "start": 175, "end": 1046 }
class ____ implements QuarkusTestResourceLifecycleManager { @Override public Map<String, String> start() { final Map<String, String> systemProperties = new HashMap<>(); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.set.bydefault\".level", "DEBUG"); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.set.above\".level", "WARN"); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.set.below\".level", "TRACE"); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.set.below.child\".level", "inherit"); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.set.promote\".level", "INFO"); return systemProperties; } @Override public void stop() { } }
SetRuntimeLogLevels
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/Action.java
{ "start": 2689, "end": 2907 }
class ____ extends StoppedResult { public Failure(String type, String reason, Object... args) { super(type, Status.FAILURE, reason, args); } } public static
Failure
java
apache__flink
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/rest/DeployScriptITCase.java
{ "start": 3499, "end": 8434 }
class ____ { @RegisterExtension @Order(1) public static final SqlGatewayServiceExtension SQL_GATEWAY_SERVICE_EXTENSION = new SqlGatewayServiceExtension(Configuration::new); @RegisterExtension @Order(2) private static final SqlGatewayRestEndpointExtension SQL_GATEWAY_REST_ENDPOINT_EXTENSION = new SqlGatewayRestEndpointExtension(SQL_GATEWAY_SERVICE_EXTENSION::getService); private static TestingRestClient restClient; private static SessionHandle sessionHandle; private static final String script = "CREATE TEMPORARY TABLE sink(\n" + " a INT\n" + ") WITH (\n" + " 'connector' = 'blackhole'\n" + ");\n" + "INSERT INTO sink VALUES (1);"; @BeforeAll static void beforeAll() throws Exception { restClient = TestingRestClient.getTestingRestClient(); sessionHandle = new SessionHandle( UUID.fromString( restClient .sendRequest( SQL_GATEWAY_REST_ENDPOINT_EXTENSION .getTargetAddress(), SQL_GATEWAY_REST_ENDPOINT_EXTENSION.getTargetPort(), OpenSessionHeaders.getInstance(), EmptyMessageParameters.getInstance(), new OpenSessionRequestBody( "test", Collections.singletonMap("key", "value"))) .get() .getSessionHandle())); } @Test void testDeployScriptToYarnCluster(@TempDir Path workDir) throws Exception { verifyDeployScriptToCluster("yarn-application", script, null, script); try (MockHttpServer server = MockHttpServer.startHttpServer()) { File file = workDir.resolve("script.sql").toFile(); assertThat(file.createNewFile()).isTrue(); FileUtils.writeFileUtf8(file, script); URL url = server.prepareResource("/download/script.sql", file); verifyDeployScriptToCluster("yarn-application", null, url.toString(), script); } } @Test void testDeployScriptToKubernetesCluster(@TempDir Path workDir) throws Exception { verifyDeployScriptToCluster("kubernetes-application", script, null, script); try (MockHttpServer server = MockHttpServer.startHttpServer()) { File file = workDir.resolve("script.sql").toFile(); assertThat(file.createNewFile()).isTrue(); FileUtils.writeFileUtf8(file, script); URL url = server.prepareResource("/download/script.sql", file); verifyDeployScriptToCluster("kubernetes-application", null, url.toString(), script); } } private void verifyDeployScriptToCluster( String target, @Nullable String script, @Nullable String scriptUri, String content) throws Exception { TestApplicationClusterClientFactory.id = target; assertThat( restClient .sendRequest( SQL_GATEWAY_REST_ENDPOINT_EXTENSION.getTargetAddress(), SQL_GATEWAY_REST_ENDPOINT_EXTENSION.getTargetPort(), DeployScriptHeaders.getInstance(), new SessionMessageParameters(sessionHandle), new DeployScriptRequestBody( script, scriptUri, Collections.singletonMap( DeploymentOptions.TARGET.key(), target))) .get() .getClusterID()) .isEqualTo("test"); ApplicationConfiguration config = TestApplicationClusterDescriptor.applicationConfiguration; assertThat(TestApplicationClusterClientFactory.configuration.getString("key", "none")) .isEqualTo("value"); assertThat(config.getApplicationClassName()).isEqualTo(SqlDriver.class.getName()); assertThat(SqlDriver.parseOptions(config.getProgramArguments())).isEqualTo(content); } /** * Test {@link ClusterClientFactory} to capture {@link Configuration} and {@link * ApplicationConfiguration}. */ @SuppressWarnings({"unchecked", "rawTypes"}) public static
DeployScriptITCase
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdate/LocalDateAssert_hasMonth_Test.java
{ "start": 1074, "end": 1955 }
class ____ { @Test void should_pass_if_actual_is_in_given_month() { // GIVEN LocalDate actual = LocalDate.of(2021, 2, 22); // WHEN/THEN then(actual).hasMonth(Month.FEBRUARY); } @Test void should_fail_if_actual_is_not_in_given_month() { // GIVEN LocalDate actual = LocalDate.of(2022, 1, 1); Month wrongMonth = Month.DECEMBER; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasMonth(wrongMonth)); // THEN then(assertionError).hasMessage(shouldHaveMonth(actual, wrongMonth).create()); } @Test void should_fail_if_actual_is_null() { // GIVEN LocalDate actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasMonth(LocalDate.now().getMonth())); // THEN then(assertionError).hasMessage(actualIsNull()); } }
LocalDateAssert_hasMonth_Test
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecSinkITCase.java
{ "start": 31231, "end": 31648 }
class ____ extends TestSinkV2.DefaultSinkWriter<RowData> { private final SharedReference<List<RowData>> rows; private RecordWriter(SharedReference<List<RowData>> rows) { this.rows = rows; } @Override public void write(RowData element, Context context) { addElement(rows, element); super.write(element, context); } } }
RecordWriter
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/GeoPointFieldMapper.java
{ "start": 16135, "end": 25283 }
class ____ extends AbstractPointFieldType<GeoPoint> implements GeoShapeQueryable { private final TimeSeriesParams.MetricType metricType; public static final GeoFormatterFactory<GeoPoint> GEO_FORMATTER_FACTORY = new GeoFormatterFactory<>( List.of(new SimpleVectorTileFormatter()) ); private final FieldValues<GeoPoint> scriptValues; private final IndexMode indexMode; private final boolean isSyntheticSource; GeoPointFieldType( String name, IndexType indexType, boolean stored, Parser<GeoPoint> parser, GeoPoint nullValue, FieldValues<GeoPoint> scriptValues, Map<String, String> meta, TimeSeriesParams.MetricType metricType, IndexMode indexMode, boolean isSyntheticSource ) { super(name, indexType, stored, parser, nullValue, meta); this.scriptValues = scriptValues; this.metricType = metricType; this.indexMode = indexMode; this.isSyntheticSource = isSyntheticSource; } // only used in test public GeoPointFieldType(String name, TimeSeriesParams.MetricType metricType, IndexMode indexMode) { this(name, IndexType.points(true, true), false, null, null, null, Collections.emptyMap(), metricType, indexMode, false); } // only used in test public GeoPointFieldType(String name) { this(name, null, null); } @Override public String typeName() { return CONTENT_TYPE; } @Override public boolean isSearchable() { return indexType.hasPoints() || hasDocValues(); } @Override protected Function<List<GeoPoint>, List<Object>> getFormatter(String format) { return GEO_FORMATTER_FACTORY.getFormatter(format, p -> new Point(p.getLon(), p.getLat())); } @Override public ValueFetcher valueFetcher(SearchExecutionContext context, String format) { if (scriptValues == null) { return super.valueFetcher(context, format); } Function<List<GeoPoint>, List<Object>> formatter = getFormatter(format != null ? format : GeometryFormatterFactory.GEOJSON); return FieldValues.valueListFetcher(scriptValues, formatter, context); } @Override public Query geoShapeQuery(SearchExecutionContext context, String fieldName, ShapeRelation relation, LatLonGeometry... geometries) { failIfNotIndexedNorDocValuesFallback(context); final ShapeField.QueryRelation luceneRelation; if (relation == ShapeRelation.INTERSECTS && isPointGeometry(geometries)) { // For point queries and intersects, lucene does not match points that are encoded // to Integer.MAX_VALUE because the use of ComponentPredicate for speeding up queries. // We use contains instead. luceneRelation = ShapeField.QueryRelation.CONTAINS; } else { luceneRelation = relation.getLuceneRelation(); } Query query; if (indexType.hasPoints()) { query = LatLonPoint.newGeometryQuery(fieldName, luceneRelation, geometries); if (hasDocValues()) { Query dvQuery = LatLonDocValuesField.newSlowGeometryQuery(fieldName, luceneRelation, geometries); query = new IndexOrDocValuesQuery(query, dvQuery); } } else { query = LatLonDocValuesField.newSlowGeometryQuery(fieldName, luceneRelation, geometries); } return query; } private static boolean isPointGeometry(LatLonGeometry[] geometries) { return geometries.length == 1 && geometries[0] instanceof org.apache.lucene.geo.Point; } @Override public IndexFieldData.Builder fielddataBuilder(FieldDataContext fieldDataContext) { FielddataOperation operation = fieldDataContext.fielddataOperation(); if (operation == FielddataOperation.SEARCH) { failIfNoDocValues(); } ValuesSourceType valuesSourceType = indexMode == IndexMode.TIME_SERIES && metricType == TimeSeriesParams.MetricType.POSITION ? TimeSeriesValuesSourceType.POSITION : CoreValuesSourceType.GEOPOINT; if ((operation == FielddataOperation.SEARCH || operation == FielddataOperation.SCRIPT) && hasDocValues()) { return new LatLonPointIndexFieldData.Builder(name(), valuesSourceType, GeoPointDocValuesField::new); } if (operation == FielddataOperation.SCRIPT) { SearchLookup searchLookup = fieldDataContext.lookupSupplier().get(); Set<String> sourcePaths = fieldDataContext.sourcePathsLookup().apply(name()); return new SourceValueFetcherMultiGeoPointIndexFieldData.Builder( name(), valuesSourceType, valueFetcher(sourcePaths, null, null, fieldDataContext.indexSettings()), searchLookup, GeoPointDocValuesField::new ); } throw new IllegalStateException("unknown field data type [" + operation.name() + "]"); } @Override public Query distanceFeatureQuery(Object origin, String pivot, SearchExecutionContext context) { failIfNotIndexedNorDocValuesFallback(context); GeoPoint originGeoPoint; if (origin instanceof GeoPoint) { originGeoPoint = (GeoPoint) origin; } else if (origin instanceof String) { originGeoPoint = GeoUtils.parseFromString((String) origin); } else { throw new IllegalArgumentException( "Illegal type [" + origin.getClass() + "] for [origin]! " + "Must be of type [geo_point] or [string] for geo_point fields!" ); } double pivotDouble = DistanceUnit.DEFAULT.parse(pivot, DistanceUnit.DEFAULT); if (indexType.hasPoints()) { // As we already apply boost in AbstractQueryBuilder::toQuery, we always passing a boost of 1.0 to distanceFeatureQuery return LatLonPoint.newDistanceFeatureQuery(name(), 1.0f, originGeoPoint.lat(), originGeoPoint.lon(), pivotDouble); } else { return new GeoPointScriptFieldDistanceFeatureQuery( new Script(""), ctx -> new SortedNumericDocValuesLongFieldScript(name(), context.lookup(), ctx), name(), originGeoPoint.lat(), originGeoPoint.lon(), pivotDouble ); } } /** * If field is a time series metric field, returns its metric type * @return the metric type or null */ @Override public TimeSeriesParams.MetricType getMetricType() { return metricType; } @Override public BlockLoader blockLoader(BlockLoaderContext blContext) { // load from doc values if (hasDocValues()) { if (blContext.fieldExtractPreference() == DOC_VALUES) { return new LongsBlockLoader(name()); } else if (blContext.fieldExtractPreference() == NONE && isSyntheticSource) { // when the preference is not explicitly set to DOC_VALUES, we expect a BytesRef -> see PlannerUtils.toElementType() return new BytesRefFromLongsBlockLoader(name()); } // if we got here, then either synthetic source is not enabled or the preference prohibits us from using doc_values } // doc_values are disabled, fallback to ignored_source, except for multi fields since then don't have fallback synthetic source if (isSyntheticSource && hasDocValues() == false && blContext.parentField(name()) == null) { return blockLoaderFromFallbackSyntheticSource(blContext); } // otherwise, load from _source (synthetic or otherwise) - very slow return blockLoaderFromSource(blContext); } } /** * This is a GeoPoint-specific block loader that helps deal with an edge case where doc_values are available, yet * FieldExtractPreference = NONE. When this happens, the BlockLoader sanity checker (see PlannerUtils.toElementType) expects a BytesRef. * This implies that we need to load the value from _source. This however is very slow, especially when synthetic source is enabled. * We're better off reading from doc_values and converting to BytesRef to satisfy the checker. This is what this block loader is for. */ static final
GeoPointFieldType
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/file/tfile/Compression.java
{ "start": 4535, "end": 5454 }
class ____ specified. Did you forget to set property " + CONF_LZO_CLASS + "?"); } InputStream bis1 = null; if (downStreamBufferSize > 0) { bis1 = new BufferedInputStream(downStream, downStreamBufferSize); } else { bis1 = downStream; } conf.setInt(IO_COMPRESSION_CODEC_LZO_BUFFERSIZE_KEY, IO_COMPRESSION_CODEC_LZO_BUFFERSIZE_DEFAULT); CompressionInputStream cis = codec.createInputStream(bis1, decompressor); BufferedInputStream bis2 = new BufferedInputStream(cis, DATA_IBUF_SIZE); return bis2; } @Override public synchronized OutputStream createCompressionStream( OutputStream downStream, Compressor compressor, int downStreamBufferSize) throws IOException { if (!isSupported()) { throw new IOException( "LZO codec
not
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMapPublisher.java
{ "start": 1063, "end": 1511 }
class ____<T, U> extends Flowable<U> { final Publisher<T> source; final Function<? super T, ? extends U> mapper; public FlowableMapPublisher(Publisher<T> source, Function<? super T, ? extends U> mapper) { this.source = source; this.mapper = mapper; } @Override protected void subscribeActual(Subscriber<? super U> s) { source.subscribe(new MapSubscriber<T, U>(s, mapper)); } }
FlowableMapPublisher
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/samesite/SetCookieHandler.java
{ "start": 309, "end": 1007 }
class ____ { public void handler(@Observes Router router) { router.route("/cookie").handler(new Handler<RoutingContext>() { @Override public void handle(RoutingContext event) { event.response().addCookie(new CookieImpl("cookie1", "value1")); event.response().addCookie(new CookieImpl("COOKIE2", "VALUE2")); event.response().addCookie(new CookieImpl("cookie3", "value3")); event.response().addCookie(new CookieImpl("COOKIE4", "VALUE4")); event.response().addCookie(new CookieImpl("foo", "foo")); event.response().end(); } }); } }
SetCookieHandler
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/bloomfilter/ES85BloomFilterPostingsFormat.java
{ "start": 2571, "end": 5442 }
class ____ extends PostingsFormat { static final String BLOOM_CODEC_NAME = "ES85BloomFilter"; static final int VERSION_START = 0; static final int VERSION_CURRENT = VERSION_START; static final String BLOOM_FILTER_META_FILE = "bfm"; static final String BLOOM_FILTER_INDEX_FILE = "bfi"; public ES85BloomFilterPostingsFormat() { super(BLOOM_CODEC_NAME); } @Override public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException { throw new UnsupportedOperationException(); } @Override public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException { return new FieldsReader(state); } @Override public String toString() { return BLOOM_CODEC_NAME; } static String metaFile(SegmentInfo si, String segmentSuffix) { return IndexFileNames.segmentFileName(si.name, segmentSuffix, BLOOM_FILTER_META_FILE); } static String indexFile(SegmentInfo si, String segmentSuffix) { return IndexFileNames.segmentFileName(si.name, segmentSuffix, BLOOM_FILTER_INDEX_FILE); } record BloomFilter(String field, long startFilePointer, int bloomFilterSize) { void writeTo(IndexOutput out, FieldInfos fieldInfos) throws IOException { out.writeVInt(fieldInfos.fieldInfo(field).number); out.writeVLong(startFilePointer); out.writeVInt(bloomFilterSize); } static BloomFilter readFrom(IndexInput in, FieldInfos fieldInfos) throws IOException { final String fieldName = fieldInfos.fieldInfo(in.readVInt()).name; final long startFilePointer = in.readVLong(); final int bloomFilterSize = in.readVInt(); return new BloomFilter(fieldName, startFilePointer, bloomFilterSize); } } record FieldsGroup(PostingsFormat postingsFormat, String suffix, List<String> fields) { void writeTo(IndexOutput out, FieldInfos fieldInfos) throws IOException { out.writeString(postingsFormat.getName()); out.writeString(suffix); out.writeVInt(fields.size()); for (String field : fields) { out.writeVInt(fieldInfos.fieldInfo(field).number); } } static FieldsGroup readFrom(IndexInput in, FieldInfos fieldInfos) throws IOException { final PostingsFormat postingsFormat = forName(in.readString()); final String suffix = in.readString(); final int numFields = in.readVInt(); final List<String> fields = new ArrayList<>(); for (int i = 0; i < numFields; i++) { fields.add(fieldInfos.fieldInfo(in.readVInt()).name); } return new FieldsGroup(postingsFormat, suffix, fields); } } static final
ES85BloomFilterPostingsFormat
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/TopFloatFloatAggregatorFunctionSupplier.java
{ "start": 652, "end": 1820 }
class ____ implements AggregatorFunctionSupplier { private final int limit; private final boolean ascending; public TopFloatFloatAggregatorFunctionSupplier(int limit, boolean ascending) { this.limit = limit; this.ascending = ascending; } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return TopFloatFloatAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return TopFloatFloatGroupingAggregatorFunction.intermediateStateDesc(); } @Override public TopFloatFloatAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return TopFloatFloatAggregatorFunction.create(driverContext, channels, limit, ascending); } @Override public TopFloatFloatGroupingAggregatorFunction groupingAggregator(DriverContext driverContext, List<Integer> channels) { return TopFloatFloatGroupingAggregatorFunction.create(channels, driverContext, limit, ascending); } @Override public String describe() { return "top_float of floats"; } }
TopFloatFloatAggregatorFunctionSupplier
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java
{ "start": 1706, "end": 5274 }
class ____ { private static TelnetHandler change = new ChangeTelnetHandler(); private Channel mockChannel; private Invoker<DemoService> mockInvoker; private static int portIncrease; @AfterAll public static void tearDown() {} @SuppressWarnings("unchecked") @BeforeEach public void setUp() { mockChannel = mock(Channel.class); mockInvoker = mock(Invoker.class); given(mockChannel.getAttribute("telnet.service")) .willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); mockChannel.setAttribute("telnet.service", "DemoService"); givenLastCall(); mockChannel.setAttribute("telnet.service", "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); givenLastCall(); mockChannel.setAttribute("telnet.service", "demo"); givenLastCall(); mockChannel.removeAttribute("telnet.service"); givenLastCall(); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:" + (20994 + portIncrease++) + "/demo")); } private void givenLastCall() {} @AfterEach public void after() { FrameworkModel.destroyAll(); reset(mockChannel, mockInvoker); } @Test void testChangeSimpleName() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "DemoService"); assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeName() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "org.apache.dubbo.qos.legacy.service.DemoService"); assertEquals( "Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangePath() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "demo"); assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeMessageNull() throws RemotingException { String result = change.telnet(mockChannel, null); assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result); } @Test void testChangeServiceNotExport() throws RemotingException { String result = change.telnet(mockChannel, "demo"); assertEquals("No such service demo", result); } @Test void testChangeCancel() throws RemotingException { String result = change.telnet(mockChannel, ".."); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } @Test void testChangeCancel2() throws RemotingException { String result = change.telnet(mockChannel, "/"); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } }
ChangeTelnetHandlerTest
java
apache__avro
lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Nested.java
{ "start": 8596, "end": 9977 }
class ____ extends org.apache.thrift.scheme.StandardScheme<Nested> { public void read(org.apache.thrift.protocol.TProtocol iprot, Nested struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // X if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.x = iprot.readI32(); struct.setXIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, Nested struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(X_FIELD_DESC); oprot.writeI32(struct.x); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static
NestedStandardScheme
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customproviders/FilterWithPathParamsTest.java
{ "start": 2707, "end": 3434 }
class ____ { @ServerRequestFilter public Uni<Response> filter(ResteasyReactiveContainerRequestContext requestContext) { if ("true".equals(requestContext.getHeaders().getFirst("abort"))) { requestContext.getUriInfo().getPathParameters(); return Uni.createFrom().item(Response.status(401).build()); } return null; } @ServerResponseFilter public void responseFilter(ResteasyReactiveContainerRequestContext requestContext, ContainerResponseContext responseContext) { responseContext.getHeaders().add("path-params", requestContext.getUriInfo().getPathParameters().size()); } } }
Filters
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/rank/RankDoc.java
{ "start": 1201, "end": 4268 }
class ____ extends ScoreDoc implements VersionedNamedWriteable, ToXContentFragment, Comparable<RankDoc> { public static final String NAME = "rank_doc"; public static final int NO_RANK = -1; /** * If this document has been ranked, this is its final rrf ranking from all the result sets. */ public int rank = NO_RANK; @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersions.V_8_16_0; } @Override public final int compareTo(RankDoc other) { if (score != other.score) { return score < other.score ? 1 : -1; } if (shardIndex != other.shardIndex) { return shardIndex < other.shardIndex ? -1 : 1; } return doc < other.doc ? -1 : 1; } public record RankKey(int doc, int shardIndex) {} public RankDoc(int doc, float score, int shardIndex) { super(doc, score, shardIndex); } public RankDoc(StreamInput in) throws IOException { super(in.readVInt(), in.readFloat(), in.readVInt()); rank = in.readVInt(); } @Override public final void writeTo(StreamOutput out) throws IOException { out.writeVInt(doc); out.writeFloat(score); out.writeVInt(shardIndex); out.writeVInt(rank); doWriteTo(out); } protected void doWriteTo(StreamOutput out) throws IOException {}; /** * Explain the ranking of this document. */ public Explanation explain(Explanation[] sourceExplanations, String[] queryNames) { return Explanation.match( rank, "doc [" + doc + "] with an original score of [" + score + "] is at rank [" + rank + "] from the following source queries.", sourceExplanations ); } @Override public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("_rank", rank); builder.field("_doc", doc); builder.field("_shard", shardIndex); builder.field("_score", score); doToXContent(builder, params); return builder; } protected void doToXContent(XContentBuilder builder, Params params) throws IOException {} @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RankDoc rd = (RankDoc) o; return doc == rd.doc && score == rd.score && shardIndex == rd.shardIndex && rank == rd.rank && doEquals(rd); } protected boolean doEquals(RankDoc rd) { return true; } @Override public final int hashCode() { return Objects.hash(doc, score, shardIndex, doHashCode()); } protected int doHashCode() { return 0; } @Override public String toString() { return "RankDoc{" + "_rank=" + rank + ", _doc=" + doc + ", _shard=" + shardIndex + ", _score=" + score + "}"; } }
RankDoc
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/fs/TestEnhancedByteBufferAccess.java
{ "start": 18617, "end": 33217 }
class ____ implements ByteBufferPool { private final boolean direct; RestrictedAllocatingByteBufferPool(boolean direct) { this.direct = direct; } @Override public ByteBuffer getBuffer(boolean direct, int length) { Preconditions.checkArgument(this.direct == direct); return direct ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length); } @Override public void putBuffer(ByteBuffer buffer) { } } private static void testFallbackImpl(InputStream stream, byte original[]) throws Exception { RestrictedAllocatingByteBufferPool bufferPool = new RestrictedAllocatingByteBufferPool( stream instanceof ByteBufferReadable); ByteBuffer result = ByteBufferUtil.fallbackRead(stream, bufferPool, 10); assertEquals(10, result.remaining()); assertArrayEquals(Arrays.copyOfRange(original, 0, 10), byteBufferToArray(result)); result = ByteBufferUtil.fallbackRead(stream, bufferPool, 5000); assertEquals(5000, result.remaining()); assertArrayEquals(Arrays.copyOfRange(original, 10, 5010), byteBufferToArray(result)); result = ByteBufferUtil.fallbackRead(stream, bufferPool, 9999999); assertEquals(11375, result.remaining()); assertArrayEquals(Arrays.copyOfRange(original, 5010, 16385), byteBufferToArray(result)); result = ByteBufferUtil.fallbackRead(stream, bufferPool, 10); assertNull(result); } /** * Test the {@link ByteBufferUtil#fallbackRead} function directly. */ @Test public void testFallbackRead() throws Exception { HdfsConfiguration conf = initZeroCopyTest(); MiniDFSCluster cluster = null; final Path TEST_PATH = new Path("/a"); final int TEST_FILE_LENGTH = 16385; final int RANDOM_SEED = 23453; FSDataInputStream fsIn = null; DistributedFileSystem fs = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); fs = cluster.getFileSystem(); DFSTestUtil.createFile(fs, TEST_PATH, TEST_FILE_LENGTH, (short)1, RANDOM_SEED); try { DFSTestUtil.waitReplication(fs, TEST_PATH, (short)1); } catch (InterruptedException e) { fail("unexpected InterruptedException during " + "waitReplication: " + e); } catch (TimeoutException e) { fail("unexpected TimeoutException during " + "waitReplication: " + e); } fsIn = fs.open(TEST_PATH); byte original[] = new byte[TEST_FILE_LENGTH]; IOUtils.readFully(fsIn, original, 0, TEST_FILE_LENGTH); fsIn.close(); fsIn = fs.open(TEST_PATH); testFallbackImpl(fsIn, original); } finally { if (fsIn != null) fsIn.close(); if (fs != null) fs.close(); if (cluster != null) cluster.shutdown(); } } /** * Test fallback reads on a stream which does not support the * ByteBufferReadable * interface. */ @Test public void testIndirectFallbackReads() throws Exception { final String testPath = GenericTestUtils .getTestDir("indirectFallbackTestFile").getAbsolutePath(); final int TEST_FILE_LENGTH = 16385; final int RANDOM_SEED = 23453; FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(testPath); Random random = new Random(RANDOM_SEED); byte original[] = new byte[TEST_FILE_LENGTH]; random.nextBytes(original); fos.write(original); fos.close(); fos = null; fis = new FileInputStream(testPath); testFallbackImpl(fis, original); } finally { IOUtils.cleanupWithLogger(LOG, fos, fis); new File(testPath).delete(); } } /** * Test that we can zero-copy read cached data even without disabling * checksums. */ @Test @Timeout(value = 120) public void testZeroCopyReadOfCachedData() throws Exception { BlockReaderTestUtil.enableShortCircuitShmTracing(); BlockReaderTestUtil.enableBlockReaderFactoryTracing(); BlockReaderTestUtil.enableHdfsCachingTracing(); final int TEST_FILE_LENGTH = BLOCK_SIZE; final Path TEST_PATH = new Path("/a"); final int RANDOM_SEED = 23453; HdfsConfiguration conf = initZeroCopyTest(); conf.setBoolean(HdfsClientConfigKeys.Read.ShortCircuit.SKIP_CHECKSUM_KEY, false); final String CONTEXT = "testZeroCopyReadOfCachedData"; conf.set(HdfsClientConfigKeys.DFS_CLIENT_CONTEXT, CONTEXT); conf.setLong(DFS_DATANODE_MAX_LOCKED_MEMORY_KEY, DFSTestUtil.roundUpToMultiple(TEST_FILE_LENGTH, (int) NativeIO.POSIX.getCacheManipulator().getOperatingSystemPageSize())); MiniDFSCluster cluster = null; ByteBuffer result = null, result2 = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); FsDatasetSpi<?> fsd = cluster.getDataNodes().get(0).getFSDataset(); DistributedFileSystem fs = cluster.getFileSystem(); DFSTestUtil.createFile(fs, TEST_PATH, TEST_FILE_LENGTH, (short)1, RANDOM_SEED); DFSTestUtil.waitReplication(fs, TEST_PATH, (short)1); byte original[] = DFSTestUtil. calculateFileContentsFromSeed(RANDOM_SEED, TEST_FILE_LENGTH); // Prior to caching, the file can't be read via zero-copy FSDataInputStream fsIn = fs.open(TEST_PATH); try { result = fsIn.read(null, TEST_FILE_LENGTH / 2, EnumSet.noneOf(ReadOption.class)); fail("expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } // Cache the file fs.addCachePool(new CachePoolInfo("pool1")); long directiveId = fs.addCacheDirective(new CacheDirectiveInfo.Builder(). setPath(TEST_PATH). setReplication((short)1). setPool("pool1"). build()); int numBlocks = (int)Math.ceil((double)TEST_FILE_LENGTH / BLOCK_SIZE); DFSTestUtil.verifyExpectedCacheUsage( DFSTestUtil.roundUpToMultiple(TEST_FILE_LENGTH, BLOCK_SIZE), numBlocks, cluster.getDataNodes().get(0).getFSDataset()); try { result = fsIn.read(null, TEST_FILE_LENGTH, EnumSet.noneOf(ReadOption.class)); } catch (UnsupportedOperationException e) { fail("expected to be able to read cached file via zero-copy"); } assertArrayEquals(Arrays.copyOfRange(original, 0, BLOCK_SIZE), byteBufferToArray(result)); // Test that files opened after the cache operation has finished // still get the benefits of zero-copy (regression test for HDFS-6086) FSDataInputStream fsIn2 = fs.open(TEST_PATH); try { result2 = fsIn2.read(null, TEST_FILE_LENGTH, EnumSet.noneOf(ReadOption.class)); } catch (UnsupportedOperationException e) { fail("expected to be able to read cached file via zero-copy"); } assertArrayEquals(Arrays.copyOfRange(original, 0, BLOCK_SIZE), byteBufferToArray(result2)); fsIn2.releaseBuffer(result2); fsIn2.close(); // check that the replica is anchored final ExtendedBlock firstBlock = DFSTestUtil.getFirstBlock(fs, TEST_PATH); final ShortCircuitCache cache = ClientContext.get( CONTEXT, conf).getShortCircuitCache(0); waitForReplicaAnchorStatus(cache, firstBlock, true, true, 1); // Uncache the replica fs.removeCacheDirective(directiveId); waitForReplicaAnchorStatus(cache, firstBlock, false, true, 1); fsIn.releaseBuffer(result); waitForReplicaAnchorStatus(cache, firstBlock, false, false, 1); DFSTestUtil.verifyExpectedCacheUsage(0, 0, fsd); fsIn.close(); fs.close(); cluster.shutdown(); } private void waitForReplicaAnchorStatus(final ShortCircuitCache cache, final ExtendedBlock block, final boolean expectedIsAnchorable, final boolean expectedIsAnchored, final int expectedOutstandingMmaps) throws Exception { GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { final MutableBoolean result = new MutableBoolean(false); cache.accept(new CacheVisitor() { @Override public void visit(int numOutstandingMmaps, Map<ExtendedBlockId, ShortCircuitReplica> replicas, Map<ExtendedBlockId, InvalidToken> failedLoads, LinkedMap evictable, LinkedMap evictableMmapped) { assertEquals(expectedOutstandingMmaps, numOutstandingMmaps); ShortCircuitReplica replica = replicas.get(ExtendedBlockId.fromExtendedBlock(block)); assertNotNull(replica); Slot slot = replica.getSlot(); if ((expectedIsAnchorable != slot.isAnchorable()) || (expectedIsAnchored != slot.isAnchored())) { LOG.info("replica " + replica + " has isAnchorable = " + slot.isAnchorable() + ", isAnchored = " + slot.isAnchored() + ". Waiting for isAnchorable = " + expectedIsAnchorable + ", isAnchored = " + expectedIsAnchored); return; } result.setValue(true); } }); return result.toBoolean(); } }, 10, 60000); } @Test public void testClientMmapDisable() throws Exception { HdfsConfiguration conf = initZeroCopyTest(); conf.setBoolean(HdfsClientConfigKeys.Mmap.ENABLED_KEY, false); MiniDFSCluster cluster = null; final Path TEST_PATH = new Path("/a"); final int TEST_FILE_LENGTH = 16385; final int RANDOM_SEED = 23453; final String CONTEXT = "testClientMmapDisable"; FSDataInputStream fsIn = null; DistributedFileSystem fs = null; conf.set(HdfsClientConfigKeys.DFS_CLIENT_CONTEXT, CONTEXT); try { // With HdfsClientConfigKeys.Mmap.ENABLED_KEY set to false, // we should not do memory mapped reads. cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); fs = cluster.getFileSystem(); DFSTestUtil.createFile(fs, TEST_PATH, TEST_FILE_LENGTH, (short)1, RANDOM_SEED); DFSTestUtil.waitReplication(fs, TEST_PATH, (short)1); fsIn = fs.open(TEST_PATH); try { fsIn.read(null, 1, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); fail("expected zero-copy read to fail when client mmaps " + "were disabled."); } catch (UnsupportedOperationException e) { } } finally { if (fsIn != null) fsIn.close(); if (fs != null) fs.close(); if (cluster != null) cluster.shutdown(); } fsIn = null; fs = null; cluster = null; try { // Now try again with HdfsClientConfigKeys.Mmap.CACHE_SIZE_KEY == 0. conf.setBoolean(HdfsClientConfigKeys.Mmap.ENABLED_KEY, true); conf.setInt(HdfsClientConfigKeys.Mmap.CACHE_SIZE_KEY, 0); conf.set(HdfsClientConfigKeys.DFS_CLIENT_CONTEXT, CONTEXT + ".1"); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); fs = cluster.getFileSystem(); DFSTestUtil.createFile(fs, TEST_PATH, TEST_FILE_LENGTH, (short)1, RANDOM_SEED); DFSTestUtil.waitReplication(fs, TEST_PATH, (short)1); fsIn = fs.open(TEST_PATH); ByteBuffer buf = fsIn.read(null, 1, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); fsIn.releaseBuffer(buf); // Test EOF behavior IOUtils.skipFully(fsIn, TEST_FILE_LENGTH - 1); buf = fsIn.read(null, 1, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); assertEquals(null, buf); } finally { if (fsIn != null) fsIn.close(); if (fs != null) fs.close(); if (cluster != null) cluster.shutdown(); } } @Test public void test2GBMmapLimit() throws Exception { assumeTrue(BlockReaderTestUtil.shouldTestLargeFiles()); HdfsConfiguration conf = initZeroCopyTest(); final long TEST_FILE_LENGTH = 2469605888L; conf.set(DFSConfigKeys.DFS_CHECKSUM_TYPE_KEY, "NULL"); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, TEST_FILE_LENGTH); MiniDFSCluster cluster = null; final Path TEST_PATH = new Path("/a"); final String CONTEXT = "test2GBMmapLimit"; conf.set(HdfsClientConfigKeys.DFS_CLIENT_CONTEXT, CONTEXT); FSDataInputStream fsIn = null, fsIn2 = null; ByteBuffer buf1 = null, buf2 = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); DFSTestUtil.createFile(fs, TEST_PATH, TEST_FILE_LENGTH, (short)1, 0xB); DFSTestUtil.waitReplication(fs, TEST_PATH, (short)1); fsIn = fs.open(TEST_PATH); buf1 = fsIn.read(null, 1, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); assertEquals(1, buf1.remaining()); fsIn.releaseBuffer(buf1); buf1 = null; fsIn.seek(2147483640L); buf1 = fsIn.read(null, 1024, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); assertEquals(7, buf1.remaining()); assertEquals(Integer.MAX_VALUE, buf1.limit()); fsIn.releaseBuffer(buf1); buf1 = null; assertEquals(2147483647L, fsIn.getPos()); try { buf1 = fsIn.read(null, 1024, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); fail("expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected; can't read past 2GB boundary. } fsIn.close(); fsIn = null; // Now create another file with normal-sized blocks, and verify we // can read past 2GB final Path TEST_PATH2 = new Path("/b"); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 268435456L); DFSTestUtil.createFile(fs, TEST_PATH2, 1024 * 1024, TEST_FILE_LENGTH, 268435456L, (short)1, 0xA); fsIn2 = fs.open(TEST_PATH2); fsIn2.seek(2147483640L); buf2 = fsIn2.read(null, 1024, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); assertEquals(8, buf2.remaining()); assertEquals(2147483648L, fsIn2.getPos()); fsIn2.releaseBuffer(buf2); buf2 = null; buf2 = fsIn2.read(null, 1024, EnumSet.of(ReadOption.SKIP_CHECKSUMS)); assertEquals(1024, buf2.remaining()); assertEquals(2147484672L, fsIn2.getPos()); fsIn2.releaseBuffer(buf2); buf2 = null; } finally { if (buf1 != null) { fsIn.releaseBuffer(buf1); } if (buf2 != null) { fsIn2.releaseBuffer(buf2); } IOUtils.cleanupWithLogger(null, fsIn, fsIn2); if (cluster != null) { cluster.shutdown(); } } } }
RestrictedAllocatingByteBufferPool
java
apache__kafka
tools/src/test/java/org/apache/kafka/tools/AclCommandTest.java
{ "start": 4725, "end": 30483 }
class ____ { public static final String STANDARD_AUTHORIZER = "org.apache.kafka.metadata.authorizer.StandardAuthorizer"; private static final String LOCALHOST = "localhost:9092"; private static final String ADD = "--add"; private static final String BOOTSTRAP_SERVER = "--bootstrap-server"; private static final String BOOTSTRAP_CONTROLLER = "--bootstrap-controller"; private static final String COMMAND_CONFIG = "--command-config"; private static final String CONSUMER = "--consumer"; private static final String IDEMPOTENT = "--idempotent"; private static final String GROUP = "--group"; private static final String LIST = "--list"; private static final String REMOVE = "--remove"; private static final String PRODUCER = "--producer"; private static final String OPERATION = "--operation"; private static final String TOPIC = "--topic"; private static final String RESOURCE_PATTERN_TYPE = "--resource-pattern-type"; private static final KafkaPrincipal PRINCIPAL = SecurityUtils.parseKafkaPrincipal("User:test2"); private static final Set<KafkaPrincipal> USERS = Set.of( SecurityUtils.parseKafkaPrincipal("User:CN=writeuser,OU=Unknown,O=Unknown,L=Unknown,ST=Unknown,C=Unknown"), PRINCIPAL, SecurityUtils.parseKafkaPrincipal("User:CN=\\#User with special chars in CN : (\\, \\+ \" \\ \\< \\> \\; ')") ); private static final Set<String> HOSTS = Set.of("host1", "host2"); private static final List<String> ALLOW_HOST_COMMAND = List.of("--allow-host", "host1", "--allow-host", "host2"); private static final List<String> DENY_HOST_COMMAND = List.of("--deny-host", "host1", "--deny-host", "host2"); private static final ResourcePattern CLUSTER_RESOURCE = new ResourcePattern(CLUSTER, Resource.CLUSTER_NAME, LITERAL); private static final Set<ResourcePattern> TOPIC_RESOURCES = Set.of( new ResourcePattern(ResourceType.TOPIC, "test-1", LITERAL), new ResourcePattern(ResourceType.TOPIC, "test-2", LITERAL) ); private static final Set<ResourcePattern> GROUP_RESOURCES = Set.of( new ResourcePattern(ResourceType.GROUP, "testGroup-1", LITERAL), new ResourcePattern(ResourceType.GROUP, "testGroup-2", LITERAL) ); private static final Set<ResourcePattern> TRANSACTIONAL_ID_RESOURCES = Set.of( new ResourcePattern(TRANSACTIONAL_ID, "t0", LITERAL), new ResourcePattern(TRANSACTIONAL_ID, "t1", LITERAL) ); private static final Set<ResourcePattern> TOKEN_RESOURCES = Set.of( new ResourcePattern(DELEGATION_TOKEN, "token1", LITERAL), new ResourcePattern(DELEGATION_TOKEN, "token2", LITERAL) ); private static final Set<ResourcePattern> USER_RESOURCES = Set.of( new ResourcePattern(USER, "User:test-user1", LITERAL), new ResourcePattern(USER, "User:test-user2", LITERAL) ); private static final Map<Set<ResourcePattern>, List<String>> RESOURCE_TO_COMMAND = Map.of( TOPIC_RESOURCES, List.of(TOPIC, "test-1", TOPIC, "test-2"), Set.of(CLUSTER_RESOURCE), List.of("--cluster"), GROUP_RESOURCES, List.of(GROUP, "testGroup-1", GROUP, "testGroup-2"), TRANSACTIONAL_ID_RESOURCES, List.of("--transactional-id", "t0", "--transactional-id", "t1"), TOKEN_RESOURCES, List.of("--delegation-token", "token1", "--delegation-token", "token2"), USER_RESOURCES, List.of("--user-principal", "User:test-user1", "--user-principal", "User:test-user2") ); private static final Map<Set<ResourcePattern>, Map.Entry<Set<AclOperation>, List<String>>> RESOURCE_TO_OPERATIONS = Map.of( TOPIC_RESOURCES, Map.entry( Set.of(READ, WRITE, CREATE, DESCRIBE, DELETE, DESCRIBE_CONFIGS, ALTER_CONFIGS, ALTER), List.of(OPERATION, "Read", OPERATION, "Write", OPERATION, "Create", OPERATION, "Describe", OPERATION, "Delete", OPERATION, "DescribeConfigs", OPERATION, "AlterConfigs", OPERATION, "Alter")), Set.of(CLUSTER_RESOURCE), Map.entry( Set.of(CREATE, CLUSTER_ACTION, DESCRIBE_CONFIGS, ALTER_CONFIGS, IDEMPOTENT_WRITE, ALTER, DESCRIBE), List.of(OPERATION, "Create", OPERATION, "ClusterAction", OPERATION, "DescribeConfigs", OPERATION, "AlterConfigs", OPERATION, "IdempotentWrite", OPERATION, "Alter", OPERATION, "Describe")), GROUP_RESOURCES, Map.entry( Set.of(READ, DESCRIBE, DELETE), List.of(OPERATION, "Read", OPERATION, "Describe", OPERATION, "Delete")), TRANSACTIONAL_ID_RESOURCES, Map.entry( Set.of(DESCRIBE, WRITE, TWO_PHASE_COMMIT), List.of(OPERATION, "Describe", OPERATION, "Write", OPERATION, "TwoPhaseCommit")), TOKEN_RESOURCES, Map.entry( Set.of(DESCRIBE), List.of(OPERATION, "Describe")), USER_RESOURCES, Map.entry( Set.of(CREATE_TOKENS, DESCRIBE_TOKENS), List.of(OPERATION, "CreateTokens", OPERATION, "DescribeTokens")) ); private static final Map<Set<ResourcePattern>, Set<AccessControlEntry>> CONSUMER_RESOURCE_TO_ACLS = Map.of( TOPIC_RESOURCES, AclCommand.getAcls(USERS, ALLOW, Set.of(READ, DESCRIBE), HOSTS), GROUP_RESOURCES, AclCommand.getAcls(USERS, ALLOW, Set.of(READ), HOSTS) ); private static final Map<List<String>, Map<Set<ResourcePattern>, Set<AccessControlEntry>>> CMD_TO_RESOURCES_TO_ACL = Map.of( List.of(PRODUCER), producerResourceToAcls(false), List.of(PRODUCER, IDEMPOTENT), producerResourceToAcls(true), List.of(CONSUMER), CONSUMER_RESOURCE_TO_ACLS, List.of(PRODUCER, CONSUMER), CONSUMER_RESOURCE_TO_ACLS.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, entry -> { Set<AccessControlEntry> value = new HashSet<>(entry.getValue()); value.addAll(producerResourceToAcls(false).getOrDefault(entry.getKey(), Set.of())); return value; } )), List.of(PRODUCER, IDEMPOTENT, CONSUMER), CONSUMER_RESOURCE_TO_ACLS.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, entry -> { Set<AccessControlEntry> value = new HashSet<>(entry.getValue()); value.addAll(producerResourceToAcls(true).getOrDefault(entry.getKey(), Set.of())); return value; } )) ); @ClusterTest public void testAclCliWithAdminAPI(ClusterInstance cluster) throws InterruptedException { testAclCli(cluster, adminArgs(cluster.bootstrapServers(), Optional.empty())); } @ClusterTest public void testAclCliWithAdminAPIAndBootstrapController(ClusterInstance cluster) throws InterruptedException { testAclCli(cluster, adminArgsWithBootstrapController(cluster.bootstrapControllers(), Optional.empty())); } @ClusterTest public void testAclCliWithMisusingBootstrapServerToController(ClusterInstance cluster) { assertThrows(RuntimeException.class, () -> testAclCli(cluster, adminArgsWithBootstrapController(cluster.bootstrapServers(), Optional.empty()))); } @ClusterTest public void testAclCliWithMisusingBootstrapControllerToServer(ClusterInstance cluster) { assertThrows(RuntimeException.class, () -> testAclCli(cluster, adminArgs(cluster.bootstrapControllers(), Optional.empty()))); } @ClusterTest public void testProducerConsumerCliWithAdminAPI(ClusterInstance cluster) throws InterruptedException { testProducerConsumerCli(cluster, adminArgs(cluster.bootstrapServers(), Optional.empty())); } @ClusterTest public void testProducerConsumerCliWithAdminAPIAndBootstrapController(ClusterInstance cluster) throws InterruptedException { testProducerConsumerCli(cluster, adminArgsWithBootstrapController(cluster.bootstrapControllers(), Optional.empty())); } @ClusterTest public void testAclCliWithClientId(ClusterInstance cluster) throws IOException, InterruptedException { try (LogCaptureAppender appender = LogCaptureAppender.createAndRegister()) { appender.setClassLogger(AppInfoParser.class, Level.WARN); testAclCli(cluster, adminArgs(cluster.bootstrapServers(), Optional.of(TestUtils.tempFile("client.id=my-client")))); assertEquals(0, appender.getEvents().stream() .filter(e -> e.getLevel().equals(Level.WARN.toString())) .filter(e -> e.getThrowableClassName().filter(name -> name.equals(InstanceAlreadyExistsException.class.getName())).isPresent()) .count(), "There should be no warnings about multiple registration of mbeans"); } } @ClusterTest public void testAclCliWithClientIdAndBootstrapController(ClusterInstance cluster) throws IOException, InterruptedException { try (LogCaptureAppender appender = LogCaptureAppender.createAndRegister()) { appender.setClassLogger(AppInfoParser.class, Level.WARN); testAclCli(cluster, adminArgsWithBootstrapController(cluster.bootstrapControllers(), Optional.of(TestUtils.tempFile("client.id=my-client")))); assertEquals(0, appender.getEvents().stream() .filter(e -> e.getLevel().equals(Level.WARN.toString())) .filter(e -> e.getThrowableClassName().filter(name -> name.equals(InstanceAlreadyExistsException.class.getName())).isPresent()) .count(), "There should be no warnings about multiple registration of mbeans"); } } @ClusterTest public void testAclsOnPrefixedResourcesWithAdminAPI(ClusterInstance cluster) throws InterruptedException { testAclsOnPrefixedResources(cluster, adminArgs(cluster.bootstrapServers(), Optional.empty())); } @ClusterTest public void testAclsOnPrefixedResourcesWithAdminAPIAndBootstrapController(ClusterInstance cluster) throws InterruptedException { testAclsOnPrefixedResources(cluster, adminArgsWithBootstrapController(cluster.bootstrapControllers(), Optional.empty())); } @ClusterTest public void testPatternTypesWithAdminAPI(ClusterInstance cluster) { testPatternTypes(adminArgs(cluster.bootstrapServers(), Optional.empty())); } @ClusterTest public void testPatternTypesWithAdminAPIAndBootstrapController(ClusterInstance cluster) { testPatternTypes(adminArgsWithBootstrapController(cluster.bootstrapControllers(), Optional.empty())); } @ClusterTest public void testDuplicateAdd(ClusterInstance cluster) { final String topicName = "test-topic"; final String principal = "User:Alice"; ResourcePattern resource = new ResourcePattern(ResourceType.TOPIC, topicName, PatternType.LITERAL); AccessControlEntry ace = new AccessControlEntry(principal, WILDCARD_HOST, READ, ALLOW); AclBinding binding = new AclBinding(resource, ace); List<String> cmdArgs = adminArgs(cluster.bootstrapServers(), Optional.empty()); List<String> initialAddArgs = new ArrayList<>(cmdArgs); initialAddArgs.addAll(List.of(ADD, TOPIC, topicName, "--allow-principal", principal, OPERATION, "Read")); callMain(initialAddArgs); String out = callMain(initialAddArgs).getKey(); assertTrue(out.contains("Acl " + binding + " already exists.")); assertFalse(out.contains("Adding ACLs for resource")); } @Test public void testUseBootstrapServerOptWithBootstrapControllerOpt() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, BOOTSTRAP_CONTROLLER, LOCALHOST), "Only one of --bootstrap-server or --bootstrap-controller must be specified" ); } @Test public void testUseWithoutBootstrapServerOptAndBootstrapControllerOpt() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(ADD), "One of --bootstrap-server or --bootstrap-controller must be specified" ); } @Test public void testExactlyOneAction() { String errMsg = "Command must include exactly one action: --list, --add, --remove. "; assertInitializeInvalidOptionsExitCodeAndMsg(List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, LIST), errMsg); assertInitializeInvalidOptionsExitCodeAndMsg(List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, LIST, REMOVE), errMsg); } @Test public void testUseListPrincipalsOptWithoutListOpt() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, "--principal", "User:CN=client"), "The --principal option is only available if --list is set" ); } @Test public void testUseProducerOptWithoutTopicOpt() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, PRODUCER), "With --producer you must specify a --topic" ); } @Test public void testUseIdempotentOptWithoutProducerOpt() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, IDEMPOTENT), "The --idempotent option is only available if --producer is set" ); } @Test public void testUseConsumerOptWithoutRequiredOpt() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, CONSUMER), "With --consumer you must specify a --topic and a --group and no --cluster or --transactional-id option should be specified." ); checkNotThrow(List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, CONSUMER, TOPIC, "test-topic", GROUP, "test-group")); } @Test public void testInvalidArgs() { assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, LIST, PRODUCER), "Option \"[list]\" can't be used with option \"[producer]\"" ); assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, PRODUCER, OPERATION, "all"), "Option \"[producer]\" can't be used with option \"[operation]\"" ); assertInitializeInvalidOptionsExitCodeAndMsg( List.of(BOOTSTRAP_SERVER, LOCALHOST, ADD, CONSUMER, OPERATION, TOPIC, "test-topic", GROUP, "test-group"), "Option \"[consumer]\" can't be used with option \"[operation]\"" ); } private void testProducerConsumerCli(ClusterInstance cluster, List<String> cmdArgs) throws InterruptedException { for (Map.Entry<List<String>, Map<Set<ResourcePattern>, Set<AccessControlEntry>>> entry : CMD_TO_RESOURCES_TO_ACL.entrySet()) { List<String> cmd = entry.getKey(); Map<Set<ResourcePattern>, Set<AccessControlEntry>> resourcesToAcls = entry.getValue(); List<String> resourceCommand = resourcesToAcls.keySet().stream() .map(RESOURCE_TO_COMMAND::get) .reduce(new ArrayList<>(), (list, commands) -> { list.addAll(commands); return list; }); List<String> args = new ArrayList<>(cmdArgs); args.addAll(getCmd(ALLOW)); args.addAll(resourceCommand); args.addAll(cmd); args.add(ADD); callMain(args); for (Map.Entry<Set<ResourcePattern>, Set<AccessControlEntry>> resourcesToAclsEntry : resourcesToAcls.entrySet()) { for (ResourcePattern resource : resourcesToAclsEntry.getKey()) { cluster.waitAcls(new AclBindingFilter(resource.toFilter(), ANY), resourcesToAclsEntry.getValue()); } } List<String> resourceCmd = new ArrayList<>(resourceCommand); resourceCmd.addAll(cmd); testRemove(cluster, cmdArgs, resourcesToAcls.keySet().stream().flatMap(Set::stream).collect(Collectors.toSet()), resourceCmd); } } private void testAclsOnPrefixedResources(ClusterInstance cluster, List<String> cmdArgs) throws InterruptedException { List<String> cmd = List.of("--allow-principal", PRINCIPAL.toString(), PRODUCER, TOPIC, "Test-", RESOURCE_PATTERN_TYPE, "Prefixed"); List<String> args = new ArrayList<>(cmdArgs); args.addAll(cmd); args.add(ADD); callMain(args); AccessControlEntry writeAcl = new AccessControlEntry(PRINCIPAL.toString(), WILDCARD_HOST, WRITE, ALLOW); AccessControlEntry describeAcl = new AccessControlEntry(PRINCIPAL.toString(), WILDCARD_HOST, DESCRIBE, ALLOW); AccessControlEntry createAcl = new AccessControlEntry(PRINCIPAL.toString(), WILDCARD_HOST, CREATE, ALLOW); cluster.waitAcls(new AclBindingFilter(new ResourcePattern(ResourceType.TOPIC, "Test-", PREFIXED).toFilter(), ANY), List.of(writeAcl, describeAcl, createAcl)); args = new ArrayList<>(cmdArgs); args.addAll(cmd); args.add(REMOVE); args.add("--force"); callMain(args); cluster.waitAcls(new AclBindingFilter(new ResourcePattern(ResourceType.CLUSTER, "kafka-cluster", PREFIXED).toFilter(), ANY), Set.of()); cluster.waitAcls(new AclBindingFilter(new ResourcePattern(ResourceType.TOPIC, "Test-", PREFIXED).toFilter(), ANY), Set.of()); } private static Map<Set<ResourcePattern>, Set<AccessControlEntry>> producerResourceToAcls(boolean enableIdempotence) { return Map.of( TOPIC_RESOURCES, AclCommand.getAcls(USERS, ALLOW, Set.of(WRITE, DESCRIBE, CREATE), HOSTS), TRANSACTIONAL_ID_RESOURCES, AclCommand.getAcls(USERS, ALLOW, Set.of(WRITE, DESCRIBE), HOSTS), Set.of(CLUSTER_RESOURCE), AclCommand.getAcls(USERS, ALLOW, enableIdempotence ? Set.of(IDEMPOTENT_WRITE) : Set.of(), HOSTS)); } private List<String> adminArgs(String bootstrapServer, Optional<File> commandConfig) { List<String> adminArgs = new ArrayList<>(List.of(BOOTSTRAP_SERVER, bootstrapServer)); commandConfig.ifPresent(file -> adminArgs.addAll(List.of(COMMAND_CONFIG, file.getAbsolutePath()))); return adminArgs; } private List<String> adminArgsWithBootstrapController(String bootstrapController, Optional<File> commandConfig) { List<String> adminArgs = new ArrayList<>(List.of(BOOTSTRAP_CONTROLLER, bootstrapController)); commandConfig.ifPresent(file -> adminArgs.addAll(List.of(COMMAND_CONFIG, file.getAbsolutePath()))); return adminArgs; } private Map.Entry<String, String> callMain(List<String> args) { return ToolsTestUtils.grabConsoleOutputAndError(() -> AclCommand.main(args.toArray(new String[0]))); } private void testAclCli(ClusterInstance cluster, List<String> cmdArgs) throws InterruptedException { for (Map.Entry<Set<ResourcePattern>, List<String>> entry : RESOURCE_TO_COMMAND.entrySet()) { Set<ResourcePattern> resources = entry.getKey(); List<String> resourceCmd = entry.getValue(); Set<AclPermissionType> permissionTypes = Set.of(ALLOW, DENY); for (AclPermissionType permissionType : permissionTypes) { Map.Entry<Set<AclOperation>, List<String>> operationToCmd = RESOURCE_TO_OPERATIONS.get(resources); Map.Entry<Set<AccessControlEntry>, List<String>> aclToCommand = getAclToCommand(permissionType, operationToCmd.getKey()); List<String> resultArgs = new ArrayList<>(cmdArgs); resultArgs.addAll(aclToCommand.getValue()); resultArgs.addAll(resourceCmd); resultArgs.addAll(operationToCmd.getValue()); resultArgs.add(ADD); Map.Entry<String, String> out = callMain(resultArgs); assertOutputContains("Adding ACLs", resources, resourceCmd, out.getKey()); assertEquals("", out.getValue()); for (ResourcePattern resource : resources) { cluster.waitAcls(new AclBindingFilter(resource.toFilter(), ANY), aclToCommand.getKey()); } resultArgs = new ArrayList<>(cmdArgs); resultArgs.add(LIST); out = callMain(resultArgs); assertOutputContains("Current ACLs", resources, resourceCmd, out.getKey()); assertEquals("", out.getValue()); testRemove(cluster, cmdArgs, resources, resourceCmd); } } } private void assertOutputContains( String prefix, Set<ResourcePattern> resources, List<String> resourceCmd, String output ) { resources.forEach(resource -> { String resourceType = resource.resourceType().toString(); List<String> cmd = resource == CLUSTER_RESOURCE ? List.of("kafka-cluster") : resourceCmd.stream().filter(s -> !s.startsWith("--")).toList(); cmd.forEach(name -> { String expected = String.format( "%s for resource `ResourcePattern(resourceType=%s, name=%s, patternType=LITERAL)`:", prefix, resourceType, name ); assertTrue(output.contains(expected), "Substring " + expected + " not in output:\n" + output); }); }); } private void testPatternTypes(List<String> cmdArgs) { Exit.setExitProcedure((status, message) -> { if (status == 1) throw new RuntimeException("Exiting command"); else throw new AssertionError("Unexpected exit with status " + status); }); try { for (PatternType patternType : PatternType.values()) { List<String> addCmd = new ArrayList<>(cmdArgs); addCmd.addAll(List.of("--allow-principal", PRINCIPAL.toString(), PRODUCER, TOPIC, "Test", ADD, RESOURCE_PATTERN_TYPE, patternType.toString())); verifyPatternType(addCmd, patternType.isSpecific()); List<String> listCmd = new ArrayList<>(cmdArgs); listCmd.addAll(List.of(TOPIC, "Test", LIST, RESOURCE_PATTERN_TYPE, patternType.toString())); verifyPatternType(listCmd, patternType != PatternType.UNKNOWN); List<String> removeCmd = new ArrayList<>(cmdArgs); removeCmd.addAll(List.of(TOPIC, "Test", "--force", REMOVE, RESOURCE_PATTERN_TYPE, patternType.toString())); verifyPatternType(removeCmd, patternType != PatternType.UNKNOWN); } } finally { Exit.resetExitProcedure(); } } private void verifyPatternType(List<String> cmd, boolean isValid) { if (isValid) { callMain(cmd); } else { assertThrows(RuntimeException.class, () -> callMain(cmd)); } } private void testRemove( ClusterInstance cluster, List<String> cmdArgs, Set<ResourcePattern> resources, List<String> resourceCmd ) throws InterruptedException { List<String> args = new ArrayList<>(cmdArgs); args.addAll(resourceCmd); args.add(REMOVE); args.add("--force"); Map.Entry<String, String> out = callMain(args); assertEquals("", out.getValue()); for (ResourcePattern resource : resources) { cluster.waitAcls(new AclBindingFilter(resource.toFilter(), ANY), Set.of()); } } private Map.Entry<Set<AccessControlEntry>, List<String>> getAclToCommand( AclPermissionType permissionType, Set<AclOperation> operations ) { return Map.entry( AclCommand.getAcls(USERS, permissionType, operations, HOSTS), getCmd(permissionType) ); } private List<String> getCmd(AclPermissionType permissionType) { String principalCmd = permissionType == ALLOW ? "--allow-principal" : "--deny-principal"; List<String> cmd = permissionType == ALLOW ? ALLOW_HOST_COMMAND : DENY_HOST_COMMAND; List<String> fullCmd = new ArrayList<>(); for (KafkaPrincipal user : USERS) { fullCmd.addAll(cmd); fullCmd.addAll(List.of(principalCmd, user.toString())); } return fullCmd; } private void assertInitializeInvalidOptionsExitCodeAndMsg(List<String> args, String expectedMsg) { Exit.setExitProcedure((exitCode, message) -> { assertEquals(1, exitCode); assertTrue(message.contains(expectedMsg)); throw new RuntimeException(); }); try { assertThrows(RuntimeException.class, () -> new AclCommand.AclCommandOptions(args.toArray(new String[0])).checkArgs()); } finally { Exit.resetExitProcedure(); } } private void checkNotThrow(List<String> args) { AtomicReference<Integer> exitStatus = new AtomicReference<>(); Exit.setExitProcedure((status, __) -> { exitStatus.set(status); throw new RuntimeException(); }); try { assertDoesNotThrow(() -> new AclCommand.AclCommandOptions(args.toArray(new String[0])).checkArgs()); assertNull(exitStatus.get()); } finally { Exit.resetExitProcedure(); } } }
AclCommandTest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/arbiters/ClassArbiter.java
{ "start": 1221, "end": 1426 }
class ____ present. */ @Plugin( name = "ClassArbiter", category = Node.CATEGORY, elementType = Arbiter.ELEMENT_TYPE, printObject = true, deferChildren = true) public
is
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableWithLatestFrom.java
{ "start": 1105, "end": 1941 }
class ____<T, U, R> extends AbstractFlowableWithUpstream<T, R> { final BiFunction<? super T, ? super U, ? extends R> combiner; final Publisher<? extends U> other; public FlowableWithLatestFrom(Flowable<T> source, BiFunction<? super T, ? super U, ? extends R> combiner, Publisher<? extends U> other) { super(source); this.combiner = combiner; this.other = other; } @Override protected void subscribeActual(Subscriber<? super R> s) { final SerializedSubscriber<R> serial = new SerializedSubscriber<>(s); final WithLatestFromSubscriber<T, U, R> wlf = new WithLatestFromSubscriber<>(serial, combiner); serial.onSubscribe(wlf); other.subscribe(new FlowableWithLatestSubscriber(wlf)); source.subscribe(wlf); } static final
FlowableWithLatestFrom
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/FunctionRoutingFilterTests.java
{ "start": 1749, "end": 2324 }
class ____ extends BaseWebClientTests { @Test public void functionRoutingFilterWorks() { URI uri = UriComponentsBuilder.fromUriString(this.baseUri + "/").build(true).toUri(); testClient.post() .uri(uri) .bodyValue("hello") .header("Host", "www.functionroutingfilterjava.org") .accept(MediaType.TEXT_PLAIN) .exchange() .expectBody(String.class) .consumeWith(res -> assertThat(res.getResponseBody()).isEqualTo("HELLO")); } @EnableAutoConfiguration @SpringBootConfiguration @Import(DefaultTestConfig.class) public static
FunctionRoutingFilterTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NettyEndpointBuilderFactory.java
{ "start": 162625, "end": 162998 }
interface ____ extends AdvancedNettyEndpointConsumerBuilder, AdvancedNettyEndpointProducerBuilder { default NettyEndpointBuilder basic() { return (NettyEndpointBuilder) this; } /** * When using UDP then this option can be used to specify a network *
AdvancedNettyEndpointBuilder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDNFencing.java
{ "start": 23562, "end": 24216 }
class ____ extends BlockPlacementPolicyDefault { public RandomDeleterPolicy() { super(); } @Override public DatanodeStorageInfo chooseReplicaToDelete( Collection<DatanodeStorageInfo> moreThanOne, Collection<DatanodeStorageInfo> exactlyOne, List<StorageType> excessTypes, Map<String, List<DatanodeStorageInfo>> rackMap) { Collection<DatanodeStorageInfo> chooseFrom = !moreThanOne.isEmpty() ? moreThanOne : exactlyOne; List<DatanodeStorageInfo> l = Lists.newArrayList(chooseFrom); return l.get(ThreadLocalRandom.current().nextInt(l.size())); } } }
RandomDeleterPolicy
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/writer/ResultPartitionWriterWithAvailabilityHelper.java
{ "start": 1125, "end": 1665 }
class ____ extends MockResultPartitionWriter { private final AvailabilityHelper availabilityHelper; public ResultPartitionWriterWithAvailabilityHelper(AvailabilityHelper availabilityHelper) { this.availabilityHelper = availabilityHelper; } @Override public CompletableFuture<?> getAvailableFuture() { return availabilityHelper.getAvailableFuture(); } @Override public boolean isAvailable() { return availabilityHelper.isAvailable(); } }
ResultPartitionWriterWithAvailabilityHelper
java
google__guice
extensions/servlet/test/com/google/inject/servlet/InvalidScopeBindingTest.java
{ "start": 497, "end": 2600 }
class ____ extends TestCase { @Override protected void tearDown() throws Exception { GuiceFilter.reset(); } public final void testServletInNonSingletonScopeThrowsServletException() { GuiceFilter guiceFilter = new GuiceFilter(); Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { serve("/*").with(MyNonSingletonServlet.class); } }); ServletException se = null; try { guiceFilter.init(mock(FilterConfig.class)); } catch (ServletException e) { se = e; } finally { assertNotNull("Servlet exception was not thrown with wrong scope binding", se); } } public final void testFilterInNonSingletonScopeThrowsServletException() { GuiceFilter guiceFilter = new GuiceFilter(); Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { filter("/*").through(MyNonSingletonFilter.class); } }); ServletException se = null; try { guiceFilter.init(mock(FilterConfig.class)); } catch (ServletException e) { se = e; } finally { assertNotNull("Servlet exception was not thrown with wrong scope binding", se); } } public final void testHappyCaseFilter() { GuiceFilter guiceFilter = new GuiceFilter(); Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { // Annotated scoping variant. filter("/*").through(MySingletonFilter.class); // Explicit scoping variant. bind(DummyFilterImpl.class).in(Scopes.SINGLETON); filter("/*").through(DummyFilterImpl.class); } }); ServletException se = null; try { guiceFilter.init(mock(FilterConfig.class)); } catch (ServletException e) { se = e; } finally { assertNull("Servlet exception was thrown with correct scope binding", se); } } @RequestScoped public static
InvalidScopeBindingTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/DocumentParserContextTests.java
{ "start": 889, "end": 6991 }
class ____ extends ESTestCase { private TestDocumentParserContext context = new TestDocumentParserContext(); private final MapperBuilderContext root = MapperBuilderContext.root(false, false); public void testDynamicMapperSizeMultipleMappers() { context.addDynamicMapper(new TextFieldMapper.Builder("foo", createDefaultIndexAnalyzers()).build(root)); assertEquals(1, context.getNewFieldsSize()); context.addDynamicMapper(new TextFieldMapper.Builder("bar", createDefaultIndexAnalyzers()).build(root)); assertEquals(2, context.getNewFieldsSize()); context.addDynamicRuntimeField(new TestRuntimeField("runtime1", "keyword")); assertEquals(3, context.getNewFieldsSize()); context.addDynamicRuntimeField(new TestRuntimeField("runtime2", "keyword")); assertEquals(4, context.getNewFieldsSize()); } public void testDynamicMapperSizeSameFieldMultipleRuntimeFields() { context.addDynamicRuntimeField(new TestRuntimeField("foo", "keyword")); context.addDynamicRuntimeField(new TestRuntimeField("foo", "keyword")); assertEquals(context.getNewFieldsSize(), 1); } public void testDynamicMapperSizeSameFieldMultipleMappers() { context.addDynamicMapper(new TextFieldMapper.Builder("foo", createDefaultIndexAnalyzers()).build(root)); assertEquals(1, context.getNewFieldsSize()); context.addDynamicMapper(new TextFieldMapper.Builder("foo", createDefaultIndexAnalyzers()).build(root)); assertEquals(1, context.getNewFieldsSize()); } public void testAddRuntimeFieldWhenLimitIsReachedViaMapper() { context = new TestDocumentParserContext( Settings.builder() .put("index.mapping.total_fields.limit", 1) .put("index.mapping.total_fields.ignore_dynamic_beyond_limit", true) .build() ); assertTrue(context.addDynamicMapper(new KeywordFieldMapper.Builder("keyword_field", defaultIndexSettings()).build(root))); assertFalse(context.addDynamicRuntimeField(new TestRuntimeField("runtime_field", "keyword"))); assertThat(context.getIgnoredFields(), contains("runtime_field")); } public void testAddFieldWhenLimitIsReachedViaRuntimeField() { context = new TestDocumentParserContext( Settings.builder() .put("index.mapping.total_fields.limit", 1) .put("index.mapping.total_fields.ignore_dynamic_beyond_limit", true) .build() ); assertTrue(context.addDynamicRuntimeField(new TestRuntimeField("runtime_field", "keyword"))); assertFalse(context.addDynamicMapper(new KeywordFieldMapper.Builder("keyword_field", defaultIndexSettings()).build(root))); assertThat(context.getIgnoredFields(), contains("keyword_field")); } public void testSwitchParser() throws IOException { var settings = Settings.builder().put("index.mapping.total_fields.limit", 1).build(); context = new TestDocumentParserContext(settings); XContentParser parser = createParser(JsonXContent.jsonXContent, "{ \"foo\": \"bar\" }"); DocumentParserContext newContext = context.switchParser(parser); assertNotEquals(context.parser(), newContext.parser()); assertEquals(context.indexSettings(), newContext.indexSettings()); assertEquals(parser, newContext.parser()); assertEquals("1", newContext.indexSettings().getSettings().get("index.mapping.total_fields.limit")); } public void testCreateDynamicMapperBuilderContextFromEmptyContext() throws IOException { var resultFromEmptyParserContext = context.createDynamicMapperBuilderContext(); assertEquals("hey", resultFromEmptyParserContext.buildFullName("hey")); assertFalse(resultFromEmptyParserContext.isSourceSynthetic()); assertFalse(resultFromEmptyParserContext.isDataStream()); assertFalse(resultFromEmptyParserContext.parentObjectContainsDimensions()); assertEquals(ObjectMapper.Defaults.DYNAMIC, resultFromEmptyParserContext.getDynamic()); assertEquals(MapperService.MergeReason.MAPPING_UPDATE, resultFromEmptyParserContext.getMergeReason()); assertFalse(resultFromEmptyParserContext.isInNestedContext()); } public void testCreateDynamicMapperBuilderContext() throws IOException { var mapping = XContentBuilder.builder(XContentType.JSON.xContent()) .startObject() .startObject("_doc") .startObject(DataStreamTimestampFieldMapper.NAME) .field("enabled", "true") .endObject() .startObject("properties") .startObject(DataStreamTimestampFieldMapper.DEFAULT_PATH) .field("type", "date") .endObject() .startObject("foo") .field("type", "passthrough") .field("time_series_dimension", "true") .field("priority", "100") .endObject() .endObject() .endObject() .endObject(); var documentMapper = new MapperServiceTestCase() { @Override protected Settings getIndexSettings() { return Settings.builder().put("index.mapping.source.mode", "synthetic").build(); } }.createDocumentMapper(mapping); var parserContext = new TestDocumentParserContext(documentMapper.mappers(), null); parserContext.path().add("foo"); var resultFromParserContext = parserContext.createDynamicMapperBuilderContext(); assertEquals("foo.hey", resultFromParserContext.buildFullName("hey")); assertTrue(resultFromParserContext.isDataStream()); assertTrue(resultFromParserContext.parentObjectContainsDimensions()); assertEquals(ObjectMapper.Defaults.DYNAMIC, resultFromParserContext.getDynamic()); assertEquals(MapperService.MergeReason.MAPPING_UPDATE, resultFromParserContext.getMergeReason()); assertFalse(resultFromParserContext.isInNestedContext()); } }
DocumentParserContextTests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/internals/ReflectiveStrategy.java
{ "start": 2397, "end": 2640 }
interface ____ { Class<?> loadClass(String className) throws ClassNotFoundException; static Loader forName() { return className -> Class.forName(className, true, Loader.class.getClassLoader()); } } }
Loader
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/merge/NodeMergeTest.java
{ "start": 906, "end": 1095 }
class ____ { @JsonMerge public ObjectNode props = MAPPER.createObjectNode(); { props.put("default", "enabled"); } } static
ObjectNodeWrapper