language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannelTest.java | {
"start": 93310,
"end": 94366
} | class ____
extends TestingPartitionRequestClient {
private ResultPartitionID partitionId;
private ResultSubpartitionIndexSet subpartitionIndexSet;
private int delayMs;
@Override
public void requestSubpartition(
ResultPartitionID partitionId,
ResultSubpartitionIndexSet subpartitionIndexSet,
RemoteInputChannel channel,
int delayMs) {
this.partitionId = partitionId;
this.subpartitionIndexSet = subpartitionIndexSet;
this.delayMs = delayMs;
}
void verifyResult(
ResultPartitionID expectedId, int expectedSubpartitionIndex, int expectedDelayMs) {
assertThat(partitionId).isEqualTo(expectedId);
assertThat(new ResultSubpartitionIndexSet(expectedSubpartitionIndex))
.isEqualTo(subpartitionIndexSet);
assertThat(delayMs).isEqualTo(expectedDelayMs);
}
}
private static final | TestVerifyPartitionRequestClient |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeConverters.java | {
"start": 6295,
"end": 6535
} | class ____ implements Converter<Calendar, OffsetDateTime> {
@Override
public OffsetDateTime convert(Calendar source) {
return calendarToZonedDateTime(source).toOffsetDateTime();
}
}
private static | CalendarToOffsetDateTimeConverter |
java | apache__camel | components/camel-aws/camel-aws2-ses/src/test/java/org/apache/camel/component/aws2/ses/AmazonSESClientMock.java | {
"start": 1261,
"end": 2420
} | class ____ implements SesClient {
private SendEmailRequest sendEmailRequest;
private SendRawEmailRequest sendRawEmailRequest;
public AmazonSESClientMock() {
}
@Override
public SendEmailResponse sendEmail(SendEmailRequest sendEmailRequest) {
this.sendEmailRequest = sendEmailRequest;
return SendEmailResponse.builder().messageId("1").build();
}
@Override
public SendRawEmailResponse sendRawEmail(SendRawEmailRequest sendRawEmailRequest) {
this.sendRawEmailRequest = sendRawEmailRequest;
return SendRawEmailResponse.builder().messageId("1").build();
}
@Override
public SesServiceClientConfiguration serviceClientConfiguration() {
return null;
}
public SendEmailRequest getSendEmailRequest() {
return sendEmailRequest;
}
public SendRawEmailRequest getSendRawEmailRequest() {
return sendRawEmailRequest;
}
@Override
public String serviceName() {
// TODO Auto-generated method stub
return null;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
}
| AmazonSESClientMock |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/function/ResourceHandlerFunctionTests.java | {
"start": 1794,
"end": 8797
} | class ____ {
private final Resource resource = new ClassPathResource("response.txt", getClass());
private final ResourceHandlerFunction handlerFunction = new ResourceHandlerFunction(this.resource, (r, h) -> {});
private ServerResponse.Context context;
private ResourceHttpMessageConverter messageConverter;
@BeforeEach
void createContext() {
this.messageConverter = new ResourceHttpMessageConverter();
ResourceRegionHttpMessageConverter regionConverter = new ResourceRegionHttpMessageConverter();
this.context = () -> Arrays.asList(messageConverter, regionConverter);
}
@Test
void get() throws IOException, ServletException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter));
ServerResponse response = this.handlerFunction.handle(request);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
assertThat(response).isInstanceOf(EntityResponse.class);
@SuppressWarnings("unchecked")
EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response;
assertThat(entityResponse.entity()).isEqualTo(this.resource);
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context);
assertThat(mav).isNull();
assertThat(servletResponse.getStatus()).isEqualTo(200);
byte[] expectedBytes = Files.readAllBytes(this.resource.getFile().toPath());
byte[] actualBytes = servletResponse.getContentAsByteArray();
assertThat(actualBytes).isEqualTo(expectedBytes);
assertThat(servletResponse.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(servletResponse.getContentLength()).isEqualTo(this.resource.contentLength());
}
@Test
void getRange() throws IOException, ServletException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addHeader("Range", "bytes=0-5");
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter));
ServerResponse response = this.handlerFunction.handle(request);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
assertThat(response).isInstanceOf(EntityResponse.class);
@SuppressWarnings("unchecked")
EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response;
assertThat(entityResponse.entity()).isEqualTo(this.resource);
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context);
assertThat(mav).isNull();
assertThat(servletResponse.getStatus()).isEqualTo(206);
byte[] expectedBytes = new byte[6];
try (InputStream is = this.resource.getInputStream()) {
is.read(expectedBytes);
}
byte[] actualBytes = servletResponse.getContentAsByteArray();
assertThat(actualBytes).isEqualTo(expectedBytes);
assertThat(servletResponse.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(servletResponse.getContentLength()).isEqualTo(6);
assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes");
}
@Test
void getInvalidRange() throws IOException, ServletException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
servletRequest.addHeader("Range", "bytes=0-10, 0-10, 0-10, 0-10, 0-10, 0-10");
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter));
ServerResponse response = this.handlerFunction.handle(request);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
assertThat(response).isInstanceOf(EntityResponse.class);
@SuppressWarnings("unchecked")
EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response;
assertThat(entityResponse.entity()).isEqualTo(this.resource);
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context);
assertThat(mav).isNull();
assertThat(servletResponse.getStatus()).isEqualTo(416);
byte[] expectedBytes = Files.readAllBytes(this.resource.getFile().toPath());
byte[] actualBytes = servletResponse.getContentAsByteArray();
assertThat(actualBytes).isEqualTo(expectedBytes);
assertThat(servletResponse.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(servletResponse.getContentLength()).isEqualTo(this.resource.contentLength());
assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes");
}
@Test
void head() throws IOException, ServletException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("HEAD", "/", true);
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter));
ServerResponse response = this.handlerFunction.handle(request);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
assertThat(response).isInstanceOf(EntityResponse.class);
@SuppressWarnings("unchecked")
EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response;
assertThat(entityResponse.entity().getFilename()).isEqualTo(this.resource.getFilename());
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context);
assertThat(mav).isNull();
assertThat(servletResponse.getStatus()).isEqualTo(200);
byte[] actualBytes = servletResponse.getContentAsByteArray();
assertThat(actualBytes).isEmpty();
assertThat(servletResponse.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(servletResponse.getContentLength()).isEqualTo(this.resource.contentLength());
}
@Test
void options() throws ServletException, IOException {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("OPTIONS", "/", true);
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter));
ServerResponse response = this.handlerFunction.handle(request);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.headers().getAllow()).isEqualTo(Set.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS));
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context);
assertThat(mav).isNull();
assertThat(servletResponse.getStatus()).isEqualTo(200);
String allowHeader = servletResponse.getHeader("Allow");
String[] methods = StringUtils.tokenizeToStringArray(allowHeader, ",");
assertThat(methods).containsExactlyInAnyOrder("GET","HEAD","OPTIONS");
byte[] actualBytes = servletResponse.getContentAsByteArray();
assertThat(actualBytes).isEmpty();
}
}
| ResourceHandlerFunctionTests |
java | quarkusio__quarkus | extensions/hibernate-search-orm-elasticsearch/deployment/src/test/java/io/quarkus/hibernate/search/orm/elasticsearch/test/configuration/ConfigActiveFalseDynamicInjectionTest.java | {
"start": 803,
"end": 4029
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class).addClass(IndexedEntity.class))
.withConfigurationResource("application.properties")
.overrideConfigKey("quarkus.hibernate-search-orm.active", "false");
@Test
public void searchMapping() {
SearchMapping searchMapping = Arc.container().instance(SearchMapping.class).get();
// The bean is always available to be injected during static init
// since we don't know whether HSearch will be active at runtime.
// So the bean cannot be null.
assertThat(searchMapping).isNotNull();
// However, any attempt to use it at runtime will fail.
assertThatThrownBy(() -> searchMapping.allIndexedEntities())
.isInstanceOf(InactiveBeanException.class)
.hasMessageContainingAll(
"Hibernate Search for persistence unit '<default>' was deactivated through configuration properties",
"To avoid this exception while keeping the bean inactive", // Message from Arc with generic hints
"To activate Hibernate Search, set configuration property 'quarkus.hibernate-search-orm.active' to 'true'");
// Hibernate Search APIs also throw exceptions,
// even if the messages are less explicit (we can't really do better).
assertThatThrownBy(() -> Search.mapping(Arc.container().instance(SessionFactory.class).get()))
.isInstanceOf(SearchException.class)
.hasMessageContaining("Hibernate Search was not initialized");
}
@Test
public void searchSession() {
SearchSession searchSession = Arc.container().instance(SearchSession.class).get();
// The bean is always available to be injected during static init
// since we don't know whether HSearch will be active at runtime.
// So the bean cannot be null.
assertThat(searchSession).isNotNull();
// However, any attempt to use it at runtime will fail.
assertThatThrownBy(() -> searchSession.search(IndexedEntity.class))
.isInstanceOf(InactiveBeanException.class)
.hasMessageContainingAll(
"Hibernate Search for persistence unit '<default>' was deactivated through configuration properties",
"To avoid this exception while keeping the bean inactive", // Message from Arc with generic hints
"To activate Hibernate Search, set configuration property 'quarkus.hibernate-search-orm.active' to 'true'");
// Hibernate Search APIs also throw exceptions,
// even if the messages are less explicit (we can't really do better).
try (Session session = Arc.container().instance(SessionFactory.class).get().openSession()) {
assertThatThrownBy(() -> Search.session(session).search(IndexedEntity.class))
.isInstanceOf(SearchException.class)
.hasMessageContaining("Hibernate Search was not initialized");
}
}
}
| ConfigActiveFalseDynamicInjectionTest |
java | apache__camel | components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlConsumerTest.java | {
"start": 1473,
"end": 3230
} | class ____ extends CamelTestSupport {
EmbeddedDatabase db;
@Override
public void doPreSetup() throws Exception {
db = new EmbeddedDatabaseBuilder()
.setName(getClass().getSimpleName())
.setType(EmbeddedDatabaseType.H2)
.addScript("sql/createAndPopulateDatabase.sql").build();
}
@Override
public void doPostTearDown() throws Exception {
if (db != null) {
db.shutdown();
}
}
@Test
public void testConsume() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(3);
MockEndpoint.assertIsSatisfied(context);
List<Exchange> exchanges = mock.getReceivedExchanges();
assertTrue(exchanges.size() >= 3);
assertEquals(1, exchanges.get(0).getIn().getBody(Map.class).get("ID"));
assertEquals("Camel", exchanges.get(0).getIn().getBody(Map.class).get("PROJECT"));
assertEquals(2, exchanges.get(1).getIn().getBody(Map.class).get("ID"));
assertEquals("AMQ", exchanges.get(1).getIn().getBody(Map.class).get("PROJECT"));
assertEquals(3, exchanges.get(2).getIn().getBody(Map.class).get("ID"));
assertEquals("Linux", exchanges.get(2).getIn().getBody(Map.class).get("PROJECT"));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
getContext().getComponent("sql", SqlComponent.class).setDataSource(db);
from("sql:select * from projects order by id?initialDelay=0&delay=50")
.to("mock:result");
}
};
}
}
| SqlConsumerTest |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java | {
"start": 28675,
"end": 28976
} | interface ____ {
@AliasFor("myValue")
String value() default "";
@AliasFor("value")
String myValue() default "";
String additional() default "direct";
String[] additionalArray() default "direct";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @ | DirectAnnotation |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/AbstractClassAssert.java | {
"start": 40741,
"end": 41508
} | class ____ extends SealedClass {}
*
* // this assertion succeeds:
* assertThat(SealedClass.class).isSealed();
*
* // this assertion fails:
* assertThat(NonSealedClass.class).isSealed();</code></pre>
*
* @return {@code this} assertions object
* @throws AssertionError if {@code actual} is {@code null}.
* @throws AssertionError if the actual {@code Class} is not sealed.
*
* @since 3.25.0
*/
public SELF isSealed() {
isNotNull();
assertIsSealed();
return myself;
}
private void assertIsSealed() {
if (!isSealed(actual)) throw assertionError(shouldBeSealed(actual));
}
/**
* Verifies that the actual {@code Class} is not sealed.
* <p>
* Example:
* <pre><code class='java'> sealed | NonSealedClass |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ConfigLoaderExtension.java | {
"start": 624,
"end": 752
} | class ____ implements BeforeAllCallback {
@Override
public void beforeAll(ExtensionContext context) {
}
}
| ConfigLoaderExtension |
java | spring-projects__spring-framework | spring-core/src/testFixtures/java/org/springframework/core/testfixture/TimeStamped.java | {
"start": 685,
"end": 843
} | interface ____ be implemented by cacheable objects or cache entries,
* to enable the freshness of objects to be checked.
*
* @author Rod Johnson
*/
public | can |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/ingest/SimulateExecutionService.java | {
"start": 1033,
"end": 4079
} | class ____ {
private static final String THREAD_POOL_NAME = ThreadPool.Names.MANAGEMENT;
private final ThreadPool threadPool;
SimulateExecutionService(ThreadPool threadPool) {
this.threadPool = threadPool;
}
static void executeDocument(
Pipeline pipeline,
IngestDocument ingestDocument,
boolean verbose,
BiConsumer<SimulateDocumentResult, Exception> handler
) {
if (verbose) {
List<SimulateProcessorResult> processorResultList = new CopyOnWriteArrayList<>();
CompoundProcessor verbosePipelineProcessor = decorate(pipeline.getCompoundProcessor(), null, processorResultList);
Pipeline verbosePipeline = new Pipeline(
pipeline.getId(),
pipeline.getDescription(),
pipeline.getVersion(),
pipeline.getMetadata(),
verbosePipelineProcessor,
pipeline.getFieldAccessPattern(),
pipeline.getDeprecated(),
pipeline.getCreatedDateMillis().orElse(null),
pipeline.getModifiedDateMillis().orElse(null)
);
ingestDocument.executePipeline(verbosePipeline, (result, e) -> {
handler.accept(new SimulateDocumentVerboseResult(processorResultList), e);
});
} else {
ingestDocument.executePipeline(pipeline, (result, e) -> {
if (e == null) {
handler.accept(new SimulateDocumentBaseResult(result), null);
} else {
handler.accept(new SimulateDocumentBaseResult(e), null);
}
});
}
}
public void execute(SimulatePipelineRequest.Parsed request, ActionListener<SimulatePipelineResponse> listener) {
threadPool.executor(THREAD_POOL_NAME).execute(ActionRunnable.wrap(listener, l -> {
final AtomicInteger counter = new AtomicInteger();
final List<SimulateDocumentResult> responses = new CopyOnWriteArrayList<>(
new SimulateDocumentBaseResult[request.documents().size()]
);
if (request.documents().isEmpty()) {
l.onResponse(new SimulatePipelineResponse(request.pipeline().getId(), request.verbose(), responses));
return;
}
int iter = 0;
for (IngestDocument ingestDocument : request.documents()) {
final int index = iter;
executeDocument(request.pipeline(), ingestDocument, request.verbose(), (response, e) -> {
if (response != null) {
responses.set(index, response);
}
if (counter.incrementAndGet() == request.documents().size()) {
l.onResponse(new SimulatePipelineResponse(request.pipeline().getId(), request.verbose(), responses));
}
});
iter++;
}
}));
}
}
| SimulateExecutionService |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ParseIpLeadingZerosAreOctalEvaluator.java | {
"start": 1195,
"end": 4915
} | class ____ extends AbstractConvertFunction.AbstractEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ParseIpLeadingZerosAreOctalEvaluator.class);
private final EvalOperator.ExpressionEvaluator string;
private final BreakingBytesRefBuilder scratch;
public ParseIpLeadingZerosAreOctalEvaluator(Source source,
EvalOperator.ExpressionEvaluator string, BreakingBytesRefBuilder scratch,
DriverContext driverContext) {
super(driverContext, source);
this.string = string;
this.scratch = scratch;
}
@Override
public EvalOperator.ExpressionEvaluator next() {
return string;
}
@Override
public Block evalVector(Vector v) {
BytesRefVector vector = (BytesRefVector) v;
int positionCount = v.getPositionCount();
BytesRef scratchPad = new BytesRef();
if (vector.isConstant()) {
try {
return driverContext.blockFactory().newConstantBytesRefBlockWith(evalValue(vector, 0, scratchPad), positionCount);
} catch (IllegalArgumentException e) {
registerException(e);
return driverContext.blockFactory().newConstantNullBlock(positionCount);
}
}
try (BytesRefBlock.Builder builder = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) {
for (int p = 0; p < positionCount; p++) {
try {
builder.appendBytesRef(evalValue(vector, p, scratchPad));
} catch (IllegalArgumentException e) {
registerException(e);
builder.appendNull();
}
}
return builder.build();
}
}
private BytesRef evalValue(BytesRefVector container, int index, BytesRef scratchPad) {
BytesRef value = container.getBytesRef(index, scratchPad);
return ParseIp.leadingZerosAreOctal(value, this.scratch);
}
@Override
public Block evalBlock(Block b) {
BytesRefBlock block = (BytesRefBlock) b;
int positionCount = block.getPositionCount();
try (BytesRefBlock.Builder builder = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) {
BytesRef scratchPad = new BytesRef();
for (int p = 0; p < positionCount; p++) {
int valueCount = block.getValueCount(p);
int start = block.getFirstValueIndex(p);
int end = start + valueCount;
boolean positionOpened = false;
boolean valuesAppended = false;
for (int i = start; i < end; i++) {
try {
BytesRef value = evalValue(block, i, scratchPad);
if (positionOpened == false && valueCount > 1) {
builder.beginPositionEntry();
positionOpened = true;
}
builder.appendBytesRef(value);
valuesAppended = true;
} catch (IllegalArgumentException e) {
registerException(e);
}
}
if (valuesAppended == false) {
builder.appendNull();
} else if (positionOpened) {
builder.endPositionEntry();
}
}
return builder.build();
}
}
private BytesRef evalValue(BytesRefBlock container, int index, BytesRef scratchPad) {
BytesRef value = container.getBytesRef(index, scratchPad);
return ParseIp.leadingZerosAreOctal(value, this.scratch);
}
@Override
public String toString() {
return "ParseIpLeadingZerosAreOctalEvaluator[" + "string=" + string + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(string, scratch);
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += string.baseRamBytesUsed();
return baseRamBytesUsed;
}
public static | ParseIpLeadingZerosAreOctalEvaluator |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/JmsRouteUsingSpringAndJmsNameIT.java | {
"start": 1196,
"end": 1615
} | class ____ extends JmsRouteUsingSpringIT {
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"org/apache/camel/component/jms/integration/spring/jmsRouteUsingSpringAndJmsName.xml");
}
@BeforeEach
public void setUp() throws Exception {
componentName = "jms";
}
}
| JmsRouteUsingSpringAndJmsNameIT |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/condition/AnyOf_anyOf_with_array_Test.java | {
"start": 1033,
"end": 1469
} | class ____ {
@Test
void should_create_new_AnyOf_with_passed_Conditions() {
Condition<Object>[] conditions = array(new TestCondition<>(), new TestCondition<>());
Condition<Object> created = AnyOf.anyOf(conditions);
assertThat(created.getClass()).isEqualTo(AnyOf.class);
AnyOf<Object> anyOf = (AnyOf<Object>) created;
assertThat(anyOf.conditions).isEqualTo(newArrayList(conditions));
}
}
| AnyOf_anyOf_with_array_Test |
java | spring-projects__spring-boot | module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java | {
"start": 5880,
"end": 5967
} | class ____ implements ExposableWebEndpoint {
}
abstract static | TestExposableWebEndpoint |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java | {
"start": 4241,
"end": 23981
} | class ____ {
private final MockHttpServletRequest request = new MockHttpServletRequest();
@BeforeEach
void setup() {
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request));
}
@AfterEach
void reset() {
RequestContextHolder.resetRequestAttributes();
}
@Test
void fromControllerPlain() {
UriComponents uriComponents = fromController(PersonControllerImpl.class).build();
assertThat(uriComponents.toUriString()).endsWith("/people");
}
@Test
void fromControllerUriTemplate() {
UriComponents uriComponents = fromController(PersonsAddressesController.class).buildAndExpand(15);
assertThat(uriComponents.toUriString()).endsWith("/people/15/addresses");
}
@Test
void fromControllerSubResource() {
UriComponents uriComponents = fromController(PersonControllerImpl.class).pathSegment("something").build();
assertThat(uriComponents.toUriString()).endsWith("/people/something");
}
@Test
void fromControllerTwoTypeLevelMappings() {
UriComponents uriComponents = fromController(InvalidController.class).build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/persons");
}
@Test
void fromControllerNotMapped() {
UriComponents uriComponents = fromController(UnmappedController.class).build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/");
}
@Test
void fromControllerWithCustomBaseUrlViaStaticCall() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base");
UriComponents uriComponents = fromController(builder, PersonControllerImpl.class).build();
assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/people");
assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base");
}
@Test
void fromControllerWithCustomBaseUrlViaInstance() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base");
MvcUriComponentsBuilder mvcBuilder = relativeTo(builder);
UriComponents uriComponents = mvcBuilder.withController(PersonControllerImpl.class).build();
assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/people");
assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base");
}
@Test
void fromControllerWithPlaceholder() {
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("test",
Map.of("context.test.mapping", "people")));
initWebApplicationContext(WebConfig.class, environment);
UriComponents uriComponents = fromController(ConfigurablePersonController.class).build();
assertThat(uriComponents.toUriString()).endsWith("/people");
}
@Test
void fromControllerWithPlaceholderAndMissingValue() {
StandardEnvironment environment = new StandardEnvironment();
assertThat(environment.containsProperty("context.test.mapping")).isFalse();
initWebApplicationContext(WebConfig.class, environment);
UriComponents uriComponents = fromController(ConfigurablePersonController.class).build();
assertThat(uriComponents.toUriString()).endsWith("/${context.test.mapping}");
}
@Test
void fromControllerWithPlaceholderAndNoValueResolver() {
UriComponents uriComponents = fromController(ConfigurablePersonController.class).build();
assertThat(uriComponents.toUriString()).endsWith("/${context.test.mapping}");
}
@Test
void usesForwardedHostAsHostIfHeaderIsSet() throws Exception {
this.request.setScheme("https");
this.request.addHeader("X-Forwarded-Host", "somethingDifferent");
adaptRequestFromForwardedHeaders();
UriComponents uriComponents = fromController(PersonControllerImpl.class).build();
assertThat(uriComponents.toUriString()).startsWith("https://somethingDifferent");
}
@Test
void usesForwardedHostAndPortFromHeader() throws Exception {
this.request.setScheme("https");
request.addHeader("X-Forwarded-Host", "foobar:8088");
adaptRequestFromForwardedHeaders();
UriComponents uriComponents = fromController(PersonControllerImpl.class).build();
assertThat(uriComponents.toUriString()).startsWith("https://foobar:8088");
}
@Test
void usesFirstHostOfXForwardedHost() throws Exception {
this.request.setScheme("https");
this.request.addHeader("X-Forwarded-Host", "barfoo:8888, localhost:8088");
adaptRequestFromForwardedHeaders();
UriComponents uriComponents = fromController(PersonControllerImpl.class).build();
assertThat(uriComponents.toUriString()).startsWith("https://barfoo:8888");
}
// SPR-16668
private void adaptRequestFromForwardedHeaders() throws Exception {
MockFilterChain chain = new MockFilterChain();
new ForwardedHeaderFilter().doFilter(this.request, new MockHttpServletResponse(), chain);
HttpServletRequest adaptedRequest = (HttpServletRequest) chain.getRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(adaptedRequest));
}
@Test
void fromMethodNamePathVariable() {
UriComponents uriComponents = fromMethodName(ControllerWithMethods.class,
"methodWithPathVariable", "1").build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/something/1/foo");
}
@Test
void fromMethodNameTypeLevelPathVariable() {
this.request.setContextPath("/myapp");
UriComponents uriComponents = fromMethodName(
PersonsAddressesController.class, "getAddressesForCountry", "DE").buildAndExpand("1");
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/myapp/people/1/addresses/DE");
}
@Test
void fromMethodNameTwoPathVariables() {
UriComponents uriComponents = fromMethodName(
ControllerWithMethods.class, "methodWithTwoPathVariables", 1, "2009-10-31").build();
assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo/2009-10-31");
}
@Test
void fromMethodNameWithPathVarAndRequestParam() {
UriComponents uriComponents = fromMethodName(
ControllerWithMethods.class, "methodForNextPage", "1", 10, 5).build();
assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo");
MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
assertThat(queryParams.get("limit")).contains("5");
assertThat(queryParams.get("offset")).contains("10");
}
@Test // SPR-12977
public void fromMethodNameWithBridgedMethod() {
UriComponents uriComponents = fromMethodName(PersonCrudController.class, "get", (long) 42).build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/42");
}
@Test // SPR-11391
public void fromMethodNameTypeLevelPathVariableWithoutArgumentValue() {
UriComponents uriComponents = fromMethodName(UserContactController.class, "showCreate", 123).build();
assertThat(uriComponents.getPath()).isEqualTo("/user/123/contacts/create");
}
@Test
void fromMethodNameInUnmappedController() {
UriComponents uriComponents = fromMethodName(UnmappedController.class, "requestMappingMethod").build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/");
}
@Test // gh-29897
public void fromMethodNameInUnmappedControllerMethod() {
UriComponents uriComponents = fromMethodName(UnmappedControllerMethod.class, "getMethod").build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/path");
}
@Test
void fromMethodNameWithCustomBaseUrlViaStaticCall() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base");
UriComponents uriComponents = fromMethodName(builder, ControllerWithMethods.class,
"methodWithPathVariable", "1").build();
assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/something/1/foo");
assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base");
}
@Test
void fromMethodNameWithCustomBaseUrlViaInstance() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base");
MvcUriComponentsBuilder mvcBuilder = relativeTo(builder);
UriComponents uriComponents = mvcBuilder.withMethodName(ControllerWithMethods.class,
"methodWithPathVariable", "1").build();
assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/something/1/foo");
assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base");
}
@Test // SPR-14405
public void fromMethodNameWithOptionalParam() {
UriComponents uriComponents = fromMethodName(ControllerWithMethods.class,
"methodWithOptionalParam", new Object[] {null}).build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/something/optional-param");
}
@Test // gh-22656
public void fromMethodNameWithOptionalNamedParam() {
UriComponents uriComponents = fromMethodName(ControllerWithMethods.class,
"methodWithOptionalNamedParam", Optional.of("foo")).build();
assertThat(uriComponents.toUriString())
.isEqualTo("http://localhost/something/optional-param-with-name?search=foo");
}
@Test
void fromMethodNameWithMetaAnnotation() {
UriComponents uriComponents = fromMethodName(MetaAnnotationController.class, "handleInput").build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/input");
}
@Test
void fromMethodNameConfigurablePath() {
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("test",
Map.of("method.test.mapping", "custom")));
initWebApplicationContext(WebConfig.class, environment);
UriComponents uriComponents = fromMethodName(ControllerWithMethods.class,
"methodWithConfigurableMapping", "1").build();
assertThat(uriComponents.toUriString()).isEqualTo("http://localhost/something/custom/1/foo");
}
@Test // gh-35348
void fromMethodNameConfigurablePathSpEL() {
try {
System.setProperty("customMapping", "custom");
StandardEnvironment environment = new StandardEnvironment();
initWebApplicationContext(WebConfig.class, environment);
UriComponents uric = fromMethodName(ControllerWithMethods.class, "methodWithSpEL", "1").build();
assertThat(uric.toUriString()).isEqualTo("http://localhost/something/custom/1/foo");
}
finally {
System.clearProperty("customMapping");
}
}
@Test
void fromMethodNameWithAnnotationsOnInterface() {
initWebApplicationContext(WebConfig.class);
UriComponents uriComponents = fromMethodName(HelloController.class, "get", "test").build();
assertThat(uriComponents.toString()).isEqualTo("http://localhost/hello/test");
}
@Test
void fromMethodCallOnSubclass() {
UriComponents uriComponents = fromMethodCall(on(ExtendedController.class).myMethod(null)).build();
assertThat(uriComponents.toUriString()).startsWith("http://localhost");
assertThat(uriComponents.toUriString()).endsWith("/extended/else");
}
@Test
void fromMethodCallPlain() {
UriComponents uriComponents = fromMethodCall(on(ControllerWithMethods.class).myMethod(null)).build();
assertThat(uriComponents.toUriString()).startsWith("http://localhost");
assertThat(uriComponents.toUriString()).endsWith("/something/else");
}
@Test
void fromMethodCallPlainWithNoArguments() {
UriComponents uriComponents = fromMethodCall(on(ControllerWithMethods.class).myMethod()).build();
assertThat(uriComponents.toUriString()).startsWith("http://localhost");
assertThat(uriComponents.toUriString()).endsWith("/something/noarg");
}
@Test
void fromMethodCallPlainOnInterface() {
UriComponents uriComponents = fromMethodCall(on(ControllerInterface.class).myMethod(null)).build();
assertThat(uriComponents.toUriString()).startsWith("http://localhost");
assertThat(uriComponents.toUriString()).endsWith("/something/else");
}
@Test
void fromMethodCallPlainWithNoArgumentsOnInterface() {
UriComponents uriComponents = fromMethodCall(on(ControllerInterface.class).myMethod()).build();
assertThat(uriComponents.toUriString()).startsWith("http://localhost");
assertThat(uriComponents.toUriString()).endsWith("/something/noarg");
}
@Test
void fromMethodCallWithTypeLevelUriVars() {
UriComponents uriComponents = fromMethodCall(
on(PersonsAddressesController.class).getAddressesForCountry("DE")).buildAndExpand(15);
assertThat(uriComponents.toUriString()).endsWith("/people/15/addresses/DE");
}
@Test
void fromMethodCallWithPathVariable() {
UriComponents uriComponents = fromMethodCall(
on(ControllerWithMethods.class).methodWithPathVariable("1")).build();
assertThat(uriComponents.toUriString()).startsWith("http://localhost");
assertThat(uriComponents.toUriString()).endsWith("/something/1/foo");
}
@Test
void fromMethodCallWithPathVariableAndRequestParams() {
UriComponents uriComponents = fromMethodCall(
on(ControllerWithMethods.class).methodForNextPage("1", 10, 5)).build();
assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo");
MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
assertThat(queryParams.get("limit")).contains("5");
assertThat(queryParams.get("offset")).contains("10");
}
@Test
void fromMethodCallWithPathVariableAndMultiValueRequestParams() {
UriComponents uriComponents = fromMethodCall(
on(ControllerWithMethods.class).methodWithMultiValueRequestParams("1", Arrays.asList(3, 7), 5)).build();
assertThat(uriComponents.getPath()).isEqualTo("/something/1/foo");
MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
assertThat(queryParams.get("limit")).contains("5");
assertThat(queryParams.get("items")).containsExactly("3", "7");
}
@Test
void fromMethodCallWithCustomBaseUrlViaStaticCall() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base");
UriComponents uriComponents = fromMethodCall(builder, on(ControllerWithMethods.class).myMethod(null)).build();
assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/something/else");
assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base");
}
@Test
void fromMethodCallWithCustomBaseUrlViaInstance() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base");
MvcUriComponentsBuilder mvcBuilder = relativeTo(builder);
UriComponents result = mvcBuilder.withMethodCall(on(ControllerWithMethods.class).myMethod(null)).build();
assertThat(result.toString()).isEqualTo("https://example.org:9090/base/something/else");
assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base");
}
@Test // SPR-16710
public void fromMethodCallWithModelAndViewReturnType() {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithModelAndView.class).getBooking(21L)).buildAndExpand(42);
assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21");
}
@Test // SPR-16710
public void fromMethodCallWithObjectReturnType() {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithObject.class).getBooking(21L)).buildAndExpand(42);
assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21");
}
@Test // SPR-16710
public void fromMethodCallWithStringReturnType() {
assertThatIllegalStateException().isThrownBy(() -> {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithString.class).getBooking(21L)).buildAndExpand(42);
uriComponents.encode().toUri().toString();
});
}
@Test // SPR-16710
public void fromMethodNameWithStringReturnType() {
UriComponents uriComponents = fromMethodName(
BookingControllerWithString.class, "getBooking", 21L).buildAndExpand(42);
assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21");
}
@Test // gh-30210
public void fromMethodCallWithCharSequenceReturnType() {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithCharSequence.class).getBooking(21L)).buildAndExpand(42);
assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21");
}
@Test // gh-30210
public void fromMethodCallWithJdbc30115ReturnType() {
UriComponents uriComponents = fromMethodCall(
on(BookingControllerWithJdbcSavepoint.class).getBooking(21L)).buildAndExpand(42);
assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21");
}
@Test
void fromMappingNamePlain() {
initWebApplicationContext(WebConfig.class);
this.request.setServerName("example.org");
this.request.setServerPort(9999);
this.request.setContextPath("/base");
String mappingName = "PAC#getAddressesForCountry";
String url = fromMappingName(mappingName).arg(0, "DE").buildAndExpand(123);
assertThat(url).isEqualTo("/base/people/123/addresses/DE");
}
@Test
void fromMappingNameWithCustomBaseUrl() {
initWebApplicationContext(WebConfig.class);
UriComponentsBuilder baseUrl = UriComponentsBuilder.fromUriString("https://example.org:9999/base");
MvcUriComponentsBuilder mvcBuilder = relativeTo(baseUrl);
String url = mvcBuilder.withMappingName("PAC#getAddressesForCountry").arg(0, "DE").buildAndExpand(123);
assertThat(url).isEqualTo("https://example.org:9999/base/people/123/addresses/DE");
}
@Test // SPR-17027
public void fromMappingNameWithEncoding() {
initWebApplicationContext(WebConfig.class);
this.request.setServerName("example.org");
this.request.setServerPort(9999);
this.request.setContextPath("/base");
String mappingName = "PAC#getAddressesForCountry";
String url = fromMappingName(mappingName).arg(0, "DE;FR").encode().buildAndExpand("_+_");
assertThat(url).isEqualTo("/base/people/_%2B_/addresses/DE%3BFR");
}
@Test
void fromMappingNameWithPathWithoutLeadingSlash() {
initWebApplicationContext(PathWithoutLeadingSlashConfig.class);
this.request.setServerName("example.org");
this.request.setServerPort(9999);
this.request.setContextPath("/base");
String mappingName = "PWLSC#getAddressesForCountry";
String url = fromMappingName(mappingName).arg(0, "DE;FR").encode().buildAndExpand("_+_");
assertThat(url).isEqualTo("/base/people/DE%3BFR");
}
@Test
void fromControllerWithPrefix() {
initWebApplicationContext(PathPrefixWebConfig.class);
this.request.setScheme("https");
this.request.setServerName("example.org");
this.request.setServerPort(9999);
this.request.setContextPath("/base");
assertThat(fromController(PersonsAddressesController.class).buildAndExpand("123").toString())
.isEqualTo("https://example.org:9999/base/api/people/123/addresses");
}
@Test
void fromMethodWithPrefix() {
initWebApplicationContext(PathPrefixWebConfig.class);
this.request.setScheme("https");
this.request.setServerName("example.org");
this.request.setServerPort(9999);
this.request.setContextPath("/base");
String url = fromMethodCall(on(PersonsAddressesController.class)
.getAddressesForCountry("DE"))
.buildAndExpand("123")
.toString();
assertThat(url).isEqualTo("https://example.org:9999/base/api/people/123/addresses/DE");
}
private void initWebApplicationContext(Class<?> configClass) {
initWebApplicationContext(configClass, null);
}
private void initWebApplicationContext(Class<?> configClass, @Nullable ConfigurableEnvironment environment) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
if (environment != null) {
context.setEnvironment(environment);
}
context.setServletContext(new MockServletContext());
context.register(configClass);
context.refresh();
this.request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
}
static | MvcUriComponentsBuilderTests |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_createError.java | {
"start": 1117,
"end": 1394
} | class ____ {
private MyErrorList<String> values;
public MyErrorList<String> getValues() {
return values;
}
public void setValues(MyErrorList<String> values) {
this.values = values;
}
}
public static | Model |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterJobCommitEvent.java | {
"start": 972,
"end": 1379
} | class ____ extends CommitterEvent {
private JobId jobID;
private JobContext jobContext;
public CommitterJobCommitEvent(JobId jobID, JobContext jobContext) {
super(CommitterEventType.JOB_COMMIT);
this.jobID = jobID;
this.jobContext = jobContext;
}
public JobId getJobID() {
return jobID;
}
public JobContext getJobContext() {
return jobContext;
}
}
| CommitterJobCommitEvent |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/MySingleMethodNoBodyBean.java | {
"start": 852,
"end": 953
} | class ____ {
public String saySomething() {
return "Hello";
}
}
| MySingleMethodNoBodyBean |
java | apache__camel | core/camel-core-processor/src/main/java/org/apache/camel/processor/loadbalancer/WeightedLoadBalancer.java | {
"start": 893,
"end": 2399
} | class ____ extends QueueLoadBalancer {
protected final List<DistributionRatio> ratios;
protected final int distributionRatioSum;
protected int runtimeRatioSum;
transient int lastIndex = -1;
public WeightedLoadBalancer(List<Integer> distributionRatios) {
this.ratios = distributionRatios.stream()
.map(DistributionRatio::new)
.toList();
this.distributionRatioSum = ratios.stream()
.mapToInt(DistributionRatio::getDistributionWeight).sum();
this.runtimeRatioSum = distributionRatioSum;
}
public int getLastChosenProcessorIndex() {
return lastIndex;
}
@Override
protected void doStart() throws Exception {
super.doStart();
if (getProcessors().size() != ratios.size()) {
throw new IllegalArgumentException(
"Loadbalacing with " + getProcessors().size()
+ " should match number of distributions " + ratios.size());
}
}
protected void decrementSum() {
if (--runtimeRatioSum == 0) {
// every processor is exhausted, reload for a new distribution round
reset();
}
}
protected void reset() {
for (DistributionRatio ratio : ratios) {
ratio.reset();
}
runtimeRatioSum = distributionRatioSum;
}
public List<DistributionRatio> getRatios() {
return ratios;
}
}
| WeightedLoadBalancer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/BundleDeserializationCastTest.java | {
"start": 987,
"end": 1677
} | class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(BundleDeserializationCast.class, getClass())
.addSourceFile("testdata/stubs/android/os/Bundle.java")
.addSourceFile("testdata/stubs/android/os/Parcel.java")
.addSourceFile("testdata/stubs/android/os/Parcelable.java")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void positiveCaseGetCustomList() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import android.os.Bundle;
import java.util.LinkedList;
public | BundleDeserializationCastTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/expiring/ExpiringCredentialRefreshingLogin.java | {
"start": 1802,
"end": 2452
} | class ____ {
public LoginContext createLoginContext(ExpiringCredentialRefreshingLogin expiringCredentialRefreshingLogin)
throws LoginException {
return new LoginContext(expiringCredentialRefreshingLogin.contextName(),
expiringCredentialRefreshingLogin.subject(), expiringCredentialRefreshingLogin.callbackHandler(),
expiringCredentialRefreshingLogin.configuration());
}
public void refresherThreadStarted() {
// empty
}
public void refresherThreadDone() {
// empty
}
}
private static | LoginContextFactory |
java | google__guice | extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProvider2Test.java | {
"start": 31479,
"end": 34932
} | interface ____ {
Car create(@Assisted("paint") Color paint, @Assisted("paint") Color morePaint);
}
@Test
public void testDuplicateKeys() {
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(DoubleToneCarFactory.class)
.toProvider(FactoryProvider.newFactory(DoubleToneCarFactory.class, Maxima.class));
}
});
fail();
} catch (CreationException expected) {
assertContains(
expected.getMessage(),
"FactoryProvider2Test$Color annotated with @Assisted("
+ Annotations.memberValueString("value", "paint")
+ ") was bound multiple times.");
}
}
@Test
public void testMethodInterceptorsOnAssistedTypes() {
assumeTrue(InternalFlags.isBytecodeGenEnabled());
final AtomicInteger invocationCount = new AtomicInteger();
final MethodInterceptor interceptor =
new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
invocationCount.incrementAndGet();
return methodInvocation.proceed();
}
};
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.any(), interceptor);
bind(Double.class).toInstance(5.0d);
bind(ColoredCarFactory.class)
.toProvider(FactoryProvider.newFactory(ColoredCarFactory.class, Mustang.class));
}
});
ColoredCarFactory factory = injector.getInstance(ColoredCarFactory.class);
Mustang mustang = (Mustang) factory.create(Color.GREEN);
assertEquals(0, invocationCount.get());
mustang.drive();
assertEquals(1, invocationCount.get());
}
/**
* Our factories aren't reusable across injectors. Although this behaviour isn't something we
* like, I have a test case to make sure the error message is pretty.
*/
@Test
public void testFactoryReuseErrorMessageIsPretty() {
final Provider<ColoredCarFactory> factoryProvider =
FactoryProvider.newFactory(ColoredCarFactory.class, Mustang.class);
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Double.class).toInstance(5.0d);
bind(ColoredCarFactory.class).toProvider(factoryProvider);
}
});
try {
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Double.class).toInstance(5.0d);
bind(ColoredCarFactory.class).toProvider(factoryProvider);
}
});
fail();
} catch (CreationException expected) {
assertContains(
expected.getMessage(), "Factories.create() factories may only be used in one Injector!");
}
}
@Test
public void testNonAssistedFactoryMethodParameter() {
try {
FactoryProvider.newFactory(NamedParameterFactory.class, Mustang.class);
fail();
} catch (ConfigurationException expected) {
assertContains(
expected.getMessage(),
"Only @Assisted is allowed for factory parameters, but found @Named");
}
}
| DoubleToneCarFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java | {
"start": 15736,
"end": 16479
} | class ____ {
private int unused;
private int unusedInt;
private static final int UNUSED_CONSTANT = 5;
private int ignored;
private int customUnused1;
private int customUnused2;
private int prefixUnused1Field;
private int prefixUnused2Field;
}
""")
.setArgs(
"-XepOpt:Unused:exemptNames=customUnused1,customUnused2",
"-XepOpt:Unused:exemptPrefixes=prefixunused1,prefixunused2")
.doTest();
}
@Test
public void suppressions() {
helper
.addSourceLines(
"Unuseds.java",
"""
package unusedvars;
| ExemptedByName |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialIntersectsGeoPointDocValuesAndConstantGridEvaluator.java | {
"start": 3904,
"end": 4904
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory encodedPoints;
private final long gridId;
private final DataType gridType;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory encodedPoints,
long gridId, DataType gridType) {
this.source = source;
this.encodedPoints = encodedPoints;
this.gridId = gridId;
this.gridType = gridType;
}
@Override
public SpatialIntersectsGeoPointDocValuesAndConstantGridEvaluator get(DriverContext context) {
return new SpatialIntersectsGeoPointDocValuesAndConstantGridEvaluator(source, encodedPoints.get(context), gridId, gridType, context);
}
@Override
public String toString() {
return "SpatialIntersectsGeoPointDocValuesAndConstantGridEvaluator[" + "encodedPoints=" + encodedPoints + ", gridId=" + gridId + ", gridType=" + gridType + "]";
}
}
}
| Factory |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/functions/Functions.java | {
"start": 20979,
"end": 21655
} | class ____<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> implements Function<Object[], R> {
final Function9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> f;
Array9Func(Function9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> f) {
this.f = f;
}
@SuppressWarnings("unchecked")
@Override
public R apply(Object[] a) throws Throwable {
if (a.length != 9) {
throw new IllegalArgumentException("Array of size 9 expected but got " + a.length);
}
return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3], (T5)a[4], (T6)a[5], (T7)a[6], (T8)a[7], (T9)a[8]);
}
}
static final | Array9Func |
java | spring-projects__spring-framework | spring-beans/src/jmh/java/org/springframework/beans/BeanUtilsBenchmark.java | {
"start": 1799,
"end": 1980
} | class ____ {
private final int value1;
private final String value2;
TestClass2(int value1, String value2) {
this.value1 = value1;
this.value2 = value2;
}
}
}
| TestClass2 |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/JsonNode.java | {
"start": 513,
"end": 1733
} | class ____ all JSON nodes, which form the basis of JSON
* Tree Model that Jackson implements.
* One way to think of these nodes is to consider them
* similar to DOM nodes in XML DOM trees.
*<p>
* As a general design rule, most accessors ("getters") are included
* in this base class, to allow for traversing structure without
* type casts. Most mutators, however, need to be accessed through
* specific sub-classes (such as <code>ObjectNode</code>
* and <code>ArrayNode</code>).
* This seems sensible because proper type
* information is generally available when building or modifying
* trees, but less often when reading a tree (newly built from
* parsed JSON content).
*<p>
* Actual concrete sub-classes can be found from package
* {@link tools.jackson.databind.node}.
*<p>
* Note that it is possible to "read" from nodes, using
* method {@link TreeNode#traverse}, which will result in
* a {@link JsonParser} being constructed. This can be used for (relatively)
* efficient conversations between different representations; and it is what
* core databind uses for methods like {@link ObjectMapper#treeToValue(TreeNode, Class)}
* and {@link ObjectMapper#treeAsTokens(TreeNode)}
*/
public abstract | for |
java | apache__camel | components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/IncomingPhoneNumberEndpointConfigurationConfigurer.java | {
"start": 742,
"end": 4534
} | class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("ApiName", org.apache.camel.component.twilio.internal.TwilioApiName.class);
map.put("AreaCode", java.lang.String.class);
map.put("MethodName", java.lang.String.class);
map.put("PathAccountSid", java.lang.String.class);
map.put("PathSid", java.lang.String.class);
map.put("PhoneNumber", com.twilio.type.PhoneNumber.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.component.twilio.IncomingPhoneNumberEndpointConfiguration target = (org.apache.camel.component.twilio.IncomingPhoneNumberEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiname":
case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.twilio.internal.TwilioApiName.class, value)); return true;
case "areacode":
case "areaCode": target.setAreaCode(property(camelContext, java.lang.String.class, value)); return true;
case "methodname":
case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true;
case "pathaccountsid":
case "pathAccountSid": target.setPathAccountSid(property(camelContext, java.lang.String.class, value)); return true;
case "pathsid":
case "pathSid": target.setPathSid(property(camelContext, java.lang.String.class, value)); return true;
case "phonenumber":
case "phoneNumber": target.setPhoneNumber(property(camelContext, com.twilio.type.PhoneNumber.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiname":
case "apiName": return org.apache.camel.component.twilio.internal.TwilioApiName.class;
case "areacode":
case "areaCode": return java.lang.String.class;
case "methodname":
case "methodName": return java.lang.String.class;
case "pathaccountsid":
case "pathAccountSid": return java.lang.String.class;
case "pathsid":
case "pathSid": return java.lang.String.class;
case "phonenumber":
case "phoneNumber": return com.twilio.type.PhoneNumber.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.component.twilio.IncomingPhoneNumberEndpointConfiguration target = (org.apache.camel.component.twilio.IncomingPhoneNumberEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiname":
case "apiName": return target.getApiName();
case "areacode":
case "areaCode": return target.getAreaCode();
case "methodname":
case "methodName": return target.getMethodName();
case "pathaccountsid":
case "pathAccountSid": return target.getPathAccountSid();
case "pathsid":
case "pathSid": return target.getPathSid();
case "phonenumber":
case "phoneNumber": return target.getPhoneNumber();
default: return null;
}
}
}
| IncomingPhoneNumberEndpointConfigurationConfigurer |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NettyEndpointBuilderFactory.java | {
"start": 31295,
"end": 69726
} | interface ____ its name, such as eth0 to join a multicast group.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common (advanced)
*
* @param networkInterface the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder networkInterface(String networkInterface) {
doSetProperty("networkInterface", networkInterface);
return this;
}
/**
* Allows to configure a backlog for netty consumer (server). Note the
* backlog is just a best effort depending on the OS. Setting this
* option to a value such as 200, 500 or 1000, tells the TCP stack how
* long the accept queue can be If this option is not configured, then
* the backlog depends on OS setting.
*
* The option is a: <code>int</code> type.
*
* Group: consumer (advanced)
*
* @param backlog the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder backlog(int backlog) {
doSetProperty("backlog", backlog);
return this;
}
/**
* Allows to configure a backlog for netty consumer (server). Note the
* backlog is just a best effort depending on the OS. Setting this
* option to a value such as 200, 500 or 1000, tells the TCP stack how
* long the accept queue can be If this option is not configured, then
* the backlog depends on OS setting.
*
* The option will be converted to a <code>int</code> type.
*
* Group: consumer (advanced)
*
* @param backlog the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder backlog(String backlog) {
doSetProperty("backlog", backlog);
return this;
}
/**
* When netty works on nio mode, it uses default bossCount parameter
* from Netty, which is 1. User can use this option to override the
* default bossCount from Netty.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: consumer (advanced)
*
* @param bossCount the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder bossCount(int bossCount) {
doSetProperty("bossCount", bossCount);
return this;
}
/**
* When netty works on nio mode, it uses default bossCount parameter
* from Netty, which is 1. User can use this option to override the
* default bossCount from Netty.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1
* Group: consumer (advanced)
*
* @param bossCount the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder bossCount(String bossCount) {
doSetProperty("bossCount", bossCount);
return this;
}
/**
* Set the BossGroup which could be used for handling the new connection
* of the server side across the NettyEndpoint.
*
* The option is a: <code>io.netty.channel.EventLoopGroup</code> type.
*
* Group: consumer (advanced)
*
* @param bossGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder bossGroup(io.netty.channel.EventLoopGroup bossGroup) {
doSetProperty("bossGroup", bossGroup);
return this;
}
/**
* Set the BossGroup which could be used for handling the new connection
* of the server side across the NettyEndpoint.
*
* The option will be converted to a
* <code>io.netty.channel.EventLoopGroup</code> type.
*
* Group: consumer (advanced)
*
* @param bossGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder bossGroup(String bossGroup) {
doSetProperty("bossGroup", bossGroup);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Setting to choose Multicast over UDP.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param broadcast the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder broadcast(boolean broadcast) {
doSetProperty("broadcast", broadcast);
return this;
}
/**
* Setting to choose Multicast over UDP.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param broadcast the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder broadcast(String broadcast) {
doSetProperty("broadcast", broadcast);
return this;
}
/**
* If sync is enabled then this option dictates NettyConsumer if it
* should disconnect where there is no reply to send back.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param disconnectOnNoReply the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder disconnectOnNoReply(boolean disconnectOnNoReply) {
doSetProperty("disconnectOnNoReply", disconnectOnNoReply);
return this;
}
/**
* If sync is enabled then this option dictates NettyConsumer if it
* should disconnect where there is no reply to send back.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param disconnectOnNoReply the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder disconnectOnNoReply(String disconnectOnNoReply) {
doSetProperty("disconnectOnNoReply", disconnectOnNoReply);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* To use a custom NettyServerBootstrapFactory.
*
* The option is a:
* <code>org.apache.camel.component.netty.NettyServerBootstrapFactory</code> type.
*
* Group: consumer (advanced)
*
* @param nettyServerBootstrapFactory the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder nettyServerBootstrapFactory(org.apache.camel.component.netty.NettyServerBootstrapFactory nettyServerBootstrapFactory) {
doSetProperty("nettyServerBootstrapFactory", nettyServerBootstrapFactory);
return this;
}
/**
* To use a custom NettyServerBootstrapFactory.
*
* The option will be converted to a
* <code>org.apache.camel.component.netty.NettyServerBootstrapFactory</code> type.
*
* Group: consumer (advanced)
*
* @param nettyServerBootstrapFactory the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder nettyServerBootstrapFactory(String nettyServerBootstrapFactory) {
doSetProperty("nettyServerBootstrapFactory", nettyServerBootstrapFactory);
return this;
}
/**
* If sync is enabled this option dictates NettyConsumer which logging
* level to use when logging a there is no reply to send back.
*
* The option is a: <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: WARN
* Group: consumer (advanced)
*
* @param noReplyLogLevel the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder noReplyLogLevel(org.apache.camel.LoggingLevel noReplyLogLevel) {
doSetProperty("noReplyLogLevel", noReplyLogLevel);
return this;
}
/**
* If sync is enabled this option dictates NettyConsumer which logging
* level to use when logging a there is no reply to send back.
*
* The option will be converted to a
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: WARN
* Group: consumer (advanced)
*
* @param noReplyLogLevel the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder noReplyLogLevel(String noReplyLogLevel) {
doSetProperty("noReplyLogLevel", noReplyLogLevel);
return this;
}
/**
* If the server (NettyConsumer) catches an
* java.nio.channels.ClosedChannelException then its logged using this
* logging level. This is used to avoid logging the closed channel
* exceptions, as clients can disconnect abruptly and then cause a flood
* of closed exceptions in the Netty server.
*
* The option is a: <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: DEBUG
* Group: consumer (advanced)
*
* @param serverClosedChannelExceptionCaughtLogLevel the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder serverClosedChannelExceptionCaughtLogLevel(org.apache.camel.LoggingLevel serverClosedChannelExceptionCaughtLogLevel) {
doSetProperty("serverClosedChannelExceptionCaughtLogLevel", serverClosedChannelExceptionCaughtLogLevel);
return this;
}
/**
* If the server (NettyConsumer) catches an
* java.nio.channels.ClosedChannelException then its logged using this
* logging level. This is used to avoid logging the closed channel
* exceptions, as clients can disconnect abruptly and then cause a flood
* of closed exceptions in the Netty server.
*
* The option will be converted to a
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: DEBUG
* Group: consumer (advanced)
*
* @param serverClosedChannelExceptionCaughtLogLevel the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder serverClosedChannelExceptionCaughtLogLevel(String serverClosedChannelExceptionCaughtLogLevel) {
doSetProperty("serverClosedChannelExceptionCaughtLogLevel", serverClosedChannelExceptionCaughtLogLevel);
return this;
}
/**
* If the server (NettyConsumer) catches an exception then its logged
* using this logging level.
*
* The option is a: <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: WARN
* Group: consumer (advanced)
*
* @param serverExceptionCaughtLogLevel the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder serverExceptionCaughtLogLevel(org.apache.camel.LoggingLevel serverExceptionCaughtLogLevel) {
doSetProperty("serverExceptionCaughtLogLevel", serverExceptionCaughtLogLevel);
return this;
}
/**
* If the server (NettyConsumer) catches an exception then its logged
* using this logging level.
*
* The option will be converted to a
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: WARN
* Group: consumer (advanced)
*
* @param serverExceptionCaughtLogLevel the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder serverExceptionCaughtLogLevel(String serverExceptionCaughtLogLevel) {
doSetProperty("serverExceptionCaughtLogLevel", serverExceptionCaughtLogLevel);
return this;
}
/**
* To use a custom ServerInitializerFactory.
*
* The option is a:
* <code>org.apache.camel.component.netty.ServerInitializerFactory</code> type.
*
* Group: consumer (advanced)
*
* @param serverInitializerFactory the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder serverInitializerFactory(org.apache.camel.component.netty.ServerInitializerFactory serverInitializerFactory) {
doSetProperty("serverInitializerFactory", serverInitializerFactory);
return this;
}
/**
* To use a custom ServerInitializerFactory.
*
* The option will be converted to a
* <code>org.apache.camel.component.netty.ServerInitializerFactory</code> type.
*
* Group: consumer (advanced)
*
* @param serverInitializerFactory the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder serverInitializerFactory(String serverInitializerFactory) {
doSetProperty("serverInitializerFactory", serverInitializerFactory);
return this;
}
/**
* Whether to use ordered thread pool, to ensure events are processed
* orderly on the same channel.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param usingExecutorService the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder usingExecutorService(boolean usingExecutorService) {
doSetProperty("usingExecutorService", usingExecutorService);
return this;
}
/**
* Whether to use ordered thread pool, to ensure events are processed
* orderly on the same channel.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param usingExecutorService the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder usingExecutorService(String usingExecutorService) {
doSetProperty("usingExecutorService", usingExecutorService);
return this;
}
/**
* Only used for TCP when transferExchange is true. When set to true,
* serializable objects in headers and properties will be added to the
* exchange. Otherwise Camel will exclude any non-serializable objects
* and log it at WARN level.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param allowSerializedHeaders the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder allowSerializedHeaders(boolean allowSerializedHeaders) {
doSetProperty("allowSerializedHeaders", allowSerializedHeaders);
return this;
}
/**
* Only used for TCP when transferExchange is true. When set to true,
* serializable objects in headers and properties will be added to the
* exchange. Otherwise Camel will exclude any non-serializable objects
* and log it at WARN level.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param allowSerializedHeaders the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder allowSerializedHeaders(String allowSerializedHeaders) {
doSetProperty("allowSerializedHeaders", allowSerializedHeaders);
return this;
}
/**
* To use an explicit ChannelGroup.
*
* The option is a: <code>io.netty.channel.group.ChannelGroup</code>
* type.
*
* Group: advanced
*
* @param channelGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder channelGroup(io.netty.channel.group.ChannelGroup channelGroup) {
doSetProperty("channelGroup", channelGroup);
return this;
}
/**
* To use an explicit ChannelGroup.
*
* The option will be converted to a
* <code>io.netty.channel.group.ChannelGroup</code> type.
*
* Group: advanced
*
* @param channelGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder channelGroup(String channelGroup) {
doSetProperty("channelGroup", channelGroup);
return this;
}
/**
* Whether to use native transport instead of NIO. Native transport
* takes advantage of the host operating system and is only supported on
* some platforms. You need to add the netty JAR for the host operating
* system you are using. See more details at:
* http://netty.io/wiki/native-transports.html.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param nativeTransport the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder nativeTransport(boolean nativeTransport) {
doSetProperty("nativeTransport", nativeTransport);
return this;
}
/**
* Whether to use native transport instead of NIO. Native transport
* takes advantage of the host operating system and is only supported on
* some platforms. You need to add the netty JAR for the host operating
* system you are using. See more details at:
* http://netty.io/wiki/native-transports.html.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param nativeTransport the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder nativeTransport(String nativeTransport) {
doSetProperty("nativeTransport", nativeTransport);
return this;
}
/**
* Allows to configure additional netty options using option. as prefix.
* For example option.child.keepAlive=false. See the Netty documentation
* for possible options that can be used. This is a multi-value option
* with prefix: option.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.Object></code> type.
* The option is multivalued, and you can use the options(String,
* Object) method to add a value (call the method multiple times to set
* more values).
*
* Group: advanced
*
* @param key the option key
* @param value the option value
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder options(String key, Object value) {
doSetMultiValueProperty("options", "option." + key, value);
return this;
}
/**
* Allows to configure additional netty options using option. as prefix.
* For example option.child.keepAlive=false. See the Netty documentation
* for possible options that can be used. This is a multi-value option
* with prefix: option.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.Object></code> type.
* The option is multivalued, and you can use the options(String,
* Object) method to add a value (call the method multiple times to set
* more values).
*
* Group: advanced
*
* @param values the values
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder options(Map values) {
doSetMultiValueProperties("options", "option.", values);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during inbound communication.
* Size is bytes.
*
* The option is a: <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param receiveBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder receiveBufferSize(int receiveBufferSize) {
doSetProperty("receiveBufferSize", receiveBufferSize);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during inbound communication.
* Size is bytes.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param receiveBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder receiveBufferSize(String receiveBufferSize) {
doSetProperty("receiveBufferSize", receiveBufferSize);
return this;
}
/**
* Configures the buffer size predictor. See details at Jetty
* documentation and this mail thread.
*
* The option is a: <code>int</code> type.
*
* Group: advanced
*
* @param receiveBufferSizePredictor the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder receiveBufferSizePredictor(int receiveBufferSizePredictor) {
doSetProperty("receiveBufferSizePredictor", receiveBufferSizePredictor);
return this;
}
/**
* Configures the buffer size predictor. See details at Jetty
* documentation and this mail thread.
*
* The option will be converted to a <code>int</code> type.
*
* Group: advanced
*
* @param receiveBufferSizePredictor the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder receiveBufferSizePredictor(String receiveBufferSizePredictor) {
doSetProperty("receiveBufferSizePredictor", receiveBufferSizePredictor);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during outbound communication.
* Size is bytes.
*
* The option is a: <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param sendBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder sendBufferSize(int sendBufferSize) {
doSetProperty("sendBufferSize", sendBufferSize);
return this;
}
/**
* The TCP/UDP buffer sizes to be used during outbound communication.
* Size is bytes.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 65536
* Group: advanced
*
* @param sendBufferSize the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder sendBufferSize(String sendBufferSize) {
doSetProperty("sendBufferSize", sendBufferSize);
return this;
}
/**
* Shutdown await timeout in milliseconds.
*
* The option is a: <code>int</code> type.
*
* Default: 100
* Group: advanced
*
* @param shutdownTimeout the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder shutdownTimeout(int shutdownTimeout) {
doSetProperty("shutdownTimeout", shutdownTimeout);
return this;
}
/**
* Shutdown await timeout in milliseconds.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 100
* Group: advanced
*
* @param shutdownTimeout the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder shutdownTimeout(String shutdownTimeout) {
doSetProperty("shutdownTimeout", shutdownTimeout);
return this;
}
/**
* Sets whether synchronous processing should be strictly used.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param synchronous the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param synchronous the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder transferExchange(boolean transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder transferExchange(String transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
/**
* For UDP only. If enabled the using byte array codec instead of Java
* serialization protocol.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param udpByteArrayCodec the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder udpByteArrayCodec(boolean udpByteArrayCodec) {
doSetProperty("udpByteArrayCodec", udpByteArrayCodec);
return this;
}
/**
* For UDP only. If enabled the using byte array codec instead of Java
* serialization protocol.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param udpByteArrayCodec the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder udpByteArrayCodec(String udpByteArrayCodec) {
doSetProperty("udpByteArrayCodec", udpByteArrayCodec);
return this;
}
/**
* Path to unix domain socket to use instead of inet socket. Host and
* port parameters will not be used, however required. It is ok to set
* dummy values for them. Must be used with nativeTransport=true and
* clientMode=false.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param unixDomainSocketPath the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder unixDomainSocketPath(String unixDomainSocketPath) {
doSetProperty("unixDomainSocketPath", unixDomainSocketPath);
return this;
}
/**
* When netty works on nio mode, it uses default workerCount parameter
* from Netty (which is cpu_core_threads x 2). User can use this option
* to override the default workerCount from Netty.
*
* The option is a: <code>int</code> type.
*
* Group: advanced
*
* @param workerCount the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder workerCount(int workerCount) {
doSetProperty("workerCount", workerCount);
return this;
}
/**
* When netty works on nio mode, it uses default workerCount parameter
* from Netty (which is cpu_core_threads x 2). User can use this option
* to override the default workerCount from Netty.
*
* The option will be converted to a <code>int</code> type.
*
* Group: advanced
*
* @param workerCount the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder workerCount(String workerCount) {
doSetProperty("workerCount", workerCount);
return this;
}
/**
* To use a explicit EventLoopGroup as the boss thread pool. For example
* to share a thread pool with multiple consumers or producers. By
* default each consumer or producer has their own worker pool with 2 x
* cpu count core threads.
*
* The option is a: <code>io.netty.channel.EventLoopGroup</code> type.
*
* Group: advanced
*
* @param workerGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder workerGroup(io.netty.channel.EventLoopGroup workerGroup) {
doSetProperty("workerGroup", workerGroup);
return this;
}
/**
* To use a explicit EventLoopGroup as the boss thread pool. For example
* to share a thread pool with multiple consumers or producers. By
* default each consumer or producer has their own worker pool with 2 x
* cpu count core threads.
*
* The option will be converted to a
* <code>io.netty.channel.EventLoopGroup</code> type.
*
* Group: advanced
*
* @param workerGroup the value to set
* @return the dsl builder
*/
default AdvancedNettyEndpointConsumerBuilder workerGroup(String workerGroup) {
doSetProperty("workerGroup", workerGroup);
return this;
}
}
/**
* Builder for endpoint producers for the Netty component.
*/
public | by |
java | apache__avro | lang/java/avro/src/test/java/org/apache/avro/specific/TestSpecificDatumReader.java | {
"start": 1224,
"end": 2291
} | class ____ {
@Test
void readMyData() throws IOException {
// Check that method newInstanceFromString from SpecificDatumReader extension is
// called.
final EncoderFactory e_factory = new EncoderFactory().configureBufferSize(30);
final DecoderFactory factory = new DecoderFactory().configureDecoderBufferSize(30);
final MyReader reader = new MyReader();
reader.setExpected(Schema.create(Schema.Type.STRING));
reader.setSchema(Schema.create(Schema.Type.STRING));
final ByteArrayOutputStream out = new ByteArrayOutputStream(30);
final BinaryEncoder encoder = e_factory.binaryEncoder(out, null);
encoder.writeString(new Utf8("Hello"));
encoder.flush();
final BinaryDecoder decoder = factory.binaryDecoder(out.toByteArray(), null);
reader.getData().setFastReaderEnabled(false);
final MyData read = reader.read(null, decoder);
Assertions.assertNotNull(read, "MyReader.newInstanceFromString was not called");
Assertions.assertEquals("Hello", read.getContent());
}
public static | TestSpecificDatumReader |
java | alibaba__fastjson | src/test/java/com/alibaba/json/test/vans/VansGeometryData.java | {
"start": 277,
"end": 579
} | class ____ implements Serializable{
public float[][] uvs;
@JSONField(name = "metadata")
public VansGeometryDataMetaData metaData;
public float[] normals;
public String name;
public int[] faces;
public float[] vertices;
public VansGeometryData(){
}
}
| VansGeometryData |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/JteEndpointBuilderFactory.java | {
"start": 11616,
"end": 13044
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final JteHeaderNameBuilder INSTANCE = new JteHeaderNameBuilder();
/**
* A URI for the template resource to use instead of the endpoint
* configured.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code JteResourceUri}.
*/
public String jteResourceUri() {
return "CamelJteResourceUri";
}
/**
* The template to use instead of the endpoint configured.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code JteTemplate}.
*/
public String jteTemplate() {
return "CamelJteTemplate";
}
/**
* The data model.
*
* The option is a: {@code Object} type.
*
* Group: producer
*
* @return the name of the header {@code JteDataModel}.
*/
public String jteDataModel() {
return "CamelJteDataModel";
}
}
static JteEndpointBuilder endpointBuilder(String componentName, String path) {
| JteHeaderNameBuilder |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSEditLogOp.java | {
"start": 104840,
"end": 104968
} | class ____ extends LogSegmentOp {
StartLogSegmentOp() {
super(OP_START_LOG_SEGMENT);
}
}
static | StartLogSegmentOp |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java | {
"start": 239410,
"end": 240528
} | class ____ implements Comparator<Field> {
@Override
public int compare(final Field f1, final Field f2) {
final Option o1 = f1.getAnnotation(Option.class);
final Option o2 = f2.getAnnotation(Option.class);
if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
} // options before params
final String[] names1 = ShortestFirst.sort(o1.names());
final String[] names2 = ShortestFirst.sort(o2.names());
int result = toRootUpperCase(names1[0]).compareTo(toRootUpperCase(names2[0])); // case insensitive sort
result = result == 0 ? -names1[0].compareTo(names2[0]) : result; // lower case before upper case
return o1.help() == o2.help() ? result : o2.help() ? -1 : 1; // help options come last
}
}
/** Sorts {@code Option} instances by their max arity first, then their min arity, then delegates to super class. */
static | SortByShortestOptionNameAlphabetically |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/IrateDoubleAggregator.java | {
"start": 1616,
"end": 2662
} | class ____ {
public static DoubleIrateGroupingState initGrouping(DriverContext driverContext, boolean isDelta) {
return new DoubleIrateGroupingState(driverContext.bigArrays(), driverContext.breaker(), isDelta);
}
public static void combine(DoubleIrateGroupingState current, int groupId, double value, long timestamp) {
current.ensureCapacity(groupId);
current.append(groupId, timestamp, value);
}
public static String describe() {
return "instant change of doubles";
}
public static void combineIntermediate(
DoubleIrateGroupingState current,
int groupId,
LongBlock timestamps,
DoubleBlock values,
int otherPosition
) {
current.combine(groupId, timestamps, values, otherPosition);
}
public static Block evaluateFinal(DoubleIrateGroupingState state, IntVector selected, GroupingAggregatorEvaluationContext evalContext) {
return state.evaluateFinal(selected, evalContext);
}
private static | IrateDoubleAggregator |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-panache/deployment/src/test/java/io/quarkus/hibernate/orm/panache/deployment/test/PanacheJAXBTest.java | {
"start": 904,
"end": 4555
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(JAXBEntity.class, JAXBTestResource.class)
.addAsResource(new StringAsset("quarkus.hibernate-orm.schema-management.strategy=none"),
"application.properties"));
@Test
public void testJaxbAnnotationTransfer() throws Exception {
// Test for fix to this bug: https://github.com/quarkusio/quarkus/issues/6021
// Ensure that any JAX-B annotations are properly moved to generated getters
Method m = JAXBEntity.class.getMethod("getNamedAnnotatedProp");
XmlAttribute anno = m.getAnnotation(XmlAttribute.class);
assertNotNull(anno);
assertEquals("Named", anno.name());
assertNull(m.getAnnotation(XmlTransient.class));
m = JAXBEntity.class.getMethod("getDefaultAnnotatedProp");
anno = m.getAnnotation(XmlAttribute.class);
assertNotNull(anno);
assertEquals("##default", anno.name());
assertNull(m.getAnnotation(XmlTransient.class));
m = JAXBEntity.class.getMethod("getUnAnnotatedProp");
assertNull(m.getAnnotation(XmlAttribute.class));
assertNull(m.getAnnotation(XmlTransient.class));
m = JAXBEntity.class.getMethod("getTransientProp");
assertNull(m.getAnnotation(XmlAttribute.class));
assertNotNull(m.getAnnotation(XmlTransient.class));
m = JAXBEntity.class.getMethod("getArrayAnnotatedProp");
assertNull(m.getAnnotation(XmlTransient.class));
XmlElements elementsAnno = m.getAnnotation(XmlElements.class);
assertNotNull(elementsAnno);
assertNotNull(elementsAnno.value());
assertEquals(2, elementsAnno.value().length);
assertEquals("array1", elementsAnno.value()[0].name());
assertEquals("array2", elementsAnno.value()[1].name());
// Ensure that all original fields were labeled @XmlTransient and had their original JAX-B annotations removed
ensureFieldSanitized("namedAnnotatedProp");
ensureFieldSanitized("transientProp");
ensureFieldSanitized("defaultAnnotatedProp");
ensureFieldSanitized("unAnnotatedProp");
ensureFieldSanitized("arrayAnnotatedProp");
}
private void ensureFieldSanitized(String fieldName) throws Exception {
Field f = JAXBEntity.class.getDeclaredField(fieldName);
assertNull(f.getAnnotation(XmlAttribute.class));
assertNotNull(f.getAnnotation(XmlTransient.class));
}
@Test
public void testPanacheSerialisation() {
RestAssured.given().accept(ContentType.XML)
.when().get("/test/ignored-properties")
.then().body(is(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><JAXBEntity><id>666</id><name>Eddie</name><serialisationTrick>1</serialisationTrick></JAXBEntity>"));
}
@Test
public void jaxbDeserializationHasAllFields() throws JAXBException {
// set Up
JAXBEntity person = new JAXBEntity();
person.name = "max";
// do
JAXBContext jaxbContext = JAXBContext.newInstance(JAXBEntity.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(person, sw);
assertEquals(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><JAXBEntity><name>max</name><serialisationTrick>1</serialisationTrick></JAXBEntity>",
sw.toString());
}
}
| PanacheJAXBTest |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/recording/BytecodeRecorderImpl.java | {
"start": 104717,
"end": 105895
} | class ____ {
boolean prepared = false;
/**
* The function that is called to read the value for use. This may be by reading the value from the Object[]
* array, or is can be a direct ldc instruction in the case of primitives.
* <p>
* Code in this method is run in a single instruction group, so large objects should be serialized in the
* {@link #doPrepare(MethodContext)} method instead
* <p>
* This should not be called directly, but by {@link SplitMethodContext#loadDeferred(DeferredParameter)}
*/
abstract ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array);
/**
* function that prepares the value for use. This is where objects should actually be loaded into the
* main array
*
* @param context The main method context.
*/
final void prepare(MethodContext context) {
if (!prepared) {
prepared = true;
doPrepare(context);
}
}
void doPrepare(MethodContext context) {
}
}
abstract | DeferredParameter |
java | spring-projects__spring-boot | module/spring-boot-r2dbc/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java | {
"start": 1215,
"end": 3133
} | class ____
extends AbstractScriptDatabaseInitializerTests<R2dbcScriptDatabaseInitializer> {
private final ConnectionFactory embeddedConnectionFactory = ConnectionFactoryBuilder
.withUrl("r2dbc:h2:mem:///" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
.build();
private final ConnectionFactory standaloneConnectionFactory = ConnectionFactoryBuilder
.withUrl(
"r2dbc:h2:file:///"
+ new BuildOutput(R2dbcScriptDatabaseInitializerTests.class).getRootLocation()
.getAbsolutePath()
.replace('\\', '/')
+ "/" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
.build();
@Override
protected R2dbcScriptDatabaseInitializer createEmbeddedDatabaseInitializer(
DatabaseInitializationSettings settings) {
return new R2dbcScriptDatabaseInitializer(this.embeddedConnectionFactory, settings);
}
@Override
protected R2dbcScriptDatabaseInitializer createStandaloneDatabaseInitializer(
DatabaseInitializationSettings settings) {
return new R2dbcScriptDatabaseInitializer(this.standaloneConnectionFactory, settings);
}
@Override
protected int numberOfEmbeddedRows(String sql) {
return numberOfRows(this.embeddedConnectionFactory, sql);
}
@Override
protected int numberOfStandaloneRows(String sql) {
return numberOfRows(this.standaloneConnectionFactory, sql);
}
private int numberOfRows(ConnectionFactory connectionFactory, String sql) {
Integer result = DatabaseClient.create(connectionFactory)
.sql(sql)
.map((row, metadata) -> row.get(0))
.first()
.map((number) -> ((Number) number).intValue())
.block();
assertThat(result).isNotNull();
return result;
}
@Override
protected void assertDatabaseAccessed(boolean accessed, R2dbcScriptDatabaseInitializer initializer) {
// No-op as R2DBC does not need to access the database to determine its type
}
}
| R2dbcScriptDatabaseInitializerTests |
java | apache__kafka | server/src/main/java/org/apache/kafka/server/share/fetch/ShareFetchPartitionData.java | {
"start": 993,
"end": 1219
} | class ____ the data and metadata for a partition that is being fetched.
*/
public record ShareFetchPartitionData(
TopicIdPartition topicIdPartition,
long fetchOffset,
FetchPartitionData fetchPartitionData
) {
}
| holds |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/ByteArrayManager.java | {
"start": 7099,
"end": 7793
} | class ____ {
private final int countLimit;
private final Map<Integer, FixedLengthManager> map = new HashMap<>();
ManagerMap(int countLimit) {
this.countLimit = countLimit;
}
/** @return the manager for the given array length. */
synchronized FixedLengthManager get(final Integer arrayLength,
final boolean createIfNotExist) {
FixedLengthManager manager = map.get(arrayLength);
if (manager == null && createIfNotExist) {
manager = new FixedLengthManager(arrayLength, countLimit);
map.put(arrayLength, manager);
}
return manager;
}
}
/**
* Configuration for ByteArrayManager.
*/
public static | ManagerMap |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest67.java | {
"start": 974,
"end": 3080
} | class ____ extends MysqlTest {
@Test
public void test_one() throws Exception {
String sql = "CREATE TABLE t1 ( a INT NOT NULL, PRIMARY KEY (a))"
+ " ENGINE=InnoDB TABLESPACE ts1 "
+ " PARTITION BY RANGE (a) PARTITIONS 3 ("
+ " PARTITION P1 VALUES LESS THAN (2),"
+ " PARTITION P2 VALUES LESS THAN (4) TABLESPACE ts2,"
+ " PARTITION P3 VALUES LESS THAN (6) TABLESPACE ts3);";
MySqlStatementParser parser = new MySqlStatementParser(sql);
SQLStatement stmt = parser.parseCreateTable();
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE t1 (\n" +
"\ta INT NOT NULL,\n" +
"\tPRIMARY KEY (a)\n" +
") ENGINE = InnoDB TABLESPACE ts1\n" +
"PARTITION BY RANGE COLUMNS (a) PARTITIONS 3 (\n" +
"\tPARTITION P1 VALUES LESS THAN (2),\n" +
"\tPARTITION P2 VALUES LESS THAN (4)\n" +
"\t\tTABLESPACE ts2,\n" +
"\tPARTITION P3 VALUES LESS THAN (6)\n" +
"\t\tTABLESPACE ts3\n" +
")", output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("create table t1 (\n" +
"\ta INT not null,\n" +
"\tprimary key (a)\n" +
") engine = InnoDB tablespace ts1\n" +
"partition by range columns (a) partitions 3 (\n" +
"\tpartition P1 values less than (2),\n" +
"\tpartition P2 values less than (4)\n" +
"\t\ttablespace ts2,\n" +
"\tpartition P3 values less than (6)\n" +
"\t\ttablespace ts3\n" +
")", output);
}
}
}
| MySqlCreateTableTest67 |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/processing/IntroductionInterfaceBeanElementCreator.java | {
"start": 2962,
"end": 4858
} | class ____ doesn't
// Because of the caching we need to process declared methods first
List<MethodElement> allMethods = new ArrayList<>(classElement.getEnclosedElements(ElementQuery.ALL_METHODS.includeOverriddenMethods()));
List<MethodElement> methods = new ArrayList<>(allMethods);
List<MethodElement> nonAbstractMethods = methods.stream().filter(m -> !m.isAbstract()).toList();
// Remove abstract methods overridden by non-abstract ones
methods.removeIf(method -> method.isAbstract() && nonAbstractMethods.stream().anyMatch(nonAbstractMethod -> nonAbstractMethod.overrides(method)));
// Remove non-abstract methods without explicit around advice
methods.removeIf(method -> !method.isAbstract() && !InterceptedMethodUtil.hasDeclaredAroundAdvice(method.getAnnotationMetadata()));
Collections.reverse(methods); // reverse to process hierarchy starting from declared methods
for (MethodElement methodElement : methods) {
visitIntrospectedMethod(aopProxyWriter, classElement, methodElement);
}
List<PropertyElement> beanProperties = classElement.getSyntheticBeanProperties();
for (PropertyElement beanProperty : beanProperties) {
handlePropertyMethod(aopProxyWriter, methods, beanProperty.getReadMethod().orElse(null));
handlePropertyMethod(aopProxyWriter, methods, beanProperty.getWriteMethod().orElse(null));
}
beanDefinitionWriters.add(aopProxyWriter);
}
private void handlePropertyMethod(BeanDefinitionVisitor aopProxyWriter, List<MethodElement> methods, MethodElement method) {
if (method != null && method.isAbstract() && !methods.contains(method)) {
visitIntrospectedMethod(
aopProxyWriter,
this.classElement,
method
);
}
}
}
| introduction |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java | {
"start": 120025,
"end": 120104
} | class ____ {
}
@Resource(name = "x")
static | SpringApplicationConfigurationClass |
java | elastic__elasticsearch | qa/smoke-test-http/src/internalClusterTest/java/org/elasticsearch/http/DanglingIndicesRestIT.java | {
"start": 9724,
"end": 12978
} | class ____ and restart nodes, assuming
* that each index has a primary or replica shard on every node, and if
* a node is stopped prematurely, this assumption is broken.
*
* @return a mapping from each created index name to its UUID
*/
private Map<String, String> createIndices(String... indices) throws IOException {
assert indices.length > 0;
for (String index : indices) {
final var request = ESRestTestCase.newXContentRequest(HttpMethod.PUT, "/" + index, (builder, params) -> {
builder.startObject("settings").startObject("index");
builder.field("number_of_shards", 1).field("number_of_replicas", 2);
builder.startObject("routing").startObject("allocation").field("total_shards_per_node", 1).endObject().endObject();
return builder.endObject().endObject();
});
assertOK(getRestClient().performRequest(request));
}
ensureGreen(indices);
final Response catResponse = getRestClient().performRequest(new Request("GET", "/_cat/indices?h=index,uuid"));
assertOK(catResponse);
final Map<String, String> createdIndexIDs = new HashMap<>();
final List<String> indicesAsList = Arrays.asList(indices);
for (String indexLine : Streams.readAllLines(catResponse.getEntity().getContent())) {
String[] elements = indexLine.split(" +");
if (indicesAsList.contains(elements[0])) {
createdIndexIDs.put(elements[0], elements[1]);
}
}
assertThat("Expected to find as many index UUIDs as created indices", createdIndexIDs.size(), equalTo(indices.length));
return createdIndexIDs;
}
private void deleteIndex(String indexName) throws IOException {
Response deleteResponse = getRestClient().performRequest(new Request("DELETE", "/" + indexName));
assertOK(deleteResponse);
}
private DanglingIndexDetails createDanglingIndices(String... indices) throws Exception {
ensureStableCluster(3);
final Map<String, String> indexToUUID = createIndices(indices);
final AtomicReference<String> stoppedNodeName = new AtomicReference<>();
assertBusy(
() -> internalCluster().getInstances(IndicesService.class)
.forEach(indicesService -> assertTrue(indicesService.allPendingDanglingIndicesWritten()))
);
// Restart node, deleting the index in its absence, so that there is a dangling index to recover
internalCluster().restartRandomDataNode(new InternalTestCluster.RestartCallback() {
@Override
public Settings onNodeStopped(String nodeName) throws Exception {
ensureClusterSizeConsistency();
stoppedNodeName.set(nodeName);
for (String index : indices) {
deleteIndex(index);
}
return super.onNodeStopped(nodeName);
}
});
ensureStableCluster(3);
return new DanglingIndexDetails(stoppedNodeName.get(), indexToUUID);
}
private record DanglingIndexDetails(String stoppedNodeName, Map<String, String> indexToUUID) {}
}
| stop |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/diversification/ResultDiversificationType.java | {
"start": 553,
"end": 1155
} | enum ____ {
MMR("mmr");
public final String value;
ResultDiversificationType(String value) {
this.value = value;
}
public static ResultDiversificationType fromString(String value) {
for (ResultDiversificationType diversificationType : ResultDiversificationType.values()) {
if (diversificationType.value.equalsIgnoreCase(value)) {
return diversificationType;
}
}
throw new IllegalArgumentException(String.format(Locale.ROOT, "unknown result diversification type [%s]", value));
}
}
| ResultDiversificationType |
java | apache__logging-log4j2 | log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamTest.java | {
"start": 1056,
"end": 3875
} | class ____ extends AbstractLoggerOutputStreamTest {
private PrintStream print;
@Override
protected ByteArrayOutputStream createOutputStream() {
return new ByteArrayOutputStream();
}
@Override
protected OutputStream createOutputStreamWrapper() {
return this.print = IoBuilder.forLogger(getExtendedLogger())
.filter(this.wrapped)
.setLevel(LEVEL)
.buildPrintStream();
}
@Test
public void testFormat() {
assertSame(this.print, this.print.format("[%s]", FIRST));
assertMessages();
this.print.println();
assertMessages("[" + FIRST + "]");
assertEquals("[" + FIRST + "]" + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_boolean() {
this.print.print(true);
assertMessages();
this.print.println();
assertMessages("true");
assertEquals("true" + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_char() {
for (final char c : FIRST.toCharArray()) {
this.print.print(c);
assertMessages();
}
this.print.println();
assertMessages(FIRST);
assertEquals(FIRST + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_CharacterArray() {
this.print.print(FIRST.toCharArray());
assertMessages();
this.print.println();
assertMessages(FIRST);
assertEquals(FIRST + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_int() {
this.print.print(12);
assertMessages();
this.print.println();
assertMessages("12");
assertEquals("12" + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_long() {
this.print.print(12L);
assertMessages();
this.print.println();
assertMessages("12");
assertEquals("12" + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_Object() {
this.print.print((Object) FIRST);
assertMessages();
this.print.println();
assertMessages(FIRST);
assertEquals(FIRST + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrint_String() {
this.print.print(FIRST);
assertMessages();
this.print.println();
assertMessages(FIRST);
assertEquals(FIRST + NEWLINE, this.wrapped.toString());
}
@Test
public void testPrintf() {
assertSame(this.print, this.print.printf("<<<%s>>>", FIRST));
assertMessages();
this.print.println();
assertMessages("<<<" + FIRST + ">>>");
assertEquals("<<<" + FIRST + ">>>" + NEWLINE, this.wrapped.toString());
}
}
| LoggerPrintStreamTest |
java | mockito__mockito | mockito-integration-tests/inline-mocks-tests/src/test/java/org/mockitoinline/ConstructionMockRuleTest.java | {
"start": 921,
"end": 1003
} | class ____ {
String foo() {
return "foo";
}
}
}
| Dummy |
java | apache__camel | components/camel-tarfile/src/test/java/org/apache/camel/dataformat/tarfile/TarUtils.java | {
"start": 4068,
"end": 4959
} | class ____ {
public final long size;
public final boolean isDirectory;
public EntryMetadata(long size, boolean isDirectory) {
this.size = size;
this.isDirectory = isDirectory;
}
}
static Map<String, EntryMetadata> toEntries(byte[] tarFileBytes) throws IOException {
Map<String, EntryMetadata> ret = new HashMap<>();
try (ArchiveInputStream i = new TarArchiveInputStream(new ByteArrayInputStream(tarFileBytes))) {
ArchiveEntry entry = null;
while ((entry = i.getNextEntry()) != null) {
if (!i.canReadEntryData(entry)) {
// log something?
continue;
}
ret.put(entry.getName(), new EntryMetadata(entry.getSize(), entry.isDirectory()));
}
}
return ret;
}
}
| EntryMetadata |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/gateway/MetadataStateFormatTests.java | {
"start": 24283,
"end": 29237
} | enum ____ {
NO_FAILURES,
FAIL_ON_METHOD,
FAIL_MULTIPLE_METHODS,
FAIL_RANDOMLY
}
private FailureMode failureMode;
private String[] failureMethods;
private Path[] failurePaths;
static final String FAIL_CREATE_OUTPUT_FILE = "createOutput";
static final String FAIL_WRITE_TO_OUTPUT_FILE = "writeBytes";
static final String FAIL_FSYNC_TMP_FILE = "sync";
static final String FAIL_RENAME_TMP_FILE = "rename";
static final String FAIL_FSYNC_STATE_DIRECTORY = "syncMetaData";
static final String FAIL_DELETE_TMP_FILE = "deleteFile";
static final String FAIL_OPEN_STATE_FILE_WHEN_COPYING = "openInput";
static final String FAIL_LIST_ALL = "listAll";
/**
* Constructs a MetadataStateFormat object for storing/retrieving DummyState.
* By default no I/O failures are injected.
* I/O failure behaviour can be controlled by {@link #noFailures()}, {@link #failOnRandomMethod(String...)},
* {@link #failOnMethods(String...)} and {@link #failRandomly()} method calls.
*/
Format(String prefix) {
super(prefix);
this.failureMode = FailureMode.NO_FAILURES;
}
@Override
public void toXContent(XContentBuilder builder, DummyState state) throws IOException {
state.toXContent(builder, null);
}
@Override
public DummyState fromXContent(XContentParser parser) throws IOException {
return new DummyState().parse(parser);
}
public void noFailures() {
this.failureMode = FailureMode.NO_FAILURES;
}
public void failOnRandomMethod(String... failureMethods) {
this.failureMode = FailureMode.FAIL_ON_METHOD;
this.failureMethods = failureMethods;
}
public void failOnMethods(String... failureMethods) {
this.failureMode = FailureMode.FAIL_MULTIPLE_METHODS;
this.failureMethods = failureMethods;
}
public void failOnPaths(Path... paths) {
this.failurePaths = paths;
}
public void failRandomly() {
this.failureMode = FailureMode.FAIL_RANDOMLY;
}
private void throwDirectoryExceptionCheckPaths(Path dir) throws MockDirectoryWrapper.FakeIOException {
if (failurePaths != null) {
for (Path p : failurePaths) {
if (p.equals(dir)) {
throw new MockDirectoryWrapper.FakeIOException();
}
}
} else {
throw new MockDirectoryWrapper.FakeIOException();
}
}
@Override
protected Directory newDirectory(Path dir) {
MockDirectoryWrapper mock = newMockFSDirectory(dir);
if (failureMode == FailureMode.FAIL_MULTIPLE_METHODS) {
final Set<String> failMethods = Set.of(failureMethods);
MockDirectoryWrapper.Failure fail = new MockDirectoryWrapper.Failure() {
@Override
public void eval(MockDirectoryWrapper directory) throws IOException {
for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
if (failMethods.contains(e.getMethodName())) {
throwDirectoryExceptionCheckPaths(dir);
}
}
}
};
mock.failOn(fail);
} else if (failureMode == FailureMode.FAIL_ON_METHOD) {
final String failMethod = randomFrom(failureMethods);
MockDirectoryWrapper.Failure fail = new MockDirectoryWrapper.Failure() {
@Override
public void eval(MockDirectoryWrapper directory) throws IOException {
for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
if (failMethod.equals(e.getMethodName())) {
throwDirectoryExceptionCheckPaths(dir);
}
}
}
};
mock.failOn(fail);
} else if (failureMode == FailureMode.FAIL_RANDOMLY) {
MockDirectoryWrapper.Failure fail = new MockDirectoryWrapper.Failure() {
@Override
public void eval(MockDirectoryWrapper directory) throws IOException {
if (randomIntBetween(0, 20) == 0) {
throwDirectoryExceptionCheckPaths(dir);
}
}
};
mock.failOn(fail);
}
closeAfterSuite(mock);
return mock;
}
}
private static | FailureMode |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/factories/TableFactory.java | {
"start": 1650,
"end": 3423
} | interface ____ {
/**
* Specifies the context that this factory has been implemented for. The framework guarantees to
* only match for this factory if the specified set of properties and values are met.
*
* <p>Typical properties might be: - connector.type - format.type
*
* <p>Specified property versions allow the framework to provide backwards compatible properties
* in case of string format changes: - connector.property-version - format.property-version
*
* <p>An empty context means that the factory matches for all requests.
*/
Map<String, String> requiredContext();
/**
* List of property keys that this factory can handle. This method will be used for validation.
* If a property is passed that this factory cannot handle, an exception will be thrown. The
* list must not contain the keys that are specified by the context.
*
* <p>Example properties might be: - schema.#.type - schema.#.name - connector.topic -
* format.line-delimiter - format.ignore-parse-errors - format.fields.#.type -
* format.fields.#.name
*
* <p>Note: Use "#" to denote an array of values where "#" represents one or more digits.
* Property versions like "format.property-version" must not be part of the supported
* properties.
*
* <p>In some cases it might be useful to declare wildcards "*". Wildcards can only be declared
* at the end of a property key.
*
* <p>For example, if an arbitrary format should be supported: - format.*
*
* <p>Note: Wildcards should be used with caution as they might swallow unsupported properties
* and thus might lead to undesired behavior.
*/
List<String> supportedProperties();
}
| TableFactory |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/LongBitFormat.java | {
"start": 916,
"end": 1023
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
public | LongBitFormat |
java | apache__camel | components/camel-saxon/src/generated/java/org/apache/camel/converter/saxon/SaxonConverterLoader.java | {
"start": 881,
"end": 5878
} | class ____ implements TypeConverterLoader, CamelContextAware {
private CamelContext camelContext;
public SaxonConverterLoader() {
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException {
registerConverters(registry);
registerFallbackConverters(registry);
}
private void registerConverters(TypeConverterRegistry registry) {
addTypeConverter(registry, javax.xml.transform.dom.DOMSource.class, net.sf.saxon.om.NodeInfo.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMSourceFromNodeInfo((net.sf.saxon.om.NodeInfo) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, javax.xml.transform.dom.DOMSource.class, net.sf.saxon.tree.tiny.TinyDocumentImpl.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMSourceFromNodeInfo((net.sf.saxon.tree.tiny.TinyDocumentImpl) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, org.w3c.dom.Document.class, net.sf.saxon.om.NodeInfo.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMDocument((net.sf.saxon.om.NodeInfo) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, org.w3c.dom.Document.class, net.sf.saxon.tree.tiny.TinyDocumentImpl.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMDocument((net.sf.saxon.tree.tiny.TinyDocumentImpl) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, org.w3c.dom.Document.class, net.sf.saxon.tree.tiny.TinyElementImpl.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMDocument((net.sf.saxon.tree.tiny.TinyElementImpl) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, org.w3c.dom.Node.class, net.sf.saxon.om.NodeInfo.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMNode((net.sf.saxon.om.NodeInfo) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, org.w3c.dom.Node.class, net.sf.saxon.tree.tiny.TinyDocumentImpl.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMNode((net.sf.saxon.tree.tiny.TinyDocumentImpl) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, org.w3c.dom.NodeList.class, java.util.List.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.converter.saxon.SaxonConverter.toDOMNodeList((java.util.List) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
}
private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) {
registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method));
}
private void registerFallbackConverters(TypeConverterRegistry registry) {
addFallbackTypeConverter(registry, false, false, (type, exchange, value) -> org.apache.camel.converter.saxon.SaxonConverter.convertTo(type, exchange, value, registry));
}
private static void addFallbackTypeConverter(TypeConverterRegistry registry, boolean allowNull, boolean canPromote, SimpleTypeConverter.ConversionMethod method) {
registry.addFallbackTypeConverter(new SimpleTypeConverter(allowNull, method), canPromote);
}
}
| SaxonConverterLoader |
java | apache__flink | flink-table/flink-sql-jdbc-driver/src/main/java/org/apache/flink/table/jdbc/BaseDatabaseMetaData.java | {
"start": 1116,
"end": 14031
} | class ____ implements DatabaseMetaData {
@Override
public String getUserName() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getUserName is not supported");
}
@Override
public String getSQLKeywords() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getSQLKeywords is not supported");
}
@Override
public String getNumericFunctions() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getNumericFunctions is not supported");
}
@Override
public String getStringFunctions() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getStringFunctions is not supported");
}
@Override
public String getSystemFunctions() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getSystemFunctions is not supported");
}
@Override
public String getTimeDateFunctions() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getTimeDateFunctions is not supported");
}
@Override
public String getSearchStringEscape() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getSearchStringEscape is not supported");
}
@Override
public String getProcedureTerm() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getProcedureTerm is not supported");
}
@Override
public String getCatalogSeparator() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getCatalogSeparator is not supported");
}
@Override
public int getMaxBinaryLiteralLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxBinaryLiteralLength is not supported");
}
@Override
public int getMaxCharLiteralLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxCharLiteralLength is not supported");
}
@Override
public int getMaxColumnNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxColumnNameLength is not supported");
}
@Override
public int getMaxColumnsInGroupBy() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxColumnsInGroupBy is not supported");
}
@Override
public int getMaxColumnsInIndex() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxColumnsInIndex is not supported");
}
@Override
public int getMaxColumnsInOrderBy() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxColumnsInOrderBy is not supported");
}
@Override
public int getMaxColumnsInSelect() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxColumnsInSelect is not supported");
}
@Override
public int getMaxColumnsInTable() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxColumnsInTable is not supported");
}
@Override
public int getMaxConnections() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxConnections is not supported");
}
@Override
public int getMaxCursorNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxCursorNameLength is not supported");
}
@Override
public int getMaxIndexLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxIndexLength is not supported");
}
@Override
public int getMaxSchemaNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxSchemaNameLength is not supported");
}
@Override
public int getMaxProcedureNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxProcedureNameLength is not supported");
}
@Override
public int getMaxCatalogNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxCatalogNameLength is not supported");
}
@Override
public int getMaxRowSize() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxRowSize is not supported");
}
@Override
public int getMaxStatementLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxStatementLength is not supported");
}
@Override
public int getMaxStatements() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxStatements is not supported");
}
@Override
public int getMaxTableNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxTableNameLength is not supported");
}
@Override
public int getMaxTablesInSelect() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxTablesInSelect is not supported");
}
@Override
public int getMaxUserNameLength() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getMaxUserNameLength is not supported");
}
@Override
public int getDefaultTransactionIsolation() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getDefaultTransactionIsolation is not supported");
}
@Override
public ResultSet getProcedures(
String catalog, String schemaPattern, String procedureNamePattern) throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getProcedures is not supported");
}
@Override
public ResultSet getProcedureColumns(
String catalog,
String schemaPattern,
String procedureNamePattern,
String columnNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getProcedureColumns is not supported");
}
@Override
public ResultSet getColumnPrivileges(
String catalog, String schema, String table, String columnNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getColumnPrivileges is not supported");
}
@Override
public ResultSet getTablePrivileges(
String catalog, String schemaPattern, String tableNamePattern) throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getTablePrivileges is not supported");
}
@Override
public ResultSet getBestRowIdentifier(
String catalog, String schema, String table, int scope, boolean nullable)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getBestRowIdentifier is not supported");
}
@Override
public ResultSet getVersionColumns(String catalog, String schema, String table)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getVersionColumns is not supported");
}
@Override
public ResultSet getImportedKeys(String catalog, String schema, String table)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getImportedKeys is not supported");
}
@Override
public ResultSet getExportedKeys(String catalog, String schema, String table)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getExportedKeys is not supported");
}
@Override
public ResultSet getCrossReference(
String parentCatalog,
String parentSchema,
String parentTable,
String foreignCatalog,
String foreignSchema,
String foreignTable)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getCrossReference is not supported");
}
@Override
public ResultSet getTypeInfo() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getTypeInfo is not supported");
}
@Override
public ResultSet getIndexInfo(
String catalog, String schema, String table, boolean unique, boolean approximate)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getIndexInfo is not supported");
}
@Override
public ResultSet getUDTs(
String catalog, String schemaPattern, String typeNamePattern, int[] types)
throws SQLException {
throw new SQLFeatureNotSupportedException("FlinkDatabaseMetaData#getUDTs is not supported");
}
@Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getSuperTypes is not supported");
}
@Override
public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getSuperTypes is not supported");
}
@Override
public ResultSet getAttributes(
String catalog,
String schemaPattern,
String typeNamePattern,
String attributeNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getAttributes is not supported");
}
@Override
public int getResultSetHoldability() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getResultSetHoldability is not supported");
}
@Override
public int getSQLStateType() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getSQLStateType is not supported");
}
@Override
public RowIdLifetime getRowIdLifetime() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getRowIdLifetime is not supported");
}
@Override
public ResultSet getClientInfoProperties() throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getClientInfoProperties is not supported");
}
@Override
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getFunctions is not supported");
}
@Override
public ResultSet getFunctionColumns(
String catalog,
String schemaPattern,
String functionNamePattern,
String columnNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getFunctionColumns is not supported");
}
@Override
public ResultSet getPseudoColumns(
String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException(
"FlinkDatabaseMetaData#getPseudoColumns is not supported");
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLFeatureNotSupportedException("FlinkDatabaseMetaData#unwrap is not supported");
}
}
| BaseDatabaseMetaData |
java | hibernate__hibernate-orm | hibernate-vector/src/main/java/org/hibernate/vector/internal/MySQLTypeContributor.java | {
"start": 860,
"end": 2931
} | class ____ implements TypeContributor {
@Override
public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
final Dialect dialect = serviceRegistry.requireService( JdbcServices.class ).getDialect();
if ( dialect instanceof MySQLDialect mySQLDialect && mySQLDialect.getMySQLVersion().isSameOrAfter( 9, 0 ) ) {
final TypeConfiguration typeConfiguration = typeContributions.getTypeConfiguration();
final JavaTypeRegistry javaTypeRegistry = typeConfiguration.getJavaTypeRegistry();
final JdbcTypeRegistry jdbcTypeRegistry = typeConfiguration.getJdbcTypeRegistry();
final BasicTypeRegistry basicTypeRegistry = typeConfiguration.getBasicTypeRegistry();
final BasicType<Float> floatBasicType = basicTypeRegistry.resolve( StandardBasicTypes.FLOAT );
final ArrayJdbcType genericVectorJdbcType = new MySQLVectorJdbcType(
jdbcTypeRegistry.getDescriptor( SqlTypes.FLOAT ),
SqlTypes.VECTOR
);
jdbcTypeRegistry.addDescriptor( SqlTypes.VECTOR, genericVectorJdbcType );
final ArrayJdbcType floatVectorJdbcType = new MySQLVectorJdbcType(
jdbcTypeRegistry.getDescriptor( SqlTypes.FLOAT ),
SqlTypes.VECTOR_FLOAT32
);
jdbcTypeRegistry.addDescriptor( SqlTypes.VECTOR_FLOAT32, floatVectorJdbcType );
basicTypeRegistry.register(
new BasicArrayType<>(
floatBasicType,
genericVectorJdbcType,
javaTypeRegistry.getDescriptor( float[].class )
),
StandardBasicTypes.VECTOR.getName()
);
basicTypeRegistry.register(
new BasicArrayType<>(
basicTypeRegistry.resolve( StandardBasicTypes.FLOAT ),
floatVectorJdbcType,
javaTypeRegistry.getDescriptor( float[].class )
),
StandardBasicTypes.VECTOR_FLOAT32.getName()
);
typeConfiguration.getDdlTypeRegistry().addDescriptor(
new VectorDdlType( SqlTypes.VECTOR, "vector($l)", "vector", dialect )
);
typeConfiguration.getDdlTypeRegistry().addDescriptor(
new VectorDdlType( SqlTypes.VECTOR_FLOAT32, "vector($l)", "vector", dialect )
);
}
}
}
| MySQLTypeContributor |
java | apache__camel | components/camel-as2/camel-as2-api/src/main/java/org/apache/camel/component/as2/api/entity/DispositionNotificationOptions.java | {
"start": 936,
"end": 1484
} | class ____ {
private Parameter signedReceiptProtocol;
private Parameter signedReceiptMicalg;
public DispositionNotificationOptions(Parameter signedReceiptProtocol, Parameter signedReceiptMicalg) {
this.signedReceiptProtocol = signedReceiptProtocol;
this.signedReceiptMicalg = signedReceiptMicalg;
}
public Parameter getSignedReceiptProtocol() {
return signedReceiptProtocol;
}
public Parameter getSignedReceiptMicalg() {
return signedReceiptMicalg;
}
}
| DispositionNotificationOptions |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/PendingCheckpoint.java | {
"start": 3104,
"end": 3241
} | class ____ implements Checkpoint {
/** Result of the {@link PendingCheckpoint#acknowledgedTasks} method. */
public | PendingCheckpoint |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/view/DefaultRenderingBuilderTests.java | {
"start": 1037,
"end": 4181
} | class ____ {
@Test
void defaultValues() {
Rendering rendering = Rendering.view("abc").build();
assertThat(rendering.view()).isEqualTo("abc");
assertThat(rendering.modelAttributes()).isEqualTo(Collections.emptyMap());
assertThat(rendering.status()).isNull();
assertThat(rendering.headers().isEmpty()).isTrue();
}
@Test
void defaultValuesForRedirect() {
Rendering rendering = Rendering.redirectTo("abc").build();
Object view = rendering.view();
assertThat(view).isExactlyInstanceOf(RedirectView.class);
RedirectView redirectView = (RedirectView) view;
assertThat(redirectView.getUrl()).isEqualTo("abc");
assertThat(redirectView.isContextRelative()).isTrue();
assertThat(redirectView.isPropagateQuery()).isFalse();
}
@Test
void viewName() {
Rendering rendering = Rendering.view("foo").build();
assertThat(rendering.view()).isEqualTo("foo");
}
@Test
void modelAttribute() {
Foo foo = new Foo();
Rendering rendering = Rendering.view("foo").modelAttribute(foo).build();
assertThat(rendering.modelAttributes()).isEqualTo(Collections.singletonMap("foo", foo));
}
@Test
void modelAttributes() {
Foo foo = new Foo();
Bar bar = new Bar();
Rendering rendering = Rendering.view("foo").modelAttributes(foo, bar).build();
Map<String, Object> map = new LinkedHashMap<>(2);
map.put("foo", foo);
map.put("bar", bar);
assertThat(rendering.modelAttributes()).isEqualTo(map);
}
@Test
void model() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("foo", new Foo());
map.put("bar", new Bar());
Rendering rendering = Rendering.view("foo").model(map).build();
assertThat(rendering.modelAttributes()).isEqualTo(map);
}
@Test
void header() {
Rendering rendering = Rendering.view("foo").header("foo", "bar").build();
assertThat(rendering.headers().size()).isOne();
assertThat(rendering.headers().get("foo")).isEqualTo(Collections.singletonList("bar"));
}
@Test
void httpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add("foo", "bar");
Rendering rendering = Rendering.view("foo").headers(headers).build();
assertThat(rendering.headers()).isEqualTo(headers);
}
@Test
void redirectWithAbsoluteUrl() {
Rendering rendering = Rendering.redirectTo("foo").contextRelative(false).build();
Object view = rendering.view();
assertThat(view).isExactlyInstanceOf(RedirectView.class);
assertThat(((RedirectView) view).isContextRelative()).isFalse();
}
@Test
void redirectWithPropagateQuery() {
Rendering rendering = Rendering.redirectTo("foo").propagateQuery(true).build();
Object view = rendering.view();
assertThat(view).isExactlyInstanceOf(RedirectView.class);
assertThat(((RedirectView) view).isPropagateQuery()).isTrue();
}
@Test // gh-33498
void redirectWithCustomStatus() {
HttpStatus status = HttpStatus.MOVED_PERMANENTLY;
Rendering rendering = Rendering.redirectTo("foo").status(status).build();
Object view = rendering.view();
assertThat(view).isExactlyInstanceOf(RedirectView.class);
assertThat(((RedirectView) view).getStatusCode()).isEqualTo(status);
}
private static | DefaultRenderingBuilderTests |
java | spring-projects__spring-boot | module/spring-boot-integration/src/main/java/org/springframework/boot/integration/autoconfigure/IntegrationProperties.java | {
"start": 4385,
"end": 5120
} | class ____ {
/**
* Whether to not silently ignore messages on the global 'errorChannel' when there
* are no subscribers.
*/
private boolean requireSubscribers = true;
/**
* Whether to ignore failures for one or more of the handlers of the global
* 'errorChannel'.
*/
private boolean ignoreFailures = true;
public boolean isRequireSubscribers() {
return this.requireSubscribers;
}
public void setRequireSubscribers(boolean requireSubscribers) {
this.requireSubscribers = requireSubscribers;
}
public boolean isIgnoreFailures() {
return this.ignoreFailures;
}
public void setIgnoreFailures(boolean ignoreFailures) {
this.ignoreFailures = ignoreFailures;
}
}
public static | Error |
java | apache__camel | components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2Constants.java | {
"start": 933,
"end": 2257
} | interface ____ {
@Metadata(description = "The sequence number of the record, as defined in\n" +
"http://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html#API_PutRecord_ResponseSyntax[Response Syntax]",
javaType = "String")
String SEQUENCE_NUMBER = "CamelAwsKinesisSequenceNumber";
@Metadata(description = "The time AWS assigned as the arrival time of the record.", javaType = "String")
String APPROX_ARRIVAL_TIME = "CamelAwsKinesisApproximateArrivalTimestamp";
@Metadata(description = "Identifies which shard in the stream the data record is assigned to.", javaType = "String")
String PARTITION_KEY = "CamelAwsKinesisPartitionKey";
@Metadata(description = "The timestamp of the message", javaType = "long")
String MESSAGE_TIMESTAMP = Exchange.MESSAGE_TIMESTAMP;
@Metadata(label = "consumer", description = "The resume action to execute when resuming.", javaType = "String")
String RESUME_ACTION = "CamelKinesisDbResumeAction";
/**
* in a Kinesis Record object, the shard ID is used on writes to indicate where the data was stored
*/
@Metadata(description = "The shard ID of the shard where the data record was placed.", javaType = "String")
String SHARD_ID = "CamelAwsKinesisShardId";
}
| Kinesis2Constants |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plugin/ClusterComputeRequest.java | {
"start": 1843,
"end": 6042
} | class ____ extends AbstractTransportRequest implements IndicesRequest.Replaceable {
private final String clusterAlias;
private final String sessionId;
private final Configuration configuration;
private final RemoteClusterPlan plan;
private transient String[] indices;
/**
* A request to start a compute on a remote cluster.
*
* @param clusterAlias the cluster alias of this remote cluster
* @param sessionId the sessionId in which the output pages will be placed in the exchange sink specified by this id
* @param configuration the configuration for this compute
* @param plan the physical plan to be executed
*/
ClusterComputeRequest(String clusterAlias, String sessionId, Configuration configuration, RemoteClusterPlan plan) {
this.clusterAlias = clusterAlias;
this.sessionId = sessionId;
this.configuration = configuration;
this.plan = plan;
this.indices = plan.originalIndices().indices();
}
ClusterComputeRequest(StreamInput in) throws IOException {
this(in, null);
}
/**
* @param idMapper must always be null in production. Only used in tests to remap NameIds when deserializing.
*/
ClusterComputeRequest(StreamInput in, PlanStreamInput.NameIdMapper idMapper) throws IOException {
super(in);
this.clusterAlias = in.readString();
this.sessionId = in.readString();
this.configuration = new Configuration(
// TODO make EsqlConfiguration Releasable
new BlockStreamInput(in, new BlockFactory(new NoopCircuitBreaker(CircuitBreaker.REQUEST), BigArrays.NON_RECYCLING_INSTANCE))
);
this.plan = RemoteClusterPlan.from(new PlanStreamInput(in, in.namedWriteableRegistry(), configuration, idMapper));
this.indices = plan.originalIndices().indices();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(clusterAlias);
out.writeString(sessionId);
configuration.writeTo(out);
plan.writeTo(new PlanStreamOutput(out, configuration));
}
@Override
public String[] indices() {
return indices;
}
@Override
public IndicesRequest indices(String... indices) {
this.indices = indices;
return this;
}
@Override
public IndicesOptions indicesOptions() {
return plan.originalIndices().indicesOptions();
}
@Override
public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) {
if (parentTaskId.isSet() == false) {
assert false : "DataNodeRequest must have a parent task";
throw new IllegalStateException("DataNodeRequest must have a parent task");
}
return new CancellableTask(id, type, action, "", parentTaskId, headers) {
@Override
public String getDescription() {
return ClusterComputeRequest.this.getDescription();
}
};
}
String clusterAlias() {
return clusterAlias;
}
String sessionId() {
return sessionId;
}
Configuration configuration() {
return configuration;
}
RemoteClusterPlan remoteClusterPlan() {
return plan;
}
@Override
public String getDescription() {
return "plan=" + plan;
}
@Override
public String toString() {
return "ClusterComputeRequest{" + getDescription() + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClusterComputeRequest request = (ClusterComputeRequest) o;
return clusterAlias.equals(request.clusterAlias)
&& sessionId.equals(request.sessionId)
&& configuration.equals(request.configuration)
&& plan.equals(request.plan)
&& getParentTask().equals(request.getParentTask());
}
@Override
public int hashCode() {
return Objects.hash(sessionId, configuration, plan);
}
}
| ClusterComputeRequest |
java | quarkusio__quarkus | extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/instrumentation/GraphQLOpenTelemetryTest.java | {
"start": 9973,
"end": 13822
} | class ____ {
@WithSpan
public void waitForSomeTime() throws InterruptedException {
Thread.sleep(10);
}
}
private Void assertSuccessfulRequestContainingMessages(String request, String... messages) {
org.hamcrest.Matcher messageMatcher = Arrays.stream(messages)
.map(CoreMatchers::containsString)
.reduce(Matchers.allOf(), (a, b) -> Matchers.allOf(a, b));
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(request)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.body(messageMatcher);
return null;
}
private void assertTimeForSpans(List<SpanData> spans) {
// Method expects for each span to have at least one child span
if (spans.size() <= 1) {
return;
}
SpanData current = getSpanByKindAndParentId(spans, SpanKind.SERVER, "0000000000000000");
for (int i = 0; i < spans.size() - 1; i++) {
SpanData successor = getSpanByKindAndParentId(spans, SpanKind.INTERNAL, current.getSpanId());
assertTrue(current.getStartEpochNanos() <= successor.getStartEpochNanos());
assertTrue(current.getEndEpochNanos() >= successor.getEndEpochNanos());
current = successor;
}
}
private SpanData assertHttpSpan(List<SpanData> spans) {
final SpanData server = getSpanByKindAndParentId(spans, SpanKind.SERVER, "0000000000000000");
assertEquals("POST /graphql", server.getName());
assertSemanticAttribute(server, (long) HTTP_OK, HTTP_RESPONSE_STATUS_CODE);
assertSemanticAttribute(server, "POST", HTTP_REQUEST_METHOD);
assertEquals("/graphql", server.getAttributes().get(HTTP_ROUTE));
return server;
}
private void assertGraphQLSpan(SpanData span, String name, String OperationType, String OperationName) {
assertEquals(name, span.getName());
assertNotNull(span.getAttributes().get(stringKey("graphql.executionId")));
assertEquals(OperationType, span.getAttributes().get(stringKey("graphql.operationType")));
assertEquals(OperationName, span.getAttributes().get(stringKey("graphql.operationName")));
}
private String getPayload(String query, String variables) {
JsonObject jsonObject = createRequestBody(query, variables);
return jsonObject.toString();
}
private JsonObject createRequestBody(String graphQL, String variables) {
JsonObjectBuilder job = Json.createObjectBuilder();
JsonObject vjo = Json.createObjectBuilder().build();
// Extract the operation name from the GraphQL query
String operationName = null;
if (graphQL != null && !graphQL.isEmpty()) {
Matcher matcher = Pattern.compile("(query|mutation|subscription)\\s+([\\w-]+)?").matcher(graphQL);
if (matcher.find()) {
operationName = matcher.group(2);
job.add(QUERY, graphQL);
}
}
// Parse variables if present
if (variables != null && !variables.isEmpty()) {
try (JsonReader jsonReader = Json.createReader(new StringReader(variables))) {
vjo = jsonReader.readObject();
}
}
if (operationName != null) {
job.add(OPERATION_NAME, operationName);
}
return job.add(VARIABLES, vjo).build();
}
private static final String MEDIATYPE_JSON = "application/json";
private static final String QUERY = "query";
private static final String VARIABLES = "variables";
private static final String OPERATION_NAME = "operationName";
}
| CustomCDIBean |
java | quarkusio__quarkus | test-framework/junit5-component/src/main/java/io/quarkus/test/component/ConfigPropertyBeanCreator.java | {
"start": 428,
"end": 2469
} | class ____ implements BeanCreator<Object> {
@Override
public Object create(SyntheticCreationalContext<Object> context) {
InjectionPoint injectionPoint = context.getInjectedReference(InjectionPoint.class);
if (Boolean.TRUE.equals(context.getParams().get("useDefaultConfigProperties"))) {
try {
return ConfigProducerUtil.getValue(injectionPoint, ConfigBeanCreator.getConfig());
} catch (NoSuchElementException e) {
Class<?> rawType = getRawType(injectionPoint.getType());
if (rawType == null) {
throw new IllegalStateException("Unable to get the raw type for: " + injectionPoint.getType());
}
if (rawType.isPrimitive()) {
if (rawType == boolean.class) {
return false;
} else if (rawType == char.class) {
return Character.MIN_VALUE;
} else {
return 0;
}
}
return null;
}
} else {
return ConfigProducerUtil.getValue(injectionPoint, ConfigBeanCreator.getConfig());
}
}
@SuppressWarnings("unchecked")
private static <T> Class<T> getRawType(Type type) {
if (type instanceof Class<?>) {
return (Class<T>) type;
}
if (type instanceof ParameterizedType) {
if (((ParameterizedType) type).getRawType() instanceof Class<?>) {
return (Class<T>) ((ParameterizedType) type).getRawType();
}
}
if (type instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) type;
Class<?> rawType = getRawType(genericArrayType.getGenericComponentType());
if (rawType != null) {
return (Class<T>) Array.newInstance(rawType, 0).getClass();
}
}
return null;
}
}
| ConfigPropertyBeanCreator |
java | google__guava | guava/src/com/google/common/collect/ImmutableList.java | {
"start": 2530,
"end": 17099
} | class ____<E> extends ImmutableCollection<E>
implements List<E>, RandomAccess {
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code
* ImmutableList}, in encounter order.
*
* @since 21.0
*/
public static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
return CollectCollectors.toImmutableList();
}
/**
* Returns the empty immutable list. This list behaves and performs comparably to {@link
* Collections#emptyList}, and is preferable mainly for consistency and maintainability of your
* code.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
// Casting to any type is safe because the list will never hold any elements.
@SuppressWarnings("unchecked")
public static <E> ImmutableList<E> of() {
return (ImmutableList<E>) EMPTY;
}
/**
* Returns an immutable list containing a single element. This list behaves and performs
* comparably to {@link Collections#singletonList}, but will not accept a null element. It is
* preferable mainly for consistency and maintainability of your code.
*
* @throws NullPointerException if the element is null
*/
public static <E> ImmutableList<E> of(E e1) {
return new SingletonImmutableList<>(e1);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2) {
return construct(e1, e2);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
return construct(e1, e2, e3);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
return construct(e1, e2, e3, e4);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
return construct(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
return construct(e1, e2, e3, e4, e5, e6);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
return construct(e1, e2, e3, e4, e5, e6, e7);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
}
// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(
/**
* Returns an immutable list containing the given elements, in order.
*
* <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
@SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) {
checkArgument(
others.length <= Integer.MAX_VALUE - 12, "the total number of elements must fit in an int");
Object[] array = new Object[12 + others.length];
array[0] = e1;
array[1] = e2;
array[2] = e3;
array[3] = e4;
array[4] = e5;
array[5] = e6;
array[6] = e7;
array[7] = e8;
array[8] = e9;
array[9] = e10;
array[10] = e11;
array[11] = e12;
System.arraycopy(others, 0, array, 12, others.length);
return construct(array);
}
/**
* Returns an immutable list containing the given elements, in order. If {@code elements} is a
* {@link Collection}, this method behaves exactly as {@link #copyOf(Collection)}; otherwise, it
* behaves exactly as {@code copyOf(elements.iterator()}.
*
* @throws NullPointerException if {@code elements} contains a null element
*/
public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
return (elements instanceof Collection)
? copyOf((Collection<? extends E>) elements)
: copyOf(elements.iterator());
}
/**
* Returns an immutable list containing the given elements, in order.
*
* <p>Despite the method name, this method attempts to avoid actually copying the data when it is
* safe to do so. The exact circumstances under which a copy will or will not be performed are
* undocumented and subject to change.
*
* <p>Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)}
* returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while
* {@code ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one
* element (the given list itself).
*
* <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
* collection that is currently being modified by another thread.
*
* @throws NullPointerException if {@code elements} contains a null element
*/
public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
if (elements instanceof ImmutableCollection) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
return list.isPartialView() ? asImmutableList(list.toArray()) : list;
}
return construct(elements.toArray());
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if {@code elements} contains a null element
*/
public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
// We special-case for 0 or 1 elements, but going further is madness.
if (!elements.hasNext()) {
return of();
}
E first = elements.next();
if (!elements.hasNext()) {
return of(first);
} else {
return new ImmutableList.Builder<E>().add(first).addAll(elements).build();
}
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if {@code elements} contains a null element
* @since 3.0
*/
public static <E> ImmutableList<E> copyOf(E[] elements) {
switch (elements.length) {
case 0:
return of();
case 1:
return of(elements[0]);
default:
return construct(elements.clone());
}
}
/**
* Returns an immutable list containing the given elements, sorted according to their natural
* order. The sorting algorithm used is stable, so elements that compare as equal will stay in the
* order in which they appear in the input.
*
* <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code
* ImmutableSortedSet.copyOf(elements)}; if you want a {@code List} you can use its {@code
* asList()} view.
*
* <p><b>Java 8+ users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted
* {@code ImmutableList}, use {@code stream.sorted().collect(toImmutableList())}.
*
* @throws NullPointerException if any element in the input is null
* @since 21.0
*/
public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf(
Iterable<? extends E> elements) {
Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]);
checkElementsNotNull((Object[]) array);
Arrays.sort(array);
return asImmutableList(array);
}
/**
* Returns an immutable list containing the given elements, in sorted order relative to the
* specified comparator. The sorting algorithm used is stable, so elements that compare as equal
* will stay in the order in which they appear in the input.
*
* <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code
* ImmutableSortedSet.copyOf(comparator, elements)}; if you want a {@code List} you can use its
* {@code asList()} view.
*
* <p><b>Java 8+ users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted
* {@code ImmutableList}, use {@code stream.sorted(comparator).collect(toImmutableList())}.
*
* @throws NullPointerException if any element in the input is null
* @since 21.0
*/
public static <E> ImmutableList<E> sortedCopyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
checkNotNull(comparator);
@SuppressWarnings("unchecked") // all supported methods are covariant
E[] array = (E[]) Iterables.toArray(elements);
checkElementsNotNull(array);
Arrays.sort(array, comparator);
return asImmutableList(array);
}
/** Views the array as an immutable list. Checks for nulls; does not copy. */
private static <E> ImmutableList<E> construct(Object... elements) {
return asImmutableList(checkElementsNotNull(elements));
}
/**
* Views the array as an immutable list. Does not check for nulls; does not copy.
*
* <p>The array must be internally created.
*/
static <E> ImmutableList<E> asImmutableList(Object[] elements) {
return asImmutableList(elements, elements.length);
}
/**
* Views the array as an immutable list. Copies if the specified range does not cover the complete
* array. Does not check for nulls.
*/
static <E> ImmutableList<E> asImmutableList(@Nullable Object[] elements, int length) {
switch (length) {
case 0:
return of();
case 1:
/*
* requireNonNull is safe because the callers promise to put non-null objects in the first
* `length` array elements.
*/
@SuppressWarnings("unchecked") // our callers put only E instances into the array
E onlyElement = (E) requireNonNull(elements[0]);
return of(onlyElement);
default:
/*
* The suppression is safe because the callers promise to put non-null objects in the first
* `length` array elements.
*/
@SuppressWarnings("nullness")
Object[] elementsWithoutTrailingNulls =
length < elements.length ? Arrays.copyOf(elements, length) : elements;
return new RegularImmutableList<>(elementsWithoutTrailingNulls);
}
}
ImmutableList() {}
// This declaration is needed to make List.iterator() and
// ImmutableCollection.iterator() consistent.
@Override
public UnmodifiableIterator<E> iterator() {
return listIterator();
}
@Override
public UnmodifiableListIterator<E> listIterator() {
return listIterator(0);
}
@Override
public UnmodifiableListIterator<E> listIterator(int index) {
return new AbstractIndexedListIterator<E>(size(), index) {
@Override
protected E get(int index) {
return ImmutableList.this.get(index);
}
};
}
@Override
public void forEach(Consumer<? super E> consumer) {
checkNotNull(consumer);
int n = size();
for (int i = 0; i < n; i++) {
consumer.accept(get(i));
}
}
@Override
public int indexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.indexOfImpl(this, object);
}
@Override
public int lastIndexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
}
@Override
public boolean contains(@Nullable Object object) {
return indexOf(object) >= 0;
}
// constrain the return type to ImmutableList<E>
/**
* Returns an immutable list of the elements between the specified {@code fromIndex}, inclusive,
* and {@code toIndex}, exclusive. (If {@code fromIndex} and {@code toIndex} are equal, the empty
* immutable list is returned.)
*
* <p><b>Note:</b> in almost all circumstances, the returned {@link ImmutableList} retains a
* strong reference to {@code this}, which may prevent the original list from being garbage
* collected. If you want the original list to be eligible for garbage collection, you should
* create and use a copy of the sub list (e.g., {@code
* ImmutableList.copyOf(originalList.subList(...))}).
*/
@Override
public ImmutableList<E> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
int length = toIndex - fromIndex;
if (length == size()) {
return this;
} else if (length == 0) {
return of();
} else if (length == 1) {
return of(get(fromIndex));
} else {
return subListUnchecked(fromIndex, toIndex);
}
}
/**
* Called by the default implementation of {@link #subList} when {@code toIndex - fromIndex > 1},
* after index validation has already been performed.
*/
ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
return new SubList(fromIndex, toIndex - fromIndex);
}
private final | ImmutableList |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java | {
"start": 1546,
"end": 3728
} | class ____ extends ContextTestSupport {
private final List<String> logs = new ArrayList<>();
private Condition exceptionCondition;
private Breakpoint breakpoint;
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
breakpoint = new BreakpointSupport() {
public void onEvent(Exchange exchange, ExchangeEvent event, NamedNode definition) {
Exception e = event.getExchange().getException();
logs.add("Breakpoint at " + definition + " caused by: " + e.getClass().getSimpleName() + "[" + e.getMessage()
+ "]");
}
};
exceptionCondition = new ConditionSupport() {
public boolean matchEvent(Exchange exchange, ExchangeEvent event) {
return event.getType() == Type.ExchangeFailed;
}
};
}
@Test
public void testDebug() throws Exception {
context.getDebugger().addBreakpoint(breakpoint, exceptionCondition);
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "Hello World");
try {
template.sendBody("direct:start", "Hello Camel");
fail("Should have thrown exception");
} catch (Exception e) {
// ignore
}
assertMockEndpointsSatisfied();
assertEquals(1, logs.size());
assertEquals(
"Breakpoint at ThrowException[java.lang.IllegalArgumentException] caused by: IllegalArgumentException[Damn]",
logs.get(0));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// turn on debugging
context.setDebugging(true);
context.setDebugger(new DefaultDebugger());
from("direct:start").to("log:foo").choice().when(body().contains("Camel"))
.throwException(new IllegalArgumentException("Damn")).end().to("mock:result");
}
};
}
}
| DebugExceptionEventBreakpointTest |
java | spring-projects__spring-boot | module/spring-boot-session/src/test/java/org/springframework/boot/session/actuate/endpoint/ReactiveSessionsEndpointWebIntegrationTests.java | {
"start": 4419,
"end": 4598
} | class ____ {
@Bean
ReactiveSessionsEndpoint sessionsEndpoint() {
return new ReactiveSessionsEndpoint(sessionRepository, indexedSessionRepository);
}
}
}
| TestConfiguration |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/params/aggregator/AggregatorIntegrationTests.java | {
"start": 9605,
"end": 9765
} | interface ____ {
int value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@AggregateWith(PersonAggregator.class)
public @ | StartIndex |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/execution/PipelineExecutor.java | {
"start": 1136,
"end": 2156
} | interface ____ {
/**
* Executes a {@link Pipeline} based on the provided configuration and returns a {@link
* JobClient} which allows to interact with the job being executed, e.g. cancel it or take a
* savepoint.
*
* <p><b>ATTENTION:</b> The caller is responsible for managing the lifecycle of the returned
* {@link JobClient}. This means that e.g. {@code close()} should be called explicitly at the
* call-site.
*
* @param pipeline the {@link Pipeline} to execute
* @param configuration the {@link Configuration} with the required execution parameters
* @param userCodeClassloader the {@link ClassLoader} to deserialize usercode
* @return a {@link CompletableFuture} with the {@link JobClient} corresponding to the pipeline.
*/
CompletableFuture<JobClient> execute(
final Pipeline pipeline,
final Configuration configuration,
final ClassLoader userCodeClassloader)
throws Exception;
}
| PipelineExecutor |
java | google__guava | guava/src/com/google/common/util/concurrent/AbstractIdleService.java | {
"start": 2199,
"end": 5964
} | class ____ extends AbstractService {
@Override
protected final void doStart() {
renamingDecorator(executor(), threadNameSupplier)
.execute(
() -> {
try {
startUp();
notifyStarted();
} catch (Throwable t) {
restoreInterruptIfIsInterruptedException(t);
notifyFailed(t);
}
});
}
@Override
protected final void doStop() {
renamingDecorator(executor(), threadNameSupplier)
.execute(
() -> {
try {
shutDown();
notifyStopped();
} catch (Throwable t) {
restoreInterruptIfIsInterruptedException(t);
notifyFailed(t);
}
});
}
@Override
public String toString() {
return AbstractIdleService.this.toString();
}
}
/** Constructor for use by subclasses. */
protected AbstractIdleService() {}
/** Start the service. */
protected abstract void startUp() throws Exception;
/** Stop the service. */
protected abstract void shutDown() throws Exception;
/**
* Returns the {@link Executor} that will be used to run this service. Subclasses may override
* this method to use a custom {@link Executor}, which may configure its worker thread with a
* specific name, thread group or priority. The returned executor's {@link
* Executor#execute(Runnable) execute()} method is called when this service is started and
* stopped, and should return promptly.
*/
protected Executor executor() {
return command -> newThread(threadNameSupplier.get(), command).start();
}
@Override
public String toString() {
return serviceName() + " [" + state() + "]";
}
@Override
public final boolean isRunning() {
return delegate.isRunning();
}
@Override
public final State state() {
return delegate.state();
}
/**
* @since 13.0
*/
@Override
public final void addListener(Listener listener, Executor executor) {
delegate.addListener(listener, executor);
}
/**
* @since 14.0
*/
@Override
public final Throwable failureCause() {
return delegate.failureCause();
}
/**
* @since 15.0
*/
@CanIgnoreReturnValue
@Override
public final Service startAsync() {
delegate.startAsync();
return this;
}
/**
* @since 15.0
*/
@CanIgnoreReturnValue
@Override
public final Service stopAsync() {
delegate.stopAsync();
return this;
}
/**
* @since 15.0
*/
@Override
public final void awaitRunning() {
delegate.awaitRunning();
}
/**
* @since 28.0
*/
@Override
public final void awaitRunning(Duration timeout) throws TimeoutException {
Service.super.awaitRunning(timeout);
}
/**
* @since 15.0
*/
@Override
public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException {
delegate.awaitRunning(timeout, unit);
}
/**
* @since 15.0
*/
@Override
public final void awaitTerminated() {
delegate.awaitTerminated();
}
/**
* @since 28.0
*/
@Override
public final void awaitTerminated(Duration timeout) throws TimeoutException {
Service.super.awaitTerminated(timeout);
}
/**
* @since 15.0
*/
@Override
public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
delegate.awaitTerminated(timeout, unit);
}
/**
* Returns the name of this service. {@link AbstractIdleService} may include the name in debugging
* output.
*
* @since 14.0
*/
protected String serviceName() {
return getClass().getSimpleName();
}
}
| DelegateService |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/streaming/api/environment/RemoteStreamEnvironmentTest.java | {
"start": 5153,
"end": 7153
} | class ____ implements PipelineExecutorServiceLoader {
private final JobID jobID;
private TestClusterClient clusterClient;
private SavepointRestoreSettings actualSavepointRestoreSettings;
TestExecutorServiceLoader(final JobID jobID) {
this.jobID = checkNotNull(jobID);
}
public TestClusterClient getCreatedClusterClient() {
return clusterClient;
}
public SavepointRestoreSettings getActualSavepointRestoreSettings() {
return actualSavepointRestoreSettings;
}
@Override
public PipelineExecutorFactory getExecutorFactory(@Nonnull Configuration configuration) {
return new PipelineExecutorFactory() {
@Override
public String getName() {
return "my-name";
}
@Override
public boolean isCompatibleWith(@Nonnull Configuration configuration) {
return true;
}
@Override
public PipelineExecutor getExecutor(@Nonnull Configuration configuration) {
return (pipeline, config, classLoader) -> {
assertTrue(pipeline instanceof StreamGraph);
actualSavepointRestoreSettings =
SavepointRestoreSettings.fromConfiguration(config);
clusterClient = new TestClusterClient(configuration, jobID);
return CompletableFuture.completedFuture(
new ClusterClientJobClientAdapter<>(
() -> clusterClient, jobID, classLoader));
};
}
};
}
@Override
public Stream<String> getExecutorNames() {
throw new UnsupportedOperationException("not implemented");
}
}
private static final | TestExecutorServiceLoader |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityExceptionHandler.java | {
"start": 2282,
"end": 2504
} | class ____ an {@code @ExceptionHandler} method that handles all Spring
* WebFlux raised exceptions by returning a {@link ResponseEntity} with
* RFC 9457 formatted error details in the body.
*
* <p>Convenient as a base | with |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/cache/ContextFailureThresholdTests.java | {
"start": 1974,
"end": 3613
} | class ____ {
private static final AtomicInteger passingLoadCount = new AtomicInteger();
private static final AtomicInteger failingLoadCount = new AtomicInteger();
@BeforeEach
@AfterEach
void resetTestFixtures() {
resetContextCache();
passingLoadCount.set(0);
failingLoadCount.set(0);
SpringProperties.setProperty(CONTEXT_FAILURE_THRESHOLD_PROPERTY_NAME, null);
}
@Test
void defaultThreshold() {
runTests();
assertThat(passingLoadCount.get()).isEqualTo(1);
assertThat(failingLoadCount.get()).isEqualTo(DEFAULT_CONTEXT_FAILURE_THRESHOLD);
}
@Test
void customThreshold() {
int customThreshold = 2;
SpringProperties.setProperty(CONTEXT_FAILURE_THRESHOLD_PROPERTY_NAME, Integer.toString(customThreshold));
runTests();
assertThat(passingLoadCount.get()).isEqualTo(1);
assertThat(failingLoadCount.get()).isEqualTo(customThreshold);
}
@Test
void thresholdEffectivelyDisabled() {
SpringProperties.setProperty(CONTEXT_FAILURE_THRESHOLD_PROPERTY_NAME, "999999");
runTests();
assertThat(passingLoadCount.get()).isEqualTo(1);
assertThat(failingLoadCount.get()).isEqualTo(6);
}
private static void runTests() {
EngineTestKit.engine("junit-jupiter")
.selectors(selectClasses(
PassingTestCase.class, // 3 passing
FailingConfigTestCase.class, // 3 failing
SharedFailingConfigTestCase.class // 3 failing
))
.execute()
.testEvents()
.assertStatistics(stats -> stats.started(9).succeeded(3).failed(6));
assertContextCacheStatistics(1, 2, (1 + 3 + 3));
}
@TestExecutionListeners(DependencyInjectionTestExecutionListener.class)
abstract static | ContextFailureThresholdTests |
java | spring-projects__spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java | {
"start": 23868,
"end": 24669
} | class ____ implements Serializable {
@Serial
private static final long serialVersionUID = 7495627155437124692L;
private boolean requireProofKey;
private ClientSettings() {
}
public boolean isRequireProofKey() {
return this.requireProofKey;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ClientSettings that)) {
return false;
}
return this.requireProofKey == that.requireProofKey;
}
@Override
public int hashCode() {
return Objects.hashCode(this.requireProofKey);
}
@Override
public String toString() {
return "ClientSettings{" + "requireProofKey=" + this.requireProofKey + '}';
}
public static Builder builder() {
return new Builder();
}
public static final | ClientSettings |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/filter/FilteringGeneratorDelegate.java | {
"start": 30797,
"end": 31268
} | class ____ for these seems correct to me, iff not directly delegating:
/*
@Override
public JsonGenerator writeObject(Object pojo) {
...
}
@Override
public JsonGenerator writeTree(TreeNode rootNode) {
...
}
*/
/*
/**********************************************************************
/* Public API, copy-through methods
/**********************************************************************
*/
// Base | definitions |
java | quarkusio__quarkus | integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacAndServiceAccountTest.java | {
"start": 874,
"end": 4219
} | class ____ {
private static final String APP_NAME = "kubernetes-with-rbac-and-service-account";
private static final String SERVICE_ACCOUNT = "my-service-account";
private static final String ROLE = "my-role";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
.setApplicationName(APP_NAME)
.setApplicationVersion("0.1-SNAPSHOT")
.withConfigurationResource(APP_NAME + ".properties");
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
public void assertGeneratedResources() throws IOException {
final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
List<HasMetadata> kubernetesList = DeserializationUtil
.deserializeAsList(kubernetesDir.resolve("kubernetes.yml"));
Deployment deployment = getDeploymentByName(kubernetesList, APP_NAME);
assertThat(deployment.getSpec().getTemplate().getSpec().getServiceAccountName()).isEqualTo(SERVICE_ACCOUNT);
// my-role assertions
Role myRole = getRoleByName(kubernetesList, ROLE);
assertThat(myRole.getRules()).satisfiesOnlyOnce(r -> {
assertThat(r.getApiGroups()).containsExactly("extensions", "apps");
assertThat(r.getResources()).containsExactly("deployments");
assertThat(r.getVerbs()).containsExactly("get", "watch", "list");
});
// service account
ServiceAccount serviceAccount = getServiceAccountByName(kubernetesList, SERVICE_ACCOUNT);
assertThat(serviceAccount).isNotNull();
// role binding
RoleBinding roleBinding = getRoleBindingByName(kubernetesList, "my-role-binding");
assertEquals("Role", roleBinding.getRoleRef().getKind());
assertEquals(ROLE, roleBinding.getRoleRef().getName());
Subject subject = roleBinding.getSubjects().get(0);
assertEquals("ServiceAccount", subject.getKind());
assertEquals(SERVICE_ACCOUNT, subject.getName());
}
private Deployment getDeploymentByName(List<HasMetadata> kubernetesList, String name) {
return getResourceByName(kubernetesList, Deployment.class, name);
}
private Role getRoleByName(List<HasMetadata> kubernetesList, String roleName) {
return getResourceByName(kubernetesList, Role.class, roleName);
}
private ServiceAccount getServiceAccountByName(List<HasMetadata> kubernetesList, String saName) {
return getResourceByName(kubernetesList, ServiceAccount.class, saName);
}
private RoleBinding getRoleBindingByName(List<HasMetadata> kubernetesList, String rbName) {
return getResourceByName(kubernetesList, RoleBinding.class, rbName);
}
private <T extends HasMetadata> T getResourceByName(List<HasMetadata> kubernetesList, Class<T> clazz, String name) {
Optional<T> resource = kubernetesList.stream()
.filter(r -> r.getMetadata().getName().equals(name))
.filter(clazz::isInstance)
.map(clazz::cast)
.findFirst();
assertTrue(resource.isPresent(), name + " resource not found!");
return resource.get();
}
}
| KubernetesWithRbacAndServiceAccountTest |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/util/DataFormatConverters.java | {
"start": 11128,
"end": 21084
} | class ____ TIMESTAMP WITH LOCAL TIME ZONE: "
+ clazz);
}
case ARRAY:
if (clazz == ArrayData.class) {
return ArrayDataConverter.INSTANCE;
} else if (clazz == boolean[].class) {
return PrimitiveBooleanArrayConverter.INSTANCE;
} else if (clazz == short[].class) {
return PrimitiveShortArrayConverter.INSTANCE;
} else if (clazz == int[].class) {
return PrimitiveIntArrayConverter.INSTANCE;
} else if (clazz == long[].class) {
return PrimitiveLongArrayConverter.INSTANCE;
} else if (clazz == float[].class) {
return PrimitiveFloatArrayConverter.INSTANCE;
} else if (clazz == double[].class) {
return PrimitiveDoubleArrayConverter.INSTANCE;
}
if (dataType instanceof CollectionDataType) {
return new ObjectArrayConverter(
((CollectionDataType) dataType)
.getElementDataType()
.bridgedTo(clazz.getComponentType()));
} else {
BasicArrayTypeInfo typeInfo =
(BasicArrayTypeInfo)
((LegacyTypeInformationType) dataType.getLogicalType())
.getTypeInformation();
return new ObjectArrayConverter(
fromLegacyInfoToDataType(typeInfo.getComponentInfo())
.bridgedTo(clazz.getComponentType()));
}
case MAP:
if (clazz == MapData.class) {
return MapDataConverter.INSTANCE;
}
KeyValueDataType keyValueDataType = (KeyValueDataType) dataType;
return new MapConverter(
keyValueDataType.getKeyDataType(), keyValueDataType.getValueDataType());
case MULTISET:
if (clazz == MapData.class) {
return MapDataConverter.INSTANCE;
}
CollectionDataType collectionDataType = (CollectionDataType) dataType;
return new MapConverter(
collectionDataType.getElementDataType(),
DataTypes.INT().bridgedTo(Integer.class));
case ROW:
case STRUCTURED_TYPE:
TypeInformation<?> asTypeInfo = fromDataTypeToTypeInfo(dataType);
if (asTypeInfo instanceof InternalTypeInfo && clazz == RowData.class) {
LogicalType realLogicalType =
((InternalTypeInfo<?>) asTypeInfo).toLogicalType();
return new RowDataConverter(getFieldCount(realLogicalType));
}
// legacy
CompositeType compositeType = (CompositeType) asTypeInfo;
DataType[] fieldTypes =
Stream.iterate(0, x -> x + 1)
.limit(compositeType.getArity())
.map((Function<Integer, TypeInformation>) compositeType::getTypeAt)
.map(TypeConversions::fromLegacyInfoToDataType)
.toArray(DataType[]::new);
if (clazz == RowData.class) {
return new RowDataConverter(compositeType.getArity());
} else if (clazz == Row.class) {
return new RowConverter(fieldTypes);
} else if (Tuple.class.isAssignableFrom(clazz)) {
return new TupleConverter((Class<Tuple>) clazz, fieldTypes);
} else if (CaseClassConverter.PRODUCT_CLASS != null
&& CaseClassConverter.PRODUCT_CLASS.isAssignableFrom(clazz)) {
return new CaseClassConverter((TupleTypeInfoBase) compositeType, fieldTypes);
} else if (compositeType instanceof PojoTypeInfo) {
return new PojoConverter((PojoTypeInfo) compositeType, fieldTypes);
} else {
throw new IllegalStateException(
"Cannot find a converter for type "
+ compositeType
+ ". If the target should be a converter to scala.Product, then you might have a scala classpath issue.");
}
case RAW:
if (logicalType instanceof RawType) {
final RawType<?> rawType = (RawType<?>) logicalType;
if (clazz == RawValueData.class) {
return RawValueDataConverter.INSTANCE;
} else {
return new GenericConverter<>(rawType.getTypeSerializer());
}
}
// legacy
TypeInformation typeInfo =
logicalType instanceof LegacyTypeInformationType
? ((LegacyTypeInformationType) logicalType).getTypeInformation()
: ((TypeInformationRawType) logicalType).getTypeInformation();
// planner type info
if (typeInfo instanceof StringDataTypeInfo) {
return StringDataConverter.INSTANCE;
} else if (typeInfo instanceof DecimalDataTypeInfo) {
DecimalDataTypeInfo decimalType = (DecimalDataTypeInfo) typeInfo;
return new DecimalDataConverter(decimalType.precision(), decimalType.scale());
} else if (typeInfo instanceof BigDecimalTypeInfo) {
BigDecimalTypeInfo decimalType = (BigDecimalTypeInfo) typeInfo;
return new BigDecimalConverter(decimalType.precision(), decimalType.scale());
} else if (typeInfo instanceof TimestampDataTypeInfo) {
TimestampDataTypeInfo timestampDataTypeInfo = (TimestampDataTypeInfo) typeInfo;
return new TimestampDataConverter(timestampDataTypeInfo.getPrecision());
} else if (typeInfo instanceof LegacyLocalDateTimeTypeInfo) {
LegacyLocalDateTimeTypeInfo dateTimeType =
(LegacyLocalDateTimeTypeInfo) typeInfo;
return new LocalDateTimeConverter(dateTimeType.getPrecision());
} else if (typeInfo instanceof LegacyTimestampTypeInfo) {
LegacyTimestampTypeInfo timestampType = (LegacyTimestampTypeInfo) typeInfo;
return new TimestampConverter(timestampType.getPrecision());
} else if (typeInfo instanceof LegacyInstantTypeInfo) {
LegacyInstantTypeInfo instantTypeInfo = (LegacyInstantTypeInfo) typeInfo;
return new InstantConverter(instantTypeInfo.getPrecision());
}
if (clazz == RawValueData.class) {
return RawValueDataConverter.INSTANCE;
} else if (clazz == Variant.class) {
return VariantConverter.INSTANCE;
}
return new GenericConverter(typeInfo.createSerializer(new SerializerConfigImpl()));
default:
throw new RuntimeException("Not support dataType: " + dataType);
}
}
private static Tuple2<Integer, Integer> getPrecision(LogicalType logicalType) {
Tuple2<Integer, Integer> ps = new Tuple2<>();
if (logicalType instanceof DecimalType) {
DecimalType decimalType = (DecimalType) logicalType;
ps.f0 = decimalType.getPrecision();
ps.f1 = decimalType.getScale();
} else {
TypeInformation typeInfo =
((LegacyTypeInformationType) logicalType).getTypeInformation();
if (typeInfo instanceof BigDecimalTypeInfo) {
BigDecimalTypeInfo decimalType = (BigDecimalTypeInfo) typeInfo;
ps.f0 = decimalType.precision();
ps.f1 = decimalType.scale();
} else if (typeInfo instanceof DecimalDataTypeInfo) {
DecimalDataTypeInfo decimalType = (DecimalDataTypeInfo) typeInfo;
ps.f0 = decimalType.precision();
ps.f1 = decimalType.scale();
} else {
ps.f0 = DecimalDataUtils.DECIMAL_SYSTEM_DEFAULT.getPrecision();
ps.f1 = DecimalDataUtils.DECIMAL_SYSTEM_DEFAULT.getScale();
}
}
return ps;
}
private static int getDateTimePrecision(LogicalType logicalType) {
if (logicalType instanceof LocalZonedTimestampType) {
return ((LocalZonedTimestampType) logicalType).getPrecision();
} else if (logicalType instanceof TimestampType) {
return ((TimestampType) logicalType).getPrecision();
} else {
TypeInformation typeInfo =
((LegacyTypeInformationType) logicalType).getTypeInformation();
if (typeInfo instanceof LegacyInstantTypeInfo) {
return ((LegacyInstantTypeInfo) typeInfo).getPrecision();
} else if (typeInfo instanceof LegacyLocalDateTimeTypeInfo) {
return ((LegacyLocalDateTimeTypeInfo) typeInfo).getPrecision();
} else {
// TimestampType.DEFAULT_PRECISION == LocalZonedTimestampType.DEFAULT_PRECISION == 6
return TimestampType.DEFAULT_PRECISION;
}
}
}
/**
* Converter between internal data format and java format.
*
* @param <Internal> Internal data format.
* @param <External> External data format.
*/
public abstract static | for |
java | apache__camel | components/camel-cm-sms/src/test/java/org/apache/camel/component/cm/test/CMProxy.java | {
"start": 1061,
"end": 1121
} | interface ____ {
void send(SMSMessage smsMessage);
}
| CMProxy |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/NonOverridingEqualsTest.java | {
"start": 4793,
"end": 5174
} | class ____ {
// BUG: Diagnostic contains:
private boolean equals(Test other) {
return false;
}
}
""")
.doTest();
}
@Test
public void flagsEvenIfAnotherMethodOverridesEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"""
public | Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cid/EmbeddedInsideEmbeddedIdTest.java | {
"start": 782,
"end": 1806
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
DomainEntity entity = new DomainEntity( InnerWrappingId.of( 1L ), "key" );
session.persist( entity );
}
);
}
@Test
public void testQuery(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "select d.id from DomainEntity d" ).getSingleResult();
}
);
}
@Test
public void testGet(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
DomainEntity domainEntity = session.get(
DomainEntity.class,
new OuterWrappingId( InnerWrappingId.of( 1L ) )
);
assertThat( domainEntity ).isNotNull();
}
);
}
@Test
public void testQuery2(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "select id from DomainEntity" ).getSingleResult();
}
);
}
@Entity(name = "DomainEntity")
@Table(name = "domain_entity")
public static | EmbeddedInsideEmbeddedIdTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/completable/CompletableTest.java | {
"start": 2583,
"end": 3160
} | class ____ implements Iterable<Completable> {
@Override
public Iterator<Completable> iterator() {
return new Iterator<Completable>() {
@Override
public boolean hasNext() {
throw new TestException();
}
@Override
public Completable next() {
return null;
}
@Override
public void remove() {
}
};
}
}
/**
* A | IterableIteratorHasNextThrows |
java | spring-projects__spring-boot | module/spring-boot-jackson2/src/test/java/org/springframework/boot/jackson2/NameAndAgeJsonKeyComponent.java | {
"start": 1404,
"end": 1642
} | class ____ extends JsonSerializer<NameAndAge> {
@Override
public void serialize(NameAndAge value, JsonGenerator jgen, SerializerProvider serializers) throws IOException {
jgen.writeFieldName(value.asKey());
}
}
static | Serializer |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/aop/introduction/Tx.java | {
"start": 1111,
"end": 1149
} | interface ____ {
}
// end::annotation[]
| Tx |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/plan/logical/DissectSerializationTests.java | {
"start": 672,
"end": 2340
} | class ____ extends AbstractLogicalPlanSerializationTests<Dissect> {
@Override
protected Dissect createTestInstance() {
Source source = randomSource();
LogicalPlan child = randomChild(0);
Expression input = FieldAttributeTests.createFieldAttribute(1, false);
Dissect.Parser parser = randomParser();
List<Attribute> extracted = randomFieldAttributes(0, 4, false);
return new Dissect(source, child, input, parser, extracted);
}
public static Dissect.Parser randomParser() {
String suffix = randomAlphaOfLength(5);
String pattern = "%{b} %{c}" + suffix;
return new Dissect.Parser(pattern, ",", new DissectParser(pattern, ","));
}
@Override
protected Dissect mutateInstance(Dissect instance) throws IOException {
LogicalPlan child = instance.child();
Expression input = instance.input();
Dissect.Parser parser = randomParser();
List<Attribute> extracted = randomFieldAttributes(0, 4, false);
switch (between(0, 3)) {
case 0 -> child = randomValueOtherThan(child, () -> randomChild(0));
case 1 -> input = randomValueOtherThan(input, () -> FieldAttributeTests.createFieldAttribute(1, false));
case 2 -> parser = randomValueOtherThan(parser, DissectSerializationTests::randomParser);
case 3 -> extracted = randomValueOtherThan(extracted, () -> randomFieldAttributes(0, 4, false));
}
return new Dissect(instance.source(), child, input, parser, extracted);
}
@Override
protected boolean alwaysEmptySource() {
return true;
}
}
| DissectSerializationTests |
java | apache__camel | components/camel-saxon/src/test/java/org/apache/camel/builder/saxon/SaxonXPathTest.java | {
"start": 1051,
"end": 2215
} | class ____ extends CamelTestSupport {
@Test
public void testSaxonXPath() throws Exception {
getMockEndpoint("mock:london").expectedMessageCount(1);
getMockEndpoint("mock:paris").expectedMessageCount(1);
getMockEndpoint("mock:other").expectedMessageCount(1);
template.sendBody("direct:start", "<person><city>London</city></person>");
template.sendBody("direct:start", "<person><city>Berlin</city></person>");
template.sendBody("direct:start", "<person><city>Paris</city></person>");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.choice()
.when().xpath("person/city = 'London'")
.to("mock:london")
.when().xpath("person/city = 'Paris'")
.to("mock:paris")
.otherwise()
.to("mock:other");
}
};
}
}
| SaxonXPathTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/legacy/RecursiveComparisonAssert_isNotEqualTo_Test.java | {
"start": 1326,
"end": 8790
} | class ____ extends WithLegacyIntrospectionStrategyBaseTest {
@Test
void should_pass_when_either_actual_or_expected_is_null() {
// GIVEN
Person actual = null;
Person other = new Person();
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.isNotEqualTo(other);
then(other).usingRecursiveComparison(recursiveComparisonConfiguration)
.isNotEqualTo(actual);
}
@Test
void should_fail_when_actual_and_expected_are_null() {
// GIVEN
Person actual = null;
Person other = null;
// WHEN
// areNotEqualRecursiveComparisonFailsAsExpected(actual, other);
// THEN
// verifyShouldNotBeEqualComparingFieldByFieldRecursivelyCall(actual, other);
}
@Test
void should_pass_when_expected_is_an_enum_and_actual_is_not() {
// GIVEN
RecursiveComparisonAssert_isEqualTo_Test.LightString actual = new RecursiveComparisonAssert_isEqualTo_Test.LightString("GREEN");
Light other = new Light(GREEN);
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.isNotEqualTo(other);
}
@Test
void should_fail_when_field_values_are_null() {
// GIVEN
Jedi actual = new Jedi("Yoda", null);
Jedi other = new Jedi("Yoda", null);
recursiveComparisonConfiguration.ignoreFields("name");
// WHEN
// areNotEqualRecursiveComparisonFailsAsExpected(actual, other);
// THEN
// verifyShouldNotBeEqualComparingFieldByFieldRecursivelyCall(actual, other);
}
@Test
void should_fail_when_fields_are_equal_even_if_objects_types_differ() {
// GIVEN
CartoonCharacter actual = new CartoonCharacter("Homer Simpson");
Person other = new Person("Homer Simpson");
recursiveComparisonConfiguration.ignoreFields("children");
// WHEN
// areNotEqualRecursiveComparisonFailsAsExpected(actual, other);
// THEN
// verifyShouldNotBeEqualComparingFieldByFieldRecursivelyCall(actual, other);
}
@Test
void should_fail_when_all_field_values_equal() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Jedi other = new Jedi("Luke", "Green");
recursiveComparisonConfiguration.ignoreFields("name");
//
// areNotEqualRecursiveComparisonFailsAsExpected(actual, other);
// THEN
// verifyShouldNotBeEqualComparingFieldByFieldRecursivelyCall(actual, other);
}
@Test
void should_fail_when_all_field_values_equal_and_no_fields_are_ignored() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Jedi other = new Jedi("Yoda", "Green");
// WHEN
// areNotEqualRecursiveComparisonFailsAsExpected(actual, other);
// THEN
// verifyShouldNotBeEqualComparingFieldByFieldRecursivelyCall(actual, other);
}
@Test
void should_be_able_to_compare_objects_of_different_types() {
// GIVEN
CartoonCharacter other = new CartoonCharacter("Homer Simpson");
Person actual = new Person("Homer Simpson");
// THEN not equal because of children field in CartoonCharacter
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.isNotEqualTo(other);
}
@Test
void should_be_able_to_use_a_comparator_for_specified_type() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Jedi other = new Jedi(new String("Yoda"), "Green");
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.withComparatorForType(NEVER_EQUALS_STRING, String.class)
.isNotEqualTo(other);
}
@Test
void should_be_able_to_use_a_BiPredicate_to_compare_specified_type() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Jedi other = new Jedi(new String("Yoda"), "Green");
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.withEqualsForType((o1, o2) -> false, String.class)
.isNotEqualTo(other);
}
@Test
void should_pass_when_one_property_or_field_to_compare_can_not_be_found() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Person other = new Person("Yoda");
other.neighbour = other;
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.isNotEqualTo(other);
}
@Test
void should_be_able_to_use_a_comparator_for_specified_fields() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Jedi other = new Jedi("Yoda", new String("Green"));
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.withComparatorForFields(NEVER_EQUALS_STRING, "lightSaberColor")
.isNotEqualTo(other);
}
@Test
void should_be_able_to_use_a_BiPredicate_for_specified_fields() {
// GIVEN
Jedi actual = new Jedi("Yoda", "Green");
Jedi other = new Jedi("Yoda", new String("Green"));
// THEN
then(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.withEqualsForFields((o1, o2) -> false, "lightSaberColor")
.isNotEqualTo(other);
}
@Test
void should_pass_using_a_BiPredicate_to_compare_fields_with_different_types_and_different_values() {
// GIVEN
TimeOffset actual = new TimeOffset();
actual.time = LocalTime.now();
TimeOffsetDto expected = new TimeOffsetDto();
expected.time = actual.time.plusHours(1).toString();
// WHEN/THEN
then(actual).usingRecursiveComparison()
.withEqualsForTypes((t, s) -> LocalTime.parse(s).equals(t), LocalTime.class, String.class)
.isNotEqualTo(expected);
}
@Test
void should_pass_using_a_never_match_BiPredicate_to_compare_fields_with_different_types() {
// GIVEN
TimeOffset actual = new TimeOffset();
actual.time = LocalTime.now();
TimeOffsetDto expected = new TimeOffsetDto();
expected.time = actual.time.toString();
// WHEN/THEN
then(actual).usingRecursiveComparison()
.withEqualsForTypes((t, s) -> false, LocalTime.class, String.class)
.isNotEqualTo(expected);
}
@Test
void should_pass_using_at_least_one_BiPredicate_that_not_matching_fields_with_different_types() {
// GIVEN
TimeOffset actual = new TimeOffset();
actual.time = LocalTime.now();
actual.offset = ZoneOffset.UTC;
TimeOffsetDto expected = new TimeOffsetDto();
expected.time = actual.time.toString();
expected.offset = actual.offset.getId();
// WHEN/THEN
then(actual).usingRecursiveComparison()
.withEqualsForTypes((z, s) -> ZoneOffset.of(s).equals(z), ZoneOffset.class, String.class)
.withEqualsForTypes((t, s) -> false, LocalTime.class, String.class)
.isNotEqualTo(expected);
}
@Test
void should_pass_having_two_BiPredicates_with_same_left_type_and_one_not_matching_fields_with_different_types() {
// GIVEN
LocalTime now = LocalTime.now();
TimeOffsetDto actual = new TimeOffsetDto();
actual.time = now.toString();
actual.offset = "Z";
TimeOffset expected = new TimeOffset();
expected.time = now;
expected.offset = ZoneOffset.UTC;
// WHEN/THEN
then(actual).usingRecursiveComparison()
.withEqualsForTypes((s, z) -> ZoneOffset.of(s).equals(z), String.class, ZoneOffset.class)
.withEqualsForTypes((s, t) -> false, String.class, LocalTime.class)
.isNotEqualTo(expected);
}
}
| RecursiveComparisonAssert_isNotEqualTo_Test |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/MatchNoneQueryBuilder.java | {
"start": 1034,
"end": 4417
} | class ____ extends AbstractQueryBuilder<MatchNoneQueryBuilder> {
public static final String NAME = "match_none";
private String rewriteReason;
public MatchNoneQueryBuilder() {}
public MatchNoneQueryBuilder(String rewriteReason) {
this.rewriteReason = rewriteReason;
}
/**
* Read from a stream.
*/
public MatchNoneQueryBuilder(StreamInput in) throws IOException {
super(in);
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_10_X)) {
rewriteReason = in.readOptionalString();
}
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_10_X)) {
out.writeOptionalString(rewriteReason);
}
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME);
printBoostAndQueryName(builder);
builder.endObject();
}
public static MatchNoneQueryBuilder fromXContent(XContentParser parser) throws IOException {
String currentFieldName = null;
XContentParser.Token token;
String queryName = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
while (((token = parser.nextToken()) != XContentParser.Token.END_OBJECT && token != XContentParser.Token.END_ARRAY)) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
queryName = parser.text();
} else if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
boost = parser.floatValue();
} else {
throw new ParsingException(
parser.getTokenLocation(),
"[" + MatchNoneQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"
);
}
} else {
throw new ParsingException(
parser.getTokenLocation(),
"[" + MatchNoneQueryBuilder.NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]"
);
}
}
MatchNoneQueryBuilder matchNoneQueryBuilder = new MatchNoneQueryBuilder();
matchNoneQueryBuilder.boost(boost);
matchNoneQueryBuilder.queryName(queryName);
return matchNoneQueryBuilder;
}
@Override
protected Query doToQuery(SearchExecutionContext context) throws IOException {
if (rewriteReason != null) {
return Queries.newMatchNoDocsQuery(rewriteReason);
}
return Queries.newMatchNoDocsQuery("User requested \"" + getName() + "\" query.");
}
@Override
protected boolean doEquals(MatchNoneQueryBuilder other) {
return true;
}
@Override
protected int doHashCode() {
return 0;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
}
| MatchNoneQueryBuilder |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/util/SideEffectAnalysis.java | {
"start": 1608,
"end": 1726
} | class ____ assumes that the expression is side-effect free and then
* tries to prove it wrong.
*/
public final | initially |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/jsontype/impl/SimpleNameIdResolver.java | {
"start": 931,
"end": 3044
} | class ____ to type id, used for serialization.
*<p>
* Since lazily constructed will require synchronization (either internal
* by type, or external)
*/
protected final ConcurrentHashMap<String, String> _typeToId;
/**
* Mappings from type id to JavaType, used for deserialization.
*<p>
* Eagerly constructed, not modified, can use regular unsynchronized {@link Map}.
*/
protected final Map<String, JavaType> _idToType;
protected final boolean _caseInsensitive;
protected SimpleNameIdResolver(JavaType baseType,
ConcurrentHashMap<String, String> typeToId,
HashMap<String, JavaType> idToType,
boolean caseInsensitive)
{
super(baseType);
_typeToId = typeToId;
_idToType = idToType;
_caseInsensitive = caseInsensitive;
}
public static SimpleNameIdResolver construct(MapperConfig<?> config, JavaType baseType,
Collection<NamedType> subtypes, boolean forSer, boolean forDeser)
{
// sanity check
if (forSer == forDeser) throw new IllegalArgumentException();
final ConcurrentHashMap<String, String> typeToId;
final HashMap<String, JavaType> idToType;
if (forSer) {
// Only need Class-to-id for serialization; but synchronized since may be
// lazily built (if adding type-id-mappings dynamically)
typeToId = new ConcurrentHashMap<>();
idToType = null;
} else {
idToType = new HashMap<>();
// 14-Apr-2016, tatu: Apparently needed for special case of `defaultImpl`;
// see [databind#1198] for details: but essentially we only need room
// for a single value.
typeToId = new ConcurrentHashMap<>(4);
}
final boolean caseInsensitive = config.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES);
if (subtypes != null) {
for (NamedType t : subtypes) {
// no name? Need to figure out default; for now, let's just
// use non-qualified | name |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/search/SpellCheckResultParser.java | {
"start": 2306,
"end": 5133
} | class ____ implements ComplexDataParser<SpellCheckResult<V>> {
private final ByteBuffer resultsKeyword = StringCodec.UTF8.encodeKey("results");
@Override
public SpellCheckResult<V> parse(ComplexData data) {
SpellCheckResult<V> result = new SpellCheckResult<>();
if (data == null) {
return null;
}
Map<Object, Object> elements = data.getDynamicMap();
if (elements == null || elements.isEmpty() || !elements.containsKey(resultsKeyword)) {
LOG.warn("Failed while parsing FT.SPELLCHECK: data must contain a 'results' key");
return result;
}
ComplexData resultsData = (ComplexData) elements.get(resultsKeyword);
Map<Object, Object> resultsMap = resultsData.getDynamicMap();
// Go through each misspelled term, should contain three items itself
for (Object term : resultsMap.keySet()) {
// Key of the inner map is the misspelled term
V misspelledTerm = codec.decodeValue((ByteBuffer) term);
// Value of the inner map is the suggestions array
ComplexData termData = (ComplexData) resultsMap.get(term);
List<Object> suggestionsArray = termData.getDynamicList();
List<SpellCheckResult.Suggestion<V>> suggestions = parseSuggestions(suggestionsArray);
result.addMisspelledTerm(new SpellCheckResult.MisspelledTerm<>(misspelledTerm, suggestions));
}
return result;
}
private List<SpellCheckResult.Suggestion<V>> parseSuggestions(List<Object> suggestionsArray) {
List<SpellCheckResult.Suggestion<V>> suggestions = new ArrayList<>();
for (Object suggestionObj : suggestionsArray) {
Map<Object, Object> suggestionMap = ((ComplexData) suggestionObj).getDynamicMap();
for (Object suggestion : suggestionMap.keySet()) {
double score = (double) suggestionMap.get(suggestion);
V suggestionValue = codec.decodeValue((ByteBuffer) suggestion);
suggestions.add(new SpellCheckResult.Suggestion<>(score, suggestionValue));
}
}
return suggestions;
}
}
/**
* Parse the RESP2 output of the Redis FT.SPELLCHECK command and convert it to a {@link SpellCheckResult} object.
* <p>
* The parsing logic handles the nested array structure returned by FT.SPELLCHECK:
* </p>
*
* <pre>
* [
* ["TERM", "misspelled_term", [["score1", "suggestion1"], ["score2", "suggestion2"]]],
* ["TERM", "another_term", [["score3", "suggestion3"]]]
* ]
* </pre>
*/
| SpellCheckResp3Parser |
java | netty__netty | common/src/main/java/io/netty/util/internal/ResourcesUtil.java | {
"start": 776,
"end": 885
} | class ____ provides various common operations and constants
* related to loading resources
*/
public final | that |
java | google__guava | android/guava-tests/test/com/google/common/collect/TreeMultisetTest.java | {
"start": 2035,
"end": 13288
} | class ____ extends TestCase {
@J2ktIncompatible
@GwtIncompatible // suite
@AndroidIncompatible // test-suite builders
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(
SortedMultisetTestSuiteBuilder.using(
new TestStringMultisetGenerator() {
@Override
protected Multiset<String> create(String[] elements) {
return TreeMultiset.create(asList(elements));
}
@Override
public List<String> order(List<String> insertionOrder) {
return Ordering.natural().sortedCopy(insertionOrder);
}
})
.withFeatures(
CollectionSize.ANY,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_QUERIES,
MultisetFeature.ENTRIES_ARE_VIEWS)
.named("TreeMultiset, Ordering.natural")
.createTestSuite());
suite.addTest(
SortedMultisetTestSuiteBuilder.using(
new TestStringMultisetGenerator() {
@Override
protected Multiset<String> create(String[] elements) {
Multiset<String> result = TreeMultiset.create(NullsBeforeB.INSTANCE);
Collections.addAll(result, elements);
return result;
}
@Override
public List<String> order(List<String> insertionOrder) {
sort(insertionOrder, NullsBeforeB.INSTANCE);
return insertionOrder;
}
})
.withFeatures(
CollectionSize.ANY,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
MultisetFeature.ENTRIES_ARE_VIEWS)
.named("TreeMultiset, NullsBeforeB")
.createTestSuite());
suite.addTest(
NavigableSetTestSuiteBuilder.using(
new TestStringSetGenerator() {
@Override
protected Set<String> create(String[] elements) {
return TreeMultiset.create(asList(elements)).elementSet();
}
@Override
public List<String> order(List<String> insertionOrder) {
return new ArrayList<>(Sets.newTreeSet(insertionOrder));
}
})
.named("TreeMultiset[Ordering.natural].elementSet")
.withFeatures(
CollectionSize.ANY,
CollectionFeature.REMOVE_OPERATIONS,
CollectionFeature.ALLOWS_NULL_QUERIES)
.createTestSuite());
suite.addTestSuite(TreeMultisetTest.class);
return suite;
}
public void testCreate() {
TreeMultiset<String> multiset = TreeMultiset.create();
multiset.add("foo", 2);
multiset.add("bar");
assertEquals(3, multiset.size());
assertEquals(2, multiset.count("foo"));
assertEquals(Ordering.natural(), multiset.comparator());
assertEquals("[bar, foo x 2]", multiset.toString());
}
public void testCreateWithComparator() {
Multiset<String> multiset = TreeMultiset.create(Collections.reverseOrder());
multiset.add("foo", 2);
multiset.add("bar");
assertEquals(3, multiset.size());
assertEquals(2, multiset.count("foo"));
assertEquals("[foo x 2, bar]", multiset.toString());
}
public void testCreateFromIterable() {
Multiset<String> multiset = TreeMultiset.create(asList("foo", "bar", "foo"));
assertEquals(3, multiset.size());
assertEquals(2, multiset.count("foo"));
assertEquals("[bar, foo x 2]", multiset.toString());
}
public void testToString() {
Multiset<String> ms = TreeMultiset.create();
ms.add("a", 3);
ms.add("c", 1);
ms.add("b", 2);
assertEquals("[a x 3, b x 2, c]", ms.toString());
}
public void testElementSetSortedSetMethods() {
TreeMultiset<String> ms = TreeMultiset.create();
ms.add("c", 1);
ms.add("a", 3);
ms.add("b", 2);
SortedSet<String> elementSet = ms.elementSet();
assertEquals("a", elementSet.first());
assertEquals("c", elementSet.last());
assertEquals(Ordering.natural(), elementSet.comparator());
assertThat(elementSet.headSet("b")).containsExactly("a");
assertThat(elementSet.tailSet("b")).containsExactly("b", "c").inOrder();
assertThat(elementSet.subSet("a", "c")).containsExactly("a", "b").inOrder();
}
public void testElementSetSubsetRemove() {
TreeMultiset<String> ms = TreeMultiset.create();
ms.add("a", 1);
ms.add("b", 3);
ms.add("c", 2);
ms.add("d", 1);
ms.add("e", 3);
ms.add("f", 2);
SortedSet<String> elementSet = ms.elementSet();
assertThat(elementSet).containsExactly("a", "b", "c", "d", "e", "f").inOrder();
SortedSet<String> subset = elementSet.subSet("b", "f");
assertThat(subset).containsExactly("b", "c", "d", "e").inOrder();
assertTrue(subset.remove("c"));
assertThat(elementSet).containsExactly("a", "b", "d", "e", "f").inOrder();
assertThat(subset).containsExactly("b", "d", "e").inOrder();
assertEquals(10, ms.size());
assertFalse(subset.remove("a"));
assertThat(elementSet).containsExactly("a", "b", "d", "e", "f").inOrder();
assertThat(subset).containsExactly("b", "d", "e").inOrder();
assertEquals(10, ms.size());
}
public void testElementSetSubsetRemoveAll() {
TreeMultiset<String> ms = TreeMultiset.create();
ms.add("a", 1);
ms.add("b", 3);
ms.add("c", 2);
ms.add("d", 1);
ms.add("e", 3);
ms.add("f", 2);
SortedSet<String> elementSet = ms.elementSet();
assertThat(elementSet).containsExactly("a", "b", "c", "d", "e", "f").inOrder();
SortedSet<String> subset = elementSet.subSet("b", "f");
assertThat(subset).containsExactly("b", "c", "d", "e").inOrder();
assertTrue(subset.removeAll(asList("a", "c")));
assertThat(elementSet).containsExactly("a", "b", "d", "e", "f").inOrder();
assertThat(subset).containsExactly("b", "d", "e").inOrder();
assertEquals(10, ms.size());
}
public void testElementSetSubsetRetainAll() {
TreeMultiset<String> ms = TreeMultiset.create();
ms.add("a", 1);
ms.add("b", 3);
ms.add("c", 2);
ms.add("d", 1);
ms.add("e", 3);
ms.add("f", 2);
SortedSet<String> elementSet = ms.elementSet();
assertThat(elementSet).containsExactly("a", "b", "c", "d", "e", "f").inOrder();
SortedSet<String> subset = elementSet.subSet("b", "f");
assertThat(subset).containsExactly("b", "c", "d", "e").inOrder();
assertTrue(subset.retainAll(asList("a", "c")));
assertThat(elementSet).containsExactly("a", "c", "f").inOrder();
assertThat(subset).containsExactly("c");
assertEquals(5, ms.size());
}
public void testElementSetSubsetClear() {
TreeMultiset<String> ms = TreeMultiset.create();
ms.add("a", 1);
ms.add("b", 3);
ms.add("c", 2);
ms.add("d", 1);
ms.add("e", 3);
ms.add("f", 2);
SortedSet<String> elementSet = ms.elementSet();
assertThat(elementSet).containsExactly("a", "b", "c", "d", "e", "f").inOrder();
SortedSet<String> subset = elementSet.subSet("b", "f");
assertThat(subset).containsExactly("b", "c", "d", "e").inOrder();
subset.clear();
assertThat(elementSet).containsExactly("a", "f").inOrder();
assertThat(subset).isEmpty();
assertEquals(3, ms.size());
}
public void testCustomComparator() throws Exception {
Comparator<String> comparator =
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
};
TreeMultiset<String> ms = TreeMultiset.create(comparator);
ms.add("b");
ms.add("c");
ms.add("a");
ms.add("b");
ms.add("d");
assertThat(ms).containsExactly("d", "c", "b", "b", "a").inOrder();
SortedSet<String> elementSet = ms.elementSet();
assertEquals("d", elementSet.first());
assertEquals("a", elementSet.last());
assertEquals(comparator, elementSet.comparator());
}
public void testNullAcceptingComparator() throws Exception {
Comparator<@Nullable String> comparator = Ordering.<String>natural().<String>nullsFirst();
TreeMultiset<@Nullable String> ms = TreeMultiset.create(comparator);
ms.add("b");
ms.add(null);
ms.add("a");
ms.add("b");
ms.add(null, 2);
assertThat(ms).containsExactly(null, null, null, "a", "b", "b").inOrder();
assertEquals(3, ms.count(null));
SortedSet<@Nullable String> elementSet = ms.elementSet();
assertEquals(null, elementSet.first());
assertEquals("b", elementSet.last());
assertEquals(comparator, elementSet.comparator());
}
private static final Comparator<String> DEGENERATE_COMPARATOR =
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
/** Test a TreeMultiset with a comparator that can return 0 when comparing unequal values. */
public void testDegenerateComparator() throws Exception {
TreeMultiset<String> ms = TreeMultiset.create(DEGENERATE_COMPARATOR);
ms.add("foo");
ms.add("a");
ms.add("bar");
ms.add("b");
ms.add("c");
assertEquals(2, ms.count("bar"));
assertEquals(3, ms.count("b"));
Multiset<String> ms2 = TreeMultiset.create(DEGENERATE_COMPARATOR);
ms2.add("cat", 2);
ms2.add("x", 3);
assertEquals(ms, ms2);
assertEquals(ms2, ms);
SortedSet<String> elementSet = ms.elementSet();
assertEquals("a", elementSet.first());
assertEquals("foo", elementSet.last());
assertEquals(DEGENERATE_COMPARATOR, elementSet.comparator());
}
public void testSubMultisetSize() {
TreeMultiset<String> ms = TreeMultiset.create();
ms.add("a", Integer.MAX_VALUE);
ms.add("b", Integer.MAX_VALUE);
ms.add("c", 3);
assertEquals(Integer.MAX_VALUE, ms.count("a"));
assertEquals(Integer.MAX_VALUE, ms.count("b"));
assertEquals(3, ms.count("c"));
assertEquals(Integer.MAX_VALUE, ms.headMultiset("c", CLOSED).size());
assertEquals(Integer.MAX_VALUE, ms.headMultiset("b", CLOSED).size());
assertEquals(Integer.MAX_VALUE, ms.headMultiset("a", CLOSED).size());
assertEquals(3, ms.tailMultiset("c", CLOSED).size());
assertEquals(Integer.MAX_VALUE, ms.tailMultiset("b", CLOSED).size());
assertEquals(Integer.MAX_VALUE, ms.tailMultiset("a", CLOSED).size());
}
@J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // Reflection bug, or actual binary compatibility problem?
public void testElementSetBridgeMethods() {
for (Method m : TreeMultiset.class.getMethods()) {
if (m.getName().equals("elementSet") && m.getReturnType().equals(SortedSet.class)) {
return;
}
}
fail("No bridge method found");
}
}
| TreeMultisetTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/nationalized/SimpleNationalizedTest.java | {
"start": 1602,
"end": 5338
} | class ____ {
@Id
private Integer id;
@Nationalized
private String nvarcharAtt;
@Lob
@Nationalized
private String materializedNclobAtt;
@Lob
@Nationalized
private NClob nclobAtt;
@Nationalized
private Character ncharacterAtt;
@Nationalized
@JavaType( CharacterArrayJavaType.class )
private Character[] ncharArrAtt;
@Lob
@Nationalized
private String nlongvarcharcharAtt;
}
@Test
public void simpleNationalizedTest() {
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
final MetadataSources ms = new MetadataSources( ssr );
ms.addAnnotatedClass( NationalizedEntity.class );
final Metadata metadata = ms.buildMetadata();
final JdbcTypeRegistry jdbcTypeRegistry = metadata.getDatabase()
.getTypeConfiguration()
.getJdbcTypeRegistry();
PersistentClass pc = metadata.getEntityBinding( NationalizedEntity.class.getName() );
assertNotNull( pc );
Property prop = pc.getProperty( "nvarcharAtt" );
BasicType<?> type = (BasicType<?>) prop.getType();
final Dialect dialect = metadata.getDatabase().getDialect();
assertSame( StringJavaType.INSTANCE, type.getJavaTypeDescriptor() );
if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) {
assertSame( jdbcTypeRegistry.getDescriptor( Types.VARCHAR ), type.getJdbcType() );
}
else {
assertSame( jdbcTypeRegistry.getDescriptor( Types.NVARCHAR ), type.getJdbcType() );
}
prop = pc.getProperty( "materializedNclobAtt" );
type = (BasicType<?>) prop.getType();
assertSame( StringJavaType.INSTANCE, type.getJavaTypeDescriptor() );
if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) {
assertSame( jdbcTypeRegistry.getDescriptor( Types.CLOB ), type.getJdbcType() );
}
else {
assertSame( jdbcTypeRegistry.getDescriptor( Types.NCLOB ), type.getJdbcType() );
}
prop = pc.getProperty( "nclobAtt" );
type = (BasicType<?>) prop.getType();
assertSame( NClobJavaType.INSTANCE, type.getJavaTypeDescriptor() );
if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) {
assertSame( jdbcTypeRegistry.getDescriptor( Types.CLOB ), type.getJdbcType() );
}
else {
assertSame( jdbcTypeRegistry.getDescriptor( Types.NCLOB ), type.getJdbcType() );
}
prop = pc.getProperty( "nlongvarcharcharAtt" );
type = (BasicType<?>) prop.getType();
assertSame( StringJavaType.INSTANCE, type.getJavaTypeDescriptor() );
if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) {
assertSame( jdbcTypeRegistry.getDescriptor( Types.CLOB ), type.getJdbcType() );
}
else {
assertSame( jdbcTypeRegistry.getDescriptor( Types.NCLOB ), type.getJdbcType() );
}
prop = pc.getProperty( "ncharArrAtt" );
type = (BasicType<?>) prop.getType();
assertInstanceOf( CharacterArrayJavaType.class, type.getJavaTypeDescriptor() );
if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) {
assertSame( jdbcTypeRegistry.getDescriptor( Types.VARCHAR ), type.getJdbcType() );
}
else {
assertSame( jdbcTypeRegistry.getDescriptor( Types.NVARCHAR ), type.getJdbcType() );
}
prop = pc.getProperty( "ncharacterAtt" );
type = (BasicType<?>) prop.getType();
assertSame( CharacterJavaType.INSTANCE, type.getJavaTypeDescriptor() );
if ( dialect.getNationalizationSupport() != NationalizationSupport.EXPLICIT ) {
assertSame( jdbcTypeRegistry.getDescriptor( Types.CHAR ), type.getJdbcType() );
}
else {
assertSame( jdbcTypeRegistry.getDescriptor( Types.NCHAR ), type.getJdbcType() );
}
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
}
}
}
| NationalizedEntity |
java | elastic__elasticsearch | x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BinaryProcessor.java | {
"start": 472,
"end": 1849
} | class ____ implements Processor {
private final Processor left, right;
public BinaryProcessor(Processor left, Processor right) {
this.left = left;
this.right = right;
}
protected BinaryProcessor(StreamInput in) throws IOException {
left = in.readNamedWriteable(Processor.class);
right = in.readNamedWriteable(Processor.class);
}
@Override
public final void writeTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(left);
out.writeNamedWriteable(right);
doWrite(out);
}
protected abstract void doWrite(StreamOutput out) throws IOException;
@Override
public Object process(Object input) {
Object l = left.process(input);
if (l == null) {
return null;
}
checkParameter(l);
Object r = right.process(input);
if (r == null) {
return null;
}
checkParameter(r);
return doProcess(l, r);
}
/**
* Checks the parameter (typically for its type) if the value is not null.
*/
protected void checkParameter(Object param) {
// no-op
}
protected Processor left() {
return left;
}
protected Processor right() {
return right;
}
protected abstract Object doProcess(Object left, Object right);
}
| BinaryProcessor |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/AdditionalAnswers.java | {
"start": 14701,
"end": 15215
} | interface ____ the answer - which is expected to return something
* @param <T> return type
* @param <A> input parameter type 1
* @param <B> input parameter type 2
* @return the answer object to use
* @since 2.1.0
*/
public static <T, A, B> Answer<T> answer(Answer2<T, A, B> answer) {
return toAnswer(answer);
}
/**
* Creates an answer from a functional interface - allows for a strongly typed answer to be created
* ideally in Java 8
* @param answer | to |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/timelineservice/TimelineEntity.java | {
"start": 2550,
"end": 2907
} | class ____ implements Comparable<TimelineEntity> {
protected final static String SYSTEM_INFO_KEY_PREFIX = "SYSTEM_INFO_";
public final static long DEFAULT_ENTITY_PREFIX = 0L;
/**
* Identifier of timeline entity(entity id + entity type).
*/
@XmlRootElement(name = "identifier")
@XmlAccessorType(XmlAccessType.NONE)
public static | TimelineEntity |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MinaEndpointBuilderFactory.java | {
"start": 49216,
"end": 59772
} | interface ____ extends EndpointProducerBuilder {
default MinaEndpointProducerBuilder basic() {
return (MinaEndpointProducerBuilder) this;
}
/**
* Whether to create the InetAddress once and reuse. Setting this to
* false allows to pickup DNS changes in the network.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param cachedAddress the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder cachedAddress(boolean cachedAddress) {
doSetProperty("cachedAddress", cachedAddress);
return this;
}
/**
* Whether to create the InetAddress once and reuse. Setting this to
* false allows to pickup DNS changes in the network.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param cachedAddress the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder cachedAddress(String cachedAddress) {
doSetProperty("cachedAddress", cachedAddress);
return this;
}
/**
* Sessions can be lazily created to avoid exceptions, if the remote
* server is not up and running when the Camel producer is started.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param lazySessionCreation the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder lazySessionCreation(boolean lazySessionCreation) {
doSetProperty("lazySessionCreation", lazySessionCreation);
return this;
}
/**
* Sessions can be lazily created to avoid exceptions, if the remote
* server is not up and running when the Camel producer is started.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param lazySessionCreation the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder lazySessionCreation(String lazySessionCreation) {
doSetProperty("lazySessionCreation", lazySessionCreation);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* If sync is enabled then this option dictates MinaConsumer if it
* should disconnect where there is no reply to send back.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param disconnectOnNoReply the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder disconnectOnNoReply(boolean disconnectOnNoReply) {
doSetProperty("disconnectOnNoReply", disconnectOnNoReply);
return this;
}
/**
* If sync is enabled then this option dictates MinaConsumer if it
* should disconnect where there is no reply to send back.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param disconnectOnNoReply the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder disconnectOnNoReply(String disconnectOnNoReply) {
doSetProperty("disconnectOnNoReply", disconnectOnNoReply);
return this;
}
/**
* Number of worker threads in the worker pool for TCP and UDP.
*
* The option is a: <code>int</code> type.
*
* Default: 16
* Group: advanced
*
* @param maximumPoolSize the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder maximumPoolSize(int maximumPoolSize) {
doSetProperty("maximumPoolSize", maximumPoolSize);
return this;
}
/**
* Number of worker threads in the worker pool for TCP and UDP.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 16
* Group: advanced
*
* @param maximumPoolSize the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder maximumPoolSize(String maximumPoolSize) {
doSetProperty("maximumPoolSize", maximumPoolSize);
return this;
}
/**
* Whether to use ordered thread pool, to ensure events are processed
* orderly on the same channel.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param orderedThreadPoolExecutor the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder orderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) {
doSetProperty("orderedThreadPoolExecutor", orderedThreadPoolExecutor);
return this;
}
/**
* Whether to use ordered thread pool, to ensure events are processed
* orderly on the same channel.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param orderedThreadPoolExecutor the value to set
* @return the dsl builder
*/
default AdvancedMinaEndpointProducerBuilder orderedThreadPoolExecutor(String orderedThreadPoolExecutor) {
doSetProperty("orderedThreadPoolExecutor", orderedThreadPoolExecutor);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level. Also make sure to configure
* objectCodecPattern to (star) to allow transferring java objects.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
@Deprecated
default AdvancedMinaEndpointProducerBuilder transferExchange(boolean transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level. Also make sure to configure
* objectCodecPattern to (star) to allow transferring java objects.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
@Deprecated
default AdvancedMinaEndpointProducerBuilder transferExchange(String transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
}
/**
* Builder for endpoint for the Mina component.
*/
public | AdvancedMinaEndpointProducerBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cdi/converters/legacy/QueryTest.java | {
"start": 1193,
"end": 3922
} | class ____ {
public static final float SALARY = 267.89f;
@Test
@JiraKey( value = "HHH-9356" )
public void testCriteriaBetween(EntityManagerFactoryScope factoryScope) {
factoryScope.inTransaction( (em) -> {
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<Employee> query = cb.createQuery( Employee.class );
final Root<Employee> root = query.from( Employee.class );
query.select( root );
query.where( cb.between( root.get( "salary" ), 300f, 400f ) );
final List<Employee> result0 = em.createQuery( query ).getResultList();
assertEquals( 0, result0.size() );
query.where( cb.between( root.get( "salary" ), 100f, 200f ) );
final List<Employee> result1 = em.createQuery( query ).getResultList();
assertEquals( 0, result1.size() );
query.where( cb.between( root.get( "salary" ), 200f, 300f ));
final List<Employee> result2 = em.createQuery( query ).getResultList();
assertEquals( 1, result2.size() );
} );
}
@Test
public void testJpqlLiteralBetween(EntityManagerFactoryScope factoryScope) {
factoryScope.inTransaction( (em) -> {
@SuppressWarnings("unchecked")
final List<Employee> result0 = em.createQuery( "from Employee where salary between 300.0F and 400.0F" ).getResultList();
assertEquals( 0, result0.size() );
@SuppressWarnings("unchecked")
final List<Employee> result1 = em.createQuery( "from Employee where salary between 100.0F and 200.0F" ).getResultList();
assertEquals( 0, result1.size() );
@SuppressWarnings("unchecked")
final List<Employee> result2 = em.createQuery( "from Employee where salary between 200.0F and 300.0F" ).getResultList();
assertEquals( 1, result2.size() );
} );
}
@Test
public void testJpqlParametrizedBetween(EntityManagerFactoryScope factoryScope) {
factoryScope.inTransaction( (em) -> {
final Query query = em.createQuery( "from Employee where salary between :low and :high" );
query.setParameter( "low", 300f );
query.setParameter( "high", 400f );
assertEquals( 0, query.getResultList().size() );
query.setParameter( "low", 100f );
query.setParameter( "high", 200f );
assertEquals( 0, query.getResultList().size() );
query.setParameter( "low", 200f );
query.setParameter( "high", 300f );
assertEquals( 1, query.getResultList().size() );
} );
}
@BeforeEach
public void setUpTestData(EntityManagerFactoryScope factoryScope) {
factoryScope.inTransaction( (em) -> {
em.persist( new Employee( 1, new Name( "John", "Q.", "Doe" ), SALARY ) );
} );
}
@AfterEach
public void cleanUpTestData(EntityManagerFactoryScope factoryScope) {
factoryScope.dropData();
}
@Entity( name = "Employee" )
@Table( name = "EMP" )
public static | QueryTest |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java | {
"start": 19612,
"end": 19849
} | class ____ {
@ReadOperation
@Nullable Object getAll() {
return null;
}
@ReadOperation
@Nullable Object getAll(String param) {
return null;
}
}
@WebEndpoint(id = "nonjmx")
static | ClashingOperationsJmxEndpointExtension |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/Politician.java | {
"start": 379,
"end": 779
} | class ____ {
private String name;
private PoliticalParty party;
@Id
@Column(columnDefinition = "VARCHAR(30)")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
@JoinColumn(name = "party_fk")
public PoliticalParty getParty() {
return party;
}
public void setParty(PoliticalParty party) {
this.party = party;
}
}
| Politician |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLTableSourceImpl.java | {
"start": 1009,
"end": 7193
} | class ____ extends SQLObjectImpl implements SQLTableSource {
protected boolean needAsTokenForAlias;
protected String alias;
protected List<SQLHint> hints;
protected SQLExpr flashback;
protected long aliasHashCode64;
protected SQLPivot pivot;
protected SQLUnpivot unpivot;
public SQLTableSourceImpl() {
}
public SQLTableSourceImpl(String alias) {
this.alias = alias;
}
public boolean isNeedAsTokenForAlias() {
return needAsTokenForAlias;
}
public void setNeedAsTokenForAlias(boolean needAsTokenForAlias) {
this.needAsTokenForAlias = needAsTokenForAlias;
}
public String getAlias() {
return this.alias;
}
public String getAlias2() {
if (this.alias == null || this.alias.length() == 0) {
return alias;
}
char first = alias.charAt(0);
if (first == '"' || first == '\'') {
char[] chars = new char[alias.length() - 2];
int len = 0;
for (int i = 1; i < alias.length() - 1; ++i) {
char ch = alias.charAt(i);
if (ch == '\\') {
++i;
ch = alias.charAt(i);
}
chars[len++] = ch;
}
return new String(chars, 0, len);
}
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
this.aliasHashCode64 = 0L;
}
public int getHintsSize() {
if (hints == null) {
return 0;
}
return hints.size();
}
public List<SQLHint> getHints() {
if (hints == null) {
hints = new ArrayList<SQLHint>(2);
}
return hints;
}
public void setHints(List<SQLHint> hints) {
this.hints = hints;
}
public SQLTableSource clone() {
throw new UnsupportedOperationException(this.getClass().getName());
}
public String computeAlias() {
return alias;
}
public SQLExpr getFlashback() {
return flashback;
}
public void setFlashback(SQLExpr flashback) {
if (flashback != null) {
flashback.setParent(this);
}
this.flashback = flashback;
}
public boolean containsAlias(String alias) {
if (SQLUtils.nameEquals(this.alias, alias)) {
return true;
}
return false;
}
public long aliasHashCode64() {
if (aliasHashCode64 == 0
&& alias != null) {
aliasHashCode64 = FnvHash.hashCode64(alias);
}
return aliasHashCode64;
}
public SQLColumnDefinition findColumn(String columnName) {
if (columnName == null) {
return null;
}
long hash = FnvHash.hashCode64(columnName);
return findColumn(hash);
}
public SQLColumnDefinition findColumn(long columnNameHash) {
return null;
}
public SQLObject resolveColumn(long columnNameHash) {
return findColumn(columnNameHash);
}
public SQLTableSource findTableSourceWithColumn(String columnName) {
if (columnName == null) {
return null;
}
long hash = FnvHash.hashCode64(columnName);
return findTableSourceWithColumn(hash, columnName, 0);
}
public SQLTableSource findTableSourceWithColumn(SQLName columnName) {
if (columnName instanceof SQLIdentifierExpr) {
return findTableSourceWithColumn(
columnName.nameHashCode64(), columnName.getSimpleName(), 0);
}
if (columnName instanceof SQLPropertyExpr) {
SQLExpr owner = ((SQLPropertyExpr) columnName).getOwner();
if (owner instanceof SQLIdentifierExpr) {
return findTableSource(((SQLIdentifierExpr) owner).nameHashCode64());
}
}
return null;
}
public SQLTableSource findTableSourceWithColumn(long columnNameHash) {
return findTableSourceWithColumn(columnNameHash, null, 0);
}
public SQLTableSource findTableSourceWithColumn(long columnNameHash, String columnName, int option) {
return null;
}
public SQLTableSource findTableSource(String alias) {
long hash = FnvHash.hashCode64(alias);
return findTableSource(hash);
}
public SQLTableSource findTableSource(long alias_hash) {
long hash = this.aliasHashCode64();
if (hash != 0 && hash == alias_hash) {
return this;
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SQLTableSourceImpl that = (SQLTableSourceImpl) o;
if (aliasHashCode64() != that.aliasHashCode64()) {
return false;
}
if (hints != null ? !hints.equals(that.hints) : that.hints != null) {
return false;
}
return flashback != null ? flashback.equals(that.flashback) : that.flashback == null;
}
@Override
public int hashCode() {
int result = (hints != null ? hints.hashCode() : 0);
result = 31 * result + (flashback != null ? flashback.hashCode() : 0);
result = 31 * result + (int) (aliasHashCode64() ^ (aliasHashCode64() >>> 32));
return result;
}
@Override
public SQLPivot getPivot() {
return pivot;
}
@Override
public void setPivot(SQLPivot x) {
if (x != null) {
x.setParent(this);
}
this.pivot = x;
}
public SQLUnpivot getUnpivot() {
return unpivot;
}
public void setUnpivot(SQLUnpivot x) {
if (x != null) {
x.setParent(this);
}
this.unpivot = x;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, this.flashback);
acceptChild(visitor, this.pivot);
acceptChild(visitor, this.unpivot);
}
visitor.endVisit(this);
}
}
| SQLTableSourceImpl |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.