language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/method/annotation/AuthenticationPrincipalArgumentResolverTests.java | {
"start": 11311,
"end": 11459
} | interface ____ {
}
@Target({ ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal
@ | CurrentUserErrorOnInvalidType |
java | netty__netty | codec-http/src/test/java/io/netty/handler/codec/http/HttpObjectAggregatorTest.java | {
"start": 1962,
"end": 34222
} | class ____ {
@Test
public void testAggregate() {
HttpObjectAggregator aggr = new HttpObjectAggregator(1024 * 1024);
EmbeddedChannel embedder = new EmbeddedChannel(aggr);
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost");
message.headers().set(of("X-Test"), true);
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test2", CharsetUtil.US_ASCII));
HttpContent chunk3 = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER);
assertFalse(embedder.writeInbound(message));
assertFalse(embedder.writeInbound(chunk1));
assertFalse(embedder.writeInbound(chunk2));
// this should trigger a channelRead event so return true
assertTrue(embedder.writeInbound(chunk3));
assertTrue(embedder.finish());
FullHttpRequest aggregatedMessage = embedder.readInbound();
assertNotNull(aggregatedMessage);
assertEquals(chunk1.content().readableBytes() + chunk2.content().readableBytes(),
HttpUtil.getContentLength(aggregatedMessage));
assertEquals(Boolean.TRUE.toString(), aggregatedMessage.headers().get(of("X-Test")));
checkContentBuffer(aggregatedMessage);
assertNull(embedder.readInbound());
}
private static void checkContentBuffer(FullHttpRequest aggregatedMessage) {
CompositeByteBuf buffer = (CompositeByteBuf) aggregatedMessage.content();
assertEquals(2, buffer.numComponents());
List<ByteBuf> buffers = buffer.decompose(0, buffer.capacity());
assertEquals(2, buffers.size());
for (ByteBuf buf: buffers) {
// This should be false as we decompose the buffer before to not have deep hierarchy
assertFalse(buf instanceof CompositeByteBuf);
}
aggregatedMessage.release();
}
@Test
public void testAggregateWithTrailer() {
HttpObjectAggregator aggr = new HttpObjectAggregator(1024 * 1024);
EmbeddedChannel embedder = new EmbeddedChannel(aggr);
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost");
message.headers().set(of("X-Test"), true);
HttpUtil.setTransferEncodingChunked(message, true);
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test2", CharsetUtil.US_ASCII));
LastHttpContent trailer = new DefaultLastHttpContent();
trailer.trailingHeaders().set(of("X-Trailer"), true);
assertFalse(embedder.writeInbound(message));
assertFalse(embedder.writeInbound(chunk1));
assertFalse(embedder.writeInbound(chunk2));
// this should trigger a channelRead event so return true
assertTrue(embedder.writeInbound(trailer));
assertTrue(embedder.finish());
FullHttpRequest aggregatedMessage = embedder.readInbound();
assertNotNull(aggregatedMessage);
assertEquals(chunk1.content().readableBytes() + chunk2.content().readableBytes(),
HttpUtil.getContentLength(aggregatedMessage));
assertEquals(Boolean.TRUE.toString(), aggregatedMessage.headers().get(of("X-Test")));
assertEquals(Boolean.TRUE.toString(), aggregatedMessage.trailingHeaders().get(of("X-Trailer")));
checkContentBuffer(aggregatedMessage);
assertNull(embedder.readInbound());
}
@Test
public void testOversizedRequest() {
final EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(4));
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test2", CharsetUtil.US_ASCII));
final HttpContent chunk3 = LastHttpContent.EMPTY_LAST_CONTENT;
assertFalse(embedder.writeInbound(message));
assertFalse(embedder.writeInbound(chunk1));
assertFalse(embedder.writeInbound(chunk2));
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertFalse(embedder.isOpen());
assertThrows(ClosedChannelException.class, new Executable() {
@Override
public void execute() {
embedder.writeInbound(chunk3);
}
});
assertFalse(embedder.finish());
}
@Test
public void testOversizedRequestWithContentLengthAndDecoder() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(4, false));
assertFalse(embedder.writeInbound(Unpooled.copiedBuffer(
"PUT /upload HTTP/1.1\r\n" +
"Content-Length: 5\r\n\r\n", CharsetUtil.US_ASCII)));
assertNull(embedder.readInbound());
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertTrue(embedder.isOpen());
assertFalse(embedder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 })));
assertFalse(embedder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 5 })));
assertNull(embedder.readOutbound());
assertFalse(embedder.writeInbound(Unpooled.copiedBuffer(
"PUT /upload HTTP/1.1\r\n" +
"Content-Length: 2\r\n\r\n", CharsetUtil.US_ASCII)));
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertInstanceOf(LastHttpContent.class, response);
ReferenceCountUtil.release(response);
assertTrue(embedder.isOpen());
assertFalse(embedder.writeInbound(Unpooled.copiedBuffer(new byte[] { 1 })));
assertNull(embedder.readOutbound());
assertTrue(embedder.writeInbound(Unpooled.copiedBuffer(new byte[] { 2 })));
assertNull(embedder.readOutbound());
FullHttpRequest request = embedder.readInbound();
assertEquals(HttpVersion.HTTP_1_1, request.protocolVersion());
assertEquals(HttpMethod.PUT, request.method());
assertEquals("/upload", request.uri());
assertEquals(2, HttpUtil.getContentLength(request));
byte[] actual = new byte[request.content().readableBytes()];
request.content().readBytes(actual);
assertArrayEquals(new byte[] { 1, 2 }, actual);
request.release();
assertFalse(embedder.finish());
}
@Test
public void testOversizedRequestWithoutKeepAlive() {
// send an HTTP/1.0 request with no keep-alive header
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.PUT, "http://localhost");
HttpUtil.setContentLength(message, 5);
checkOversizedRequest(message);
}
@Test
public void testOversizedRequestWithContentLength() {
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
HttpUtil.setContentLength(message, 5);
checkOversizedRequest(message);
}
private static void checkOversizedRequest(HttpRequest message) {
final EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(4));
assertFalse(embedder.writeInbound(message));
HttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertInstanceOf(LastHttpContent.class, response);
ReferenceCountUtil.release(response);
if (serverShouldCloseConnection(message, response)) {
assertFalse(embedder.isOpen());
assertThrows(ClosedChannelException.class, new Executable() {
@Override
public void execute() {
embedder.writeInbound(new DefaultHttpContent(Unpooled.EMPTY_BUFFER));
}
});
assertFalse(embedder.finish());
} else {
assertTrue(embedder.isOpen());
assertFalse(embedder.writeInbound(new DefaultHttpContent(Unpooled.copiedBuffer(new byte[8]))));
assertFalse(embedder.writeInbound(new DefaultHttpContent(Unpooled.copiedBuffer(new byte[8]))));
// Now start a new message and ensure we will not reject it again.
HttpRequest message2 = new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.PUT, "http://localhost");
HttpUtil.setContentLength(message, 2);
assertFalse(embedder.writeInbound(message2));
assertNull(embedder.readOutbound());
assertFalse(embedder.writeInbound(new DefaultHttpContent(Unpooled.copiedBuffer(new byte[] { 1 }))));
assertNull(embedder.readOutbound());
assertTrue(embedder.writeInbound(new DefaultLastHttpContent(Unpooled.copiedBuffer(new byte[] { 2 }))));
assertNull(embedder.readOutbound());
FullHttpRequest request = embedder.readInbound();
assertEquals(message2.protocolVersion(), request.protocolVersion());
assertEquals(message2.method(), request.method());
assertEquals(message2.uri(), request.uri());
assertEquals(2, HttpUtil.getContentLength(request));
byte[] actual = new byte[request.content().readableBytes()];
request.content().readBytes(actual);
assertArrayEquals(new byte[] { 1, 2 }, actual);
request.release();
assertFalse(embedder.finish());
}
}
private static boolean serverShouldCloseConnection(HttpRequest message, HttpResponse response) {
// If the response wasn't keep-alive, the server should close the connection.
if (!HttpUtil.isKeepAlive(response)) {
return true;
}
// The connection should only be kept open if Expect: 100-continue is set,
// or if keep-alive is on.
if (HttpUtil.is100ContinueExpected(message)) {
return false;
}
if (HttpUtil.isKeepAlive(message)) {
return false;
}
return true;
}
@Test
public void testOversizedResponse() {
final EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(4));
HttpResponse message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
final HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test2", CharsetUtil.US_ASCII));
assertFalse(embedder.writeInbound(message));
assertFalse(embedder.writeInbound(chunk1));
assertThrows(TooLongHttpContentException.class, new Executable() {
@Override
public void execute() {
embedder.writeInbound(chunk2);
}
});
assertFalse(embedder.isOpen());
assertFalse(embedder.finish());
}
@Test
public void testInvalidConstructorUsage() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
new HttpObjectAggregator(-1);
}
});
}
@Test
public void testInvalidMaxCumulationBufferComponents() {
final HttpObjectAggregator aggr = new HttpObjectAggregator(Integer.MAX_VALUE);
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
aggr.setMaxCumulationBufferComponents(1);
}
});
}
@Test
public void testSetMaxCumulationBufferComponentsAfterInit() throws Exception {
final HttpObjectAggregator aggr = new HttpObjectAggregator(Integer.MAX_VALUE);
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
aggr.handlerAdded(ctx);
Mockito.verifyNoMoreInteractions(ctx);
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
aggr.setMaxCumulationBufferComponents(10);
}
});
}
@Test
public void testAggregateTransferEncodingChunked() {
HttpObjectAggregator aggr = new HttpObjectAggregator(1024 * 1024);
EmbeddedChannel embedder = new EmbeddedChannel(aggr);
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
message.headers().set(of("X-Test"), true);
message.headers().set(of("Transfer-Encoding"), of("Chunked"));
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test2", CharsetUtil.US_ASCII));
HttpContent chunk3 = LastHttpContent.EMPTY_LAST_CONTENT;
assertFalse(embedder.writeInbound(message));
assertFalse(embedder.writeInbound(chunk1));
assertFalse(embedder.writeInbound(chunk2));
// this should trigger a channelRead event so return true
assertTrue(embedder.writeInbound(chunk3));
assertTrue(embedder.finish());
FullHttpRequest aggregatedMessage = embedder.readInbound();
assertNotNull(aggregatedMessage);
assertEquals(chunk1.content().readableBytes() + chunk2.content().readableBytes(),
HttpUtil.getContentLength(aggregatedMessage));
assertEquals(Boolean.TRUE.toString(), aggregatedMessage.headers().get(of("X-Test")));
checkContentBuffer(aggregatedMessage);
assertNull(embedder.readInbound());
}
@Test
public void testBadRequest() {
EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(1024 * 1024));
ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0 with extra\r\n", CharsetUtil.UTF_8));
Object inbound = ch.readInbound();
assertInstanceOf(FullHttpRequest.class, inbound);
assertTrue(((DecoderResultProvider) inbound).decoderResult().isFailure());
assertNull(ch.readInbound());
ch.finish();
}
@Test
public void testBadResponse() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder(), new HttpObjectAggregator(1024 * 1024));
ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.0 BAD_CODE Bad Server\r\n", CharsetUtil.UTF_8));
Object inbound = ch.readInbound();
assertInstanceOf(FullHttpResponse.class, inbound);
assertTrue(((DecoderResultProvider) inbound).decoderResult().isFailure());
assertNull(ch.readInbound());
ch.finish();
}
@Test
public void testOversizedRequestWith100Continue() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(8));
// Send an oversized request with 100 continue.
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
HttpUtil.set100ContinueExpected(message, true);
HttpUtil.setContentLength(message, 16);
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("some", CharsetUtil.US_ASCII));
HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
HttpContent chunk3 = LastHttpContent.EMPTY_LAST_CONTENT;
// Send a request with 100-continue + large Content-Length header value.
assertFalse(embedder.writeInbound(message));
// The aggregator should respond with '413.'
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// An ill-behaving client could continue to send data without a respect, and such data should be discarded.
assertFalse(embedder.writeInbound(chunk1));
// The aggregator should not close the connection because keep-alive is on.
assertTrue(embedder.isOpen());
// Now send a valid request.
HttpRequest message2 = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
assertFalse(embedder.writeInbound(message2));
assertFalse(embedder.writeInbound(chunk2));
assertTrue(embedder.writeInbound(chunk3));
FullHttpRequest fullMsg = embedder.readInbound();
assertNotNull(fullMsg);
assertEquals(
chunk2.content().readableBytes() + chunk3.content().readableBytes(),
HttpUtil.getContentLength(fullMsg));
assertEquals(HttpUtil.getContentLength(fullMsg), fullMsg.content().readableBytes());
fullMsg.release();
assertFalse(embedder.finish());
}
@Test
public void testUnsupportedExpectHeaderExpectation() {
runUnsupportedExceptHeaderExceptionTest(true);
runUnsupportedExceptHeaderExceptionTest(false);
}
private static void runUnsupportedExceptHeaderExceptionTest(final boolean close) {
final HttpObjectAggregator aggregator;
final int maxContentLength = 4;
if (close) {
aggregator = new HttpObjectAggregator(maxContentLength, true);
} else {
aggregator = new HttpObjectAggregator(maxContentLength);
}
final EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), aggregator);
assertFalse(embedder.writeInbound(Unpooled.copiedBuffer(
"GET / HTTP/1.1\r\n" +
"Expect: chocolate=yummy\r\n" +
"Content-Length: 100\r\n\r\n", CharsetUtil.US_ASCII)));
assertNull(embedder.readInbound());
final FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.EXPECTATION_FAILED, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
response.release();
if (close) {
assertFalse(embedder.isOpen());
} else {
// keep-alive is on by default in HTTP/1.1, so the connection should be still alive
assertTrue(embedder.isOpen());
// the decoder should be reset by the aggregator at this point and be able to decode the next request
assertTrue(embedder.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.1\r\n\r\n", CharsetUtil.US_ASCII)));
final FullHttpRequest request = embedder.readInbound();
assertEquals(HttpMethod.GET, request.method());
assertEquals("/", request.uri());
assertEquals(0, request.content().readableBytes());
request.release();
}
assertFalse(embedder.finish());
}
@Test
public void testValidRequestWith100ContinueAndDecoder() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(100));
embedder.writeInbound(Unpooled.copiedBuffer(
"GET /upload HTTP/1.1\r\n" +
"Expect: 100-continue\r\n" +
"Content-Length: 0\r\n\r\n", CharsetUtil.US_ASCII));
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.CONTINUE, response.status());
FullHttpRequest request = embedder.readInbound();
assertFalse(request.headers().contains(HttpHeaderNames.EXPECT));
request.release();
response.release();
assertFalse(embedder.finish());
}
@Test
public void testOversizedRequestWith100ContinueAndDecoder() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(4));
embedder.writeInbound(Unpooled.copiedBuffer(
"PUT /upload HTTP/1.1\r\n" +
"Expect: 100-continue\r\n" +
"Content-Length: 100\r\n\r\n", CharsetUtil.US_ASCII));
assertNull(embedder.readInbound());
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// Keep-alive is on by default in HTTP/1.1, so the connection should be still alive.
assertTrue(embedder.isOpen());
// The decoder should be reset by the aggregator at this point and be able to decode the next request.
embedder.writeInbound(Unpooled.copiedBuffer("GET /max-upload-size HTTP/1.1\r\n\r\n", CharsetUtil.US_ASCII));
FullHttpRequest request = embedder.readInbound();
assertEquals(HttpMethod.GET, request.method());
assertEquals("/max-upload-size", request.uri());
assertEquals(0, request.content().readableBytes());
request.release();
assertFalse(embedder.finish());
}
@Test
public void testOversizedRequestWith100ContinueAndDecoderCloseConnection() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(4, true));
embedder.writeInbound(Unpooled.copiedBuffer(
"PUT /upload HTTP/1.1\r\n" +
"Expect: 100-continue\r\n" +
"Content-Length: 100\r\n\r\n", CharsetUtil.US_ASCII));
assertNull(embedder.readInbound());
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// We are forcing the connection closed if an expectation is exceeded.
assertFalse(embedder.isOpen());
assertFalse(embedder.finish());
}
@Test
public void testRequestAfterOversized100ContinueAndDecoder() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(15));
// Write first request with Expect: 100-continue.
HttpRequest message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
HttpUtil.set100ContinueExpected(message, true);
HttpUtil.setContentLength(message, 16);
HttpContent chunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("some", CharsetUtil.US_ASCII));
HttpContent chunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII));
HttpContent chunk3 = LastHttpContent.EMPTY_LAST_CONTENT;
// Send a request with 100-continue + large Content-Length header value.
assertFalse(embedder.writeInbound(message));
// The aggregator should respond with '413'.
FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// An ill-behaving client could continue to send data without a respect, and such data should be discarded.
assertFalse(embedder.writeInbound(chunk1));
// The aggregator should not close the connection because keep-alive is on.
assertTrue(embedder.isOpen());
// Now send a valid request.
HttpRequest message2 = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "http://localhost");
assertFalse(embedder.writeInbound(message2));
assertFalse(embedder.writeInbound(chunk2));
assertTrue(embedder.writeInbound(chunk3));
FullHttpRequest fullMsg = embedder.readInbound();
assertNotNull(fullMsg);
assertEquals(
chunk2.content().readableBytes() + chunk3.content().readableBytes(),
HttpUtil.getContentLength(fullMsg));
assertEquals(HttpUtil.getContentLength(fullMsg), fullMsg.content().readableBytes());
fullMsg.release();
assertFalse(embedder.finish());
}
@Test
public void testReplaceAggregatedRequest() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(1024 * 1024));
Exception boom = new Exception("boom");
HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost");
req.setDecoderResult(DecoderResult.failure(boom));
assertTrue(embedder.writeInbound(req) && embedder.finish());
FullHttpRequest aggregatedReq = embedder.readInbound();
FullHttpRequest replacedReq = aggregatedReq.replace(Unpooled.EMPTY_BUFFER);
assertEquals(replacedReq.decoderResult(), aggregatedReq.decoderResult());
aggregatedReq.release();
replacedReq.release();
}
@Test
public void testReplaceAggregatedResponse() {
EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(1024 * 1024));
Exception boom = new Exception("boom");
HttpResponse rep = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
rep.setDecoderResult(DecoderResult.failure(boom));
assertTrue(embedder.writeInbound(rep) && embedder.finish());
FullHttpResponse aggregatedRep = embedder.readInbound();
FullHttpResponse replacedRep = aggregatedRep.replace(Unpooled.EMPTY_BUFFER);
assertEquals(replacedRep.decoderResult(), aggregatedRep.decoderResult());
aggregatedRep.release();
replacedRep.release();
}
@Test
public void testSelectiveRequestAggregation() {
HttpObjectAggregator myPostAggregator = new HttpObjectAggregator(1024 * 1024) {
@Override
protected boolean isStartMessage(HttpObject msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
HttpMethod method = request.method();
if (method.equals(HttpMethod.POST)) {
return true;
}
}
return false;
}
};
EmbeddedChannel channel = new EmbeddedChannel(myPostAggregator);
try {
// Aggregate: POST
HttpRequest request1 = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
HttpContent content1 = new DefaultHttpContent(Unpooled.copiedBuffer("Hello, World!", CharsetUtil.UTF_8));
request1.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
assertTrue(channel.writeInbound(request1, content1, LastHttpContent.EMPTY_LAST_CONTENT));
// Getting an aggregated response out
Object msg1 = channel.readInbound();
try {
assertTrue(msg1 instanceof FullHttpRequest);
} finally {
ReferenceCountUtil.release(msg1);
}
// Don't aggregate: non-POST
HttpRequest request2 = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/");
HttpContent content2 = new DefaultHttpContent(Unpooled.copiedBuffer("Hello, World!", CharsetUtil.UTF_8));
request2.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
try {
assertTrue(channel.writeInbound(request2, content2, LastHttpContent.EMPTY_LAST_CONTENT));
// Getting the same response objects out
assertSame(request2, channel.readInbound());
assertSame(content2, channel.readInbound());
assertSame(LastHttpContent.EMPTY_LAST_CONTENT, channel.readInbound());
} finally {
ReferenceCountUtil.release(request2);
ReferenceCountUtil.release(content2);
}
assertFalse(channel.finish());
} finally {
channel.close();
}
}
@Test
public void testSelectiveResponseAggregation() {
HttpObjectAggregator myTextAggregator = new HttpObjectAggregator(1024 * 1024) {
@Override
protected boolean isStartMessage(HttpObject msg) throws Exception {
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
HttpHeaders headers = response.headers();
String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
if (AsciiString.contentEqualsIgnoreCase(contentType, HttpHeaderValues.TEXT_PLAIN)) {
return true;
}
}
return false;
}
};
EmbeddedChannel channel = new EmbeddedChannel(myTextAggregator);
try {
// Aggregate: text/plain
HttpResponse response1 = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
HttpContent content1 = new DefaultHttpContent(Unpooled.copiedBuffer("Hello, World!", CharsetUtil.UTF_8));
response1.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
assertTrue(channel.writeInbound(response1, content1, LastHttpContent.EMPTY_LAST_CONTENT));
// Getting an aggregated response out
Object msg1 = channel.readInbound();
try {
assertTrue(msg1 instanceof FullHttpResponse);
} finally {
ReferenceCountUtil.release(msg1);
}
// Don't aggregate: application/json
HttpResponse response2 = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
HttpContent content2 = new DefaultHttpContent(Unpooled.copiedBuffer("{key: 'value'}", CharsetUtil.UTF_8));
response2.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
try {
assertTrue(channel.writeInbound(response2, content2, LastHttpContent.EMPTY_LAST_CONTENT));
// Getting the same response objects out
assertSame(response2, channel.readInbound());
assertSame(content2, channel.readInbound());
assertSame(LastHttpContent.EMPTY_LAST_CONTENT, channel.readInbound());
} finally {
ReferenceCountUtil.release(response2);
ReferenceCountUtil.release(content2);
}
assertFalse(channel.finish());
} finally {
channel.close();
}
}
@Test
public void testPrematureClosureWithChunkedEncodingAndAggregator() {
final EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder(), new HttpObjectAggregator(1024));
// Write the partial response.
assertFalse(ch.writeInbound(Unpooled.copiedBuffer(
"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n8\r\n12345678", CharsetUtil.US_ASCII)));
assertThrows(PrematureChannelClosureException.class, new Executable() {
@Override
public void execute() {
ch.finish();
}
});
}
@Test
public void invalidContinueLength() {
EmbeddedChannel channel = new EmbeddedChannel(new HttpServerCodec(), new HttpObjectAggregator(1024));
channel.writeInbound(Unpooled.copiedBuffer("POST / HTTP/1.1\r\n" +
"Expect: 100-continue\r\n" +
"Content-Length:\r\n" +
"\r\n\r\n", CharsetUtil.US_ASCII));
assertTrue(channel.finishAndReleaseAll());
}
}
| HttpObjectAggregatorTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/node/reload/NodesReloadSecureSettingsResponse.java | {
"start": 1448,
"end": 3800
} | class ____ extends BaseNodesResponse<NodesReloadSecureSettingsResponse.NodeResponse>
implements
ToXContentFragment {
public NodesReloadSecureSettingsResponse(ClusterName clusterName, List<NodeResponse> nodes, List<FailedNodeException> failures) {
super(clusterName, nodes, failures);
}
@Override
protected List<NodesReloadSecureSettingsResponse.NodeResponse> readNodesFrom(StreamInput in) throws IOException {
return TransportAction.localOnly();
}
@Override
protected void writeNodesTo(StreamOutput out, List<NodesReloadSecureSettingsResponse.NodeResponse> nodes) throws IOException {
TransportAction.localOnly();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject("nodes");
for (final NodesReloadSecureSettingsResponse.NodeResponse node : getNodes()) {
builder.startObject(node.getNode().getId());
builder.field("name", node.getNode().getName());
final Exception e = node.reloadException();
if (e != null) {
builder.startObject("reload_exception");
ElasticsearchException.generateThrowableXContent(builder, params, e);
builder.endObject();
}
if (node.secureSettingNames() != null) {
builder.array("secure_setting_names", b -> {
for (String settingName : Stream.of(node.secureSettingNames()).sorted().toList()) {
b.value(settingName);
}
});
}
if (node.keystorePath() != null) {
builder.field("keystore_path", node.keystorePath());
}
if (node.keystoreDigest() != null) {
builder.field("keystore_digest", node.keystoreDigest());
}
if (node.keystoreLastModifiedTime() != null) {
builder.field("keystore_last_modified_time", Instant.ofEpochMilli(node.keystoreLastModifiedTime()));
}
builder.endObject();
}
builder.endObject();
return builder;
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
public static | NodesReloadSecureSettingsResponse |
java | google__dagger | javatests/dagger/hilt/android/processor/internal/customtestapplication/CustomTestApplicationProcessorTest.java | {
"start": 2392,
"end": 3100
} | class ____ {}"))
.compile(
subject -> {
subject.hasErrorContaining(
"@CustomTestApplication value should be an instance of android.app.Application. "
+ "Found: test.Foo");
});
}
@Test
public void baseWithHiltAndroidApp_fails() {
HiltCompilerTests.hiltCompiler(
HiltCompilerTests.javaSource(
"test.BaseApplication",
"package test;",
"",
"import android.app.Application;",
"import dagger.hilt.android.HiltAndroidApp;",
"",
"@HiltAndroidApp(Application.class)",
"public | HiltTest |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanWithPublicConstructor.java | {
"start": 833,
"end": 1168
} | class ____ {
private @Nullable String value;
public JavaBeanWithPublicConstructor() {
}
public JavaBeanWithPublicConstructor(String value) {
setValue(value);
}
public @Nullable String getValue() {
return this.value;
}
public void setValue(@Nullable String value) {
this.value = value;
}
}
| JavaBeanWithPublicConstructor |
java | quarkusio__quarkus | extensions/hibernate-validator/deployment/src/main/java/io/quarkus/hibernate/validator/deployment/MethodValidatedAnnotationsTransformer.java | {
"start": 703,
"end": 4695
} | class ____ implements AnnotationsTransformer {
private static final Logger LOGGER = Logger.getLogger(MethodValidatedAnnotationsTransformer.class.getPackage().getName());
private final Set<DotName> consideredAnnotations;
private final Map<DotName, Set<SimpleMethodSignatureKey>> methodsWithInheritedValidation;
private final Map<DotName, Set<SimpleMethodSignatureKey>> jaxRsMethods;
MethodValidatedAnnotationsTransformer(Set<DotName> consideredAnnotations,
Map<DotName, Set<SimpleMethodSignatureKey>> jaxRsMethods,
Map<DotName, Set<SimpleMethodSignatureKey>> methodsWithInheritedValidation) {
this.consideredAnnotations = consideredAnnotations;
this.jaxRsMethods = jaxRsMethods;
this.methodsWithInheritedValidation = methodsWithInheritedValidation;
}
@Override
public boolean appliesTo(Kind kind) {
return Kind.METHOD == kind;
}
@Override
public void transform(TransformationContext transformationContext) {
MethodInfo method = transformationContext.getTarget().asMethod();
if (requiresValidation(method)) {
if (Modifier.isStatic(method.flags())) {
// We don't support validating methods on static methods yet as it used to not be supported by CDI/Weld
// Supporting it will require some work in Hibernate Validator so we are going back to the old behavior of ignoring them but we log a warning.
LOGGER.warnf(
"Hibernate Validator does not support constraints on static methods yet. Constraints on %s are ignored.",
method.declaringClass().name().toString() + "#" + method.toString());
return;
}
if (isJaxrsMethod(method)) {
transformationContext.transform().add(DotName.createSimple(JaxrsEndPointValidated.class.getName())).done();
} else {
transformationContext.transform().add(DotName.createSimple(MethodValidated.class.getName())).done();
}
}
}
private boolean requiresValidation(MethodInfo method) {
for (DotName consideredAnnotation : consideredAnnotations) {
if (method.hasAnnotation(consideredAnnotation)) {
return !isSynthetic(method.flags());
}
}
// This method has no annotations of its own: look for inherited annotations
Set<SimpleMethodSignatureKey> validatedMethods = methodsWithInheritedValidation.get(method.declaringClass().name());
if (validatedMethods == null || validatedMethods.isEmpty()) {
return false;
}
return validatedMethods.contains(new SimpleMethodSignatureKey(method));
}
private boolean isSynthetic(int mod) {
return (mod & Opcodes.ACC_SYNTHETIC) != 0;
}
private boolean isJaxrsMethod(MethodInfo method) {
ClassInfo clazz = method.declaringClass();
SimpleMethodSignatureKey signatureKey = new SimpleMethodSignatureKey(method);
if (isJaxrsMethod(signatureKey, clazz.name())) {
return true;
}
// check interfaces
for (DotName iface : clazz.interfaceNames()) {
if (isJaxrsMethod(signatureKey, iface)) {
return true;
}
}
// check superclass, but only the direct one since we do not (yet) have the entire ClassInfo hierarchy here
DotName superClass = clazz.superName();
if (!superClass.equals(IndexingUtil.OBJECT)) {
if (isJaxrsMethod(signatureKey, superClass)) {
return true;
}
}
return false;
}
private boolean isJaxrsMethod(SimpleMethodSignatureKey signatureKey, DotName dotName) {
Set<SimpleMethodSignatureKey> signatureKeys = jaxRsMethods.get(dotName);
return signatureKeys != null && signatureKeys.contains(signatureKey);
}
}
| MethodValidatedAnnotationsTransformer |
java | elastic__elasticsearch | x-pack/plugin/esql/arrow/src/main/java/org/elasticsearch/xpack/esql/arrow/BlockConverter.java | {
"start": 4048,
"end": 5333
} | class ____ extends BlockConverter {
public AsInt32(String esqlType) {
super(esqlType, Types.MinorType.INT);
}
@Override
public void convert(Block b, boolean multivalued, List<ArrowBuf> bufs, List<BufWriter> bufWriters) {
IntBlock block = (IntBlock) b;
if (multivalued) {
addListOffsets(bufs, bufWriters, block);
}
accumulateVectorValidity(bufs, bufWriters, block, multivalued);
bufs.add(dummyArrowBuf(vectorByteSize(block)));
bufWriters.add(out -> {
if (block.areAllValuesNull()) {
return BlockConverter.writeZeroes(out, vectorByteSize(block));
}
// TODO could we "just" get the memory of the array and dump it?
int count = BlockConverter.valueCount(block);
for (int i = 0; i < count; i++) {
out.writeIntLE(block.getInt(i));
}
return (long) count * Integer.BYTES;
});
}
private static int vectorByteSize(Block b) {
return Integer.BYTES * BlockConverter.valueCount(b);
}
}
/**
* Conversion of Long blocks
*/
public static | AsInt32 |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java | {
"start": 1611,
"end": 3960
} | class ____ {
private ParserContext parserContext;
private CollectingReaderEventListener readerEventListener = new CollectingReaderEventListener();
private BeanDefinitionRegistry registry = new DefaultListableBeanFactory();
@BeforeEach
public void setUp() {
SourceExtractor sourceExtractor = new PassThroughSourceExtractor();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.registry);
XmlReaderContext readerContext =
new XmlReaderContext(null, null, this.readerEventListener, sourceExtractor, reader, null);
this.parserContext = new ParserContext(readerContext, null);
}
@Test
void testRegisterAutoProxyCreator() {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
}
@Test
void testRegisterAspectJAutoProxyCreator() {
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertThat(definition.getBeanClassName()).as("Incorrect APC class").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName());
}
@Test
void testRegisterAspectJAutoProxyCreatorWithExistingAutoProxyCreator() {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertThat(registry.getBeanDefinitionCount()).isEqualTo(1);
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertThat(registry.getBeanDefinitionCount()).as("Incorrect definition count").isEqualTo(1);
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertThat(definition.getBeanClassName()).as("APC | AspectJNamespaceHandlerTests |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/classloading/ComponentClassLoader.java | {
"start": 4307,
"end": 4571
} | class ____ subsume the FlinkUserCodeClassLoader (with an added
// exception handler)
return loadClassFromComponentOnly(name, resolve);
} catch (ClassNotFoundException e) {
// If we know the package of this | to |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/reindex/ScrollableHitSource.java | {
"start": 8094,
"end": 9563
} | interface ____ {
/**
* The index in which the hit is stored.
*/
String getIndex();
/**
* The document id of the hit.
*/
String getId();
/**
* The version of the match or {@code -1} if the version wasn't requested. The {@code -1} keeps it inline with Elasticsearch's
* internal APIs.
*/
long getVersion();
/**
* The sequence number of the match or {@link SequenceNumbers#UNASSIGNED_SEQ_NO} if sequence numbers weren't requested.
*/
long getSeqNo();
/**
* The primary term of the match or {@link SequenceNumbers#UNASSIGNED_PRIMARY_TERM} if sequence numbers weren't requested.
*/
long getPrimaryTerm();
/**
* The source of the hit. Returns null if the source didn't come back from the search, usually because it source wasn't stored at
* all.
*/
@Nullable
BytesReference getSource();
/**
* The content type of the hit source. Returns null if the source didn't come back from the search.
*/
@Nullable
XContentType getXContentType();
/**
* The routing on the hit if there is any or null if there isn't.
*/
@Nullable
String getRouting();
}
/**
* An implementation of {@linkplain Hit} that uses getters and setters.
*/
public static | Hit |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java | {
"start": 3598,
"end": 11026
} | class ____ the element type to decode to
* @param <T> the element type to decode to
* @return {@code BodyExtractor} for {@code Flux<T>}
*/
public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(Class<? extends T> elementClass) {
return toFlux(ResolvableType.forClass(elementClass));
}
/**
* Variant of {@link #toFlux(Class)} for type information with generics.
* @param typeRef the type reference for the type to decode to
* @param <T> the element type to decode to
* @return {@code BodyExtractor} for {@code Flux<T>}
*/
public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ParameterizedTypeReference<T> typeRef) {
return toFlux(ResolvableType.forType(typeRef.getType()));
}
@SuppressWarnings("unchecked")
private static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ResolvableType elementType) {
return (inputMessage, context) ->
readWithMessageReaders(inputMessage, context, elementType,
(HttpMessageReader<T> reader) -> readToFlux(inputMessage, context, elementType, reader),
ex -> unsupportedErrorHandler(inputMessage, ex),
skipBodyAsFlux(inputMessage));
}
// Extractors for specific content ..
/**
* Extractor to read form data into {@code MultiValueMap<String, String>}.
* <p>As of 5.1 this method can also be used on the client side to read form
* data from a server response (for example, OAuth).
* @return {@code BodyExtractor} for form data
*/
public static BodyExtractor<Mono<MultiValueMap<String, String>>, ReactiveHttpInputMessage> toFormData() {
return (message, context) -> {
ResolvableType elementType = FORM_DATA_TYPE;
MediaType mediaType = MediaType.APPLICATION_FORM_URLENCODED;
HttpMessageReader<MultiValueMap<String, String>> reader = findReader(elementType, mediaType, context);
return readToMono(message, context, elementType, reader);
};
}
/**
* Extractor to read multipart data into a {@code MultiValueMap<String, Part>}.
* <p><strong>Note:</strong> that resources used for part handling,
* like storage for the uploaded files, is not deleted automatically, but
* should be done via {@link Part#delete()}.
* @return {@code BodyExtractor} for multipart data
*/
// Parameterized for server-side use
public static BodyExtractor<Mono<MultiValueMap<String, Part>>, ServerHttpRequest> toMultipartData() {
return (serverRequest, context) -> {
ResolvableType elementType = MULTIPART_DATA_TYPE;
MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
HttpMessageReader<MultiValueMap<String, Part>> reader = findReader(elementType, mediaType, context);
return readToMono(serverRequest, context, elementType, reader);
};
}
/**
* Extractor to read multipart data into {@code Flux<Part>}.
* <p><strong>Note:</strong> that resources used for part handling,
* like storage for the uploaded files, is not deleted automatically, but
* should be done via {@link Part#delete()}.
* @return {@code BodyExtractor} for multipart request parts
*/
// Parameterized for server-side use
public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() {
return (serverRequest, context) -> {
ResolvableType elementType = PART_TYPE;
MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
HttpMessageReader<Part> reader = findReader(elementType, mediaType, context);
return readToFlux(serverRequest, context, elementType, reader);
};
}
/**
* Extractor that returns the raw {@link DataBuffer DataBuffers}.
* <p><strong>Note:</strong> the data buffers should be
* {@link org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer)
* released} after being used.
* @return {@code BodyExtractor} for data buffers
*/
public static BodyExtractor<Flux<DataBuffer>, ReactiveHttpInputMessage> toDataBuffers() {
return (inputMessage, context) -> inputMessage.getBody();
}
// Private support methods
private static <T, S extends Publisher<T>> S readWithMessageReaders(
ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType,
Function<HttpMessageReader<T>, S> readerFunction,
Function<UnsupportedMediaTypeException, S> errorFunction,
Supplier<S> emptySupplier) {
if (VOID_TYPE.equals(elementType)) {
return emptySupplier.get();
}
MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType())
.orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageReader<?> messageReader : context.messageReaders()) {
if (messageReader.canRead(elementType, contentType)) {
return readerFunction.apply(cast(messageReader));
}
}
List<MediaType> mediaTypes = context.messageReaders().stream()
.flatMap(reader -> reader.getReadableMediaTypes(elementType).stream())
.toList();
return errorFunction.apply(
new UnsupportedMediaTypeException(contentType, mediaTypes, elementType));
}
private static <T> Mono<T> readToMono(ReactiveHttpInputMessage message, BodyExtractor.Context context,
ResolvableType type, HttpMessageReader<T> reader) {
return context.serverResponse()
.map(response -> reader.readMono(type, type, (ServerHttpRequest) message, response, context.hints()))
.orElseGet(() -> reader.readMono(type, message, context.hints()));
}
private static <T> Flux<T> readToFlux(ReactiveHttpInputMessage message, BodyExtractor.Context context,
ResolvableType type, HttpMessageReader<T> reader) {
return context.serverResponse()
.map(response -> reader.read(type, type, (ServerHttpRequest) message, response, context.hints()))
.orElseGet(() -> reader.read(type, message, context.hints()));
}
private static <T> Flux<T> unsupportedErrorHandler(
ReactiveHttpInputMessage message, UnsupportedMediaTypeException ex) {
Flux<T> result;
if (message.getHeaders().getContentType() == null) {
// Maybe it's okay there is no content type, if there is no content.
result = message.getBody().map(buffer -> {
DataBufferUtils.release(buffer);
throw ex;
});
}
else {
result = message instanceof ClientHttpResponse ?
consumeAndCancel(message).thenMany(Flux.error(ex)) : Flux.error(ex);
}
return result;
}
private static <T> HttpMessageReader<T> findReader(
ResolvableType elementType, MediaType mediaType, BodyExtractor.Context context) {
for (HttpMessageReader<?> messageReader : context.messageReaders()) {
if (messageReader.canRead(elementType, mediaType)) {
return cast(messageReader);
}
}
throw new IllegalStateException(
"No HttpMessageReader for \"" + mediaType + "\" and \"" + elementType + "\"");
}
@SuppressWarnings("unchecked")
private static <T> HttpMessageReader<T> cast(HttpMessageReader<?> reader) {
return (HttpMessageReader<T>) reader;
}
private static <T> Supplier<Flux<T>> skipBodyAsFlux(ReactiveHttpInputMessage message) {
return message instanceof ClientHttpResponse ?
() -> consumeAndCancel(message).thenMany(Mono.empty()) : Flux::empty;
}
@SuppressWarnings("unchecked")
private static <T> Supplier<Mono<T>> skipBodyAsMono(ReactiveHttpInputMessage message) {
return message instanceof ClientHttpResponse ?
() -> consumeAndCancel(message).then(Mono.empty()) : Mono::empty;
}
private static Flux<DataBuffer> consumeAndCancel(ReactiveHttpInputMessage message) {
return message.getBody().takeWhile(buffer -> {
DataBufferUtils.release(buffer);
return false;
});
}
}
| of |
java | google__gson | gson/src/test/java/com/google/gson/FieldAttributesTest.java | {
"start": 2428,
"end": 2541
} | class ____ {
@SuppressWarnings({"unused", "EffectivelyPrivate"})
public transient List<String> bar;
}
}
| Foo |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ccr/action/PutFollowAction.java | {
"start": 1717,
"end": 2235
} | class ____ extends AcknowledgedRequest<Request> implements IndicesRequest, ToXContentObject {
private static final ParseField REMOTE_CLUSTER_FIELD = new ParseField("remote_cluster");
private static final ParseField LEADER_INDEX_FIELD = new ParseField("leader_index");
private static final ParseField SETTINGS_FIELD = new ParseField("settings");
private static final ParseField DATA_STREAM_NAME = new ParseField("data_stream_name");
// Note that Request should be the Value | Request |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumSqlserverEndpointBuilderFactory.java | {
"start": 1593,
"end": 4369
} | interface ____
extends
EndpointConsumerBuilder {
default AdvancedDebeziumSqlserverEndpointBuilder advanced() {
return (AdvancedDebeziumSqlserverEndpointBuilder) this;
}
/**
* Additional properties for debezium components in case they can't be
* set directly on the camel configurations (e.g: setting Kafka Connect
* properties needed by Debezium engine, for example setting
* KafkaOffsetBackingStore), the properties have to be prefixed with
* additionalProperties.. E.g:
* additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=http://localhost:8811/avro. This is a multi-value option with prefix: additionalProperties.
*
* 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
* additionalProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: common
*
* @param key the option key
* @param value the option value
* @return the dsl builder
*/
default DebeziumSqlserverEndpointBuilder additionalProperties(String key, Object value) {
doSetMultiValueProperty("additionalProperties", "additionalProperties." + key, value);
return this;
}
/**
* Additional properties for debezium components in case they can't be
* set directly on the camel configurations (e.g: setting Kafka Connect
* properties needed by Debezium engine, for example setting
* KafkaOffsetBackingStore), the properties have to be prefixed with
* additionalProperties.. E.g:
* additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=http://localhost:8811/avro. This is a multi-value option with prefix: additionalProperties.
*
* 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
* additionalProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: common
*
* @param values the values
* @return the dsl builder
*/
default DebeziumSqlserverEndpointBuilder additionalProperties(Map values) {
doSetMultiValueProperties("additionalProperties", "additionalProperties.", values);
return this;
}
/**
* The Converter | DebeziumSqlserverEndpointBuilder |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/Custom.java | {
"start": 1171,
"end": 5852
} | class ____ {
private Integer id;
private long timestamp1;
private long timestamp2;
private long timestamp3;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) throws InterruptedException {
timestamp1 = System.currentTimeMillis();
Thread.sleep( 100 );
// Revision 1
scope.inTransaction( em -> {
StrTestEntity te = new StrTestEntity( "x" );
em.persist( te );
id = te.getId();
} );
timestamp2 = System.currentTimeMillis();
Thread.sleep( 100 );
// Revision 2
scope.inTransaction( em -> {
StrTestEntity te = em.find( StrTestEntity.class, id );
te.setStr( "y" );
} );
timestamp3 = System.currentTimeMillis();
}
@Test
public void testTimestamps1(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertThrows( RevisionDoesNotExistException.class,
() -> auditReader.getRevisionNumberForDate( new Date( timestamp1 ) ) );
} );
}
@Test
public void testTimestamps(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
final Date date1 = new Date( timestamp2 );
final Date date2 = new Date( timestamp3 );
assertEquals( 1, auditReader.getRevisionNumberForDate( date1 ).intValue() );
assertEquals( 2, auditReader.getRevisionNumberForDate( date2 ).intValue() );
final LocalDateTime localDateTime1 = LocalDateTime.ofInstant( date1.toInstant(), ZoneId.systemDefault() );
final LocalDateTime localDateTime2 = LocalDateTime.ofInstant( date2.toInstant(), ZoneId.systemDefault() );
assertEquals( 1, auditReader.getRevisionNumberForDate( localDateTime1 ).intValue() );
assertEquals( 2, auditReader.getRevisionNumberForDate( localDateTime2 ).intValue() );
} );
}
@Test
public void testDatesForRevisions(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertEquals( 1, auditReader.getRevisionNumberForDate( auditReader.getRevisionDate( 1 ) ).intValue() );
assertEquals( 2, auditReader.getRevisionNumberForDate( auditReader.getRevisionDate( 2 ) ).intValue() );
} );
}
@Test
public void testRevisionsForDates(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertTrue( auditReader.getRevisionDate( auditReader.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2 );
assertTrue( auditReader.getRevisionDate( auditReader.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 )
.getTime() > timestamp2 );
assertTrue( auditReader.getRevisionDate( auditReader.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3 );
} );
}
@Test
public void testFindRevision(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
long rev1Timestamp = auditReader.findRevision( CustomRevEntity.class, 1 ).getCustomTimestamp();
assertTrue( rev1Timestamp > timestamp1 );
assertTrue( rev1Timestamp <= timestamp2 );
long rev2Timestamp = auditReader.findRevision( CustomRevEntity.class, 2 ).getCustomTimestamp();
assertTrue( rev2Timestamp > timestamp2 );
assertTrue( rev2Timestamp <= timestamp3 );
} );
}
@Test
public void testFindRevisions(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
Set<Number> revNumbers = new HashSet<Number>();
revNumbers.add( 1 );
revNumbers.add( 2 );
Map<Number, CustomRevEntity> revisionMap = auditReader.findRevisions( CustomRevEntity.class, revNumbers );
assertEquals( 2, revisionMap.size() );
assertEquals( auditReader.findRevision( CustomRevEntity.class, 1 ), revisionMap.get( 1 ) );
assertEquals( auditReader.findRevision( CustomRevEntity.class, 2 ), revisionMap.get( 2 ) );
} );
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( StrTestEntity.class, id ) );
} );
}
@Test
public void testHistoryOfId1(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
StrTestEntity ver1 = new StrTestEntity( "x", id );
StrTestEntity ver2 = new StrTestEntity( "y", id );
assertEquals( ver1, auditReader.find( StrTestEntity.class, id, 1 ) );
assertEquals( ver2, auditReader.find( StrTestEntity.class, id, 2 ) );
} );
}
}
| Custom |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java | {
"start": 29996,
"end": 40240
} | class ____ extends Timer implements ToXContentFragment, Writeable {
protected final RecoveryFilesDetails fileDetails;
public static final long UNKNOWN = -1L;
private long sourceThrottlingInNanos = UNKNOWN;
private long targetThrottleTimeInNanos = UNKNOWN;
public Index() {
this(new RecoveryFilesDetails());
}
public Index(RecoveryFilesDetails recoveryFilesDetails) {
this.fileDetails = recoveryFilesDetails;
}
public Index(StreamInput in) throws IOException {
super(in);
fileDetails = new RecoveryFilesDetails(in);
sourceThrottlingInNanos = in.readLong();
targetThrottleTimeInNanos = in.readLong();
}
@Override
public synchronized void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
fileDetails.writeTo(out);
out.writeLong(sourceThrottlingInNanos);
out.writeLong(targetThrottleTimeInNanos);
}
public synchronized List<FileDetail> fileDetails() {
return List.copyOf(fileDetails.values());
}
public synchronized void reset() {
super.reset();
fileDetails.clear();
sourceThrottlingInNanos = UNKNOWN;
targetThrottleTimeInNanos = UNKNOWN;
}
public synchronized void addFileDetail(String name, long length, boolean reused) {
fileDetails.addFileDetails(name, length, reused);
}
public synchronized void setFileDetailsComplete() {
fileDetails.setComplete();
}
public synchronized void addRecoveredBytesToFile(String name, long bytes) {
fileDetails.addRecoveredBytesToFile(name, bytes);
}
public synchronized void resetRecoveredBytesOfFile(String name) {
fileDetails.resetRecoveredBytesOfFile(name);
}
public synchronized void addRecoveredFromSnapshotBytesToFile(String name, long bytes) {
fileDetails.addRecoveredFromSnapshotBytesToFile(name, bytes);
}
public synchronized void addSourceThrottling(long timeInNanos) {
if (sourceThrottlingInNanos == UNKNOWN) {
sourceThrottlingInNanos = timeInNanos;
} else {
sourceThrottlingInNanos += timeInNanos;
}
}
public synchronized void addTargetThrottling(long timeInNanos) {
if (targetThrottleTimeInNanos == UNKNOWN) {
targetThrottleTimeInNanos = timeInNanos;
} else {
targetThrottleTimeInNanos += timeInNanos;
}
}
public synchronized TimeValue sourceThrottling() {
return TimeValue.timeValueNanos(sourceThrottlingInNanos);
}
public synchronized TimeValue targetThrottling() {
return TimeValue.timeValueNanos(targetThrottleTimeInNanos);
}
/**
* total number of files that are part of this recovery, both re-used and recovered
*/
public synchronized int totalFileCount() {
return fileDetails.size();
}
/**
* total number of files to be recovered (potentially not yet done)
*/
public synchronized int totalRecoverFiles() {
int total = 0;
for (FileDetail file : fileDetails.values()) {
if (file.reused() == false) {
total++;
}
}
return total;
}
/**
* number of file that were recovered (excluding on ongoing files)
*/
public synchronized int recoveredFileCount() {
int count = 0;
for (FileDetail file : fileDetails.values()) {
if (file.fullyRecovered()) {
count++;
}
}
return count;
}
/**
* percent of recovered (i.e., not reused) files out of the total files to be recovered
*/
public synchronized float recoveredFilesPercent() {
int total = 0;
int recovered = 0;
for (FileDetail file : fileDetails.values()) {
if (file.reused() == false) {
total++;
if (file.fullyRecovered()) {
recovered++;
}
}
}
if (total == 0 && fileDetails.size() == 0) { // indicates we are still in init phase
return 0.0f;
}
if (total == recovered) {
return 100.0f;
} else {
return 100.0f * (recovered / (float) total);
}
}
/**
* total number of bytes in th shard
*/
public synchronized long totalBytes() {
long total = 0;
for (FileDetail file : fileDetails.values()) {
total += file.length();
}
return total;
}
/**
* total number of bytes recovered so far, including both existing and reused
*/
public synchronized long recoveredBytes() {
long recovered = 0;
for (FileDetail file : fileDetails.values()) {
recovered += file.recovered();
}
return recovered;
}
public synchronized long recoveredFromSnapshotBytes() {
long recoveredFromSnapshot = 0;
for (FileDetail fileDetail : fileDetails.values()) {
recoveredFromSnapshot += fileDetail.recoveredFromSnapshot();
}
return recoveredFromSnapshot;
}
/**
* total bytes of files to be recovered (potentially not yet done)
*/
public synchronized long totalRecoverBytes() {
long total = 0;
for (FileDetail file : fileDetails.values()) {
if (file.reused() == false) {
total += file.length();
}
}
return total;
}
/**
* @return number of bytes still to recover, i.e. {@link Index#totalRecoverBytes()} minus {@link Index#recoveredBytes()}, or
* {@code -1} if the full set of files to recover is not yet known
*/
public synchronized long bytesStillToRecover() {
if (fileDetails.isComplete() == false) {
return -1L;
}
long total = 0L;
for (FileDetail file : fileDetails.values()) {
if (file.reused() == false) {
total += file.length() - file.recovered();
}
}
return total;
}
/**
* percent of bytes recovered out of total files bytes *to be* recovered
*/
public synchronized float recoveredBytesPercent() {
long total = 0;
long recovered = 0;
for (FileDetail file : fileDetails.values()) {
if (file.reused() == false) {
total += file.length();
recovered += file.recovered();
}
}
if (total == 0 && fileDetails.size() == 0) {
// indicates we are still in init phase
return 0.0f;
}
if (total == recovered) {
return 100.0f;
} else {
return 100.0f * recovered / total;
}
}
public synchronized int reusedFileCount() {
int reused = 0;
for (FileDetail file : fileDetails.values()) {
if (file.reused()) {
reused++;
}
}
return reused;
}
public synchronized long reusedBytes() {
long reused = 0;
for (FileDetail file : fileDetails.values()) {
if (file.reused()) {
reused += file.length();
}
}
return reused;
}
@Override
public synchronized XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// stream size first, as it matters more and the files section can be long
builder.startObject(Fields.SIZE);
builder.humanReadableField(Fields.TOTAL_IN_BYTES, Fields.TOTAL, ByteSizeValue.ofBytes(totalBytes()));
builder.humanReadableField(Fields.REUSED_IN_BYTES, Fields.REUSED, ByteSizeValue.ofBytes(reusedBytes()));
builder.humanReadableField(Fields.RECOVERED_IN_BYTES, Fields.RECOVERED, ByteSizeValue.ofBytes(recoveredBytes()));
builder.humanReadableField(
Fields.RECOVERED_FROM_SNAPSHOT_IN_BYTES,
Fields.RECOVERED_FROM_SNAPSHOT,
ByteSizeValue.ofBytes(recoveredFromSnapshotBytes())
);
builder.field(Fields.PERCENT, String.format(Locale.ROOT, "%1.1f%%", recoveredBytesPercent()));
builder.endObject();
builder.startObject(Fields.FILES);
builder.field(Fields.TOTAL, totalFileCount());
builder.field(Fields.REUSED, reusedFileCount());
builder.field(Fields.RECOVERED, recoveredFileCount());
builder.field(Fields.PERCENT, String.format(Locale.ROOT, "%1.1f%%", recoveredFilesPercent()));
fileDetails.toXContent(builder, params);
builder.endObject();
builder.humanReadableField(Fields.TOTAL_TIME_IN_MILLIS, Fields.TOTAL_TIME, new TimeValue(time()));
builder.humanReadableField(Fields.SOURCE_THROTTLE_TIME_IN_MILLIS, Fields.SOURCE_THROTTLE_TIME, sourceThrottling());
builder.humanReadableField(Fields.TARGET_THROTTLE_TIME_IN_MILLIS, Fields.TARGET_THROTTLE_TIME, targetThrottling());
return builder;
}
@Override
public synchronized String toString() {
return Strings.toString(this);
}
public synchronized FileDetail getFileDetails(String dest) {
return fileDetails.get(dest);
}
}
}
| Index |
java | elastic__elasticsearch | client/sniffer/src/test/java/org/elasticsearch/client/sniff/documentation/SnifferDocumentation.java | {
"start": 1300,
"end": 1856
} | class ____ used to generate the Java low-level REST client documentation.
* You need to wrap your code between two tags like:
* // tag::example[]
* // end::example[]
*
* Where example is your tag name.
*
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/SnifferDocumentation.java[example]
* --------------------------------------------------
*
* Note that this is not a test | is |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/annotation/ProcedureHint.java | {
"start": 1726,
"end": 2446
} | class ____ inherited by all {@code call()}
* methods. The {@link DataTypeHint} for the output data type should always hint the component type
* of the array returned by {@link Procedure}.
*
* <p>The following examples show how to explicitly specify procedure signatures as a whole or in
* part and let the default extraction do the rest:
*
* <pre>{@code
* // accepts (INT, STRING) and returns BOOLEAN,
* // the arguments have names and are optional
* @ProcedureHint(
* arguments = {
* @ArgumentHint(type = @DataTypeHint("INT"), name = "in1", isOptional = true),
* @ArgumentHint(type = @DataTypeHint("STRING"), name = "in2", isOptional = true)
* },
* output = @DataTypeHint("BOOLEAN")
* )
* | are |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByValidatorTest.java | {
"start": 6737,
"end": 7276
} | class ____ {
@GuardedBy("this")
// BUG: Diagnostic contains:
// Invalid @GuardedBy expression: static member guarded by instance
static int x;
}
""")
.doTest();
}
@Test
public void staticGuardedByInstanceMethod() {
compilationHelper
.addSourceLines(
"threadsafety/Test.java",
"""
package threadsafety.Test;
import com.google.errorprone.annotations.concurrent.GuardedBy;
| Test |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ForeignKeyDescriptor.java | {
"start": 5030,
"end": 5137
} | enum ____ {
KEY,
TARGET;
public Nature inverse() {
return this == KEY ? TARGET : KEY;
}
}
| Nature |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestProtosLegacy.java | {
"start": 14857,
"end": 23632
} | class ____ extends
com.google.protobuf.GeneratedMessage
implements EmptyResponseProtoOrBuilder {
// Use EmptyResponseProto.newBuilder() to construct.
private EmptyResponseProto(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private EmptyResponseProto(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final EmptyResponseProto defaultInstance;
public static EmptyResponseProto getDefaultInstance() {
return defaultInstance;
}
public EmptyResponseProto getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private EmptyResponseProto(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_EmptyResponseProto_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_EmptyResponseProto_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.class, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.Builder.class);
}
public static com.google.protobuf.Parser<EmptyResponseProto> PARSER =
new com.google.protobuf.AbstractParser<EmptyResponseProto>() {
public EmptyResponseProto parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new EmptyResponseProto(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<EmptyResponseProto> getParserForType() {
return PARSER;
}
private void initFields() {
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto)) {
return super.equals(obj);
}
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto other = (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto) obj;
boolean result = true;
result = result &&
getUnknownFields().equals(other.getUnknownFields());
return result;
}
private int memoizedHashCode = 0;
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code hadoop.common.EmptyResponseProto}
*/
public static final | EmptyResponseProto |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/PreExceptionMapperHandlerTest.java | {
"start": 3092,
"end": 3436
} | class ____ implements ServerRestHandler {
@Override
public void handle(ResteasyReactiveRequestContext requestContext) throws Exception {
assertThat(requestContext.getThrowable()).isInstanceOf(RuntimeException.class);
requestContext.setProperty("foo", "bar");
}
}
}
| DummyPreExceptionMapperHandler |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/springapplication/applicationavailability/managing/MyReadinessStateExporter.java | {
"start": 981,
"end": 1282
} | class ____ {
@EventListener
public void onStateChange(AvailabilityChangeEvent<ReadinessState> event) {
switch (event.getState()) {
case ACCEPTING_TRAFFIC -> {
// create file /tmp/healthy
}
case REFUSING_TRAFFIC -> {
// remove file /tmp/healthy
}
}
}
}
| MyReadinessStateExporter |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppender2Test.java | {
"start": 1360,
"end": 2378
} | class ____ {
private static final String CONFIG = "log4j-routing2.json";
private static final String LOG_FILENAME = "target/rolling1/rollingtest-Unknown.log";
private final LoggerContextRule loggerContextRule = new LoggerContextRule(CONFIG);
@Rule
public RuleChain rules = loggerContextRule.withCleanFilesRule(LOG_FILENAME);
@Test
public void routingTest() {
StructuredDataMessage msg = new StructuredDataMessage("Test", "This is a test", "Service");
EventLogger.logEvent(msg);
final List<LogEvent> list = loggerContextRule.getListAppender("List").getEvents();
assertNotNull("No events generated", list);
assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size());
msg = new StructuredDataMessage("Test", "This is a test", "Unknown");
EventLogger.logEvent(msg);
final File file = new File(LOG_FILENAME);
assertTrue("File was not created", file.exists());
}
}
| JsonRoutingAppender2Test |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java | {
"start": 9316,
"end": 9477
} | class ____ {
}
@ActiveProfiles(profiles = "default", resolver = ExtendedDefaultActiveProfilesResolver.class)
private static | DefaultActiveProfilesResolverTestCase |
java | spring-projects__spring-boot | module/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java | {
"start": 47976,
"end": 48256
} | class ____ extends AbstractUserH2DataSourceConfiguration {
private final String name = UUID.randomUUID().toString();
@Override
protected String getDatabaseName(DataSourceProperties properties) {
return this.name;
}
}
static final | CustomBackedH2DataSourceConfiguration |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/metadata/FlinkMetadata.java | {
"start": 8953,
"end": 9399
} | interface ____ extends Metadata {
Method METHOD =
Types.lookupMethod(ModifiedMonotonicity.class, "getRelModifiedMonotonicity");
MetadataDef<ModifiedMonotonicity> DEF =
MetadataDef.of(
ModifiedMonotonicity.class, ModifiedMonotonicity.Handler.class, METHOD);
RelModifiedMonotonicity getRelModifiedMonotonicity();
/** Handler API. */
| ModifiedMonotonicity |
java | alibaba__nacos | client/src/main/java/com/alibaba/nacos/client/ai/NacosAiService.java | {
"start": 2753,
"end": 15777
} | class ____ implements AiService {
private static final Logger LOGGER = LogUtils.logger(NacosAiService.class);
private final String namespaceId;
private final AiGrpcClient grpcClient;
private final NacosMcpServerCacheHolder mcpServerCacheHolder;
private final NacosAgentCardCacheHolder agentCardCacheHolder;
private final AiChangeNotifier aiChangeNotifier;
public NacosAiService(Properties properties) throws NacosException {
NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
LOGGER.info(ClientBasicParamUtil.getInputParameters(clientProperties.asProperties()));
this.namespaceId = initNamespace(clientProperties);
this.grpcClient = new AiGrpcClient(namespaceId, clientProperties);
this.mcpServerCacheHolder = new NacosMcpServerCacheHolder(grpcClient, clientProperties);
this.agentCardCacheHolder = new NacosAgentCardCacheHolder(grpcClient, clientProperties);
this.aiChangeNotifier = new AiChangeNotifier();
start();
}
private String initNamespace(NacosClientProperties properties) {
String tempNamespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
if (StringUtils.isBlank(tempNamespace)) {
return Constants.DEFAULT_NAMESPACE_ID;
}
return tempNamespace;
}
private void start() throws NacosException {
this.grpcClient.start(this.mcpServerCacheHolder, this.agentCardCacheHolder);
NotifyCenter.registerToPublisher(McpServerChangedEvent.class, 16384);
NotifyCenter.registerSubscriber(this.aiChangeNotifier);
}
@Override
public McpServerDetailInfo getMcpServer(String mcpName, String version) throws NacosException {
if (StringUtils.isBlank(mcpName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"Required parameter `mcpName` not present");
}
return grpcClient.queryMcpServer(mcpName, version);
}
@Override
public String releaseMcpServer(McpServerBasicInfo serverSpecification, McpToolSpecification toolSpecification,
McpEndpointSpec endpointSpecification) throws NacosException {
if (null == serverSpecification) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"Required parameter `serverSpecification` not present");
}
if (StringUtils.isBlank(serverSpecification.getName())) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"Required parameter `serverSpecification.name` not present");
}
if (null == serverSpecification.getVersionDetail() || StringUtils.isBlank(
serverSpecification.getVersionDetail().getVersion())) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"Required parameter `serverSpecification.versionDetail.version` not present");
}
return grpcClient.releaseMcpServer(serverSpecification, toolSpecification, endpointSpecification);
}
@Override
public void registerMcpServerEndpoint(String mcpName, String address, int port, String version)
throws NacosException {
if (StringUtils.isBlank(mcpName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `mcpName` can't be empty or null");
}
Instance instance = new Instance();
instance.setIp(address);
instance.setPort(port);
instance.validate();
grpcClient.registerMcpServerEndpoint(mcpName, address, port, version);
}
@Override
public void deregisterMcpServerEndpoint(String mcpName, String address, int port) throws NacosException {
if (StringUtils.isBlank(mcpName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `mcpName` can't be empty or null");
}
Instance instance = new Instance();
instance.setIp(address);
instance.setPort(port);
instance.validate();
grpcClient.deregisterMcpServerEndpoint(mcpName, address, port);
}
@Override
public McpServerDetailInfo subscribeMcpServer(String mcpName, String version,
AbstractNacosMcpServerListener mcpServerListener) throws NacosException {
if (StringUtils.isBlank(mcpName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `mcpName` can't be empty or null");
}
if (null == mcpServerListener) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `mcpServerListener` can't be empty or null");
}
McpServerListenerInvoker listenerInvoker = new McpServerListenerInvoker(mcpServerListener);
aiChangeNotifier.registerListener(mcpName, version, listenerInvoker);
McpServerDetailInfo result = grpcClient.subscribeMcpServer(mcpName, version);
if (null != result && !listenerInvoker.isInvoked()) {
listenerInvoker.invoke(new NacosMcpServerEvent(result));
}
return result;
}
@Override
public void unsubscribeMcpServer(String mcpName, String version, AbstractNacosMcpServerListener mcpServerListener)
throws NacosException {
if (StringUtils.isBlank(mcpName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `mcpName` can't be empty or null");
}
if (null == mcpServerListener) {
return;
}
McpServerListenerInvoker listenerInvoker = new McpServerListenerInvoker(mcpServerListener);
aiChangeNotifier.deregisterListener(mcpName, version, listenerInvoker);
if (!aiChangeNotifier.isMcpServerSubscribed(mcpName, version)) {
grpcClient.unsubscribeMcpServer(mcpName, version);
}
}
@Override
public AgentCardDetailInfo getAgentCard(String agentName, String version, String registrationType)
throws NacosException {
if (StringUtils.isBlank(agentName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentName` can't be empty or null");
}
return grpcClient.getAgentCard(agentName, version, registrationType);
}
@Override
public void releaseAgentCard(AgentCard agentCard, String registrationType, boolean setAsLatest)
throws NacosException {
if (null == agentCard) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentCard` can't be null");
}
validateAgentCardField("name", agentCard.getName());
validateAgentCardField("version", agentCard.getVersion());
validateAgentCardField("protocolVersion", agentCard.getProtocolVersion());
if (StringUtils.isBlank(registrationType)) {
registrationType = AiConstants.A2a.A2A_ENDPOINT_TYPE_SERVICE;
}
grpcClient.releaseAgentCard(agentCard, registrationType, setAsLatest);
}
@Override
public void registerAgentEndpoint(String agentName, AgentEndpoint endpoint) throws NacosException {
if (StringUtils.isBlank(agentName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentName` can't be empty or null");
}
validateAgentEndpoint(endpoint);
grpcClient.registerAgentEndpoint(agentName, endpoint);
}
@Override
public void registerAgentEndpoint(String agentName, Collection<AgentEndpoint> endpoints) throws NacosException {
if (StringUtils.isBlank(agentName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentName` can't be empty or null");
}
validateAgentEndpoint(endpoints);
grpcClient.registerAgentEndpoints(agentName, endpoints);
}
@Override
public void deregisterAgentEndpoint(String agentName, AgentEndpoint endpoint) throws NacosException {
if (StringUtils.isBlank(agentName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentName` can't be empty or null");
}
validateAgentEndpoint(endpoint);
grpcClient.deregisterAgentEndpoint(agentName, endpoint);
}
@Override
public AgentCardDetailInfo subscribeAgentCard(String agentName, String version,
AbstractNacosAgentCardListener agentCardListener) throws NacosException {
if (StringUtils.isBlank(agentName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentName` can't be empty or null");
}
if (null == agentCardListener) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentCardListener` can't be empty or null");
}
AgentCardListenerInvoker listenerInvoker = new AgentCardListenerInvoker(agentCardListener);
aiChangeNotifier.registerListener(agentName, version, listenerInvoker);
AgentCardDetailInfo result = grpcClient.subscribeAgentCard(agentName, version);
if (null != result && !listenerInvoker.isInvoked()) {
listenerInvoker.invoke(new NacosAgentCardEvent(result));
}
return result;
}
@Override
public void unsubscribeAgentCard(String agentName, String version, AbstractNacosAgentCardListener agentCardListener)
throws NacosException {
if (StringUtils.isBlank(agentName)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `agentName` can't be empty or null");
}
if (null == agentCardListener) {
return;
}
AgentCardListenerInvoker listenerInvoker = new AgentCardListenerInvoker(agentCardListener);
aiChangeNotifier.deregisterListener(agentName, version, listenerInvoker);
if (!aiChangeNotifier.isAgentCardSubscribed(agentName, version)) {
grpcClient.unsubscribeAgentCard(agentName, version);
}
}
private void validateAgentEndpoint(Collection<AgentEndpoint> endpoints) throws NacosApiException {
if (null == endpoints || endpoints.isEmpty()) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `endpoints` can't be empty or null, if want to deregister endpoints, please use deregister API.");
}
Set<String> versions = new HashSet<>();
for (AgentEndpoint endpoint : endpoints) {
validateAgentEndpoint(endpoint);
versions.add(endpoint.getVersion());
}
if (versions.size() > 1) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_VALIDATE_ERROR,
String.format("Required parameter `endpoint.version` can't be different, current includes: %s.",
String.join(",", versions)));
}
}
private void validateAgentEndpoint(AgentEndpoint endpoint) throws NacosApiException {
if (null == endpoint) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"parameters `endpoint` can't be null");
}
if (StringUtils.isBlank(endpoint.getVersion())) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"Required parameter `endpoint.version` can't be empty or null");
}
Instance instance = new Instance();
instance.setIp(endpoint.getAddress());
instance.setPort(endpoint.getPort());
instance.validate();
}
private static void validateAgentCardField(String fieldName, String fieldValue) throws NacosApiException {
if (StringUtils.isEmpty(fieldValue)) {
throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.PARAMETER_MISSING,
"Required parameter `agentCard." + fieldName + "` not present");
}
}
@Override
public void shutdown() throws NacosException {
this.grpcClient.shutdown();
this.mcpServerCacheHolder.shutdown();
}
}
| NacosAiService |
java | apache__flink | flink-core-api/src/main/java/org/apache/flink/api/java/tuple/builder/Tuple6Builder.java | {
"start": 1525,
"end": 1988
} | class ____<T0, T1, T2, T3, T4, T5> {
private List<Tuple6<T0, T1, T2, T3, T4, T5>> tuples = new ArrayList<>();
public Tuple6Builder<T0, T1, T2, T3, T4, T5> add(T0 f0, T1 f1, T2 f2, T3 f3, T4 f4, T5 f5) {
tuples.add(new Tuple6<>(f0, f1, f2, f3, f4, f5));
return this;
}
@SuppressWarnings("unchecked")
public Tuple6<T0, T1, T2, T3, T4, T5>[] build() {
return tuples.toArray(new Tuple6[tuples.size()]);
}
}
| Tuple6Builder |
java | quarkusio__quarkus | extensions/infinispan-client/deployment/src/main/java/io/quarkus/infinispan/client/deployment/MarshallingBuildItem.java | {
"start": 164,
"end": 773
} | class ____ extends SimpleBuildItem {
// holds protostream requirements
private final Properties properties;
// a marshaller can be defined for different client names
private Map<String, Object> marshallers;
public MarshallingBuildItem(Properties properties, Map<String, Object> marshallers) {
this.properties = properties;
this.marshallers = marshallers;
}
public Object getMarshallerForClientName(String clientName) {
return marshallers.get(clientName);
}
public Properties getProperties() {
return properties;
}
}
| MarshallingBuildItem |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_330.java | {
"start": 833,
"end": 1408
} | class ____<T> {
private int code;
private String msg;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public static | StatusBean |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/HeapAggregatingState.java | {
"start": 1770,
"end": 4609
} | class ____<K, N, IN, ACC, OUT> extends AbstractHeapMergingState<K, N, IN, ACC, OUT>
implements InternalAggregatingState<K, N, IN, ACC, OUT> {
private AggregateTransformation<IN, ACC, OUT> aggregateTransformation;
/**
* Creates a new key/value state for the given hash map of key/value pairs.
*
* @param stateTable The state table for which this state is associated to.
* @param keySerializer The serializer for the keys.
* @param valueSerializer The serializer for the state.
* @param namespaceSerializer The serializer for the namespace.
* @param defaultValue The default value for the state.
* @param aggregateFunction The aggregating function used for aggregating state.
*/
private HeapAggregatingState(
StateTable<K, N, ACC> stateTable,
TypeSerializer<K> keySerializer,
TypeSerializer<ACC> valueSerializer,
TypeSerializer<N> namespaceSerializer,
ACC defaultValue,
AggregateFunction<IN, ACC, OUT> aggregateFunction) {
super(stateTable, keySerializer, valueSerializer, namespaceSerializer, defaultValue);
this.aggregateTransformation = new AggregateTransformation<>(aggregateFunction);
}
@Override
public TypeSerializer<K> getKeySerializer() {
return keySerializer;
}
@Override
public TypeSerializer<N> getNamespaceSerializer() {
return namespaceSerializer;
}
@Override
public TypeSerializer<ACC> getValueSerializer() {
return valueSerializer;
}
// ------------------------------------------------------------------------
// state access
// ------------------------------------------------------------------------
@Override
public OUT get() {
ACC accumulator = getInternal();
return accumulator != null
? aggregateTransformation.aggFunction.getResult(accumulator)
: null;
}
@Override
public void add(IN value) throws Exception {
final N namespace = currentNamespace;
if (value == null) {
clear();
return;
}
stateTable.transform(namespace, value, aggregateTransformation);
}
// ------------------------------------------------------------------------
// state merging
// ------------------------------------------------------------------------
@Override
protected ACC mergeState(ACC a, ACC b) {
return aggregateTransformation.aggFunction.merge(a, b);
}
HeapAggregatingState<K, N, IN, ACC, OUT> setAggregateFunction(
AggregateFunction<IN, ACC, OUT> aggregateFunction) {
this.aggregateTransformation = new AggregateTransformation<>(aggregateFunction);
return this;
}
static final | HeapAggregatingState |
java | quarkusio__quarkus | extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/ConcurrentExecutionSkipTest.java | {
"start": 775,
"end": 1912
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Jobs.class));
@Test
public void testExecution() {
try {
// Wait until Jobs#nonconcurrent() is executed 1x and skipped 1x
if (Jobs.SKIPPED_LATCH.await(10, TimeUnit.SECONDS)) {
// Exactly one job is blocked
assertEquals(1, Jobs.COUNTER.get());
// Skipped Execution does not fire SuccessfulExecution event
assertEquals(0, Jobs.SUCCESS_COUNTER.get());
// Unblock all executions
Jobs.BLOCKING_LATCH.countDown();
} else {
fail("Jobs were not executed in 10 seconds!");
}
assertTrue(Jobs.FAILED_LATCH.await(5, TimeUnit.SECONDS));
assertTrue(Jobs.FAILURE_COUNTER.get() > 0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
static | ConcurrentExecutionSkipTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/references/samename/a/CustomMapper.java | {
"start": 209,
"end": 318
} | class ____ {
public String intToString(int i) {
return String.valueOf( i * 2 );
}
}
| CustomMapper |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/model/SetVariablesDefinitionTest.java | {
"start": 1114,
"end": 3164
} | class ____ extends TestSupport {
@Test
void testSetFromMap() {
Map<String, Expression> map = new java.util.LinkedHashMap<>(3);
map.put("fromBody", body());
map.put("isCamel", ExpressionNodeHelper.toExpressionDefinition(body().contains("Camel")));
map.put("isHorse", ExpressionNodeHelper.toExpressionDefinition(body().contains("Horse")));
SetVariablesDefinition def = new SetVariablesDefinition(map);
assertNotNull(def.getVariables());
assertEquals(3, def.getVariables().size());
assertEquals("isCamel", def.getVariables().get(1).getName());
}
@Test
void testSetFromMapOf() {
SetVariablesDefinition def = new SetVariablesDefinition(
Map.of("fromBody", body(),
"isCamel", body().contains("Camel"), "isHorse", body().contains("Horse")));
assertNotNull(def.getVariables());
assertEquals(3, def.getVariables().size());
Set<String> names = new java.util.HashSet<>();
for (SetVariableDefinition varDef : def.getVariables()) {
names.add(varDef.getName());
}
assertEquals(names, Set.of("fromBody", "isCamel", "isHorse"));
}
@Test
void testSetFromVarargs() {
SetVariablesDefinition def = new SetVariablesDefinition(
"fromBody", body(),
"isCamel", ExpressionNodeHelper.toExpressionDefinition(body().contains("Camel")),
"isHorse", ExpressionNodeHelper.toExpressionDefinition(body().contains("Camel")));
assertNotNull(def.getVariables());
assertEquals(3, def.getVariables().size());
assertEquals("isCamel", def.getVariables().get(1).getName());
}
@Test
void testSetFromOnePair() {
SetVariablesDefinition def = new SetVariablesDefinition("fromBody", body());
assertNotNull(def.getVariables());
assertEquals(1, def.getVariables().size());
assertEquals("fromBody", def.getVariables().get(0).getName());
}
}
| SetVariablesDefinitionTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestFileOutputCommitter.java | {
"start": 20259,
"end": 20413
} | class ____ a overrided implementation of commitJobInternal which
* causes the commit failed for the first time then succeed.
*/
public static | provides |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/CompositeIdFkGeneratedValueTest.java | {
"start": 9591,
"end": 9780
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long hid;
private String name;
}
@Entity(name = "NodeS")
@IdClass(NodeS.PK.class)
public static | HeadS |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstancePreConstructCallbackTests.java | {
"start": 1452,
"end": 7836
} | class ____ extends AbstractJupiterTestEngineTests {
private static final List<String> callSequence = new ArrayList<>();
@BeforeEach
void resetCallSequence() {
callSequence.clear();
}
@Test
void instancePreConstruct() {
executeTestsForClass(InstancePreConstructTestCase.class).testEvents()//
.assertStatistics(stats -> stats.started(2).succeeded(2));
// @formatter:off
assertThat(callSequence).containsExactly(
"beforeAll",
"PreConstructCallback: name=foo, testClass=InstancePreConstructTestCase, outerInstance: null",
"constructor",
"beforeEach",
"test1",
"afterEach",
"close: name=foo, testClass=InstancePreConstructTestCase",
"PreConstructCallback: name=foo, testClass=InstancePreConstructTestCase, outerInstance: null",
"constructor",
"beforeEach",
"test2",
"afterEach",
"close: name=foo, testClass=InstancePreConstructTestCase",
"afterAll"
);
// @formatter:on
}
@Test
void factoryPreConstruct() {
executeTestsForClass(FactoryPreConstructTestCase.class).testEvents()//
.assertStatistics(stats -> stats.started(2).succeeded(2));
// @formatter:off
assertThat(callSequence).containsExactly(
"beforeAll",
"PreConstructCallback: name=foo, testClass=FactoryPreConstructTestCase, outerInstance: null",
"testInstanceFactory",
"constructor",
"beforeEach",
"test1",
"afterEach",
"close: name=foo, testClass=FactoryPreConstructTestCase",
"PreConstructCallback: name=foo, testClass=FactoryPreConstructTestCase, outerInstance: null",
"testInstanceFactory",
"constructor",
"beforeEach",
"test2",
"afterEach",
"close: name=foo, testClass=FactoryPreConstructTestCase",
"afterAll"
);
// @formatter:on
}
@Test
void preConstructInNested() {
executeTestsForClass(PreConstructInNestedTestCase.class).testEvents()//
.assertStatistics(stats -> stats.started(3).succeeded(3));
// @formatter:off
assertThat(callSequence).containsExactly(
"beforeAll",
"PreConstructCallback: name=foo, testClass=PreConstructInNestedTestCase, outerInstance: null",
"constructor",
"beforeEach",
"outerTest1",
"afterEach",
"close: name=foo, testClass=PreConstructInNestedTestCase",
"PreConstructCallback: name=foo, testClass=PreConstructInNestedTestCase, outerInstance: null",
"constructor",
"beforeEach",
"outerTest2",
"afterEach",
"close: name=foo, testClass=PreConstructInNestedTestCase",
"PreConstructCallback: name=foo, testClass=PreConstructInNestedTestCase, outerInstance: null",
"constructor",
"PreConstructCallback: name=foo, testClass=InnerTestCase, outerInstance: #3",
"PreConstructCallback: name=bar, testClass=InnerTestCase, outerInstance: #3",
"PreConstructCallback: name=baz, testClass=InnerTestCase, outerInstance: #3",
"constructorInner",
"beforeEach",
"beforeEachInner",
"innerTest1",
"afterEachInner",
"afterEach",
"close: name=baz, testClass=InnerTestCase",
"close: name=bar, testClass=InnerTestCase",
"close: name=foo, testClass=InnerTestCase",
"close: name=foo, testClass=PreConstructInNestedTestCase",
"afterAll"
);
// @formatter:on
}
@Test
void preConstructOnMethod() {
executeTestsForClass(PreConstructOnMethod.class).testEvents()//
.assertStatistics(stats -> stats.started(2).succeeded(2));
// @formatter:off
assertThat(callSequence).containsExactly(
"PreConstructCallback: name=foo, testClass=PreConstructOnMethod, outerInstance: null",
"constructor",
"beforeEach",
"test1",
"afterEach",
"close: name=foo, testClass=PreConstructOnMethod",
"constructor",
"beforeEach",
"test2",
"afterEach"
);
// @formatter:on
}
@Test
void preConstructWithClassLifecycle() {
executeTestsForClass(PreConstructWithClassLifecycle.class).testEvents()//
.assertStatistics(stats -> stats.started(2).succeeded(2));
// @formatter:off
assertThat(callSequence).containsExactly(
"PreConstructCallback: name=foo, testClass=PreConstructWithClassLifecycle, outerInstance: null",
"PreConstructCallback: name=bar, testClass=PreConstructWithClassLifecycle, outerInstance: null",
"constructor",
"beforeEach",
"test1",
"beforeEach",
"test2",
"close: name=bar, testClass=PreConstructWithClassLifecycle",
"close: name=foo, testClass=PreConstructWithClassLifecycle"
);
// @formatter:on
}
@Test
void legacyPreConstruct() {
executeTestsForClass(LegacyPreConstructTestCase.class).testEvents()//
.assertStatistics(stats -> stats.started(3).succeeded(3));
// @formatter:off
assertThat(callSequence).containsExactly(
"beforeAll",
"PreConstructCallback: name=foo, testClass=LegacyPreConstructTestCase, outerInstance: null",
"PreConstructCallback: name=legacy, testClass=LegacyPreConstructTestCase, outerInstance: null",
"constructor",
"beforeEach",
"outerTest1",
"afterEach",
"close: name=foo, testClass=LegacyPreConstructTestCase",
"PreConstructCallback: name=foo, testClass=LegacyPreConstructTestCase, outerInstance: null",
"PreConstructCallback: name=legacy, testClass=LegacyPreConstructTestCase, outerInstance: null",
"constructor",
"beforeEach",
"outerTest2",
"afterEach",
"close: name=foo, testClass=LegacyPreConstructTestCase",
"PreConstructCallback: name=foo, testClass=LegacyPreConstructTestCase, outerInstance: null",
"PreConstructCallback: name=legacy, testClass=LegacyPreConstructTestCase, outerInstance: null",
"constructor",
"PreConstructCallback: name=foo, testClass=InnerTestCase, outerInstance: LegacyPreConstructTestCase",
"PreConstructCallback: name=legacy, testClass=InnerTestCase, outerInstance: LegacyPreConstructTestCase",
"constructorInner",
"beforeEach",
"beforeEachInner",
"innerTest1",
"afterEachInner",
"afterEach",
"close: name=foo, testClass=InnerTestCase",
"close: name=foo, testClass=LegacyPreConstructTestCase",
"close: name=legacy, testClass=InnerTestCase",
"afterAll",
"close: name=legacy, testClass=LegacyPreConstructTestCase",
"close: name=legacy, testClass=LegacyPreConstructTestCase",
"close: name=legacy, testClass=LegacyPreConstructTestCase"
);
// @formatter:on
}
private abstract static | TestInstancePreConstructCallbackTests |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-common/spi-deployment/src/main/java/io/quarkus/resteasy/reactive/spi/CustomExceptionMapperBuildItem.java | {
"start": 241,
"end": 515
} | class ____ extends MultiBuildItem {
private final String className;
public CustomExceptionMapperBuildItem(String className) {
this.className = className;
}
public String getClassName() {
return className;
}
}
| CustomExceptionMapperBuildItem |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLShowTableGroupsStatement.java | {
"start": 906,
"end": 1657
} | class ____ extends SQLStatementImpl implements SQLShowStatement, SQLReplaceable {
protected SQLName database;
public SQLName getDatabase() {
return database;
}
public void setDatabase(SQLName database) {
if (database != null) {
database.setParent(this);
}
this.database = database;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, database);
}
}
@Override
public boolean replace(SQLExpr expr, SQLExpr target) {
if (database == expr) {
setDatabase((SQLName) target);
return true;
}
return false;
}
}
| SQLShowTableGroupsStatement |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/security/FormAuthNoRedirectAfterLoginTestCase.java | {
"start": 807,
"end": 5628
} | class ____ {
private static final String APP_PROPS = "" +
"quarkus.http.auth.form.enabled=true\n" +
"quarkus.http.auth.form.login-page=login\n" +
"quarkus.http.auth.form.error-page=error\n" +
"quarkus.http.auth.form.landing-page=landing\n" +
"quarkus.http.auth.form.redirect-after-login=false\n" +
"quarkus.http.auth.policy.r1.roles-allowed=a d m i n\n" +
"quarkus.http.auth.permission.roles1.paths=/admin\n" +
"quarkus.http.auth.permission.roles1.policy=r1\n";
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(TestIdentityProvider.class, TestIdentityController.class, TestTrustedIdentityProvider.class,
PathHandler.class)
.addAsResource(new StringAsset(APP_PROPS), "application.properties");
}
});
@BeforeAll
public static void setup() {
TestIdentityController.resetRoles()
.add("a d m i n", "a d m i n", "a d m i n");
}
/**
* First, protected /admin resource is accessed. No quarkus-credential cookie
* is presented by the client, so server should redirect to /login page.
*
* Next, let's assume there was a login form on the /login page,
* we do POST with valid credentials.
* Server should provide a response with quarkus-credential cookie
* and a redirect to the previously attempted /admin page.
* Note the redirect takes place despite having quarkus.http.auth.form.redirect-after-login=false
* because there is some previous location to redirect to.
*
* Last but not least, client accesses the protected /admin resource again,
* this time providing server with stored quarkus-credential cookie.
* Access is granted and landing page displayed.
*/
@Test
public void testFormBasedAuthSuccess() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
CookieFilter cookies = new CookieFilter();
RestAssured
.given()
.filter(cookies)
.redirects().follow(false)
.when()
.get("/admin")
.then()
.assertThat()
.statusCode(302)
.header("location", containsString("/login"))
.cookie("quarkus-redirect-location", containsString("/admin"));
RestAssured
.given()
.filter(cookies)
.redirects().follow(false)
.when()
.formParam("j_username", "a d m i n")
.formParam("j_password", "a d m i n")
.post("/j_security_check")
.then()
.assertThat()
.statusCode(302)
.header("location", containsString("/admin"))
.cookie("quarkus-credential", notNullValue());
RestAssured
.given()
.filter(cookies)
.redirects().follow(false)
.when()
.get("/admin")
.then()
.assertThat()
.statusCode(200)
.body(equalTo("a d m i n:/admin"));
}
@Test
public void testFormBasedAuthSuccessLandingPage() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
CookieFilter cookies = new CookieFilter();
RestAssured
.given()
.filter(cookies)
.redirects().follow(false)
.when()
.formParam("j_username", "a d m i n")
.formParam("j_password", "a d m i n")
.post("/j_security_check")
.then()
.assertThat()
.statusCode(200)
.cookie("quarkus-credential", notNullValue());
}
@Test
public void testFormAuthFailure() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
CookieFilter cookies = new CookieFilter();
RestAssured
.given()
.filter(cookies)
.redirects().follow(false)
.when()
.formParam("j_username", "a d m i n")
.formParam("j_password", "wrongpassword")
.post("/j_security_check")
.then()
.assertThat()
.statusCode(302)
.header("location", containsString("/error"))
.header("quarkus-credential", nullValue());
}
}
| FormAuthNoRedirectAfterLoginTestCase |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/fpga/TestFpgaResourceHandlerImpl.java | {
"start": 4114,
"end": 25530
} | class ____ {
private static final String HASHABLE_STRING = "abcdef";
private static final String EXPECTED_HASH =
"bef57ec7f53a6d40beb640a780a639c83bc29ac8a9816f1fc6c5c6dcd93c4721";
private Context mockContext;
private FpgaResourceHandlerImpl fpgaResourceHandler;
private Configuration configuration;
private CGroupsHandler mockCGroupsHandler;
private PrivilegedOperationExecutor mockPrivilegedExecutor;
private NMStateStoreService mockNMStateStore;
private ConcurrentHashMap<ContainerId, Container> runningContainersMap;
private IntelFpgaOpenclPlugin mockVendorPlugin;
private List<FpgaDevice> deviceList;
private FpgaDiscoverer fpgaDiscoverer;
private static final String vendorType = "IntelOpenCL";
private File dummyAocx;
private String getTestParentFolder() {
File f = new File("target/temp/" +
TestFpgaResourceHandlerImpl.class.getName());
return f.getAbsolutePath();
}
@BeforeEach
public void setup() throws IOException, YarnException {
CustomResourceTypesConfigurationProvider.
initResourceTypes(ResourceInformation.FPGA_URI);
configuration = new YarnConfiguration();
mockCGroupsHandler = mock(CGroupsHandler.class);
mockPrivilegedExecutor = mock(PrivilegedOperationExecutor.class);
mockNMStateStore = mock(NMStateStoreService.class);
mockContext = mock(Context.class);
// Assumed devices parsed from output
deviceList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
deviceList.add(new FpgaDevice(vendorType, 247, i, "acl" + i));
}
String aocxPath = getTestParentFolder() + "/test.aocx";
mockVendorPlugin = mockPlugin(vendorType, deviceList, aocxPath);
fpgaDiscoverer = new FpgaDiscoverer();
fpgaDiscoverer.setResourceHanderPlugin(mockVendorPlugin);
fpgaDiscoverer.initialize(configuration);
when(mockContext.getNMStateStore()).thenReturn(mockNMStateStore);
runningContainersMap = new ConcurrentHashMap<>();
when(mockContext.getContainers()).thenReturn(runningContainersMap);
fpgaResourceHandler = new FpgaResourceHandlerImpl(mockContext,
mockCGroupsHandler, mockPrivilegedExecutor, mockVendorPlugin,
fpgaDiscoverer);
dummyAocx = new File(aocxPath);
Files.createParentDirs(dummyAocx);
Files.touch(dummyAocx);
Files.asCharSink(dummyAocx, StandardCharsets.UTF_8, FileWriteMode.APPEND)
.write(HASHABLE_STRING);
}
@AfterEach
public void teardown() {
if (dummyAocx != null) {
dummyAocx.delete();
}
}
@Test
public void testBootstrap() throws ResourceHandlerException {
// Case 1. auto
String allowed = "auto";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
// initPlugin() was also called in setup()
verify(mockVendorPlugin, times(2)).initPlugin(configuration);
verify(mockCGroupsHandler, times(1)).initializeCGroupController(
CGroupsHandler.CGroupController.DEVICES);
assertEquals(5, fpgaResourceHandler.getFpgaAllocator()
.getAvailableFpgaCount());
assertEquals(5, fpgaResourceHandler.getFpgaAllocator()
.getAllowedFpga().size());
// Case 2. subset of devices
fpgaResourceHandler = new FpgaResourceHandlerImpl(mockContext,
mockCGroupsHandler, mockPrivilegedExecutor, mockVendorPlugin,
fpgaDiscoverer);
allowed = "0,1,2";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga().size());
List<FpgaDevice> allowedDevices =
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga();
for (String s : allowed.split(",")) {
boolean check = false;
for (FpgaDevice device : allowedDevices) {
if (String.valueOf(device.getMinor()).equals(s)) {
check = true;
}
}
assertTrue(check, "Minor:" + s +" found");
}
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 3. User configuration contains invalid minor device number
fpgaResourceHandler = new FpgaResourceHandlerImpl(mockContext,
mockCGroupsHandler, mockPrivilegedExecutor, mockVendorPlugin,
fpgaDiscoverer);
allowed = "0,1,7";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga().size());
}
@Test
public void testBootstrapWithInvalidUserConfiguration()
throws ResourceHandlerException {
// User configuration contains invalid minor device number
String allowed = "0,1,7";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga().size());
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
String[] invalidAllowedStrings = {"a,1,2,", "a,1,2", "0,1,2,#", "a", "1,"};
for (String s : invalidAllowedStrings) {
boolean invalidConfiguration = false;
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, s);
try {
fpgaResourceHandler.bootstrap(configuration);
} catch (ResourceHandlerException e) {
invalidConfiguration = true;
}
assertTrue(invalidConfiguration);
}
String[] allowedStrings = {"1,2", "1"};
for (String s : allowedStrings) {
boolean invalidConfiguration = false;
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, s);
try {
fpgaResourceHandler.bootstrap(configuration);
} catch (ResourceHandlerException e) {
invalidConfiguration = true;
}
assertFalse(invalidConfiguration);
}
}
@Test
public void testBootStrapWithEmptyUserConfiguration()
throws ResourceHandlerException {
// User configuration contains invalid minor device number
String allowed = "";
boolean invalidConfiguration = false;
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
try {
fpgaResourceHandler.bootstrap(configuration);
} catch (ResourceHandlerException e) {
invalidConfiguration = true;
}
assertTrue(invalidConfiguration);
}
@Test
public void testAllocationWithPreference()
throws ResourceHandlerException, PrivilegedOperationException {
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, "0,1,2");
fpgaResourceHandler.bootstrap(configuration);
// Case 1. The id-0 container request 1 FPGA of IntelOpenCL type and GEMM IP
fpgaResourceHandler.preStart(mockContainer(0, 1, "GEMM"));
assertEquals(1, fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
verifyDeniedDevices(getContainerId(0), Arrays.asList(1, 2));
List<FpgaDevice> list = fpgaResourceHandler.getFpgaAllocator()
.getUsedFpga().get(getContainerId(0).toString());
for (FpgaDevice device : list) {
assertEquals("GEMM", device.getIPID(), "IP should be updated to GEMM");
}
// Case 2. The id-1 container request 3 FPGA of IntelOpenCL and GEMM IP. this should fail
boolean flag = false;
try {
fpgaResourceHandler.preStart(mockContainer(1, 3, "GZIP"));
} catch (ResourceHandlerException e) {
flag = true;
}
assertTrue(flag);
// Case 3. Release the id-0 container
fpgaResourceHandler.postComplete(getContainerId(0));
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Now we have enough devices, re-allocate for the id-1 container
fpgaResourceHandler.preStart(mockContainer(1, 3, "GEMM"));
// Id-1 container should have 0 denied devices
verifyDeniedDevices(getContainerId(1), new ArrayList<>());
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Release container id-1
fpgaResourceHandler.postComplete(getContainerId(1));
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 4. Now all 3 devices should have IPID GEMM
// Try container id-2 and id-3
fpgaResourceHandler.preStart(mockContainer(2, 1, "GZIP"));
fpgaResourceHandler.postComplete(getContainerId(2));
fpgaResourceHandler.preStart(mockContainer(3, 2, "GEMM"));
// IPID should be GEMM for id-3 container
list = fpgaResourceHandler.getFpgaAllocator()
.getUsedFpga().get(getContainerId(3).toString());
for (FpgaDevice device : list) {
assertEquals("GEMM", device.getIPID(), "IPID should be GEMM");
}
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(1,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
fpgaResourceHandler.postComplete(getContainerId(3));
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 5. id-4 request 0 FPGA device
fpgaResourceHandler.preStart(mockContainer(4, 0, ""));
// Deny all devices for id-4
verifyDeniedDevices(getContainerId(4), Arrays.asList(0, 1, 2));
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 6. id-5 with invalid FPGA device
try {
fpgaResourceHandler.preStart(mockContainer(5, -2, ""));
} catch (ResourceHandlerException e) {
assertTrue(true);
}
}
@Test
public void testsAllocationWithExistingIPIDDevices()
throws ResourceHandlerException, PrivilegedOperationException,
IOException {
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, "0,1,2");
fpgaResourceHandler.bootstrap(configuration);
// The id-0 container request 3 FPGA of IntelOpenCL type and GEMM IP
fpgaResourceHandler.preStart(mockContainer(0, 3, "GEMM"));
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
List<FpgaDevice> list =
fpgaResourceHandler
.getFpgaAllocator()
.getUsedFpga()
.get(getContainerId(0).toString());
fpgaResourceHandler.postComplete(getContainerId(0));
for (FpgaDevice device : list) {
assertEquals("GEMM", device.getIPID(),
"IP should be updated to GEMM");
}
// Case 1. id-1 container request preStart, with no plugin.configureIP called
fpgaResourceHandler.preStart(mockContainer(1, 1, "GEMM"));
fpgaResourceHandler.preStart(mockContainer(2, 1, "GEMM"));
// we should have 3 times due to id-1 skip 1 invocation
verify(mockVendorPlugin, times(3)).configureIP(anyString(),
any(FpgaDevice.class));
fpgaResourceHandler.postComplete(getContainerId(1));
fpgaResourceHandler.postComplete(getContainerId(2));
// Case 2. id-2 container request preStart, with 1 plugin.configureIP called
// Add some characters to the dummy file to have its hash changed
Files.asCharSink(dummyAocx, StandardCharsets.UTF_8, FileWriteMode.APPEND)
.write("12345");
fpgaResourceHandler.preStart(mockContainer(1, 1, "GZIP"));
// we should have 4 times invocation
verify(mockVendorPlugin, times(4)).configureIP(anyString(),
any(FpgaDevice.class));
}
@Test
public void testAllocationWithZeroDevices()
throws ResourceHandlerException, PrivilegedOperationException {
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, "0,1,2");
fpgaResourceHandler.bootstrap(configuration);
// The id-0 container request 0 FPGA
fpgaResourceHandler.preStart(mockContainer(0, 0, null));
verifyDeniedDevices(getContainerId(0), Arrays.asList(0, 1, 2));
verify(mockVendorPlugin, times(0)).retrieveIPfilePath(anyString(),
anyString(), anyMap());
verify(mockVendorPlugin, times(0)).configureIP(anyString(),
any(FpgaDevice.class));
}
@Test
public void testStateStore()
throws ResourceHandlerException, IOException {
// Case 1. store 3 devices
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, "0,1,2");
fpgaResourceHandler.bootstrap(configuration);
Container container0 = mockContainer(0, 3, "GEMM");
fpgaResourceHandler.preStart(container0);
List<FpgaDevice> assigned =
fpgaResourceHandler
.getFpgaAllocator()
.getUsedFpga()
.get(getContainerId(0).toString());
verify(mockNMStateStore).storeAssignedResources(container0,
ResourceInformation.FPGA_URI,
new ArrayList<>(assigned));
fpgaResourceHandler.postComplete(getContainerId(0));
// Case 2. ask 0, no store api called
Container container1 = mockContainer(1, 0, "");
fpgaResourceHandler.preStart(container1);
verify(mockNMStateStore, never()).storeAssignedResources(
eq(container1), eq(ResourceInformation.FPGA_URI), anyList());
}
@Test
public void testReacquireContainer() throws ResourceHandlerException {
Container c0 = mockContainer(0, 2, "GEMM");
List<FpgaDevice> assigned = new ArrayList<>();
assigned.add(new FpgaDevice(
vendorType, 247, 0, "acl0"));
assigned.add(new FpgaDevice(
vendorType, 247, 1, "acl1"));
// Mock we've stored the c0 states
mockStateStoreForContainer(c0, assigned);
// NM start
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, "0,1,2");
fpgaResourceHandler.bootstrap(configuration);
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 1. try recover state for id-0 container
fpgaResourceHandler.reacquireContainer(getContainerId(0));
// minor number matches
List<FpgaDevice> used =
fpgaResourceHandler.getFpgaAllocator().
getUsedFpga().get(getContainerId(0).toString());
int count = 0;
for (FpgaDevice device : used) {
if (device.getMinor() == 0){
count++;
}
if (device.getMinor() == 1) {
count++;
}
}
assertEquals(2, count, "Unexpected used minor number in allocator");
List<FpgaDevice> available =
fpgaResourceHandler
.getFpgaAllocator()
.getAvailableFpga()
.get(vendorType);
count = 0;
for (FpgaDevice device : available) {
if (device.getMinor() == 2) {
count++;
}
}
assertEquals(1, count, "Unexpected available minor number in allocator");
// Case 2. Recover a not allowed device with minor number 5
Container c1 = mockContainer(1, 1, "GEMM");
assigned = new ArrayList<>();
assigned.add(new FpgaDevice(
vendorType, 247, 5, "acl0"));
// Mock we've stored the c1 states
mockStateStoreForContainer(c1, assigned);
boolean flag = false;
try {
fpgaResourceHandler.reacquireContainer(getContainerId(1));
} catch (ResourceHandlerException e) {
flag = true;
}
assertTrue(flag);
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(1,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 3. recover a already used device by other container
Container c2 = mockContainer(2, 1, "GEMM");
assigned = new ArrayList<>();
assigned.add(new FpgaDevice(
vendorType, 247, 1, "acl0"));
// Mock we've stored the c2 states
mockStateStoreForContainer(c2, assigned);
flag = false;
try {
fpgaResourceHandler.reacquireContainer(getContainerId(2));
} catch (ResourceHandlerException e) {
flag = true;
}
assertTrue(flag);
assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(1,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 4. recover a normal container c3 with remaining minor device number 2
Container c3 = mockContainer(3, 1, "GEMM");
assigned = new ArrayList<>();
assigned.add(new FpgaDevice(
vendorType, 247, 2, "acl2"));
// Mock we've stored the c2 states
mockStateStoreForContainer(c3, assigned);
fpgaResourceHandler.reacquireContainer(getContainerId(3));
assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
}
@Test
public void testSha256CalculationFails() throws ResourceHandlerException {
ResourceHandlerException exception =
assertThrows(ResourceHandlerException.class, () -> {
dummyAocx.delete();
fpgaResourceHandler.preStart(mockContainer(0, 1, "GEMM"));
});
assertEquals("Could not calculate SHA-256", exception.getMessage());
}
@Test
public void testSha256CalculationSucceeds()
throws IOException, ResourceHandlerException {
mockVendorPlugin =
mockPlugin(vendorType, deviceList, dummyAocx.getAbsolutePath());
fpgaResourceHandler = new FpgaResourceHandlerImpl(mockContext,
mockCGroupsHandler, mockPrivilegedExecutor, mockVendorPlugin,
fpgaDiscoverer);
fpgaResourceHandler.bootstrap(configuration);
fpgaResourceHandler.preStart(mockContainer(0, 1, "GEMM"));
// IP file is assigned to the first device
List<FpgaDevice> devices =
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga();
FpgaDevice device = devices.get(0);
assertEquals(EXPECTED_HASH, device.getAocxHash(), "Hash value");
}
private void verifyDeniedDevices(ContainerId containerId,
List<Integer> deniedDevices)
throws ResourceHandlerException, PrivilegedOperationException {
verify(mockCGroupsHandler, atLeastOnce()).createCGroup(
CGroupsHandler.CGroupController.DEVICES, containerId.toString());
if (null != deniedDevices && !deniedDevices.isEmpty()) {
verify(mockPrivilegedExecutor, times(1)).executePrivilegedOperation(
new PrivilegedOperation(PrivilegedOperation.OperationType.FPGA, Arrays
.asList(FpgaResourceHandlerImpl.CONTAINER_ID_CLI_OPTION,
containerId.toString(),
FpgaResourceHandlerImpl.EXCLUDED_FPGAS_CLI_OPTION,
StringUtils.join(",", deniedDevices))), true);
} else if (deniedDevices.isEmpty()) {
verify(mockPrivilegedExecutor, times(1)).executePrivilegedOperation(
new PrivilegedOperation(PrivilegedOperation.OperationType.FPGA, Arrays
.asList(FpgaResourceHandlerImpl.CONTAINER_ID_CLI_OPTION,
containerId.toString())), true);
}
}
private static IntelFpgaOpenclPlugin mockPlugin(String type,
List<FpgaDevice> list, String aocxPath) {
IntelFpgaOpenclPlugin plugin = mock(IntelFpgaOpenclPlugin.class);
when(plugin.initPlugin(any())).thenReturn(true);
when(plugin.getFpgaType()).thenReturn(type);
when(plugin.retrieveIPfilePath(anyString(),
anyString(), anyMap())).thenReturn(aocxPath);
when(plugin.configureIP(anyString(), any()))
.thenReturn(true);
when(plugin.discover(anyInt())).thenReturn(list);
return plugin;
}
private static Container mockContainer(int id, int numFpga, String IPID) {
Container c = mock(Container.class);
Resource res = Resource.newInstance(1024, 1);
ResourceMappings resMapping = new ResourceMappings();
res.setResourceValue(ResourceInformation.FPGA_URI, numFpga);
when(c.getResource()).thenReturn(res);
when(c.getResourceMappings()).thenReturn(resMapping);
when(c.getContainerId()).thenReturn(getContainerId(id));
ContainerLaunchContext clc = mock(ContainerLaunchContext.class);
Map<String, String> envs = new HashMap<>();
if (numFpga > 0) {
envs.put("REQUESTED_FPGA_IP_ID", IPID);
}
when(c.getLaunchContext()).thenReturn(clc);
when(clc.getEnvironment()).thenReturn(envs);
when(c.getWorkDir()).thenReturn("/tmp");
ResourceSet resourceSet = new ResourceSet();
when(c.getResourceSet()).thenReturn(resourceSet);
return c;
}
private void mockStateStoreForContainer(Container container,
List<FpgaDevice> assigned) {
ResourceMappings rmap = new ResourceMappings();
ResourceMappings.AssignedResources ar =
new ResourceMappings.AssignedResources();
ar.updateAssignedResources(new ArrayList<>(assigned));
rmap.addAssignedResources(ResourceInformation.FPGA_URI, ar);
when(container.getResourceMappings()).thenReturn(rmap);
runningContainersMap.put(container.getContainerId(), container);
}
private static ContainerId getContainerId(int id) {
return ContainerId.newContainerId(ApplicationAttemptId
.newInstance(ApplicationId.newInstance(1234L, 1), 1), id);
}
}
| TestFpgaResourceHandlerImpl |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestRpcServiceProtosLegacy.java | {
"start": 102191,
"end": 104287
} | class ____ extends org.apache.hadoop.ipc.protobuf.TestRpcServiceProtosLegacy.OldProtobufRpcProto implements Interface {
private Stub(com.google.protobuf.RpcChannel channel) {
this.channel = channel;
}
private final com.google.protobuf.RpcChannel channel;
public com.google.protobuf.RpcChannel getChannel() {
return channel;
}
public void ping(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request,
com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto> done) {
channel.callMethod(
getDescriptor().getMethods().get(0),
controller,
request,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance(),
com.google.protobuf.RpcUtil.generalizeCallback(
done,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.class,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance()));
}
public void echo(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request,
com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto> done) {
channel.callMethod(
getDescriptor().getMethods().get(1),
controller,
request,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance(),
com.google.protobuf.RpcUtil.generalizeCallback(
done,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.class,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance()));
}
}
public static BlockingInterface newBlockingStub(
com.google.protobuf.BlockingRpcChannel channel) {
return new BlockingStub(channel);
}
public | Stub |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/config/immutable/EngineConfig.java | {
"start": 1250,
"end": 2013
} | class ____ {
private final String manufacturer;
private final int cylinders;
private final CrankShaft crankShaft;
@ConfigurationInject // <2>
public EngineConfig(
@Bindable(defaultValue = "Ford") @NotBlank String manufacturer, // <3>
@Min(1L) int cylinders, // <4>
@NotNull CrankShaft crankShaft) {
this.manufacturer = manufacturer;
this.cylinders = cylinders;
this.crankShaft = crankShaft;
}
public String getManufacturer() {
return manufacturer;
}
public int getCylinders() {
return cylinders;
}
public CrankShaft getCrankShaft() {
return crankShaft;
}
@ConfigurationProperties("crank-shaft")
public static | EngineConfig |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestTimedOutTestsListener.java | {
"start": 2274,
"end": 3941
} | class ____ extends SubjectInheritingThread {
private Lock lock1 = null;
private Lock lock2 = null;
private Monitor mon1 = null;
private Monitor mon2 = null;
private boolean useSync;
DeadlockThread(String name, Lock lock1, Lock lock2) {
super(name);
this.lock1 = lock1;
this.lock2 = lock2;
this.useSync = true;
}
DeadlockThread(String name, Monitor mon1, Monitor mon2) {
super(name);
this.mon1 = mon1;
this.mon2 = mon2;
this.useSync = false;
}
public void work() {
if (useSync) {
syncLock();
} else {
monitorLock();
}
}
private void syncLock() {
lock1.lock();
try {
try {
barrier.await();
} catch (Exception e) {
}
goSyncDeadlock();
} finally {
lock1.unlock();
}
}
private void goSyncDeadlock() {
try {
barrier.await();
} catch (Exception e) {
}
lock2.lock();
throw new RuntimeException("should not reach here.");
}
private void monitorLock() {
synchronized (mon1) {
try {
barrier.await();
} catch (Exception e) {
}
goMonitorDeadlock();
}
}
private void goMonitorDeadlock() {
try {
barrier.await();
} catch (Exception e) {
}
synchronized (mon2) {
throw new RuntimeException(getName() + " should not reach here.");
}
}
}
| DeadlockThread |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/service/UnknownServiceException.java | {
"start": 291,
"end": 614
} | class ____ extends ServiceException {
public final Class<?> serviceRole;
public UnknownServiceException(Class<?> serviceRole) {
super( "Unknown service requested [" + serviceRole.getName() + "]" );
this.serviceRole = serviceRole;
}
public Class<?> getServiceRole() {
return serviceRole;
}
}
| UnknownServiceException |
java | reactor__reactor-core | reactor-test/src/test/java/reactor/test/MessageFormatterTest.java | {
"start": 890,
"end": 12370
} | class ____ {
@Test
public void noScenarioEmpty() {
assertThat(new MessageFormatter("", null, null).scenarioPrefix)
.isNotNull()
.isEmpty();
}
@Test
public void nullScenarioEmpty() {
assertThat(new MessageFormatter(null, null, null).scenarioPrefix)
.isNotNull()
.isEmpty();
}
@Test
public void givenScenarioWrapped() {
assertThat(new MessageFormatter("foo", null, null).scenarioPrefix)
.isEqualTo("[foo] ");
}
// === Tests with an empty scenario name ===
static final MessageFormatter noScenario = new MessageFormatter("", null, null);
@Test
public void noScenarioFailNullEventNoArgs() {
assertThat(noScenario.fail(null, "details"))
.hasMessage("expectation failed (details)");
}
@Test
public void noScenarioFailNoDescriptionNoArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"");
assertThat(noScenario.fail(event, "details"))
.hasMessage("expectation failed (details)");
}
@Test
public void noScenarioFailDescriptionNoArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"eventDescription");
assertThat(noScenario.fail(event, "details"))
.hasMessage("expectation \"eventDescription\" failed (details)");
}
@Test
public void noScenarioFailNullEventHasArgs() {
assertThat(noScenario.fail(null, "details = %s", "bar"))
.hasMessage("expectation failed (details = bar)");
}
@Test
public void noScenarioFailNoDescriptionHasArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"");
assertThat(noScenario.fail(event, "details = %s", "bar"))
.hasMessage("expectation failed (details = bar)");
}
@Test
public void noScenarioFailDescriptionHasArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"eventDescription");
assertThat(noScenario.fail(event, "details = %s", "bar"))
.hasMessage("expectation \"eventDescription\" failed (details = bar)");
}
@Test
public void noScenarioFailOptional() {
assertThat(noScenario.failOptional(null, "foo"))
.hasValueSatisfying(ae -> assertThat(ae).hasMessage("expectation failed (foo)"));
}
@Test
public void noScenarioFailPrefixNoArgs() {
assertThat(noScenario.failPrefix("firstPart", "secondPart"))
.hasMessage("firstPartsecondPart)"); //note the prefix doesn't have an opening parenthesis
}
@Test
public void noScenarioFailPrefixHasArgs() {
assertThat(noScenario.failPrefix("firstPart(", "secondPart = %s", "foo"))
.hasMessage("firstPart(secondPart = foo)");
}
@Test
public void noScenarioAssertionError() {
assertThat(noScenario.assertionError("plain"))
.hasMessage("plain")
.hasNoCause();
}
@Test
public void noScenarioAssertionErrorWithCause() {
Throwable cause = new IllegalArgumentException("boom");
assertThat(noScenario.assertionError("plain", cause))
.hasMessage("plain")
.hasCause(cause);
}
@Test
public void noScenarioAssertionErrorWithNullCause() {
assertThat(noScenario.assertionError("plain", null))
.hasMessage("plain")
.hasNoCause();
}
@Test
public void noScenarioIllegalStateException() {
assertThat(noScenario.<Throwable>error(IllegalStateException::new, "plain"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("plain");
}
// === Tests with a scenario name ===
static final MessageFormatter
withScenario = new MessageFormatter("MessageFormatterTest", null, null);
@Test
public void withScenarioFailNullEventNoArgs() {
assertThat(withScenario.fail(null, "details"))
.hasMessage("[MessageFormatterTest] expectation failed (details)");
}
@Test
public void withScenarioFailNoDescriptionNoArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"");
assertThat(withScenario.fail(event, "details"))
.hasMessage("[MessageFormatterTest] expectation failed (details)");
}
@Test
public void withScenarioFailDescriptionNoArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"eventDescription");
assertThat(withScenario.fail(event, "details"))
.hasMessage("[MessageFormatterTest] expectation \"eventDescription\" failed (details)");
}
@Test
public void withScenarioFailNullEventHasArgs() {
assertThat(withScenario.fail(null, "details = %s", "bar"))
.hasMessage("[MessageFormatterTest] expectation failed (details = bar)");
}
@Test
public void withScenarioFailNoDescriptionHasArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"");
assertThat(withScenario.fail(event, "details = %s", "bar"))
.hasMessage("[MessageFormatterTest] expectation failed (details = bar)");
}
@Test
public void withScenarioFailDescriptionHasArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"eventDescription");
assertThat(withScenario.fail(event, "details = %s", "bar"))
.hasMessage("[MessageFormatterTest] expectation \"eventDescription\" failed (details = bar)");
}
@Test
public void withScenarioFailOptional() {
assertThat(withScenario.failOptional(null, "foo"))
.hasValueSatisfying(ae -> assertThat(ae).hasMessage("[MessageFormatterTest] expectation failed (foo)"));
}
@Test
public void withScenarioFailPrefixNoArgs() {
assertThat(withScenario.failPrefix("firstPart", "secondPart"))
.hasMessage("[MessageFormatterTest] firstPartsecondPart)"); //note the prefix doesn't have an opening parenthesis
}
@Test
public void withScenarioFailPrefixHasArgs() {
assertThat(withScenario.failPrefix("firstPart(", "secondPart = %s", "foo"))
.hasMessage("[MessageFormatterTest] firstPart(secondPart = foo)");
}
@Test
public void withScenarioAssertionError() {
assertThat(withScenario.assertionError("plain"))
.hasMessage("[MessageFormatterTest] plain")
.hasNoCause();
}
@Test
public void withScenarioAssertionErrorWithCause() {
Throwable cause = new IllegalArgumentException("boom");
assertThat(withScenario.assertionError("plain", cause))
.hasMessage("[MessageFormatterTest] plain")
.hasCause(cause);
}
@Test
public void withScenarioAssertionErrorWithNullCause() {
assertThat(withScenario.assertionError("plain", null))
.hasMessage("[MessageFormatterTest] plain")
.hasNoCause();
}
@Test
public void withScenarioIllegalStateException() {
assertThat(withScenario.<Throwable>error(IllegalStateException::new, "plain"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("[MessageFormatterTest] plain");
}
// === Tests with a value formatter ===
static final MessageFormatter withCustomFormatter = new MessageFormatter("withCustomFormatter",
ValueFormatters.forClass(String.class, o -> o.getClass().getSimpleName() + "=>" + o),
Arrays.asList(ValueFormatters.DEFAULT_SIGNAL_EXTRACTOR, ValueFormatters.DEFAULT_ITERABLE_EXTRACTOR, ValueFormatters.arrayExtractor(Object[].class)));
@Test
public void withCustomFormatterFailNullEventNoArgs() {
assertThat(withCustomFormatter.fail(null, "details"))
.hasMessage("[withCustomFormatter] expectation failed (details)");
}
@Test
public void withCustomFormatterFailNoDescriptionNoArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"");
assertThat(withCustomFormatter.fail(event, "details"))
.hasMessage("[withCustomFormatter] expectation failed (details)");
}
@Test
public void withCustomFormatterFailDescriptionNoArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"eventDescription");
assertThat(withCustomFormatter.fail(event, "details"))
.hasMessage("[withCustomFormatter] expectation \"eventDescription\" failed (details)");
}
@Test
public void withCustomFormatterFailNullEventHasArgs() {
assertThat(withCustomFormatter.fail(null, "details = %s", "bar"))
.hasMessage("[withCustomFormatter] expectation failed (details = String=>bar)");
}
@Test
public void withCustomFormatterFailNoDescriptionHasArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"");
assertThat(withCustomFormatter.fail(event, "details = %s", "bar"))
.hasMessage("[withCustomFormatter] expectation failed (details = String=>bar)");
}
@Test
public void withCustomFormatterFailDescriptionHasArgs() {
DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
"eventDescription");
assertThat(withCustomFormatter.fail(event, "details = %s", "bar"))
.hasMessage("[withCustomFormatter] expectation \"eventDescription\" failed (details = String=>bar)");
}
@Test
public void withCustomFormatterFailOptional() {
assertThat(withCustomFormatter.failOptional(null, "foo"))
.hasValueSatisfying(ae -> assertThat(ae).hasMessage("[withCustomFormatter] expectation failed (foo)"));
}
@Test
public void withCustomFormatterFailPrefixNoArgs() {
assertThat(withCustomFormatter.failPrefix("firstPart", "secondPart"))
.hasMessage("[withCustomFormatter] firstPartsecondPart)"); //note the prefix doesn't have an opening parenthesis
}
@Test
public void withCustomFormatterFailPrefixHasArgs() {
assertThat(withCustomFormatter.failPrefix("firstPart(", "secondPart = %s", "foo"))
.hasMessage("[withCustomFormatter] firstPart(secondPart = String=>foo)");
}
@Test
public void withCustomFormatterAssertionError() {
assertThat(withCustomFormatter.assertionError("plain"))
.hasMessage("[withCustomFormatter] plain")
.hasNoCause();
}
@Test
public void withCustomFormatterAssertionErrorWithCause() {
Throwable cause = new IllegalArgumentException("boom");
assertThat(withCustomFormatter.assertionError("plain", cause))
.hasMessage("[withCustomFormatter] plain")
.hasCause(cause);
}
@Test
public void withCustomFormatterAssertionErrorWithNullCause() {
assertThat(withCustomFormatter.assertionError("plain", null))
.hasMessage("[withCustomFormatter] plain")
.hasNoCause();
}
@Test
public void withCustomFormatterIllegalStateException() {
assertThat(withCustomFormatter.<Throwable>error(IllegalStateException::new, "plain"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("[withCustomFormatter] plain");
}
@Test
public void withCustomFormatterFormatSignal() {
assertThat(withCustomFormatter.format("expectation %s expected %s got %s",
Signal.next("foo"), "foo", Signal.next("bar")))
.isEqualTo("expectation onNext(String=>foo) expected String=>foo got onNext(String=>bar)");
}
@Test
public void withCustomFormatterFormatIterable() {
assertThat(withCustomFormatter.format("expectation %s expected %s got %s",
Arrays.asList("foo","bar"), "foo", Collections.singletonList("bar")))
.isEqualTo("expectation [String=>foo, String=>bar] expected String=>foo got [String=>bar]");
}
@Test
public void withCustomFormatterFormatArray() {
assertThat(withCustomFormatter.format("expectation %s expected %s got %s",
new Object[] {"foo","bar"}, "foo", new Object[] {"bar"}))
.isEqualTo("expectation [String=>foo, String=>bar] expected String=>foo got [String=>bar]");
}
} | MessageFormatterTest |
java | quarkusio__quarkus | extensions/amazon-lambda-rest/runtime/src/main/java/io/quarkus/amazon/lambda/http/model/AwsProxyResponse.java | {
"start": 883,
"end": 3515
} | class ____ {
//-------------------------------------------------------------
// Variables - Private
//-------------------------------------------------------------
private int statusCode;
private String statusDescription;
private Map<String, String> headers;
private Headers multiValueHeaders;
private String body;
private boolean isBase64Encoded;
//-------------------------------------------------------------
// Constructors
//-------------------------------------------------------------
public AwsProxyResponse() {
}
public AwsProxyResponse(int statusCode) {
this(statusCode, null);
}
public AwsProxyResponse(int statusCode, Headers headers) {
this(statusCode, headers, null);
}
public AwsProxyResponse(int statusCode, Headers headers, String body) {
this.statusCode = statusCode;
this.multiValueHeaders = headers;
this.body = body;
}
//-------------------------------------------------------------
// Methods - Public
//-------------------------------------------------------------
public void addHeader(String key, String value) {
if (this.multiValueHeaders == null) {
this.multiValueHeaders = new Headers();
}
this.multiValueHeaders.add(key, value);
}
//-------------------------------------------------------------
// Methods - Getter/Setter
//-------------------------------------------------------------
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public Headers getMultiValueHeaders() {
return multiValueHeaders;
}
public void setMultiValueHeaders(Headers multiValueHeaders) {
this.multiValueHeaders = multiValueHeaders;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@JsonProperty("isBase64Encoded")
public boolean isBase64Encoded() {
return isBase64Encoded;
}
public void setBase64Encoded(boolean base64Encoded) {
isBase64Encoded = base64Encoded;
}
public String getStatusDescription() {
return statusDescription;
}
public void setStatusDescription(String statusDescription) {
this.statusDescription = statusDescription;
}
}
| AwsProxyResponse |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/tofix/ExternalTypeCustomResolver1288Test.java | {
"start": 10720,
"end": 10854
} | class ____ implements PaymentDetails {
@JsonPOJOBuilder (withPrefix = "")
public static | EncryptedCreditCardDetails |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/cluster/ClusterServiceSelectors.java | {
"start": 2380,
"end": 3477
} | class ____ implements CamelClusterService.Selector {
@Override
public Optional<CamelClusterService> select(Collection<CamelClusterService> services) {
Optional<Map.Entry<Integer, List<CamelClusterService>>> highPriorityServices = services.stream()
.collect(Collectors.groupingBy(CamelClusterService::getOrder))
.entrySet().stream()
.min(Comparator.comparingInt(Map.Entry::getKey));
if (highPriorityServices.isPresent()) {
if (highPriorityServices.get().getValue().size() == 1) {
return Optional.of(highPriorityServices.get().getValue().iterator().next());
} else {
LOGGER.warn("Multiple CamelClusterService instances available for highest priority (order={}, items={})",
highPriorityServices.get().getKey(),
highPriorityServices.get().getValue());
}
}
return Optional.empty();
}
}
public static final | SelectByOrder |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/monitor/os/OsProbeTests.java | {
"start": 1249,
"end": 22554
} | class ____ extends ESTestCase {
public void testOsInfo() throws IOException {
final int allocatedProcessors = randomIntBetween(1, Runtime.getRuntime().availableProcessors());
final long refreshInterval = randomBoolean() ? -1 : randomNonNegativeLong();
final String prettyName;
if (Constants.LINUX) {
prettyName = randomFrom("Fedora 28 (Workstation Edition)", "Linux", null);
} else {
prettyName = Constants.OS_NAME;
}
final OsProbe osProbe = new OsProbe() {
@Override
List<String> readOsRelease() {
assert Constants.LINUX : Constants.OS_NAME;
if (prettyName != null) {
final String quote = randomFrom("\"", "'", "");
final String space = randomFrom(" ", "");
final String prettyNameLine = Strings.format("PRETTY_NAME=%s%s%s%s", quote, prettyName, quote, space);
return Arrays.asList("NAME=" + randomAlphaOfLength(16), prettyNameLine);
} else {
return Collections.singletonList("NAME=" + randomAlphaOfLength(16));
}
}
};
final OsInfo info = osProbe.osInfo(refreshInterval, Processors.of((double) allocatedProcessors));
assertNotNull(info);
assertThat(info.getRefreshInterval(), equalTo(refreshInterval));
assertThat(info.getName(), equalTo(Constants.OS_NAME));
if (Constants.LINUX) {
if (prettyName != null) {
assertThat(info.getPrettyName(), equalTo(prettyName));
} else {
assertThat(info.getPrettyName(), equalTo(Constants.OS_NAME));
}
}
assertThat(info.getArch(), equalTo(Constants.OS_ARCH));
assertThat(info.getVersion(), equalTo(Constants.OS_VERSION));
assertThat(info.getAllocatedProcessors(), equalTo(allocatedProcessors));
assertThat(info.getAvailableProcessors(), equalTo(Runtime.getRuntime().availableProcessors()));
}
public void testOsStats() {
final OsProbe osProbe = new OsProbe();
OsStats stats = osProbe.osStats();
assertNotNull(stats);
assertThat(stats.getTimestamp(), greaterThan(0L));
assertThat(
stats.getCpu().getPercent(),
anyOf(equalTo((short) -1), is(both(greaterThanOrEqualTo((short) 0)).and(lessThanOrEqualTo((short) 100))))
);
double[] loadAverage = stats.getCpu().getLoadAverage();
if (loadAverage != null) {
assertThat(loadAverage.length, equalTo(3));
}
if (Constants.WINDOWS) {
// load average is unavailable on Windows
assertNull(loadAverage);
} else if (Constants.LINUX) {
// we should be able to get the load average
assertNotNull(loadAverage);
assertThat(loadAverage[0], greaterThanOrEqualTo((double) 0));
assertThat(loadAverage[1], greaterThanOrEqualTo((double) 0));
assertThat(loadAverage[2], greaterThanOrEqualTo((double) 0));
} else if (Constants.MAC_OS_X) {
// one minute load average is available, but 10-minute and 15-minute load averages are not
assertNotNull(loadAverage);
assertThat(loadAverage[0], greaterThanOrEqualTo((double) 0));
assertThat(loadAverage[1], equalTo((double) -1));
assertThat(loadAverage[2], equalTo((double) -1));
} else {
// unknown system, but the best case is that we have the one-minute load average
if (loadAverage != null) {
assertThat(loadAverage[0], anyOf(equalTo((double) -1), greaterThanOrEqualTo((double) 0)));
assertThat(loadAverage[1], equalTo((double) -1));
assertThat(loadAverage[2], equalTo((double) -1));
}
}
assertThat(stats.getCpu().getAvailableProcessors(), greaterThanOrEqualTo(1));
assertNotNull(stats.getMem());
assertThat(stats.getMem().getTotal().getBytes(), greaterThan(0L));
assertThat(stats.getMem().getFree().getBytes(), greaterThan(0L));
assertThat(stats.getMem().getFreePercent(), allOf(greaterThanOrEqualTo((short) 0), lessThanOrEqualTo((short) 100)));
assertThat(stats.getMem().getUsed().getBytes(), greaterThan(0L));
assertThat(stats.getMem().getUsedPercent(), allOf(greaterThanOrEqualTo((short) 0), lessThanOrEqualTo((short) 100)));
assertNotNull(stats.getSwap());
assertNotNull(stats.getSwap().getTotal());
long total = stats.getSwap().getTotal().getBytes();
if (total > 0) {
assertThat(stats.getSwap().getTotal().getBytes(), greaterThan(0L));
assertThat(stats.getSwap().getFree().getBytes(), greaterThanOrEqualTo(0L));
assertThat(stats.getSwap().getUsed().getBytes(), greaterThanOrEqualTo(0L));
} else {
// On platforms with no swap
assertThat(stats.getSwap().getTotal().getBytes(), equalTo(0L));
assertThat(stats.getSwap().getFree().getBytes(), equalTo(0L));
assertThat(stats.getSwap().getUsed().getBytes(), equalTo(0L));
}
if (Constants.LINUX) {
if (stats.getCgroup() != null) {
assertThat(stats.getCgroup().getCpuAcctControlGroup(), notNullValue());
assertThat(stats.getCgroup().getCpuAcctUsageNanos(), greaterThan(BigInteger.ZERO));
assertThat(stats.getCgroup().getCpuCfsQuotaMicros(), anyOf(equalTo(-1L), greaterThanOrEqualTo(0L)));
assertThat(stats.getCgroup().getCpuCfsPeriodMicros(), greaterThanOrEqualTo(0L));
assertThat(stats.getCgroup().getCpuStat().getNumberOfElapsedPeriods(), greaterThanOrEqualTo(BigInteger.ZERO));
assertThat(stats.getCgroup().getCpuStat().getNumberOfTimesThrottled(), greaterThanOrEqualTo(BigInteger.ZERO));
assertThat(stats.getCgroup().getCpuStat().getTimeThrottledNanos(), greaterThanOrEqualTo(BigInteger.ZERO));
// These could be null if transported from a node running an older version, but shouldn't be null on the current node
assertThat(stats.getCgroup().getMemoryControlGroup(), notNullValue());
String memoryLimitInBytes = stats.getCgroup().getMemoryLimitInBytes();
assertThat(memoryLimitInBytes, notNullValue());
if (memoryLimitInBytes.equals("max") == false) {
assertThat(new BigInteger(memoryLimitInBytes), greaterThan(BigInteger.ZERO));
}
assertThat(stats.getCgroup().getMemoryUsageInBytes(), notNullValue());
assertThat(new BigInteger(stats.getCgroup().getMemoryUsageInBytes()), greaterThan(BigInteger.ZERO));
}
} else {
assertNull(stats.getCgroup());
}
}
public void testGetSystemLoadAverage() {
assumeTrue("test runs on Linux only", Constants.LINUX);
final OsProbe probe = new OsProbe() {
@Override
String readProcLoadavg() {
return "1.51 1.69 1.99 3/417 23251";
}
};
final double[] systemLoadAverage = probe.getSystemLoadAverage();
assertNotNull(systemLoadAverage);
assertThat(systemLoadAverage.length, equalTo(3));
// avoid silliness with representing doubles
assertThat(systemLoadAverage[0], equalTo(Double.parseDouble("1.51")));
assertThat(systemLoadAverage[1], equalTo(Double.parseDouble("1.69")));
assertThat(systemLoadAverage[2], equalTo(Double.parseDouble("1.99")));
}
public void testCgroupProbe() {
final int availableCgroupsVersion = randomFrom(0, 1, 2);
final String hierarchy = randomAlphaOfLength(16);
final OsProbe probe = buildStubOsProbe(availableCgroupsVersion, hierarchy);
final OsStats.Cgroup cgroup = probe.osStats().getCgroup();
switch (availableCgroupsVersion) {
case 0 -> assertNull(cgroup);
case 1 -> {
assertNotNull(cgroup);
assertThat(cgroup.getCpuAcctControlGroup(), equalTo("/" + hierarchy));
assertThat(cgroup.getCpuAcctUsageNanos(), equalTo(new BigInteger("364869866063112")));
assertThat(cgroup.getCpuControlGroup(), equalTo("/" + hierarchy));
assertThat(cgroup.getCpuCfsPeriodMicros(), equalTo(100000L));
assertThat(cgroup.getCpuCfsQuotaMicros(), equalTo(50000L));
assertThat(cgroup.getCpuStat().getNumberOfElapsedPeriods(), equalTo(BigInteger.valueOf(17992)));
assertThat(cgroup.getCpuStat().getNumberOfTimesThrottled(), equalTo(BigInteger.valueOf(1311)));
assertThat(cgroup.getCpuStat().getTimeThrottledNanos(), equalTo(new BigInteger("139298645489")));
assertThat(cgroup.getMemoryLimitInBytes(), equalTo("18446744073709551615"));
assertThat(cgroup.getMemoryUsageInBytes(), equalTo("4796416"));
}
case 2 -> {
assertNotNull(cgroup);
assertThat(cgroup.getCpuAcctControlGroup(), equalTo("/" + hierarchy));
assertThat(cgroup.getCpuAcctUsageNanos(), equalTo(new BigInteger("364869866063000")));
assertThat(cgroup.getCpuControlGroup(), equalTo("/" + hierarchy));
assertThat(cgroup.getCpuCfsPeriodMicros(), equalTo(100000L));
assertThat(cgroup.getCpuCfsQuotaMicros(), equalTo(50000L));
assertThat(cgroup.getCpuStat().getNumberOfElapsedPeriods(), equalTo(BigInteger.valueOf(17992)));
assertThat(cgroup.getCpuStat().getNumberOfTimesThrottled(), equalTo(BigInteger.valueOf(1311)));
assertThat(cgroup.getCpuStat().getTimeThrottledNanos(), equalTo(new BigInteger("139298645000")));
assertThat(cgroup.getMemoryLimitInBytes(), equalTo("18446744073709551615"));
assertThat(cgroup.getMemoryUsageInBytes(), equalTo("4796416"));
}
}
}
public void testCgroupProbeWithMissingCpuAcct() {
final String hierarchy = randomAlphaOfLength(16);
// This cgroup data is missing a line about cpuacct
List<String> procSelfCgroupLines = getProcSelfGroupLines(1, hierarchy).stream()
.map(line -> line.replaceFirst(",cpuacct", ""))
.toList();
final OsProbe probe = buildStubOsProbe(1, hierarchy, procSelfCgroupLines);
final OsStats.Cgroup cgroup = probe.osStats().getCgroup();
assertNull(cgroup);
}
public void testCgroupProbeWithMissingCpu() {
final String hierarchy = randomAlphaOfLength(16);
// This cgroup data is missing a line about cpu
List<String> procSelfCgroupLines = getProcSelfGroupLines(1, hierarchy).stream()
.map(line -> line.replaceFirst(":cpu,", ":"))
.toList();
final OsProbe probe = buildStubOsProbe(1, hierarchy, procSelfCgroupLines);
final OsStats.Cgroup cgroup = probe.osStats().getCgroup();
assertNull(cgroup);
}
public void testCgroupProbeWithMissingMemory() {
final String hierarchy = randomAlphaOfLength(16);
// This cgroup data is missing a line about memory
List<String> procSelfCgroupLines = getProcSelfGroupLines(1, hierarchy).stream()
.filter(line -> line.contains(":memory:") == false)
.toList();
final OsProbe probe = buildStubOsProbe(1, hierarchy, procSelfCgroupLines);
final OsStats.Cgroup cgroup = probe.osStats().getCgroup();
assertNull(cgroup);
}
public void testGetTotalMemFromProcMeminfo() throws Exception {
int cgroupsVersion = randomFrom(1, 2);
// missing MemTotal line
var meminfoLines = Arrays.asList(
"MemFree: 8467692 kB",
"MemAvailable: 39646240 kB",
"Buffers: 4699504 kB",
"Cached: 23290380 kB",
"SwapCached: 0 kB",
"Active: 43637908 kB",
"Inactive: 8130280 kB"
);
OsProbe probe = buildStubOsProbe(cgroupsVersion, "", List.of(), meminfoLines);
assertThat(probe.getTotalMemFromProcMeminfo(), equalTo(0L));
// MemTotal line with invalid value
meminfoLines = Arrays.asList(
"MemTotal: invalid kB",
"MemFree: 8467692 kB",
"MemAvailable: 39646240 kB",
"Buffers: 4699504 kB",
"Cached: 23290380 kB",
"SwapCached: 0 kB",
"Active: 43637908 kB",
"Inactive: 8130280 kB"
);
probe = buildStubOsProbe(cgroupsVersion, "", List.of(), meminfoLines);
assertThat(probe.getTotalMemFromProcMeminfo(), equalTo(0L));
// MemTotal line with invalid unit
meminfoLines = Arrays.asList(
"MemTotal: 39646240 MB",
"MemFree: 8467692 kB",
"MemAvailable: 39646240 kB",
"Buffers: 4699504 kB",
"Cached: 23290380 kB",
"SwapCached: 0 kB",
"Active: 43637908 kB",
"Inactive: 8130280 kB"
);
probe = buildStubOsProbe(cgroupsVersion, "", List.of(), meminfoLines);
assertThat(probe.getTotalMemFromProcMeminfo(), equalTo(0L));
// MemTotal line with random valid value
long memTotalInKb = randomLongBetween(1, Long.MAX_VALUE / 1024L);
meminfoLines = Arrays.asList(
"MemTotal: " + memTotalInKb + " kB",
"MemFree: 8467692 kB",
"MemAvailable: 39646240 kB",
"Buffers: 4699504 kB",
"Cached: 23290380 kB",
"SwapCached: 0 kB",
"Active: 43637908 kB",
"Inactive: 8130280 kB"
);
probe = buildStubOsProbe(cgroupsVersion, "", List.of(), meminfoLines);
assertThat(probe.getTotalMemFromProcMeminfo(), equalTo(memTotalInKb * 1024L));
}
public void testTotalMemoryOverride() {
assertThat(OsProbe.getTotalMemoryOverride("123456789"), is(123456789L));
assertThat(OsProbe.getTotalMemoryOverride("123456789123456789"), is(123456789123456789L));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> OsProbe.getTotalMemoryOverride("-1"));
assertThat(e.getMessage(), is("Negative memory size specified in [es.total_memory_bytes]: [-1]"));
e = expectThrows(IllegalArgumentException.class, () -> OsProbe.getTotalMemoryOverride("abc"));
assertThat(e.getMessage(), is("Invalid value for [es.total_memory_bytes]: [abc]"));
// Although numeric, this value overflows long. This won't be a problem in practice for sensible
// overrides, as it will be a very long time before machines have more than 8 exabytes of RAM.
e = expectThrows(IllegalArgumentException.class, () -> OsProbe.getTotalMemoryOverride("123456789123456789123456789"));
assertThat(e.getMessage(), is("Invalid value for [es.total_memory_bytes]: [123456789123456789123456789]"));
}
public void testGetTotalMemoryOnDebian8() throws Exception {
// tests the workaround for JDK bug on debian8: https://github.com/elastic/elasticsearch/issues/67089#issuecomment-756114654
final OsProbe osProbe = new OsProbe();
assumeTrue("runs only on Debian 8", osProbe.isDebian8());
assertThat(osProbe.getTotalPhysicalMemorySize(), greaterThan(0L));
}
private static List<String> getProcSelfGroupLines(int cgroupsVersion, String hierarchy) {
// It doesn't really matter if cgroupsVersion == 0 here
if (cgroupsVersion == 2) {
return List.of("0::/" + hierarchy);
}
return Arrays.asList(
"10:freezer:/",
"9:net_cls,net_prio:/",
"8:pids:/",
"7:blkio:/",
"6:memory:/" + hierarchy,
"5:devices:/user.slice",
"4:hugetlb:/",
"3:perf_event:/",
"2:cpu,cpuacct,cpuset:/" + hierarchy,
"1:name=systemd:/user.slice/user-1000.slice/session-2359.scope",
"0::/cgroup2"
);
}
private static OsProbe buildStubOsProbe(final int availableCgroupsVersion, final String hierarchy) {
List<String> procSelfCgroupLines = getProcSelfGroupLines(availableCgroupsVersion, hierarchy);
return buildStubOsProbe(availableCgroupsVersion, hierarchy, procSelfCgroupLines);
}
/**
* Builds a test instance of OsProbe. Methods that ordinarily read from the filesystem are overridden to return values based upon
* the arguments to this method.
*
* @param availableCgroupsVersion what version of cgroups are available, 1 or 2, or 0 for no cgroups. Normally OsProbe establishes this
* for itself.
* @param hierarchy a mock value used to generate a cgroup hierarchy.
* @param procSelfCgroupLines the lines that will be used as the content of <code>/proc/self/cgroup</code>
* @param procMeminfoLines lines that will be used as the content of <code>/proc/meminfo</code>
* @return a test instance
*/
private static OsProbe buildStubOsProbe(
final int availableCgroupsVersion,
final String hierarchy,
List<String> procSelfCgroupLines,
List<String> procMeminfoLines
) {
return new OsProbe() {
@Override
OsStats.Cgroup getCgroup(boolean isLinux) {
// Pretend we're always on Linux so that we can run the cgroup tests
return super.getCgroup(true);
}
@Override
List<String> readProcSelfCgroup() {
return procSelfCgroupLines;
}
@Override
String readSysFsCgroupCpuAcctCpuAcctUsage(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return "364869866063112";
}
@Override
String readSysFsCgroupCpuAcctCpuCfsPeriod(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return "100000";
}
@Override
String readSysFsCgroupCpuAcctCpuAcctCfsQuota(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return "50000";
}
@Override
List<String> readSysFsCgroupCpuAcctCpuStat(String controlGroup) {
return Arrays.asList("nr_periods 17992", "nr_throttled 1311", "throttled_time 139298645489");
}
@Override
String readSysFsCgroupMemoryLimitInBytes(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
// This is the highest value that can be stored in an unsigned 64 bit number, hence too big for long
return "18446744073709551615";
}
@Override
String readSysFsCgroupMemoryUsageInBytes(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return "4796416";
}
@Override
boolean areCgroupStatsAvailable() {
return availableCgroupsVersion > 0;
}
@Override
List<String> readProcMeminfo() {
return procMeminfoLines;
}
@Override
String readSysFsCgroupV2MemoryLimitInBytes(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
// This is the highest value that can be stored in an unsigned 64 bit number, hence too big for long
return "18446744073709551615";
}
@Override
String readSysFsCgroupV2MemoryUsageInBytes(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return "4796416";
}
@Override
List<String> readCgroupV2CpuStats(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return List.of(
"usage_usec 364869866063",
"user_usec 34636",
"system_usec 9896",
"nr_periods 17992",
"nr_throttled 1311",
"throttled_usec 139298645"
);
}
@Override
String readCgroupV2CpuLimit(String controlGroup) {
assertThat(controlGroup, equalTo("/" + hierarchy));
return "50000 100000";
}
};
}
private static OsProbe buildStubOsProbe(final int availableCgroupsVersion, final String hierarchy, List<String> procSelfCgroupLines) {
return buildStubOsProbe(availableCgroupsVersion, hierarchy, procSelfCgroupLines, List.of());
}
}
| OsProbeTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_1594/Issue1594Mapper.java | {
"start": 1573,
"end": 1825
} | class ____ {
private String fullAddress;
public String getFullAddress() {
return fullAddress;
}
public void setFullAddress(String fullAddress) {
this.fullAddress = fullAddress;
}
}
}
| Dto |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/consumer/TopicMessageQueueChangeListener.java | {
"start": 934,
"end": 1243
} | interface ____ {
/**
* This method will be invoked in the condition of queue numbers changed, These scenarios occur when the topic is
* expanded or shrunk.
*
* @param messageQueues
*/
void onChanged(String topic, Set<MessageQueue> messageQueues);
}
| TopicMessageQueueChangeListener |
java | quarkusio__quarkus | devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/examples/google-cloud-functions-http-example/java/src/main/java/org/acme/googlecloudfunctions/GreetingRoutes.java | {
"start": 185,
"end": 667
} | class ____ {
@Route(path = "/vertx/hello", methods = GET)
void hello(RoutingContext context) {
context.response().headers().set("Content-Type", "text/plain");
context.response().setStatusCode(200).end("hello");
}
@Route(path = "/vertx/error", methods = GET)
void error(RoutingContext context) {
context.response().headers().set("Content-Type", "text/plain");
context.response().setStatusCode(500).end("Oups!");
}
}
| GreetingRoutes |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToAggregateMetricDouble.java | {
"start": 7212,
"end": 11368
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final EvalOperator.ExpressionEvaluator.Factory fieldEvaluator;
public DoubleFactory(EvalOperator.ExpressionEvaluator.Factory fieldEvaluator) {
this.fieldEvaluator = fieldEvaluator;
}
@Override
public String toString() {
return "ToAggregateMetricDoubleFromDoubleEvaluator[" + "field=" + fieldEvaluator + "]";
}
@Override
public EvalOperator.ExpressionEvaluator get(DriverContext context) {
return new DoubleEvaluator(context.blockFactory(), fieldEvaluator.get(context));
}
}
public record DoubleEvaluator(BlockFactory blockFactory, EvalOperator.ExpressionEvaluator eval)
implements
EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DoubleEvaluator.class);
private Block evalBlock(Block block) {
int positionCount = block.getPositionCount();
DoubleBlock doubleBlock = (DoubleBlock) block;
try (AggregateMetricDoubleBlockBuilder builder = blockFactory.newAggregateMetricDoubleBlockBuilder(positionCount)) {
CompensatedSum compensatedSum = new CompensatedSum();
for (int p = 0; p < positionCount; p++) {
int valueCount = doubleBlock.getValueCount(p);
if (valueCount == 0) {
builder.appendNull();
continue;
}
int start = doubleBlock.getFirstValueIndex(p);
int end = start + valueCount;
if (valueCount == 1) {
double current = doubleBlock.getDouble(start);
builder.min().appendDouble(current);
builder.max().appendDouble(current);
builder.sum().appendDouble(current);
builder.count().appendInt(valueCount);
continue;
}
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = start; i < end; i++) {
double current = doubleBlock.getDouble(i);
min = Math.min(min, current);
max = Math.max(max, current);
compensatedSum.add(current);
}
builder.min().appendDouble(min);
builder.max().appendDouble(max);
builder.sum().appendDouble(compensatedSum.value());
builder.count().appendInt(valueCount);
compensatedSum.reset(0, 0);
}
return builder.build();
}
}
private Block evalVector(Vector vector) {
int positionCount = vector.getPositionCount();
DoubleVector doubleVector = (DoubleVector) vector;
try (AggregateMetricDoubleVectorBuilder builder = new AggregateMetricDoubleVectorBuilder(positionCount, blockFactory)) {
for (int p = 0; p < positionCount; p++) {
double value = doubleVector.getDouble(p);
builder.appendValue(value);
}
return builder.build();
}
}
@Override
public Block eval(Page page) {
try (Block block = eval.eval(page)) {
Vector vector = block.asVector();
return vector == null ? evalBlock(block) : evalVector(vector);
}
}
@Override
public void close() {
Releasables.closeExpectNoException(eval);
}
@Override
public long baseRamBytesUsed() {
return BASE_RAM_BYTES_USED + eval.baseRamBytesUsed();
}
@Override
public String toString() {
return "ToAggregateMetricDoubleFromDoubleEvaluator[field=" + eval + "]";
}
}
public static | DoubleFactory |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/extractor/GeoShapeField.java | {
"start": 804,
"end": 3527
} | class ____ extends SourceField {
static final String TYPE = "geo_shape";
private static final Set<String> TYPES = Collections.singleton(TYPE);
public GeoShapeField(String name) {
super(name, TYPES);
}
@Override
public Object[] value(SearchHit hit, SourceSupplier source) {
Object[] value = super.value(hit, source);
if (value.length == 0) {
return value;
}
if (value.length > 1) {
throw new IllegalStateException("Unexpected values for a geo_shape field: " + Arrays.toString(value));
}
if (value[0] instanceof String stringValue) {
value[0] = handleString(stringValue);
} else if (value[0] instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, Object> geoObject = (Map<String, Object>) value[0];
value[0] = handleObject(geoObject);
} else {
throw new IllegalStateException("Unexpected value type for a geo_shape field: " + value[0].getClass());
}
return value;
}
private static String handleString(String geoString) {
try {
if (geoString.startsWith("POINT")) { // Entry is of the form "POINT (-77.03653 38.897676)"
Geometry geometry = WellKnownText.fromWKT(StandardValidator.instance(true), true, geoString);
if (geometry.type() != ShapeType.POINT) {
throw new IllegalArgumentException("Unexpected non-point geo_shape type: " + geometry.type().name());
}
Point pt = ((Point) geometry);
return pt.getY() + "," + pt.getX();
} else {
throw new IllegalArgumentException("Unexpected value for a geo_shape field: " + geoString);
}
} catch (IOException | ParseException ex) {
throw new IllegalArgumentException("Unexpected value for a geo_shape field: " + geoString);
}
}
private static String handleObject(Map<String, Object> geoObject) {
String geoType = (String) geoObject.get("type");
if (geoType != null && "point".equals(geoType.toLowerCase(Locale.ROOT))) {
@SuppressWarnings("unchecked")
List<Double> coordinates = (List<Double>) geoObject.get("coordinates");
if (coordinates == null || coordinates.size() != 2) {
throw new IllegalArgumentException("Invalid coordinates for geo_shape point: " + geoObject);
}
return coordinates.get(1) + "," + coordinates.get(0);
} else {
throw new IllegalArgumentException("Unexpected value for a geo_shape field: " + geoObject);
}
}
}
| GeoShapeField |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/files/Files_assertIsRelative_Test.java | {
"start": 1388,
"end": 2198
} | class ____ extends FilesBaseTest {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
File actual = null;
// WHEN
var assertionError = expectAssertionError(() -> underTest.assertIsRelative(INFO, actual));
// THEN
then(assertionError).hasMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_not_relative_path() {
// GIVEN
File actual = newFile(tempDir.getAbsolutePath() + "/Test.java");
// WHEN
expectAssertionError(() -> underTest.assertIsRelative(INFO, actual));
// THEN
verify(failures).failure(INFO, shouldBeRelativePath(actual));
}
@Test
void should_pass_if_actual_is_relative_path() {
// GIVEN
File actual = new File("file.txt");
// THEN
underTest.assertIsRelative(INFO, actual);
}
}
| Files_assertIsRelative_Test |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/examples/ConnectToMasterSlaveUsingRedisSentinel.java | {
"start": 340,
"end": 1005
} | class ____ {
public static void main(String[] args) {
// Syntax: redis-sentinel://[password@]host[:port][,host2[:port2]][/databaseNumber]#sentinelMasterId
RedisClient redisClient = RedisClient.create();
StatefulRedisMasterReplicaConnection<String, String> connection = MasterReplica.connect(redisClient, StringCodec.UTF8,
RedisURI.create("redis-sentinel://localhost:26379,localhost:26380/0#mymaster"));
connection.setReadFrom(ReadFrom.UPSTREAM_PREFERRED);
System.out.println("Connected to Redis");
connection.close();
redisClient.shutdown();
}
}
| ConnectToMasterSlaveUsingRedisSentinel |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/instrument/classloading/LoadTimeWeaver.java | {
"start": 1125,
"end": 2332
} | interface ____ {
/**
* Add a {@code ClassFileTransformer} to be applied by this
* {@code LoadTimeWeaver}.
* @param transformer the {@code ClassFileTransformer} to add
*/
void addTransformer(ClassFileTransformer transformer);
/**
* Return a {@code ClassLoader} that supports instrumentation
* through AspectJ-style load-time weaving based on user-defined
* {@link ClassFileTransformer ClassFileTransformers}.
* <p>May be the current {@code ClassLoader}, or a {@code ClassLoader}
* created by this {@link LoadTimeWeaver} instance.
* @return the {@code ClassLoader} which will expose
* instrumented classes according to the registered transformers
*/
ClassLoader getInstrumentableClassLoader();
/**
* Return a throwaway {@code ClassLoader}, enabling classes to be
* loaded and inspected without affecting the parent {@code ClassLoader}.
* <p>Should <i>not</i> return the same instance of the {@link ClassLoader}
* returned from an invocation of {@link #getInstrumentableClassLoader()}.
* @return a temporary throwaway {@code ClassLoader}; should return
* a new instance for each call, with no existing state
*/
ClassLoader getThrowawayClassLoader();
}
| LoadTimeWeaver |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/IdGeneratorType.java | {
"start": 787,
"end": 1327
} | class ____ implements BeforeExecutionGenerator {
* public CustomSequenceGenerator(CustomSequence config, Member annotatedMember,
* GeneratorCreationContext context) {
* ...
* }
* ...
* }
* </pre>
* <p>
* Then we may also define an annotation which associates this generator with
* an entity and supplies configuration parameters:
* <pre>
* @IdGeneratorType(CustomSequenceGenerator.class)
* @Retention(RUNTIME) @Target({METHOD,FIELD})
* public @ | CustomSequenceGenerator |
java | grpc__grpc-java | util/src/jmh/java/io/grpc/util/HandlerRegistryBenchmark.java | {
"start": 1376,
"end": 3772
} | class ____ {
private static final String VALID_CHARACTERS =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.";
@Param({"50"})
public int nameLength;
@Param({"100"})
public int serviceCount;
@Param({"100"})
public int methodCountPerService;
private MutableHandlerRegistry registry;
private List<String> fullMethodNames;
/**
* Set up the registry.
*/
@Setup(Level.Trial)
public void setup() throws Exception {
registry = new MutableHandlerRegistry();
fullMethodNames = new ArrayList<>(serviceCount * methodCountPerService);
for (int serviceIndex = 0; serviceIndex < serviceCount; ++serviceIndex) {
String serviceName = randomString();
ServerServiceDefinition.Builder serviceBuilder = ServerServiceDefinition.builder(serviceName);
for (int methodIndex = 0; methodIndex < methodCountPerService; ++methodIndex) {
String methodName = randomString();
MethodDescriptor<Void, Void> methodDescriptor = MethodDescriptor.<Void, Void>newBuilder()
.setType(MethodDescriptor.MethodType.UNKNOWN)
.setFullMethodName(MethodDescriptor.generateFullMethodName(serviceName, methodName))
.setRequestMarshaller(TestMethodDescriptors.voidMarshaller())
.setResponseMarshaller(TestMethodDescriptors.voidMarshaller())
.build();
serviceBuilder.addMethod(methodDescriptor,
new ServerCallHandler<Void, Void>() {
@Override
public Listener<Void> startCall(ServerCall<Void, Void> call,
Metadata headers) {
return null;
}
});
fullMethodNames.add(methodDescriptor.getFullMethodName());
}
registry.addService(serviceBuilder.build());
}
}
/**
* Benchmark the {@link MutableHandlerRegistry#lookupMethod(String)} throughput.
*/
@Benchmark
public void lookupMethod(Blackhole bh) {
for (String fullMethodName : fullMethodNames) {
bh.consume(registry.lookupMethod(fullMethodName));
}
}
private String randomString() {
Random r = new Random();
char[] bytes = new char[nameLength];
for (int ix = 0; ix < nameLength; ++ix) {
int charIx = r.nextInt(VALID_CHARACTERS.length());
bytes[ix] = VALID_CHARACTERS.charAt(charIx);
}
return new String(bytes);
}
}
| HandlerRegistryBenchmark |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/AnyDiscriminator.java | {
"start": 1467,
"end": 1713
} | interface ____ {
/// The type of the discriminator, as a JPA [DiscriminatorType].
/// For more precise specification of the type, use [JdbcType]
/// or [JdbcTypeCode].
DiscriminatorType value() default DiscriminatorType.STRING;
}
| AnyDiscriminator |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/inheritance/QualifiersInheritanceTest.java | {
"start": 1752,
"end": 1851
} | class ____ extends SuperBean {
}
@Inherited
@Qualifier
@Retention(RUNTIME)
@ | Bravo |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/AbstractClassAssert.java | {
"start": 3757,
"end": 4171
} | class ____<SELF extends AbstractClassAssert<SELF>>
extends AbstractAssertWithComparator<SELF, Class<?>> {
Classes classes = Classes.instance();
protected AbstractClassAssert(Class<?> actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the actual {@code Class} is assignable from others {@code Class}
* <p>
* Example:
* <pre><code class='java'> | AbstractClassAssert |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/ChoiceWhenBeanExpressionWithExceptionTest.java | {
"start": 1200,
"end": 3252
} | class ____ extends ContextTestSupport {
private MockEndpoint gradeA;
private MockEndpoint otherGrade;
protected void verifyGradeA(String endpointUri) throws Exception {
gradeA.reset();
otherGrade.reset();
gradeA.expectedMessageCount(0);
otherGrade.expectedMessageCount(0);
try {
template.sendBody(endpointUri, new Student(95));
fail();
} catch (CamelExecutionException e) {
// expected
}
assertMockEndpointsSatisfied();
}
public void verifyOtherGrade(String endpointUri) throws Exception {
gradeA.reset();
otherGrade.reset();
gradeA.expectedMessageCount(0);
otherGrade.expectedMessageCount(0);
try {
template.sendBody(endpointUri, new Student(60));
fail();
} catch (CamelExecutionException e) {
// expected
}
assertMockEndpointsSatisfied();
}
@Test
public void testBeanExpression() throws Exception {
verifyGradeA("direct:expression");
verifyOtherGrade("direct:expression");
}
@Test
public void testMethod() throws Exception {
verifyGradeA("direct:method");
verifyOtherGrade("direct:method");
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
gradeA = getMockEndpoint("mock:gradeA");
otherGrade = getMockEndpoint("mock:otherGrade");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:expression").choice().when(method(MyBean.class, "isGradeA")).to("mock:gradeA").otherwise()
.to("mock:otherGrade").end();
from("direct:method").choice().when().method(MyBean.class).to("mock:gradeA").otherwise().to("mock:otherGrade")
.end();
}
};
}
public static | ChoiceWhenBeanExpressionWithExceptionTest |
java | google__auto | value/src/main/java/com/google/auto/value/processor/AutoValueishProcessor.java | {
"start": 58455,
"end": 59531
} | class ____<T extends Something>} then this method will
* return just {@code <?>}.
*/
private static String wildcardTypeParametersString(TypeElement type) {
List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
if (typeParameters.isEmpty()) {
return "";
} else {
return typeParameters.stream().map(e -> "?").collect(joining(", ", "<", ">"));
}
}
// TODO(emcmanus,ronshapiro): move to auto-common
static Optional<AnnotationMirror> getAnnotationMirror(Element element, String annotationName) {
for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
TypeElement annotationElement = MoreTypes.asTypeElement(annotation.getAnnotationType());
if (annotationElement.getQualifiedName().contentEquals(annotationName)) {
return Optional.of(annotation);
}
}
return Optional.empty();
}
static boolean hasAnnotationMirror(Element element, String annotationName) {
return getAnnotationMirror(element, annotationName).isPresent();
}
/** True if the type is a | Foo |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/aggregate/LastOverTimeTests.java | {
"start": 1340,
"end": 5284
} | class ____ extends AbstractAggregationTestCase {
public LastOverTimeTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) {
this.testCase = testCaseSupplier.get();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
var suppliers = new ArrayList<TestCaseSupplier>();
var valuesSuppliers = List.of(
MultiRowTestCaseSupplier.longCases(1, 1000, Long.MIN_VALUE, Long.MAX_VALUE, true),
MultiRowTestCaseSupplier.intCases(1, 1000, Integer.MIN_VALUE, Integer.MAX_VALUE, true),
MultiRowTestCaseSupplier.doubleCases(1, 1000, -Double.MAX_VALUE, Double.MAX_VALUE, true),
MultiRowTestCaseSupplier.tsidCases(1, 1000)
);
for (List<TestCaseSupplier.TypedDataSupplier> valuesSupplier : valuesSuppliers) {
for (TestCaseSupplier.TypedDataSupplier fieldSupplier : valuesSupplier) {
DataType type = fieldSupplier.type();
suppliers.add(makeSupplier(fieldSupplier, type));
switch (type) {
case LONG -> suppliers.add(makeSupplier(fieldSupplier, DataType.COUNTER_LONG));
case DOUBLE -> suppliers.add(makeSupplier(fieldSupplier, DataType.COUNTER_DOUBLE));
case INTEGER -> suppliers.add(makeSupplier(fieldSupplier, DataType.COUNTER_INTEGER));
}
}
}
return parameterSuppliersFromTypedDataWithDefaultChecks(suppliers);
}
@Override
protected Expression build(Source source, List<Expression> args) {
return new LastOverTime(source, args.get(0), AggregateFunction.NO_WINDOW, args.get(1));
}
@Override
public void testAggregate() {
assumeTrue("time-series aggregation doesn't support ungrouped", false);
}
@Override
public void testAggregateIntermediate() {
assumeTrue("time-series aggregation doesn't support ungrouped", false);
}
private static TestCaseSupplier makeSupplier(TestCaseSupplier.TypedDataSupplier fieldSupplier, DataType type) {
return new TestCaseSupplier(fieldSupplier.name(), List.of(type, DataType.DATETIME), () -> {
TestCaseSupplier.TypedData fieldTypedData = fieldSupplier.get();
List<Object> dataRows = fieldTypedData.multiRowData();
fieldTypedData = TestCaseSupplier.TypedData.multiRow(dataRows, type, fieldTypedData.name());
List<Long> timestamps = IntStream.range(0, dataRows.size()).mapToLong(unused -> randomNonNegativeLong()).boxed().toList();
TestCaseSupplier.TypedData timestampsField = TestCaseSupplier.TypedData.multiRow(timestamps, DataType.DATETIME, "timestamps");
Object expected = null;
long lastTimestamp = Long.MIN_VALUE;
for (int i = 0; i < dataRows.size(); i++) {
if (i == 0) {
expected = dataRows.get(i);
lastTimestamp = timestamps.get(i);
} else if (timestamps.get(i) > lastTimestamp) {
expected = dataRows.get(i);
lastTimestamp = timestamps.get(i);
}
}
return new TestCaseSupplier.TestCase(
List.of(fieldTypedData, timestampsField),
standardAggregatorName("Last", type) + "ByTimestamp",
fieldSupplier.type(),
equalTo(expected)
);
});
}
public static List<DocsV3Support.Param> signatureTypes(List<DocsV3Support.Param> params) {
assertThat(params, hasSize(2));
assertThat(params.get(1).dataType(), equalTo(DataType.DATETIME));
var preview = appliesTo(FunctionAppliesToLifecycle.PREVIEW, "9.3.0", "", false);
DocsV3Support.Param window = new DocsV3Support.Param(DataType.TIME_DURATION, List.of(preview));
return List.of(params.get(0), window);
}
}
| LastOverTimeTests |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FSDataInputStream.java | {
"start": 1825,
"end": 10603
} | class ____ extends DataInputStream
implements Seekable, PositionedReadable,
ByteBufferReadable, HasFileDescriptor, CanSetDropBehind, CanSetReadahead,
HasEnhancedByteBufferAccess, CanUnbuffer, StreamCapabilities,
ByteBufferPositionedReadable, IOStatisticsSource {
/**
* Map ByteBuffers that we have handed out to readers to ByteBufferPool
* objects
*/
private final IdentityHashStore<ByteBuffer, ByteBufferPool>
extendedReadBuffers
= new IdentityHashStore<>(0);
public FSDataInputStream(InputStream in) {
super(in);
if( !(in instanceof Seekable) || !(in instanceof PositionedReadable) ) {
throw new IllegalArgumentException(in.getClass().getCanonicalName() +
" is not an instance of Seekable or PositionedReadable");
}
}
/**
* Seek to the given offset.
*
* @param desired offset to seek to
*/
@Override
public void seek(long desired) throws IOException {
((Seekable)in).seek(desired);
}
/**
* Get the current position in the input stream.
*
* @return current position in the input stream
*/
@Override
public long getPos() throws IOException {
return ((Seekable)in).getPos();
}
/**
* Read bytes from the given position in the stream to the given buffer.
*
* @param position position in the input stream to seek
* @param buffer buffer into which data is read
* @param offset offset into the buffer in which data is written
* @param length maximum number of bytes to read
* @return total number of bytes read into the buffer, or <code>-1</code>
* if there is no more data because the end of the stream has been
* reached
*/
@Override
public int read(long position, byte[] buffer, int offset, int length)
throws IOException {
return ((PositionedReadable)in).read(position, buffer, offset, length);
}
/**
* Read bytes from the given position in the stream to the given buffer.
* Continues to read until <code>length</code> bytes have been read.
*
* @param position position in the input stream to seek
* @param buffer buffer into which data is read
* @param offset offset into the buffer in which data is written
* @param length the number of bytes to read
* @throws IOException IO problems
* @throws EOFException If the end of stream is reached while reading.
* If an exception is thrown an undetermined number
* of bytes in the buffer may have been written.
*/
@Override
public void readFully(long position, byte[] buffer, int offset, int length)
throws IOException {
((PositionedReadable)in).readFully(position, buffer, offset, length);
}
/**
* See {@link #readFully(long, byte[], int, int)}.
*/
@Override
public void readFully(long position, byte[] buffer)
throws IOException {
((PositionedReadable)in).readFully(position, buffer, 0, buffer.length);
}
/**
* Seek to the given position on an alternate copy of the data.
*
* @param targetPos position to seek to
* @return true if a new source is found, false otherwise
*/
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
return ((Seekable)in).seekToNewSource(targetPos);
}
/**
* Get a reference to the wrapped input stream. Used by unit tests.
*
* @return the underlying input stream
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public InputStream getWrappedStream() {
return in;
}
@Override
public int read(ByteBuffer buf) throws IOException {
if (in instanceof ByteBufferReadable) {
return ((ByteBufferReadable)in).read(buf);
}
throw new UnsupportedOperationException("Byte-buffer read unsupported " +
"by " + in.getClass().getCanonicalName());
}
@Override
public FileDescriptor getFileDescriptor() throws IOException {
if (in instanceof HasFileDescriptor) {
return ((HasFileDescriptor) in).getFileDescriptor();
} else if (in instanceof FileInputStream) {
return ((FileInputStream) in).getFD();
} else {
return null;
}
}
@Override
public void setReadahead(Long readahead)
throws IOException, UnsupportedOperationException {
try {
((CanSetReadahead)in).setReadahead(readahead);
} catch (ClassCastException e) {
throw new UnsupportedOperationException(in.getClass().getCanonicalName() +
" does not support setting the readahead caching strategy.");
}
}
@Override
public void setDropBehind(Boolean dropBehind)
throws IOException, UnsupportedOperationException {
try {
((CanSetDropBehind)in).setDropBehind(dropBehind);
} catch (ClassCastException e) {
throw new UnsupportedOperationException("this stream does not " +
"support setting the drop-behind caching setting.");
}
}
@Override
public ByteBuffer read(ByteBufferPool bufferPool, int maxLength,
EnumSet<ReadOption> opts)
throws IOException, UnsupportedOperationException {
try {
return ((HasEnhancedByteBufferAccess)in).read(bufferPool,
maxLength, opts);
}
catch (ClassCastException e) {
ByteBuffer buffer = ByteBufferUtil.
fallbackRead(this, bufferPool, maxLength);
if (buffer != null) {
extendedReadBuffers.put(buffer, bufferPool);
}
return buffer;
}
}
private static final EnumSet<ReadOption> EMPTY_READ_OPTIONS_SET =
EnumSet.noneOf(ReadOption.class);
final public ByteBuffer read(ByteBufferPool bufferPool, int maxLength)
throws IOException, UnsupportedOperationException {
return read(bufferPool, maxLength, EMPTY_READ_OPTIONS_SET);
}
@Override
public void releaseBuffer(ByteBuffer buffer) {
try {
((HasEnhancedByteBufferAccess)in).releaseBuffer(buffer);
}
catch (ClassCastException e) {
ByteBufferPool bufferPool = extendedReadBuffers.remove( buffer);
if (bufferPool == null) {
throw new IllegalArgumentException("tried to release a buffer " +
"that was not created by this stream.");
}
bufferPool.putBuffer(buffer);
}
}
@Override
public void unbuffer() {
StreamCapabilitiesPolicy.unbuffer(in);
}
@Override
public boolean hasCapability(String capability) {
return StoreImplementationUtils.hasCapability(in, capability);
}
/**
* String value. Includes the string value of the inner stream
* @return the stream
*/
@Override
public String toString() {
return super.toString() + ": " + in;
}
@Override
public int read(long position, ByteBuffer buf) throws IOException {
if (in instanceof ByteBufferPositionedReadable) {
return ((ByteBufferPositionedReadable) in).read(position, buf);
}
throw new UnsupportedOperationException("Byte-buffer pread unsupported " +
"by " + in.getClass().getCanonicalName());
}
/**
* Delegate to the underlying stream.
* @param position position within file
* @param buf the ByteBuffer to receive the results of the read operation.
* @throws IOException on a failure from the nested stream.
* @throws UnsupportedOperationException if the inner stream does not
* support this operation.
*/
@Override
public void readFully(long position, ByteBuffer buf) throws IOException {
if (in instanceof ByteBufferPositionedReadable) {
((ByteBufferPositionedReadable) in).readFully(position, buf);
} else {
throw new UnsupportedOperationException("Byte-buffer pread " +
"unsupported by " + in.getClass().getCanonicalName());
}
}
/**
* Get the IO Statistics of the nested stream, falling back to
* null if the stream does not implement the interface
* {@link IOStatisticsSource}.
* @return an IOStatistics instance or null
*/
@Override
public IOStatistics getIOStatistics() {
return IOStatisticsSupport.retrieveIOStatistics(in);
}
@Override
public int minSeekForVectorReads() {
return ((PositionedReadable) in).minSeekForVectorReads();
}
@Override
public int maxReadSizeForVectorReads() {
return ((PositionedReadable) in).maxReadSizeForVectorReads();
}
@Override
public void readVectored(List<? extends FileRange> ranges,
IntFunction<ByteBuffer> allocate) throws IOException {
((PositionedReadable) in).readVectored(ranges, allocate);
}
@Override
public void readVectored(final List<? extends FileRange> ranges,
final IntFunction<ByteBuffer> allocate,
final Consumer<ByteBuffer> release) throws IOException {
((PositionedReadable) in).readVectored(ranges, allocate, release);
}
}
| FSDataInputStream |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/DiscoveryTests.java | {
"start": 3125,
"end": 12965
} | class ____ extends AbstractJupiterTestEngineTests {
@Test
void discoverTestClass() {
LauncherDiscoveryRequest request = defaultRequest().selectors(selectClass(LocalTestCase.class)).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(7, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void doNotDiscoverAbstractTestClass() {
LauncherDiscoveryRequest request = defaultRequest().selectors(selectClass(AbstractTestCase.class)).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(0, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@ParameterizedTest
@ValueSource(strings = { "org.junit.jupiter.engine.discovery.DiscoveryTests$InterfaceTestCase",
"org.junit.jupiter.engine.kotlin.KotlinInterfaceTestCase" })
void doNotDiscoverTestInterface(String className) {
assumeFalse(runningInEclipse() && className.contains(".kotlin."));
LauncherDiscoveryRequest request = defaultRequest().selectors(selectClass(className)).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(0, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
@DisabledInEclipse
void doNotDiscoverGeneratedKotlinDefaultImplsClass() {
LauncherDiscoveryRequest request = defaultRequest() //
.selectors(selectClass("org.junit.jupiter.engine.kotlin.KotlinInterfaceTestCase$DefaultImpls")) //
.build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(0, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
@DisabledInEclipse
void discoverDeclaredKotlinDefaultImplsClass() {
LauncherDiscoveryRequest request = defaultRequest().selectors(
selectClass("org.junit.jupiter.engine.kotlin.KotlinDefaultImplsTestCase$DefaultImpls")).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@ParameterizedTest
@ValueSource(strings = {
"org.junit.jupiter.engine.discovery.DiscoveryTests$ConcreteImplementationOfInterfaceTestCase",
"org.junit.jupiter.engine.kotlin.KotlinInterfaceImplementationTestCase" })
void discoverTestClassInheritingTestsFromInterface(String className) {
assumeFalse(runningInEclipse() && className.contains(".kotlin."));
LauncherDiscoveryRequest request = defaultRequest().selectors(selectClass(className)).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverMethodByUniqueId() {
LauncherDiscoveryRequest request = defaultRequest().selectors(
selectUniqueId(JupiterUniqueIdBuilder.uniqueIdForMethod(LocalTestCase.class, "test1()"))).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverMethodByUniqueIdForOverloadedMethod() {
LauncherDiscoveryRequest request = defaultRequest().selectors(
selectUniqueId(JupiterUniqueIdBuilder.uniqueIdForMethod(LocalTestCase.class, "test4()"))).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverMethodByUniqueIdForOverloadedMethodVariantThatAcceptsArguments() {
LauncherDiscoveryRequest request = defaultRequest().selectors(
selectUniqueId(JupiterUniqueIdBuilder.uniqueIdForMethod(LocalTestCase.class,
"test4(" + TestInfo.class.getName() + ")"))).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverMethodByMethodReference() throws NoSuchMethodException {
Method testMethod = LocalTestCase.class.getDeclaredMethod("test3");
LauncherDiscoveryRequest request = defaultRequest().selectors(
selectMethod(LocalTestCase.class, testMethod)).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverMultipleMethodsOfSameClass() {
LauncherDiscoveryRequest request = defaultRequest().selectors(selectMethod(LocalTestCase.class, "test1"),
selectMethod(LocalTestCase.class, "test2")).build();
TestDescriptor engineDescriptor = discoverTestsWithoutIssues(request);
assertThat(engineDescriptor.getChildren()).hasSize(1);
TestDescriptor classDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertThat(classDescriptor.getChildren()).hasSize(2);
}
@Test
void discoverCompositeSpec() {
LauncherDiscoveryRequest spec = defaultRequest().selectors(
selectUniqueId(JupiterUniqueIdBuilder.uniqueIdForMethod(LocalTestCase.class, "test2()")),
selectClass(LocalTestCase.class)).build();
TestDescriptor engineDescriptor = discoverTests(spec).getEngineDescriptor();
assertEquals(7, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverTestTemplateMethodByUniqueId() {
LauncherDiscoveryRequest spec = defaultRequest().selectors(
selectUniqueId(uniqueIdForTestTemplateMethod(TestTemplateClass.class, "testTemplate()"))).build();
TestDescriptor engineDescriptor = discoverTests(spec).getEngineDescriptor();
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverTestTemplateMethodByMethodSelector() {
LauncherDiscoveryRequest spec = defaultRequest().selectors(
selectMethod(TestTemplateClass.class, "testTemplate")).build();
TestDescriptor engineDescriptor = discoverTests(spec).getEngineDescriptor();
assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors");
}
@Test
void discoverDeeplyNestedTestMethodByNestedMethodSelector() throws Exception {
var selector = selectNestedMethod(
List.of(TestCaseWithExtendedNested.class, TestCaseWithExtendedNested.ConcreteInner1.class),
AbstractSuperClass.NestedInAbstractClass.class,
AbstractSuperClass.NestedInAbstractClass.class.getDeclaredMethod("test"));
LauncherDiscoveryRequest spec = defaultRequest().selectors(selector).build();
TestDescriptor engineDescriptor = discoverTests(spec).getEngineDescriptor();
ClassTestDescriptor topLevelClassDescriptor = (ClassTestDescriptor) getOnlyElement(
engineDescriptor.getChildren());
assertThat(topLevelClassDescriptor.getTestClass()).isEqualTo(TestCaseWithExtendedNested.class);
NestedClassTestDescriptor firstLevelNestedClassDescriptor = (NestedClassTestDescriptor) getOnlyElement(
topLevelClassDescriptor.getChildren());
assertThat(firstLevelNestedClassDescriptor.getTestClass()).isEqualTo(
TestCaseWithExtendedNested.ConcreteInner1.class);
NestedClassTestDescriptor secondLevelNestedClassDescriptor = (NestedClassTestDescriptor) getOnlyElement(
firstLevelNestedClassDescriptor.getChildren());
assertThat(secondLevelNestedClassDescriptor.getTestClass()).isEqualTo(
AbstractSuperClass.NestedInAbstractClass.class);
TestMethodTestDescriptor methodDescriptor = (TestMethodTestDescriptor) getOnlyElement(
secondLevelNestedClassDescriptor.getChildren());
assertThat(methodDescriptor.getTestMethod().getName()).isEqualTo("test");
}
@ParameterizedTest
@MethodSource("requestsForTestClassWithInvalidTestMethod")
void reportsWarningForTestClassWithInvalidTestMethod(LauncherDiscoveryRequest request) throws Exception {
var method = InvalidTestCases.InvalidTestMethodTestCase.class.getDeclaredMethod("test");
var results = discoverTests(request);
var discoveryIssues = results.getDiscoveryIssues().stream().sorted(comparing(DiscoveryIssue::message)).toList();
assertThat(discoveryIssues).hasSize(3);
assertThat(discoveryIssues.getFirst().message()) //
.isEqualTo("@Test method '%s' must not be private. It will not be executed.", method.toGenericString());
assertThat(discoveryIssues.get(1).message()) //
.isEqualTo("@Test method '%s' must not be static. It will not be executed.", method.toGenericString());
assertThat(discoveryIssues.getLast().message()) //
.isEqualTo("@Test method '%s' must not return a value. It will not be executed.",
method.toGenericString());
}
static List<Named<LauncherDiscoveryRequest>> requestsForTestClassWithInvalidTestMethod() {
return List.of( //
named("directly selected",
defaultRequest().selectors(selectClass(InvalidTestCases.InvalidTestMethodTestCase.class)).build()), //
named("indirectly selected", defaultRequest() //
.selectors(selectPackage(InvalidTestCases.InvalidTestMethodTestCase.class.getPackageName())) //
.filters(includeClassNamePatterns(
Pattern.quote(InvalidTestCases.InvalidTestMethodTestCase.class.getName()))).build()), //
named("subclasses", defaultRequest() //
.selectors(selectClasses(InvalidTestCases.InvalidTestMethodSubclass1TestCase.class,
InvalidTestCases.InvalidTestMethodSubclass2TestCase.class)) //
.build()) //
);
}
@ParameterizedTest
@MethodSource("requestsForTestClassWithInvalidStandaloneTestClass")
void reportsWarningForInvalidStandaloneTestClass(LauncherDiscoveryRequest request, Class<?> testClass) {
var results = discoverTests(request);
var discoveryIssues = results.getDiscoveryIssues().stream().sorted(comparing(DiscoveryIssue::message)).toList();
assertThat(discoveryIssues).hasSize(2);
assertThat(discoveryIssues.getFirst().message()) //
.isEqualTo(
"Test class '%s' must not be an inner | DiscoveryTests |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/PickFirstLeafLoadBalancer.java | {
"start": 22746,
"end": 23670
} | class ____ extends SubchannelPicker {
private final PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer;
private final AtomicBoolean connectionRequested = new AtomicBoolean(false);
RequestConnectionPicker(PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer) {
this.pickFirstLeafLoadBalancer =
checkNotNull(pickFirstLeafLoadBalancer, "pickFirstLeafLoadBalancer");
}
@Override
public PickResult pickSubchannel(PickSubchannelArgs args) {
if (connectionRequested.compareAndSet(false, true)) {
helper.getSynchronizationContext().execute(pickFirstLeafLoadBalancer::requestConnection);
}
return PickResult.withNoResult();
}
}
/**
* This contains both an ordered list of addresses and a pointer(i.e. index) to the current entry.
* All updates should be done in a synchronization context.
*/
@VisibleForTesting
static final | RequestConnectionPicker |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/observers/ResourceObserver.java | {
"start": 2196,
"end": 3551
} | class ____> multiple times."}.
*
* <p>Implementation of {@link #onStart()}, {@link #onNext(Object)}, {@link #onError(Throwable)}
* and {@link #onComplete()} are not allowed to throw any unchecked exceptions.
* If for some reason this can't be avoided, use {@link io.reactivex.rxjava3.core.Observable#safeSubscribe(io.reactivex.rxjava3.core.Observer)}
* instead of the standard {@code subscribe()} method.
*
* <p>Example<pre><code>
* Disposable d =
* Observable.range(1, 5)
* .subscribeWith(new ResourceObserver<Integer>() {
* @Override public void onStart() {
* add(Schedulers.single()
* .scheduleDirect(() -> System.out.println("Time!"),
* 2, TimeUnit.SECONDS));
* request(1);
* }
* @Override public void onNext(Integer t) {
* if (t == 3) {
* dispose();
* }
* System.out.println(t);
* }
* @Override public void onError(Throwable t) {
* t.printStackTrace();
* dispose();
* }
* @Override public void onComplete() {
* System.out.println("Done!");
* dispose();
* }
* });
* // ...
* d.dispose();
* </code></pre>
*
* @param <T> the value type
*/
public abstract | name |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/security/NMTokenSecretManagerInNM.java | {
"start": 2105,
"end": 11460
} | class ____ extends BaseNMTokenSecretManager {
private static final Logger LOG =
LoggerFactory.getLogger(NMTokenSecretManagerInNM.class);
private MasterKeyData previousMasterKey;
private final Map<ApplicationAttemptId, MasterKeyData> oldMasterKeys;
private final Map<ApplicationId, List<ApplicationAttemptId>> appToAppAttemptMap;
private final NMStateStoreService stateStore;
private NodeId nodeId;
public NMTokenSecretManagerInNM() {
this(new NMNullStateStoreService());
}
public NMTokenSecretManagerInNM(NMStateStoreService stateStore) {
this.oldMasterKeys =
new HashMap<ApplicationAttemptId, MasterKeyData>();
appToAppAttemptMap =
new HashMap<ApplicationId, List<ApplicationAttemptId>>();
this.stateStore = stateStore;
}
public synchronized void recover()
throws IOException {
RecoveredNMTokensState state = stateStore.loadNMTokensState();
MasterKey key = state.getCurrentMasterKey();
if (key != null) {
super.currentMasterKey =
new MasterKeyData(key, createSecretKey(key.getBytes().array()));
}
key = state.getPreviousMasterKey();
if (key != null) {
previousMasterKey =
new MasterKeyData(key, createSecretKey(key.getBytes().array()));
}
// restore the serial number from the current master key
if (super.currentMasterKey != null) {
super.serialNo = super.currentMasterKey.getMasterKey().getKeyId() + 1;
}
try (RecoveryIterator<Map.Entry<ApplicationAttemptId, MasterKey>> it =
state.getIterator()) {
while (it.hasNext()) {
Map.Entry<ApplicationAttemptId, MasterKey> entry = it.next();
key = entry.getValue();
oldMasterKeys.put(entry.getKey(),
new MasterKeyData(key, createSecretKey(key.getBytes().array())));
}
}
// reconstruct app to app attempts map
appToAppAttemptMap.clear();
for (ApplicationAttemptId attempt : oldMasterKeys.keySet()) {
ApplicationId app = attempt.getApplicationId();
List<ApplicationAttemptId> attempts = appToAppAttemptMap.get(app);
if (attempts == null) {
attempts = new ArrayList<ApplicationAttemptId>();
appToAppAttemptMap.put(app, attempts);
}
attempts.add(attempt);
}
}
private void updateCurrentMasterKey(MasterKeyData key) {
super.currentMasterKey = key;
try {
stateStore.storeNMTokenCurrentMasterKey(key.getMasterKey());
} catch (IOException e) {
LOG.error("Unable to update current master key in state store", e);
}
}
private void updatePreviousMasterKey(MasterKeyData key) {
previousMasterKey = key;
try {
stateStore.storeNMTokenPreviousMasterKey(key.getMasterKey());
} catch (IOException e) {
LOG.error("Unable to update previous master key in state store", e);
}
}
/**
* Used by NodeManagers to create a token-secret-manager with the key
* obtained from the RM. This can happen during registration or when the RM
* rolls the master-key and signal the NM.
*/
@Private
public synchronized void setMasterKey(MasterKey masterKey) {
// Update keys only if the key has changed.
if (super.currentMasterKey == null || super.currentMasterKey.getMasterKey()
.getKeyId() != masterKey.getKeyId()) {
LOG.info("Rolling master-key for container-tokens, got key with id "
+ masterKey.getKeyId());
if (super.currentMasterKey != null) {
updatePreviousMasterKey(super.currentMasterKey);
}
updateCurrentMasterKey(new MasterKeyData(masterKey,
createSecretKey(masterKey.getBytes().array())));
}
}
/**
* This method will be used to verify NMTokens generated by different master
* keys.
*/
@Override
public synchronized byte[] retrievePassword(NMTokenIdentifier identifier)
throws InvalidToken {
int keyId = identifier.getKeyId();
ApplicationAttemptId appAttemptId = identifier.getApplicationAttemptId();
/*
* MasterKey used for retrieving password will be as follows. 1) By default
* older saved master key will be used. 2) If identifier's master key id
* matches that of previous master key id then previous key will be used. 3)
* If identifier's master key id matches that of current master key id then
* current key will be used.
*/
MasterKeyData oldMasterKey = oldMasterKeys.get(appAttemptId);
MasterKeyData masterKeyToUse = oldMasterKey;
if (previousMasterKey != null
&& keyId == previousMasterKey.getMasterKey().getKeyId()) {
masterKeyToUse = previousMasterKey;
} else if (keyId == currentMasterKey.getMasterKey().getKeyId()) {
masterKeyToUse = currentMasterKey;
}
if (nodeId != null && !identifier.getNodeId().equals(nodeId)) {
throw new InvalidToken("Given NMToken for application : "
+ appAttemptId.toString() + " is not valid for current node manager."
+ "expected : " + nodeId.toString() + " found : "
+ identifier.getNodeId().toString());
}
if (masterKeyToUse != null) {
byte[] password = retrivePasswordInternal(identifier, masterKeyToUse);
LOG.debug("NMToken password retrieved successfully!!");
return password;
}
throw new InvalidToken("Given NMToken for application : "
+ appAttemptId.toString() + " seems to have been generated illegally.");
}
public synchronized void appFinished(ApplicationId appId) {
List<ApplicationAttemptId> appAttemptList = appToAppAttemptMap.get(appId);
if (appAttemptList != null) {
LOG.debug("Removing application attempts NMToken keys for"
+ " application {}", appId);
for (ApplicationAttemptId appAttemptId : appAttemptList) {
removeAppAttemptKey(appAttemptId);
}
appToAppAttemptMap.remove(appId);
} else {
LOG.error("No application Attempt for application : " + appId
+ " started on this NM.");
}
}
/**
* This will be called by startContainer. It will add the master key into
* the cache used for starting this container. This should be called before
* validating the startContainer request.
*/
public synchronized void appAttemptStartContainer(
NMTokenIdentifier identifier)
throws org.apache.hadoop.security.token.SecretManager.InvalidToken {
ApplicationAttemptId appAttemptId = identifier.getApplicationAttemptId();
if (!appToAppAttemptMap.containsKey(appAttemptId.getApplicationId())) {
// First application attempt for the given application
appToAppAttemptMap.put(appAttemptId.getApplicationId(),
new ArrayList<ApplicationAttemptId>());
}
MasterKeyData oldKey = oldMasterKeys.get(appAttemptId);
if (oldKey == null) {
// This is a new application attempt.
appToAppAttemptMap.get(appAttemptId.getApplicationId()).add(appAttemptId);
}
if (oldKey == null
|| oldKey.getMasterKey().getKeyId() != identifier.getKeyId()) {
// Update key only if it is modified.
LOG.debug("NMToken key updated for application attempt : {}",
identifier.getApplicationAttemptId().toString());
if (identifier.getKeyId() == currentMasterKey.getMasterKey()
.getKeyId()) {
updateAppAttemptKey(appAttemptId, currentMasterKey);
} else if (previousMasterKey != null
&& identifier.getKeyId() == previousMasterKey.getMasterKey()
.getKeyId()) {
updateAppAttemptKey(appAttemptId, previousMasterKey);
} else {
throw new InvalidToken(
"Older NMToken should not be used while starting the container.");
}
}
}
public synchronized void setNodeId(NodeId nodeId) {
LOG.debug("updating nodeId : {}", nodeId);
this.nodeId = nodeId;
}
@Private
@VisibleForTesting
public synchronized boolean
isAppAttemptNMTokenKeyPresent(ApplicationAttemptId appAttemptId) {
return oldMasterKeys.containsKey(appAttemptId);
}
@Private
@VisibleForTesting
public synchronized NodeId getNodeId() {
return this.nodeId;
}
private void updateAppAttemptKey(ApplicationAttemptId attempt,
MasterKeyData key) {
this.oldMasterKeys.put(attempt, key);
try {
stateStore.storeNMTokenApplicationMasterKey(attempt,
key.getMasterKey());
} catch (IOException e) {
LOG.error("Unable to store master key for application " + attempt, e);
}
}
private void removeAppAttemptKey(ApplicationAttemptId attempt) {
this.oldMasterKeys.remove(attempt);
try {
stateStore.removeNMTokenApplicationMasterKey(attempt);
} catch (IOException e) {
LOG.error("Unable to remove master key for application " + attempt, e);
}
}
/**
* Used by the Distributed Scheduler framework to generate NMTokens
* @param applicationSubmitter
* @param container
* @return NMToken
*/
public NMToken generateNMToken(
String applicationSubmitter, Container container) {
this.readLock.lock();
try {
Token token =
createNMToken(container.getId().getApplicationAttemptId(),
container.getNodeId(), applicationSubmitter);
return NMToken.newInstance(container.getNodeId(), token);
} finally {
this.readLock.unlock();
}
}
}
| NMTokenSecretManagerInNM |
java | spring-projects__spring-security | config/src/integration-test/java/org/springframework/security/config/ldap/EmbeddedLdapServerContextSourceFactoryBeanITests.java | {
"start": 6375,
"end": 7088
} | class ____ {
@Bean
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean
.fromEmbeddedLdapServer();
factoryBean.setManagerDn("uid=admin,ou=system");
return factoryBean;
}
@Bean
AuthenticationManager authenticationManager(LdapContextSource contextSource) {
LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, NoOpPasswordEncoder.getInstance());
factory.setUserDnPatterns("uid={0},ou=people");
return factory.createAuthenticationManager();
}
}
}
| CustomManagerDnNoPasswordConfig |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/property/access/internal/AbstractSetterMethodSerialForm.java | {
"start": 434,
"end": 1783
} | class ____ implements Serializable {
private final Class<?> containerClass;
private final String propertyName;
private final Class<?> declaringClass;
private final String methodName;
private final Class<?> argumentType;
public AbstractSetterMethodSerialForm(Class<?> containerClass, String propertyName, Method method) {
this.containerClass = containerClass;
this.propertyName = propertyName;
this.declaringClass = method.getDeclaringClass();
this.methodName = method.getName();
this.argumentType = method.getParameterTypes()[0];
}
public Class<?> getContainerClass() {
return containerClass;
}
public String getPropertyName() {
return propertyName;
}
public Class<?> getDeclaringClass() {
return declaringClass;
}
public String getMethodName() {
return methodName;
}
public Class<?> getArgumentType() {
return argumentType;
}
protected Method resolveMethod() {
try {
final var method = declaringClass.getDeclaredMethod( methodName, argumentType );
ReflectHelper.ensureAccessibility( method );
return method;
}
catch (NoSuchMethodException e) {
throw new PropertyAccessSerializationException(
"Unable to resolve setter method on deserialization : " + declaringClass.getName() + "#"
+ methodName + "(" + argumentType.getName() + ")"
);
}
}
}
| AbstractSetterMethodSerialForm |
java | apache__camel | components/camel-test/camel-test-junit5/src/main/java/org/apache/camel/test/junit5/ContextManagerExtension.java | {
"start": 1295,
"end": 4710
} | class ____
implements BeforeEachCallback, AfterEachCallback, AfterAllCallback, BeforeAllCallback {
private static final Logger LOG = LoggerFactory.getLogger(ContextManagerExtension.class);
private final TestExecutionConfiguration testConfigurationBuilder;
private final CamelContextConfiguration camelContextConfiguration;
private CamelContextManager contextManager;
private final ContextManagerFactory contextManagerFactory;
private String currentTestName;
public ContextManagerExtension() {
this(new ContextManagerFactory());
}
public ContextManagerExtension(ContextManagerFactory contextManagerFactory) {
testConfigurationBuilder = new TestExecutionConfiguration();
camelContextConfiguration = new CamelContextConfiguration();
this.contextManagerFactory = contextManagerFactory;
}
public ContextManagerExtension(TestExecutionConfiguration testConfigurationBuilder,
CamelContextConfiguration camelContextConfiguration) {
this.testConfigurationBuilder = testConfigurationBuilder;
this.camelContextConfiguration = camelContextConfiguration;
this.contextManagerFactory = new ContextManagerFactory();
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
final boolean perClassPresent
= context.getTestInstanceLifecycle().filter(lc -> lc.equals(TestInstance.Lifecycle.PER_CLASS)).isPresent();
if (perClassPresent) {
LOG.warn("Creating a legacy context manager for {}. This function is deprecated and will be removed in the future",
context.getDisplayName());
contextManager = contextManagerFactory.createContextManager(
ContextManagerFactory.Type.BEFORE_ALL, testConfigurationBuilder, camelContextConfiguration);
ExtensionContext.Store globalStore = context.getStore(ExtensionContext.Namespace.GLOBAL);
contextManager.setGlobalStore(globalStore);
}
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
contextManager.stop();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
if (contextManager == null) {
LOG.trace("Creating a transient context manager for {}", context.getDisplayName());
contextManager = contextManagerFactory.createContextManager(ContextManagerFactory.Type.BEFORE_EACH,
testConfigurationBuilder, camelContextConfiguration);
}
currentTestName = context.getDisplayName();
ExtensionContext.Store globalStore = context.getStore(ExtensionContext.Namespace.GLOBAL);
contextManager.setGlobalStore(globalStore);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
DefaultCamelContext.clearOptions();
contextManager.stop();
}
public CamelContextManager getContextManager() {
return contextManager;
}
public String getCurrentTestName() {
return currentTestName;
}
public TestExecutionConfiguration getTestConfigurationBuilder() {
return testConfigurationBuilder;
}
public CamelContextConfiguration getCamelContextConfiguration() {
return camelContextConfiguration;
}
}
| ContextManagerExtension |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/StateHandleDummyUtil.java | {
"start": 8616,
"end": 9860
} | class ____ implements KeyedStateHandle {
private static final long serialVersionUID = 1L;
private final KeyGroupRange keyGroupRange;
private final StateHandleID stateHandleId;
private DummyKeyedStateHandle(KeyGroupRange keyGroupRange) {
this.keyGroupRange = keyGroupRange;
this.stateHandleId = StateHandleID.randomStateHandleId();
}
@Override
public KeyGroupRange getKeyGroupRange() {
return keyGroupRange;
}
@Override
public KeyedStateHandle getIntersection(KeyGroupRange keyGroupRange) {
return new DummyKeyedStateHandle(this.keyGroupRange.getIntersection(keyGroupRange));
}
@Override
public StateHandleID getStateHandleId() {
return stateHandleId;
}
@Override
public void registerSharedStates(SharedStateRegistry stateRegistry, long checkpointID) {}
@Override
public void discardState() throws Exception {}
@Override
public long getStateSize() {
return 0L;
}
@Override
public long getCheckpointedSize() {
return getStateSize();
}
}
}
| DummyKeyedStateHandle |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/records/MasterKey.java | {
"start": 896,
"end": 1031
} | interface ____ {
int getKeyId();
void setKeyId(int keyId);
ByteBuffer getBytes();
void setBytes(ByteBuffer bytes);
}
| MasterKey |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/support/profile/Profiler.java | {
"start": 722,
"end": 2787
} | class ____ {
public static final String PROFILE_TYPE_WEB = "WEB";
public static final String PROFILE_TYPE_SPRING = "SPRING";
public static final String PROFILE_TYPE_SQL = "SQL";
private static ThreadLocal<Map<ProfileEntryKey, ProfileEntryReqStat>> statsMapLocal = new ThreadLocal<Map<ProfileEntryKey, ProfileEntryReqStat>>();
private static final ThreadLocal<ProfileEntry> currentLocal = new ThreadLocal<ProfileEntry>();
public static boolean isEnable() {
return statsMapLocal != null;
}
public static void enter(String name, String type) {
if (!isEnable()) {
return;
}
ProfileEntry parent = currentLocal.get();
String parentName = null;
if (parent != null) {
parentName = parent.getName();
}
ProfileEntryKey key = new ProfileEntryKey(parentName, name, type);
ProfileEntry entry = new ProfileEntry(parent, key);
currentLocal.set(entry);
}
public static ProfileEntry current() {
return currentLocal.get();
}
public static void release(long nanos) {
ProfileEntry current = currentLocal.get();
if (current == null) {
return;
}
currentLocal.set(current.getParent());
ProfileEntryReqStat stat = null;
Map<ProfileEntryKey, ProfileEntryReqStat> statsMap = statsMapLocal.get();
if (statsMap == null) {
return;
}
stat = statsMap.get(current.getKey());
if (stat == null) {
stat = new ProfileEntryReqStat();
statsMap.put(current.getKey(), stat);
}
stat.incrementExecuteCount();
stat.addExecuteTimeNanos(nanos);
}
public static Map<ProfileEntryKey, ProfileEntryReqStat> getStatsMap() {
return statsMapLocal.get();
}
public static void initLocal() {
statsMapLocal.set(new LinkedHashMap<ProfileEntryKey, ProfileEntryReqStat>());
}
public static void removeLocal() {
statsMapLocal.remove();
}
}
| Profiler |
java | quarkusio__quarkus | independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/json/JsonEntityWithAnySupport.java | {
"start": 756,
"end": 1467
} | class ____ {
protected Map<String, Object> metadata;
@JsonAnyGetter
public Map<String, Object> getMetadata() {
return metadata == null ? metadata = new HashMap<>() : metadata;
}
public Builder setMetadata(Map<String, Object> newValues) {
metadata = JsonBuilder.modifiableMapOrNull(newValues, HashMap::new);
return this;
}
@JsonAnySetter
public Builder setMetadata(String key, Object value) {
getMetadata().put(key, value);
return this;
}
public Builder removeMetadata(String key) {
getMetadata().remove(key);
return this;
}
}
}
| Builder |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/TransportVersionTests.java | {
"start": 1264,
"end": 2367
} | class ____ extends ESTestCase {
public void testVersionComparison() {
TransportVersion V_8_2_0 = TransportVersions.V_8_2_0;
TransportVersion V_8_16_0 = TransportVersions.V_8_16_0;
assertThat(V_8_2_0.before(V_8_16_0), is(true));
assertThat(V_8_2_0.before(V_8_2_0), is(false));
assertThat(V_8_16_0.before(V_8_2_0), is(false));
assertThat(V_8_2_0.onOrBefore(V_8_16_0), is(true));
assertThat(V_8_2_0.onOrBefore(V_8_2_0), is(true));
assertThat(V_8_16_0.onOrBefore(V_8_2_0), is(false));
assertThat(V_8_2_0.after(V_8_16_0), is(false));
assertThat(V_8_2_0.after(V_8_2_0), is(false));
assertThat(V_8_16_0.after(V_8_2_0), is(true));
assertThat(V_8_2_0.onOrAfter(V_8_16_0), is(false));
assertThat(V_8_2_0.onOrAfter(V_8_2_0), is(true));
assertThat(V_8_16_0.onOrAfter(V_8_2_0), is(true));
assertThat(V_8_2_0, is(lessThan(V_8_16_0)));
assertThat(V_8_2_0.compareTo(V_8_2_0), is(0));
assertThat(V_8_16_0, is(greaterThan(V_8_2_0)));
}
public static | TransportVersionTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimeStampInheritanceTest.java | {
"start": 9031,
"end": 9540
} | class ____ extends AbstractPerson {
private String email;
@ElementCollection
private Set<String> books = new HashSet<>();
@OneToOne(cascade = CascadeType.ALL)
private Address homeAddress;
public void setEmail(String email) {
this.email = email;
}
public void addBook(String book) {
this.books.add( book );
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public void setBooks(Set<String> books) {
this.books = books;
}
}
}
| Customer |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/objectarrays/ObjectArrays_assertIsSubsetOf_Test.java | {
"start": 1260,
"end": 4887
} | class ____ extends ObjectArraysBaseTest {
@Test
void should_pass_if_actual_is_subset_of_set() {
arrays.assertIsSubsetOf(INFO, array("Yoda", "Luke"), list("Luke", "Yoda", "Obi-Wan"));
}
@Test
void should_pass_if_actual_has_the_same_elements_as_set() {
arrays.assertIsSubsetOf(INFO, array("Yoda", "Luke"), list("Luke", "Yoda"));
}
@Test
void should_pass_if_actual_is_empty() {
arrays.assertIsSubsetOf(INFO, new String[0], list("Luke", "Yoda"));
}
@Test
void should_pass_if_actual_and_set_are_both_empty() {
arrays.assertIsSubsetOf(INFO, new String[0], list());
}
@Test
void should_pass_if_actual_has_duplicates_but_all_elements_are_in_values() {
arrays.assertIsSubsetOf(INFO, array("Yoda", "Yoda"), list("Yoda"));
}
@Test
void should_pass_if_values_has_duplicates_but_all_elements_are_in_values() {
arrays.assertIsSubsetOf(INFO, array("Yoda", "C-3PO"), list("Yoda", "Yoda", "C-3PO"));
}
@Test
void should_pass_if_both_actual_and_values_have_duplicates_but_all_elements_are_in_values() {
arrays.assertIsSubsetOf(INFO,
array("Yoda", "Yoda", "Yoda", "C-3PO", "Obi-Wan"),
list("Yoda", "Yoda", "C-3PO", "C-3PO", "Obi-Wan"));
}
@Test
void should_throw_error_if_set_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertIsSubsetOf(INFO, array("Yoda", "Luke"), null))
.withMessage(iterableToLookForIsNull());
}
@Test
void should_throw_error_if_actual_is_null() {
// WHEN
var error = expectAssertionError(() -> arrays.assertIsSubsetOf(INFO, null, list("Yoda")));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_not_subset_of_values() {
// GIVEN
var actual = array("Yoda");
List<String> values = list("C-3PO", "Leila");
List<String> extra = list("Yoda");
// WHEN
var error = expectAssertionError(() -> arrays.assertIsSubsetOf(INFO, actual, values));
// THEN
then(error).hasMessage(shouldBeSubsetOf(actual, values, extra).create());
}
// ------------------------------------------------------------------------------------------------------------------
// tests using a custom comparison strategy
// ------------------------------------------------------------------------------------------------------------------
@Test
void should_pass_if_actual_is_subset_of_values_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertIsSubsetOf(INFO, array("Yoda", "Luke"), list("yoda", "lUKE"));
}
@Test
void should_pass_if_actual_contains_duplicates_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertIsSubsetOf(INFO, array("Luke", "Luke"), list("LUke", "yoda"));
}
@Test
void should_pass_if_actual_contains_given_values_even_if_duplicated_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertIsSubsetOf(INFO, array("Yoda", "Luke"), list("LUke", "LuKe", "yoda"));
}
@Test
void should_fail_if_actual_is_not_subset_of_values_according_to_custom_comparison_strategy() {
// GIVEN
var actual = array("Yoda", "Luke");
List<String> values = list("yoda", "C-3PO");
List<String> extra = list("Luke");
// WHEN
var error = expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertIsSubsetOf(INFO, actual, values));
// THEN
then(error).hasMessage(shouldBeSubsetOf(actual, values, extra, caseInsensitiveStringComparisonStrategy).create());
}
}
| ObjectArrays_assertIsSubsetOf_Test |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/ast/MemberElement.java | {
"start": 1036,
"end": 1121
} | class ____ declares the element.
*
* @author graemerocher
* @since 1.0
*/
public | that |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java | {
"start": 4228,
"end": 5351
} | class ____ are mapping to. */
private @Nullable Class<T> mappedClass;
/** Whether we're strictly validating. */
private boolean checkFullyPopulated = false;
/**
* Whether {@code NULL} database values should be ignored for primitive
* properties in the target class.
* @see #setPrimitivesDefaultedForNullValue(boolean)
*/
private boolean primitivesDefaultedForNullValue = false;
/** ConversionService for binding JDBC values to bean properties. */
private @Nullable ConversionService conversionService = DefaultConversionService.getSharedInstance();
/** Map of the properties we provide mapping for. */
private @Nullable Map<String, PropertyDescriptor> mappedProperties;
/** Set of bean property names we provide mapping for. */
private @Nullable Set<String> mappedPropertyNames;
/**
* Create a new {@code BeanPropertyRowMapper} for bean-style configuration.
* @see #setMappedClass
* @see #setCheckFullyPopulated
*/
public BeanPropertyRowMapper() {
}
/**
* Create a new {@code BeanPropertyRowMapper}, accepting unpopulated
* properties in the target bean.
* @param mappedClass the | we |
java | quarkusio__quarkus | extensions/grpc/deployment/src/test/java/io/quarkus/grpc/server/blocking/BlockingMethodsTest.java | {
"start": 1176,
"end": 9825
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.setFlatClassPath(true)
.setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addPackage(EmptyProtos.class.getPackage())
.addPackage(Messages.class.getPackage())
.addPackage(BlockingTestServiceGrpc.class.getPackage())
.addClasses(BlockingTestService.class, AssertHelper.class,
io.quarkus.grpc.blocking.BlockingTestService.class))
.withConfigurationResource("blocking-test-config.properties");
protected static final Duration TIMEOUT = Duration.ofSeconds(5);
@GrpcClient("blocking-test")
BlockingTestServiceGrpc.BlockingTestServiceBlockingStub service;
@GrpcClient("blocking-test")
MutinyBlockingTestServiceGrpc.MutinyBlockingTestServiceStub mutiny;
@GrpcClient("blocking-test")
io.quarkus.grpc.blocking.BlockingTestService client;
@Test
@Timeout(5)
public void testEmpty() {
EmptyProtos.Empty empty = service
.emptyCall(EmptyProtos.Empty.newBuilder().build());
assertThat(empty).isNotNull();
}
@Test
@Timeout(5)
public void testBlockingEmpty() {
EmptyProtos.Empty empty = service
.emptyCallBlocking(EmptyProtos.Empty.newBuilder().build());
assertThat(empty).isNotNull();
}
@Test
@Timeout(5)
public void testUnaryMethod() {
Messages.SimpleResponse response = service
.unaryCall(Messages.SimpleRequest.newBuilder().build());
assertThat(response).isNotNull();
}
@Test
@Timeout(5)
public void testUnaryMethodBlocking() {
Messages.SimpleResponse response = service
.unaryCallBlocking(Messages.SimpleRequest.newBuilder().build());
assertThat(response).isNotNull();
}
@Test
@Timeout(5)
public void testUnaryMethodBlockingClient() {
Messages.SimpleRequest request = Messages.SimpleRequest.newBuilder()
.setMsg("IllegalArgument")
.build();
try {
client.unaryCallBlocking(request).await().indefinitely();
fail(); // should get SRE ...
} catch (StatusRuntimeException e) {
assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatus().getCode());
}
}
@Test
@Timeout(5)
public void testStreamingOutMethod() {
Iterator<Messages.StreamingOutputCallResponse> iterator = service
.streamingOutputCall(Messages.StreamingOutputCallRequest.newBuilder().build());
assertThat(iterator).isNotNull();
List<String> list = new CopyOnWriteArrayList<>();
iterator.forEachRemaining(so -> {
String content = so.getPayload().getBody().toStringUtf8();
list.add(content);
});
assertThat(list).hasSize(10)
.allSatisfy(s -> {
assertThat(s).contains("eventloop");
});
}
@Test
@Timeout(5)
public void testStreamingOutMethodBlocking() {
Iterator<Messages.StreamingOutputCallResponse> iterator = service
.streamingOutputCallBlocking(Messages.StreamingOutputCallRequest.newBuilder().build());
assertThat(iterator).isNotNull();
List<String> list = new CopyOnWriteArrayList<>();
iterator.forEachRemaining(so -> {
String content = so.getPayload().getBody().toStringUtf8();
list.add(content);
});
assertThat(list).hasSize(10)
.allSatisfy(s -> {
assertThat(s).contains("executor");
});
}
@Test
@Timeout(5)
public void testStreamingInMethodWithMutinyClient() {
Multi<Messages.StreamingInputCallRequest> input = Multi.createFrom().items("a", "b", "c", "d")
.map(s -> Messages.Payload.newBuilder().setBody(ByteString.copyFromUtf8(s)).build())
.map(p -> Messages.StreamingInputCallRequest.newBuilder().setPayload(p).build());
Uni<Messages.StreamingInputCallResponse> done = mutiny.streamingInputCall(input);
assertThat(done).isNotNull();
done.await().atMost(TIMEOUT);
}
@Test
@Timeout(5)
public void testStreamingInMethodBlockingWithMutinyClient() {
Multi<Messages.StreamingInputCallRequest> input = Multi.createFrom().items("a", "b", "c", "d")
.map(s -> Messages.Payload.newBuilder().setBody(ByteString.copyFromUtf8(s)).build())
.map(p -> Messages.StreamingInputCallRequest.newBuilder().setPayload(p).build());
Uni<Messages.StreamingInputCallResponse> done = mutiny.streamingInputCallBlocking(input);
assertThat(done).isNotNull();
done.await().atMost(TIMEOUT);
}
@Test
@Timeout(5)
public void testFullDuplexMethodWithMutinyClient() {
Multi<Messages.StreamingOutputCallRequest> input = Multi.createFrom().items("a", "b", "c", "d")
.map(s -> Messages.Payload.newBuilder().setBody(ByteString.copyFromUtf8(s)).build())
.map(p -> Messages.StreamingOutputCallRequest.newBuilder().setPayload(p).build());
List<String> response = mutiny.fullDuplexCall(input)
.map(o -> o.getPayload().getBody().toStringUtf8())
.collect().asList()
.await().atMost(TIMEOUT);
assertThat(response).isNotNull().hasSize(4)
.allSatisfy(s -> {
assertThat(s).contains("eventloop");
});
}
@Test
@Timeout(5)
public void testFullDuplexMethodBlockingWithMutinyClient() {
Multi<Messages.StreamingOutputCallRequest> input = Multi.createFrom().items("a", "b", "c", "d")
.map(s -> Messages.Payload.newBuilder().setBody(ByteString.copyFromUtf8(s)).build())
.map(p -> Messages.StreamingOutputCallRequest.newBuilder().setPayload(p).build());
List<String> response = mutiny.fullDuplexCallBlocking(input)
.map(o -> o.getPayload().getBody().toStringUtf8())
.collect().asList()
.await().atMost(TIMEOUT);
assertThat(response).isNotNull().hasSize(4)
.allSatisfy(s -> {
assertThat(s).contains("executor");
});
}
@Test
public void testHalfDuplexMethodWithMutinyClient() {
Multi<Messages.StreamingOutputCallRequest> input = Multi.createFrom().items("a", "b", "c", "d")
.map(s -> Messages.Payload.newBuilder().setBody(ByteString.copyFromUtf8(s)).build())
.map(p -> Messages.StreamingOutputCallRequest.newBuilder().setPayload(p).build());
List<String> response = mutiny.halfDuplexCall(input)
.map(o -> o.getPayload().getBody().toStringUtf8())
.collect().asList()
.await().atMost(TIMEOUT);
assertThat(response).isNotNull().hasSize(4)
.allSatisfy(s -> {
assertThat(s).contains("eventloop");
});
}
@Test
public void testHalfDuplexMethodBlockingWithMutinyClient() {
Multi<Messages.StreamingOutputCallRequest> input = Multi.createFrom().items("a", "b", "c", "d")
.map(s -> Messages.Payload.newBuilder().setBody(ByteString.copyFromUtf8(s)).build())
.map(p -> Messages.StreamingOutputCallRequest.newBuilder().setPayload(p).build());
List<String> response = mutiny.halfDuplexCallBlocking(input)
.map(o -> o.getPayload().getBody().toStringUtf8())
.collect().asList()
.await().atMost(TIMEOUT);
assertThat(response).isNotNull().hasSize(4)
.allSatisfy(s -> {
assertThat(s).contains("executor");
});
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void testUnimplementedMethod() {
Assertions.assertThatThrownBy(
() -> service
.unimplementedCall(EmptyProtos.Empty.newBuilder().build()))
.isInstanceOf(StatusRuntimeException.class).hasMessageContaining("UNIMPLEMENTED");
Assertions.assertThatThrownBy(
() -> service
.unimplementedCallBlocking(EmptyProtos.Empty.newBuilder().build()))
.isInstanceOf(StatusRuntimeException.class).hasMessageContaining("UNIMPLEMENTED");
}
}
| BlockingMethodsTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/integers/Integers_assertNotEqual_Test.java | {
"start": 1416,
"end": 3275
} | class ____ extends IntegersBaseTest {
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integers.assertNotEqual(someInfo(), null, 8))
.withMessage(actualIsNull());
}
@Test
void should_pass_if_integers_are_not_equal() {
integers.assertNotEqual(someInfo(), 8, 6);
}
@Test
void should_fail_if_integers_are_equal() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> integers.assertNotEqual(info, 6, 6));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqual(6, 6));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integersWithAbsValueComparisonStrategy.assertNotEqual(someInfo(),
null,
8))
.withMessage(actualIsNull());
}
@Test
void should_pass_if_integers_are_not_equal_according_to_custom_comparison_strategy() {
integersWithAbsValueComparisonStrategy.assertNotEqual(someInfo(), 8, 6);
}
@Test
void should_fail_if_integers_are_equal_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> integersWithAbsValueComparisonStrategy.assertNotEqual(info, 6, -6));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqual(6, -6, absValueComparisonStrategy));
}
}
| Integers_assertNotEqual_Test |
java | apache__maven | impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/Apply.java | {
"start": 1119,
"end": 1563
} | class ____ extends AbstractUpgradeGoal {
@Inject
public Apply(StrategyOrchestrator orchestrator) {
super(orchestrator);
}
@Override
protected boolean shouldSaveModifications() {
return true;
}
@Override
public int execute(UpgradeContext context) throws Exception {
context.info("Maven Upgrade Tool - Apply");
context.println();
return super.execute(context);
}
}
| Apply |
java | apache__camel | components/camel-google/camel-google-drive/src/test/java/org/apache/camel/component/google/drive/MyClientFactory.java | {
"start": 1092,
"end": 1736
} | class ____ implements GoogleDriveClientFactory {
public MyClientFactory() {
}
@Override
public Drive makeClient(
String clientId, String clientSecret, Collection<String> scopes, String applicationName, String refreshToken,
String accessToken) {
return new Drive(new NetHttpTransport(), new JacksonFactory(), null);
}
@Override
public Drive makeClient(
CamelContext camelContext, String serviceAccountKey, Collection<String> scopes, String applicationName,
String delegate) {
throw new IllegalArgumentException("Not implemented");
}
}
| MyClientFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ConstantOverflowTest.java | {
"start": 2963,
"end": 3339
} | class ____ {
public static final char a = (char) Integer.MAX_VALUE;
public static final char b = (char) -1;
public static final char c = (char) 1;
}
""")
.doTest();
}
@Test
public void negativeCast() {
testHelper
.addSourceLines(
"Test.java",
"""
| Test |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/BasicAnnotationsTest.java | {
"start": 2594,
"end": 2628
} | class ____ { }
final static | Dummy |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/inject/NamedBeanPropertyNotFoundTest.java | {
"start": 951,
"end": 1054
} | class ____ {
public List<String> getList() {
return null;
}
}
}
| NamedFoo |
java | quarkusio__quarkus | integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java | {
"start": 49051,
"end": 49360
} | class ____ be deleted
assertThat(innerClassFile).doesNotExist();
assertThat(helloClassFile).exists();
assertThat(classDeletionResourceClassFile).exists();
// Delete source file
source.delete();
// Wait until we get "404 Not Found" because ClassDeletionResource. | to |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidInlineTagTest.java | {
"start": 3720,
"end": 4017
} | interface ____ {
/** Provide an {@code a} */
void foo(int a);
}
""")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void improperParam() {
refactoring
.addInputLines(
"Test.java",
"""
| Test |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/repositories/CityRepository.java | {
"start": 798,
"end": 931
} | interface ____ extends Neo4jRepository<City, Long> {
Optional<City> findOneByNameAndState(String name, String state);
}
| CityRepository |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/QueryableStoreTypes.java | {
"start": 4418,
"end": 4936
} | class ____<K, V> extends QueryableStoreTypeMatcher<ReadOnlyKeyValueStore<K, V>> {
KeyValueStoreType() {
super(Collections.singleton(ReadOnlyKeyValueStore.class));
}
@Override
public ReadOnlyKeyValueStore<K, V> create(final StateStoreProvider storeProvider,
final String storeName) {
return new CompositeReadOnlyKeyValueStore<>(storeProvider, this, storeName);
}
}
private static | KeyValueStoreType |
java | apache__camel | test-infra/camel-test-infra-ignite/src/main/java/org/apache/camel/test/infra/ignite/services/IgniteInfraService.java | {
"start": 1040,
"end": 1151
} | interface ____ extends InfrastructureService {
IgniteConfiguration createConfiguration();
}
| IgniteInfraService |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/processor/MethodRetrievalProcessor.java | {
"start": 3332,
"end": 28743
} | class ____ implements ModelElementProcessor<Void, List<SourceMethod>> {
private static final String MAPPING_FQN = "org.mapstruct.Mapping";
private static final String MAPPINGS_FQN = "org.mapstruct.Mappings";
private static final String SUB_CLASS_MAPPING_FQN = "org.mapstruct.SubclassMapping";
private static final String SUB_CLASS_MAPPINGS_FQN = "org.mapstruct.SubclassMappings";
private static final String VALUE_MAPPING_FQN = "org.mapstruct.ValueMapping";
private static final String VALUE_MAPPINGS_FQN = "org.mapstruct.ValueMappings";
private static final String CONDITION_FQN = "org.mapstruct.Condition";
private static final String IGNORED_FQN = "org.mapstruct.Ignored";
private static final String IGNORED_LIST_FQN = "org.mapstruct.IgnoredList";
private FormattingMessager messager;
private TypeFactory typeFactory;
private AccessorNamingUtils accessorNaming;
private Map<String, EnumTransformationStrategy> enumTransformationStrategies;
private TypeUtils typeUtils;
private ElementUtils elementUtils;
private Options options;
@Override
public List<SourceMethod> process(ProcessorContext context, TypeElement mapperTypeElement, Void sourceModel) {
this.messager = context.getMessager();
this.typeFactory = context.getTypeFactory();
this.accessorNaming = context.getAccessorNaming();
this.typeUtils = context.getTypeUtils();
this.elementUtils = context.getElementUtils();
this.enumTransformationStrategies = context.getEnumTransformationStrategies();
this.options = context.getOptions();
this.messager.note( 0, Message.PROCESSING_NOTE, mapperTypeElement );
MapperOptions mapperOptions = MapperOptions.getInstanceOn( mapperTypeElement, context.getOptions() );
if ( mapperOptions.hasMapperConfig() ) {
this.messager.note( 0, Message.CONFIG_NOTE, mapperOptions.mapperConfigType().asElement().getSimpleName() );
}
if ( !mapperOptions.isValid() ) {
throw new AnnotationProcessingException(
"Couldn't retrieve @Mapper annotation",
mapperTypeElement,
mapperOptions.getAnnotationMirror() );
}
List<SourceMethod> prototypeMethods = retrievePrototypeMethods( mapperTypeElement, mapperOptions );
return retrieveMethods(
typeFactory.getType( mapperTypeElement.asType() ),
mapperTypeElement,
mapperOptions,
prototypeMethods
);
}
@Override
public int getPriority() {
return 1;
}
private List<SourceMethod> retrievePrototypeMethods(TypeElement mapperTypeElement,
MapperOptions mapperAnnotation) {
if ( !mapperAnnotation.hasMapperConfig() ) {
return Collections.emptyList();
}
TypeElement typeElement = asTypeElement( mapperAnnotation.mapperConfigType() );
List<SourceMethod> methods = new ArrayList<>();
for ( ExecutableElement executable : elementUtils.getAllEnclosedExecutableElements( typeElement ) ) {
if ( executable.isDefault() || executable.getModifiers().contains( Modifier.STATIC ) ) {
// skip the default and static methods because these are not prototypes.
continue;
}
ExecutableType methodType = typeFactory.getMethodType( mapperAnnotation.mapperConfigType(), executable );
List<Parameter> parameters = typeFactory.getParameters( methodType, executable );
boolean containsTargetTypeParameter = SourceMethod.containsTargetTypeParameter( parameters );
// prototype methods don't have prototypes themselves
List<SourceMethod> prototypeMethods = Collections.emptyList();
SourceMethod method =
getMethodRequiringImplementation(
methodType,
executable,
parameters,
containsTargetTypeParameter,
mapperAnnotation,
prototypeMethods,
mapperTypeElement
);
if ( method != null ) {
methods.add( method );
}
}
return methods;
}
/**
* Retrieves the mapping methods declared by the given mapper type.
*
* @param usedMapperType The type of interest (either the mapper to implement, a used mapper via @uses annotation,
* or a parameter type annotated with @Context)
* @param mapperToImplement the top level type (mapper) that requires implementation
* @param mapperOptions the mapper config
* @param prototypeMethods prototype methods defined in mapper config type
* @return All mapping methods declared by the given type
*/
private List<SourceMethod> retrieveMethods(Type usedMapperType, TypeElement mapperToImplement,
MapperOptions mapperOptions, List<SourceMethod> prototypeMethods) {
List<SourceMethod> methods = new ArrayList<>();
TypeElement usedMapper = usedMapperType.getTypeElement();
for ( ExecutableElement executable : elementUtils.getAllEnclosedExecutableElements( usedMapper ) ) {
SourceMethod method = getMethod(
usedMapperType,
executable,
mapperToImplement,
mapperOptions,
prototypeMethods );
if ( method != null ) {
methods.add( method );
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( usedMapper.equals( mapperToImplement ) ) {
for ( DeclaredType mapper : mapperOptions.uses() ) {
TypeElement usesMapperElement = asTypeElement( mapper );
if ( !mapperToImplement.equals( usesMapperElement ) ) {
methods.addAll( retrieveMethods(
typeFactory.getType( mapper ),
mapperToImplement,
mapperOptions,
prototypeMethods ) );
}
else {
messager.printMessage(
mapperToImplement,
mapperOptions.getAnnotationMirror(),
Message.RETRIEVAL_MAPPER_USES_CYCLE,
mapperToImplement
);
}
}
}
return methods;
}
private TypeElement asTypeElement(DeclaredType type) {
return (TypeElement) type.asElement();
}
private SourceMethod getMethod(Type usedMapperType,
ExecutableElement method,
TypeElement mapperToImplement,
MapperOptions mapperOptions,
List<SourceMethod> prototypeMethods) {
TypeElement usedMapper = usedMapperType.getTypeElement();
ExecutableType methodType = typeFactory.getMethodType( (DeclaredType) usedMapperType.getTypeMirror(), method );
List<Parameter> parameters = typeFactory.getParameters( methodType, method );
Type returnType = typeFactory.getReturnType( methodType );
boolean methodRequiresImplementation = method.getModifiers().contains( Modifier.ABSTRACT );
boolean containsTargetTypeParameter = SourceMethod.containsTargetTypeParameter( parameters );
//add method with property mappings if an implementation needs to be generated
if ( ( usedMapper.equals( mapperToImplement ) ) && methodRequiresImplementation ) {
return getMethodRequiringImplementation( methodType,
method,
parameters,
containsTargetTypeParameter,
mapperOptions,
prototypeMethods,
mapperToImplement );
}
// otherwise add reference to existing mapper method
else if ( isValidReferencedMethod( parameters ) || isValidFactoryMethod( method, parameters, returnType )
|| isValidLifecycleCallbackMethod( method )
|| isValidPresenceCheckMethod( method, parameters, returnType ) ) {
return getReferencedMethod( usedMapper, methodType, method, mapperToImplement, parameters );
}
else {
return null;
}
}
private SourceMethod getMethodRequiringImplementation(ExecutableType methodType, ExecutableElement method,
List<Parameter> parameters,
boolean containsTargetTypeParameter,
MapperOptions mapperOptions,
List<SourceMethod> prototypeMethods,
TypeElement mapperToImplement) {
Type returnType = typeFactory.getReturnType( methodType );
List<Type> exceptionTypes = typeFactory.getThrownTypes( methodType );
List<Parameter> sourceParameters = Parameter.getSourceParameters( parameters );
List<Parameter> contextParameters = Parameter.getContextParameters( parameters );
Parameter targetParameter = extractTargetParameter( parameters );
Type resultType = selectResultType( returnType, targetParameter );
boolean isValid = checkParameterAndReturnType(
method,
sourceParameters,
targetParameter,
contextParameters,
resultType,
returnType,
containsTargetTypeParameter
);
if ( !isValid ) {
return null;
}
ParameterProvidedMethods contextProvidedMethods =
retrieveContextProvidedMethods( contextParameters, mapperToImplement, mapperOptions );
BeanMappingOptions beanMappingOptions = BeanMappingOptions.getInstanceOn(
BeanMappingGem.instanceOn( method ),
mapperOptions,
method,
messager,
typeUtils,
typeFactory );
Set<MappingOptions> mappingOptions = getMappings( method, beanMappingOptions );
IterableMappingOptions iterableMappingOptions = IterableMappingOptions.fromGem(
IterableMappingGem.instanceOn( method ),
mapperOptions,
method,
messager,
typeUtils
);
MapMappingOptions mapMappingOptions = MapMappingOptions.fromGem(
MapMappingGem.instanceOn( method ),
mapperOptions,
method,
messager,
typeUtils
);
EnumMappingOptions enumMappingOptions = EnumMappingOptions.getInstanceOn(
method,
mapperOptions,
enumTransformationStrategies,
messager
);
// We want to get as much error reporting as possible.
// If targetParameter is not null it means we have an update method
SubclassValidator subclassValidator = new SubclassValidator( messager, typeUtils );
Set<SubclassMappingOptions> subclassMappingOptions = getSubclassMappings(
sourceParameters,
targetParameter != null ? null : resultType,
method,
beanMappingOptions,
subclassValidator
);
return new SourceMethod.Builder()
.setExecutable( method )
.setParameters( parameters )
.setReturnType( returnType )
.setExceptionTypes( exceptionTypes )
.setMapper( mapperOptions )
.setBeanMappingOptions( beanMappingOptions )
.setMappingOptions( mappingOptions )
.setIterableMappingOptions( iterableMappingOptions )
.setMapMappingOptions( mapMappingOptions )
.setValueMappingOptionss( getValueMappings( method ) )
.setEnumMappingOptions( enumMappingOptions )
.setSubclassMappings( subclassMappingOptions )
.setSubclassValidator( subclassValidator )
.setTypeUtils( typeUtils )
.setTypeFactory( typeFactory )
.setPrototypeMethods( prototypeMethods )
.setContextProvidedMethods( contextProvidedMethods )
.setVerboseLogging( options.isVerbose() )
.build();
}
private ParameterProvidedMethods retrieveContextProvidedMethods(
List<Parameter> contextParameters, TypeElement mapperToImplement, MapperOptions mapperConfig) {
ParameterProvidedMethods.Builder builder = ParameterProvidedMethods.builder();
for ( Parameter contextParam : contextParameters ) {
if ( contextParam.getType().isPrimitive() || contextParam.getType().isArrayType() ) {
continue;
}
List<SourceMethod> contextParamMethods = retrieveMethods(
contextParam.getType(),
mapperToImplement,
mapperConfig,
Collections.emptyList() );
List<SourceMethod> contextProvidedMethods = new ArrayList<>( contextParamMethods.size() );
for ( SourceMethod sourceMethod : contextParamMethods ) {
if ( sourceMethod.isLifecycleCallbackMethod() || sourceMethod.isObjectFactory()
|| sourceMethod.getConditionOptions().isAnyStrategyApplicable() ) {
contextProvidedMethods.add( sourceMethod );
}
}
builder.addMethodsForParameter( contextParam, contextProvidedMethods );
}
return builder.build();
}
private SourceMethod getReferencedMethod(TypeElement usedMapper, ExecutableType methodType,
ExecutableElement method, TypeElement mapperToImplement,
List<Parameter> parameters) {
Type returnType = typeFactory.getReturnType( methodType );
List<Type> exceptionTypes = typeFactory.getThrownTypes( methodType );
Type usedMapperAsType = typeFactory.getType( usedMapper );
Type mapperToImplementAsType = typeFactory.getType( mapperToImplement );
if ( !mapperToImplementAsType.canAccess( usedMapperAsType, method ) ) {
return null;
}
Type definingType = typeFactory.getType( method.getEnclosingElement().asType() );
return new SourceMethod.Builder()
.setDeclaringMapper( usedMapper.equals( mapperToImplement ) ? null : usedMapperAsType )
.setDefiningType( definingType )
.setExecutable( method )
.setParameters( parameters )
.setReturnType( returnType )
.setExceptionTypes( exceptionTypes )
.setTypeUtils( typeUtils )
.setTypeFactory( typeFactory )
.setConditionOptions( getConditionOptions( method, parameters ) )
.setVerboseLogging( options.isVerbose() )
.build();
}
private boolean isValidLifecycleCallbackMethod(ExecutableElement method) {
return Executables.isLifecycleCallbackMethod( method );
}
private boolean isValidReferencedMethod(List<Parameter> parameters) {
return isValidReferencedOrFactoryMethod( 1, 1, parameters );
}
private boolean isValidFactoryMethod(ExecutableElement method, List<Parameter> parameters, Type returnType) {
return !isVoid( returnType )
&& ( isValidReferencedOrFactoryMethod( 0, 0, parameters ) || hasFactoryAnnotation( method ) );
}
private boolean hasFactoryAnnotation(ExecutableElement method) {
return ObjectFactoryGem.instanceOn( method ) != null;
}
private boolean isValidPresenceCheckMethod(ExecutableElement method, List<Parameter> parameters, Type returnType) {
for ( Parameter param : parameters ) {
if ( param.isSourcePropertyName() && !param.getType().isString() ) {
messager.printMessage(
param.getElement(),
SourcePropertyNameGem.instanceOn( param.getElement() ).mirror(),
Message.RETRIEVAL_SOURCE_PROPERTY_NAME_WRONG_TYPE
);
return false;
}
if ( param.isTargetPropertyName() && !param.getType().isString() ) {
messager.printMessage(
param.getElement(),
TargetPropertyNameGem.instanceOn( param.getElement() ).mirror(),
Message.RETRIEVAL_TARGET_PROPERTY_NAME_WRONG_TYPE
);
return false;
}
}
return isBoolean( returnType ) && hasConditionAnnotation( method );
}
private boolean hasConditionAnnotation(ExecutableElement method) {
return ConditionGem.instanceOn( method ) != null;
}
private boolean isVoid(Type returnType) {
return returnType.getTypeMirror().getKind() == TypeKind.VOID;
}
private boolean isBoolean(Type returnType) {
return Boolean.class.getCanonicalName().equals( returnType.getBoxedEquivalent().getFullyQualifiedName() );
}
private boolean isValidReferencedOrFactoryMethod(int sourceParamCount, int targetParamCount,
List<Parameter> parameters) {
int validSourceParameters = 0;
int targetParameters = 0;
int targetTypeParameters = 0;
for ( Parameter param : parameters ) {
if ( param.isMappingTarget() ) {
targetParameters++;
}
else if ( param.isTargetType() ) {
targetTypeParameters++;
}
else if ( !param.isMappingContext() ) {
validSourceParameters++;
}
}
return validSourceParameters == sourceParamCount
&& targetParameters <= targetParamCount
&& targetTypeParameters <= 1;
}
private Parameter extractTargetParameter(List<Parameter> parameters) {
for ( Parameter param : parameters ) {
if ( param.isMappingTarget() ) {
return param;
}
}
return null;
}
private Type selectResultType(Type returnType, Parameter targetParameter) {
if ( null != targetParameter ) {
return targetParameter.getType();
}
else {
return returnType;
}
}
private boolean checkParameterAndReturnType(ExecutableElement method, List<Parameter> sourceParameters,
Parameter targetParameter, List<Parameter> contextParameters,
Type resultType, Type returnType, boolean containsTargetTypeParameter) {
if ( sourceParameters.isEmpty() ) {
messager.printMessage( method, Message.RETRIEVAL_NO_INPUT_ARGS );
return false;
}
if ( targetParameter != null
&& ( sourceParameters.size() + contextParameters.size() + 1 != method.getParameters().size() ) ) {
messager.printMessage( method, Message.RETRIEVAL_DUPLICATE_MAPPING_TARGETS );
return false;
}
if ( isVoid( resultType ) ) {
messager.printMessage( method, Message.RETRIEVAL_VOID_MAPPING_METHOD );
return false;
}
if ( returnType.getTypeMirror().getKind() != TypeKind.VOID &&
!resultType.isAssignableTo( returnType ) &&
!resultType.isAssignableTo( typeFactory.effectiveResultTypeFor( returnType, null ) ) ) {
messager.printMessage( method, Message.RETRIEVAL_NON_ASSIGNABLE_RESULTTYPE );
return false;
}
for ( Parameter sourceParameter : sourceParameters ) {
if ( sourceParameter.getType().isTypeVar() ) {
messager.printMessage( method, Message.RETRIEVAL_TYPE_VAR_SOURCE );
return false;
}
}
Set<Type> contextParameterTypes = new HashSet<>();
for ( Parameter contextParameter : contextParameters ) {
if ( !contextParameterTypes.add( contextParameter.getType() ) ) {
messager.printMessage( method, Message.RETRIEVAL_CONTEXT_PARAMS_WITH_SAME_TYPE );
return false;
}
}
if ( returnType.isTypeVar() || resultType.isTypeVar() ) {
messager.printMessage( method, Message.RETRIEVAL_TYPE_VAR_RESULT );
return false;
}
if ( sourceParameters.size() == 1 ) {
Type parameterType = sourceParameters.get( 0 ).getType();
if ( isStreamTypeOrIterableFromJavaStdLib( parameterType ) && !resultType.isIterableOrStreamType() ) {
messager.printMessage( method, Message.RETRIEVAL_ITERABLE_TO_NON_ITERABLE );
return false;
}
if ( !parameterType.isIterableOrStreamType() && isStreamTypeOrIterableFromJavaStdLib( resultType ) ) {
messager.printMessage( method, Message.RETRIEVAL_NON_ITERABLE_TO_ITERABLE );
return false;
}
if ( !parameterType.isIterableOrStreamType() && resultType.isArrayType() ) {
messager.printMessage( method, Message.RETRIEVAL_NON_ITERABLE_TO_ARRAY );
return false;
}
if ( parameterType.isPrimitive() ) {
messager.printMessage( method, Message.RETRIEVAL_PRIMITIVE_PARAMETER );
return false;
}
for ( Type typeParameter : parameterType.getTypeParameters() ) {
if ( typeParameter.hasSuperBound() ) {
messager.printMessage( method, Message.RETRIEVAL_WILDCARD_SUPER_BOUND_SOURCE );
return false;
}
if ( typeParameter.isTypeVar() ) {
messager.printMessage( method, Message.RETRIEVAL_TYPE_VAR_SOURCE );
return false;
}
}
}
if ( containsTargetTypeParameter ) {
messager.printMessage( method, Message.RETRIEVAL_MAPPING_HAS_TARGET_TYPE_PARAMETER );
return false;
}
if ( resultType.isPrimitive() ) {
messager.printMessage( method, Message.RETRIEVAL_PRIMITIVE_RETURN );
return false;
}
for ( Type typeParameter : resultType.getTypeParameters() ) {
if ( typeParameter.isTypeVar() ) {
messager.printMessage( method, Message.RETRIEVAL_TYPE_VAR_RESULT );
return false;
}
if ( typeParameter.hasExtendsBound() ) {
messager.printMessage( method, Message.RETRIEVAL_WILDCARD_EXTENDS_BOUND_RESULT );
return false;
}
}
if ( Executables.isAfterMappingMethod( method ) ) {
messager.printMessage( method, Message.RETRIEVAL_AFTER_METHOD_NOT_IMPLEMENTED );
return false;
}
if ( Executables.isBeforeMappingMethod( method ) ) {
messager.printMessage( method, Message.RETRIEVAL_BEFORE_METHOD_NOT_IMPLEMENTED );
return false;
}
return true;
}
private boolean isStreamTypeOrIterableFromJavaStdLib(Type type) {
return type.isStreamType() || ( type.isIterableType() && type.isJavaLangType() );
}
/**
* Retrieves the mappings configured via {@code @Mapping} from the given method.
*
* @param method The method of interest
* @param beanMapping options coming from bean mapping method
* @return The mappings for the given method, keyed by target property name
*/
private Set<MappingOptions> getMappings(ExecutableElement method, BeanMappingOptions beanMapping) {
Set<MappingOptions> processedAnnotations = new RepeatableMappings( beanMapping )
.getProcessedAnnotations( method );
processedAnnotations.addAll( new IgnoredConditions( processedAnnotations )
.getProcessedAnnotations( method ) );
return processedAnnotations;
}
/**
* Retrieves the subclass mappings configured via {@code @SubclassMapping} from the given method.
*
* @param method The method of interest
* @param beanMapping options coming from bean mapping method
*
* @return The subclass mappings for the given method
*/
private Set<SubclassMappingOptions> getSubclassMappings(List<Parameter> sourceParameters, Type resultType,
ExecutableElement method, BeanMappingOptions beanMapping,
SubclassValidator validator) {
return new RepeatableSubclassMappings( beanMapping, sourceParameters, resultType, validator )
.getProcessedAnnotations( method );
}
/**
* Retrieves the conditions configured via {@code @Condition} from the given method.
*
* @param method The method of interest
* @param parameters
* @return The condition options for the given method
*/
private Set<ConditionOptions> getConditionOptions(ExecutableElement method, List<Parameter> parameters) {
return new MetaConditions( parameters ).getProcessedAnnotations( method );
}
private | MethodRetrievalProcessor |
java | dropwizard__dropwizard | dropwizard-migrations/src/test/java/io/dropwizard/migrations/DbPrepareRollbackCommandTest.java | {
"start": 580,
"end": 4074
} | class ____ {
private final DbPrepareRollbackCommand<TestMigrationConfiguration> prepareRollbackCommand =
new DbPrepareRollbackCommand<>(new TestMigrationDatabaseConfiguration(), TestMigrationConfiguration.class,
"migrations-ddl.xml");
private TestMigrationConfiguration conf;
@BeforeEach
void setUp() {
final String databaseUrl = MigrationTestSupport.getDatabaseUrl();
conf = MigrationTestSupport.createConfiguration(databaseUrl);
}
@Test
void testRun() throws Exception {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
prepareRollbackCommand.setOutputStream(new PrintStream(baos));
prepareRollbackCommand.run(null, new Namespace(Collections.emptyMap()), conf);
assertThat(baos.toString(UTF_8))
.contains("ALTER TABLE PUBLIC.persons DROP COLUMN email;")
.contains("DROP TABLE PUBLIC.persons;");
}
@Test
void testPrepareOnlyChange() throws Exception {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
prepareRollbackCommand.setOutputStream(new PrintStream(baos));
prepareRollbackCommand.run(null, new Namespace(Collections.singletonMap("count", 1)), conf);
assertThat(baos.toString(UTF_8)).contains("DROP TABLE PUBLIC.persons;");
}
@Test
void testPrintHelp() throws Exception {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
MigrationTestSupport.createSubparser(prepareRollbackCommand).printHelp(new PrintWriter(new OutputStreamWriter(out, UTF_8), true));
assertThat(out.toString(UTF_8)).isEqualToNormalizingNewlines(
"usage: db prepare-rollback [-h] [--migrations MIGRATIONS-FILE]\n" +
" [--catalog CATALOG] [--schema SCHEMA]\n" +
" [--analytics-enabled ANALYTICS-ENABLED] [-c COUNT] [-i CONTEXTS]\n" +
" [file]\n" +
"\n" +
"Generate rollback DDL scripts for pending change sets.\n" +
"\n" +
"positional arguments:\n" +
" file application configuration file\n" +
"\n" +
"named arguments:\n" +
" -h, --help show this help message and exit\n" +
" --migrations MIGRATIONS-FILE\n" +
" the file containing the Liquibase migrations for\n" +
" the application\n" +
" --catalog CATALOG Specify the database catalog (use database\n" +
" default if omitted)\n" +
" --schema SCHEMA Specify the database schema (use database default\n" +
" if omitted)\n" +
" --analytics-enabled ANALYTICS-ENABLED\n" +
" This turns on analytics gathering for that single\n" +
" occurrence of a command.\n" +
" -c COUNT, --count COUNT\n" +
" limit script to the specified number of pending\n" +
" change sets\n" +
" -i CONTEXTS, --include CONTEXTS\n" +
" include change sets from the given context\n");
}
}
| DbPrepareRollbackCommandTest |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/CommentsTest.java | {
"start": 8009,
"end": 8608
} | class ____ {
abstract void target(Object param1, Object param2);
private void test(Object param1, Object param2) {
// BUG: Diagnostic contains: [[] param1 [1], [2] param2 []]
target(param1 /* 1 */, /* 2 */ param2);
}
}
""")
.doTest();
}
@Test
public void findCommentsForArguments_findsNoComments_whenNoComments() {
CompilationTestHelper.newInstance(PrintCommentsForArguments.class, getClass())
.addSourceLines(
"Test.java",
"""
abstract | Test |
java | apache__camel | components/camel-consul/src/main/java/org/apache/camel/component/consul/ConsulFactories.java | {
"start": 1015,
"end": 1181
} | interface ____ {
Producer create(ConsulEndpoint endpoint, ConsulConfiguration configuration) throws Exception;
}
@FunctionalInterface
| ProducerFactory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.