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
quarkusio__quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/ReflectiveBeanITCase.java
{ "start": 107, "end": 166 }
class ____ extends ReflectiveBeanTest { }
ReflectiveBeanITCase
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/model/MessageResponse.java
{ "start": 1047, "end": 1955 }
class ____ { @JsonProperty("messaging_product") private String messagingProduct = "whatsapp"; private List<Contact> contacts; private List<Message> messages; private String id; public MessageResponse() { } public String getMessagingProduct() { return messagingProduct; } public void setMessagingProduct(String messagingProduct) { this.messagingProduct = messagingProduct; } public List<Contact> getContacts() { return contacts; } public void setContacts(List<Contact> contacts) { this.contacts = contacts; } public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
MessageResponse
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/AsyncResult.java
{ "start": 959, "end": 5967 }
interface ____<T> { /** * The result of the operation. This will be null if the operation failed. * * @return the result or null if the operation failed. */ T result(); /** * A Throwable describing failure. This will be null if the operation succeeded. * * @return the cause or null if the operation succeeded. */ Throwable cause(); /** * Did it succeed? * * @return true if it succeded or false otherwise */ boolean succeeded(); /** * Did it fail? * * @return true if it failed or false otherwise */ boolean failed(); /** * Apply a {@code mapper} function on this async result.<p> * * The {@code mapper} is called with the completed value and this mapper returns a value. This value will complete the result returned by this method call.<p> * * When this async result is failed, the failure will be propagated to the returned async result and the {@code mapper} will not be called. * * @param mapper the mapper function * @return the mapped async result */ default <U> AsyncResult<U> map(Function<? super T, U> mapper) { if (mapper == null) { throw new NullPointerException(); } return new AsyncResult<U>() { @Override public U result() { if (succeeded()) { return mapper.apply(AsyncResult.this.result()); } else { return null; } } @Override public Throwable cause() { return AsyncResult.this.cause(); } @Override public boolean succeeded() { return AsyncResult.this.succeeded(); } @Override public boolean failed() { return AsyncResult.this.failed(); } }; } /** * Map the result of this async result to a specific {@code value}.<p> * * When this async result succeeds, this {@code value} will succeeed the async result returned by this method call.<p> * * When this async result fails, the failure will be propagated to the returned async result. * * @param value the value that eventually completes the mapped async result * @return the mapped async result */ default <V> AsyncResult<V> map(V value) { return map(t -> value); } /** * Map the result of this async result to {@code null}.<p> * * This is a convenience for {@code asyncResult.map((T) null)} or {@code asyncResult.map((Void) null)}.<p> * * When this async result succeeds, {@code null} will succeeed the async result returned by this method call.<p> * * When this async result fails, the failure will be propagated to the returned async result. * * @return the mapped async result */ default <V> AsyncResult<V> mapEmpty() { return map((V)null); } /** * Apply a {@code mapper} function on this async result.<p> * * The {@code mapper} is called with the failure and this mapper returns a value. This value will complete the result returned by this method call.<p> * * When this async result is succeeded, the value will be propagated to the returned async result and the {@code mapper} will not be called. * * @param mapper the mapper function * @return the mapped async result */ default AsyncResult<T> otherwise(Function<Throwable, T> mapper) { if (mapper == null) { throw new NullPointerException(); } return new AsyncResult<T>() { @Override public T result() { if (AsyncResult.this.succeeded()) { return AsyncResult.this.result(); } else if (AsyncResult.this.failed()) { return mapper.apply(AsyncResult.this.cause()); } else { return null; } } @Override public Throwable cause() { return null; } @Override public boolean succeeded() { return AsyncResult.this.succeeded() || AsyncResult.this.failed(); } @Override public boolean failed() { return false; } }; } /** * Map the failure of this async result to a specific {@code value}.<p> * * When this async result fails, this {@code value} will succeeed the async result returned by this method call.<p> * * When this async succeeds, the result will be propagated to the returned async result. * * @param value the value that eventually completes the mapped async result * @return the mapped async result */ default AsyncResult<T> otherwise(T value) { return otherwise(err -> value); } /** * Map the failure of this async result to {@code null}.<p> * * This is a convenience for {@code asyncResult.otherwise((T) null)}.<p> * * When this async result fails, the {@code null} will succeeed the async result returned by this method call.<p> * * When this async succeeds, the result will be propagated to the returned async result. * * @return the mapped async result */ default AsyncResult<T> otherwiseEmpty() { return otherwise(err -> null); } }
AsyncResult
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/ConnectorConfigTest.java
{ "start": 2669, "end": 9182 }
class ____<R extends ConnectRecord<R>> implements Transformation<R>, Versioned { int magicNumber = 0; @Override public String version() { return "1.0"; } @Override public void configure(Map<String, ?> props) { magicNumber = Integer.parseInt((String) props.get("magic.number")); } @Override public R apply(R record) { return record.newRecord(null, magicNumber, null, null, null, null, 0L); } @Override public void close() { magicNumber = 0; } @Override public ConfigDef config() { return new ConfigDef() .define("magic.number", ConfigDef.Type.INT, ConfigDef.NO_DEFAULT_VALUE, ConfigDef.Range.atLeast(42), ConfigDef.Importance.HIGH, ""); } } @Test public void noTransforms() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); new ConnectorConfig(MOCK_PLUGINS, props); } @Test public void danglingTransformAlias() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "dangler"); ConfigException e = assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); assertTrue(e.getMessage().contains("Not a Transformation")); } @Test public void emptyConnectorName() { Map<String, String> props = new HashMap<>(); props.put("name", ""); props.put("connector.class", TestConnector.class.getName()); ConfigException e = assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); assertTrue(e.getMessage().contains("String may not be empty")); } @Test public void wrongTransformationType() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a"); props.put("transforms.a.type", "uninstantiable"); ConfigException e = assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); assertTrue(e.getMessage().contains("Class uninstantiable could not be found")); } @Test public void unconfiguredTransform() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a"); props.put("transforms.a.type", SimpleTransformation.class.getName()); ConfigException e = assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); assertTrue(e.getMessage().contains("Missing required configuration \"transforms.a.magic.number\" which")); } @Test public void misconfiguredTransform() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a"); props.put("transforms.a.type", SimpleTransformation.class.getName()); props.put("transforms.a.magic.number", "40"); ConfigException e = assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); assertTrue(e.getMessage().contains("Value must be at least 42")); } @Test public void singleTransform() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a"); props.put("transforms.a.type", SimpleTransformation.class.getName()); props.put("transforms.a.magic.number", "42"); final ConnectorConfig config = new ConnectorConfig(MOCK_PLUGINS, props); final List<TransformationStage<SinkRecord>> transformationStages = config.transformationStages(MOCK_PLUGINS, CONNECTOR_TASK_ID, METRICS); assertEquals(1, transformationStages.size()); final TransformationStage<SinkRecord> stage = transformationStages.get(0); assertEquals(SimpleTransformation.class, stage.transformClass()); assertEquals(42, stage.apply(DUMMY_RECORD).kafkaPartition().intValue()); } @Test public void multipleTransformsOneDangling() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a, b"); props.put("transforms.a.type", SimpleTransformation.class.getName()); props.put("transforms.a.magic.number", "42"); assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); } @Test public void multipleTransforms() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a, b"); props.put("transforms.a.type", SimpleTransformation.class.getName()); props.put("transforms.a.magic.number", "42"); props.put("transforms.b.type", SimpleTransformation.class.getName()); props.put("transforms.b.magic.number", "84"); final ConnectorConfig config = new ConnectorConfig(MOCK_PLUGINS, props); final List<TransformationStage<SinkRecord>> transformationStages = config.transformationStages(MOCK_PLUGINS, CONNECTOR_TASK_ID, METRICS); assertEquals(2, transformationStages.size()); assertEquals(42, transformationStages.get(0).apply(DUMMY_RECORD).kafkaPartition().intValue()); assertEquals(84, transformationStages.get(1).apply(DUMMY_RECORD).kafkaPartition().intValue()); } @Test public void abstractTransform() { Map<String, String> props = new HashMap<>(); props.put("name", "test"); props.put("connector.class", TestConnector.class.getName()); props.put("transforms", "a"); props.put("transforms.a.type", AbstractTransformation.class.getName()); ConfigException ex = assertThrows(ConfigException.class, () -> new ConnectorConfig(MOCK_PLUGINS, props)); assertTrue( ex.getMessage().contains("This
SimpleTransformation
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/tier/remote/RemoteTierFactory.java
{ "start": 2986, "end": 6579 }
class ____ implements TierFactory { private static final String DEFAULT_REMOTE_STORAGE_BASE_PATH = null; private static final int DEFAULT_REMOTE_TIER_EXCLUSIVE_BUFFERS = 1; private static final int DEFAULT_REMOTE_TIER_NUM_BYTES_PER_SEGMENT = 16 * 32 * 1024; private int bufferSizeBytes = -1; private String remoteStoragePath = DEFAULT_REMOTE_STORAGE_BASE_PATH; @Override public void setup(Configuration configuration) { this.bufferSizeBytes = ConfigurationParserUtils.getPageSize(configuration); this.remoteStoragePath = checkNotNull( configuration.get( NettyShuffleEnvironmentOptions .NETWORK_HYBRID_SHUFFLE_REMOTE_STORAGE_BASE_PATH)); } @Override public TieredStorageMemorySpec getMasterAgentMemorySpec() { return new TieredStorageMemorySpec(getRemoteTierName(), 0); } @Override public TieredStorageMemorySpec getProducerAgentMemorySpec() { return new TieredStorageMemorySpec( getRemoteTierName(), DEFAULT_REMOTE_TIER_EXCLUSIVE_BUFFERS); } @Override public TieredStorageMemorySpec getConsumerAgentMemorySpec() { return new TieredStorageMemorySpec(getRemoteTierName(), 0); } @Override public TierMasterAgent createMasterAgent(TieredStorageResourceRegistry resourceRegistry) { return new RemoteTierMasterAgent(remoteStoragePath, resourceRegistry); } @Override public TierProducerAgent createProducerAgent( int numPartitions, int numSubpartitions, TieredStoragePartitionId partitionID, String dataFileBasePath, boolean isBroadcastOnly, TieredStorageMemoryManager storageMemoryManager, TieredStorageNettyService nettyService, TieredStorageResourceRegistry resourceRegistry, BatchShuffleReadBufferPool bufferPool, ScheduledExecutorService ioExecutor, List<TierShuffleDescriptor> shuffleDescriptors, int maxRequestedBuffers, @Nullable BufferCompressor bufferCompressor) { checkState(bufferSizeBytes > 0); checkNotNull(remoteStoragePath); PartitionFileWriter partitionFileWriter = SegmentPartitionFile.createPartitionFileWriter(remoteStoragePath, numSubpartitions); return new RemoteTierProducerAgent( partitionID, numSubpartitions, DEFAULT_REMOTE_TIER_NUM_BYTES_PER_SEGMENT, bufferSizeBytes, isBroadcastOnly, partitionFileWriter, storageMemoryManager, resourceRegistry, bufferCompressor); } @Override public TierConsumerAgent createConsumerAgent( List<TieredStorageConsumerSpec> tieredStorageConsumerSpecs, List<TierShuffleDescriptor> shuffleDescriptors, TieredStorageNettyService nettyService) { PartitionFileReader partitionFileReader = SegmentPartitionFile.createPartitionFileReader(remoteStoragePath); RemoteStorageScanner remoteStorageScanner = new RemoteStorageScanner(remoteStoragePath); return new RemoteTierConsumerAgent( tieredStorageConsumerSpecs, remoteStorageScanner, partitionFileReader, bufferSizeBytes); } @Override public String identifier() { return "remote"; } }
RemoteTierFactory
java
apache__flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/operator/StreamRecordComparator.java
{ "start": 1117, "end": 1574 }
class ____<IN> implements Comparator<StreamRecord<IN>>, Serializable { private static final long serialVersionUID = 1581054988433915305L; @Override public int compare(StreamRecord<IN> o1, StreamRecord<IN> o2) { if (o1.getTimestamp() < o2.getTimestamp()) { return -1; } else if (o1.getTimestamp() > o2.getTimestamp()) { return 1; } else { return 0; } } }
StreamRecordComparator
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java
{ "start": 1899, "end": 6351 }
class ____ { private static final Map<String, Object> HINTS = Collections.emptyMap(); private final ResourceHttpMessageWriter writer = new ResourceHttpMessageWriter(); private final MockServerHttpResponse response = new MockServerHttpResponse(); private final Mono<Resource> input = Mono.just(new ByteArrayResource( "Spring Framework test resource content.".getBytes(StandardCharsets.UTF_8))); @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void getWritableMediaTypes() { assertThat((List) this.writer.getWritableMediaTypes()) .containsExactlyInAnyOrder(MimeTypeUtils.APPLICATION_OCTET_STREAM, MimeTypeUtils.ALL); } @Test void writeResourceServer() { testWrite(get("/").build()); assertThat(this.response.getHeaders().getContentType()).isEqualTo(TEXT_PLAIN); assertThat(this.response.getHeaders().getContentLength()).isEqualTo(39L); assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); String content = "Spring Framework test resource content."; StepVerifier.create(this.response.getBodyAsString()).expectNext(content).expectComplete().verify(); } @Test void writeResourceClient() { MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, "/"); Mono<Void> mono = this.writer.write(this.input, ResolvableType.forClass(Resource.class), TEXT_PLAIN, request, HINTS); StepVerifier.create(mono).expectComplete().verify(); assertThat(request.getHeaders().getContentType()).isEqualTo(TEXT_PLAIN); assertThat(request.getHeaders().getContentLength()).isEqualTo(39L); assertThat(request.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)).isNull(); String content = "Spring Framework test resource content."; StepVerifier.create(request.getBodyAsString()).expectNext(content).expectComplete().verify(); } @Test void writeSingleRegion() { testWrite(get("/").range(of(0, 5)).build()); assertThat(this.response.getHeaders().getContentType()).isEqualTo(TEXT_PLAIN); assertThat(this.response.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE)).isEqualTo("bytes 0-5/39"); assertThat(this.response.getHeaders().getContentLength()).isEqualTo(6L); StepVerifier.create(this.response.getBodyAsString()).expectNext("Spring").expectComplete().verify(); } @Test void writeMultipleRegions() { testWrite(get("/").range(of(0,5), of(7,15), of(17,20), of(22,38)).build()); HttpHeaders headers = this.response.getHeaders(); String contentType = headers.getContentType().toString(); String boundary = contentType.substring(30); assertThat(contentType).startsWith("multipart/byteranges;boundary="); StepVerifier.create(this.response.getBodyAsString()) .consumeNextWith(content -> { String[] actualRanges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); String[] expected = new String[] { "--" + boundary, "Content-Type: text/plain", "Content-Range: bytes 0-5/39", "Spring", "--" + boundary, "Content-Type: text/plain", "Content-Range: bytes 7-15/39", "Framework", "--" + boundary, "Content-Type: text/plain", "Content-Range: bytes 17-20/39", "test", "--" + boundary, "Content-Type: text/plain", "Content-Range: bytes 22-38/39", "resource content.", "--" + boundary + "--" }; assertThat(actualRanges).isEqualTo(expected); }) .expectComplete() .verify(); } @Test void invalidRange() { testWrite(get("/").header(HttpHeaders.RANGE, "invalid").build()); assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); assertThat(this.response.getStatusCode()).isEqualTo(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); } @Test // gh-35536 void invalidRangePosition() { testWrite(get("/").header(HttpHeaders.RANGE, "bytes=2000-5000").build()); assertThat(this.response.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)).isEqualTo("bytes"); assertThat(this.response.getStatusCode()).isEqualTo(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); } private void testWrite(MockServerHttpRequest request) { Mono<Void> mono = this.writer.write(this.input, null, null, TEXT_PLAIN, request, this.response, HINTS); StepVerifier.create(mono).expectComplete().verify(); } private static HttpRange of(int first, int last) { return HttpRange.createByteRange(first, last); } }
ResourceHttpMessageWriterTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/oncrpc/RpcUtil.java
{ "start": 3657, "end": 5125 }
class ____ extends ChannelInboundHandlerAdapter { private static final Logger LOG = LoggerFactory .getLogger(RpcMessageParserStage.class); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf; SocketAddress remoteAddress; if (msg instanceof DatagramPacket) { DatagramPacket packet = (DatagramPacket)msg; buf = packet.content(); remoteAddress = packet.sender(); } else { buf = (ByteBuf) msg; remoteAddress = ctx.channel().remoteAddress(); } ByteBuffer b = buf.nioBuffer().asReadOnlyBuffer(); XDR in = new XDR(b, XDR.State.READING); RpcInfo info = null; try { RpcCall callHeader = RpcCall.read(in); ByteBuf dataBuffer = buf.slice(b.position(), b.remaining()); info = new RpcInfo(callHeader, dataBuffer, ctx, ctx.channel(), remoteAddress); } catch (Exception exc) { LOG.info("Malformed RPC request from " + remoteAddress); } finally { // only release buffer if it is not passed to downstream handler if (info == null) { buf.release(); } } if (info != null) { ctx.fireChannelRead(info); } } } /** * RpcTcpResponseStage sends an RpcResponse across the wire with the * appropriate fragment header. */ @ChannelHandler.Sharable private static
RpcMessageParserStage
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/ActiveProfiles.java
{ "start": 2887, "end": 3055 }
class ____ * <em>inherit</em> bean definition profiles defined by a test superclass or * enclosing class. Specifically, the bean definition profiles for a test *
will
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/StructAttributeValues.java
{ "start": 231, "end": 930 }
class ____ implements ValueAccess { private final Object[] attributeValues; private final int size; private Object discriminator; public StructAttributeValues(int size, Object[] rawJdbcValues) { this.size = size; if ( rawJdbcValues == null || size != rawJdbcValues.length) { attributeValues = new Object[size]; } else { attributeValues = rawJdbcValues; } } @Override public Object[] getValues() { return attributeValues; } public void setAttributeValue(int index, Object value) { if ( index == size ) { discriminator = value; } else { attributeValues[index] = value; } } public Object getDiscriminator() { return discriminator; } }
StructAttributeValues
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/jaxb/mapping/spi/JaxbStandardAttribute.java
{ "start": 347, "end": 532 }
interface ____ extends JaxbPersistentAttribute { FetchType getFetch(); void setFetch(FetchType value); Boolean isOptional(); void setOptional(Boolean optional); }
JaxbStandardAttribute
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java
{ "start": 7373, "end": 7564 }
interface ____ { TestBean getPrototypeDependency(); TestBean getPrototypeDependency(Object someParam); } /** * @author Rod Johnson * @author Juergen Hoeller */ abstract
OverrideInterface
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/util/InstantFormatter.java
{ "start": 6419, "end": 8057 }
class ____ implements Formatter { private final DateTimeFormatter formatter; private final MutableInstant mutableInstant; private JavaDateTimeFormatter(final String pattern, final Locale locale, final TimeZone timeZone) { this.formatter = DateTimeFormatter.ofPattern(pattern).withLocale(locale).withZone(timeZone.toZoneId()); this.mutableInstant = new MutableInstant(); } @Override public Class<?> getInternalImplementationClass() { return DateTimeFormatter.class; } @Override public void format(final Instant instant, final StringBuilder stringBuilder) { if (instant instanceof MutableInstant) { formatMutableInstant((MutableInstant) instant, stringBuilder); } else { formatInstant(instant, stringBuilder); } } private void formatMutableInstant(final MutableInstant instant, final StringBuilder stringBuilder) { formatter.formatTo(instant, stringBuilder); } private void formatInstant(final Instant instant, final StringBuilder stringBuilder) { mutableInstant.initFrom(instant); formatMutableInstant(mutableInstant, stringBuilder); } @Override public boolean isInstantMatching(final Instant instant1, final Instant instant2) { return instant1.getEpochSecond() == instant2.getEpochSecond() && instant1.getNanoOfSecond() == instant2.getNanoOfSecond(); } } private static final
JavaDateTimeFormatter
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptor.java
{ "start": 1824, "end": 6046 }
interface ____ { /** * Invoked immediately before the start of concurrent handling, in the same * thread that started it. This method may be used to capture state just prior * to the start of concurrent processing with the given {@code DeferredResult}. * @param request the current request * @param deferredResult the DeferredResult for the current request * @throws Exception in case of errors */ default <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { } /** * Invoked immediately after the start of concurrent handling, in the same * thread that started it. This method may be used to detect the start of * concurrent processing with the given {@code DeferredResult}. * <p>The {@code DeferredResult} may have already been set, for example at * the time of its creation or by another thread. * @param request the current request * @param deferredResult the DeferredResult for the current request * @throws Exception in case of errors */ default <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { } /** * Invoked after a {@code DeferredResult} has been set, via * {@link DeferredResult#setResult(Object)} or * {@link DeferredResult#setErrorResult(Object)}, and is also ready to * handle the concurrent result. * <p>This method may also be invoked after a timeout when the * {@code DeferredResult} was created with a constructor accepting a default * timeout result. * @param request the current request * @param deferredResult the DeferredResult for the current request * @param concurrentResult the concurrent result * @throws Exception in case of errors */ default <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, @Nullable Object concurrentResult) throws Exception { } /** * Invoked from a container thread when an async request times out before * the {@code DeferredResult} has been set. Implementations may invoke * {@link DeferredResult#setResult(Object) setResult} or * {@link DeferredResult#setErrorResult(Object) setErrorResult} to resume processing. * @param request the current request * @param deferredResult the DeferredResult for the current request; if the * {@code DeferredResult} is set, then concurrent processing is resumed and * subsequent interceptors are not invoked * @return {@code true} if processing should continue, or {@code false} if * other interceptors should not be invoked * @throws Exception in case of errors */ default <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { return true; } /** * Invoked from a container thread when an error occurred while processing an async request * before the {@code DeferredResult} has been set. Implementations may invoke * {@link DeferredResult#setResult(Object) setResult} or * {@link DeferredResult#setErrorResult(Object) setErrorResult} to resume processing. * @param request the current request * @param deferredResult the DeferredResult for the current request; if the * {@code DeferredResult} is set, then concurrent processing is resumed and * subsequent interceptors are not invoked * @param t the error that occurred while request processing * @return {@code true} if error handling should continue, or {@code false} if * other interceptors should be bypassed and not be invoked * @throws Exception in case of errors */ default <T> boolean handleError(NativeWebRequest request, DeferredResult<T> deferredResult, Throwable t) throws Exception { return true; } /** * Invoked from a container thread when an async request completed for any * reason including timeout and network error. This method is useful for * detecting that a {@code DeferredResult} instance is no longer usable. * @param request the current request * @param deferredResult the DeferredResult for the current request * @throws Exception in case of errors */ default <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { } }
DeferredResultProcessingInterceptor
java
grpc__grpc-java
api/src/main/java/io/grpc/NameResolver.java
{ "start": 15832, "end": 20075 }
class ____ for the argument's scope. * * <p>{@link Args} are normally reserved for information in *support* of name resolution, not * the name to be resolved itself. However, there are rare cases where all or part of the target * name can't be represented by any standard URI scheme or can't be encoded as a String at all. * Custom args, in contrast, can hold arbitrary Java types, making them a useful work around in * these cases. * * <p>Custom args can also be used simply to avoid adding inappropriate deps to the low level * io.grpc package. */ @SuppressWarnings("unchecked") // Cast is safe because all put()s go through the setArg() API. @Nullable public <T> T getArg(Key<T> key) { return customArgs != null ? (T) customArgs.get(key) : null; } /** * Returns the {@link ChannelLogger} for the Channel served by this NameResolver. * * @since 1.26.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/6438") public ChannelLogger getChannelLogger() { if (channelLogger == null) { throw new IllegalStateException("ChannelLogger is not set in Builder"); } return channelLogger; } /** * Returns the Executor on which this resolver should execute long-running or I/O bound work. * Null if no Executor was set. * * @since 1.25.0 */ @Nullable public Executor getOffloadExecutor() { return executor; } /** * Returns the overrideAuthority from channel {@link ManagedChannelBuilder#overrideAuthority}. * Overrides the host name for L7 HTTP virtual host matching. Almost all name resolvers should * not use this. * * @since 1.49.0 */ @Nullable @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9406") public String getOverrideAuthority() { return overrideAuthority; } /** * Returns the {@link MetricRecorder} that the channel uses to record metrics. */ @Nullable public MetricRecorder getMetricRecorder() { return metricRecorder; } /** * Returns the {@link NameResolverRegistry} that the Channel uses to look for {@link * NameResolver}s. * * @since 1.74.0 */ public NameResolverRegistry getNameResolverRegistry() { if (nameResolverRegistry == null) { throw new IllegalStateException("NameResolverRegistry is not set in Builder"); } return nameResolverRegistry; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("defaultPort", defaultPort) .add("proxyDetector", proxyDetector) .add("syncContext", syncContext) .add("serviceConfigParser", serviceConfigParser) .add("customArgs", customArgs) .add("scheduledExecutorService", scheduledExecutorService) .add("channelLogger", channelLogger) .add("executor", executor) .add("overrideAuthority", overrideAuthority) .add("metricRecorder", metricRecorder) .add("nameResolverRegistry", nameResolverRegistry) .toString(); } /** * Returns a builder with the same initial values as this object. * * @since 1.21.0 */ public Builder toBuilder() { Builder builder = new Builder(); builder.setDefaultPort(defaultPort); builder.setProxyDetector(proxyDetector); builder.setSynchronizationContext(syncContext); builder.setServiceConfigParser(serviceConfigParser); builder.setScheduledExecutorService(scheduledExecutorService); builder.setChannelLogger(channelLogger); builder.setOffloadExecutor(executor); builder.setOverrideAuthority(overrideAuthority); builder.setMetricRecorder(metricRecorder); builder.setNameResolverRegistry(nameResolverRegistry); builder.customArgs = cloneCustomArgs(customArgs); return builder; } /** * Creates a new builder. * * @since 1.21.0 */ public static Builder newBuilder() { return new Builder(); } /** * Builder for {@link Args}. * * @since 1.21.0 */ public static final
appropriate
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
{ "start": 3696, "end": 4281 }
class ____ from caching, but some comes // from the special int to StringBuffer conversion. // // The following produces a padded 2-digit number: // buffer.append((char)(value / 10 + '0')); // buffer.append((char)(value % 10 + '0')); // // Note that the fastest append to StringBuffer is a single char (used here). // Note that Integer.toString() is not called, the conversion is simply // taking the value and adding (mathematically) the ASCII value for '0'. // So, don't change this code! It works and is very fast. /** * Inner
comes
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/StoragePolicyAdmin.java
{ "start": 8474, "end": 9963 }
class ____ implements AdminHelper.Command { @Override public String getName() { return "-satisfyStoragePolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -path <path>]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<path>", "The path of the file/directory to satisfy" + " storage policy"); return getShortUsage() + "\n" + "Schedule blocks to move based on file/directory policy.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String path = StringUtils.popOptionWithArgument("-path", args); if (path == null) { System.err.println("Please specify the path for setting the storage " + "policy.\nUsage: " + getLongUsage()); return 1; } Path p = new Path(path); final FileSystem fs = FileSystem.get(p.toUri(), conf); try { fs.satisfyStoragePolicy(p); System.out.println("Scheduled blocks to move based on the current" + " storage policy on " + path); } catch (Exception e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /* Command to unset the storage policy set for a file/directory */ private static
SatisfyStoragePolicyCommand
java
apache__maven
compat/maven-compat/src/test/java/org/apache/maven/project/inheritance/t07/ProjectInheritanceTest.java
{ "start": 1433, "end": 3078 }
class ____ extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 // p0 inherits from super model // // or we can show it graphically as: // // p1 ---> p0 --> super model // // ---------------------------------------------------------------------- @Test void testDependencyManagement() throws Exception { File localRepo = getLocalRepositoryPath(); File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load everything... MavenProject project1 = getProjectWithDependencies(pom1); assertEquals(pom0Basedir, project1.getParent().getBasedir()); System.out.println("Project " + project1.getId() + " " + project1); Set set = project1.getArtifacts(); assertNotNull(set, "No artifacts"); assertFalse(set.isEmpty(), "No Artifacts"); assertTrue(set.size() == 3, "Set size should be 3, is " + set.size()); for (Object aSet : set) { Artifact artifact = (Artifact) aSet; assertFalse(artifact.getArtifactId().equals("t07-d")); System.out.println("Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + " Optional=" + (artifact.isOptional() ? "true" : "false")); assertTrue( artifact.getVersion().equals("1.0"), "Incorrect version for " + artifact.getDependencyConflictId()); } } }
ProjectInheritanceTest
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/PluginUtils.java
{ "start": 16525, "end": 18228 }
class ____ of the plugin. */ public static String prunedName(PluginDesc<?> plugin) { // It's currently simpler to switch on type than do pattern matching. return switch (plugin.type()) { case SOURCE, SINK -> prunePluginName(plugin, "Connector"); default -> prunePluginName(plugin, plugin.type().simpleName()); }; } private static String prunePluginName(PluginDesc<?> plugin, String suffix) { String simple = plugin.pluginClass().getSimpleName(); int pos = simple.lastIndexOf(suffix); if (pos > 0) { return simple.substring(0, pos); } return simple; } public static Map<String, String> computeAliases(PluginScanResult scanResult) { Map<String, Set<String>> aliasCollisions = new HashMap<>(); scanResult.forEach(pluginDesc -> { aliasCollisions.computeIfAbsent(simpleName(pluginDesc), ignored -> new HashSet<>()).add(pluginDesc.className()); aliasCollisions.computeIfAbsent(prunedName(pluginDesc), ignored -> new HashSet<>()).add(pluginDesc.className()); }); Map<String, String> aliases = new HashMap<>(); for (Map.Entry<String, Set<String>> entry : aliasCollisions.entrySet()) { String alias = entry.getKey(); Set<String> classNames = entry.getValue(); if (classNames.size() == 1) { aliases.put(alias, classNames.stream().findAny().get()); } else { log.debug("Ignoring ambiguous alias '{}' since it refers to multiple distinct plugins {}", alias, classNames); } } return aliases; } private static
name
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/query/RankDocsQueryBuilderTests.java
{ "start": 1481, "end": 12429 }
class ____ extends AbstractQueryTestCase<RankDocsQueryBuilder> { private RankDoc[] generateRandomRankDocs() { int totalDocs = randomIntBetween(0, 10); RankDoc[] rankDocs = new RankDoc[totalDocs]; int currentDoc = 0; for (int i = 0; i < totalDocs; i++) { RankDoc rankDoc = new RankDoc(currentDoc, randomFloat(), randomIntBetween(0, 2)); rankDocs[i] = rankDoc; currentDoc += randomIntBetween(0, 100); } return rankDocs; } @Override protected RankDocsQueryBuilder doCreateTestQueryBuilder() { RankDoc[] rankDocs = generateRandomRankDocs(); return new RankDocsQueryBuilder(rankDocs, null, false); } @Override protected void doAssertLuceneQuery(RankDocsQueryBuilder queryBuilder, Query query, SearchExecutionContext context) throws IOException { assertTrue(query instanceof RankDocsQuery); RankDocsQuery rankDocsQuery = (RankDocsQuery) query; assertArrayEquals(queryBuilder.rankDocs(), rankDocsQuery.rankDocs()); } /** * Overridden to ensure that {@link SearchExecutionContext} has a non-null {@link IndexReader} */ @Override public void testToQuery() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(new Document()); try (IndexReader reader = iw.getReader()) { SearchExecutionContext context = createSearchExecutionContext(newSearcher(reader)); RankDocsQueryBuilder queryBuilder = createTestQueryBuilder(); Query query = queryBuilder.doToQuery(context); assertTrue(query instanceof RankDocsQuery); RankDocsQuery rankDocsQuery = (RankDocsQuery) query; int shardIndex = context.getShardRequestIndex(); int expectedDocs = (int) Arrays.stream(queryBuilder.rankDocs()).filter(x -> x.shardIndex == shardIndex).count(); assertEquals(expectedDocs, rankDocsQuery.rankDocs().length); } } } /** * Overridden to ensure that {@link SearchExecutionContext} has a non-null {@link IndexReader} */ @Override public void testCacheability() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(new Document()); try (IndexReader reader = iw.getReader()) { SearchExecutionContext context = createSearchExecutionContext(newSearcher(reader)); RankDocsQueryBuilder queryBuilder = createTestQueryBuilder(); QueryBuilder rewriteQuery = rewriteQuery(queryBuilder, new SearchExecutionContext(context)); assertNotNull(rewriteQuery.toQuery(context)); assertTrue("query should be cacheable: " + queryBuilder.toString(), context.isCacheable()); } } } /** * Overridden to ensure that {@link SearchExecutionContext} has a non-null {@link IndexReader} */ @Override public void testMustRewrite() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(new Document()); try (IndexReader reader = iw.getReader()) { SearchExecutionContext context = createSearchExecutionContext(newSearcher(reader)); context.setAllowUnmappedFields(true); RankDocsQueryBuilder queryBuilder = createTestQueryBuilder(); queryBuilder.toQuery(context); } } } public void testRankDocsQueryEarlyTerminate() throws IOException { try (Directory directory = newDirectory()) { IndexWriterConfig config = new IndexWriterConfig().setMergePolicy(NoMergePolicy.INSTANCE); try (IndexWriter iw = new IndexWriter(directory, config)) { int seg = atLeast(5); int numDocs = atLeast(20); for (int i = 0; i < seg; i++) { for (int j = 0; j < numDocs; j++) { Document doc = new Document(); doc.add(new NumericDocValuesField("active", 1)); iw.addDocument(doc); } if (frequently()) { iw.flush(); } } } try (IndexReader reader = DirectoryReader.open(directory)) { int topSize = randomIntBetween(1, reader.maxDoc() / 5); RankDoc[] rankDocs = new RankDoc[topSize]; int index = 0; for (int r : randomSample(random(), reader.maxDoc(), topSize)) { rankDocs[index++] = new RankDoc(r, randomFloat(), randomIntBetween(0, 5)); } Arrays.sort(rankDocs); for (int i = 0; i < rankDocs.length; i++) { rankDocs[i].rank = i; } IndexSearcher searcher = new IndexSearcher(reader); for (int totalHitsThreshold = 0; totalHitsThreshold < reader.maxDoc(); totalHitsThreshold += randomIntBetween(1, 10)) { // Tests that the query matches only the {@link RankDoc} when the hit threshold is reached. RankDocsQuery q = new RankDocsQuery( reader, rankDocs, new Query[] { NumericDocValuesField.newSlowExactQuery("active", 1) }, new String[1], false ); var topDocsManager = new TopScoreDocCollectorManager(topSize, null, totalHitsThreshold); var col = searcher.search(q, topDocsManager); // depending on the doc-ids of the RankDocs (i.e. the actual docs to have score) we could visit them last, // so worst case is we could end up collecting up to 1 + max(topSize , totalHitsThreshold) + rankDocs.length documents // as we could have already filled the priority queue with non-optimal docs assertThat( col.totalHits.value(), lessThanOrEqualTo((long) (1 + Math.max(topSize, totalHitsThreshold) + rankDocs.length)) ); assertEqualTopDocs(col.scoreDocs, rankDocs); } { // Return all docs (rank + tail) RankDocsQuery q = new RankDocsQuery( reader, rankDocs, new Query[] { NumericDocValuesField.newSlowExactQuery("active", 1) }, new String[1], false ); var topDocsManager = new TopScoreDocCollectorManager(topSize, null, Integer.MAX_VALUE); var col = searcher.search(q, topDocsManager); assertThat(col.totalHits.value(), equalTo((long) reader.maxDoc())); assertEqualTopDocs(col.scoreDocs, rankDocs); } { // Only rank docs RankDocsQuery q = new RankDocsQuery( reader, rankDocs, new Query[] { NumericDocValuesField.newSlowExactQuery("active", 1) }, new String[1], true ); var topDocsManager = new TopScoreDocCollectorManager(topSize, null, Integer.MAX_VALUE); var col = searcher.search(q, topDocsManager); assertThat(col.totalHits.value(), equalTo((long) topSize)); assertEqualTopDocs(col.scoreDocs, rankDocs); } { // A single rank doc in the last segment RankDoc[] singleRankDoc = new RankDoc[1]; singleRankDoc[0] = rankDocs[rankDocs.length - 1]; RankDocsQuery q = new RankDocsQuery( reader, singleRankDoc, new Query[] { NumericDocValuesField.newSlowExactQuery("active", 1) }, new String[1], false ); var topDocsManager = new TopScoreDocCollectorManager(1, null, 0); var col = searcher.search(q, topDocsManager); assertThat(col.totalHits.value(), lessThanOrEqualTo((long) (2 + rankDocs.length))); assertEqualTopDocs(col.scoreDocs, singleRankDoc); } } } } private static int[] randomSample(Random rand, int n, int k) { int[] reservoir = new int[k]; for (int i = 0; i < k; i++) { reservoir[i] = i; } for (int i = k; i < n; i++) { int j = rand.nextInt(i + 1); if (j < k) { reservoir[j] = i; } } return reservoir; } private static void assertEqualTopDocs(ScoreDoc[] scoreDocs, RankDoc[] rankDocs) { for (int i = 0; i < scoreDocs.length; i++) { assertEquals(rankDocs[i].doc, scoreDocs[i].doc); assertEquals(rankDocs[i].score, scoreDocs[i].score, 0f); assertEquals(-1, scoreDocs[i].shardIndex); } } @Override public void testFromXContent() throws IOException { // no-op since RankDocsQueryBuilder is an internal only API } @Override public void testUnknownField() throws IOException { // no-op since RankDocsQueryBuilder is agnostic to unknown fields and an internal only API } @Override public void testValidOutput() throws IOException { // no-op since RankDocsQueryBuilder is an internal only API } public void shouldThrowForNegativeScores() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(new Document()); try (IndexReader reader = iw.getReader()) { SearchExecutionContext context = createSearchExecutionContext(newSearcher(reader)); RankDocsQueryBuilder queryBuilder = new RankDocsQueryBuilder(new RankDoc[] { new RankDoc(0, -1.0f, 0) }, null, false); IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> queryBuilder.doToQuery(context)); assertEquals("RankDoc scores must be positive values. Missing a normalization step?", ex.getMessage()); } } } }
RankDocsQueryBuilderTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/tableperclass/Product.java
{ "start": 456, "end": 492 }
class ____ extends Component { }
Product
java
apache__flink
flink-queryable-state/flink-queryable-state-runtime/src/test/java/org/apache/flink/queryablestate/network/AbstractServerTest.java
{ "start": 8833, "end": 9578 }
class ____ extends MessageBody { private final String message; TestMessage(String message) { this.message = Preconditions.checkNotNull(message); } public String getMessage() { return message; } @Override public byte[] serialize() { byte[] content = message.getBytes(ConfigConstants.DEFAULT_CHARSET); // message size + 4 for the length itself return ByteBuffer.allocate(content.length + Integer.BYTES) .putInt(content.length) .put(content) .array(); } /** The deserializer for our {@link TestMessage test messages}. */ public static
TestMessage
java
resilience4j__resilience4j
resilience4j-circuitbreaker/src/test/java/io/github/resilience4j/circuitbreaker/CircuitBreakerRegistryTest.java
{ "start": 21445, "end": 21918 }
class ____ implements RegistryEventConsumer<CircuitBreaker> { @Override public void onEntryAddedEvent(EntryAddedEvent<CircuitBreaker> entryAddedEvent) { } @Override public void onEntryRemovedEvent(EntryRemovedEvent<CircuitBreaker> entryRemoveEvent) { } @Override public void onEntryReplacedEvent(EntryReplacedEvent<CircuitBreaker> entryReplacedEvent) { } } }
NoOpCircuitBreakerEventConsumer
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoOneOfTest.java
{ "start": 17898, "end": 17954 }
enum ____ { FUNKY_STRING } public static
Kind
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpointStatsSummary.java
{ "start": 1077, "end": 4172 }
class ____ implements Serializable { private static final long serialVersionUID = 5784360461635814038L; private static final int HISTOGRAM_WINDOW_SIZE = 10_000; // ~300Kb per job with four histograms /** State size statistics for all completed checkpoints. */ private final StatsSummary stateSize; private final StatsSummary checkpointedSize; /** Duration statistics for all completed checkpoints. */ private final StatsSummary duration; private final StatsSummary processedData; private final StatsSummary persistedData; CompletedCheckpointStatsSummary() { this( new StatsSummary(HISTOGRAM_WINDOW_SIZE), new StatsSummary(HISTOGRAM_WINDOW_SIZE), new StatsSummary(HISTOGRAM_WINDOW_SIZE), new StatsSummary(HISTOGRAM_WINDOW_SIZE), new StatsSummary(HISTOGRAM_WINDOW_SIZE)); } private CompletedCheckpointStatsSummary( StatsSummary stateSize, StatsSummary checkpointedSize, StatsSummary duration, StatsSummary processedData, StatsSummary persistedData) { this.stateSize = checkNotNull(stateSize); this.checkpointedSize = checkNotNull(checkpointedSize); this.duration = checkNotNull(duration); this.processedData = checkNotNull(processedData); this.persistedData = checkNotNull(persistedData); } /** * Updates the summary with the given completed checkpoint. * * @param completed Completed checkpoint to update the summary with. */ void updateSummary(CompletedCheckpointStats completed) { stateSize.add(completed.getStateSize()); checkpointedSize.add(completed.getCheckpointedSize()); duration.add(completed.getEndToEndDuration()); processedData.add(completed.getProcessedData()); persistedData.add(completed.getPersistedData()); } /** * Creates a snapshot of the current state. * * @return A snapshot of the current state. */ CompletedCheckpointStatsSummarySnapshot createSnapshot() { return new CompletedCheckpointStatsSummarySnapshot( duration.createSnapshot(), processedData.createSnapshot(), persistedData.createSnapshot(), stateSize.createSnapshot(), checkpointedSize.createSnapshot()); } /** * Returns the summary stats for the state size of completed checkpoints. * * @return Summary stats for the state size. */ public StatsSummary getStateSizeStats() { return stateSize; } /** * Returns the summary stats for the duration of completed checkpoints. * * @return Summary stats for the duration. */ public StatsSummary getEndToEndDurationStats() { return duration; } public StatsSummary getProcessedDataStats() { return processedData; } public StatsSummary getPersistedDataStats() { return persistedData; } }
CompletedCheckpointStatsSummary
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueJava8Test.java
{ "start": 6411, "end": 10095 }
class ____ { abstract @Nullable String nullableString(); abstract int randomInt(); static NullableProperties create(@Nullable String nullableString, int randomInt) { return new AutoValue_AutoValueJava8Test_NullableProperties(nullableString, randomInt); } } @Test public void testNullablePropertiesCanBeNull() { NullableProperties instance = NullableProperties.create(null, 23); assertThat(instance.nullableString()).isNull(); assertThat(instance.randomInt()).isEqualTo(23); assertThat(instance.toString()) .isEqualTo("NullableProperties{nullableString=null, randomInt=23}"); } @Test public void testEqualsParameterIsAnnotated() throws NoSuchMethodException { // Sadly we can't rely on JDK 8 to handle type annotations correctly. // Some versions do, some don't. So skip the test unless we are on at least JDK 9. double javaVersion = Double.parseDouble(JAVA_SPECIFICATION_VERSION.value()); assume().that(javaVersion).isAtLeast(9.0); NullableProperties nullableProperties = NullableProperties.create(null, 23); Method equals = nullableProperties.getClass().getMethod("equals", Object.class); // If `java.lang.Object.equals` is itself annotated, for example with the JSpecify `@Nullable`, // then we will copy that annotation onto the parameter of the generated `equals` // implementation. Otherwise we will copy the `@Nullable` from the return type of the // `nullableString()` method. So we accept either @Nullable here. // (You might think we could just reflect on Object.equals to see if it has @Nullable, but in // some environments we have nullness annotations at compile time but not at run time.) assertThat(equals.getAnnotatedParameterTypes()[0].getAnnotations()) .asList() .containsAnyIn(nullables(nullableProperties.getClass())); } @AutoAnnotation static Nullable nullable() { return new AutoAnnotation_AutoValueJava8Test_nullable(); } /** * Returns a set containing this test's {@link Nullable @Nullable} annotation, plus possibly * another {@code @Nullable} that is present on the parameter of {@link Object#equals}. */ static ImmutableSet<Annotation> nullables(Class<?> autoValueImplClass) { try { return Stream.concat( Stream.of(nullable()), stream( autoValueImplClass .getMethod("equals", Object.class) .getAnnotatedParameterTypes()[0] .getAnnotations()) .filter(a -> a.annotationType().getSimpleName().equals("Nullable"))) .collect(toImmutableSet()); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } @Test public void testNullablePropertyImplementationIsNullable() throws NoSuchMethodException { Method method = AutoValue_AutoValueJava8Test_NullableProperties.class.getDeclaredMethod("nullableString"); assertThat(method.getAnnotatedReturnType().getAnnotations()).asList().contains(nullable()); } @Test public void testNullablePropertyConstructorParameterIsNullable() throws NoSuchMethodException { Constructor<?> constructor = AutoValue_AutoValueJava8Test_NullableProperties.class.getDeclaredConstructor( String.class, int.class); try { assertThat(constructor.getAnnotatedParameterTypes()[0].getAnnotations()) .asList() .contains(nullable()); } catch (AssertionError e) { if (javacHandlesTypeAnnotationsCorrectly) { throw e; } } } @AutoValue abstract static
NullableProperties
java
playframework__playframework
web/play-java-forms/src/main/java/play/data/validation/Constraints.java
{ "start": 19864, "end": 19991 }
interface ____ { ValidateWith[] value(); } } /** Validator for {@code @ValidateWith} fields. */ public static
List
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitchTest.java
{ "start": 5405, "end": 6090 }
enum ____ { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } void m(Case c) { // BUG: Diagnostic contains: TWO, THREE, FOUR, and 4 others switch (c) { case ONE: System.err.println("found it!"); break; } } } """) .doTest(); } @Test public void nonExhaustive_nonEnum() { compilationHelper .addSourceLines( "Test.java", """
Case
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
{ "start": 29218, "end": 36970 }
class ____ implements the <code>org.apache.kafka.streams.processor.TimestampExtractor</code> interface."; /** {@code enable.metrics.push} */ @SuppressWarnings("WeakerAccess") public static final String ENABLE_METRICS_PUSH_CONFIG = CommonClientConfigs.ENABLE_METRICS_PUSH_CONFIG; @Deprecated public static final String ENABLE_METRICS_PUSH_DOC = "Whether to enable pushing of internal client metrics for (main, restore, and global) consumers, producers, and admin clients." + " The cluster must have a client metrics subscription which corresponds to a client."; /** {@code ensure.explicit.internal.resource.naming} */ public static final String ENSURE_EXPLICIT_INTERNAL_RESOURCE_NAMING_CONFIG = "ensure.explicit.internal.resource.naming"; static final String ENSURE_EXPLICIT_INTERNAL_RESOURCE_NAMING_DOC = "Whether to enforce explicit naming for all internal resources of the topology, including internal" + " topics (e.g., changelog and repartition topics) and their associated state stores." + " When enabled, the application will refuse to start if any internal resource has an auto-generated name."; /** * <code>group.protocol</code> */ public static final String GROUP_PROTOCOL_CONFIG = "group.protocol"; public static final String DEFAULT_GROUP_PROTOCOL = GroupProtocol.CLASSIC.name().toLowerCase( Locale.ROOT); private static final String GROUP_PROTOCOL_DOC = "The group protocol streams should use. We currently " + "support \"classic\" or \"streams\". If \"streams\" is specified, then the streams rebalance protocol will be " + "used. Otherwise, the classic group protocol will be used."; public static final String ERRORS_DEAD_LETTER_QUEUE_TOPIC_NAME_CONFIG = "errors.dead.letter.queue.topic.name"; private static final String ERRORS_DEAD_LETTER_QUEUE_TOPIC_NAME_DOC = "If not null, the default exception handler will build and send a Dead Letter Queue record to the topic with the provided name if an error occurs.\n" + "If a custom deserialization/production or processing exception handler is set, this parameter is ignored for this handler."; /** {@code log.summary.interval.ms} */ public static final String LOG_SUMMARY_INTERVAL_MS_CONFIG = "log.summary.interval.ms"; private static final String LOG_SUMMARY_INTERVAL_MS_DOC = "The output interval in milliseconds for logging summary information.\n" + "If greater or equal to 0, the summary log will be output according to the set time interval;\n" + "If less than 0, summary output is disabled."; /** {@code max.task.idle.ms} */ public static final String MAX_TASK_IDLE_MS_CONFIG = "max.task.idle.ms"; @Deprecated public static final String MAX_TASK_IDLE_MS_DOC = "This config controls whether joins and merges" + " may produce out-of-order results." + " The config value is the maximum amount of time in milliseconds a stream task will stay idle" + " when it is fully caught up on some (but not all) input partitions" + " to wait for producers to send additional records and avoid potential" + " out-of-order record processing across multiple input streams." + " The default (zero) does not wait for producers to send more records," + " but it does wait to fetch data that is already present on the brokers." + " This default means that for records that are already present on the brokers," + " Streams will process them in timestamp order." + " Set to -1 to disable idling entirely and process any locally available data," + " even though doing so may produce out-of-order processing."; /** {@code max.warmup.replicas} */ public static final String MAX_WARMUP_REPLICAS_CONFIG = "max.warmup.replicas"; private static final String MAX_WARMUP_REPLICAS_DOC = "The maximum number of warmup replicas (extra standbys beyond the configured num.standbys) that can be assigned at once for the purpose of keeping " + " the task available on one instance while it is warming up on another instance it has been reassigned to. Used to throttle how much extra broker " + " traffic and cluster state can be used for high availability. Must be at least 1." + "Note that one warmup replica corresponds to one Stream Task. Furthermore, note that each warmup replica can only be promoted to an active task " + "during a rebalance (normally during a so-called probing rebalance, which occur at a frequency specified by the <code>probing.rebalance.interval.ms</code> config). This means " + "that the maximum rate at which active tasks can be migrated from one Kafka Streams Instance to another instance can be determined by " + "(<code>max.warmup.replicas</code> / <code>probing.rebalance.interval.ms</code>)."; /** {@code metadata.max.age.ms} */ @SuppressWarnings("WeakerAccess") public static final String METADATA_MAX_AGE_CONFIG = CommonClientConfigs.METADATA_MAX_AGE_CONFIG; /** {@code metrics.num.samples} */ @SuppressWarnings("WeakerAccess") public static final String METRICS_NUM_SAMPLES_CONFIG = CommonClientConfigs.METRICS_NUM_SAMPLES_CONFIG; /** {@code metrics.record.level} */ @SuppressWarnings("WeakerAccess") public static final String METRICS_RECORDING_LEVEL_CONFIG = CommonClientConfigs.METRICS_RECORDING_LEVEL_CONFIG; /** {@code metric.reporters} */ @SuppressWarnings("WeakerAccess") public static final String METRIC_REPORTER_CLASSES_CONFIG = CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG; /** {@code metrics.sample.window.ms} */ @SuppressWarnings("WeakerAccess") public static final String METRICS_SAMPLE_WINDOW_MS_CONFIG = CommonClientConfigs.METRICS_SAMPLE_WINDOW_MS_CONFIG; /** {@code num.standby.replicas} */ @SuppressWarnings("WeakerAccess") public static final String NUM_STANDBY_REPLICAS_CONFIG = "num.standby.replicas"; private static final String NUM_STANDBY_REPLICAS_DOC = "The number of standby replicas for each task."; /** {@code num.stream.threads} */ @SuppressWarnings("WeakerAccess") public static final String NUM_STREAM_THREADS_CONFIG = "num.stream.threads"; private static final String NUM_STREAM_THREADS_DOC = "The number of threads to execute stream processing."; /** {@code poll.ms} */ @SuppressWarnings("WeakerAccess") public static final String POLL_MS_CONFIG = "poll.ms"; private static final String POLL_MS_DOC = "The amount of time in milliseconds to block waiting for input."; /** {@code probing.rebalance.interval.ms} */ public static final String PROBING_REBALANCE_INTERVAL_MS_CONFIG = "probing.rebalance.interval.ms"; private static final String PROBING_REBALANCE_INTERVAL_MS_DOC = "The maximum time in milliseconds to wait before triggering a rebalance to probe for warmup replicas that have finished warming up and are ready to become active." + " Probing rebalances will continue to be triggered until the assignment is balanced. Must be at least 1 minute."; /** {@code processing.exception.handler} */ @SuppressWarnings("WeakerAccess") public static final String PROCESSING_EXCEPTION_HANDLER_CLASS_CONFIG = "processing.exception.handler"; @Deprecated public static final String PROCESSING_EXCEPTION_HANDLER_CLASS_DOC = "Exception handling
that
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java
{ "start": 1516, "end": 2947 }
class ____ { private final ConfigurationPropertiesReportEndpoint delegate; private final Show showValues; private final Set<String> roles; public ConfigurationPropertiesReportEndpointWebExtension(ConfigurationPropertiesReportEndpoint delegate, Show showValues, Set<String> roles) { this.delegate = delegate; this.showValues = showValues; this.roles = roles; } @ReadOperation public ConfigurationPropertiesDescriptor configurationProperties(SecurityContext securityContext) { boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles); return this.delegate.getConfigurationProperties(showUnsanitized); } @ReadOperation public WebEndpointResponse<ConfigurationPropertiesDescriptor> configurationPropertiesWithPrefix( SecurityContext securityContext, @Selector String prefix) { boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles); ConfigurationPropertiesDescriptor configurationProperties = this.delegate.getConfigurationProperties(prefix, showUnsanitized); boolean foundMatchingBeans = configurationProperties.getContexts() .values() .stream() .anyMatch((context) -> !context.getBeans().isEmpty()); return (foundMatchingBeans) ? new WebEndpointResponse<>(configurationProperties, WebEndpointResponse.STATUS_OK) : new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } }
ConfigurationPropertiesReportEndpointWebExtension
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleFlatMapBiSelector.java
{ "start": 3732, "end": 5163 }
class ____<T, U, R> extends AtomicReference<Disposable> implements SingleObserver<U> { private static final long serialVersionUID = -2897979525538174559L; final SingleObserver<? super R> downstream; final BiFunction<? super T, ? super U, ? extends R> resultSelector; T value; InnerObserver(SingleObserver<? super R> actual, BiFunction<? super T, ? super U, ? extends R> resultSelector) { this.downstream = actual; this.resultSelector = resultSelector; } @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onSuccess(U value) { T t = this.value; this.value = null; R r; try { r = Objects.requireNonNull(resultSelector.apply(t, value), "The resultSelector returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); downstream.onError(ex); return; } downstream.onSuccess(r); } @Override public void onError(Throwable e) { downstream.onError(e); } } } }
InnerObserver
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java
{ "start": 2131, "end": 8147 }
class ____ extends SpringConfigurationPropertySource implements IterableConfigurationPropertySource, CachingConfigurationPropertySource { private final BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> ancestorOfCheck; private final SoftReferenceConfigurationPropertyCache<Cache> cache; private volatile @Nullable ConfigurationPropertyName @Nullable [] configurationPropertyNames; private final @Nullable Map<ConfigurationPropertyName, ConfigurationPropertyState> containsDescendantOfCache; SpringIterableConfigurationPropertySource(EnumerablePropertySource<?> propertySource, boolean systemEnvironmentSource, PropertyMapper... mappers) { super(propertySource, systemEnvironmentSource, mappers); assertEnumerablePropertySource(); boolean immutable = isImmutablePropertySource(); this.ancestorOfCheck = getAncestorOfCheck(mappers); this.cache = new SoftReferenceConfigurationPropertyCache<>(immutable); this.containsDescendantOfCache = (!systemEnvironmentSource) ? null : new ConcurrentReferenceHashMap<>(); } private BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> getAncestorOfCheck( PropertyMapper[] mappers) { BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> ancestorOfCheck = mappers[0] .getAncestorOfCheck(); for (int i = 1; i < mappers.length; i++) { ancestorOfCheck = ancestorOfCheck.or(mappers[i].getAncestorOfCheck()); } return ancestorOfCheck; } private void assertEnumerablePropertySource() { if (getPropertySource() instanceof MapPropertySource mapSource) { try { mapSource.getSource().size(); } catch (UnsupportedOperationException ex) { throw new IllegalArgumentException("PropertySource must be fully enumerable"); } } } @Override public ConfigurationPropertyCaching getCaching() { return this.cache; } @Override public @Nullable ConfigurationProperty getConfigurationProperty(@Nullable ConfigurationPropertyName name) { if (name == null) { return null; } ConfigurationProperty configurationProperty = super.getConfigurationProperty(name); if (configurationProperty != null) { return configurationProperty; } for (String candidate : getCache().getMapped(name)) { Object value = getPropertySourceProperty(candidate); if (value != null) { Origin origin = PropertySourceOrigin.get(getPropertySource(), candidate); return ConfigurationProperty.of(this, name, value, origin); } } return null; } @Override protected @Nullable Object getSystemEnvironmentProperty(Map<String, Object> systemEnvironment, String name) { return getCache().getSystemEnvironmentProperty(name); } @Override public Stream<ConfigurationPropertyName> stream() { @Nullable ConfigurationPropertyName[] names = getConfigurationPropertyNames(); return Arrays.stream(names).filter(Objects::nonNull); } @Override public Iterator<ConfigurationPropertyName> iterator() { return new ConfigurationPropertyNamesIterator(getConfigurationPropertyNames()); } @Override public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { ConfigurationPropertyState result = super.containsDescendantOf(name); if (result != ConfigurationPropertyState.UNKNOWN) { return result; } if (this.ancestorOfCheck == PropertyMapper.DEFAULT_ANCESTOR_OF_CHECK) { Set<ConfigurationPropertyName> descendants = getCache().getDescendants(); if (descendants != null) { if (name.isEmpty() && !descendants.isEmpty()) { return ConfigurationPropertyState.PRESENT; } return !descendants.contains(name) ? ConfigurationPropertyState.ABSENT : ConfigurationPropertyState.PRESENT; } } result = (this.containsDescendantOfCache != null) ? this.containsDescendantOfCache.get(name) : null; if (result == null) { result = (!ancestorOfCheck(name)) ? ConfigurationPropertyState.ABSENT : ConfigurationPropertyState.PRESENT; if (this.containsDescendantOfCache != null) { this.containsDescendantOfCache.put(name, result); } } return result; } private boolean ancestorOfCheck(ConfigurationPropertyName name) { @Nullable ConfigurationPropertyName[] candidates = getConfigurationPropertyNames(); for (ConfigurationPropertyName candidate : candidates) { if (candidate != null && this.ancestorOfCheck.test(name, candidate)) { return true; } } return false; } @Nullable ConfigurationPropertyName[] getConfigurationPropertyNames() { if (!isImmutablePropertySource()) { return getCache().getConfigurationPropertyNames(getPropertySource().getPropertyNames()); } @Nullable ConfigurationPropertyName[] configurationPropertyNames = this.configurationPropertyNames; if (configurationPropertyNames == null) { configurationPropertyNames = getCache() .getConfigurationPropertyNames(getPropertySource().getPropertyNames()); this.configurationPropertyNames = configurationPropertyNames; } return configurationPropertyNames; } private Cache getCache() { return this.cache.get(this::createCache, this::updateCache); } private Cache createCache() { boolean immutable = isImmutablePropertySource(); boolean captureDescendants = this.ancestorOfCheck == PropertyMapper.DEFAULT_ANCESTOR_OF_CHECK; return new Cache(getMappers(), immutable, captureDescendants, isSystemEnvironmentSource()); } private Cache updateCache(Cache cache) { cache.update(getPropertySource()); return cache; } boolean isImmutablePropertySource() { EnumerablePropertySource<?> source = getPropertySource(); if (source instanceof PropertySourceInfo propertySourceInfo) { return propertySourceInfo.isImmutable(); } if (StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME.equals(source.getName())) { return source.getSource() == System.getenv(); } return false; } @Override protected EnumerablePropertySource<?> getPropertySource() { return (EnumerablePropertySource<?>) super.getPropertySource(); } private static
SpringIterableConfigurationPropertySource
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/util/DataFormatConverters.java
{ "start": 61362, "end": 62165 }
class ____ extends DataFormatConverter<TimestampData, Long> { private static final long serialVersionUID = 1L; private final int precision; public LongTimestampDataConverter(int precision) { this.precision = precision; } @Override TimestampData toInternalImpl(Long value) { return TimestampData.fromEpochMillis(value); } @Override Long toExternalImpl(TimestampData value) { return value.getMillisecond(); } @Override Long toExternalImpl(RowData row, int column) { return toExternalImpl(row.getTimestamp(column, precision)); } } /** Converter for {@link TimestampData} class. */ public static final
LongTimestampDataConverter
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/future/FutureTest.java
{ "start": 71879, "end": 72235 }
interface ____<A, B, C, D, E, F, G, H, R> { R apply(A a, B b, C c, D d, E e, F f, G g, H h); default <V> EightFunction<A, B, C, D, E, F, G, H, V> andThen( Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (a, b, c, d, e, f, g, h) -> after.apply(apply(a, b, c, d, e, f, g, h)); } } }
EightFunction
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/sequencedmultisetstate/linked/NodeSerializerTest.java
{ "start": 1240, "end": 1922 }
class ____ extends SerializerTestBase<Node> { @Override protected TypeSerializer<Node> createSerializer() { return new NodeSerializer(new RowDataSerializer(new IntType())); } @Override protected int getLength() { return -1; } @Override protected Class<Node> getTypeClass() { return Node.class; } @Override protected Node[] getTestData() { return new Node[] { new Node(StreamRecordUtils.row(1), 1L, null, 2L, 2L, 1L), new Node(StreamRecordUtils.row(2), 2L, 1L, 3L, 3L, 2L), new Node(StreamRecordUtils.row(3), 3L, 2L, null, null, 3L), }; } }
NodeSerializerTest
java
apache__camel
components/camel-pqc/src/generated/java/org/apache/camel/component/pqc/PQCEndpointUriFactory.java
{ "start": 513, "end": 2677 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":label"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(14); props.add("keyEncapsulationAlgorithm"); props.add("keyGenerator"); props.add("keyPair"); props.add("keyPairAlias"); props.add("keyStore"); props.add("keyStorePassword"); props.add("label"); props.add("lazyStartProducer"); props.add("operation"); props.add("signatureAlgorithm"); props.add("signer"); props.add("storeExtractedSecretKeyAsHeader"); props.add("symmetricKeyAlgorithm"); props.add("symmetricKeyLength"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(1); secretProps.add("keyStorePassword"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "pqc".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "label", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
PQCEndpointUriFactory
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeRecovery.java
{ "start": 8042, "end": 9325 }
class ____ extends EditLogTestSetup { private final int paddingLength; public EltsTestEmptyLog(int paddingLength) { this.paddingLength = paddingLength; } @Override public void addTransactionsToLog(EditLogOutputStream elos, OpInstanceCache cache) throws IOException { padEditLog(elos, paddingLength); } @Override public long getLastValidTxId() { return -1; } @Override public Set<Long> getValidTxIds() { return new HashSet<Long>(); } } /** Test an empty edit log */ @Test @Timeout(value = 180) public void testEmptyLog() throws IOException { runEditLogTest(new EltsTestEmptyLog(0)); } /** Test an empty edit log with padding */ @Test @Timeout(value = 180) public void testEmptyPaddedLog() throws IOException { runEditLogTest(new EltsTestEmptyLog( EditLogFileOutputStream.MIN_PREALLOCATION_LENGTH)); } /** Test an empty edit log with extra-long padding */ @Test @Timeout(value = 180) public void testEmptyExtraPaddedLog() throws IOException { runEditLogTest(new EltsTestEmptyLog( 3 * EditLogFileOutputStream.MIN_PREALLOCATION_LENGTH)); } /** * Test using a non-default maximum opcode length. */ private static
EltsTestEmptyLog
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/file/PartitionFileWriter.java
{ "start": 1198, "end": 1284 }
interface ____ the write logic for different types of shuffle * files. */ public
defines
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/types/DataTypePrecisionFixerTest.java
{ "start": 6703, "end": 7277 }
class ____ { private TypeInformation<?> typeInfo; private LogicalType logicalType; static TestSpecs fix(TypeInformation<?> typeInfo) { TestSpecs testSpecs = new TestSpecs(); testSpecs.typeInfo = typeInfo; return testSpecs; } TestSpecs logicalType(LogicalType logicalType) { this.logicalType = logicalType; return this; } TestSpec expect(DataType expectedType) { return new TestSpec(typeInfo, logicalType, expectedType); } } }
TestSpecs
java
quarkusio__quarkus
extensions/hibernate-reactive/runtime/src/main/java/io/quarkus/hibernate/reactive/runtime/boot/registry/PreconfiguredReactiveServiceRegistryBuilder.java
{ "start": 4435, "end": 13142 }
class ____ { private final Map configurationValues = new HashMap(); private final List<StandardServiceInitiator<?>> initiators; private final List<ProvidedService<?>> providedServices = new ArrayList<>(); private final Collection<Integrator> integrators; private final StandardServiceRegistryImpl destroyedRegistry; public PreconfiguredReactiveServiceRegistryBuilder(String puConfigName, RecordedState rs, HibernateOrmRuntimeConfigPersistenceUnit puConfig) { checkIsReactive(rs); this.initiators = buildQuarkusServiceInitiatorList(puConfigName, rs, puConfig); this.integrators = rs.getIntegrators(); this.destroyedRegistry = (StandardServiceRegistryImpl) rs.getMetadata() .getMetadataBuildingOptions() .getServiceRegistry(); } private static void checkIsReactive(RecordedState rs) { if (rs.isReactive() == false) throw new IllegalStateException("Booting an Hibernate Reactive serviceregistry on a non-reactive RecordedState!"); } public PreconfiguredReactiveServiceRegistryBuilder applySetting(String settingName, Object value) { configurationValues.put(settingName, value); return this; } public PreconfiguredReactiveServiceRegistryBuilder addInitiator(StandardServiceInitiator initiator) { initiators.add(initiator); return this; } public PreconfiguredReactiveServiceRegistryBuilder addService(ProvidedService providedService) { providedServices.add(providedService); return this; } public StandardServiceRegistryImpl buildNewServiceRegistry() { final BootstrapServiceRegistry bootstrapServiceRegistry = buildEmptyBootstrapServiceRegistry(); // Can skip, it's only deprecated stuff: // applyServiceContributingIntegrators( bootstrapServiceRegistry ); // This is NOT deprecated stuff, yet they will at best contribute stuff we // already recorded as part of #applyIntegrator, #addInitiator, #addService // applyServiceContributors( bootstrapServiceRegistry ); final Map settingsCopy = new HashMap(); settingsCopy.putAll(configurationValues); destroyedRegistry.resetAndReactivate(bootstrapServiceRegistry, initiators, providedServices, settingsCopy); return destroyedRegistry; } private BootstrapServiceRegistry buildEmptyBootstrapServiceRegistry() { final ClassLoaderService providedClassLoaderService = FlatClassLoaderService.INSTANCE; // N.B. support for custom IntegratorProvider injected via Properties (as // instance) removed // N.B. support for custom StrategySelector is not implemented yet // A non-empty selector is needed in order to support ID generators that retrieve a naming strategy -- at runtime! var strategySelector = QuarkusStrategySelectorBuilder.buildRuntimeSelector(providedClassLoaderService); return new BootstrapServiceRegistryImpl(true, providedClassLoaderService, strategySelector, // new MirroringStrategySelector(), new MirroringIntegratorService(integrators)); } /** * Modified copy from * org.hibernate.service.StandardServiceInitiators#buildStandardServiceInitiatorList * * N.B. not to be confused with * org.hibernate.service.internal.StandardSessionFactoryServiceInitiators#buildStandardServiceInitiatorList() * * @return */ private static List<StandardServiceInitiator<?>> buildQuarkusServiceInitiatorList(String puConfigName, RecordedState rs, HibernateOrmRuntimeConfigPersistenceUnit puConfig) { final ArrayList<StandardServiceInitiator<?>> serviceInitiators = new ArrayList<>(); //References to this object need to be injected in both the initiator for BytecodeProvider and for //the registered ProxyFactoryFactoryInitiator QuarkusRuntimeProxyFactoryFactory preGeneratedProxyFactory = new QuarkusRuntimeProxyFactoryFactory( rs.getProxyClassDefinitions()); // Definitely exclusive to Hibernate Reactive, as it marks the registry as Reactive: serviceInitiators.add(ReactiveMarkerServiceInitiator.INSTANCE); // Custom to Quarkus: Hibernate Reactive upstream would use org.hibernate.reactive.context.impl.VertxContextInitiator serviceInitiators.add(CheckingVertxContextInitiator.INSTANCE); //Custom for Hibernate Reactive: serviceInitiators.add(ReactiveSessionFactoryBuilderInitiator.INSTANCE); //Enforces no bytecode enhancement will happen at runtime, //but allows use of proxies generated at build time serviceInitiators.add(new QuarkusRuntimeBytecodeProviderInitiator(preGeneratedProxyFactory)); serviceInitiators.add(ProxyFactoryFactoryInitiator.INSTANCE); serviceInitiators.add(ReactiveMutationExecutorServiceInitiator.INSTANCE); // Replaces org.hibernate.boot.cfgxml.internal.CfgXmlAccessServiceInitiator : // not used // (Original disabled) serviceInitiators.add(CfgXmlAccessServiceInitiatorQuarkus.INSTANCE); // Useful as-is serviceInitiators.add(ConfigurationServiceInitiator.INSTANCE); // TODO (optional): assume entities are already enhanced? serviceInitiators.add(PropertyAccessStrategyResolverInitiator.INSTANCE); // Custom one! serviceInitiators.add(QuarkusImportSqlCommandExtractorInitiator.INSTANCE); // TODO disable? serviceInitiators.add(SchemaManagementToolInitiator.INSTANCE); serviceInitiators.add(NoJdbcEnvironmentInitiator.INSTANCE); // Custom one! serviceInitiators.add(QuarkusJndiServiceInitiator.INSTANCE); //Custom for Hibernate Reactive: serviceInitiators.add(ReactivePersisterClassResolverInitiator.INSTANCE); serviceInitiators.add(PersisterFactoryInitiator.INSTANCE); //Custom for Hibernate Reactive: serviceInitiators.add(QuarkusNoJdbcConnectionProviderInitiator.INSTANCE); serviceInitiators.add(MultiTenantConnectionProviderInitiator.INSTANCE); // Custom one: Dialect is injected explicitly serviceInitiators.add(new QuarkusRuntimeInitDialectResolverInitiator(rs.getDialect())); // Custom one: Dialect is injected explicitly serviceInitiators.add(new QuarkusRuntimeInitDialectFactoryInitiator(puConfigName, rs.isFromPersistenceXml(), rs.getDialect(), rs.getBuildTimeSettings().getSource(), puConfig)); // Default implementation serviceInitiators.add(BatchBuilderInitiator.INSTANCE); serviceInitiators.add(JdbcServicesInitiator.INSTANCE); serviceInitiators.add(RefCursorSupportInitiator.INSTANCE); // Custom for Hibernate Reactive: serviceInitiators.add(ReactiveSchemaManagementToolInitiator.INSTANCE); // Disabled: IdentifierGenerators are no longer initiated after Metadata was generated. // serviceInitiators.add(MutableIdentifierGeneratorFactoryInitiator.INSTANCE); // Custom for Hibernate Reactive: serviceInitiators.add(NoJtaPlatformInitiator.INSTANCE); serviceInitiators.add(SessionFactoryServiceRegistryFactoryInitiator.INSTANCE); // Replaces RegionFactoryInitiator.INSTANCE serviceInitiators.add(QuarkusRegionFactoryInitiator.INSTANCE); serviceInitiators.add(TransactionCoordinatorBuilderInitiator.INSTANCE); // Replaces ManagedBeanRegistryInitiator.INSTANCE serviceInitiators.add(QuarkusManagedBeanRegistryInitiator.INSTANCE); serviceInitiators.add(EntityCopyObserverFactoryInitiator.INSTANCE); //Custom for Hibernate Reactive: serviceInitiators.add(ReactiveValuesMappingProducerProviderInitiator.INSTANCE); //Custom for Hibernate Reactive: serviceInitiators.add(ReactiveSqmMultiTableMutationStrategyProviderInitiator.INSTANCE); // Custom for Hibernate Reactive: ParameterMarkerStrategy serviceInitiators.add(NativeParametersHandling.INSTANCE); // Default implementation serviceInitiators.add(SqlStatementLoggerInitiator.INSTANCE); // Custom for Hibernate Reactive: BatchLoaderFactory serviceInitiators.add(ReactiveBatchLoaderFactoryInitiator.INSTANCE); // Custom Quarkus implementation: overrides the internal cache to leverage Caffeine serviceInitiators.add(QuarkusInternalCacheFactoryInitiator.INSTANCE); serviceInitiators.trimToSize(); return serviceInitiators; } }
PreconfiguredReactiveServiceRegistryBuilder
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptorTests.java
{ "start": 2027, "end": 2206 }
class ____ { void m() { } } assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMeta"); } } @Async("qMeta") @Retention(RetentionPolicy.RUNTIME) @
C
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpStatus.java
{ "start": 852, "end": 1544 }
enum ____ { OK(200), CREATED(201), ACCEPTED(202), NO_CONTENT(204), MOVED_PERMANENTLY(301), FOUND(302), BAD_REQUEST(400), UNAUTHORIZED(401), FORBIDDEN(403), NOT_FOUND(404), METHOD_NOT_ALLOWED(405), NOT_ACCEPTABLE(406), REQUEST_TIMEOUT(408), CONFLICT(409), UNSUPPORTED_MEDIA_TYPE(415), INTERNAL_SERVER_ERROR(500); private final int code; private final String statusString; HttpStatus(int code) { this.code = code; this.statusString = String.valueOf(code); } public int getCode() { return code; } public String getStatusString() { return statusString; } }
HttpStatus
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/bucket/sampler/DiversifiedSamplerTests.java
{ "start": 2543, "end": 11590 }
class ____ extends AggregatorTestCase { private void writeBooks(RandomIndexWriter iw) throws IOException { String data[] = { // "id,cat,name,price,inStock,author_t,series_t,sequence_i,genre_s,genre_id", "0553573403,book,A Game of Thrones,7.99,true,George R.R. Martin,A Song of Ice and Fire,1,fantasy,0", "0553579908,book,A Clash of Kings,7.99,true,George R.R. Martin,A Song of Ice and Fire,2,fantasy,0", "055357342X,book,A Storm of Swords,7.99,true,George R.R. Martin,A Song of Ice and Fire,3,fantasy,0", "0553293354,book,Foundation,17.99,true,Isaac Asimov,Foundation Novels,1,scifi,1", "0812521390,book,The Black Company,6.99,false,Glen Cook,The Chronicles of The Black Company,1,fantasy,0", "0812550706,book,Ender's Game,6.99,true,Orson Scott Card,Ender,1,scifi,1", "0441385532,book,Jhereg,7.95,false,Steven Brust,Vlad Taltos,1,fantasy,0", "0380014300,book,Nine Princes In Amber,6.99,true,Roger Zelazny,the Chronicles of Amber,1,fantasy,0", "0805080481,book,The Book of Three,5.99,true,Lloyd Alexander,The Chronicles of Prydain,1,fantasy,0", "080508049X,book,The Black Cauldron,5.99,true,Lloyd Alexander,The Chronicles of Prydain,2,fantasy,0" }; List<Document> docs = new ArrayList<>(); for (String entry : data) { String[] parts = entry.split(","); Document document = new Document(); document.add(new SortedDocValuesField("id", new BytesRef(parts[0]))); document.add(new StringField("cat", parts[1], Field.Store.NO)); document.add(new TextField("name", parts[2], Field.Store.NO)); document.add(new DoubleDocValuesField("price", Double.valueOf(parts[3]))); document.add(new StringField("inStock", parts[4], Field.Store.NO)); document.add(new StringField("author", parts[5], Field.Store.NO)); document.add(new StringField("series", parts[6], Field.Store.NO)); document.add(new StringField("sequence", parts[7], Field.Store.NO)); document.add(new SortedDocValuesField("genre", new BytesRef(parts[8]))); document.add(new NumericDocValuesField("genre_id", Long.valueOf(parts[9]))); docs.add(document); } /* * Add all documents at once to force the test to aggregate all * values together at the same time. *That* is required because * the tests assume that all books are on a shard together. And * they aren't always if they end up in separate leaves. */ iw.addDocuments(docs); } public void testDiversifiedSampler() throws Exception { Directory directory = newDirectory(); IndexWriterConfig iwc = LuceneTestCase.newIndexWriterConfig(random(), new MockAnalyzer(random())); iwc.setMergePolicy(new LogDocMergePolicy()); RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory, iwc); MappedFieldType genreFieldType = new KeywordFieldMapper.KeywordFieldType("genre"); writeBooks(indexWriter); indexWriter.close(); DirectoryReader indexReader = DirectoryReader.open(directory); Consumer<InternalSampler> verify = result -> { Terms terms = result.getAggregations().get("terms"); assertEquals(2, terms.getBuckets().size()); assertEquals("0805080481", terms.getBuckets().get(0).getKeyAsString()); assertEquals("0812550706", terms.getBuckets().get(1).getKeyAsString()); }; testCase(indexReader, genreFieldType, "map", verify); testCase(indexReader, genreFieldType, "global_ordinals", verify); testCase(indexReader, genreFieldType, "bytes_hash", verify); genreFieldType = new NumberFieldMapper.NumberFieldType("genre_id", NumberFieldMapper.NumberType.LONG); testCase(indexReader, genreFieldType, null, verify); // wrong field: genreFieldType = new KeywordFieldMapper.KeywordFieldType("wrong_field"); testCase(indexReader, genreFieldType, null, result -> { Terms terms = result.getAggregations().get("terms"); assertEquals(1, terms.getBuckets().size()); assertEquals("0805080481", terms.getBuckets().get(0).getKeyAsString()); }); indexReader.close(); directory.close(); } public void testRidiculousSize() throws Exception { Directory directory = newDirectory(); RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory); writeBooks(indexWriter); indexWriter.close(); DirectoryReader indexReader = DirectoryReader.open(directory); MappedFieldType genreFieldType = new KeywordFieldMapper.KeywordFieldType("genre"); Consumer<InternalSampler> verify = result -> { Terms terms = result.getAggregations().get("terms"); assertThat(terms.getBuckets().size(), greaterThan(0)); }; try { // huge shard_size testCase(indexReader, genreFieldType, "map", verify, Integer.MAX_VALUE, 1); testCase(indexReader, genreFieldType, "global_ordinals", verify, Integer.MAX_VALUE, 1); testCase(indexReader, genreFieldType, "bytes_hash", verify, Integer.MAX_VALUE, 1); // huge maxDocsPerValue testCase(indexReader, genreFieldType, "map", verify, 100, Integer.MAX_VALUE); testCase(indexReader, genreFieldType, "global_ordinals", verify, 100, Integer.MAX_VALUE); testCase(indexReader, genreFieldType, "bytes_hash", verify, 100, Integer.MAX_VALUE); } finally { indexReader.close(); directory.close(); } } private void testCase(IndexReader indexReader, MappedFieldType genreFieldType, String executionHint, Consumer<InternalSampler> verify) throws IOException { testCase(indexReader, genreFieldType, executionHint, verify, 100, 1); } private void testCase( IndexReader indexReader, MappedFieldType genreFieldType, String executionHint, Consumer<InternalSampler> verify, int shardSize, int maxDocsPerValue ) throws IOException { MappedFieldType idFieldType = new KeywordFieldMapper.KeywordFieldType("id"); SortedDoublesIndexFieldData fieldData = new SortedDoublesIndexFieldData( "price", IndexNumericFieldData.NumericType.DOUBLE, CoreValuesSourceType.NUMERIC, (dv, n) -> new DelegateDocValuesField(new Doubles(new DoublesSupplier(dv)), n), IndexType.NONE ); FunctionScoreQuery query = new FunctionScoreQuery( new MatchAllDocsQuery(), new FieldValueFactorFunction("price", 1, FieldValueFactorFunction.Modifier.RECIPROCAL, null, fieldData) ); DiversifiedAggregationBuilder builder = new DiversifiedAggregationBuilder("_name").field(genreFieldType.name()) .executionHint(executionHint) .maxDocsPerValue(maxDocsPerValue) .shardSize(shardSize) .subAggregation(new TermsAggregationBuilder("terms").field("id")); InternalSampler result = searchAndReduce(indexReader, new AggTestConfig(builder, genreFieldType, idFieldType).withQuery(query)); verify.accept(result); } public void testDiversifiedSampler_noDocs() throws Exception { Directory directory = newDirectory(); RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory); indexWriter.close(); IndexReader indexReader = DirectoryReader.open(directory); MappedFieldType idFieldType = new KeywordFieldMapper.KeywordFieldType("id"); MappedFieldType genreFieldType = new KeywordFieldMapper.KeywordFieldType("genre"); DiversifiedAggregationBuilder builder = new DiversifiedAggregationBuilder("_name").field(genreFieldType.name()) .subAggregation(new TermsAggregationBuilder("terms").field("id")); InternalSampler result = searchAndReduce(indexReader, new AggTestConfig(builder, genreFieldType, idFieldType)); Terms terms = result.getAggregations().get("terms"); assertEquals(0, terms.getBuckets().size()); indexReader.close(); directory.close(); } public void testSupportsParallelCollection() { DiversifiedAggregationBuilder sampler = new DiversifiedAggregationBuilder("name"); if (randomBoolean()) { sampler.field("field"); } if (randomBoolean()) { sampler.maxDocsPerValue(randomIntBetween(1, 1000)); } if (randomBoolean()) { sampler.subAggregation(new TermsAggregationBuilder("name").field("field")); } if (randomBoolean()) { sampler.shardSize(randomIntBetween(1, 1000)); } assertFalse(sampler.supportsParallelCollection(null)); } }
DiversifiedSamplerTests
java
apache__camel
components/camel-dynamic-router/src/main/java/org/apache/camel/component/dynamicrouter/routing/DynamicRouterConfiguration.java
{ "start": 1463, "end": 20297 }
class ____ { /** * Channel for the Dynamic Router. For example, if the Dynamic Router URI is "dynamic-router://test", then the * channel is "test". Channels are a way of keeping routing participants, their rules, and exchanges logically * separate from the participants, rules, and exchanges on other channels. This can be seen as analogous to VLANs in * networking. */ @UriPath(name = "channel", label = "common", description = "Channel of the Dynamic Router") @Metadata(required = true) private String channel; /** * Sets the behavior of the Dynamic Router when routing participants are selected to receive an incoming exchange. * If the mode is "firstMatch", then the exchange is routed only to the first participant that has a matching * predicate. If the mode is "allMatch", then the exchange is routed to all participants that have a matching * predicate. */ @UriParam(label = "common", defaultValue = MODE_FIRST_MATCH, enums = MODE_FIRST_MATCH + "," + MODE_ALL_MATCH, description = "Recipient mode: firstMatch or allMatch") private String recipientMode = MODE_FIRST_MATCH; /** * Sets whether synchronous processing should be strictly used. When enabled then the same thread is used to * continue routing after the multicast is complete, even if parallel processing is enabled. */ @UriParam(label = "common", defaultValue = "false") private boolean synchronous; /** * Flag to log a warning if no predicates match for an exchange. */ @UriParam(label = "common", defaultValue = "false") private boolean warnDroppedMessage; /** * If enabled, then sending via multicast occurs concurrently. Note that the caller thread will still wait until all * messages have been fully processed before it continues. It is only the sending and processing of the replies from * the multicast recipients that happens concurrently. When parallel processing is enabled, then the Camel routing * engine will continue processing using the last used thread from the parallel thread pool. However, if you want to * use the original thread that called the multicast, then make sure to enable the synchronous option as well. */ @UriParam(label = "common", defaultValue = "false") private boolean parallelProcessing; /** * If enabled then the aggregate method on AggregationStrategy can be called concurrently. Notice that this would * require the implementation of AggregationStrategy to be implemented as thread-safe. By default, this is false, * meaning that Camel synchronizes the call to the aggregate method. Though, in some use-cases, this can be used to * archive higher performance when the AggregationStrategy is implemented as thread-safe. */ @UriParam(label = "common", defaultValue = "false") private boolean parallelAggregate; /** * Will stop further processing if an exception or failure occurred during processing of an * {@link org.apache.camel.Exchange} and the caused exception will be thrown. Will also stop if processing the * exchange failed (has a fault message), or an exception was thrown and handled by the error handler (such as using * onException). In all situations, the multicast will stop further processing. This is the same behavior as in the * pipeline that is used by the routing engine. The default behavior is to not stop, but to continue processing * until the end. */ @UriParam(label = "common", defaultValue = "false") private boolean stopOnException; /** * Ignore the invalid endpoint exception when attempting to create a producer with an invalid endpoint. */ @UriParam(label = "common", defaultValue = "false") private boolean ignoreInvalidEndpoints; /** * If enabled, then Camel will process replies out-of-order (e.g., in the order they come back). If disabled, Camel * will process replies in the same order as defined by the multicast. */ @UriParam(label = "common", defaultValue = "false") private boolean streaming; /** * Sets a total timeout specified in milliseconds, when using parallel processing. If the Multicast has not been * able to send and process all replies within the given timeframe, then the timeout triggers and the Multicast * breaks out and continues. Notice that, if you provide a TimeoutAwareAggregationStrategy, then the timeout method * is invoked before breaking out. If the timeout is reached with running tasks still remaining, certain tasks (for * which it is difficult for Camel to shut down in a graceful manner) may continue to run. So use this option with a * bit of care. */ @UriParam(label = "common", defaultValue = "-1") private long timeout; /** * When caching producer endpoints, this is the size of the cache. Default is 100. */ @UriParam(label = "common", defaultValue = "100") private int cacheSize = 100; /** * Uses the Processor when preparing the {@link org.apache.camel.Exchange} to be sent. This can be used to * deep-clone messages that should be sent, or to provide any custom logic that is needed before the exchange is * sent. This is the name of a bean in the registry. */ @UriParam(label = "common") private String onPrepare; /** * Uses the Processor when preparing the {@link org.apache.camel.Exchange} to be sent. This can be used to * deep-clone messages that should be sent, or to provide any custom logic that is needed before the exchange is * sent. This is a {@link Processor} instance. */ @UriParam(label = "common") private Processor onPrepareProcessor; /** * Shares the {@link org.apache.camel.spi.UnitOfWork} with the parent and each of the sub messages. Multicast will, * by default, not share a unit of work between the parent exchange and each multicasted exchange. This means each * sub exchange has its own individual unit of work. */ @UriParam(label = "common", defaultValue = "false") private boolean shareUnitOfWork; /** * Refers to a custom Thread Pool to be used for parallel processing. Notice that, if you set this option, then * parallel processing is automatically implied, and you do not have to enable that option in addition to this one. */ @UriParam(label = "common") private String executorService; /** * Refers to a custom Thread Pool to be used for parallel processing. Notice that, if you set this option, then * parallel processing is automatically implied, and you do not have to enable that option in addition to this one. */ @UriParam(label = "common") private ExecutorService executorServiceBean; /** * Refers to an AggregationStrategy to be used to assemble the replies from the multicasts, into a single outgoing * message from the Multicast. By default, Camel will use the last reply as the outgoing message. You can also use a * POJO as the AggregationStrategy. */ @UriParam(label = "common") private String aggregationStrategy; /** * Refers to an AggregationStrategy to be used to assemble the replies from the multicasts, into a single outgoing * message from the Multicast. By default, Camel will use the last reply as the outgoing message. You can also use a * POJO as the AggregationStrategy. */ @UriParam(label = "common") private AggregationStrategy aggregationStrategyBean; /** * You can use a POJO as the AggregationStrategy. This refers to the name of the method that aggregates the * exchanges. */ @UriParam(label = "common") private String aggregationStrategyMethodName; /** * If this option is false then the aggregate method is not used if there was no data to enrich. If this option is * true then null values is used as the oldExchange (when no data to enrich), when using POJOs as the * AggregationStrategy */ @UriParam(label = "common") private boolean aggregationStrategyMethodAllowNull; /** * Channel for the Dynamic Router. For example, if the Dynamic Router URI is "dynamic-router://test", then the * channel is "test". Channels are a way of keeping routing participants, their rules, and exchanges logically * separate from the participants, rules, and exchanges on other channels. This can be seen as analogous to VLANs in * networking. * * @return the channel */ public String getChannel() { return channel; } /** * Channel for the Dynamic Router. For example, if the Dynamic Router URI is "dynamic-router://test", then the * channel is "test". Channels are a way of keeping routing participants, their rules, and exchanges logically * separate from the participants, rules, and exchanges on other channels. This can be seen as analogous to VLANs in * networking. * * @param channel the channel */ public void setChannel(final String channel) { this.channel = channel; } /** * Gets the behavior of the Dynamic Router when routing participants are selected to receive an incoming exchange. * If the mode is "firstMatch", then the exchange is routed only to the first participant that has a matching * predicate. If the mode is "allMatch", then the exchange is routed to all participants that have a matching * predicate. * * @return the recipient mode */ public String getRecipientMode() { return recipientMode; } /** * Sets the behavior of the Dynamic Router when routing participants are selected to receive an incoming exchange. * If the mode is "firstMatch", then the exchange is routed only to the first participant that has a matching * predicate. If the mode is "allMatch", then the exchange is routed to all participants that have a matching * predicate. * * @param recipientMode the recipient mode */ public void setRecipientMode(final String recipientMode) { this.recipientMode = recipientMode; } /** * Flag to ensure synchronous processing. * * @return true if processing will be synchronous, false otherwise */ public boolean isSynchronous() { return synchronous; } /** * Flag to ensure synchronous processing. * * @param synchronous flag if processing will be synchronous */ public void setSynchronous(boolean synchronous) { this.synchronous = synchronous; } /** * Flag to log a warning if no predicates match for an exchange. * * @return true if logging a warning when no predicates match an exchange, false otherwise */ public boolean isWarnDroppedMessage() { return warnDroppedMessage; } /** * Flag to log a warning if no predicates match for an exchange. * * @param warnDroppedMessage flag to log warnings when no predicates match */ public void setWarnDroppedMessage(boolean warnDroppedMessage) { this.warnDroppedMessage = warnDroppedMessage; } /** * Gets whether the multicast should be streaming or not. * * @return true if streaming, false otherwise */ public boolean isStreaming() { return streaming; } /** * Sets whether the multicast should be streaming or not. * * @param streaming flag to set whether the multicast should be streaming or not */ public void setStreaming(boolean streaming) { this.streaming = streaming; } /** * Gets whether invalid endpoints should be ignored. * * @return true if invalid endpoints should be ignored, false otherwise */ public boolean isIgnoreInvalidEndpoints() { return ignoreInvalidEndpoints; } /** * Sets whether invalid endpoints should be ignored. * * @param ignoreInvalidEndpoints flag to set whether invalid endpoints should be ignored */ public void setIgnoreInvalidEndpoints(boolean ignoreInvalidEndpoints) { this.ignoreInvalidEndpoints = ignoreInvalidEndpoints; } /** * Gets whether parallel processing is enabled. * * @return true if parallel processing is enabled, false otherwise */ public boolean isParallelProcessing() { return parallelProcessing; } /** * Sets whether parallel processing is enabled. * * @param parallelProcessing flag to set whether parallel processing is enabled */ public void setParallelProcessing(boolean parallelProcessing) { this.parallelProcessing = parallelProcessing; } /** * Gets whether parallel aggregation is enabled. * * @return true if parallel aggregation is enabled, false otherwise */ public boolean isParallelAggregate() { return parallelAggregate; } /** * Sets whether parallel aggregation is enabled. * * @param parallelAggregate flag to set whether parallel aggregation is enabled */ public void setParallelAggregate(boolean parallelAggregate) { this.parallelAggregate = parallelAggregate; } /** * Gets whether the multicast should stop on exception. * * @return true if the multicast should stop on exception, false otherwise */ public boolean isStopOnException() { return stopOnException; } /** * Sets whether the multicast should stop on exception. * * @param stopOnException flag to set whether the multicast should stop on exception */ public void setStopOnException(boolean stopOnException) { this.stopOnException = stopOnException; } /** * Gets the executor service. * * @return the executor service */ public String getExecutorService() { return executorService; } /** * Sets the executor service. * * @param executorService the executor service */ public void setExecutorService(String executorService) { this.executorService = executorService; } /** * Gets the executor service bean. * * @return the executor service bean */ public ExecutorService getExecutorServiceBean() { return executorServiceBean; } /** * Sets the executor service bean. * * @param executorServiceBean the executor service bean */ public void setExecutorServiceBean(ExecutorService executorServiceBean) { this.executorServiceBean = executorServiceBean; } /** * Gets the aggregation strategy. * * @return the aggregation strategy */ public String getAggregationStrategy() { return aggregationStrategy; } /** * Sets the aggregation strategy. * * @param aggregationStrategy the aggregation strategy */ public void setAggregationStrategy(String aggregationStrategy) { this.aggregationStrategy = aggregationStrategy; } /** * Gets the timeout. * * @return the timeout */ public long getTimeout() { return timeout; } /** * Sets the timeout. * * @param timeout the timeout */ public void setTimeout(long timeout) { this.timeout = timeout; } /** * Gets the cache size. * * @return the cache size */ public int getCacheSize() { return cacheSize; } /** * Sets the cache size. * * @param cacheSize the cache size */ public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } /** * Gets the on prepare processor reference. * * @return the on prepare processor reference */ public String getOnPrepare() { return onPrepare; } /** * Sets the on prepare processor reference. * * @param onPrepare the on prepare processor reference */ public void setOnPrepare(String onPrepare) { this.onPrepare = onPrepare; } /** * Gets the on prepare processor. * * @return the on prepare processor */ public Processor getOnPrepareProcessor() { return onPrepareProcessor; } /** * Sets the on prepare processor. * * @param onPrepare the on prepare processor */ public void setOnPrepareProcessor(Processor onPrepare) { this.onPrepareProcessor = onPrepare; } /** * Gets the share unit of work flag. * * @return the share unit of work flag */ public boolean isShareUnitOfWork() { return shareUnitOfWork; } /** * Sets the share unit of work flag. * * @param shareUnitOfWork the share unit of work flag */ public void setShareUnitOfWork(boolean shareUnitOfWork) { this.shareUnitOfWork = shareUnitOfWork; } /** * Gets the aggregation strategy method name. * * @return the aggregation strategy method name */ public String getAggregationStrategyMethodName() { return aggregationStrategyMethodName; } /** * Sets the aggregation strategy method name. * * @param aggregationStrategyMethodName the aggregation strategy method name */ public void setAggregationStrategyMethodName(String aggregationStrategyMethodName) { this.aggregationStrategyMethodName = aggregationStrategyMethodName; } /** * Gets whether the aggregation strategy method allows null. * * @return true if the aggregation strategy method allows null, false otherwise */ public boolean isAggregationStrategyMethodAllowNull() { return aggregationStrategyMethodAllowNull; } /** * Sets whether the aggregation strategy method allows null. * * @param aggregationStrategyMethodAllowNull flag to set whether the aggregation strategy method allows null */ public void setAggregationStrategyMethodAllowNull(boolean aggregationStrategyMethodAllowNull) { this.aggregationStrategyMethodAllowNull = aggregationStrategyMethodAllowNull; } /** * Gets the aggregation strategy bean. * * @return the aggregation strategy bean */ public AggregationStrategy getAggregationStrategyBean() { return aggregationStrategyBean; } /** * Sets the aggregation strategy bean. * * @param aggregationStrategyBean the aggregation strategy bean */ public void setAggregationStrategyBean(AggregationStrategy aggregationStrategyBean) { this.aggregationStrategyBean = aggregationStrategyBean; } }
DynamicRouterConfiguration
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 146640, "end": 146828 }
class ____ {}"); JavaFileObject string = JavaFileObjects.forSourceLines( "foo.bar.String", // "package foo.bar;", "", "public
Object
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/FailedToCreateConsumerException.java
{ "start": 975, "end": 2141 }
class ____ extends RuntimeCamelException { private final String uri; public FailedToCreateConsumerException(String endpointURI, Throwable cause) { super("Failed to create Consumer for endpoint for: " + sanitizeUri(endpointURI) + ". Reason: " + cause, cause); this.uri = sanitizeUri(endpointURI); } public FailedToCreateConsumerException(Endpoint endpoint, Throwable cause) { super("Failed to create Consumer for endpoint: " + endpoint + ". Reason: " + cause, cause); this.uri = sanitizeUri(endpoint.getEndpointUri()); } public FailedToCreateConsumerException(Endpoint endpoint, String message, Throwable cause) { super("Failed to create Consumer for endpoint: " + endpoint + ". Reason: " + message, cause); this.uri = sanitizeUri(endpoint.getEndpointUri()); } public FailedToCreateConsumerException(Endpoint endpoint, String message) { super("Failed to create Consumer for endpoint: " + endpoint + ". Reason: " + message); this.uri = sanitizeUri(endpoint.getEndpointUri()); } public String getUri() { return uri; } }
FailedToCreateConsumerException
java
elastic__elasticsearch
plugins/examples/custom-suggester/src/main/java/org/elasticsearch/example/customsuggester/CustomSuggestion.java
{ "start": 3632, "end": 5123 }
class ____ extends Suggest.Suggestion.Entry.Option { private String dummy; public Option(Text text, float score, String dummy) { super(text, score); this.dummy = dummy; } public Option(StreamInput in) throws IOException { super(in); dummy = in.readString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(dummy); } /** * A meaningless value used to test that plugin suggesters can add fields to their options */ public String getDummy() { return dummy; } /* * the value of dummy will always be the same, so this just tests that we can merge options with custom fields */ @Override protected void mergeInto(Suggest.Suggestion.Entry.Option otherOption) { super.mergeInto(otherOption); dummy = ((Option) otherOption).getDummy(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder = super.toXContent(builder, params); builder.field(DUMMY.getPreferredName(), dummy); return builder; } } } }
Option
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/quic/KeyLogFile.java
{ "start": 732, "end": 1111 }
class ____ implements BoringSSLKeylog { private final File file; KeyLogFile(File file) { this.file = file; } @Override public void logKey(SSLEngine engine, String key) { try (PrintWriter out = new PrintWriter(new FileWriter(file, StandardCharsets.UTF_8, true))) { out.println(key); out.flush(); } catch (Exception ignore) { } } }
KeyLogFile
java
netty__netty
codec-http3/src/main/java/io/netty/handler/codec/http3/DefaultHttp3UnknownFrame.java
{ "start": 835, "end": 2840 }
class ____ extends DefaultByteBufHolder implements Http3UnknownFrame { private final long type; public DefaultHttp3UnknownFrame(long type, ByteBuf payload) { super(payload); this.type = Http3CodecUtils.checkIsReservedFrameType(type); } @Override public long type() { return type; } @Override public Http3UnknownFrame copy() { return new DefaultHttp3UnknownFrame(type, content().copy()); } @Override public Http3UnknownFrame duplicate() { return new DefaultHttp3UnknownFrame(type, content().duplicate()); } @Override public Http3UnknownFrame retainedDuplicate() { return new DefaultHttp3UnknownFrame(type, content().retainedDuplicate()); } @Override public Http3UnknownFrame replace(ByteBuf content) { return new DefaultHttp3UnknownFrame(type, content); } @Override public Http3UnknownFrame retain() { super.retain(); return this; } @Override public Http3UnknownFrame retain(int increment) { super.retain(increment); return this; } @Override public Http3UnknownFrame touch() { super.touch(); return this; } @Override public Http3UnknownFrame touch(Object hint) { super.touch(hint); return this; } @Override public String toString() { return StringUtil.simpleClassName(this) + "(type=" + type() + ", content=" + content() + ')'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultHttp3UnknownFrame that = (DefaultHttp3UnknownFrame) o; if (type != that.type) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode(), type); } }
DefaultHttp3UnknownFrame
java
playframework__playframework
documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/guice/CircularDependencies.java
{ "start": 624, "end": 682 }
class ____ { // #circular-provider public
WithProvider
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/alter/OracleAlterTableTest18.java
{ "start": 977, "end": 2487 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "ALTER TABLE project_measures DROP (diff_value_1, diff_value_2, diff_value_3)"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("project_measures"))); assertEquals(3, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("PRODUCT_IDS_ZZJ_TBD0209", "discount_amount"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("ws_affiliate_tran_product", "commission_amount"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleAlterTableTest18
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/io/BinaryDecoder.java
{ "start": 20803, "end": 25497 }
class ____ extends InputStream { // maintain a reference to the buffer, so that if this // source is detached from the Decoder, and a client still // has a reference to it via inputStream(), bytes are not // lost protected BufferAccessor ba; protected ByteSource() { } abstract boolean isEof(); protected void attach(int bufferSize, BinaryDecoder decoder) { decoder.buf = new byte[bufferSize]; decoder.pos = 0; decoder.minPos = 0; decoder.limit = 0; this.ba = new BufferAccessor(decoder); } protected void detach() { ba.detach(); } /** * Skips length bytes from the source. If length bytes cannot be skipped due to * end of file/stream/channel/etc an EOFException is thrown * * @param length the number of bytes to attempt to skip * @throws IOException if an error occurs * @throws EOFException if length bytes cannot be skipped */ protected abstract void skipSourceBytes(long length) throws IOException; /** * Attempts to skip <i>skipLength</i> bytes from the source. Returns the actual * number of bytes skipped. This method must attempt to skip as many bytes as * possible up to <i>skipLength</i> bytes. Skipping 0 bytes signals end of * stream/channel/file/etc * * @param skipLength the number of bytes to attempt to skip * @return the count of actual bytes skipped. */ protected abstract long trySkipBytes(long skipLength) throws IOException; /** * Reads raw from the source, into a byte[]. Used for reads that are larger than * the buffer, or otherwise unbuffered. This is a mandatory read -- if there is * not enough bytes in the source, EOFException is thrown. * * @throws IOException if an error occurs * @throws EOFException if len bytes cannot be read */ protected abstract void readRaw(byte[] data, int off, int len) throws IOException; /** * Attempts to copy up to <i>len</i> bytes from the source into data, starting * at index <i>off</i>. Returns the actual number of bytes copied which may be * between 0 and <i>len</i>. * <p/> * This method must attempt to read as much as possible from the source. Returns * 0 when at the end of stream/channel/file/etc. * * @throws IOException if an error occurs reading **/ protected abstract int tryReadRaw(byte[] data, int off, int len) throws IOException; /** * If this source buffers, compacts the buffer by placing the <i>remaining</i> * bytes starting at <i>pos</i> at <i>minPos</i>. This may be done in the * current buffer, or may replace the buffer with a new one. * * The end result must be a buffer with at least 16 bytes of remaining space. * * @param pos * @param minPos * @param remaining * @throws IOException */ protected void compactAndFill(byte[] buf, int pos, int minPos, int remaining) throws IOException { System.arraycopy(buf, pos, buf, minPos, remaining); ba.setPos(minPos); int newLimit = remaining + tryReadRaw(buf, minPos + remaining, buf.length - remaining); ba.setLimit(newLimit); } @Override public int read(byte[] b, int off, int len) throws IOException { int lim = ba.getLim(); int pos = ba.getPos(); byte[] buf = ba.getBuf(); int remaining = (lim - pos); if (remaining >= len) { System.arraycopy(buf, pos, b, off, len); pos = pos + len; ba.setPos(pos); return len; } else { // flush buffer to array System.arraycopy(buf, pos, b, off, remaining); pos = pos + remaining; ba.setPos(pos); // get the rest from the stream (skip array) int inputRead = remaining + tryReadRaw(b, off + remaining, len - remaining); if (inputRead == 0) { return -1; } else { return inputRead; } } } @Override public long skip(long n) throws IOException { int lim = ba.getLim(); int pos = ba.getPos(); int remaining = lim - pos; if (remaining > n) { pos = (int) (pos + n); ba.setPos(pos); return n; } else { pos = lim; ba.setPos(pos); long isSkipCount = trySkipBytes(n - remaining); return isSkipCount + remaining; } } /** * returns the number of bytes remaining that this BinaryDecoder has buffered * from its source */ @Override public int available() throws IOException { return (ba.getLim() - ba.getPos()); } } private static
ByteSource
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/AclSetuserArgs.java
{ "start": 21317, "end": 21450 }
class ____ extends KeywordArgument { public AllKeys() { super(ALLKEYS); } } private static
AllKeys
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/xml_external_ref/MultipleReverseIncludeTest.java
{ "start": 1344, "end": 3372 }
class ____ { @Test void multipleReverseIncludeXmlConfig() throws Exception { testMultipleReverseIncludes(getSqlSessionFactoryXmlConfig()); } @Test void multipleReverseIncludeJavaConfig() throws Exception { testMultipleReverseIncludes(getSqlSessionFactoryJavaConfig()); } private void testMultipleReverseIncludes(SqlSessionFactory sqlSessionFactory) { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MultipleReverseIncludePersonMapper personMapper = sqlSession.getMapper(MultipleReverseIncludePersonMapper.class); Person person = personMapper.select(1); assertEquals((Integer) 1, person.getId()); assertEquals("John", person.getName()); } } private SqlSessionFactory getSqlSessionFactoryXmlConfig() throws Exception { try (Reader configReader = Resources .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MultipleReverseIncludeMapperConfig.xml")) { SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader); initDb(sqlSessionFactory); return sqlSessionFactory; } } private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception { Configuration configuration = new Configuration(); Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null)); configuration.setEnvironment(environment); configuration.addMapper(MultipleReverseIncludePersonMapper.class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); initDb(sqlSessionFactory); return sqlSessionFactory; } private static void initDb(SqlSessionFactory sqlSessionFactory) throws IOException, SQLException { BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), "org/apache/ibatis/submitted/xml_external_ref/CreateDB.sql"); } }
MultipleReverseIncludeTest
java
playframework__playframework
documentation/manual/working/javaGuide/main/pekko/code/javaguide/pekko/HelloActorProtocol.java
{ "start": 277, "end": 409 }
class ____ { public final String name; public SayHello(String name) { this.name = name; } } } // #protocol
SayHello
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/message/MessageId.java
{ "start": 886, "end": 1394 }
class ____ { private SocketAddress address; private long offset; public MessageId(SocketAddress address, long offset) { this.address = address; this.offset = offset; } public SocketAddress getAddress() { return address; } public void setAddress(SocketAddress address) { this.address = address; } public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } }
MessageId
java
apache__camel
components/camel-grpc/src/main/java/org/apache/camel/component/grpc/client/GrpcExchangeForwarderFactory.java
{ "start": 1058, "end": 1749 }
class ____ { private GrpcExchangeForwarderFactory() { } public static GrpcExchangeForwarder createExchangeForwarder(GrpcConfiguration configuration, Object grpcStub) { if (configuration.getProducerStrategy() == GrpcProducerStrategy.SIMPLE) { return new GrpcSimpleExchangeForwarder(configuration, grpcStub); } else if (configuration.getProducerStrategy() == GrpcProducerStrategy.STREAMING) { return new GrpcStreamingExchangeForwarder(configuration, grpcStub); } else { throw new IllegalStateException("Unsupported producer strategy: " + configuration.getProducerStrategy()); } } }
GrpcExchangeForwarderFactory
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/AbstractWorkerSourceTaskTest.java
{ "start": 6096, "end": 47350 }
class ____ { private static final String TOPIC = "topic"; private static final String OTHER_TOPIC = "other-topic"; private static final Map<String, byte[]> PARTITION = Map.of("key", "partition".getBytes()); private static final Map<String, Integer> OFFSET = Map.of("key", 12); // Connect-format data private static final Schema KEY_SCHEMA = Schema.INT32_SCHEMA; private static final Integer KEY = -1; private static final Schema RECORD_SCHEMA = Schema.INT64_SCHEMA; private static final Long RECORD = 12L; // Serialized data. The actual format of this data doesn't matter -- we just want to see that the right version // is used in the right place. private static final byte[] SERIALIZED_KEY = "converted-key".getBytes(); private static final byte[] SERIALIZED_RECORD = "converted-record".getBytes(); @Mock private SourceTask sourceTask; @Mock private TopicAdmin admin; @Mock private KafkaProducer<byte[], byte[]> producer; @Mock private Converter keyConverter; @Mock private Converter valueConverter; @Mock private HeaderConverter headerConverter; @Mock private TransformationChain<SourceRecord, SourceRecord> transformationChain; @Mock private CloseableOffsetStorageReader offsetReader; @Mock private OffsetStorageWriter offsetWriter; @Mock private ConnectorOffsetBackingStore offsetStore; @Mock private StatusBackingStore statusBackingStore; @Mock private WorkerTransactionContext workerTransactionContext; @Mock private TaskStatus.Listener statusListener; @Mock private ClusterConfigState configState; private final ConnectorTaskId taskId = new ConnectorTaskId("job", 0); private final ConnectorTaskId taskId1 = new ConnectorTaskId("job", 1); private Plugins plugins; private WorkerConfig config; private SourceConnectorConfig sourceConfig; private MockConnectMetrics metrics; @Mock private ErrorHandlingMetrics errorHandlingMetrics; private AbstractWorkerSourceTask workerTask; @BeforeEach public void setup() { Map<String, String> workerProps = workerProps(); plugins = new Plugins(workerProps); config = new StandaloneConfig(workerProps); sourceConfig = new SourceConnectorConfig(plugins, sourceConnectorPropsWithGroups(), true); metrics = new MockConnectMetrics(); } private Map<String, String> workerProps() { Map<String, String> props = new HashMap<>(); props.put(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put("key.converter", "org.apache.kafka.connect.json.JsonConverter"); props.put("value.converter", "org.apache.kafka.connect.json.JsonConverter"); props.put("offset.storage.file.filename", "/tmp/connect.offsets"); props.put(TOPIC_CREATION_ENABLE_CONFIG, "true"); return props; } private Map<String, String> sourceConnectorPropsWithGroups() { // setup up props for the source connector Map<String, String> props = new HashMap<>(); props.put("name", "foo-connector"); props.put(CONNECTOR_CLASS_CONFIG, TestableSourceConnector.class.getSimpleName()); props.put(TASKS_MAX_CONFIG, String.valueOf(1)); props.put(TOPIC_CONFIG, TOPIC); props.put(KEY_CONVERTER_CLASS_CONFIG, StringConverter.class.getName()); props.put(VALUE_CONVERTER_CLASS_CONFIG, StringConverter.class.getName()); props.put(TOPIC_CREATION_GROUPS_CONFIG, String.join(",", "foo", "bar")); props.put(DEFAULT_TOPIC_CREATION_PREFIX + REPLICATION_FACTOR_CONFIG, String.valueOf(1)); props.put(DEFAULT_TOPIC_CREATION_PREFIX + PARTITIONS_CONFIG, String.valueOf(1)); props.put(SourceConnectorConfig.TOPIC_CREATION_PREFIX + "foo" + "." + INCLUDE_REGEX_CONFIG, TOPIC); props.put(SourceConnectorConfig.TOPIC_CREATION_PREFIX + "bar" + "." + INCLUDE_REGEX_CONFIG, ".*"); props.put(SourceConnectorConfig.TOPIC_CREATION_PREFIX + "bar" + "." + EXCLUDE_REGEX_CONFIG, TOPIC); return props; } @AfterEach public void tearDown() { if (metrics != null) metrics.stop(); verifyNoMoreInteractions(statusListener); } @Test public void testMetricsGroup() { AbstractWorkerSourceTask.SourceTaskMetricsGroup group = new AbstractWorkerSourceTask.SourceTaskMetricsGroup(taskId, metrics); AbstractWorkerSourceTask.SourceTaskMetricsGroup group1 = new AbstractWorkerSourceTask.SourceTaskMetricsGroup(taskId1, metrics); for (int i = 0; i != 10; ++i) { group.recordPoll(100, 1000 + i * 100); group.recordWrite(10, 2); } for (int i = 0; i != 20; ++i) { group1.recordPoll(100, 1000 + i * 100); group1.recordWrite(10, 4); } assertEquals(1900.0, metrics.currentMetricValueAsDouble(group.metricGroup(), "poll-batch-max-time-ms"), 0.001d); assertEquals(1450.0, metrics.currentMetricValueAsDouble(group.metricGroup(), "poll-batch-avg-time-ms"), 0.001d); assertEquals(33.333, metrics.currentMetricValueAsDouble(group.metricGroup(), "source-record-poll-rate"), 0.001d); assertEquals(1000, metrics.currentMetricValueAsDouble(group.metricGroup(), "source-record-poll-total"), 0.001d); assertEquals(2.666, metrics.currentMetricValueAsDouble(group.metricGroup(), "source-record-write-rate"), 0.001d); assertEquals(80, metrics.currentMetricValueAsDouble(group.metricGroup(), "source-record-write-total"), 0.001d); assertEquals(900.0, metrics.currentMetricValueAsDouble(group.metricGroup(), "source-record-active-count"), 0.001d); // Close the group group.close(); for (MetricName metricName : group.metricGroup().metrics().metrics().keySet()) { // Metrics for this group should no longer exist assertFalse(group.metricGroup().groupId().includes(metricName)); } // Sensors for this group should no longer exist assertNull(group.metricGroup().metrics().getSensor("sink-record-read")); assertNull(group.metricGroup().metrics().getSensor("sink-record-send")); assertNull(group.metricGroup().metrics().getSensor("sink-record-active-count")); assertNull(group.metricGroup().metrics().getSensor("partition-count")); assertNull(group.metricGroup().metrics().getSensor("offset-seq-number")); assertNull(group.metricGroup().metrics().getSensor("offset-commit-completion")); assertNull(group.metricGroup().metrics().getSensor("offset-commit-completion-skip")); assertNull(group.metricGroup().metrics().getSensor("put-batch-time")); assertEquals(2900.0, metrics.currentMetricValueAsDouble(group1.metricGroup(), "poll-batch-max-time-ms"), 0.001d); assertEquals(1950.0, metrics.currentMetricValueAsDouble(group1.metricGroup(), "poll-batch-avg-time-ms"), 0.001d); assertEquals(66.667, metrics.currentMetricValueAsDouble(group1.metricGroup(), "source-record-poll-rate"), 0.001d); assertEquals(2000, metrics.currentMetricValueAsDouble(group1.metricGroup(), "source-record-poll-total"), 0.001d); assertEquals(4.0, metrics.currentMetricValueAsDouble(group1.metricGroup(), "source-record-write-rate"), 0.001d); assertEquals(120, metrics.currentMetricValueAsDouble(group1.metricGroup(), "source-record-write-total"), 0.001d); assertEquals(1800.0, metrics.currentMetricValueAsDouble(group1.metricGroup(), "source-record-active-count"), 0.001d); } @Test public void testSendRecordsConvertsData() { createWorkerTask(); // Can just use the same record for key and value List<SourceRecord> records = List.of( new SourceRecord(PARTITION, OFFSET, "topic", null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD) ); expectSendRecord(emptyHeaders()); expectApplyTransformationChain(); expectTopicCreation(TOPIC); workerTask.toSend = records; workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(); assertArrayEquals(SERIALIZED_KEY, sent.getValue().key()); assertArrayEquals(SERIALIZED_RECORD, sent.getValue().value()); verifyTaskGetTopic(); verifyTopicCreation(); } @Test public void testSendRecordsPropagatesTimestamp() { final Long timestamp = System.currentTimeMillis(); createWorkerTask(); expectSendRecord(emptyHeaders()); expectApplyTransformationChain(); expectTopicCreation(TOPIC); workerTask.toSend = List.of( new SourceRecord(PARTITION, OFFSET, "topic", null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD, timestamp) ); workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(); assertEquals(timestamp, sent.getValue().timestamp()); verifyTaskGetTopic(); verifyTopicCreation(); } @Test public void testSendRecordsCorruptTimestamp() { final Long timestamp = -3L; createWorkerTask(); expectConvertHeadersAndKeyValue(emptyHeaders(), TOPIC); expectApplyTransformationChain(); workerTask.toSend = List.of( new SourceRecord(PARTITION, OFFSET, "topic", null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD, timestamp) ); assertThrows(InvalidRecordException.class, workerTask::sendRecords); verifyNoInteractions(producer); verifyNoInteractions(admin); } @Test public void testSendRecordsNoTimestamp() { final Long timestamp = -1L; createWorkerTask(); expectSendRecord(emptyHeaders()); expectApplyTransformationChain(); expectTopicCreation(TOPIC); workerTask.toSend = List.of( new SourceRecord(PARTITION, OFFSET, "topic", null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD, timestamp) ); workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(); assertNull(sent.getValue().timestamp()); verifyTaskGetTopic(); verifyTopicCreation(); } @Test public void testHeaders() { Headers headers = new RecordHeaders() .add("header_key", "header_value".getBytes()); org.apache.kafka.connect.header.Headers connectHeaders = new ConnectHeaders() .add("header_key", new SchemaAndValue(Schema.STRING_SCHEMA, "header_value")); createWorkerTask(); expectSendRecord(headers); expectApplyTransformationChain(); expectTopicCreation(TOPIC); workerTask.toSend = List.of( new SourceRecord(PARTITION, OFFSET, TOPIC, null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD, null, connectHeaders) ); workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(); assertArrayEquals(SERIALIZED_KEY, sent.getValue().key()); assertArrayEquals(SERIALIZED_RECORD, sent.getValue().value()); assertEquals(headers, sent.getValue().headers()); verifyTaskGetTopic(); verifyTopicCreation(); } @Test public void testHeadersWithCustomConverter() throws Exception { StringConverter stringConverter = new StringConverter(); SampleConverterWithHeaders testConverter = new SampleConverterWithHeaders(); createWorkerTask(stringConverter, testConverter, stringConverter, RetryWithToleranceOperatorTest.noneOperator(), List::of, transformationChain); expectSendRecord(null); expectApplyTransformationChain(); expectTopicCreation(TOPIC); String stringA = "Árvíztűrő tükörfúrógép"; String encodingA = "latin2"; String stringB = "Тестовое сообщение"; String encodingB = "koi8_r"; org.apache.kafka.connect.header.Headers headersA = new ConnectHeaders() .addString("encoding", encodingA); org.apache.kafka.connect.header.Headers headersB = new ConnectHeaders() .addString("encoding", encodingB); workerTask.toSend = List.of( new SourceRecord(PARTITION, OFFSET, "topic", null, Schema.STRING_SCHEMA, "a", Schema.STRING_SCHEMA, stringA, null, headersA), new SourceRecord(PARTITION, OFFSET, "topic", null, Schema.STRING_SCHEMA, "b", Schema.STRING_SCHEMA, stringB, null, headersB) ); workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(2); List<ProducerRecord<byte[], byte[]>> capturedValues = sent.getAllValues(); assertEquals(2, capturedValues.size()); ProducerRecord<byte[], byte[]> sentRecordA = capturedValues.get(0); ProducerRecord<byte[], byte[]> sentRecordB = capturedValues.get(1); assertEquals(ByteBuffer.wrap("a".getBytes()), ByteBuffer.wrap(sentRecordA.key())); assertEquals( ByteBuffer.wrap(stringA.getBytes(encodingA)), ByteBuffer.wrap(sentRecordA.value()) ); assertEquals(encodingA, new String(sentRecordA.headers().lastHeader("encoding").value())); assertEquals(ByteBuffer.wrap("b".getBytes()), ByteBuffer.wrap(sentRecordB.key())); assertEquals( ByteBuffer.wrap(stringB.getBytes(encodingB)), ByteBuffer.wrap(sentRecordB.value()) ); assertEquals(encodingB, new String(sentRecordB.headers().lastHeader("encoding").value())); verifyTaskGetTopic(2); verifyTopicCreation(); } @Test public void testTopicCreateWhenTopicExists() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(0, null, List.of(), List.of()); TopicDescription topicDesc = new TopicDescription(TOPIC, false, List.of(topicPartitionInfo)); when(admin.describeTopics(TOPIC)).thenReturn(Map.of(TOPIC, topicDesc)); expectSendRecord(emptyHeaders()); workerTask.toSend = List.of(record1, record2); workerTask.sendRecords(); verifySendRecord(2); verify(admin, never()).createOrFindTopics(any(NewTopic.class)); // Make sure we didn't try to create the topic after finding out it already existed verifyNoMoreInteractions(admin); } @Test public void testSendRecordsTopicDescribeRetries() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); when(admin.describeTopics(TOPIC)) .thenThrow(new RetriableException(new TimeoutException("timeout"))) .thenReturn(Map.of()); workerTask.toSend = List.of(record1, record2); workerTask.sendRecords(); assertEquals(List.of(record1, record2), workerTask.toSend); verify(admin, never()).createOrFindTopics(any(NewTopic.class)); verifyNoMoreInteractions(admin); // Second round - calls to describe and create succeed expectTopicCreation(TOPIC); workerTask.sendRecords(); assertNull(workerTask.toSend); verifyTopicCreation(); } @Test public void testSendRecordsTopicCreateRetries() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); when(admin.describeTopics(TOPIC)).thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))) // First call to create the topic times out .thenThrow(new RetriableException(new TimeoutException("timeout"))) // Next attempt succeeds .thenReturn(createdTopic(TOPIC)); workerTask.toSend = List.of(record1, record2); workerTask.sendRecords(); assertEquals(List.of(record1, record2), workerTask.toSend); // Next they all succeed workerTask.sendRecords(); assertNull(workerTask.toSend); // First attempt failed, second succeeded verifyTopicCreation(2, TOPIC, TOPIC); } @Test public void testSendRecordsTopicDescribeRetriesMidway() { createWorkerTask(); // Differentiate only by Kafka partition so we can reuse conversion expectations SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, OTHER_TOPIC, 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); expectPreliminaryCalls(OTHER_TOPIC); when(admin.describeTopics(anyString())) .thenReturn(Map.of()) .thenThrow(new RetriableException(new TimeoutException("timeout"))) .thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))).thenAnswer( (Answer<TopicAdmin.TopicCreationResponse>) invocation -> { NewTopic newTopic = invocation.getArgument(0); return createdTopic(newTopic.name()); }); // Try to send 3, make first pass, second fail. Should save last record workerTask.toSend = List.of(record1, record2, record3); workerTask.sendRecords(); assertEquals(List.of(record3), workerTask.toSend); // Next they all succeed workerTask.sendRecords(); assertNull(workerTask.toSend); verify(admin, times(3)).describeTopics(anyString()); ArgumentCaptor<NewTopic> newTopicCaptor = ArgumentCaptor.forClass(NewTopic.class); verify(admin, times(2)).createOrFindTopics(newTopicCaptor.capture()); assertEquals(List.of(TOPIC, OTHER_TOPIC), newTopicCaptor.getAllValues() .stream() .map(NewTopic::name) .toList()); } @Test public void testSendRecordsTopicCreateRetriesMidway() { createWorkerTask(); // Differentiate only by Kafka partition so we can reuse conversion expectations SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, OTHER_TOPIC, 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); expectPreliminaryCalls(OTHER_TOPIC); when(admin.describeTopics(anyString())).thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))) .thenReturn(createdTopic(TOPIC)) .thenThrow(new RetriableException(new TimeoutException("timeout"))) .thenReturn(createdTopic(OTHER_TOPIC)); // Try to send 3, make first pass, second fail. Should save last record workerTask.toSend = List.of(record1, record2, record3); workerTask.sendRecords(); assertEquals(List.of(record3), workerTask.toSend); verifyTopicCreation(2, TOPIC, OTHER_TOPIC); // Second call to createOrFindTopics will throw // Next they all succeed workerTask.sendRecords(); assertNull(workerTask.toSend); verifyTopicCreation(3, TOPIC, OTHER_TOPIC, OTHER_TOPIC); } @Test public void testTopicDescribeFails() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); when(admin.describeTopics(TOPIC)).thenThrow( new ConnectException(new TopicAuthorizationException("unauthorized")) ); workerTask.toSend = List.of(record1, record2); assertThrows(ConnectException.class, workerTask::sendRecords); } @Test public void testTopicCreateFails() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); when(admin.describeTopics(TOPIC)).thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))).thenThrow( new ConnectException(new TopicAuthorizationException("unauthorized")) ); workerTask.toSend = List.of(record1, record2); assertThrows(ConnectException.class, workerTask::sendRecords); verify(admin).createOrFindTopics(any()); verifyTopicCreation(); } @Test public void testTopicCreateFailsWithExceptionWhenCreateReturnsTopicNotCreatedOrFound() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(TOPIC); when(admin.describeTopics(TOPIC)).thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))).thenReturn(TopicAdmin.EMPTY_CREATION); workerTask.toSend = List.of(record1, record2); assertThrows(ConnectException.class, workerTask::sendRecords); verify(admin).createOrFindTopics(any()); verifyTopicCreation(); } @Test public void testTopicCreateSucceedsWhenCreateReturnsExistingTopicFound() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectSendRecord(emptyHeaders()); expectApplyTransformationChain(); when(admin.describeTopics(TOPIC)).thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))).thenReturn(foundTopic(TOPIC)); workerTask.toSend = List.of(record1, record2); workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(2); List<ProducerRecord<byte[], byte[]>> capturedValues = sent.getAllValues(); assertEquals(2, capturedValues.size()); verifyTaskGetTopic(2); verifyTopicCreation(); } @Test public void testTopicCreateSucceedsWhenCreateReturnsNewTopicFound() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectSendRecord(emptyHeaders()); expectApplyTransformationChain(); when(admin.describeTopics(TOPIC)).thenReturn(Map.of()); when(admin.createOrFindTopics(any(NewTopic.class))).thenReturn(createdTopic(TOPIC)); workerTask.toSend = List.of(record1, record2); workerTask.sendRecords(); ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = verifySendRecord(2); List<ProducerRecord<byte[], byte[]>> capturedValues = sent.getAllValues(); assertEquals(2, capturedValues.size()); verifyTaskGetTopic(2); verifyTopicCreation(); } @Test public void testSendRecordsRetriableException() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, TOPIC, 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectConvertHeadersAndKeyValue(emptyHeaders(), TOPIC); when(transformationChain.apply(any(), eq(record1))).thenReturn(null); when(transformationChain.apply(any(), eq(record2))).thenReturn(null); when(transformationChain.apply(any(), eq(record3))).thenReturn(record3); TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(0, null, List.of(), List.of()); TopicDescription topicDesc = new TopicDescription(TOPIC, false, List.of(topicPartitionInfo)); when(admin.describeTopics(TOPIC)).thenReturn(Map.of(TOPIC, topicDesc)); when(producer.send(any(), any())).thenThrow(new RetriableException("Retriable exception")).thenReturn(null); workerTask.toSend = List.of(record1, record2, record3); // The first two records are filtered out / dropped by the transformation chain; only the third record will be attempted to be sent. // The producer throws a RetriableException the first time we try to send the third record assertFalse(workerTask.sendRecords()); // The next attempt to send the third record should succeed assertTrue(workerTask.sendRecords()); // Ensure that the first two records that were filtered out by the transformation chain // aren't re-processed when we retry the call to sendRecords() verify(transformationChain, times(1)).apply(any(), eq(record1)); verify(transformationChain, times(1)).apply(any(), eq(record2)); verify(transformationChain, times(2)).apply(any(), eq(record3)); } @Test public void testSendRecordsFailedTransformationErrorToleranceNone() { SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); RetryWithToleranceOperator<RetriableException> retryWithToleranceOperator = RetryWithToleranceOperatorTest.noneOperator(); TransformationChain<RetriableException, SourceRecord> transformationChainRetriableException = WorkerTestUtils.getTransformationChain(retryWithToleranceOperator, List.of(new RetriableException("Test"), record1)); createWorkerTask(transformationChainRetriableException, retryWithToleranceOperator); expectConvertHeadersAndKeyValue(emptyHeaders(), TOPIC); TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(0, null, List.of(), List.of()); TopicDescription topicDesc = new TopicDescription(TOPIC, false, List.of(topicPartitionInfo)); when(admin.describeTopics(TOPIC)).thenReturn(Map.of(TOPIC, topicDesc)); workerTask.toSend = List.of(record1); // The transformation errored out so the error should be re-raised by sendRecords with error tolerance None Exception exception = assertThrows(ConnectException.class, workerTask::sendRecords); assertTrue(exception.getMessage().contains("Tolerance exceeded")); // Ensure the transformation was called verify(transformationChainRetriableException, times(1)).apply(any(), eq(record1)); // The second transform call will succeed, batch should succeed at sending the one record (none were skipped) assertTrue(workerTask.sendRecords()); verifySendRecord(1); } @Test public void testSendRecordsFailedTransformationErrorToleranceAll() { RetryWithToleranceOperator<RetriableException> retryWithToleranceOperator = RetryWithToleranceOperatorTest.allOperator(); TransformationChain<RetriableException, SourceRecord> transformationChainRetriableException = WorkerTestUtils.getTransformationChain( retryWithToleranceOperator, List.of(new RetriableException("Test"))); createWorkerTask(transformationChainRetriableException, retryWithToleranceOperator); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectConvertHeadersAndKeyValue(emptyHeaders(), TOPIC); workerTask.toSend = List.of(record1); // The transformation errored out so the error should be ignored & the record skipped with error tolerance all assertTrue(workerTask.sendRecords()); // Ensure the transformation was called verify(transformationChainRetriableException, times(1)).apply(any(), eq(record1)); } @Test public void testSendRecordsConversionExceptionErrorToleranceNone() { SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, TOPIC, 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); RetryWithToleranceOperator<RetriableException> retryWithToleranceOperator = RetryWithToleranceOperatorTest.noneOperator(); List<Object> results = Stream.of(record1, record2, record3) .collect(Collectors.toList()); TransformationChain<RetriableException, SourceRecord> chain = WorkerTestUtils.getTransformationChain( retryWithToleranceOperator, results); createWorkerTask(chain, retryWithToleranceOperator); // When we try to convert the key/value of each record, throw an exception throwExceptionWhenConvertKey(emptyHeaders(), TOPIC); TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(0, null, List.of(), List.of()); TopicDescription topicDesc = new TopicDescription(TOPIC, false, List.of(topicPartitionInfo)); when(admin.describeTopics(TOPIC)).thenReturn(Map.of(TOPIC, topicDesc)); workerTask.toSend = List.of(record1, record2, record3); // Send records should fail when errors.tolerance is none and the conversion call fails Exception exception = assertThrows(ConnectException.class, workerTask::sendRecords); assertTrue(exception.getMessage().contains("Tolerance exceeded")); assertThrows(ConnectException.class, workerTask::sendRecords); assertThrows(ConnectException.class, workerTask::sendRecords); // Set the conversion call to succeed, batch should succeed at sending all three records (none were skipped) expectConvertHeadersAndKeyValue(emptyHeaders(), TOPIC); assertTrue(workerTask.sendRecords()); verifySendRecord(3); } @Test public void testSendRecordsConversionExceptionErrorToleranceAll() { SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, TOPIC, 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); RetryWithToleranceOperator<RetriableException> retryWithToleranceOperator = RetryWithToleranceOperatorTest.allOperator(); List<Object> results = Stream.of(record1, record2, record3) .collect(Collectors.toList()); TransformationChain<RetriableException, SourceRecord> chain = WorkerTestUtils.getTransformationChain( retryWithToleranceOperator, results); createWorkerTask(chain, retryWithToleranceOperator); // When we try to convert the key/value of each record, throw an exception throwExceptionWhenConvertKey(emptyHeaders(), TOPIC); workerTask.toSend = List.of(record1, record2, record3); // With errors.tolerance to all, the failed conversion should simply skip the record, and record successful batch assertTrue(workerTask.sendRecords()); } private void expectSendRecord(Headers headers) { if (headers != null) expectConvertHeadersAndKeyValue(headers, TOPIC); expectTaskGetTopic(); } private ArgumentCaptor<ProducerRecord<byte[], byte[]>> verifySendRecord() { return verifySendRecord(1); } private ArgumentCaptor<ProducerRecord<byte[], byte[]>> verifySendRecord(int times) { ArgumentCaptor<ProducerRecord<byte[], byte[]>> sent = ArgumentCaptor.forClass(ProducerRecord.class); ArgumentCaptor<Callback> producerCallbacks = ArgumentCaptor.forClass(Callback.class); verify(producer, times(times)).send(sent.capture(), producerCallbacks.capture()); for (Callback cb : producerCallbacks.getAllValues()) { cb.onCompletion(new RecordMetadata(new TopicPartition("foo", 0), 0, 0, 0L, 0, 0), null); } return sent; } private void expectTaskGetTopic() { when(statusBackingStore.getTopic(anyString(), anyString())).thenAnswer((Answer<TopicStatus>) invocation -> { String connector = invocation.getArgument(0, String.class); String topic = invocation.getArgument(1, String.class); return new TopicStatus(topic, new ConnectorTaskId(connector, 0), Time.SYSTEM.milliseconds()); }); } private void verifyTaskGetTopic() { verifyTaskGetTopic(1); } private void verifyTaskGetTopic(int times) { ArgumentCaptor<String> connectorCapture = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> topicCapture = ArgumentCaptor.forClass(String.class); verify(statusBackingStore, times(times)).getTopic(connectorCapture.capture(), topicCapture.capture()); assertEquals("job", connectorCapture.getValue()); assertEquals(TOPIC, topicCapture.getValue()); } @SuppressWarnings("SameParameterValue") private void expectTopicCreation(String topic) { when(admin.createOrFindTopics(any(NewTopic.class))).thenReturn(createdTopic(topic)); } private void verifyTopicCreation() { verifyTopicCreation(1, TOPIC); } private void verifyTopicCreation(int times, String... topics) { ArgumentCaptor<NewTopic> newTopicCapture = ArgumentCaptor.forClass(NewTopic.class); verify(admin, times(times)).createOrFindTopics(newTopicCapture.capture()); assertArrayEquals(topics, newTopicCapture.getAllValues() .stream() .map(NewTopic::name) .toArray(String[]::new)); } @SuppressWarnings("SameParameterValue") private TopicAdmin.TopicCreationResponse createdTopic(String topic) { Set<String> created = Set.of(topic); Set<String> existing = Set.of(); return new TopicAdmin.TopicCreationResponse(created, existing); } @SuppressWarnings("SameParameterValue") private TopicAdmin.TopicCreationResponse foundTopic(String topic) { Set<String> created = Set.of(); Set<String> existing = Set.of(topic); return new TopicAdmin.TopicCreationResponse(created, existing); } private void expectPreliminaryCalls(String topic) { expectConvertHeadersAndKeyValue(emptyHeaders(), topic); expectApplyTransformationChain(); } private void expectConvertHeadersAndKeyValue(Headers headers, String topic) { if (headers.iterator().hasNext()) { when(headerConverter.fromConnectHeader(anyString(), anyString(), eq(Schema.STRING_SCHEMA), anyString())) .thenAnswer((Answer<byte[]>) invocation -> { String headerValue = invocation.getArgument(3, String.class); return headerValue.getBytes(StandardCharsets.UTF_8); }); } when(keyConverter.fromConnectData(eq(topic), any(Headers.class), eq(KEY_SCHEMA), eq(KEY))) .thenReturn(SERIALIZED_KEY); when(valueConverter.fromConnectData(eq(topic), any(Headers.class), eq(RECORD_SCHEMA), eq(RECORD))) .thenReturn(SERIALIZED_RECORD); assertEquals(SERIALIZED_KEY, keyConverter.fromConnectData(topic, headers, KEY_SCHEMA, KEY)); assertEquals(SERIALIZED_RECORD, valueConverter.fromConnectData(topic, headers, RECORD_SCHEMA, RECORD)); } private void throwExceptionWhenConvertKey(Headers headers, String topic) { if (headers.iterator().hasNext()) { when(headerConverter.fromConnectHeader(anyString(), anyString(), eq(Schema.STRING_SCHEMA), anyString())) .thenAnswer((Answer<byte[]>) invocation -> { String headerValue = invocation.getArgument(3, String.class); return headerValue.getBytes(StandardCharsets.UTF_8); }); } when(keyConverter.fromConnectData(eq(topic), any(Headers.class), eq(KEY_SCHEMA), eq(KEY))) .thenThrow(new RetriableException("Failed to convert key")); } private void expectApplyTransformationChain() { when(transformationChain.apply(any(), any(SourceRecord.class))) .thenAnswer(AdditionalAnswers.returnsSecondArg()); SourceRecord randomString = mock(SourceRecord.class); assertEquals(transformationChain.apply(null, randomString), randomString); } private RecordHeaders emptyHeaders() { return new RecordHeaders(); } private void createWorkerTask(TransformationChain transformationChain, RetryWithToleranceOperator toleranceOperator) { createWorkerTask(keyConverter, valueConverter, headerConverter, toleranceOperator, List::of, transformationChain); } private void createWorkerTask() { createWorkerTask( keyConverter, valueConverter, headerConverter, RetryWithToleranceOperatorTest.noneOperator(), List::of, transformationChain); } private void createWorkerTask(Converter keyConverter, Converter valueConverter, HeaderConverter headerConverter, RetryWithToleranceOperator<SourceRecord> retryWithToleranceOperator, Supplier<List<ErrorReporter<SourceRecord>>> errorReportersSupplier, TransformationChain<SourceRecord, SourceRecord> transformationChain) { Plugin<Converter> keyConverterPlugin = metrics.wrap(keyConverter, taskId, true); Plugin<Converter> valueConverterPlugin = metrics.wrap(valueConverter, taskId, false); Plugin<HeaderConverter> headerConverterPlugin = metrics.wrap(headerConverter, taskId); workerTask = new AbstractWorkerSourceTask( taskId, sourceTask, statusListener, TargetState.STARTED, configState, keyConverterPlugin, valueConverterPlugin, headerConverterPlugin, transformationChain, workerTransactionContext, producer, admin, TopicCreationGroup.configuredGroups(sourceConfig), offsetReader, offsetWriter, offsetStore, config, metrics, errorHandlingMetrics, plugins.delegatingLoader(), Time.SYSTEM, retryWithToleranceOperator, statusBackingStore, Runnable::run, errorReportersSupplier, null, TestPlugins.noOpLoaderSwap()) { @Override protected void prepareToInitializeTask() { } @Override protected void prepareToEnterSendLoop() { } @Override protected void beginSendIteration() { } @Override protected void prepareToPollTask() { } @Override protected void recordDropped(SourceRecord record) { } @Override protected Optional<SubmittedRecords.SubmittedRecord> prepareToSendRecord(SourceRecord sourceRecord, ProducerRecord<byte[], byte[]> producerRecord) { return Optional.empty(); } @Override protected void recordDispatched(SourceRecord record) { } @Override protected void batchDispatched() { } @Override protected void recordSent(SourceRecord sourceRecord, ProducerRecord<byte[], byte[]> producerRecord, RecordMetadata recordMetadata) { } @Override protected void producerSendFailed(ProcessingContext<SourceRecord> context, boolean synchronous, ProducerRecord<byte[], byte[]> producerRecord, SourceRecord preTransformRecord, Exception e) { } @Override protected void finalOffsetCommit(boolean failed) { } }; } }
AbstractWorkerSourceTaskTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/util/NodeManagerHardwareUtils.java
{ "start": 1662, "end": 15340 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(NodeManagerHardwareUtils.class); private static boolean isHardwareDetectionEnabled(Configuration conf) { return conf.getBoolean( YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION, YarnConfiguration.DEFAULT_NM_ENABLE_HARDWARE_CAPABILITY_DETECTION); } /** * * Returns the number of CPUs on the node. This value depends on the * configuration setting which decides whether to count logical processors * (such as hyperthreads) as cores or not. * * @param conf * - Configuration object * @return Number of CPUs */ public static int getNodeCPUs(Configuration conf) { ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); return NodeManagerHardwareUtils.getNodeCPUs(plugin, conf); } /** * * Returns the number of CPUs on the node. This value depends on the * configuration setting which decides whether to count logical processors * (such as hyperthreads) as cores or not. * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - Configuration object * @return Number of CPU cores on the node. */ public static int getNodeCPUs(ResourceCalculatorPlugin plugin, Configuration conf) { int numProcessors = plugin.getNumProcessors(); boolean countLogicalCores = conf.getBoolean(YarnConfiguration.NM_COUNT_LOGICAL_PROCESSORS_AS_CORES, YarnConfiguration.DEFAULT_NM_COUNT_LOGICAL_PROCESSORS_AS_CORES); if (!countLogicalCores) { numProcessors = plugin.getNumCores(); } return numProcessors; } /** * * Returns the fraction of CPUs that should be used for YARN containers. * The number is derived based on various configuration params such as * YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT * * @param conf * - Configuration object * @return Fraction of CPUs to be used for YARN containers */ public static float getContainersCPUs(Configuration conf) { ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); return NodeManagerHardwareUtils.getContainersCPUs(plugin, conf); } /** * * Returns the fraction of CPUs that should be used for YARN containers. * The number is derived based on various configuration params such as * YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - Configuration object * @return Fraction of CPUs to be used for YARN containers */ public static float getContainersCPUs(ResourceCalculatorPlugin plugin, Configuration conf) { int numProcessors = getNodeCPUs(plugin, conf); int nodeCpuPercentage = getNodeCpuPercentage(conf); return (nodeCpuPercentage * numProcessors) / 100.0f; } /** * Gets the percentage of physical CPU that is configured for YARN containers. * This is percent {@literal >} 0 and {@literal <=} 100 based on * {@link YarnConfiguration#NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT} * @param conf Configuration object * @return percent {@literal >} 0 and {@literal <=} 100 */ public static int getNodeCpuPercentage(Configuration conf) { int nodeCpuPercentage = Math.min(conf.getInt( YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT, YarnConfiguration.DEFAULT_NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT), 100); nodeCpuPercentage = Math.max(0, nodeCpuPercentage); if (nodeCpuPercentage == 0) { String message = "Illegal value for " + YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT + ". Value cannot be less than or equal to 0."; throw new IllegalArgumentException(message); } return nodeCpuPercentage; } private static int getConfiguredVCores(Configuration conf) { int cores = conf.getInt(YarnConfiguration.NM_VCORES, YarnConfiguration.DEFAULT_NM_VCORES); if (cores == -1) { cores = YarnConfiguration.DEFAULT_NM_VCORES; } return cores; } /** * Function to return the number of vcores on the system that can be used for * YARN containers. If a number is specified in the configuration file, then * that number is returned. If nothing is specified - 1. If the OS is an * "unknown" OS(one for which we don't have ResourceCalculatorPlugin * implemented), return the default NodeManager cores. 2. If the config * variable yarn.nodemanager.cpu.use_logical_processors is set to true, it * returns the logical processor count(count hyperthreads as cores), else it * returns the physical cores count. * * @param conf * - the configuration for the NodeManager * @return the number of cores to be used for YARN containers * */ public static int getVCores(Configuration conf) { if (!isHardwareDetectionEnabled(conf)) { return getConfiguredVCores(conf); } // is this os for which we can determine cores? ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); if (plugin == null) { return getConfiguredVCores(conf); } return getVCoresInternal(plugin, conf); } /** * Function to return the number of vcores on the system that can be used for * YARN containers. If a number is specified in the configuration file, then * that number is returned. If nothing is specified - 1. If the OS is an * "unknown" OS(one for which we don't have ResourceCalculatorPlugin * implemented), return the default NodeManager cores. 2. If the config * variable yarn.nodemanager.cpu.use_logical_processors is set to true, it * returns the logical processor count(count hyperthreads as cores), else it * returns the physical cores count. * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - the configuration for the NodeManager * @return the number of cores to be used for YARN containers * */ public static int getVCores(ResourceCalculatorPlugin plugin, Configuration conf) { if (!isHardwareDetectionEnabled(conf) || plugin == null) { return getConfiguredVCores(conf); } return getVCoresInternal(plugin, conf); } private static int getVCoresInternal(ResourceCalculatorPlugin plugin, Configuration conf) { String message; int cores = conf.getInt(YarnConfiguration.NM_VCORES, -1); if (cores == -1) { float physicalCores = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf); float multiplier = conf.getFloat(YarnConfiguration.NM_PCORES_VCORES_MULTIPLIER, YarnConfiguration.DEFAULT_NM_PCORES_VCORES_MULTIPLIER); if (multiplier > 0) { float tmp = physicalCores * multiplier; if (tmp > 0 && tmp < 1) { // on a single core machine - tmp can be between 0 and 1 cores = 1; } else { cores = Math.round(tmp); } } else { message = "Illegal value for " + YarnConfiguration.NM_PCORES_VCORES_MULTIPLIER + ". Value must be greater than 0."; throw new IllegalArgumentException(message); } } if(cores <= 0) { message = "Illegal value for " + YarnConfiguration.NM_VCORES + ". Value must be greater than 0."; throw new IllegalArgumentException(message); } return cores; } private static long getConfiguredMemoryMB(Configuration conf) { long memoryMb = conf.getLong(YarnConfiguration.NM_PMEM_MB, YarnConfiguration.DEFAULT_NM_PMEM_MB); if (memoryMb == -1) { memoryMb = YarnConfiguration.DEFAULT_NM_PMEM_MB; } return memoryMb; } /** * Function to return how much memory we should set aside for YARN containers. * If a number is specified in the configuration file, then that number is * returned. If nothing is specified - 1. If the OS is an "unknown" OS(one for * which we don't have ResourceCalculatorPlugin implemented), return the * default NodeManager physical memory. 2. If the OS has a * ResourceCalculatorPlugin implemented, the calculation is 0.8 * (RAM - 2 * * JVM-memory) i.e. use 80% of the memory after accounting for memory used by * the DataNode and the NodeManager. If the number is less than 1GB, log a * warning message. * * @param conf * - the configuration for the NodeManager * @return the amount of memory that will be used for YARN containers in MB. */ public static long getContainerMemoryMB(Configuration conf) { if (!isHardwareDetectionEnabled(conf)) { return getConfiguredMemoryMB(conf); } ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); if (plugin == null) { return getConfiguredMemoryMB(conf); } return getContainerMemoryMBInternal(plugin, conf); } /** * Function to return how much memory we should set aside for YARN containers. * If a number is specified in the configuration file, then that number is * returned. If nothing is specified - 1. If the OS is an "unknown" OS(one for * which we don't have ResourceCalculatorPlugin implemented), return the * default NodeManager physical memory. 2. If the OS has a * ResourceCalculatorPlugin implemented, the calculation is 0.8 * (RAM - 2 * * JVM-memory) i.e. use 80% of the memory after accounting for memory used by * the DataNode and the NodeManager. If the number is less than 1GB, log a * warning message. * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - the configuration for the NodeManager * @return the amount of memory that will be used for YARN containers in MB. */ public static long getContainerMemoryMB(ResourceCalculatorPlugin plugin, Configuration conf) { if (!isHardwareDetectionEnabled(conf) || plugin == null) { return getConfiguredMemoryMB(conf); } return getContainerMemoryMBInternal(plugin, conf); } private static long getContainerMemoryMBInternal(ResourceCalculatorPlugin plugin, Configuration conf) { long memoryMb = conf.getInt(YarnConfiguration.NM_PMEM_MB, -1); if (memoryMb == -1) { long physicalMemoryMB = (plugin.getPhysicalMemorySize() / (1024 * 1024)); long hadoopHeapSizeMB = (Runtime.getRuntime().maxMemory() / (1024 * 1024)); long containerPhysicalMemoryMB = (long) (0.8f * (physicalMemoryMB - (2 * hadoopHeapSizeMB))); long reservedMemoryMB = conf .getInt(YarnConfiguration.NM_SYSTEM_RESERVED_PMEM_MB, -1); if (reservedMemoryMB != -1) { containerPhysicalMemoryMB = physicalMemoryMB - reservedMemoryMB; } if (containerPhysicalMemoryMB <= 0) { LOG.error("Calculated memory for YARN containers is too low." + " Node memory is " + physicalMemoryMB + " MB, system reserved memory is " + reservedMemoryMB + " MB."); } containerPhysicalMemoryMB = Math.max(containerPhysicalMemoryMB, 0); memoryMb = containerPhysicalMemoryMB; } if(memoryMb <= 0) { String message = "Illegal value for " + YarnConfiguration.NM_PMEM_MB + ". Value must be greater than 0."; throw new IllegalArgumentException(message); } return memoryMb; } /** * Get the resources for the node. * @param configuration configuration file * @return the resources for the node */ public static Resource getNodeResources(Configuration configuration) { Configuration conf = new Configuration(configuration); String memory = ResourceInformation.MEMORY_MB.getName(); String vcores = ResourceInformation.VCORES.getName(); Resource ret = Resource.newInstance(0, 0); Map<String, ResourceInformation> resourceInformation = ResourceUtils.getNodeResourceInformation(conf); for (Map.Entry<String, ResourceInformation> entry : resourceInformation .entrySet()) { ret.setResourceInformation(entry.getKey(), entry.getValue()); LOG.debug("Setting key {} to {}", entry.getKey(), entry.getValue()); } if (resourceInformation.containsKey(memory)) { Long value = resourceInformation.get(memory).getValue(); if (value > Integer.MAX_VALUE) { throw new YarnRuntimeException("Value '" + value + "' for resource memory is more than the maximum for an integer."); } ResourceInformation memResInfo = resourceInformation.get(memory); if(memResInfo.getValue() == 0) { ret.setMemorySize(getContainerMemoryMB(conf)); LOG.debug("Set memory to {}", ret.getMemorySize()); } } if (resourceInformation.containsKey(vcores)) { Long value = resourceInformation.get(vcores).getValue(); if (value > Integer.MAX_VALUE) { throw new YarnRuntimeException("Value '" + value + "' for resource vcores is more than the maximum for an integer."); } ResourceInformation vcoresResInfo = resourceInformation.get(vcores); if(vcoresResInfo.getValue() == 0) { ret.setVirtualCores(getVCores(conf)); LOG.debug("Set vcores to {}", ret.getVirtualCores()); } } LOG.debug("Node resource information map is {}", ret); return ret; } }
NodeManagerHardwareUtils
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/naming/CommonParams.java
{ "start": 754, "end": 1250 }
class ____ { public static final String CODE = "code"; public static final String SERVICE_NAME = "serviceName"; public static final String CLUSTER_NAME = "clusterName"; public static final String NAMESPACE_ID = "namespaceId"; public static final String GROUP_NAME = "groupName"; public static final String LIGHT_BEAT_ENABLED = "lightBeatEnabled"; public static final String NAMING_REQUEST_TIMEOUT = "namingRequestTimeout"; }
CommonParams
java
apache__camel
components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerConsumerValidationRunnable.java
{ "start": 3965, "end": 4076 }
class ____, the component URI and the connection information * <p/> * The String will in the format <
name
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/commit/impl/CommitOperations.java
{ "start": 27336, "end": 28681 }
class ____ { private final IOException exception; public static final MaybeIOE NONE = new MaybeIOE(null); /** * Construct with an exception. * @param exception exception */ public MaybeIOE(IOException exception) { this.exception = exception; } /** * Get any exception. * @return the exception. */ public IOException getException() { return exception; } /** * Is there an exception in this class? * @return true if there is an exception */ public boolean hasException() { return exception != null; } /** * Rethrow any exception. * @throws IOException the exception field, if non-null. */ public void maybeRethrow() throws IOException { if (exception != null) { throw exception; } } @Override public String toString() { final StringBuilder sb = new StringBuilder("MaybeIOE{"); sb.append(hasException() ? exception : ""); sb.append('}'); return sb.toString(); } /** * Get an instance based on the exception: either a value * or a reference to {@link #NONE}. * @param ex exception * @return an instance. */ public static MaybeIOE of(IOException ex) { return ex != null ? new MaybeIOE(ex) : NONE; } } }
MaybeIOE
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/DefaultInMemorySorterFactory.java
{ "start": 1147, "end": 2565 }
class ____<T> implements InMemorySorterFactory<T> { @Nonnull private final TypeSerializer<T> typeSerializer; @Nonnull private final TypeComparator<T> typeComparator; private final boolean useFixedLengthRecordSorter; public DefaultInMemorySorterFactory( @Nonnull TypeSerializer<T> typeSerializer, @Nonnull TypeComparator<T> typeComparator, int thresholdForInPlaceSorting) { this.typeSerializer = typeSerializer; this.typeComparator = typeComparator; this.useFixedLengthRecordSorter = typeComparator.supportsSerializationWithKeyNormalization() && typeSerializer.getLength() > 0 && typeSerializer.getLength() <= thresholdForInPlaceSorting; } @Override public InMemorySorter<T> create(List<MemorySegment> sortSegments) { final TypeSerializer<T> duplicatedTypeSerializer = typeSerializer.duplicate(); final TypeComparator<T> duplicateTypeComparator = typeComparator.duplicate(); if (useFixedLengthRecordSorter) { return new FixedLengthRecordSorter<>( duplicatedTypeSerializer, duplicateTypeComparator, sortSegments); } else { return new NormalizedKeySorter<>( duplicatedTypeSerializer, duplicateTypeComparator, sortSegments); } } }
DefaultInMemorySorterFactory
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/azureaistudio/action/AzureAiStudioActionCreator.java
{ "start": 1414, "end": 3455 }
class ____ implements AzureAiStudioActionVisitor { private final Sender sender; private final ServiceComponents serviceComponents; public AzureAiStudioActionCreator(Sender sender, ServiceComponents serviceComponents) { this.sender = Objects.requireNonNull(sender); this.serviceComponents = Objects.requireNonNull(serviceComponents); } @Override public ExecutableAction create(AzureAiStudioChatCompletionModel completionModel, Map<String, Object> taskSettings) { var overriddenModel = AzureAiStudioChatCompletionModel.of(completionModel, taskSettings); var requestManager = new AzureAiStudioChatCompletionRequestManager(overriddenModel, serviceComponents.threadPool()); var errorMessage = constructFailedToSendRequestMessage("Azure AI Studio completion"); return new SenderExecutableAction(sender, requestManager, errorMessage); } @Override public ExecutableAction create(AzureAiStudioEmbeddingsModel embeddingsModel, Map<String, Object> taskSettings) { var overriddenModel = AzureAiStudioEmbeddingsModel.of(embeddingsModel, taskSettings); var requestManager = new AzureAiStudioEmbeddingsRequestManager( overriddenModel, serviceComponents.truncator(), serviceComponents.threadPool() ); var errorMessage = constructFailedToSendRequestMessage("Azure AI Studio embeddings"); return new SenderExecutableAction(sender, requestManager, errorMessage); } @Override public ExecutableAction create(AzureAiStudioRerankModel rerankModel, Map<String, Object> taskSettings) { var overriddenModel = AzureAiStudioRerankModel.of(rerankModel, taskSettings); var requestManager = new AzureAiStudioRerankRequestManager(overriddenModel, serviceComponents.threadPool()); var errorMessage = constructFailedToSendRequestMessage("Azure AI Studio rerank"); return new SenderExecutableAction(sender, requestManager, errorMessage); } }
AzureAiStudioActionCreator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterNamingTest.java
{ "start": 6290, "end": 6553 }
class ____ { public <B, B2, B3, B4, Bad> void method(Bad f) { Bad d = f; B2 wow = null; } } """) .addOutputLines( "out/Test.java", """
Test
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/converter/ConverterTest.java
{ "start": 1550, "end": 3786 }
class ____ { @Test public void testToArray() throws Exception { List<String> testList = new ArrayList<>(); testList.add("string 1"); testList.add("string 2"); Object[] array = CxfConverter.toArray(testList); assertNotNull(array, "The array should not be null"); assertEquals(2, array.length, "The array size should not be wrong"); } @Test public void testFallbackConverter() throws Exception { CamelContext context = new DefaultCamelContext(); Exchange exchange = new DefaultExchange(context); MessageContentsList list = new MessageContentsList(); NodeListWrapper nl = new NodeListWrapper(new ArrayList<Element>()); list.add(nl); exchange.getIn().setBody(list); Node node = exchange.getIn().getBody(Node.class); assertNull(node); File file = new File("src/test/resources/org/apache/camel/component/cxf/converter/test.xml"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(file); document.getDocumentElement().normalize(); List<Element> elements = new ArrayList<>(); elements.add(document.getDocumentElement()); nl = new NodeListWrapper(elements); list.clear(); // there is only 1 element in the list so it can be converted to a single node element list.add(nl); exchange.getIn().setBody(list); node = exchange.getIn().getBody(Node.class); assertNotNull(node); } @Test public void testMessageContentsListAsGeneralList() throws Exception { CamelContext context = new DefaultCamelContext(); Exchange exchange = new DefaultExchange(context); MessageContentsList list = new MessageContentsList(); list.add("hehe"); list.add("haha"); exchange.getIn().setBody(list); String ret = exchange.getIn().getBody(String.class); assertEquals("[hehe, haha]", ret, "shouldn't miss list content"); } }
ConverterTest
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java
{ "start": 1649, "end": 10619 }
class ____ { private DefaultListableBeanFactory bf; @BeforeEach void setUp() { bf = new DefaultListableBeanFactory(); } @Test void testNoArgGetter() { bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("factory", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator.class) .getBeanDefinition()); TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory"); TestService testService = factory.getTestService(); assertThat(testService).isNotNull(); } @Test void testErrorOnTooManyOrTooFew() { bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("testServiceInstance2", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("factory", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator.class) .getBeanDefinition()); bf.registerBeanDefinition("factory2", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator2.class) .getBeanDefinition()); bf.registerBeanDefinition("factory3", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestService2Locator.class) .getBeanDefinition()); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("more than one matching type").isThrownBy(() -> ((TestServiceLocator) bf.getBean("factory")).getTestService()); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("more than one matching type").isThrownBy(() -> ((TestServiceLocator2) bf.getBean("factory2")).getTestService(null)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("no matching types").isThrownBy(() -> ((TestService2Locator) bf.getBean("factory3")).getTestService()); } @Test void testErrorOnTooManyOrTooFewWithCustomServiceLocatorException() { bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("testServiceInstance2", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("factory", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator.class) .addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException1.class) .getBeanDefinition()); bf.registerBeanDefinition("factory2", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator2.class) .addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException2.class) .getBeanDefinition()); bf.registerBeanDefinition("factory3", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestService2Locator.class) .addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException3.class) .getBeanDefinition()); assertThatExceptionOfType(CustomServiceLocatorException1.class).as("more than one matching type").isThrownBy(() -> ((TestServiceLocator) bf.getBean("factory")).getTestService()) .withCauseInstanceOf(NoSuchBeanDefinitionException.class); assertThatExceptionOfType(CustomServiceLocatorException2.class).as("more than one matching type").isThrownBy(() -> ((TestServiceLocator2) bf.getBean("factory2")).getTestService(null)) .withCauseInstanceOf(NoSuchBeanDefinitionException.class); assertThatExceptionOfType(CustomServiceLocatorException3.class).as("no matching type").isThrownBy(() -> ((TestService2Locator) bf.getBean("factory3")).getTestService()); } @Test void testStringArgGetter() throws Exception { bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("factory", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator2.class) .getBeanDefinition()); // test string-arg getter with null id TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory"); @SuppressWarnings("unused") TestService testBean = factory.getTestService(null); // now test with explicit id testBean = factory.getTestService("testService"); // now verify failure on bad id assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> factory.getTestService("bogusTestService")); } @Disabled @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory public void testCombinedLocatorInterface() { bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerAlias("testService", "1"); bf.registerBeanDefinition("factory", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class) .getBeanDefinition()); // StaticApplicationContext ctx = new StaticApplicationContext(); // ctx.registerPrototype("testService", TestService.class, new MutablePropertyValues()); // ctx.registerAlias("testService", "1"); // MutablePropertyValues mpv = new MutablePropertyValues(); // mpv.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class); // ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); // ctx.refresh(); TestServiceLocator3 factory = (TestServiceLocator3) bf.getBean("factory"); TestService testBean1 = factory.getTestService(); TestService testBean2 = factory.getTestService("testService"); TestService testBean3 = factory.getTestService(1); TestService testBean4 = factory.someFactoryMethod(); assertThat(testBean2).isNotSameAs(testBean1); assertThat(testBean3).isNotSameAs(testBean1); assertThat(testBean4).isNotSameAs(testBean1); assertThat(testBean3).isNotSameAs(testBean2); assertThat(testBean4).isNotSameAs(testBean2); assertThat(testBean4).isNotSameAs(testBean3); assertThat(factory.toString()).contains("TestServiceLocator3"); } @Disabled @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory public void testServiceMappings() { bf.registerBeanDefinition("testService1", genericBeanDefinition(TestService.class).getBeanDefinition()); bf.registerBeanDefinition("testService2", genericBeanDefinition(ExtendedTestService.class).getBeanDefinition()); bf.registerBeanDefinition("factory", genericBeanDefinition(ServiceLocatorFactoryBean.class) .addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class) .addPropertyValue("serviceMappings", "=testService1\n1=testService1\n2=testService2") .getBeanDefinition()); // StaticApplicationContext ctx = new StaticApplicationContext(); // ctx.registerPrototype("testService1", TestService.class, new MutablePropertyValues()); // ctx.registerPrototype("testService2", ExtendedTestService.class, new MutablePropertyValues()); // MutablePropertyValues mpv = new MutablePropertyValues(); // mpv.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class); // mpv.addPropertyValue("serviceMappings", "=testService1\n1=testService1\n2=testService2"); // ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); // ctx.refresh(); TestServiceLocator3 factory = (TestServiceLocator3) bf.getBean("factory"); TestService testBean1 = factory.getTestService(); TestService testBean2 = factory.getTestService("testService1"); TestService testBean3 = factory.getTestService(1); TestService testBean4 = factory.getTestService(2); assertThat(testBean2).isNotSameAs(testBean1); assertThat(testBean3).isNotSameAs(testBean1); assertThat(testBean4).isNotSameAs(testBean1); assertThat(testBean3).isNotSameAs(testBean2); assertThat(testBean4).isNotSameAs(testBean2); assertThat(testBean4).isNotSameAs(testBean3); assertThat(testBean1).isNotInstanceOf(ExtendedTestService.class); assertThat(testBean2).isNotInstanceOf(ExtendedTestService.class); assertThat(testBean3).isNotInstanceOf(ExtendedTestService.class); assertThat(testBean4).isInstanceOf(ExtendedTestService.class); } @Test void testNoServiceLocatorInterfaceSupplied() { assertThatIllegalArgumentException().isThrownBy( new ServiceLocatorFactoryBean()::afterPropertiesSet); } @Test void testWhenServiceLocatorInterfaceIsNotAnInterfaceType() { ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean(); factory.setServiceLocatorInterface(getClass()); assertThatIllegalArgumentException().isThrownBy( factory::afterPropertiesSet); // should throw, bad (non-interface-type) serviceLocator
ServiceLocatorFactoryBeanTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryAssignmentTest.java
{ "start": 5428, "end": 5833 }
class ____ { // BUG: Diagnostic contains: with @Inject should not @Inject boolean myFoo = false; } """) .doTest(); } @Test public void positiveOnTestParameter() { testHelper .addSourceLines( "Test.java", """ import com.google.testing.junit.testparameterinjector.TestParameter;
Test
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/errors/ProductionExceptionHandler.java
{ "start": 6941, "end": 8766 }
enum ____ { /** Continue processing. * * <p> For this case, output records which could not be written successfully are lost. * Use this option only if you can tolerate data loss. */ CONTINUE(0, "CONTINUE"), /** Fail processing. * * <p> Kafka Streams will raise an exception and the {@code StreamsThread} will fail. * No offsets (for {@link org.apache.kafka.streams.StreamsConfig#AT_LEAST_ONCE at-least-once}) or transactions * (for {@link org.apache.kafka.streams.StreamsConfig#EXACTLY_ONCE_V2 exactly-once}) will be committed. */ FAIL(1, "FAIL"), /** Retry the failed operation. * * <p> Retrying might imply that a {@link TaskCorruptedException} exception is thrown, and that the retry * is started from the last committed offset. * * <p> <b>NOTE:</b> {@code RETRY} is only a valid return value for * {@link org.apache.kafka.common.errors.RetriableException retriable exceptions}. * If {@code RETRY} is returned for a non-retriable exception it will be interpreted as {@link #FAIL}. */ RETRY(2, "RETRY"); /** * An english description for the used option. This is for debugging only and may change. */ public final String name; /** * The permanent and immutable id for the used option. This can't change ever. */ public final int id; ProductionExceptionHandlerResponse(final int id, final String name) { this.id = id; this.name = name; } } /** * Enumeration that describes the response from the exception handler. */
ProductionExceptionHandlerResponse
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/schedulers/ExecutorScheduler.java
{ "start": 14741, "end": 16334 }
class ____ extends AtomicReference<Runnable> implements Runnable, Disposable, SchedulerRunnableIntrospection { private static final long serialVersionUID = -4101336210206799084L; final SequentialDisposable timed; final SequentialDisposable direct; DelayedRunnable(Runnable run) { super(run); this.timed = new SequentialDisposable(); this.direct = new SequentialDisposable(); } @Override public void run() { Runnable r = get(); if (r != null) { try { try { r.run(); } finally { lazySet(null); timed.lazySet(DisposableHelper.DISPOSED); direct.lazySet(DisposableHelper.DISPOSED); } } catch (Throwable ex) { // Exceptions.throwIfFatal(ex); nowhere to go RxJavaPlugins.onError(ex); throw ex; } } } @Override public boolean isDisposed() { return get() == null; } @Override public void dispose() { if (getAndSet(null) != null) { timed.dispose(); direct.dispose(); } } @Override public Runnable getWrappedRunnable() { Runnable r = get(); return r != null ? r : Functions.EMPTY_RUNNABLE; } } final
DelayedRunnable
java
apache__rocketmq
auth/src/main/java/org/apache/rocketmq/auth/authorization/builder/AuthorizationContextBuilder.java
{ "start": 1154, "end": 1391 }
interface ____ { List<DefaultAuthorizationContext> build(Metadata metadata, GeneratedMessageV3 message); List<DefaultAuthorizationContext> build(ChannelHandlerContext context, RemotingCommand command); }
AuthorizationContextBuilder
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/CompareCondition.java
{ "start": 6226, "end": 8274 }
enum ____ { EQ() { @Override public boolean eval(Object v1, Object v2) { Integer compVal = LenientCompare.compare(v1, v2); return compVal != null && compVal == 0; } @Override public boolean supportsStructures() { return true; } }, NOT_EQ() { @Override public boolean eval(Object v1, Object v2) { Integer compVal = LenientCompare.compare(v1, v2); return compVal == null || compVal != 0; } @Override public boolean supportsStructures() { return true; } }, LT() { @Override public boolean eval(Object v1, Object v2) { Integer compVal = LenientCompare.compare(v1, v2); return compVal != null && compVal < 0; } }, LTE() { @Override public boolean eval(Object v1, Object v2) { Integer compVal = LenientCompare.compare(v1, v2); return compVal != null && compVal <= 0; } }, GT() { @Override public boolean eval(Object v1, Object v2) { Integer compVal = LenientCompare.compare(v1, v2); return compVal != null && compVal > 0; } }, GTE() { @Override public boolean eval(Object v1, Object v2) { Integer compVal = LenientCompare.compare(v1, v2); return compVal != null && compVal >= 0; } }; public abstract boolean eval(Object v1, Object v2); public boolean supportsStructures() { return false; } public String id() { return name().toLowerCase(Locale.ROOT); } public static Op resolve(String id) { return Op.valueOf(id.toUpperCase(Locale.ROOT)); } } }
Op
java
apache__flink
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/rest/OperationRelatedITCase.java
{ "start": 2594, "end": 8384 }
class ____ extends RestAPIITCaseBase { private static final String sessionName = "test"; private static final Map<String, String> properties = new HashMap<>(); static { properties.put("k1", "v1"); properties.put("k2", "v2"); } private static final OpenSessionHeaders openSessionHeaders = OpenSessionHeaders.getInstance(); private static final OpenSessionRequestBody openSessionRequestBody = new OpenSessionRequestBody(sessionName, properties); private static final EmptyMessageParameters emptyParameters = EmptyMessageParameters.getInstance(); private static final EmptyRequestBody emptyRequestBody = EmptyRequestBody.getInstance(); private static final GetOperationStatusHeaders getOperationStatusHeaders = GetOperationStatusHeaders.getInstance(); private static final CancelOperationHeaders cancelOperationHeaders = CancelOperationHeaders.getInstance(); private static final CloseOperationHeaders closeOperationHeaders = CloseOperationHeaders.getInstance(); @Test void testWhenSubmitOperation() throws Exception { submitOperation(); } @Test void testOperationRelatedApis() throws Exception { List<String> ids; String status; // Get the RUNNING status when an operation is submitted ids = submitOperation(); status = getOperationStatus(ids); assertThat(OperationStatus.RUNNING).hasToString(status); // Get the CANCELED status when an operation is canceled ids = submitOperation(); status = cancelOperation(ids); assertThat(OperationStatus.CANCELED).hasToString(status); status = getOperationStatus(ids); assertThat(OperationStatus.CANCELED).hasToString(status); // Get the CLOSED status when an operation is closed ids = submitOperation(); status = closeOperation(ids); assertThat(OperationStatus.CLOSED).hasToString(status); SessionHandle sessionHandle = new SessionHandle(UUID.fromString(ids.get(0))); OperationHandle operationHandle = new OperationHandle(UUID.fromString(ids.get(1))); assertThatThrownBy( () -> SQL_GATEWAY_SERVICE_EXTENSION .getSessionManager() .getSession(sessionHandle) .getOperationManager() .getOperation(operationHandle)) .isInstanceOf(SqlGatewayException.class); } List<String> submitOperation() throws Exception { CompletableFuture<OpenSessionResponseBody> response = sendRequest(openSessionHeaders, emptyParameters, openSessionRequestBody); String sessionHandleId = response.get().getSessionHandle(); assertThat(sessionHandleId).isNotNull(); SessionHandle sessionHandle = new SessionHandle(UUID.fromString(sessionHandleId)); assertThat(SQL_GATEWAY_SERVICE_EXTENSION.getSessionManager().getSession(sessionHandle)) .isNotNull(); OneShotLatch startLatch = new OneShotLatch(); Thread main = Thread.currentThread(); OperationHandle operationHandle = SQL_GATEWAY_SERVICE_EXTENSION .getService() .submitOperation( sessionHandle, () -> { try { startLatch.trigger(); // keep operation in RUNNING state in response to cancel // or close operations. main.join(); } catch (InterruptedException ignored) { } return NotReadyResult.INSTANCE; }); startLatch.await(); assertThat(operationHandle).isNotNull(); return Arrays.asList(sessionHandleId, operationHandle.getIdentifier().toString()); } String getOperationStatus(List<String> ids) throws Exception { String sessionId = ids.get(0); String operationId = ids.get(1); OperationMessageParameters operationMessageParameters = new OperationMessageParameters( new SessionHandle(UUID.fromString(sessionId)), new OperationHandle(UUID.fromString(operationId))); CompletableFuture<OperationStatusResponseBody> future = sendRequest( getOperationStatusHeaders, operationMessageParameters, emptyRequestBody); return future.get().getStatus(); } String cancelOperation(List<String> ids) throws Exception { CompletableFuture<OperationStatusResponseBody> future = sendRequest(cancelOperationHeaders, getMessageParameters(ids), emptyRequestBody); return future.get().getStatus(); } String closeOperation(List<String> ids) throws Exception { CompletableFuture<OperationStatusResponseBody> future = sendRequest(closeOperationHeaders, getMessageParameters(ids), emptyRequestBody); return future.get().getStatus(); } OperationMessageParameters getMessageParameters(List<String> ids) { String sessionId = ids.get(0); String operationId = ids.get(1); return new OperationMessageParameters( new SessionHandle(UUID.fromString(sessionId)), new OperationHandle(UUID.fromString(operationId))); } }
OperationRelatedITCase
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8385PropertyContributoSPITest.java
{ "start": 1027, "end": 1820 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that PropertyContributorSPI is used and does it's job */ @Test void testIt() throws Exception { File testDir = extractResources("/mng-8385"); Verifier verifier; verifier = newVerifier(new File(testDir, "spi-extension").getAbsolutePath()); verifier.addCliArgument("install"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier = newVerifier(new File(testDir, "spi-consumer").getAbsolutePath()); verifier.addCliArgument("validate"); verifier.addCliArgument("-X"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyTextInLog("washere!"); } }
MavenITmng8385PropertyContributoSPITest
java
quarkusio__quarkus
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/MessageBundleProcessor.java
{ "start": 56335, "end": 64319 }
enum ____ // These methods are used to handle the {msg:myEnum$CONSTANT_1} and {msg:myEnum$CONSTANT_2} if (messageTemplate == null && method.parametersCount() == 1) { Type paramType = method.parameterType(0); if (paramType.kind() == org.jboss.jandex.Type.Kind.CLASS) { ClassInfo maybeEnum = index.getClassByName(paramType.name()); if (maybeEnum != null && maybeEnum.isEnum()) { StringBuilder generatedMessageTemplate = new StringBuilder("{#when ") .append(getParameterName(method, 0)) .append("}"); Set<String> enumConstants = maybeEnum.fields().stream().filter(FieldInfo::isEnumConstant) .map(FieldInfo::name).collect(Collectors.toSet()); String separator = enumConstantSeparator(enumConstants); for (String enumConstant : enumConstants) { // myEnum_CONSTANT // myEnum_$CONSTANT_1 // myEnum_$CONSTANT$NEXT String enumConstantKey = toEnumConstantKey(method.name(), separator, enumConstant); String enumConstantTemplate = messageTemplates.get(enumConstantKey); if (enumConstantTemplate == null) { throw new TemplateException( String.format("Enum constant message not found in bundle [%s] for key: %s", bundleName + (locale != null ? "_" + locale : ""), enumConstantKey)); } generatedMessageTemplate.append("{#is ") .append(enumConstant) .append("}{") .append(bundle.getName()) .append(":") .append(enumConstantKey) .append("}"); // For each constant we generate a method: // myEnum_CONSTANT(MyEnum val) // myEnum_$CONSTANT_1(MyEnum val) // myEnum_$CONSTANT$NEXT(MyEnum val) generateEnumConstantMessageMethod(cc, bundleName, locale, bundleInterface, defaultBundleInterface, enumConstantKey, keyMap, enumConstantTemplate, messageTemplateMethods); } generatedMessageTemplate.append("{/when}"); messageTemplate = generatedMessageTemplate.toString(); generatedTemplate = true; } } } if (messageTemplate == null) { throw new MessageBundleException( String.format("Message template for key [%s] is missing for default locale [%s]", key, bundle.getDefaultLocale())); } String templateId = null; String defaultLocale = locale; if (messageTemplate.contains("}")) { // Qute is needed - at least one expression/section found if (defaultBundleInterface != null) { if (defaultLocale == null) { AnnotationInstance localizedAnnotation = bundleInterface.declaredAnnotation(Names.LOCALIZED); defaultLocale = localizedAnnotation.value().asString(); } templateId = bundleName + "_" + defaultLocale + "_" + key; } else { templateId = bundleName + "_" + key; } } MessageBundleMethodBuildItem messageBundleMethod = new MessageBundleMethodBuildItem(bundleName, key, templateId, method, messageTemplate, defaultBundleInterface == null, generatedTemplate); messageTemplateMethods .produce(messageBundleMethod); String effectiveMessageTemplate = messageTemplate; String effectiveTemplateId = templateId; String effectiveLocale = defaultLocale; mc.body(bc -> { if (!messageBundleMethod.isValidatable()) { // No expression/tag - no need to use qute bc.return_(Const.of(effectiveMessageTemplate)); } else { // Obtain the template, e.g. msg_hello_name LocalVar template = bc.localVar("template", bc.invokeStatic( io.quarkus.qute.deployment.Descriptors.BUNDLES_GET_TEMPLATE, Const.of(effectiveTemplateId))); // Create a template instance LocalVar templateInstance = bc.localVar("templateInstance", bc .invokeInterface(io.quarkus.qute.deployment.Descriptors.TEMPLATE_INSTANCE, template)); if (effectiveLocale != null) { bc.invokeInterface( MethodDesc.of(TemplateInstance.class, "setLocale", TemplateInstance.class, String.class), templateInstance, Const.of(effectiveLocale)); } List<Type> paramTypes = method.parameterTypes(); if (!paramTypes.isEmpty()) { // Set data int i = 0; Iterator<Type> it = paramTypes.iterator(); while (it.hasNext()) { String name = getParameterName(method, i); bc.invokeInterface(io.quarkus.qute.deployment.Descriptors.TEMPLATE_INSTANCE_DATA, templateInstance, Const.of(name), params.get(i)); i++; it.next(); } } // Render the template // At this point it's already validated that the method returns String bc.return_(bc.invokeInterface( io.quarkus.qute.deployment.Descriptors.TEMPLATE_INSTANCE_RENDER, templateInstance)); } }); }); } implementResolve(defaultBundleImpl, cc, keyMap, resolveMethodPrefix, generatedClassName); }); return generatedClassName; } private String enumConstantSeparator(Set<String> enumConstants) { for (String constant : enumConstants) { if (constant.contains("_$")) { throw new MessageBundleException("A constant of a localized
constant
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/AggregationInitializationException.java
{ "start": 714, "end": 1010 }
class ____ extends ElasticsearchException { public AggregationInitializationException(String msg, Throwable cause) { super(msg, cause); } public AggregationInitializationException(StreamInput in) throws IOException { super(in); } }
AggregationInitializationException
java
elastic__elasticsearch
x-pack/plugin/esql/qa/server/src/main/java/org/elasticsearch/xpack/esql/qa/rest/EsqlSpecTestCase.java
{ "start": 4591, "end": 5957 }
class ____ extends ESRestTestCase { @Rule(order = Integer.MIN_VALUE) public ProfileLogger profileLogger = new ProfileLogger(); private static final Logger LOGGER = LogManager.getLogger(EsqlSpecTestCase.class); private final String fileName; private final String groupName; private final String testName; private final Integer lineNumber; protected final CsvTestCase testCase; protected final String instructions; protected final Mode mode; protected static Boolean supportsTook; @ParametersFactory(argumentFormatting = "csv-spec:%2$s.%3$s") public static List<Object[]> readScriptSpec() throws Exception { List<URL> urls = classpathResources("/*.csv-spec"); assertTrue("Not enough specs found " + urls, urls.size() > 0); return SpecReader.readScriptSpec(urls, specParser()); } protected EsqlSpecTestCase( String fileName, String groupName, String testName, Integer lineNumber, CsvTestCase testCase, String instructions ) { this.fileName = fileName; this.groupName = groupName; this.testName = testName; this.lineNumber = lineNumber; this.testCase = testCase; this.instructions = instructions; this.mode = randomFrom(Mode.values()); } private static
EsqlSpecTestCase
java
apache__flink
flink-python/src/main/java/org/apache/flink/python/metric/embedded/MetricDistribution.java
{ "start": 1011, "end": 1232 }
class ____ implements Gauge<Long> { private long value; public void update(long value) { this.value = value; } @Override public Long getValue() { return value; } }
MetricDistribution
java
spring-projects__spring-boot
module/spring-boot-zipkin/src/test/java/org/springframework/boot/zipkin/autoconfigure/ZipkinAutoConfigurationTests.java
{ "start": 4880, "end": 5068 }
class ____ { @Bean HttpEndpointSupplier.Factory httpEndpointSupplier() { return new CustomHttpEndpointSupplierFactory(); } } static
CustomHttpEndpointSupplierFactoryConfiguration
java
apache__camel
components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/OriginalSimpleTest.java
{ "start": 93460, "end": 93593 }
class ____ { public Object[] getMyArray() { return new Object[] { "Hallo", "World", "!" }; } } }
MyClass
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/type/AbstractMethodMetadataTests.java
{ "start": 7614, "end": 7717 }
class ____ { @Tag public static String test() { return ""; } } public static
WithStaticMethod
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java
{ "start": 3069, "end": 3332 }
class ____ extends AsyncScalarFunction { * public void eval(CompletableFuture<String> future, Object o) { * return future.complete(o.toString()); * } * } * * // a function that accepts any data type as argument and computes a STRING *
StringifyFunction
java
elastic__elasticsearch
libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/entitlements/Entitlement.java
{ "start": 612, "end": 756 }
interface ____ ensure that only {@link Entitlement} are * part of a {@link Policy}. All entitlement classes should implement * this. */ public
to
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ModifiedButNotUsedTest.java
{ "start": 6113, "end": 6745 }
class ____ { void test() { List<Integer> foo = new ArrayList<>(); foo.add(1); foo.get(0); foo = new ArrayList<>(); foo.add(1); foo.get(0); } } """) .doTest(); } @Test public void proto() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;
Test
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/TriggeredWatchStore.java
{ "start": 2458, "end": 9534 }
class ____ { private static final Logger logger = LogManager.getLogger(TriggeredWatchStore.class); private final int scrollSize; private final Client client; private final TimeValue scrollTimeout; private final TriggeredWatch.Parser triggeredWatchParser; private final TimeValue defaultBulkTimeout; private final TimeValue defaultSearchTimeout; private final BulkProcessor2 bulkProcessor; public TriggeredWatchStore(Settings settings, Client client, TriggeredWatch.Parser triggeredWatchParser, BulkProcessor2 bulkProcessor) { this.scrollSize = settings.getAsInt("xpack.watcher.execution.scroll.size", 1000); this.client = ClientHelper.clientWithOrigin(client, WATCHER_ORIGIN); this.scrollTimeout = settings.getAsTime("xpack.watcher.execution.scroll.timeout", TimeValue.timeValueMinutes(5)); this.defaultBulkTimeout = settings.getAsTime("xpack.watcher.internal.ops.bulk.default_timeout", TimeValue.timeValueSeconds(120)); this.defaultSearchTimeout = settings.getAsTime("xpack.watcher.internal.ops.search.default_timeout", TimeValue.timeValueSeconds(30)); this.triggeredWatchParser = triggeredWatchParser; this.bulkProcessor = bulkProcessor; } public void putAll(final List<TriggeredWatch> triggeredWatches, final ActionListener<BulkResponse> listener) throws IOException { if (triggeredWatches.isEmpty()) { listener.onResponse(new BulkResponse(new BulkItemResponse[] {}, 0)); return; } client.bulk(createBulkRequest(triggeredWatches), listener); } public BulkResponse putAll(final List<TriggeredWatch> triggeredWatches) throws IOException { PlainActionFuture<BulkResponse> future = new PlainActionFuture<>(); putAll(triggeredWatches, future); return future.actionGet(defaultBulkTimeout); } /** * Create a bulk request from the triggered watches with a specified document type * @param triggeredWatches The list of triggered watches * @return The bulk request for the triggered watches * @throws IOException If a triggered watch could not be parsed to JSON, this exception is thrown */ private static BulkRequest createBulkRequest(final List<TriggeredWatch> triggeredWatches) throws IOException { BulkRequest request = new BulkRequest(); for (TriggeredWatch triggeredWatch : triggeredWatches) { IndexRequest indexRequest = new IndexRequest(TriggeredWatchStoreField.INDEX_NAME).id(triggeredWatch.id().value()); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { triggeredWatch.toXContent(builder, ToXContent.EMPTY_PARAMS); indexRequest.source(builder); } indexRequest.opType(IndexRequest.OpType.CREATE); request.add(indexRequest); } return request; } /** * Delete a triggered watch entry. * Note that this happens asynchronously, as these kind of requests are batched together to reduce the amount of concurrent requests. * * @param wid The ID os the triggered watch id */ public void delete(Wid wid) { DeleteRequest request = new DeleteRequest(TriggeredWatchStoreField.INDEX_NAME, wid.value()); bulkProcessor.add(request); } /** * Checks if any of the loaded watches has been put into the triggered watches index for immediate execution * * Note: This is executing a blocking call over the network, thus a potential source of problems * * @param watches The list of watches that will be loaded here * @param clusterState The current cluster state * @return A list of triggered watches that have been started to execute somewhere else but not finished */ public Collection<TriggeredWatch> findTriggeredWatches(Collection<Watch> watches, ClusterState clusterState) { if (watches.isEmpty()) { return Collections.emptyList(); } // non existing index, return immediately IndexMetadata indexMetadata = WatchStoreUtils.getConcreteIndex(TriggeredWatchStoreField.INDEX_NAME, clusterState.metadata()); if (indexMetadata == null) { return Collections.emptyList(); } try { RefreshRequest request = new RefreshRequest(TriggeredWatchStoreField.INDEX_NAME); client.admin().indices().refresh(request).actionGet(TimeValue.timeValueSeconds(5)); } catch (IndexNotFoundException e) { return Collections.emptyList(); } Set<String> ids = watches.stream().map(Watch::id).collect(Collectors.toSet()); Collection<TriggeredWatch> triggeredWatches = new ArrayList<>(ids.size()); SearchRequest searchRequest = new SearchRequest(TriggeredWatchStoreField.INDEX_NAME).scroll(scrollTimeout) .preference(Preference.LOCAL.toString()) .source(new SearchSourceBuilder().size(scrollSize).sort(SortBuilders.fieldSort("_doc")).version(true)); SearchResponse response = null; try { response = client.search(searchRequest).actionGet(defaultSearchTimeout); logger.debug("trying to find triggered watches for ids {}: found [{}] docs", ids, response.getHits().getTotalHits().value()); while (response.getHits().getHits().length != 0) { for (SearchHit hit : response.getHits()) { Wid wid = new Wid(hit.getId()); if (ids.contains(wid.watchId())) { TriggeredWatch triggeredWatch = triggeredWatchParser.parse(hit.getId(), hit.getVersion(), hit.getSourceRef()); triggeredWatches.add(triggeredWatch); } } SearchScrollRequest request = new SearchScrollRequest(response.getScrollId()); request.scroll(scrollTimeout); response.decRef(); response = client.searchScroll(request).actionGet(defaultSearchTimeout); } } finally { if (response != null) { final String scrollId = response.getScrollId(); response.decRef(); ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(scrollId); client.clearScroll(clearScrollRequest).actionGet(scrollTimeout); } } return triggeredWatches; } @NotMultiProjectCapable(description = "Watcher is not available in serverless") public static boolean validate(ClusterState state) { IndexMetadata indexMetadata = WatchStoreUtils.getConcreteIndex(TriggeredWatchStoreField.INDEX_NAME, state.metadata()); return indexMetadata == null || (indexMetadata.getState() == IndexMetadata.State.OPEN && state.routingTable(ProjectId.DEFAULT).index(indexMetadata.getIndex()).allPrimaryShardsActive()); } }
TriggeredWatchStore
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1799/Issue1799Mapper.java
{ "start": 308, "end": 446 }
interface ____ { Issue1799Mapper INSTANCE = Mappers.getMapper( Issue1799Mapper.class ); Target map(Source source); }
Issue1799Mapper
java
google__auto
common/src/test/java/com/google/auto/common/OverridesTest.java
{ "start": 15693, "end": 18960 }
class ____<T extends Comparable<T>> extends Converter<String, Range<T>> { @Override protected String doBackward(Range<T> b) { return ""; } } @Test public void methodParams_RecursiveBound() { TypeElement stringToRangeConverter = getTypeElement(StringToRangeConverter.class); TypeElement range = getTypeElement(Range.class); ExecutableElement valueConverter = getMethod(stringToRangeConverter, "doBackward", TypeKind.DECLARED); List<TypeMirror> params = explicitOverrides.erasedParameterTypes(valueConverter, stringToRangeConverter); List<TypeMirror> expectedParams = ImmutableList.<TypeMirror>of(typeUtils.erasure(range.asType())); assertTypeListsEqual(params, expectedParams); } @Test public void methodFromSuperclasses() { TypeElement xAbstractCollection = getTypeElement(XAbstractCollection.class); TypeElement xAbstractList = getTypeElement(XAbstractList.class); TypeElement xAbstractStringList = getTypeElement(XAbstractStringList.class); TypeElement xStringList = getTypeElement(XStringList.class); ExecutableElement add = getMethod(xAbstractCollection, "add", TypeKind.TYPEVAR); ExecutableElement addInAbstractStringList = explicitOverrides.methodFromSuperclasses(xAbstractStringList, add); assertThat(addInAbstractStringList).isNull(); ExecutableElement addInStringList = explicitOverrides.methodFromSuperclasses(xStringList, add); assertThat(requireNonNull(addInStringList).getEnclosingElement()).isEqualTo(xAbstractList); } @Test public void methodFromSuperinterfaces() { TypeElement xCollection = getTypeElement(XCollection.class); TypeElement xAbstractList = getTypeElement(XAbstractList.class); TypeElement xAbstractStringList = getTypeElement(XAbstractStringList.class); TypeElement xNumberList = getTypeElement(XNumberList.class); TypeElement xList = getTypeElement(XList.class); ExecutableElement add = getMethod(xCollection, "add", TypeKind.TYPEVAR); ExecutableElement addInAbstractStringList = explicitOverrides.methodFromSuperinterfaces(xAbstractStringList, add); assertThat(requireNonNull(addInAbstractStringList).getEnclosingElement()) .isEqualTo(xCollection); ExecutableElement addInNumberList = explicitOverrides.methodFromSuperinterfaces(xNumberList, add); assertThat(requireNonNull(addInNumberList).getEnclosingElement()).isEqualTo(xAbstractList); ExecutableElement addInList = explicitOverrides.methodFromSuperinterfaces(xList, add); assertThat(requireNonNull(addInList).getEnclosingElement()).isEqualTo(xCollection); } private void assertTypeListsEqual(@Nullable List<TypeMirror> actual, List<TypeMirror> expected) { assertThat(actual) .comparingElementsUsing(Correspondence.from(typeUtils::isSameType, "is same type as")) .containsExactlyElementsIn(expected) .inOrder(); } // TODO(emcmanus): replace this with something from compile-testing when that's available. /** * An equivalent to {@link CompilationRule} that uses ecj (the Eclipse compiler) instead of javac. * If the parameterized test is not selecting ecj then this rule has no effect. */ public
StringToRangeConverter
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/UrlDecodeEvaluator.java
{ "start": 4539, "end": 5111 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory val; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory val) { this.source = source; this.val = val; } @Override public UrlDecodeEvaluator get(DriverContext context) { return new UrlDecodeEvaluator(source, val.get(context), context); } @Override public String toString() { return "UrlDecodeEvaluator[" + "val=" + val + "]"; } } }
Factory
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2TokenExchangeGrantTests.java
{ "start": 5712, "end": 21351 }
class ____ { private static final String DEFAULT_TOKEN_ENDPOINT_URI = "/oauth2/token"; private static final String RESOURCE = "https://mydomain.com/resource"; private static final String AUDIENCE = "audience"; private static final String SUBJECT_TOKEN = "EfYu_0jEL"; private static final String ACTOR_TOKEN = "JlNE_xR1f"; private static final String ACCESS_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:access_token"; private static final String JWT_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:jwt"; private static NimbusJwtEncoder dPoPProofJwtEncoder; public final SpringTestContext spring = new SpringTestContext(this); private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); @Autowired private MockMvc mvc; @Autowired private JdbcOperations jdbcOperations; @Autowired private RegisteredClientRepository registeredClientRepository; @Autowired private OAuth2AuthorizationService authorizationService; @BeforeAll public static void init() { JWKSet jwkSet = new JWKSet(TestJwks.DEFAULT_RSA_JWK); AuthorizationServerConfiguration.JWK_SOURCE = (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); JWKSet clientJwkSet = new JWKSet(TestJwks.DEFAULT_EC_JWK); JWKSource<SecurityContext> clientJwkSource = (jwkSelector, securityContext) -> jwkSelector.select(clientJwkSet); dPoPProofJwtEncoder = new NimbusJwtEncoder(clientJwkSource); // @formatter:off AuthorizationServerConfiguration.DB = new EmbeddedDatabaseBuilder() .generateUniqueName(true) .setType(EmbeddedDatabaseType.HSQL) .setScriptEncoding("UTF-8") .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql") .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql") .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql") .build(); // @formatter:on } @AfterEach public void tearDown() { this.jdbcOperations.update("truncate table oauth2_authorization"); this.jdbcOperations.update("truncate table oauth2_authorization_consent"); this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll public static void destroy() { AuthorizationServerConfiguration.DB.shutdown(); } @Test public void requestWhenAccessTokenRequestNotAuthenticatedThenUnauthorized() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE) .build(); this.registeredClientRepository.save(registeredClient); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()); parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); // @formatter:off this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI).params(parameters)) .andExpect(status().isUnauthorized()); // @formatter:on } @Test public void requestWhenAccessTokenRequestValidAndNoActorTokenThenReturnAccessTokenResponseForImpersonation() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE) .build(); this.registeredClientRepository.save(registeredClient); UsernamePasswordAuthenticationToken userPrincipal = createUserPrincipal("user"); OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient) .attribute(Principal.class.getName(), userPrincipal) .build(); this.authorizationService.save(subjectAuthorization); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()); parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); parameters.set(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, JWT_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN, subjectAuthorization.getAccessToken().getToken().getTokenValue()); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, JWT_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.RESOURCE, RESOURCE); parameters.set(OAuth2ParameterNames.AUDIENCE, AUDIENCE); parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); // @formatter:off MvcResult mvcResult = this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(parameters) .headers(withClientAuth(registeredClient))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").doesNotExist()) .andExpect(jsonPath("$.expires_in").isNumber()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.issued_token_type").isNotEmpty()) .andReturn(); // @formatter:on MockHttpServletResponse servletResponse = mvcResult.getResponse(); MockClientHttpResponse httpResponse = new MockClientHttpResponse(servletResponse.getContentAsByteArray(), HttpStatus.OK); OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseHttpMessageConverter .read(OAuth2AccessTokenResponse.class, httpResponse); String accessToken = accessTokenResponse.getAccessToken().getTokenValue(); OAuth2Authorization authorization = this.authorizationService.findByToken(accessToken, OAuth2TokenType.ACCESS_TOKEN); assertThat(authorization).isNotNull(); assertThat(authorization.getAccessToken()).isNotNull(); assertThat(authorization.getAccessToken().getClaims()).isNotNull(); // We do not populate claims (e.g. `aud`) based on the resource or audience // parameters assertThat(authorization.getAccessToken().getClaims().get(OAuth2TokenClaimNames.AUD)) .isEqualTo(List.of(registeredClient.getClientId())); assertThat(authorization.getRefreshToken()).isNull(); assertThat(authorization.<Authentication>getAttribute(Principal.class.getName())).isEqualTo(userPrincipal); } @Test public void requestWhenAccessTokenRequestValidAndActorTokenThenReturnAccessTokenResponseForDelegation() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE) .build(); this.registeredClientRepository.save(registeredClient); UsernamePasswordAuthenticationToken userPrincipal = createUserPrincipal("user"); UsernamePasswordAuthenticationToken adminPrincipal = createUserPrincipal("admin"); Map<String, Object> actorTokenClaims = new HashMap<>(); actorTokenClaims.put(OAuth2TokenClaimNames.ISS, "issuer2"); actorTokenClaims.put(OAuth2TokenClaimNames.SUB, "admin"); Map<String, Object> subjectTokenClaims = new HashMap<>(); subjectTokenClaims.put(OAuth2TokenClaimNames.ISS, "issuer1"); subjectTokenClaims.put(OAuth2TokenClaimNames.SUB, "user"); subjectTokenClaims.put("may_act", actorTokenClaims); OAuth2AccessToken subjectToken = createAccessToken(SUBJECT_TOKEN); OAuth2AccessToken actorToken = createAccessToken(ACTOR_TOKEN); // @formatter:off OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient, subjectToken, subjectTokenClaims) .id(UUID.randomUUID().toString()) .attribute(Principal.class.getName(), userPrincipal) .build(); OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient, actorToken, actorTokenClaims) .id(UUID.randomUUID().toString()) .attribute(Principal.class.getName(), adminPrincipal) .build(); // @formatter:on this.authorizationService.save(subjectAuthorization); this.authorizationService.save(actorAuthorization); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()); parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); parameters.set(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, JWT_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN, SUBJECT_TOKEN); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, JWT_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.ACTOR_TOKEN, ACTOR_TOKEN); parameters.set(OAuth2ParameterNames.ACTOR_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); // @formatter:off MvcResult mvcResult = this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(parameters) .headers(withClientAuth(registeredClient))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.refresh_token").doesNotExist()) .andExpect(jsonPath("$.expires_in").isNumber()) .andExpect(jsonPath("$.scope").isNotEmpty()) .andExpect(jsonPath("$.token_type").isNotEmpty()) .andExpect(jsonPath("$.issued_token_type").isNotEmpty()) .andReturn(); // @formatter:on MockHttpServletResponse servletResponse = mvcResult.getResponse(); MockClientHttpResponse httpResponse = new MockClientHttpResponse(servletResponse.getContentAsByteArray(), HttpStatus.OK); OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseHttpMessageConverter .read(OAuth2AccessTokenResponse.class, httpResponse); String accessToken = accessTokenResponse.getAccessToken().getTokenValue(); OAuth2Authorization authorization = this.authorizationService.findByToken(accessToken, OAuth2TokenType.ACCESS_TOKEN); assertThat(authorization).isNotNull(); assertThat(authorization.getAccessToken()).isNotNull(); assertThat(authorization.getAccessToken().getClaims()).isNotNull(); assertThat(authorization.getAccessToken().getClaims().get("act")).isNotNull(); assertThat(authorization.getRefreshToken()).isNull(); assertThat(authorization.<Authentication>getAttribute(Principal.class.getName())) .isInstanceOf(OAuth2TokenExchangeCompositeAuthenticationToken.class); } @Test public void requestWhenAccessTokenRequestWithDPoPProofThenReturnDPoPBoundAccessToken() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE) .build(); this.registeredClientRepository.save(registeredClient); UsernamePasswordAuthenticationToken userPrincipal = createUserPrincipal("user"); UsernamePasswordAuthenticationToken adminPrincipal = createUserPrincipal("admin"); Map<String, Object> actorTokenClaims = new HashMap<>(); actorTokenClaims.put(OAuth2TokenClaimNames.ISS, "issuer2"); actorTokenClaims.put(OAuth2TokenClaimNames.SUB, "admin"); Map<String, Object> subjectTokenClaims = new HashMap<>(); subjectTokenClaims.put(OAuth2TokenClaimNames.ISS, "issuer1"); subjectTokenClaims.put(OAuth2TokenClaimNames.SUB, "user"); subjectTokenClaims.put("may_act", actorTokenClaims); OAuth2AccessToken subjectToken = createAccessToken(SUBJECT_TOKEN); OAuth2AccessToken actorToken = createAccessToken(ACTOR_TOKEN); // @formatter:off OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient, subjectToken, subjectTokenClaims) .id(UUID.randomUUID().toString()) .attribute(Principal.class.getName(), userPrincipal) .build(); OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient, actorToken, actorTokenClaims) .id(UUID.randomUUID().toString()) .attribute(Principal.class.getName(), adminPrincipal) .build(); // @formatter:on this.authorizationService.save(subjectAuthorization); this.authorizationService.save(actorAuthorization); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()); parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); parameters.set(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, JWT_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN, SUBJECT_TOKEN); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, JWT_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.ACTOR_TOKEN, ACTOR_TOKEN); parameters.set(OAuth2ParameterNames.ACTOR_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE); parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); String tokenEndpointUri = "http://localhost" + DEFAULT_TOKEN_ENDPOINT_URI; String dPoPProof = generateDPoPProof(tokenEndpointUri); // @formatter:off this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI) .params(parameters) .headers(withClientAuth(registeredClient)) .header(OAuth2AccessToken.TokenType.DPOP.getValue(), dPoPProof)) .andExpect(status().isOk()) .andExpect(jsonPath("$.token_type").value(OAuth2AccessToken.TokenType.DPOP.getValue())); // @formatter:on } private static OAuth2AccessToken createAccessToken(String tokenValue) { Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(300); return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, tokenValue, issuedAt, expiresAt); } private static UsernamePasswordAuthenticationToken createUserPrincipal(String username) { User user = new User(username, "", AuthorityUtils.createAuthorityList("ROLE_USER")); return UsernamePasswordAuthenticationToken.authenticated(user, null, user.getAuthorities()); } private static HttpHeaders withClientAuth(RegisteredClient registeredClient) { HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth(registeredClient.getClientId(), registeredClient.getClientSecret()); return headers; } private static Consumer<Map<String, Object>> withInvalidated() { return (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true); } private static Function<OAuth2Authorization.Token<? extends OAuth2Token>, Boolean> isInvalidated() { return (token) -> token.getMetadata(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME); } private static String generateDPoPProof(String tokenEndpointUri) { // @formatter:off Map<String, Object> publicJwk = TestJwks.DEFAULT_EC_JWK .toPublicJWK() .toJSONObject(); JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.ES256) .type("dpop+jwt") .jwk(publicJwk) .build(); JwtClaimsSet claims = JwtClaimsSet.builder() .issuedAt(Instant.now()) .claim("htm", "POST") .claim("htu", tokenEndpointUri) .id(UUID.randomUUID().toString()) .build(); // @formatter:on Jwt jwt = dPoPProofJwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)); return jwt.getTokenValue(); } @EnableWebSecurity @Import(OAuth2AuthorizationServerConfiguration.class) static
OAuth2TokenExchangeGrantTests
java
google__guava
android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
{ "start": 24250, "end": 31180 }
class ____ extends Fourth<String, Integer> {} public void testAssignableClassToClass() { @SuppressWarnings("rawtypes") // To test TypeToken<List> TypeToken<List> tokL = new TypeToken<List>() {}; assertTrue(tokL.isSupertypeOf(List.class)); assertTrue(tokL.isSupertypeOf(ArrayList.class)); assertFalse(tokL.isSupertypeOf(List[].class)); TypeToken<Number> tokN = new TypeToken<Number>() {}; assertTrue(tokN.isSupertypeOf(Number.class)); assertTrue(tokN.isSupertypeOf(Integer.class)); } public <T> void testAssignableParameterizedTypeToObject() { assertTrue( TypeToken.of(Object.class).isSupertypeOf(TypeToken.of(new TypeCapture<T>() {}.capture()))); assertFalse( TypeToken.of(int.class).isSupertypeOf(TypeToken.of(new TypeCapture<T>() {}.capture()))); } public <T, T1 extends T> void testAssignableGenericArrayToGenericArray() { assertTrue(new TypeToken<T[]>() {}.isSupertypeOf(new TypeToken<T[]>() {})); assertTrue(new TypeToken<T[]>() {}.isSupertypeOf(new TypeToken<T1[]>() {})); assertFalse(new TypeToken<T[]>() {}.isSupertypeOf(new TypeToken<T[][]>() {})); } public <T, T1 extends T> void testAssignableGenericArrayToClass() { assertTrue(TypeToken.of(Object[].class.getSuperclass()).isSupertypeOf(new TypeToken<T[]>() {})); for (Class<?> interfaceType : Object[].class.getInterfaces()) { assertTrue(TypeToken.of(interfaceType).isSupertypeOf(new TypeToken<T[]>() {})); } assertTrue(TypeToken.of(Object.class).isSupertypeOf(new TypeToken<T[]>() {})); assertFalse(TypeToken.of(String.class).isSupertypeOf(new TypeToken<T[]>() {})); } public void testAssignableWildcardBoundedByArrayToArrayClass() { Type wildcardType = Types.subtypeOf(Object[].class); assertTrue(TypeToken.of(Object[].class).isSupertypeOf(wildcardType)); assertTrue(TypeToken.of(Object.class).isSupertypeOf(wildcardType)); assertFalse(TypeToken.of(wildcardType).isSupertypeOf(wildcardType)); assertFalse(TypeToken.of(int[].class).isSupertypeOf(wildcardType)); } public void testAssignableWildcardTypeParameterToClassTypeParameter() { TypeToken<?> wildcardType = new TypeToken<Iterable<? extends Object[]>>() {}; assertFalse(new TypeToken<Iterable<Object[]>>() {}.isSupertypeOf(wildcardType)); assertFalse(new TypeToken<Iterable<Object>>() {}.isSupertypeOf(wildcardType)); assertTrue(wildcardType.isSupertypeOf(wildcardType)); assertFalse(new TypeToken<Iterable<int[]>>() {}.isSupertypeOf(wildcardType)); } public void testAssignableArrayClassToBoundedWildcard() { TypeToken<?> subtypeOfArray = TypeToken.of(Types.subtypeOf(Object[].class)); TypeToken<?> supertypeOfArray = TypeToken.of(Types.supertypeOf(Object[].class)); assertFalse(subtypeOfArray.isSupertypeOf(Object[].class)); assertFalse(subtypeOfArray.isSupertypeOf(Object[][].class)); assertFalse(subtypeOfArray.isSupertypeOf(String[].class)); assertTrue(supertypeOfArray.isSupertypeOf(Object[].class)); assertFalse(supertypeOfArray.isSupertypeOf(Object.class)); assertTrue(supertypeOfArray.isSupertypeOf(Object[][].class)); assertTrue(supertypeOfArray.isSupertypeOf(String[].class)); } public void testAssignableClassTypeParameterToWildcardTypeParameter() { TypeToken<?> subtypeOfArray = new TypeToken<Iterable<? extends Object[]>>() {}; TypeToken<?> supertypeOfArray = new TypeToken<Iterable<? super Object[]>>() {}; assertTrue(subtypeOfArray.isSupertypeOf(new TypeToken<Iterable<Object[]>>() {})); assertTrue(subtypeOfArray.isSupertypeOf(new TypeToken<Iterable<Object[][]>>() {})); assertTrue(subtypeOfArray.isSupertypeOf(new TypeToken<Iterable<String[]>>() {})); assertTrue(supertypeOfArray.isSupertypeOf(new TypeToken<Iterable<Object[]>>() {})); assertTrue(supertypeOfArray.isSupertypeOf(new TypeToken<Iterable<Object>>() {})); assertFalse(supertypeOfArray.isSupertypeOf(new TypeToken<Iterable<Object[][]>>() {})); assertFalse(supertypeOfArray.isSupertypeOf(new TypeToken<Iterable<String[]>>() {})); } public void testAssignableNonParameterizedClassToWildcard() { TypeToken<?> supertypeOfString = TypeToken.of(Types.supertypeOf(String.class)); assertFalse(supertypeOfString.isSupertypeOf(supertypeOfString)); assertFalse(supertypeOfString.isSupertypeOf(Object.class)); assertFalse(supertypeOfString.isSupertypeOf(CharSequence.class)); assertTrue(supertypeOfString.isSupertypeOf(String.class)); assertTrue(supertypeOfString.isSupertypeOf(Types.subtypeOf(String.class))); } public void testAssignableWildcardBoundedByIntArrayToArrayClass() { Type wildcardType = Types.subtypeOf(int[].class); assertTrue(TypeToken.of(int[].class).isSupertypeOf(wildcardType)); assertTrue(TypeToken.of(Object.class).isSupertypeOf(wildcardType)); assertFalse(TypeToken.of(wildcardType).isSupertypeOf(wildcardType)); assertFalse(TypeToken.of(Object[].class).isSupertypeOf(wildcardType)); } public void testAssignableWildcardTypeParameterBoundedByIntArrayToArrayClassTypeParameter() { TypeToken<?> wildcardType = new TypeToken<Iterable<? extends int[]>>() {}; assertFalse(new TypeToken<Iterable<int[]>>() {}.isSupertypeOf(wildcardType)); assertFalse(new TypeToken<Iterable<Object>>() {}.isSupertypeOf(wildcardType)); assertTrue(wildcardType.isSupertypeOf(wildcardType)); assertFalse(new TypeToken<Iterable<Object[]>>() {}.isSupertypeOf(wildcardType)); } public void testAssignableWildcardToWildcard() { TypeToken<?> subtypeOfArray = TypeToken.of(Types.subtypeOf(Object[].class)); TypeToken<?> supertypeOfArray = TypeToken.of(Types.supertypeOf(Object[].class)); assertTrue(supertypeOfArray.isSupertypeOf(subtypeOfArray)); assertFalse(supertypeOfArray.isSupertypeOf(supertypeOfArray)); assertFalse(subtypeOfArray.isSupertypeOf(subtypeOfArray)); assertFalse(subtypeOfArray.isSupertypeOf(supertypeOfArray)); } public void testAssignableWildcardTypeParameterToWildcardTypeParameter() { TypeToken<?> subtypeOfArray = new TypeToken<Iterable<? extends Object[]>>() {}; TypeToken<?> supertypeOfArray = new TypeToken<Iterable<? super Object[]>>() {}; assertFalse(supertypeOfArray.isSupertypeOf(subtypeOfArray)); assertTrue(supertypeOfArray.isSupertypeOf(supertypeOfArray)); assertTrue(subtypeOfArray.isSupertypeOf(subtypeOfArray)); assertFalse(subtypeOfArray.isSupertypeOf(supertypeOfArray)); } public <T> void testAssignableGenericArrayToArrayClass() { assertTrue(TypeToken.of(Object[].class).isSupertypeOf(new TypeToken<T[]>() {})); assertTrue(TypeToken.of(Object[].class).isSupertypeOf(new TypeToken<T[][]>() {})); assertTrue(TypeToken.of(Object[][].class).isSupertypeOf(new TypeToken<T[][]>() {})); } public void testAssignableParameterizedTypeToClass() { @SuppressWarnings("rawtypes") // Trying to test raw
ConcreteStringInteger
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/async/QlStatusResponse.java
{ "start": 1291, "end": 7139 }
interface ____ { String id(); boolean isRunning(); boolean isPartial(); } public QlStatusResponse( String id, boolean isRunning, boolean isPartial, Long startTimeMillis, long expirationTimeMillis, RestStatus completionStatus ) { this.id = id; this.isRunning = isRunning; this.isPartial = isPartial; this.startTimeMillis = startTimeMillis; this.expirationTimeMillis = expirationTimeMillis; this.completionStatus = completionStatus; } /** * Get status from the stored Ql search response * @param storedResponse - a response from a stored search * @param expirationTimeMillis – expiration time in milliseconds * @param id – encoded async search id * @return a status response */ public static <S extends Writeable & AsyncStatus> QlStatusResponse getStatusFromStoredSearch( StoredAsyncResponse<S> storedResponse, long expirationTimeMillis, String id ) { S searchResponse = storedResponse.getResponse(); if (searchResponse != null) { assert searchResponse.isRunning() == false : "Stored Ql search response must have a completed status!"; return new QlStatusResponse( searchResponse.id(), false, searchResponse.isPartial(), null, // we don't store in the index the start time for completed response expirationTimeMillis, RestStatus.OK ); } else { Exception exc = storedResponse.getException(); assert exc != null : "Stored Ql response must either have a search response or an exception!"; return new QlStatusResponse( id, false, false, null, // we don't store in the index the start time for completed response expirationTimeMillis, ExceptionsHelper.status(exc) ); } } public QlStatusResponse(StreamInput in) throws IOException { this.id = in.readString(); this.isRunning = in.readBoolean(); this.isPartial = in.readBoolean(); this.startTimeMillis = in.readOptionalLong(); this.expirationTimeMillis = in.readLong(); this.completionStatus = (this.isRunning == false) ? RestStatus.readFrom(in) : null; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(id); out.writeBoolean(isRunning); out.writeBoolean(isPartial); out.writeOptionalLong(startTimeMillis); out.writeLong(expirationTimeMillis); if (isRunning == false) { RestStatus.writeTo(out, completionStatus); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); { builder.field("id", id); builder.field("is_running", isRunning); builder.field("is_partial", isPartial); if (startTimeMillis != null) { // start time is available only for a running eql search builder.timestampFieldsFromUnixEpochMillis("start_time_in_millis", "start_time", startTimeMillis); } builder.timestampFieldsFromUnixEpochMillis("expiration_time_in_millis", "expiration_time", expirationTimeMillis); if (isRunning == false) { // completion status is available only for a completed eql search builder.field("completion_status", completionStatus.getStatus()); } } builder.endObject(); return builder; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; QlStatusResponse other = (QlStatusResponse) obj; return id.equals(other.id) && isRunning == other.isRunning && isPartial == other.isPartial && Objects.equals(startTimeMillis, other.startTimeMillis) && expirationTimeMillis == other.expirationTimeMillis && Objects.equals(completionStatus, other.completionStatus); } @Override public int hashCode() { return Objects.hash(id, isRunning, isPartial, startTimeMillis, expirationTimeMillis, completionStatus); } /** * Returns the id of the eql search status request. */ public String getId() { return id; } /** * Returns {@code true} if the eql search is still running in the cluster, * or {@code false} if the search has been completed. */ public boolean isRunning() { return isRunning; } /** * Returns {@code true} if the eql search results are partial. * This could be either because eql search hasn't finished yet, * or if it finished and some shards have failed or timed out. */ public boolean isPartial() { return isPartial; } /** * Returns a timestamp when the eql search task started, in milliseconds since epoch. * For a completed eql search returns {@code null}, as we don't store start time for completed searches. */ public Long getStartTime() { return startTimeMillis; } /** * Returns a timestamp when the eql search will be expired, in milliseconds since epoch. */ @Override public long getExpirationTime() { return expirationTimeMillis; } /** * For a completed eql search returns the completion status. * For a still running eql search returns {@code null}. */ public RestStatus getCompletionStatus() { return completionStatus; } }
AsyncStatus
java
quarkusio__quarkus
integration-tests/hibernate-orm-graphql-panache/src/main/java/io/quarkus/it/hibertnate/orm/graphql/panache/BookRepository.java
{ "start": 195, "end": 255 }
class ____ implements PanacheRepository<Book> { }
BookRepository
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/AggregationBuilders.java
{ "start": 5484, "end": 13971 }
class ____ { private AggregationBuilders() {} /** * Create a new {@link ValueCount} aggregation with the given name. */ public static ValueCountAggregationBuilder count(String name) { return new ValueCountAggregationBuilder(name); } /** * Create a new {@link Avg} aggregation with the given name. */ public static AvgAggregationBuilder avg(String name) { return new AvgAggregationBuilder(name); } /** * Create a new {@link Max} aggregation with the given name. */ public static MaxAggregationBuilder max(String name) { return new MaxAggregationBuilder(name); } /** * Create a new {@link Min} aggregation with the given name. */ public static MinAggregationBuilder min(String name) { return new MinAggregationBuilder(name); } /** * Create a new {@link Sum} aggregation with the given name. */ public static SumAggregationBuilder sum(String name) { return new SumAggregationBuilder(name); } /** * Create a new {@link Stats} aggregation with the given name. */ public static StatsAggregationBuilder stats(String name) { return new StatsAggregationBuilder(name); } /** * Create a new {@link ExtendedStats} aggregation with the given name. */ public static ExtendedStatsAggregationBuilder extendedStats(String name) { return new ExtendedStatsAggregationBuilder(name); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static FilterAggregationBuilder filter(String name, QueryBuilder filter) { return new FilterAggregationBuilder(name, filter); } /** * Create a new {@link Filters} aggregation with the given name. */ public static FiltersAggregationBuilder filters(String name, KeyedFilter... filters) { return new FiltersAggregationBuilder(name, filters); } /** * Create a new {@link Filters} aggregation with the given name. */ public static FiltersAggregationBuilder filters(String name, QueryBuilder... filters) { return new FiltersAggregationBuilder(name, filters); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static SamplerAggregationBuilder sampler(String name) { return new SamplerAggregationBuilder(name); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static DiversifiedAggregationBuilder diversifiedSampler(String name) { return new DiversifiedAggregationBuilder(name); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static GlobalAggregationBuilder global(String name) { return new GlobalAggregationBuilder(name); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static MissingAggregationBuilder missing(String name) { return new MissingAggregationBuilder(name); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static NestedAggregationBuilder nested(String name, String path) { return new NestedAggregationBuilder(name, path); } /** * Create a new {@link SingleBucketAggregation} aggregation with the given name. */ public static ReverseNestedAggregationBuilder reverseNested(String name) { return new ReverseNestedAggregationBuilder(name); } /** * Create a new {@link GeoDistance} aggregation with the given name. */ public static GeoDistanceAggregationBuilder geoDistance(String name, GeoPoint origin) { return new GeoDistanceAggregationBuilder(name, origin); } /** * Create a new {@link Histogram} aggregation with the given name. */ public static HistogramAggregationBuilder histogram(String name) { return new HistogramAggregationBuilder(name); } /** * Create a new {@link InternalGeoHashGrid} aggregation with the given name. */ public static GeoHashGridAggregationBuilder geohashGrid(String name) { return new GeoHashGridAggregationBuilder(name); } /** * Create a new {@link InternalGeoTileGrid} aggregation with the given name. */ public static GeoTileGridAggregationBuilder geotileGrid(String name) { return new GeoTileGridAggregationBuilder(name); } /** * Create a new {@link SignificantTerms} aggregation with the given name. */ public static SignificantTermsAggregationBuilder significantTerms(String name) { return new SignificantTermsAggregationBuilder(name); } /** * Create a new {@link SignificantTextAggregationBuilder} aggregation with the given name and text field name */ public static SignificantTextAggregationBuilder significantText(String name, String fieldName) { return new SignificantTextAggregationBuilder(name, fieldName); } /** * Create a new {@link DateHistogramAggregationBuilder} aggregation with the given * name. */ public static DateHistogramAggregationBuilder dateHistogram(String name) { return new DateHistogramAggregationBuilder(name); } /** * Create a new {@link Range} aggregation with the given name. */ public static RangeAggregationBuilder range(String name) { return new RangeAggregationBuilder(name); } /** * Create a new {@link DateRangeAggregationBuilder} aggregation with the * given name. */ public static DateRangeAggregationBuilder dateRange(String name) { return new DateRangeAggregationBuilder(name); } /** * Create a new {@link IpRangeAggregationBuilder} aggregation with the * given name. */ public static IpRangeAggregationBuilder ipRange(String name) { return new IpRangeAggregationBuilder(name); } /** * Create a new {@link Terms} aggregation with the given name. */ public static TermsAggregationBuilder terms(String name) { return new TermsAggregationBuilder(name); } /** * Create a new {@link Percentiles} aggregation with the given name. */ public static PercentilesAggregationBuilder percentiles(String name) { return new PercentilesAggregationBuilder(name); } /** * Create a new {@link PercentileRanks} aggregation with the given name. */ public static PercentileRanksAggregationBuilder percentileRanks(String name, double[] values) { return new PercentileRanksAggregationBuilder(name, values); } /** * Create a new {@link MedianAbsoluteDeviation} aggregation with the given name */ public static MedianAbsoluteDeviationAggregationBuilder medianAbsoluteDeviation(String name) { return new MedianAbsoluteDeviationAggregationBuilder(name); } /** * Create a new {@link Cardinality} aggregation with the given name. */ public static CardinalityAggregationBuilder cardinality(String name) { return new CardinalityAggregationBuilder(name); } /** * Create a new {@link TopHits} aggregation with the given name. */ public static TopHitsAggregationBuilder topHits(String name) { return new TopHitsAggregationBuilder(name); } /** * Create a new {@link GeoBounds} aggregation with the given name. */ public static GeoBoundsAggregationBuilder geoBounds(String name) { return new GeoBoundsAggregationBuilder(name); } /** * Create a new {@link GeoCentroid} aggregation with the given name. */ public static GeoCentroidAggregationBuilder geoCentroid(String name) { return new GeoCentroidAggregationBuilder(name); } /** * Create a new {@link ScriptedMetric} aggregation with the given name. */ public static ScriptedMetricAggregationBuilder scriptedMetric(String name) { return new ScriptedMetricAggregationBuilder(name); } /** * Create a new {@link CompositeAggregationBuilder} aggregation with the given name. */ public static CompositeAggregationBuilder composite(String name, List<CompositeValuesSourceBuilder<?>> sources) { return new CompositeAggregationBuilder(name, sources); } }
AggregationBuilders
java
elastic__elasticsearch
x-pack/plugin/esql/arrow/src/test/java/org/elasticsearch/xpack/esql/arrow/ArrowResponseTests.java
{ "start": 20817, "end": 22000 }
class ____ implements Iterator<Object> { private final int fieldPos; private final ValueType type; private final Iterator<TestPage> pages; private TestPage page; private int position; EsqlValuesIterator(TestCase testCase, int column) { this.fieldPos = column; this.type = testCase.columns.get(column).valueType; this.position = 0; this.pages = testCase.pages.iterator(); this.page = pages.next(); } @Override public boolean hasNext() { return page != null; } @Override public Object next() { if (page == null) { throw new NoSuchElementException(); } Block block = page.blocks.get(fieldPos).block; Object result = block.isNull(position) ? null : type.valueAt(block, position, new BytesRef()); position++; if (position >= block.getPositionCount()) { position = 0; page = pages.hasNext() ? pages.next() : null; } return result; } } static
EsqlValuesIterator
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryServerStateStoreServiceFactory.java
{ "start": 1015, "end": 1936 }
class ____ { /** * Constructs an instance of the configured storage class * * @param conf the configuration * @return the state storage instance */ public static HistoryServerStateStoreService getStore(Configuration conf) { Class<? extends HistoryServerStateStoreService> storeClass = HistoryServerNullStateStoreService.class; boolean recoveryEnabled = conf.getBoolean( JHAdminConfig.MR_HS_RECOVERY_ENABLE, JHAdminConfig.DEFAULT_MR_HS_RECOVERY_ENABLE); if (recoveryEnabled) { storeClass = conf.getClass(JHAdminConfig.MR_HS_STATE_STORE, null, HistoryServerStateStoreService.class); if (storeClass == null) { throw new RuntimeException("Unable to locate storage class, check " + JHAdminConfig.MR_HS_STATE_STORE); } } return ReflectionUtils.newInstance(storeClass, conf); } }
HistoryServerStateStoreServiceFactory
java
bumptech__glide
integration/cronet/src/main/java/com/bumptech/glide/integration/cronet/ChromiumUrlLoader.java
{ "start": 2245, "end": 3656 }
class ____ implements ModelLoaderFactory<GlideUrl, InputStream>, ByteBufferParser<InputStream> { private CronetRequestFactory requestFactory; @Nullable private final DataLogger dataLogger; @Nullable private final GlideExecutor executor; public StreamFactory(CronetRequestFactory requestFactory, @Nullable DataLogger dataLogger) { this.requestFactory = requestFactory; this.dataLogger = dataLogger; this.executor = null; } /** * @param executor See {@link ChromiumUrlLoader} for details. */ public StreamFactory( CronetRequestFactory requestFactory, @Nullable DataLogger dataLogger, @Nullable GlideExecutor executor) { this.requestFactory = requestFactory; this.dataLogger = dataLogger; this.executor = executor; } @Override public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) { return new ChromiumUrlLoader<>(/* parser= */ this, requestFactory, dataLogger, executor); } @Override public void teardown() {} @Override public InputStream parse(ByteBuffer byteBuffer) { return ByteBufferUtil.toStream(byteBuffer); } @Override public Class<InputStream> getDataClass() { return InputStream.class; } } /** Loads {@link ByteBuffer}s for {@link GlideUrl}s using cronet. */ public static final
StreamFactory
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_13.java
{ "start": 1683, "end": 1920 }
class ____ { public VO(){ } private double type; public double getType() { return type; } public void setType(double type) { this.type = type; } } }
VO
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/FlushJobActionRequestTests.java
{ "start": 597, "end": 2130 }
class ____ extends AbstractBWCWireSerializationTestCase<Request> { @Override protected Request createTestInstance() { Request request = new Request(randomAlphaOfLengthBetween(1, 20)); if (randomBoolean()) { request.setWaitForNormalization(randomBoolean()); } if (randomBoolean()) { request.setRefreshRequired(randomBoolean()); } if (randomBoolean()) { request.setCalcInterim(randomBoolean()); } if (randomBoolean()) { request.setStart(Long.toString(randomNonNegativeLong())); } if (randomBoolean()) { request.setEnd(Long.toString(randomNonNegativeLong())); } if (randomBoolean()) { request.setAdvanceTime(Long.toString(randomNonNegativeLong())); } if (randomBoolean()) { request.setSkipTime(Long.toString(randomNonNegativeLong())); } return request; } @Override protected Request mutateInstance(Request instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Request> instanceReader() { return Request::new; } @Override protected Request mutateInstanceForVersion(Request instance, TransportVersion version) { if (version.before(TransportVersions.V_8_9_X)) { instance.setRefreshRequired(true); } return instance; } }
FlushJobActionRequestTests
java
mapstruct__mapstruct
core/src/main/java/org/mapstruct/MapperConfig.java
{ "start": 2046, "end": 2346 }
interface ____ { * // ... * } * </code></pre> * <pre><code class='java'> * // result after applying CentralConfig * &#64;Mapper( * uses = { CustomMapperViaMapper.class, CustomMapperViaMapperConfig.class }, * unmappedTargetPolicy = ReportingPolicy.ERROR * ) * public
SourceTargetMapper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 22107, "end": 22389 }
class ____ { public void doTest() { Client client = new Client(); client = client.noOp(); } } """) .addOutputLines( "out/Caller.java", """ public final
Caller