language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/AmbiguousTableFactoryException.java | {
"start": 1222,
"end": 2023
} | class ____
extends org.apache.flink.table.api.AmbiguousTableFactoryException {
public AmbiguousTableFactoryException(
List<? extends TableFactory> matchingFactories,
Class<? extends TableFactory> factoryClass,
List<TableFactory> factories,
Map<String, String> properties,
Throwable cause) {
super(matchingFactories, factoryClass, factories, properties, cause);
}
public AmbiguousTableFactoryException(
List<? extends TableFactory> matchingFactories,
Class<? extends TableFactory> factoryClass,
List<TableFactory> factories,
Map<String, String> properties) {
super(matchingFactories, factoryClass, factories, properties);
}
}
| AmbiguousTableFactoryException |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/exception/ExceptionUtilsTest.java | {
"start": 2143,
"end": 2405
} | class ____ extends AbstractLangTest {
/**
* Provides a method with a well known chained/nested exception
* name which matches the full signature (e.g. has a return value
* of {@code Throwable}).
*/
private static final | ExceptionUtilsTest |
java | google__gson | gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java | {
"start": 12159,
"end": 12223
} | class ____ {
@SuppressWarnings("ClassCanBeStatic")
| Outer |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/spi/context/storage/ContextLocal.java | {
"start": 2374,
"end": 4786
} | interface ____<T> {
/**
* Registers a context local storage.
*
* @return the context local storage
*/
static <T> ContextLocal<T> registerLocal(Class<T> type) {
return ContextLocalImpl.create(type, Function.identity());
}
/**
* Registers a context local storage.
*
* @return the context local storage
*/
static <T> ContextLocal<T> registerLocal(Class<T> type, Function<T, T> duplicator) {
return ContextLocalImpl.create(type, duplicator);
}
/**
* Get the local data from the {@code context}.
*
* @return the local data
*/
default T get(Context context) {
return get(context, AccessMode.CONCURRENT);
}
/**
* Get the local data from the {@code context}, when it does not exist then call {@code initialValueSupplier} to obtain
* the initial value. The supplier can be called multiple times when several threads call this method concurrently.
*
* @param initialValueSupplier the supplier of the initial value
* @return the local data
*/
default T get(Context context, Supplier<? extends T> initialValueSupplier) {
return get(context, AccessMode.CONCURRENT, initialValueSupplier);
}
/**
* Put local data in the {@code context}.
*
* @param data the data
*/
default void put(Context context, T data) {
put(context, AccessMode.CONCURRENT, data);
}
/**
* Remove the local data from the context.
*/
default void remove(Context context) {
put(context, AccessMode.CONCURRENT, null);
}
/**
* Like {@link #get(Context)} but with an {@code accessMode}.
*/
default T get(Context context, AccessMode accessMode) {
return ((ContextInternal)context).getLocal(this, accessMode);
}
/**
* Like {@link #get(Context, Supplier)} but with an {@code accessMode}.
*/
default T get(Context context, AccessMode accessMode, Supplier<? extends T> initialValueSupplier) {
return ((ContextInternal)context).getLocal(this, accessMode, initialValueSupplier);
}
/**
* Like {@link #put(Context, T)} but with an {@code accessMode}.
*/
default void put(Context context, AccessMode accessMode, T value) {
((ContextInternal)context).putLocal(this, accessMode, value);
}
/**
* Like {@link #remove(Context)} but with an {@code accessMode}.
*/
default void remove(Context context, AccessMode accessMode) {
put(context, accessMode, null);
}
}
| ContextLocal |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/metrics/Measurable.java | {
"start": 916,
"end": 1771
} | interface ____ extends MetricValueProvider<Double> {
/**
* Measure this quantity and return the result as a double.
*
* @param config The configuration for this metric
* @param now The POSIX time in milliseconds the measurement is being taken
* @return The measured value
*/
double measure(MetricConfig config, long now);
/**
* Measure this quantity and return the result as a double.
*
* This default implementation delegates to {@link #measure(MetricConfig, long)}.
*
* @param config The configuration for this metric
* @param now The POSIX time in milliseconds the measurement is being taken
* @return The measured value as a {@link Double}
*/
@Override
default Double value(MetricConfig config, long now) {
return measure(config, now);
}
}
| Measurable |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/DynamicPropertyRegistrar.java | {
"start": 3451,
"end": 3608
} | interface ____ {
/**
* Register dynamic properties in the supplied registry.
*/
void accept(DynamicPropertyRegistry registry);
}
| DynamicPropertyRegistrar |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/PrototypeProcessorExchangeFactory.java | {
"start": 1373,
"end": 5036
} | class ____ extends PooledObjectFactorySupport<Exchange>
implements ProcessorExchangeFactory {
private static final Logger LOG = LoggerFactory.getLogger(PrototypeProcessorExchangeFactory.class);
final Processor processor;
String routeId;
String id;
public PrototypeProcessorExchangeFactory() {
this.processor = null;
}
public PrototypeProcessorExchangeFactory(Processor processor) {
this.processor = processor;
}
@Override
public String getRouteId() {
return routeId;
}
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public Processor getProcessor() {
return processor;
}
@Override
public ProcessorExchangeFactory newProcessorExchangeFactory(Processor processor) {
PrototypeProcessorExchangeFactory answer = new PrototypeProcessorExchangeFactory(processor);
answer.setStatisticsEnabled(statisticsEnabled);
answer.setCapacity(capacity);
answer.setCamelContext(camelContext);
return answer;
}
@Override
public Exchange createCopy(Exchange exchange) {
return exchange.copy();
}
@Override
public Exchange createCorrelatedCopy(Exchange exchange, boolean handover) {
return ExchangeHelper.createCorrelatedCopy(exchange, handover);
}
@Override
public Exchange create(Endpoint fromEndpoint, ExchangePattern exchangePattern) {
return DefaultExchange.newFromEndpoint(fromEndpoint, exchangePattern);
}
@Override
public Exchange acquire() {
throw new UnsupportedOperationException("Not in use");
}
@Override
public boolean release(Exchange exchange) {
if (statisticsEnabled) {
statistics.released.increment();
}
return true;
}
@Override
public boolean isPooled() {
return false;
}
@Override
protected void doStop() throws Exception {
super.doStop();
logUsageSummary(LOG, "PrototypeProcessorExchangeFactory", 0);
}
void logUsageSummary(Logger log, String name, int pooled) {
if (statisticsEnabled && processor != null) {
// only log if there is any usage
long created = statistics.getCreatedCounter();
long acquired = statistics.getAcquiredCounter();
long released = statistics.getReleasedCounter();
long discarded = statistics.getDiscardedCounter();
boolean shouldLog = pooled > 0 || created > 0 || acquired > 0 || released > 0 || discarded > 0;
if (shouldLog) {
String rid = getRouteId();
String pid = getId();
// are there any leaks?
boolean leak = created + acquired > released + discarded;
if (leak) {
long leaks = (created + acquired) - (released + discarded);
log.warn(
"{} {} ({}) usage (leaks detected: {}) [pooled: {}, created: {}, acquired: {} released: {}, discarded: {}]",
name, rid, pid, leaks, pooled, created, acquired, released, discarded);
} else {
log.info("{} {} ({}) usage [pooled: {}, created: {}, acquired: {} released: {}, discarded: {}]",
name, rid, pid, pooled, created, acquired, released, discarded);
}
}
}
}
}
| PrototypeProcessorExchangeFactory |
java | apache__camel | components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/spi/PlatformHttpPluginRegistry.java | {
"start": 1314,
"end": 1698
} | class ____
* @return the plugin if found
*/
<T extends PlatformHttpPlugin> Optional<T> resolvePluginById(String id, Class<T> type);
/**
* Register the plugin into the registry.
*
* @param plugin the plugin
* @return true if the plugin was added, or false if already exists
*/
boolean register(PlatformHttpPlugin plugin);
}
| type |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/huggingface/request/HuggingFaceUnifiedChatCompletionRequestEntityTests.java | {
"start": 1024,
"end": 4154
} | class ____ extends ESTestCase {
private static final String ROLE = "user";
public void testSerializationWithModelIdStreaming() throws IOException {
testSerialization("test-endpoint", true, """
{
"messages": [
{
"content": "Hello, world!",
"role": "user"
}
],
"model": "test-endpoint",
"n": 1,
"stream": true,
"stream_options": {
"include_usage": true
}
}
""");
}
public void testSerializationWithModelIdNonStreaming() throws IOException {
testSerialization("test-endpoint", false, """
{
"messages": [
{
"content": "Hello, world!",
"role": "user"
}
],
"model": "test-endpoint",
"n": 1,
"stream": false
}
""");
}
public void testSerializationWithoutModelIdStreaming() throws IOException {
testSerialization(null, true, """
{
"messages": [
{
"content": "Hello, world!",
"role": "user"
}
],
"n": 1,
"stream": true,
"stream_options": {
"include_usage": true
}
}
""");
}
public void testSerializationWithoutModelIdNonStreaming() throws IOException {
testSerialization(null, false, """
{
"messages": [
{
"content": "Hello, world!",
"role": "user"
}
],
"n": 1,
"stream": false
}
""");
}
private static void testSerialization(String modelId, boolean isStreaming, String expectedJson) throws IOException {
UnifiedCompletionRequest.Message message = new UnifiedCompletionRequest.Message(
new UnifiedCompletionRequest.ContentString("Hello, world!"),
ROLE,
null,
null
);
var messageList = new ArrayList<UnifiedCompletionRequest.Message>();
messageList.add(message);
var unifiedRequest = UnifiedCompletionRequest.of(messageList);
UnifiedChatInput unifiedChatInput = new UnifiedChatInput(unifiedRequest, isStreaming);
HuggingFaceUnifiedChatCompletionRequestEntity entity = new HuggingFaceUnifiedChatCompletionRequestEntity(unifiedChatInput, modelId);
XContentBuilder builder = JsonXContent.contentBuilder();
entity.toXContent(builder, ToXContent.EMPTY_PARAMS);
String jsonString = Strings.toString(builder);
assertJsonEquals(jsonString, XContentHelper.stripWhitespace(expectedJson));
}
}
| HuggingFaceUnifiedChatCompletionRequestEntityTests |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/CountDistinctBooleanAggregatorFunctionTests.java | {
"start": 821,
"end": 1922
} | class ____ extends AggregatorFunctionTestCase {
@Override
protected SourceOperator simpleInput(BlockFactory blockFactory, int size) {
return new SequenceBooleanBlockSourceOperator(blockFactory, LongStream.range(0, size).mapToObj(l -> randomBoolean()).toList());
}
@Override
protected AggregatorFunctionSupplier aggregatorFunction() {
return new CountDistinctBooleanAggregatorFunctionSupplier();
}
@Override
protected String expectedDescriptionOfAggregator() {
return "count_distinct of booleans";
}
@Override
protected void assertSimpleOutput(List<Page> input, Block result) {
long expected = input.stream().flatMap(p -> allBooleans(p.getBlock(0))).distinct().count();
long count = ((LongBlock) result).getLong(0);
assertThat(count, equalTo(expected));
}
@Override
protected void assertOutputFromEmpty(Block b) {
assertThat(b.getPositionCount(), equalTo(1));
assertThat(valuesAtPositions(b, 0, 1), equalTo(List.of(List.of(0L))));
}
}
| CountDistinctBooleanAggregatorFunctionTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/mapping/IdentifierCollection.java | {
"start": 557,
"end": 2440
} | class ____ extends Collection {
public static final String DEFAULT_IDENTIFIER_COLUMN_NAME = "id";
private KeyValue identifier;
public IdentifierCollection(MetadataBuildingContext buildingContext, PersistentClass owner) {
super( buildingContext, owner );
}
public IdentifierCollection(
Supplier<ManagedBean<? extends UserCollectionType>> customTypeBeanResolver,
PersistentClass owner,
MetadataBuildingContext buildingContext) {
super( customTypeBeanResolver, owner, buildingContext );
}
protected IdentifierCollection(IdentifierCollection original) {
super( original );
this.identifier = (KeyValue) original.identifier.copy();
}
public KeyValue getIdentifier() {
return identifier;
}
public void setIdentifier(KeyValue identifier) {
this.identifier = identifier;
}
public final boolean isIdentified() {
return true;
}
@Override
public boolean isSame(Collection other) {
return other instanceof IdentifierCollection identifierCollection
&& isSame( identifierCollection );
}
public boolean isSame(IdentifierCollection other) {
return super.isSame( other )
&& isSame( identifier, other.identifier );
}
void createPrimaryKey() {
if ( !isOneToMany() ) {
final var primaryKey = new PrimaryKey( getCollectionTable() );
primaryKey.addColumns( getIdentifier() );
getCollectionTable().setPrimaryKey(primaryKey);
}
// create an index on the key columns??
}
public void validate(MappingContext mappingContext) throws MappingException {
super.validate( mappingContext );
assert getElement() != null : "IdentifierCollection identifier not bound : " + getRole();
if ( !getIdentifier().isValid( mappingContext ) ) {
throw new MappingException(
"collection id mapping has wrong number of columns: " +
getRole() +
" type: " +
getIdentifier().getType().getName()
);
}
}
}
| IdentifierCollection |
java | apache__camel | components/camel-git/src/main/java/org/apache/camel/component/git/consumer/GitCommitConsumer.java | {
"start": 1262,
"end": 3191
} | class ____ extends AbstractGitConsumer {
private final List<ObjectId> commitsConsumed = new ArrayList<>();
public GitCommitConsumer(GitEndpoint endpoint, Processor processor) {
super(endpoint, processor);
}
@Override
public GitEndpoint getEndpoint() {
return (GitEndpoint) super.getEndpoint();
}
@Override
protected int poll() throws Exception {
Queue<Object> exchanges = new ArrayDeque<>();
String branch = getEndpoint().getBranchName();
Iterable<RevCommit> commits;
ObjectId id = null;
if (ObjectHelper.isNotEmpty(branch)) {
id = getGit().getRepository().resolve(branch);
}
if (id != null) {
commits = getGit().log().add(id).call();
} else {
commits = getGit().log().all().call();
}
for (RevCommit commit : commits) {
if (!commitsConsumed.contains(commit.getId())) {
Exchange e = createExchange(true);
e.getMessage().setBody(commit.getFullMessage());
e.getMessage().setHeader(GitConstants.GIT_COMMIT_ID, commit.getId());
e.getMessage().setHeader(GitConstants.GIT_COMMIT_AUTHOR_NAME, commit.getAuthorIdent().getName());
e.getMessage().setHeader(GitConstants.GIT_COMMIT_COMMITTER_NAME, commit.getCommitterIdent().getName());
e.getMessage().setHeader(GitConstants.GIT_COMMIT_TIME, commit.getCommitTime());
exchanges.add(e);
}
}
return processBatch(exchanges);
}
@Override
public Object onPreProcessed(Exchange exchange) {
return exchange.getMessage().getHeader(GitConstants.GIT_COMMIT_ID);
}
@Override
public void onProcessed(Exchange exchange, Object value) {
if (value instanceof ObjectId oid) {
commitsConsumed.add(oid);
}
}
}
| GitCommitConsumer |
java | elastic__elasticsearch | x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/index/fielddata/LeafShapeFieldData.java | {
"start": 2099,
"end": 3443
} | class ____<T extends SpatialPoint, V extends ShapeValues.ShapeValue> extends ScriptDocValues.BaseGeometry<
T,
V> {
private final GeometrySupplier<T, V> gsSupplier;
protected ShapeScriptValues(GeometrySupplier<T, V> supplier) {
super(supplier);
this.gsSupplier = supplier;
}
@Override
public int getDimensionalType() {
return gsSupplier.getInternal(0) == null ? -1 : gsSupplier.getInternal(0).dimensionalShapeType().ordinal();
}
@Override
public T getCentroid() {
return gsSupplier.getInternal(0) == null ? null : gsSupplier.getInternalCentroid();
}
@Override
public BoundingBox<T> getBoundingBox() {
return gsSupplier.getInternal(0) == null ? null : gsSupplier.getInternalBoundingBox();
}
@Override
public T getLabelPosition() {
return gsSupplier.getInternal(0) == null ? null : gsSupplier.getInternalLabelPosition();
}
@Override
public V get(int index) {
return gsSupplier.getInternal(0);
}
public V getValue() {
return gsSupplier.getInternal(0);
}
@Override
public int size() {
return supplier.size();
}
}
}
| ShapeScriptValues |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/AccessExecutionVertex.java | {
"start": 1146,
"end": 3172
} | interface ____ {
/**
* Returns the name of this execution vertex in the format "myTask (2/7)".
*
* @return name of this execution vertex
*/
String getTaskNameWithSubtaskIndex();
/**
* Returns the subtask index of this execution vertex.
*
* @return subtask index of this execution vertex.
*/
int getParallelSubtaskIndex();
/**
* Returns the current execution for this execution vertex.
*
* @return current execution
*/
AccessExecution getCurrentExecutionAttempt();
/**
* Returns the current executions for this execution vertex. The returned collection must
* contain the current execution attempt.
*
* @return current executions
*/
<T extends AccessExecution> Collection<T> getCurrentExecutions();
/**
* Returns the current {@link ExecutionState} for this execution vertex.
*
* @return execution state for this execution vertex
*/
ExecutionState getExecutionState();
/**
* Returns the timestamp for the given {@link ExecutionState}.
*
* @param state state for which the timestamp should be returned
* @return timestamp for the given state
*/
long getStateTimestamp(ExecutionState state);
/**
* Returns the exception that caused the job to fail. This is the first root exception that was
* not recoverable and triggered job failure.
*
* @return failure exception wrapped in an {@code Optional} of {@link ErrorInfo}, or an empty
* {@link Optional} if no exception was caught.
*/
Optional<ErrorInfo> getFailureInfo();
/**
* Returns the {@link TaskManagerLocation} for this execution vertex.
*
* @return taskmanager location for this execution vertex.
*/
TaskManagerLocation getCurrentAssignedResourceLocation();
/**
* Returns the execution history.
*
* @return the execution history
*/
ExecutionHistory getExecutionHistory();
}
| AccessExecutionVertex |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/throwable/ThrowableAssert_extracting_with_Function_Test.java | {
"start": 753,
"end": 1150
} | class ____ {
@Test
void should_allow_type_specific_extractor() {
// GIVEN
Exception cause = new Exception("boom!");
ClassNotFoundException exception = new ClassNotFoundException("message", cause);
// WHEN/THEN
assertThat(exception).extracting(ClassNotFoundException::getException)
.isSameAs(cause);
}
}
| ThrowableAssert_extracting_with_Function_Test |
java | google__dagger | javatests/dagger/internal/codegen/ScopingValidationTest.java | {
"start": 15446,
"end": 15530
} | class ____ {",
" @Inject SimpleType() {}",
" static | SimpleType |
java | netty__netty | codec-compression/src/main/java/io/netty/handler/codec/compression/SnappyOptions.java | {
"start": 767,
"end": 868
} | class ____ implements CompressionOptions {
// Will add config if Snappy supports this
}
| SnappyOptions |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/TaskAssertions.java | {
"start": 1305,
"end": 4504
} | class ____ {
private static final Logger logger = LogManager.getLogger(TaskAssertions.class);
private TaskAssertions() {}
public static void awaitTaskWithPrefix(String actionPrefix) throws Exception {
awaitTaskWithPrefix(actionPrefix, internalCluster().getInstances(TransportService.class));
}
public static void awaitTaskWithPrefixOnMaster(String actionPrefix) throws Exception {
awaitTaskWithPrefix(actionPrefix, List.of(internalCluster().getCurrentMasterNodeInstance(TransportService.class)));
}
private static void awaitTaskWithPrefix(String actionPrefix, Iterable<TransportService> transportServiceInstances) throws Exception {
logger.info("--> waiting for task with prefix [{}] to start", actionPrefix);
assertBusy(() -> {
for (TransportService transportService : transportServiceInstances) {
List<Task> matchingTasks = transportService.getTaskManager()
.getTasks()
.values()
.stream()
.filter(t -> t.getAction().startsWith(actionPrefix))
.collect(Collectors.toList());
if (matchingTasks.isEmpty() == false) {
logger.trace("--> found {} tasks with prefix [{}]: {}", matchingTasks.size(), actionPrefix, matchingTasks);
return;
}
}
fail("no task with prefix [" + actionPrefix + "] found");
});
}
public static void assertAllCancellableTasksAreCancelled(String actionPrefix, @Nullable String opaqueId) throws Exception {
logger.info("--> checking that all tasks with prefix {} are marked as cancelled", actionPrefix);
assertBusy(() -> {
var tasks = new ArrayList<CancellableTask>();
for (TransportService transportService : internalCluster().getInstances(TransportService.class)) {
var taskManager = transportService.getTaskManager();
assertTrue(taskManager.assertCancellableTaskConsistency());
taskManager.getCancellableTasks().values().stream().filter(t -> t.getAction().startsWith(actionPrefix)).forEach(tasks::add);
}
assertFalse("no tasks found for action: " + actionPrefix, tasks.isEmpty());
assertTrue(
tasks.toString(),
tasks.stream().allMatch(t -> t.isCancelled() && Objects.equals(t.getHeader(Task.X_OPAQUE_ID_HTTP_HEADER), opaqueId))
);
}, 30, TimeUnit.SECONDS);
}
public static void assertAllCancellableTasksAreCancelled(String actionPrefix) throws Exception {
assertAllCancellableTasksAreCancelled(actionPrefix, null);
}
public static void assertAllTasksHaveFinished(String actionPrefix) throws Exception {
logger.info("--> checking that all tasks with prefix {} have finished", actionPrefix);
assertBusy(() -> {
final List<TaskInfo> tasks = client().admin().cluster().prepareListTasks().get().getTasks();
assertTrue(tasks.toString(), tasks.stream().noneMatch(t -> t.action().startsWith(actionPrefix)));
});
}
}
| TaskAssertions |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java | {
"start": 23038,
"end": 23260
} | class ____ extends CompoundAggTranslator<Stats> {
@Override
protected LeafAgg toAgg(String id, Stats s) {
return new StatsAgg(id, asFieldOrLiteralOrScript(s));
}
}
static | StatsAggs |
java | quarkusio__quarkus | extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/config/ConfigMappingInjectionInValidatorTest.java | {
"start": 1011,
"end": 1441
} | class ____ {
@RegisterExtension
private static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class));
@Inject
Validator validator;
@Test
void valid() {
assertTrue(validator.validate(new Entity()).isEmpty());
}
@StaticInitSafe
@ConfigMapping(prefix = "valid.config")
public | ConfigMappingInjectionInValidatorTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/properties/PropertiesComponentPropertiesSourceTest.java | {
"start": 1326,
"end": 5344
} | class ____ {
@Test
public void testPropertiesSourceFromRegistry() {
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("my-ps-1", new PropertiesPropertiesSource("ps1", "my-key-1", "my-val-1"));
context.getRegistry().bind("my-ps-2", new PropertiesPropertiesSource("ps2", "my-key-2", "my-val-2"));
assertThat(context.resolvePropertyPlaceholders("{{my-key-1}}")).isEqualTo("my-val-1");
assertThat(context.resolvePropertyPlaceholders("{{my-key-2}}")).isEqualTo("my-val-2");
}
@Test
public void testOrderedPropertiesSources() {
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("my-ps-1",
new PropertiesPropertiesSource(Ordered.HIGHEST, "ps1", "shared", "v1", "my-key-1", "my-val-1"));
context.getRegistry().bind("my-ps-2",
new PropertiesPropertiesSource(Ordered.LOWEST, "ps2", "shared", "v2", "my-key-2", "my-val-2"));
{
Properties properties = context.getPropertiesComponent().loadProperties();
assertThat(properties.get("my-key-1")).isEqualTo("my-val-1");
assertThat(properties.get("my-key-2")).isEqualTo("my-val-2");
assertThat(properties.get("shared")).isEqualTo("v1");
}
{
Map<String, Object> properties = context.getPropertiesComponent().loadPropertiesAsMap();
assertThat(properties.get("my-key-1")).isEqualTo("my-val-1");
assertThat(properties.get("my-key-2")).isEqualTo("my-val-2");
assertThat(properties.get("shared")).isEqualTo("v1");
}
}
@Test
public void testFilteredPropertiesSources() {
Properties initial = new Properties();
initial.put("initial-1", "initial-val-1");
initial.put("initial-2", "initial-val-2");
initial.put("my-key-2", "initial-val-2");
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("my-ps-1", new PropertiesPropertiesSource("ps1", "my-key-1", "my-val-1"));
context.getRegistry().bind("my-ps-2", new PropertiesPropertiesSource("ps2", "my-key-2", "my-val-2"));
context.getPropertiesComponent().setInitialProperties(initial);
{
Properties properties = context.getPropertiesComponent().loadProperties(k -> k.endsWith("-2"));
assertThat(properties).hasSize(2);
assertThat(properties.get("initial-2")).isEqualTo("initial-val-2");
assertThat(properties.get("my-key-2")).isEqualTo("my-val-2");
}
{
Map<String, Object> properties = context.getPropertiesComponent().loadPropertiesAsMap(k -> k.endsWith("-2"));
assertThat(properties).hasSize(2);
assertThat(properties.get("initial-2")).isEqualTo("initial-val-2");
assertThat(properties.get("my-key-2")).isEqualTo("my-val-2");
}
}
@Test
public void testDisablePropertiesSourceDiscovery() {
CamelContext context = new DefaultCamelContext();
PropertiesComponent pc = (PropertiesComponent) context.getPropertiesComponent();
pc.setAutoDiscoverPropertiesSources(false);
context.getRegistry().bind("my-ps-1", new PropertiesPropertiesSource("ps1", "my-key-1", "my-val-1"));
context.getRegistry().bind("my-ps-2", new PropertiesPropertiesSource("ps2", "my-key-2", "my-val-2"));
assertThatThrownBy(() -> context.resolvePropertyPlaceholders("{{my-key-1}}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Property with key [my-key-1] not found in properties from text: {{my-key-1}}");
assertThatThrownBy(() -> context.resolvePropertyPlaceholders("{{my-key-2}}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Property with key [my-key-2] not found in properties from text: {{my-key-2}}");
}
private static final | PropertiesComponentPropertiesSourceTest |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/ParsingTests.java | {
"start": 13115,
"end": 13822
} | class ____ {
@Test
void elvis() {
parseCheck("3?:1", "(3 ?: 1)");
parseCheck("(2*3)?:1*10", "((2 * 3) ?: (1 * 10))");
parseCheck("((2*3)?:1)*10", "(((2 * 3) ?: 1) * 10)");
}
@Test
void ternary() {
parseCheck("1>2?3:4", "((1 > 2) ? 3 : 4)");
parseCheck("(a ? 1 : 0) * 10", "((a ? 1 : 0) * 10)");
parseCheck("(a?1:0)*10", "((a ? 1 : 0) * 10)");
parseCheck("(4 % 2 == 0 ? 1 : 0) * 10", "((((4 % 2) == 0) ? 1 : 0) * 10)");
parseCheck("((4 % 2 == 0) ? 1 : 0) * 10", "((((4 % 2) == 0) ? 1 : 0) * 10)");
parseCheck("{1}.#isEven(#this) == 'y'?'it is even':'it is odd'",
"(({1}.#isEven(#this) == 'y') ? 'it is even' : 'it is odd')");
}
}
@Nested
| ElvisAndTernaryOperators |
java | apache__kafka | tools/src/test/java/org/apache/kafka/tools/UserScramCredentialsCommandTest.java | {
"start": 1563,
"end": 1866
} | class ____ {
private static final String USER1 = "user1";
private static final String USER2 = "user2";
private final ClusterInstance cluster;
public UserScramCredentialsCommandTest(ClusterInstance cluster) {
this.cluster = cluster;
}
static | UserScramCredentialsCommandTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/records/RecordDeserialization3906Test.java | {
"start": 1777,
"end": 6649
} | class ____ "failing/" for 3.0
/*
/**********************************************************
/* Passing Tests : Suggested work-arounds
/* for future modifications
/**********************************************************
*/
@Test
public void testEmptyJsonToRecordWorkAround() throws Exception {
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
.changeDefaultVisibility(vc ->
vc.withVisibility(PropertyAccessor.ALL, Visibility.NONE)
.withVisibility(PropertyAccessor.CREATOR, Visibility.ANY))
.build();
Record3906 recordDeser = mapper.readValue("{}", Record3906.class);
assertEquals(new Record3906(null, 0), recordDeser);
}
@Test
public void testEmptyJsonToRecordCreatorsVisible() throws Exception {
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
.changeDefaultVisibility(vc ->
vc.withVisibility(PropertyAccessor.CREATOR, Visibility.NON_PRIVATE))
.build();
Record3906 recordDeser = mapper.readValue("{}", Record3906.class);
assertEquals(new Record3906(null, 0), recordDeser);
}
@Test
public void testEmptyJsonToRecordUsingModule() throws Exception {
ObjectMapper mapper = jsonMapperBuilder().addModule(new SimpleModule() {
@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.insertAnnotationIntrospector(new NopAnnotationIntrospector() {
@Override
public VisibilityChecker findAutoDetectVisibility(MapperConfig<?> cfg,
AnnotatedClass ac,
VisibilityChecker checker) {
return ac.getType().isRecordType()
? checker.withCreatorVisibility(JsonAutoDetect.Visibility.NON_PRIVATE)
: checker;
}
});
}
})
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
.build();
Record3906 recordDeser = mapper.readValue("{}", Record3906.class);
assertEquals(new Record3906(null, 0), recordDeser);
}
@Test
public void testEmptyJsonToRecordDirectAutoDetectConfig() throws Exception {
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
.build();
Record3906Annotated recordDeser = mapper.readValue("{}", Record3906Annotated.class);
assertEquals(new Record3906Annotated(null, 0), recordDeser);
}
@Test
public void testEmptyJsonToRecordJsonCreator() throws Exception {
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
.build();
Record3906Creator recordDeser = mapper.readValue("{}", Record3906Creator.class);
assertEquals(new Record3906Creator(null, 0), recordDeser);
}
@Test
public void testEmptyJsonToRecordUsingModuleOther() throws Exception {
ObjectMapper mapper = jsonMapperBuilder().addModule(
new SimpleModule() {
@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.insertAnnotationIntrospector(new NopAnnotationIntrospector() {
@Override
public VisibilityChecker findAutoDetectVisibility(MapperConfig<?> cfg,
AnnotatedClass ac,
VisibilityChecker checker) {
if (ac.getType() == null) {
return checker;
}
if (!ac.getType().isRecordType()) {
return checker;
}
// If this is a Record, then increase the "creator" visibility again
return checker.withCreatorVisibility(Visibility.ANY);
}
});
}
})
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
.build();
assertEquals(new Record3906(null, 0),
mapper.readValue("{}", Record3906.class));
assertEquals(new PrivateRecord3906(null, 0),
mapper.readValue("{}", PrivateRecord3906.class));
}
}
| under |
java | quarkusio__quarkus | integration-tests/main/src/test/java/io/quarkus/it/main/CoreSerializationInGraalITCase.java | {
"start": 226,
"end": 451
} | class ____ {
@Test
public void testEntitySerializationFromServlet() throws Exception {
RestAssured.when().get("/core/serialization").then()
.body(is("OK"));
}
}
| CoreSerializationInGraalITCase |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/InheritanceQueryGroupByTest.java | {
"start": 11029,
"end": 11268
} | class ____ extends SingleTableParent {
@Column( name = "child_one_col" )
private Integer childOneProp;
}
@SuppressWarnings("unused")
@Entity( name = "SingleTableChildTwo" )
@DiscriminatorValue( "2" )
public static | SingleTableChildOne |
java | netty__netty | common/src/main/java/io/netty/util/NettyRuntime.java | {
"start": 903,
"end": 972
} | class ____ available processors to enable testing.
*/
static | for |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/NestedMethodSelector.java | {
"start": 1616,
"end": 2538
} | class ____ method
* if {@link #getEnclosingClasses()}, {@link #getNestedClass()},
* {@link #getMethod()}, or {@link #getParameterTypes()} is invoked.
*
* <p>In this context, a Java {@code Method} means anything that can be referenced
* as a {@link Method} on the JVM — for example, methods from Java classes
* or methods from other JVM languages such Groovy, Scala, etc.
*
* @since 1.6
* @see DiscoverySelectors#selectNestedMethod(List, String, String)
* @see DiscoverySelectors#selectNestedMethod(List, String, String, String)
* @see DiscoverySelectors#selectNestedMethod(List, Class, String)
* @see DiscoverySelectors#selectNestedMethod(List, Class, String, String)
* @see DiscoverySelectors#selectNestedMethod(List, Class, Method)
* @see org.junit.platform.engine.support.descriptor.MethodSource
* @see NestedClassSelector
* @see MethodSelector
*/
@API(status = STABLE, since = "1.6")
public final | or |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googleaistudio/embeddings/GoogleAiStudioEmbeddingsServiceSettingsTests.java | {
"start": 1315,
"end": 5084
} | class ____ extends AbstractWireSerializingTestCase<GoogleAiStudioEmbeddingsServiceSettings> {
private static GoogleAiStudioEmbeddingsServiceSettings createRandom() {
return new GoogleAiStudioEmbeddingsServiceSettings(
randomAlphaOfLength(8),
randomNonNegativeIntOrNull(),
randomNonNegativeIntOrNull(),
randomFrom(randomSimilarityMeasure(), null),
randomFrom(RateLimitSettingsTests.createRandom(), null)
);
}
public void testFromMap_Request_CreatesSettingsCorrectly() {
var model = randomAlphaOfLength(8);
var maxInputTokens = randomIntBetween(1, 1024);
var dims = randomIntBetween(1, 10000);
var similarity = randomSimilarityMeasure();
var serviceSettings = GoogleAiStudioEmbeddingsServiceSettings.fromMap(
new HashMap<>(
Map.of(
ServiceFields.MODEL_ID,
model,
ServiceFields.MAX_INPUT_TOKENS,
maxInputTokens,
ServiceFields.DIMENSIONS,
dims,
ServiceFields.SIMILARITY,
similarity.toString()
)
),
ConfigurationParseContext.PERSISTENT
);
assertThat(serviceSettings, is(new GoogleAiStudioEmbeddingsServiceSettings(model, maxInputTokens, dims, similarity, null)));
}
public void testToXContent_WritesAllValues() throws IOException {
var entity = new GoogleAiStudioEmbeddingsServiceSettings("model", 1024, 8, SimilarityMeasure.DOT_PRODUCT, null);
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
entity.toXContent(builder, null);
String xContentResult = Strings.toString(builder);
assertThat(xContentResult, equalToIgnoringWhitespaceInJsonString("""
{
"model_id":"model",
"max_input_tokens": 1024,
"dimensions": 8,
"similarity": "dot_product",
"rate_limit": {
"requests_per_minute":360
}
}"""));
}
@Override
protected Writeable.Reader<GoogleAiStudioEmbeddingsServiceSettings> instanceReader() {
return GoogleAiStudioEmbeddingsServiceSettings::new;
}
@Override
protected GoogleAiStudioEmbeddingsServiceSettings createTestInstance() {
return createRandom();
}
@Override
protected GoogleAiStudioEmbeddingsServiceSettings mutateInstance(GoogleAiStudioEmbeddingsServiceSettings instance) throws IOException {
var modelId = instance.modelId();
var maxInputTokens = instance.maxInputTokens();
var dimensions = instance.dimensions();
var similarity = instance.similarity();
var rateLimitSettings = instance.rateLimitSettings();
switch (randomInt(4)) {
case 0 -> modelId = randomValueOtherThan(modelId, () -> randomAlphaOfLength(8));
case 1 -> maxInputTokens = randomValueOtherThan(maxInputTokens, ESTestCase::randomNonNegativeIntOrNull);
case 2 -> dimensions = randomValueOtherThan(dimensions, ESTestCase::randomNonNegativeIntOrNull);
case 3 -> similarity = randomValueOtherThan(similarity, () -> randomFrom(Utils.randomSimilarityMeasure(), null));
case 4 -> rateLimitSettings = randomValueOtherThan(rateLimitSettings, RateLimitSettingsTests::createRandom);
default -> throw new AssertionError("Illegal randomisation branch");
}
return new GoogleAiStudioEmbeddingsServiceSettings(modelId, maxInputTokens, dimensions, similarity, rateLimitSettings);
}
}
| GoogleAiStudioEmbeddingsServiceSettingsTests |
java | apache__camel | components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/FhirCustomClientConfigurationIT.java | {
"start": 2724,
"end": 2777
} | class ____ {@link FhirConfiguration} APIs.
*/
public | for |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/rules/physical/local/SubstituteRoundToTests.java | {
"start": 4681,
"end": 47393
} | class ____ extends AbstractLocalPhysicalPlanOptimizerTests {
public SubstituteRoundToTests(String name, Configuration config) {
super(name, config);
}
private static final List<String> dateHistograms = List.of(
"date_trunc(1 day, date)",
"bucket(date, 1 day)",
"round_to(date, \"2023-10-20\", \"2023-10-21\", \"2023-10-22\", \"2023-10-23\")"
);
private static final Map<String, List<Object>> roundToAllTypes = new HashMap<>(
Map.ofEntries(
Map.entry("byte", List.of(2, 1, 3, 4)),
Map.entry("short", List.of(1, 3, 2, 4)),
Map.entry("integer", List.of(1, 2, 3, 4)),
Map.entry("long", List.of(1697760000000L, 1697846400000L, 1697932800000L, 1698019200000L)),
Map.entry("float", List.of(3.0, 2.0, 1.0, 4.0)),
Map.entry("half_float", List.of(4.0, 2.0, 3.0, 1.0)),
Map.entry("scaled_float", List.of(4.0, 3.0, 2.0, 1.0)),
Map.entry("double", List.of(1.0, 2.0, 3.0, 4.0)),
Map.entry("date", List.of("\"2023-10-20\"::date", "\"2023-10-21\"::date", "\"2023-10-22\"::date", "\"2023-10-23\"::date")),
Map.entry(
"date_nanos",
List.of(
"\"2023-10-20\"::date_nanos",
"\"2023-10-21\"::date_nanos",
"\"2023-10-22\"::date_nanos",
"\"2023-10-23\"::date_nanos"
)
)
)
);
private static final Map<String, QueryBuilder> otherPushDownFunctions = new HashMap<>(
Map.ofEntries(
Map.entry("keyword == \"keyword\"", termQuery("keyword", "keyword").boost(0)),
Map.entry(
"date >= \"2023-10-19\" and date <= \"2023-10-24\"",
rangeQuery("date").gte("2023-10-19T00:00:00.000Z")
.lte("2023-10-24T00:00:00.000Z")
.timeZone("Z")
.boost(0)
.format(DEFAULT_DATE_TIME_FORMATTER.pattern())
),
Map.entry("keyword : \"keyword\"", matchQuery("keyword", "keyword").lenient(true))
)
);
// The date range of SearchStats is from 2023-10-20 to 2023-10-23.
private static final SearchStats searchStats = searchStats();
// DateTrunc/Bucket is transformed to RoundTo first and then to QueryAndTags
public void testDateTruncBucketTransformToQueryAndTags() {
for (String dateHistogram : dateHistograms) {
String query = LoggerMessageFormat.format(null, """
from test
| stats count(*) by x = {}
""", dateHistogram);
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.DATETIME);
var queryBuilderAndTags = getBuilderAndTagsFromStats(exchange, DataType.DATETIME);
List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags = expectedQueryBuilderAndTags(
query,
"date",
List.of(),
new Source(2, 24, dateHistogram),
null
);
verifyQueryAndTags(expectedQueryBuilderAndTags, queryBuilderAndTags);
}
}
// Pushing count to source isn't supported when there is a filter on the count at the moment.
public void testDateTruncBucketTransformToQueryAndTagsWithWhereInsideAggregation() {
for (String dateHistogram : dateHistograms) {
String query = LoggerMessageFormat.format(null, """
from test
| stats count(*) where long > 10 by x = {}
""", dateHistogram);
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.DATETIME, List.of("count(*) where long > 10"));
AggregateExec agg = as(exchange.child(), AggregateExec.class);
FieldExtractExec fieldExtractExec = as(agg.child(), FieldExtractExec.class);
EvalExec evalExec = as(fieldExtractExec.child(), EvalExec.class);
List<Alias> aliases = evalExec.fields();
assertEquals(1, aliases.size());
FieldAttribute roundToTag = as(aliases.get(0).child(), FieldAttribute.class);
assertEquals("$$date$round_to$datetime", roundToTag.name());
EsQueryExec esQueryExec = as(evalExec.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags = expectedQueryBuilderAndTags(
query,
"date",
List.of(),
new Source(2, 40, dateHistogram),
null
);
verifyQueryAndTags(expectedQueryBuilderAndTags, queryBuilderAndTags);
assertThrows(UnsupportedOperationException.class, esQueryExec::query);
}
}
// We do not support count pushdown when there is an ES filter at the moment, even if it's on the same field.
public void testDateTruncBucketTransformToQueryAndTagsWithEsFilter() {
for (String dateHistogram : dateHistograms) {
String query = LoggerMessageFormat.format(null, """
from test
| stats count(*) by x = {}
""", dateHistogram);
RangeQueryBuilder esFilter = rangeQuery("date").from("2023-10-21T00:00:00.000Z").to("2023-10-22T00:00:00.000Z");
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.DATETIME, List.of("count(*)"), esFilter);
AggregateExec agg = as(exchange.child(), AggregateExec.class);
EvalExec evalExec = as(agg.child(), EvalExec.class);
List<Alias> aliases = evalExec.fields();
assertEquals(1, aliases.size());
FieldAttribute roundToTag = as(aliases.get(0).child(), FieldAttribute.class);
assertEquals("$$date$round_to$datetime", roundToTag.name());
EsQueryExec esQueryExec = as(evalExec.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags = expectedQueryBuilderAndTags(
query,
"date",
List.of(),
new Source(2, 24, dateHistogram),
esFilter
);
verifyQueryAndTags(expectedQueryBuilderAndTags, queryBuilderAndTags);
assertThrows(UnsupportedOperationException.class, esQueryExec::query);
}
}
// Pushing count to source isn't supported when there are multiple aggregates.
public void testDateTruncBucketTransformToQueryAndTagsWithMultipleAggregates() {
for (String dateHistogram : dateHistograms) {
String query = LoggerMessageFormat.format(null, """
from test
| stats sum(long), count(*) by x = {}
""", dateHistogram);
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.DATETIME, List.of("sum(long)", "count(*)"));
AggregateExec agg = as(exchange.child(), AggregateExec.class);
FieldExtractExec fieldExtractExec = as(agg.child(), FieldExtractExec.class);
EvalExec evalExec = as(fieldExtractExec.child(), EvalExec.class);
List<Alias> aliases = evalExec.fields();
assertEquals(1, aliases.size());
FieldAttribute roundToTag = as(aliases.get(0).child(), FieldAttribute.class);
assertEquals("$$date$round_to$datetime", roundToTag.name());
EsQueryExec esQueryExec = as(evalExec.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags = expectedQueryBuilderAndTags(
query,
"date",
List.of(),
new Source(2, 35, dateHistogram),
null
);
verifyQueryAndTags(expectedQueryBuilderAndTags, queryBuilderAndTags);
assertThrows(UnsupportedOperationException.class, esQueryExec::query);
}
}
// DateTrunc is transformed to RoundTo first but cannot be transformed to QueryAndTags, when the TopN is pushed down to EsQueryExec
public void testDateTruncNotTransformToQueryAndTags() {
for (String dateHistogram : dateHistograms) {
if (dateHistogram.contains("bucket")) { // bucket cannot be used outside of stats
continue;
}
String query = LoggerMessageFormat.format(null, """
from test
| sort date
| eval x = {}
| keep alias_integer, date, x
| limit 5
""", dateHistogram);
PhysicalPlan plan = plannerOptimizer.plan(query, searchStats, makeAnalyzer("mapping-all-types.json"));
ProjectExec projectExec = as(plan, ProjectExec.class);
TopNExec topNExec = as(projectExec.child(), TopNExec.class);
ExchangeExec exchangeExec = as(topNExec.child(), ExchangeExec.class);
projectExec = as(exchangeExec.child(), ProjectExec.class);
FieldExtractExec fieldExtractExec = as(projectExec.child(), FieldExtractExec.class);
EvalExec evalExec = as(fieldExtractExec.child(), EvalExec.class);
List<Alias> aliases = evalExec.fields();
assertEquals(1, aliases.size());
RoundTo roundTo = as(aliases.getFirst().child(), RoundTo.class);
assertEquals(4, roundTo.points().size());
fieldExtractExec = as(evalExec.child(), FieldExtractExec.class);
EsQueryExec esQueryExec = as(fieldExtractExec.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
assertEquals(1, queryBuilderAndTags.size());
EsQueryExec.QueryBuilderAndTags queryBuilder = queryBuilderAndTags.getFirst();
assertNull(queryBuilder.query());
assertTrue(queryBuilder.tags().isEmpty());
assertNull(esQueryExec.query());
}
}
// RoundTo(all numeric data types) is transformed to QueryAndTags
public void testRoundToTransformToQueryAndTags() {
for (Map.Entry<String, List<Object>> roundTo : roundToAllTypes.entrySet()) {
String fieldName = roundTo.getKey();
List<Object> roundingPoints = roundTo.getValue();
String expression = "round_to("
+ fieldName
+ ", "
+ roundingPoints.stream().map(Object::toString).collect(Collectors.joining(","))
+ ")";
String query = LoggerMessageFormat.format(null, """
from test
| stats count(*) by x = {}
""", expression);
DataType bucketType = DataType.fromTypeName(roundTo.getKey()).widenSmallNumeric();
ExchangeExec exchange = validatePlanBeforeExchange(query, bucketType);
var queryBuilderAndTags = getBuilderAndTagsFromStats(exchange, bucketType);
List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags = expectedQueryBuilderAndTags(
query,
fieldName,
roundingPoints,
new Source(2, 24, expression),
null
);
verifyQueryAndTags(expectedQueryBuilderAndTags, queryBuilderAndTags);
}
}
// test if the combine query is generated correctly when there are other functions that can be pushed down
public void testDateTruncBucketTransformToQueryAndTagsWithOtherPushdownFunctions() {
for (String dateHistogram : dateHistograms) {
for (Map.Entry<String, QueryBuilder> otherPushDownFunction : otherPushDownFunctions.entrySet()) {
String predicate = otherPushDownFunction.getKey();
QueryBuilder qb = otherPushDownFunction.getValue();
String query = LoggerMessageFormat.format(null, """
from test
| where {}
| stats count(*) by x = {}
""", predicate, dateHistogram);
QueryBuilder mainQueryBuilder = qb instanceof MatchQueryBuilder
? qb
: wrapWithSingleQuery(
query,
qb,
predicate.contains("and") ? "date" : "keyword",
new Source(2, 8, predicate.contains("and") ? predicate.substring(0, 20) : predicate)
);
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.DATETIME);
AggregateExec agg = as(exchange.child(), AggregateExec.class);
EvalExec eval = as(agg.child(), EvalExec.class);
List<Alias> aliases = eval.fields();
assertEquals(1, aliases.size());
FieldAttribute roundToTag = as(aliases.get(0).child(), FieldAttribute.class);
assertEquals("$$date$round_to$datetime", roundToTag.name());
EsQueryExec esQueryExec = as(eval.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags = expectedQueryBuilderAndTags(
query,
"date",
List.of(),
new Source(3, 24, dateHistogram),
mainQueryBuilder
);
verifyQueryAndTags(expectedQueryBuilderAndTags, queryBuilderAndTags);
assertThrows(UnsupportedOperationException.class, esQueryExec::query);
}
}
}
/**
* ReplaceRoundToWithQueryAndTags does not support lookup joins yet
* LimitExec[1000[INTEGER],16]
* \_AggregateExec[[x{r}#8],[COUNT(*[KEYWORD],true[BOOLEAN]) AS count(*)#9, x{r}#8],FINAL,[x{r}#8, $$count(*)$count{r}#34, $$count(*
* )$seen{r}#35],16]
* \_ExchangeExec[[x{r}#8, $$count(*)$count{r}#34, $$count(*)$seen{r}#35],true]
* \_AggregateExec[[x{r}#8],[COUNT(*[KEYWORD],true[BOOLEAN]) AS count(*)#9, x{r}#8],INITIAL,[x{r}#8, $$count(*)$count{r}#36, $$count
* (*)$seen{r}#37],16]
* \_EvalExec[[ROUNDTO(date{f}#15,1697760000000[DATETIME],1697846400000[DATETIME],1697932800000[DATETIME],1698019200000[DATE
* TIME]) AS x#8]]
* \_FieldExtractExec[date{f}#15]
* \_LookupJoinExec[[integer{f}#21],[language_code{f}#32],[]]
* |_FieldExtractExec[integer{f}#21]
* | \_EsQueryExec[test], indexMode[standard], [_doc{f}#38], limit[], sort[] estimatedRowSize[24]
* queryBuilderAndTags [[QueryBuilderAndTags{queryBuilder=[null], tags=[]}]]
* \_FragmentExec[filter=null, estimatedRowSize=0, reducer=[], fragment=[
* EsRelation[languages_lookup][LOOKUP][language_code{f}#32]]]
*/
public void testDateTruncBucketNotTransformToQueryAndTagsWithLookupJoin() {
for (String dateHistogram : dateHistograms) {
String query = LoggerMessageFormat.format(null, """
from test
| rename integer as language_code
| lookup join languages_lookup on language_code
| stats count(*) by x = {}
""", dateHistogram);
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.DATETIME);
AggregateExec agg = as(exchange.child(), AggregateExec.class);
EvalExec eval = as(agg.child(), EvalExec.class);
List<Alias> aliases = eval.fields();
assertEquals(1, aliases.size());
RoundTo roundTo = as(aliases.getFirst().child(), RoundTo.class);
assertEquals(4, roundTo.points().size());
FieldExtractExec fieldExtractExec = as(eval.child(), FieldExtractExec.class);
List<Attribute> attributes = fieldExtractExec.attributesToExtract();
assertEquals(1, attributes.size());
assertEquals("date", attributes.getFirst().name());
LookupJoinExec lookupJoinExec = as(fieldExtractExec.child(), LookupJoinExec.class); // this is why the rule doesn't apply
// lhs of lookup join
fieldExtractExec = as(lookupJoinExec.left(), FieldExtractExec.class);
attributes = fieldExtractExec.attributesToExtract();
assertEquals(1, attributes.size());
assertEquals("integer", attributes.getFirst().name());
EsQueryExec esQueryExec = as(fieldExtractExec.child(), EsQueryExec.class);
assertEquals("test", esQueryExec.indexPattern());
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
assertEquals(1, queryBuilderAndTags.size());
EsQueryExec.QueryBuilderAndTags queryBuilder = queryBuilderAndTags.getFirst();
assertNull(queryBuilder.query());
assertTrue(queryBuilder.tags().isEmpty());
assertNull(esQueryExec.query());
// rhs of lookup join
FragmentExec fragmentExec = as(lookupJoinExec.right(), FragmentExec.class);
EsRelation esRelation = as(fragmentExec.fragment(), EsRelation.class);
assertTrue(esRelation.toString().contains("EsRelation[languages_lookup][LOOKUP]"));
}
}
// ReplaceRoundToWithQueryAndTags does not support lookup joins yet
public void testDateTruncBucketNotTransformToQueryAndTagsWithFork() {
for (String dateHistogram : dateHistograms) {
String query = LoggerMessageFormat.format(null, """
from test
| fork (where integer > 100)
(where keyword : "keyword")
| stats count(*) by x = {}
""", dateHistogram);
PhysicalPlan plan = plannerOptimizer.plan(query, searchStats, makeAnalyzer("mapping-all-types.json"));
LimitExec limit = as(plan, LimitExec.class);
AggregateExec agg = as(limit.child(), AggregateExec.class);
assertThat(agg.getMode(), is(SINGLE));
List<? extends Expression> groupings = agg.groupings();
NamedExpression grouping = as(groupings.getFirst(), NamedExpression.class);
assertEquals("x", grouping.name());
assertEquals(DataType.DATETIME, grouping.dataType());
assertEquals(List.of("count(*)", "x"), Expressions.names(agg.aggregates()));
EvalExec eval = as(agg.child(), EvalExec.class);
List<Alias> aliases = eval.fields();
assertEquals(1, aliases.size());
var function = as(aliases.getFirst().child(), Function.class);
ReferenceAttribute fa = null; // if merge returns FieldAttribute instead of ReferenceAttribute, the rule might apply
if (function instanceof DateTrunc dateTrunc) {
fa = as(dateTrunc.field(), ReferenceAttribute.class);
} else if (function instanceof Bucket bucket) {
fa = as(bucket.field(), ReferenceAttribute.class);
} else if (function instanceof RoundTo roundTo) {
fa = as(roundTo.field(), ReferenceAttribute.class);
}
assertNotNull(fa);
assertEquals("date", fa.name());
assertEquals(DataType.DATETIME, fa.dataType());
as(eval.child(), MergeExec.class);
}
}
/**
* If the number of rounding points is 127 or less, the query is rewritten to QueryAndTags.
* If the number of rounding points is 128 or more, the query is not rewritten.
*/
public void testRoundToTransformToQueryAndTagsWithDefaultUpperLimit() {
for (int numOfPoints : List.of(127, 128)) {
StringBuilder points = new StringBuilder();
for (int i = 0; i < numOfPoints; i++) {
if (i > 0) {
points.append(", ");
}
points.append(i);
}
String query = LoggerMessageFormat.format(null, """
from test
| stats count(*) by x = round_to(integer, {})
""", points.toString());
ExchangeExec exchange = validatePlanBeforeExchange(query, DataType.INTEGER);
if (numOfPoints == 127) {
var queryBuilderAndTags = getBuilderAndTagsFromStats(exchange, DataType.INTEGER);
assertThat(queryBuilderAndTags, hasSize(128)); // 127 + nullBucket
} else { // numOfPoints == 128, query rewrite does not happen
AggregateExec agg = as(exchange.child(), AggregateExec.class);
EvalExec evalExec = as(agg.child(), EvalExec.class);
List<Alias> aliases = evalExec.fields();
assertEquals(1, aliases.size());
RoundTo roundTo = as(aliases.getFirst().child(), RoundTo.class);
assertEquals(128, roundTo.points().size());
FieldExtractExec fieldExtractExec = as(evalExec.child(), FieldExtractExec.class);
EsQueryExec esQueryExec = as(fieldExtractExec.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
assertEquals(1, queryBuilderAndTags.size());
EsQueryExec.QueryBuilderAndTags queryBuilder = queryBuilderAndTags.getFirst();
assertNull(queryBuilder.query());
assertTrue(queryBuilder.tags().isEmpty());
assertNull(esQueryExec.query());
}
}
}
private static List<EsQueryExec.QueryBuilderAndTags> getBuilderAndTagsFromStats(ExchangeExec exchange, DataType aggregateType) {
FilterExec filter = as(exchange.child(), FilterExec.class);
GreaterThan condition = as(filter.condition(), GreaterThan.class);
Literal literal = as(condition.right(), Literal.class);
assertThat(literal.value(), is(0L));
EsStatsQueryExec statsQueryExec = as(filter.child(), EsStatsQueryExec.class);
assertThat(
statsQueryExec.output().stream().map(Attribute::dataType).toList(),
equalTo(List.of(aggregateType, DataType.LONG, DataType.BOOLEAN))
);
var left = as(condition.left(), ReferenceAttribute.class);
assertThat(left.id(), is(statsQueryExec.output().get(1).id()));
return as(statsQueryExec.stat(), EsStatsQueryExec.ByStat.class).queryBuilderAndTags();
}
/**
* Query level threshold(if greater than -1) set in QueryPragmas overrides the cluster level threshold set in EsqlFlags.
*/
public void testRoundToTransformToQueryAndTagsWithCustomizedUpperLimit() {
for (int clusterLevelThreshold : List.of(-1, 0, 60, 126, 128, 256)) {
for (int queryLevelThreshold : List.of(-1, 0, 60, 126, 128, 256)) {
StringBuilder points = new StringBuilder(); // there are 127 rounding points
for (int i = 0; i < 127; i++) {
if (i > 0) {
points.append(", ");
}
points.append(i);
}
String query = LoggerMessageFormat.format(null, """
from test
| stats count(*) by x = round_to(integer, {})
""", points.toString());
TestPlannerOptimizer plannerOptimizerWithPragmas = new TestPlannerOptimizer(
configuration(
new QueryPragmas(
Settings.builder()
.put(QueryPragmas.ROUNDTO_PUSHDOWN_THRESHOLD.getKey().toLowerCase(Locale.ROOT), queryLevelThreshold)
.build()
),
query
),
makeAnalyzer("mapping-all-types.json")
);
EsqlFlags esqlFlags = new EsqlFlags(clusterLevelThreshold);
assertEquals(clusterLevelThreshold, esqlFlags.roundToPushdownThreshold());
assertTrue(esqlFlags.stringLikeOnIndex());
boolean pushdown;
if (queryLevelThreshold > -1) {
pushdown = queryLevelThreshold >= 127;
} else {
pushdown = clusterLevelThreshold >= 127;
}
ExchangeExec exchange = validatePlanBeforeExchange(
plannerOptimizerWithPragmas.plan(query, searchStats, esqlFlags),
DataType.INTEGER,
List.of("count(*)")
);
if (pushdown) {
var queryBuilderAndTags = getQueryBuilderAndTags(exchange);
assertThat(queryBuilderAndTags, hasSize(128)); // 127 + nullBucket
} else { // query rewrite does not happen
AggregateExec agg = as(exchange.child(), AggregateExec.class);
EvalExec evalExec = as(agg.child(), EvalExec.class);
List<Alias> aliases = evalExec.fields();
assertEquals(1, aliases.size());
RoundTo roundTo = as(aliases.getFirst().child(), RoundTo.class);
assertEquals(127, roundTo.points().size());
FieldExtractExec fieldExtractExec = as(evalExec.child(), FieldExtractExec.class);
EsQueryExec esQueryExec = as(fieldExtractExec.child(), EsQueryExec.class);
List<EsQueryExec.QueryBuilderAndTags> queryBuilderAndTags = esQueryExec.queryBuilderAndTags();
assertEquals(1, queryBuilderAndTags.size());
EsQueryExec.QueryBuilderAndTags queryBuilder = queryBuilderAndTags.getFirst();
assertNull(queryBuilder.query());
assertTrue(queryBuilder.tags().isEmpty());
assertNull(esQueryExec.query());
}
}
}
}
private static List<EsQueryExec.QueryBuilderAndTags> getQueryBuilderAndTags(ExchangeExec exchange) {
return getBuilderAndTagsFromStats(exchange, DataType.INTEGER);
}
private ExchangeExec validatePlanBeforeExchange(String query, DataType aggregateType) {
return validatePlanBeforeExchange(query, aggregateType, List.of("count(*)"));
}
private ExchangeExec validatePlanBeforeExchange(String query, DataType aggregateType, List<String> aggregation) {
return validatePlanBeforeExchange(query, aggregateType, aggregation, null);
}
private ExchangeExec validatePlanBeforeExchange(
String query,
DataType aggregateType,
List<String> aggregation,
@Nullable QueryBuilder esFilter
) {
return validatePlanBeforeExchange(
plannerOptimizer.plan(query, searchStats, makeAnalyzer("mapping-all-types.json"), esFilter),
aggregateType,
aggregation
);
}
private static ExchangeExec validatePlanBeforeExchange(PhysicalPlan plan, DataType aggregateType, List<String> aggregation) {
LimitExec limit = as(plan, LimitExec.class);
AggregateExec agg = as(limit.child(), AggregateExec.class);
assertThat(agg.getMode(), is(FINAL));
List<? extends Expression> groupings = agg.groupings();
NamedExpression grouping = as(groupings.getFirst(), NamedExpression.class);
assertEquals("x", grouping.name());
assertEquals(aggregateType, grouping.dataType());
assertEquals(CollectionUtils.appendToCopy(aggregation, "x"), Expressions.names(agg.aggregates()));
ExchangeExec exchange = as(agg.child(), ExchangeExec.class);
assertThat(exchange.inBetweenAggs(), is(true));
return exchange;
}
private static String pointArray(int numPoints) {
return IntStream.range(0, numPoints).mapToObj(Integer::toString).collect(Collectors.joining(","));
}
private static int plainQueryAndTags(PhysicalPlan plan) {
EsQueryExec esQuery = (EsQueryExec) plan.collectFirstChildren(EsQueryExec.class::isInstance).getFirst();
return esQuery.queryBuilderAndTags().size();
}
private static int statsQueryAndTags(PhysicalPlan plan) {
EsStatsQueryExec esQuery = (EsStatsQueryExec) plan.collectFirstChildren(EsStatsQueryExec.class::isInstance).getFirst();
return ((EsStatsQueryExec.ByStat) esQuery.stat()).queryBuilderAndTags().size();
}
public void testAdjustThresholdForQueries() {
{
int points = between(2, 127);
String q = String.format(Locale.ROOT, """
from test
| stats count(*) by x = round_to(integer, %s)
""", pointArray(points));
PhysicalPlan plan = plannerOptimizer.plan(q, searchStats, makeAnalyzer("mapping-all-types.json"));
int queryAndTags = statsQueryAndTags(plan);
assertThat(queryAndTags, equalTo(points + 1)); // include null bucket
}
{
int points = between(2, 64);
String q = String.format(Locale.ROOT, """
from test
| where date >= "2023-10-19"
| stats count(*) by x = round_to(integer, %s)
""", pointArray(points));
var plan = plannerOptimizer.plan(q, searchStats, makeAnalyzer("mapping-all-types.json"));
int queryAndTags = plainQueryAndTags(plan);
assertThat(queryAndTags, equalTo(points + 1)); // include null bucket
}
{
int points = between(65, 128);
String q = String.format(Locale.ROOT, """
from test
| where date >= "2023-10-19"
| stats count(*) by x = round_to(integer, %s)
""", pointArray(points));
var plan = plannerOptimizer.plan(q, searchStats, makeAnalyzer("mapping-all-types.json"));
int queryAndTags = plainQueryAndTags(plan);
assertThat(queryAndTags, equalTo(1)); // no rewrite
}
{
int points = between(2, 19);
String q = String.format(Locale.ROOT, """
from test
| where date >= "2023-10-19"
| where keyword LIKE "w*"
| stats count(*) by x = round_to(integer, %s)
""", pointArray(points));
var plan = plannerOptimizer.plan(q, searchStats, makeAnalyzer("mapping-all-types.json"));
int queryAndTags = plainQueryAndTags(plan);
assertThat("points=" + points, queryAndTags, equalTo(points + 1)); // include null bucket
}
{
int points = between(20, 128);
String q = String.format(Locale.ROOT, """
from test
| where date >= "2023-10-19"
| where keyword LIKE "*w*"
| stats count(*) by x = round_to(integer, %s)
""", pointArray(points));
PhysicalPlan plan = plannerOptimizer.plan(q, searchStats, makeAnalyzer("mapping-all-types.json"));
int queryAndTags = plainQueryAndTags(plan);
assertThat("points=" + points, queryAndTags, equalTo(1)); // no rewrite
}
}
private static void verifyQueryAndTags(List<EsQueryExec.QueryBuilderAndTags> expected, List<EsQueryExec.QueryBuilderAndTags> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
EsQueryExec.QueryBuilderAndTags expectedItem = expected.get(i);
EsQueryExec.QueryBuilderAndTags actualItem = actual.get(i);
assertEquals(expectedItem.query().toString(), actualItem.query().toString());
assertEquals(expectedItem.tags().getFirst(), actualItem.tags().getFirst());
}
}
private static List<EsQueryExec.QueryBuilderAndTags> expectedQueryBuilderAndTags(
String query,
String fieldName,
List<Object> roundingPoints,
Source source,
QueryBuilder mainQueryBuilder
) {
List<EsQueryExec.QueryBuilderAndTags> expected = new ArrayList<>(5);
boolean isDateField = fieldName.equals("date");
boolean isDateNanosField = fieldName.equals("date_nanos");
boolean isNumericField = (isDateField || isDateNanosField) == false;
List<List<Object>> rangeAndTags = isNumericField ? numericBuckets(roundingPoints) : dateBuckets(isDateField);
for (List<Object> rangeAndTag : rangeAndTags) {
Object lower = rangeAndTag.get(0);
Object upper = rangeAndTag.get(1);
Object tag = rangeAndTag.get(2);
RangeQueryBuilder rangeQueryBuilder;
if (isNumericField) {
rangeQueryBuilder = rangeQuery(fieldName).boost(0);
} else if (isDateField) { // date
rangeQueryBuilder = rangeQuery(fieldName).boost(0).timeZone("Z").format(DEFAULT_DATE_TIME_FORMATTER.pattern());
} else { // date_nanos
rangeQueryBuilder = rangeQuery(fieldName).boost(0).timeZone("Z").format(DEFAULT_DATE_NANOS_FORMATTER.pattern());
}
if (upper != null) {
rangeQueryBuilder = rangeQueryBuilder.lt(upper);
}
if (lower != null) {
rangeQueryBuilder = rangeQueryBuilder.gte(lower);
}
QueryBuilder qb = wrapWithSingleQuery(query, rangeQueryBuilder, fieldName, source);
if (mainQueryBuilder != null) {
qb = boolQuery().filter(mainQueryBuilder).filter(qb);
}
expected.add(new EsQueryExec.QueryBuilderAndTags(qb, List.of(tag)));
}
// add null bucket
BoolQueryBuilder isNullQueryBuilder = boolQuery().mustNot(existsQuery(fieldName).boost(0));
List<Object> nullTags = new ArrayList<>(1);
nullTags.add(null);
if (mainQueryBuilder != null) {
isNullQueryBuilder = boolQuery().filter(mainQueryBuilder).filter(isNullQueryBuilder.boost(0));
}
expected.add(new EsQueryExec.QueryBuilderAndTags(isNullQueryBuilder, nullTags));
return expected;
}
private static List<List<Object>> dateBuckets(boolean isDate) {
// Date rounding points
String[] dates = { "2023-10-20T00:00:00.000Z", "2023-10-21T00:00:00.000Z", "2023-10-22T00:00:00.000Z", "2023-10-23T00:00:00.000Z" };
// first bucket has no lower bound
List<Object> firstBucket = new ArrayList<>(3);
firstBucket.add(null);
firstBucket.add(dates[1]);
firstBucket.add(isDate ? dateTimeToLong(dates[0]) : dateNanosToLong(dates[0]));
// last bucket has no upper bound
List<Object> lastBucket = new ArrayList<>(3);
lastBucket.add(dates[3]);
lastBucket.add(null);
lastBucket.add(isDate ? dateTimeToLong(dates[3]) : dateNanosToLong(dates[3]));
return List.of(
firstBucket,
List.of(dates[1], dates[2], isDate ? dateTimeToLong(dates[1]) : dateNanosToLong(dates[1])),
List.of(dates[2], dates[3], isDate ? dateTimeToLong(dates[2]) : dateNanosToLong(dates[2])),
lastBucket
);
}
private static List<List<Object>> numericBuckets(List<Object> roundingPoints) {
// sort the rounding points in ascending order
roundingPoints = roundingPoints.stream().sorted().collect(Collectors.toList());
Object p1 = roundingPoints.get(0);
Object p2 = roundingPoints.get(1);
Object p3 = roundingPoints.get(2);
Object p4 = roundingPoints.get(3);
// first bucket has no lower bound
List<Object> firstBucket = new ArrayList<>(3);
firstBucket.add(null);
firstBucket.add(p2);
firstBucket.add(p1);
// last bucket has no upper bound
List<Object> lastBucket = new ArrayList<>(3);
lastBucket.add(p4);
lastBucket.add(null);
lastBucket.add(p4);
return List.of(firstBucket, List.of(p2, p3, p2), List.of(p3, p4, p3), lastBucket);
}
public void testForkWithStatsCountStarDateTrunc() {
String query = """
from test
| fork (stats x = count(*), y = max(long) by hd = date_trunc(1 day, date))
(stats x = count(*), y = min(long) by hd = date_trunc(2 day, date))
""";
PhysicalPlan plan = plannerOptimizer.plan(query, searchStats, makeAnalyzer("mapping-all-types.json"));
LimitExec limit = as(plan, LimitExec.class);
MergeExec merge = as(limit.child(), MergeExec.class);
List<PhysicalPlan> mergeChildren = merge.children();
assertThat(mergeChildren, hasSize(2));
PhysicalPlan firstBranch = mergeChildren.get(0);
ProjectExec firstProject = as(firstBranch, ProjectExec.class);
EvalExec firstEval = as(firstProject.child(), EvalExec.class);
LimitExec firstLimit = as(firstEval.child(), LimitExec.class);
AggregateExec firstFinalAgg = as(firstLimit.child(), AggregateExec.class);
assertThat(firstFinalAgg.getMode(), is(FINAL));
var firstGroupings = firstFinalAgg.groupings();
assertThat(firstGroupings, hasSize(1));
NamedExpression firstGrouping = as(firstGroupings.getFirst(), NamedExpression.class);
assertThat(firstGrouping.name(), is("hd"));
assertThat(firstGrouping.dataType(), is(DataType.DATETIME));
assertThat(Expressions.names(firstFinalAgg.aggregates()), is(List.of("x", "y", "hd")));
ExchangeExec firstExchange = as(firstFinalAgg.child(), ExchangeExec.class);
assertThat(firstExchange.inBetweenAggs(), is(true));
AggregateExec firstInitialAgg = as(firstExchange.child(), AggregateExec.class);
FieldExtractExec firstFieldExtract = as(firstInitialAgg.child(), FieldExtractExec.class);
EvalExec firstDateTruncEval = as(firstFieldExtract.child(), EvalExec.class);
as(firstDateTruncEval.child(), EsQueryExec.class);
PhysicalPlan secondBranch = mergeChildren.get(1);
ProjectExec secondProject = as(secondBranch, ProjectExec.class);
EvalExec secondEval = as(secondProject.child(), EvalExec.class);
LimitExec secondLimit = as(secondEval.child(), LimitExec.class);
AggregateExec secondFinalAgg = as(secondLimit.child(), AggregateExec.class);
assertThat(secondFinalAgg.getMode(), is(FINAL));
var secondGroupings = secondFinalAgg.groupings();
assertThat(secondGroupings, hasSize(1));
NamedExpression secondGrouping = as(secondGroupings.getFirst(), NamedExpression.class);
assertThat(secondGrouping.name(), is("hd"));
assertThat(secondGrouping.dataType(), is(DataType.DATETIME));
assertThat(Expressions.names(secondFinalAgg.aggregates()), is(List.of("x", "y", "hd")));
ExchangeExec secondExchange = as(secondFinalAgg.child(), ExchangeExec.class);
assertThat(secondExchange.inBetweenAggs(), is(true));
AggregateExec secondInitialAgg = as(secondExchange.child(), AggregateExec.class);
FieldExtractExec secondFieldExtract = as(secondInitialAgg.child(), FieldExtractExec.class);
EvalExec secondDateTruncEval = as(secondFieldExtract.child(), EvalExec.class);
FieldExtractExec secondDateFieldExtract = as(secondDateTruncEval.child(), FieldExtractExec.class);
as(secondDateFieldExtract.child(), EsQueryExec.class);
}
public void testSubqueryWithCountStarAndDateTrunc() {
assumeTrue("requires subqueries in from", EsqlCapabilities.Cap.SUBQUERY_IN_FROM_COMMAND.isEnabled());
String query = """
from test, (from test | stats cnt = count(*) by x = date_trunc(1 day, date))
| keep x, cnt, date
""";
PhysicalPlan plan = plannerOptimizer.plan(query, searchStats, makeAnalyzer("mapping-all-types.json"));
ProjectExec project = as(plan, ProjectExec.class);
LimitExec limit = as(project.child(), LimitExec.class);
MergeExec merge = as(limit.child(), MergeExec.class);
List<PhysicalPlan> mergeChildren = merge.children();
assertThat(mergeChildren, hasSize(2));
PhysicalPlan leftBranch = mergeChildren.get(0);
ProjectExec leftProject = as(leftBranch, ProjectExec.class);
EvalExec leftEval = as(leftProject.child(), EvalExec.class);
LimitExec leftLimit = as(leftEval.child(), LimitExec.class);
ExchangeExec leftExchange = as(leftLimit.child(), ExchangeExec.class);
ProjectExec leftInnerProject = as(leftExchange.child(), ProjectExec.class);
FieldExtractExec leftFieldExtract = as(leftInnerProject.child(), FieldExtractExec.class);
as(leftFieldExtract.child(), EsQueryExec.class);
PhysicalPlan rightBranch = mergeChildren.get(1);
ProjectExec subqueryProject = as(rightBranch, ProjectExec.class);
EvalExec subqueryEval = as(subqueryProject.child(), EvalExec.class);
LimitExec subqueryLimit = as(subqueryEval.child(), LimitExec.class);
AggregateExec finalAgg = as(subqueryLimit.child(), AggregateExec.class);
assertThat(finalAgg.getMode(), is(FINAL));
var groupings = finalAgg.groupings();
assertThat(groupings, hasSize(1));
ExchangeExec partialExchange = as(finalAgg.child(), ExchangeExec.class);
assertThat(partialExchange.inBetweenAggs(), is(true));
FilterExec filter = as(partialExchange.child(), FilterExec.class);
EsStatsQueryExec statsQueryExec = as(filter.child(), EsStatsQueryExec.class);
assertThat(statsQueryExec.stat(), is(instanceOf(EsStatsQueryExec.ByStat.class)));
EsStatsQueryExec.ByStat byStat = (EsStatsQueryExec.ByStat) statsQueryExec.stat();
assertThat(byStat.queryBuilderAndTags(), is(not(empty())));
}
private static SearchStats searchStats() {
// create a SearchStats with min and max in milliseconds
Map<String, Object> minValue = Map.of("date", 1697804103360L); // 2023-10-20T12:15:03.360Z
Map<String, Object> maxValue = Map.of("date", 1698069301543L); // 2023-10-23T13:55:01.543Z
return new EsqlTestUtils.TestSearchStatsWithMinMax(minValue, maxValue);
}
}
| SubstituteRoundToTests |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/selectkey/Name.java | {
"start": 705,
"end": 1199
} | class ____ {
private int nameId;
private String name;
private String generatedName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNameId() {
return nameId;
}
public void setNameId(int nameId) {
this.nameId = nameId;
}
public String getGeneratedName() {
return generatedName;
}
public void setGeneratedName(String generatedName) {
this.generatedName = generatedName;
}
}
| Name |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/TempDirectory.java | {
"start": 3468,
"end": 3717
} | class ____, lifecycle method, or test method is annotated with
* {@code @TempDir}.
*
* <p>Consult the Javadoc for {@link TempDir} for details on the contract.
*
* @since 5.4
* @see TempDir @TempDir
* @see Files#createTempDirectory
*/
| constructor |
java | elastic__elasticsearch | plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextFieldMapperTests.java | {
"start": 3148,
"end": 31961
} | class ____ extends MapperTestCase {
@Override
protected Collection<Plugin> getPlugins() {
return Collections.singletonList(new AnnotatedTextPlugin());
}
@Override
protected void minimalMapping(XContentBuilder b) throws IOException {
b.field("type", "annotated_text");
}
@Override
protected Object getSampleValueForDocument() {
return "some text";
}
@Override
protected void registerParameters(ParameterChecker checker) throws IOException {
checker.registerUpdateCheck(b -> {
b.field("analyzer", "default");
b.field("search_analyzer", "keyword");
}, m -> assertEquals("keyword", m.fieldType().getTextSearchInfo().searchAnalyzer().name()));
checker.registerUpdateCheck(b -> {
b.field("analyzer", "default");
b.field("search_analyzer", "keyword");
b.field("search_quote_analyzer", "keyword");
}, m -> assertEquals("keyword", m.fieldType().getTextSearchInfo().searchQuoteAnalyzer().name()));
checker.registerConflictCheck("store", b -> b.field("store", true));
checker.registerConflictCheck("index_options", b -> b.field("index_options", "docs"));
checker.registerConflictCheck("similarity", b -> b.field("similarity", "boolean"));
checker.registerConflictCheck("analyzer", b -> b.field("analyzer", "keyword"));
checker.registerConflictCheck("term_vector", b -> b.field("term_vector", "yes"));
checker.registerConflictCheck("position_increment_gap", b -> b.field("position_increment_gap", 10));
// norms can be set from true to false, but not vice versa
checker.registerConflictCheck("norms", fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("norms", false);
}), fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("norms", true);
}));
checker.registerUpdateCheck(b -> {
b.field("type", "annotated_text");
b.field("norms", true);
}, b -> {
b.field("type", "annotated_text");
b.field("norms", false);
}, m -> assertFalse(m.fieldType().getTextSearchInfo().hasNorms()));
}
@Override
protected IndexAnalyzers createIndexAnalyzers(IndexSettings indexSettings) {
NamedAnalyzer dflt = new NamedAnalyzer(
"default",
AnalyzerScope.INDEX,
new StandardAnalyzer(),
TextFieldMapper.Defaults.POSITION_INCREMENT_GAP
);
NamedAnalyzer standard = new NamedAnalyzer("standard", AnalyzerScope.INDEX, new StandardAnalyzer());
NamedAnalyzer keyword = new NamedAnalyzer("keyword", AnalyzerScope.INDEX, new KeywordAnalyzer());
NamedAnalyzer whitespace = new NamedAnalyzer("whitespace", AnalyzerScope.INDEX, new WhitespaceAnalyzer());
NamedAnalyzer stop = new NamedAnalyzer(
"my_stop_analyzer",
AnalyzerScope.INDEX,
new CustomAnalyzer(
new StandardTokenizerFactory(indexSettings, null, "standard", indexSettings.getSettings()),
new CharFilterFactory[0],
new TokenFilterFactory[] { new TokenFilterFactory() {
@Override
public String name() {
return "stop";
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new StopFilter(tokenStream, EnglishAnalyzer.ENGLISH_STOP_WORDS_SET);
}
} }
)
);
return IndexAnalyzers.of(
Map.of("default", dflt, "standard", standard, "keyword", keyword, "whitespace", whitespace, "my_stop_analyzer", stop),
Map.of("lowercase", new NamedAnalyzer("lowercase", AnalyzerScope.INDEX, new LowercaseNormalizer()))
);
}
public void testAnnotationInjection() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(this::minimalMapping));
// Use example of typed and untyped annotations
String annotatedText = "He paid [Stormy Daniels](Stephanie+Clifford&Payee) hush money";
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.field("field", annotatedText)));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.size());
assertEquals(annotatedText, fields.get(0).stringValue());
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
LeafReader leaf = reader.leaves().get(0).reader();
TermsEnum terms = leaf.terms("field").iterator();
assertTrue(terms.seekExact(new BytesRef("stormy")));
PostingsEnum postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(2, postings.nextPosition());
assertTrue(terms.seekExact(new BytesRef("Stephanie Clifford")));
postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(2, postings.nextPosition());
assertTrue(terms.seekExact(new BytesRef("Payee")));
postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(2, postings.nextPosition());
assertTrue(terms.seekExact(new BytesRef("hush")));
postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(4, postings.nextPosition());
});
}
public void testToleranceForBadAnnotationMarkup() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(this::minimalMapping));
String annotatedText = "foo [bar](MissingEndBracket baz";
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.field("field", annotatedText)));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.size());
assertEquals(annotatedText, fields.get(0).stringValue());
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
LeafReader leaf = reader.leaves().get(0).reader();
TermsEnum terms = leaf.terms("field").iterator();
assertTrue(terms.seekExact(new BytesRef("foo")));
PostingsEnum postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(0, postings.nextPosition());
assertTrue(terms.seekExact(new BytesRef("bar")));
postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(1, postings.nextPosition());
assertFalse(terms.seekExact(new BytesRef("MissingEndBracket")));
// Bad markup means value is treated as plain text and fed through tokenisation
assertTrue(terms.seekExact(new BytesRef("missingendbracket")));
});
}
public void testIndexedTermVectors() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("term_vector", "with_positions_offsets_payloads");
}));
String text = "the quick [brown](Color) fox jumped over the lazy dog";
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.field("field", text)));
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
LeafReader leaf = reader.leaves().get(0).reader();
Terms terms = leaf.termVectors().get(0, "field");
TermsEnum iterator = terms.iterator();
BytesRef term;
Set<String> foundTerms = new HashSet<>();
while ((term = iterator.next()) != null) {
foundTerms.add(term.utf8ToString());
}
// Check we have both text and annotation tokens
assertTrue(foundTerms.contains("brown"));
assertTrue(foundTerms.contains("Color"));
assertTrue(foundTerms.contains("fox"));
});
}
public void testDefaults() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(this::minimalMapping));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.size());
assertEquals("1234", fields.get(0).stringValue());
IndexableFieldType fieldType = fields.get(0).fieldType();
assertThat(fieldType.omitNorms(), equalTo(false));
assertTrue(fieldType.tokenized());
assertFalse(fieldType.stored());
assertThat(fieldType.indexOptions(), equalTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS));
assertThat(fieldType.storeTermVectors(), equalTo(false));
assertThat(fieldType.storeTermVectorOffsets(), equalTo(false));
assertThat(fieldType.storeTermVectorPositions(), equalTo(false));
assertThat(fieldType.storeTermVectorPayloads(), equalTo(false));
assertEquals(DocValuesType.NONE, fieldType.docValuesType());
}
public void testEnableStore() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("store", true);
}));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.size());
assertTrue(fields.get(0).fieldType().stored());
}
public void testStoreParameterDefaultsToFalse() throws IOException {
// given
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> { b.field("type", "annotated_text"); }));
// when
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
// then
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertFalse(fields.getFirst().fieldType().stored());
}
public void testStoreParameterDefaultsToFalseWhenSyntheticSourceIsEnabled() throws IOException {
// given
var indexSettings = getIndexSettingsBuilder().put(IndexSettings.INDEX_MAPPER_SOURCE_MODE_SETTING.getKey(), "synthetic").build();
DocumentMapper mapper = createMapperService(indexSettings, fieldMapping(b -> { b.field("type", "annotated_text"); }))
.documentMapper();
// when
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
// then
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertFalse(fields.getFirst().fieldType().stored());
}
public void testStoreParameterDefaultsWhenIndexVersionIsNotLatest() throws IOException {
var timeSeriesIndexMode = randomBoolean();
var isStored = randomBoolean();
var hasKeywordFieldForSyntheticSource = randomBoolean();
var indexSettingsBuilder = getIndexSettingsBuilder();
if (timeSeriesIndexMode) {
indexSettingsBuilder.put(IndexSettings.MODE.getKey(), IndexMode.TIME_SERIES)
.putList(IndexMetadata.INDEX_ROUTING_PATH.getKey(), "dimension")
.put(IndexSettings.TIME_SERIES_START_TIME.getKey(), "2000-01-08T23:40:53.384Z")
.put(IndexSettings.TIME_SERIES_END_TIME.getKey(), "2106-01-08T23:40:53.384Z");
}
var indexSettings = indexSettingsBuilder.build();
var mapping = mapping(b -> {
b.startObject("field");
b.field("type", "annotated_text");
if (isStored) {
b.field("store", isStored);
}
if (hasKeywordFieldForSyntheticSource) {
b.startObject("fields");
b.startObject("keyword");
b.field("type", "keyword");
b.endObject();
b.endObject();
}
b.endObject();
if (timeSeriesIndexMode) {
b.startObject("@timestamp");
b.field("type", "date");
b.endObject();
b.startObject("dimension");
b.field("type", "keyword");
b.field("time_series_dimension", "true");
b.endObject();
}
});
IndexVersion bwcIndexVersion = IndexVersions.MAPPER_TEXT_MATCH_ONLY_MULTI_FIELDS_DEFAULT_NOT_STORED;
DocumentMapper mapper = createMapperService(bwcIndexVersion, indexSettings, () -> true, mapping).documentMapper();
var source = source(TimeSeriesRoutingHashFieldMapper.DUMMY_ENCODED_VALUE, b -> {
b.field("field", "1234");
if (timeSeriesIndexMode) {
b.field("@timestamp", "2000-10-10T23:40:53.384Z");
b.field("dimension", "dimension1");
}
}, null);
ParsedDocument doc = mapper.parse(source);
List<IndexableField> fields = doc.rootDoc().getFields("field");
IndexableFieldType fieldType = fields.get(0).fieldType();
if (isStored || (timeSeriesIndexMode && hasKeywordFieldForSyntheticSource == false)) {
assertTrue(fieldType.stored());
} else {
assertFalse(fieldType.stored());
}
}
public void testDisableNorms() throws IOException {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("norms", false);
}));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.size());
assertTrue(fields.get(0).fieldType().omitNorms());
}
public void testIndexOptions() throws IOException {
Map<String, IndexOptions> supportedOptions = new HashMap<>();
supportedOptions.put("docs", IndexOptions.DOCS);
supportedOptions.put("freqs", IndexOptions.DOCS_AND_FREQS);
supportedOptions.put("positions", IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
supportedOptions.put("offsets", IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
for (String option : supportedOptions.keySet()) {
DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("index_options", option);
}));
ParsedDocument doc = mapper.parse(source(b -> b.field("field", "1234")));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(1, fields.size());
assertEquals(supportedOptions.get(option), fields.get(0).fieldType().indexOptions());
}
}
public void testDefaultPositionIncrementGap() throws IOException {
MapperService mapperService = createMapperService(fieldMapping(this::minimalMapping));
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.array("field", "a", "b")));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(2, fields.size());
assertEquals("a", fields.get(0).stringValue());
assertEquals("b", fields.get(1).stringValue());
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
LeafReader leaf = reader.leaves().get(0).reader();
TermsEnum terms = leaf.terms("field").iterator();
assertTrue(terms.seekExact(new BytesRef("b")));
PostingsEnum postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(TextFieldMapper.Defaults.POSITION_INCREMENT_GAP + 1, postings.nextPosition());
});
}
public void testPositionIncrementGap() throws IOException {
final int positionIncrementGap = randomIntBetween(1, 1000);
MapperService mapperService = createMapperService(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("position_increment_gap", positionIncrementGap);
}));
ParsedDocument doc = mapperService.documentMapper().parse(source(b -> b.array("field", "a", "b")));
List<IndexableField> fields = doc.rootDoc().getFields("field");
assertEquals(2, fields.size());
assertEquals("a", fields.get(0).stringValue());
assertEquals("b", fields.get(1).stringValue());
withLuceneIndex(mapperService, iw -> iw.addDocument(doc.rootDoc()), reader -> {
LeafReader leaf = reader.leaves().get(0).reader();
TermsEnum terms = leaf.terms("field").iterator();
assertTrue(terms.seekExact(new BytesRef("b")));
PostingsEnum postings = terms.postings(null, PostingsEnum.POSITIONS);
assertEquals(0, postings.nextDoc());
assertEquals(positionIncrementGap + 1, postings.nextPosition());
});
}
public void testSearchAnalyzerSerialization() throws IOException {
String mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "standard")
.field("search_analyzer", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
);
DocumentMapper mapper = createDocumentMapper(mapping);
assertEquals(mapping, mapper.mappingSource().toString());
// special case: default index analyzer
mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "default")
.field("search_analyzer", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
);
mapper = createDocumentMapper(mapping);
assertEquals(mapping, mapper.mappingSource().toString());
mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
);
mapper = createDocumentMapper(mapping);
assertEquals(mapping, mapper.mappingSource().toString());
// special case: default search analyzer
mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "keyword")
.field("search_analyzer", "default")
.endObject()
.endObject()
.endObject()
.endObject()
);
mapper = createDocumentMapper(mapping);
assertEquals(mapping, mapper.mappingSource().toString());
mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
);
mapper = createDocumentMapper(mapping);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
mapper.mapping().toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("include_defaults", "true")));
builder.endObject();
String mappingString = Strings.toString(builder);
assertTrue(mappingString.contains("analyzer"));
assertTrue(mappingString.contains("search_analyzer"));
assertTrue(mappingString.contains("search_quote_analyzer"));
}
public void testSearchQuoteAnalyzerSerialization() throws IOException {
String mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "standard")
.field("search_analyzer", "standard")
.field("search_quote_analyzer", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
);
DocumentMapper mapper = createDocumentMapper(mapping);
assertEquals(mapping, mapper.mappingSource().toString());
// special case: default index/search analyzer
mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("field")
.field("type", "annotated_text")
.field("analyzer", "default")
.field("search_analyzer", "default")
.field("search_quote_analyzer", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
);
mapper = createDocumentMapper(mapping);
assertEquals(mapping, mapper.mappingSource().toString());
}
public void testTermVectors() throws IOException {
DocumentMapper defaultMapper = createDocumentMapper(mapping(b -> {
b.startObject("field1").field("type", "annotated_text").field("term_vector", "no").endObject();
b.startObject("field2").field("type", "annotated_text").field("term_vector", "yes").endObject();
b.startObject("field3").field("type", "annotated_text").field("term_vector", "with_offsets").endObject();
b.startObject("field4").field("type", "annotated_text").field("term_vector", "with_positions").endObject();
b.startObject("field5").field("type", "annotated_text").field("term_vector", "with_positions_offsets").endObject();
b.startObject("field6").field("type", "annotated_text").field("term_vector", "with_positions_offsets_payloads").endObject();
}));
ParsedDocument doc = defaultMapper.parse(source(b -> {
b.field("field1", "1234");
b.field("field2", "1234");
b.field("field3", "1234");
b.field("field4", "1234");
b.field("field5", "1234");
b.field("field6", "1234");
}));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectors(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorPayloads(), equalTo(true));
}
public void testNullConfigValuesFail() {
Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "annotated_text");
b.nullField("analyzer");
})));
assertThat(e.getMessage(), containsString("must not have a [null] value"));
}
public void testNotIndexedField() {
Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("index", false);
})));
assertEquals("Failed to parse mapping: unknown parameter [index] on mapper [field] of type [annotated_text]", e.getMessage());
}
public void testAnalyzedFieldPositionIncrementWithoutPositions() {
for (String indexOptions : Arrays.asList("docs", "freqs")) {
Exception e = expectThrows(MapperParsingException.class, () -> createMapperService(fieldMapping(b -> {
b.field("type", "annotated_text");
b.field("index_options", indexOptions);
b.field("position_increment_gap", 0);
})));
assertThat(e.getMessage(), containsString("Cannot set position_increment_gap on field [field] without positions enabled"));
}
}
@Override
protected Object generateRandomInputValue(MappedFieldType ft) {
assumeFalse("annotated_text doesn't have fielddata so we can't check against anything here.", true);
return null;
}
@Override
protected boolean supportsIgnoreMalformed() {
return false;
}
@Override
protected SyntheticSourceSupport syntheticSourceSupport(boolean ignoreMalformed) {
assumeFalse("ignore_malformed not supported", ignoreMalformed);
return TextFieldFamilySyntheticSourceTestSetup.syntheticSourceSupport("annotated_text", false);
}
@Override
protected void validateRoundTripReader(String syntheticSource, DirectoryReader reader, DirectoryReader roundTripReader) {
TextFieldFamilySyntheticSourceTestSetup.validateRoundTripReader(syntheticSource, reader, roundTripReader);
}
@Override
protected IngestScriptSupport ingestScriptSupport() {
throw new AssumptionViolatedException("not supported");
}
@Override
protected List<SortShortcutSupport> getSortShortcutSupport() {
return List.of();
}
@Override
protected boolean supportsDocValuesSkippers() {
return false;
}
}
| AnnotatedTextFieldMapperTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/runner/StoppedDispatcherLeaderProcess.java | {
"start": 1138,
"end": 1229
} | class ____ useful as the
* initial state of the {@link DefaultDispatcherRunner}.
*/
public | is |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/util/Holder.java | {
"start": 1082,
"end": 1255
} | class ____<T> {
public T held;
public Holder(T held) {
this.held = held;
}
@Override
public String toString() {
return String.valueOf(held);
}
}
| Holder |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/frommap/MapToBeanFromMapAndNestedSource.java | {
"start": 1516,
"end": 2045
} | class ____ {
private int integer;
private String stringFromNestedSource;
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
public String getStringFromNestedSource() {
return stringFromNestedSource;
}
public void setStringFromNestedSource(String stringFromNestedSource) {
this.stringFromNestedSource = stringFromNestedSource;
}
}
}
| Target |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanOverrideProcessorTests.java | {
"start": 6568,
"end": 6685
} | class ____ {
}
@MockitoBean(name = "bogus", types = { Integer.class, Float.class })
static | MissingTypesTestCase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/health/node/UpdateHealthInfoCacheAction.java | {
"start": 2217,
"end": 8543
} | class ____ extends HealthNodeRequest {
private final String nodeId;
@Nullable
private final DiskHealthInfo diskHealthInfo;
@Nullable
private final DataStreamLifecycleHealthInfo dslHealthInfo;
@Nullable
private final RepositoriesHealthInfo repositoriesHealthInfo;
@Nullable
private final FileSettingsService.FileSettingsHealthInfo fileSettingsHealthInfo;
public Request(
String nodeId,
DiskHealthInfo diskHealthInfo,
DataStreamLifecycleHealthInfo dslHealthInfo,
RepositoriesHealthInfo repositoriesHealthInfo,
@Nullable FileSettingsService.FileSettingsHealthInfo fileSettingsHealthInfo
) {
this.nodeId = nodeId;
this.diskHealthInfo = diskHealthInfo;
this.dslHealthInfo = dslHealthInfo;
this.repositoriesHealthInfo = repositoriesHealthInfo;
this.fileSettingsHealthInfo = fileSettingsHealthInfo;
}
public Request(String nodeId, DataStreamLifecycleHealthInfo dslHealthInfo) {
this.nodeId = nodeId;
this.diskHealthInfo = null;
this.repositoriesHealthInfo = null;
this.dslHealthInfo = dslHealthInfo;
this.fileSettingsHealthInfo = null;
}
public Request(String nodeId, FileSettingsService.FileSettingsHealthInfo info) {
this.nodeId = nodeId;
this.diskHealthInfo = null;
this.repositoriesHealthInfo = null;
this.dslHealthInfo = null;
this.fileSettingsHealthInfo = info;
}
public Request(StreamInput in) throws IOException {
super(in);
this.nodeId = in.readString();
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_12_0)) {
this.diskHealthInfo = in.readOptionalWriteable(DiskHealthInfo::new);
this.dslHealthInfo = in.readOptionalWriteable(DataStreamLifecycleHealthInfo::new);
this.repositoriesHealthInfo = in.getTransportVersion().onOrAfter(TransportVersions.V_8_13_0)
? in.readOptionalWriteable(RepositoriesHealthInfo::new)
: null;
this.fileSettingsHealthInfo = in.getTransportVersion().supports(FILE_SETTINGS_HEALTH_INFO)
? in.readOptionalWriteable(FileSettingsService.FileSettingsHealthInfo::new)
: null;
} else {
// BWC for pre-8.12 the disk health info was mandatory. Evolving this request has proven tricky however we've made use of
// waiting for all nodes to be on the {@link TransportVersions.HEALTH_INFO_ENRICHED_WITH_DSL_STATUS} transport version
// before sending any requests to update the health info that'd break the pre HEALTH_INFO_ENRICHED_WITH_DSL_STATUS
// transport invariant of always having a disk health information in the request
this.diskHealthInfo = new DiskHealthInfo(in);
this.dslHealthInfo = null;
this.repositoriesHealthInfo = null;
this.fileSettingsHealthInfo = null;
}
}
public String getNodeId() {
return nodeId;
}
public DiskHealthInfo getDiskHealthInfo() {
return diskHealthInfo;
}
public DataStreamLifecycleHealthInfo getDslHealthInfo() {
return dslHealthInfo;
}
public RepositoriesHealthInfo getRepositoriesHealthInfo() {
return repositoriesHealthInfo;
}
@Nullable
public FileSettingsService.FileSettingsHealthInfo getFileSettingsHealthInfo() {
return fileSettingsHealthInfo;
}
@Override
public ActionRequestValidationException validate() {
return null;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(nodeId);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_12_0)) {
out.writeOptionalWriteable(diskHealthInfo);
out.writeOptionalWriteable(dslHealthInfo);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_13_0)) {
out.writeOptionalWriteable(repositoriesHealthInfo);
}
if (out.getTransportVersion().supports(FILE_SETTINGS_HEALTH_INFO)) {
out.writeOptionalWriteable(fileSettingsHealthInfo);
}
} else {
// BWC for pre-8.12 the disk health info was mandatory. Evolving this request has proven tricky however we've made use of
// waiting for all nodes to be on the {@link TransportVersions.V_8_12_0} transport version
// before sending any requests to update the health info that'd break the pre-8.12
// transport invariant of always having a disk health information in the request
diskHealthInfo.writeTo(out);
}
}
@Override
public String getDescription() {
return String.format(
Locale.ROOT,
"Update health info cache for node [%s] with disk health info [%s], DSL health info [%s], repositories health info [%s].",
nodeId,
diskHealthInfo,
dslHealthInfo,
repositoriesHealthInfo
);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Request request = (Request) o;
return Objects.equals(nodeId, request.nodeId)
&& Objects.equals(diskHealthInfo, request.diskHealthInfo)
&& Objects.equals(dslHealthInfo, request.dslHealthInfo)
&& Objects.equals(repositoriesHealthInfo, request.repositoriesHealthInfo);
}
@Override
public int hashCode() {
return Objects.hash(nodeId, diskHealthInfo, dslHealthInfo, repositoriesHealthInfo);
}
public static | Request |
java | apache__camel | core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedShutdownStrategy.java | {
"start": 1206,
"end": 3689
} | class ____ extends ManagedService implements ManagedShutdownStrategyMBean {
private final ShutdownStrategy strategy;
public ManagedShutdownStrategy(CamelContext context, ShutdownStrategy controller) {
super(context, controller);
this.strategy = controller;
}
public ShutdownStrategy getShutdownStrategy() {
return strategy;
}
@Override
public void setTimeout(long timeout) {
strategy.setTimeout(timeout);
}
@Override
public long getTimeout() {
return strategy.getTimeout();
}
@Override
public void setTimeUnit(TimeUnit timeUnit) {
strategy.setTimeUnit(timeUnit);
}
@Override
public TimeUnit getTimeUnit() {
return strategy.getTimeUnit();
}
@Override
public void setSuppressLoggingOnTimeout(boolean suppressLoggingOnTimeout) {
strategy.setSuppressLoggingOnTimeout(suppressLoggingOnTimeout);
}
@Override
public boolean isSuppressLoggingOnTimeout() {
return strategy.isSuppressLoggingOnTimeout();
}
@Override
public void setShutdownNowOnTimeout(boolean shutdownNowOnTimeout) {
strategy.setShutdownNowOnTimeout(shutdownNowOnTimeout);
}
@Override
public boolean isShutdownNowOnTimeout() {
return strategy.isShutdownNowOnTimeout();
}
@Override
public void setShutdownRoutesInReverseOrder(boolean shutdownRoutesInReverseOrder) {
strategy.setShutdownRoutesInReverseOrder(shutdownRoutesInReverseOrder);
}
@Override
public boolean isShutdownRoutesInReverseOrder() {
return strategy.isShutdownRoutesInReverseOrder();
}
@Override
public void setLogInflightExchangesOnTimeout(boolean logInflightExchangesOnTimeout) {
strategy.setLogInflightExchangesOnTimeout(logInflightExchangesOnTimeout);
}
@Override
public boolean isLogInflightExchangesOnTimeout() {
return strategy.isLogInflightExchangesOnTimeout();
}
@Override
public boolean isForceShutdown() {
return strategy.isForceShutdown();
}
@Override
public boolean isTimeoutOccurred() {
return strategy.isTimeoutOccurred();
}
@Override
public String getLoggingLevel() {
return strategy.getLoggingLevel().toString();
}
@Override
public void setLoggingLevel(String loggingLevel) {
strategy.setLoggingLevel(LoggingLevel.valueOf(loggingLevel));
}
}
| ManagedShutdownStrategy |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctions.java | {
"start": 1287,
"end": 3499
} | class ____ {
/**
* Consume up to the specified number of bytes from the response body and
* cancel if any more data arrives.
* <p>Internally delegates to {@link DataBufferUtils#takeUntilByteCount}.
* @param maxByteCount the limit as number of bytes
* @return the filter to limit the response size with
* @since 5.1
*/
public static ExchangeFilterFunction limitResponseSize(long maxByteCount) {
return (request, next) ->
next.exchange(request).map(response ->
response.mutate()
.body(body -> DataBufferUtils.takeUntilByteCount(body, maxByteCount))
.build());
}
/**
* Return a filter that generates an error signal when the given
* {@link HttpStatusCode} predicate matches.
* @param statusPredicate the predicate to check the HTTP status with
* @param exceptionFunction the function to create the exception
* @return the filter to generate an error signal
*/
public static ExchangeFilterFunction statusError(Predicate<HttpStatusCode> statusPredicate,
Function<ClientResponse, ? extends Throwable> exceptionFunction) {
Assert.notNull(statusPredicate, "Predicate must not be null");
Assert.notNull(exceptionFunction, "Function must not be null");
return ExchangeFilterFunction.ofResponseProcessor(
response -> (statusPredicate.test(response.statusCode()) ?
Mono.error(exceptionFunction.apply(response)) : Mono.just(response)));
}
/**
* Return a filter that applies HTTP Basic Authentication to the request
* headers via {@link HttpHeaders#setBasicAuth(String)} and
* {@link HttpHeaders#encodeBasicAuth(String, String, Charset)}.
* @param username the username
* @param password the password
* @return the filter to add authentication headers with
* @see HttpHeaders#encodeBasicAuth(String, String, Charset)
* @see HttpHeaders#setBasicAuth(String)
*/
public static ExchangeFilterFunction basicAuthentication(String username, String password) {
String encodedCredentials = HttpHeaders.encodeBasicAuth(username, password, null);
return (request, next) ->
next.exchange(ClientRequest.from(request)
.headers(headers -> headers.setBasicAuth(encodedCredentials))
.build());
}
}
| ExchangeFilterFunctions |
java | redisson__redisson | redisson/src/test/java/org/redisson/executor/IncrementCallableTask.java | {
"start": 192,
"end": 673
} | class ____ implements Callable<String>, Serializable {
private String counterName;
@RInject
private RedissonClient redisson;
public IncrementCallableTask() {
}
public IncrementCallableTask(String counterName) {
super();
this.counterName = counterName;
}
@Override
public String call() throws Exception {
redisson.getAtomicLong(counterName).incrementAndGet();
return "1234";
}
}
| IncrementCallableTask |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng7804PluginExecutionOrderTest.java | {
"start": 1286,
"end": 2254
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that plugin executions are executed in order
*
* @throws Exception in case of failure
*/
@Test
void testOrder() throws Exception {
File testDir = extractResources("/mng-7804-plugin-execution-order");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.addCliArgument("clean");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> executions = verifier.loadLogLines().stream()
.filter(l -> l.contains(" This should be "))
.collect(Collectors.toList());
assertEquals(4, executions.size());
assertTrue(executions.get(0).contains("100"));
assertTrue(executions.get(1).contains("200"));
assertTrue(executions.get(2).contains("300"));
assertTrue(executions.get(3).contains("400"));
}
}
| MavenITmng7804PluginExecutionOrderTest |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java | {
"start": 56099,
"end": 57034
} | class ____ extends AbstractRouterFunction<ServerResponse> {
private final Function<ServerRequest, Mono<Resource>> lookupFunction;
private final BiConsumer<Resource, HttpHeaders> headersConsumer;
public ResourcesRouterFunction(Function<ServerRequest, Mono<Resource>> lookupFunction,
BiConsumer<Resource, HttpHeaders> headersConsumer) {
Assert.notNull(lookupFunction, "Function must not be null");
Assert.notNull(headersConsumer, "HeadersConsumer must not be null");
this.lookupFunction = lookupFunction;
this.headersConsumer = headersConsumer;
}
@Override
public Mono<HandlerFunction<ServerResponse>> route(ServerRequest request) {
return this.lookupFunction.apply(request)
.map(resource -> new ResourceHandlerFunction(resource, this.headersConsumer));
}
@Override
public void accept(Visitor visitor) {
visitor.resources(this.lookupFunction);
}
}
static final | ResourcesRouterFunction |
java | netty__netty | transport-native-io_uring/src/test/java/io/netty/channel/uring/IoUringBufferRingCompositeBufferGatheringWriteTest.java | {
"start": 1059,
"end": 1881
} | class ____ extends CompositeBufferGatheringWriteTest {
@BeforeAll
public static void loadJNI() {
assumeTrue(IoUring.isAvailable());
assumeTrue(IoUring.isRegisterBufferRingSupported());
}
@Override
protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() {
return IoUringSocketTestPermutation.INSTANCE.socket();
}
@Override
protected void configure(ServerBootstrap sb, Bootstrap cb, ByteBufAllocator allocator) {
super.configure(sb, cb, allocator);
sb.childOption(IoUringChannelOption.IO_URING_BUFFER_GROUP_ID, IoUringSocketTestPermutation.BGID);
cb.option(IoUringChannelOption.IO_URING_BUFFER_GROUP_ID, IoUringSocketTestPermutation.BGID);
}
}
| IoUringBufferRingCompositeBufferGatheringWriteTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java | {
"start": 48676,
"end": 49447
} | class ____ {
void f() {
Outer a = new Outer();
Outer b = new Outer();
Outer.Inner ai = a.new Inner();
synchronized (b.mu) {
// BUG: Diagnostic contains:
// Access should be guarded by 'mu' in enclosing instance 'threadsafety.Outer' of 'ai', which
// is not accessible in this scope; instead found: 'b.mu'
ai.x++;
}
synchronized (b) {
// BUG: Diagnostic contains:
// Access should be guarded by enclosing instance 'threadsafety.Outer' of 'ai', which is not
// accessible in this scope; instead found: 'b'
ai.y++;
}
}
}
""")
.doTest();
}
@Test
public void regression_b27686620() {
compilationHelper
.addSourceLines(
"A.java",
"""
| Test |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/JgroupsRaftComponentBuilderFactory.java | {
"start": 1891,
"end": 7503
} | interface ____ extends ComponentBuilder<JGroupsRaftComponent> {
/**
* Specifies configuration properties of the RaftHandle JChannel used by
* the endpoint (ignored if raftHandle ref is provided).
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: raft.xml
* Group: common
*
* @param channelProperties the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder channelProperties(java.lang.String channelProperties) {
doSetProperty("channelProperties", channelProperties);
return this;
}
/**
* RaftHandle to use.
*
* The option is a: <code>org.jgroups.raft.RaftHandle</code>
* type.
*
* Group: common
*
* @param raftHandle the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder raftHandle(org.jgroups.raft.RaftHandle raftHandle) {
doSetProperty("raftHandle", raftHandle);
return this;
}
/**
* Unique raftId to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param raftId the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder raftId(java.lang.String raftId) {
doSetProperty("raftId", raftId);
return this;
}
/**
* StateMachine to use.
*
* The option is a:
* <code>org.jgroups.raft.StateMachine</code> type.
*
* Default: NopStateMachine
* Group: common
*
* @param stateMachine the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder stateMachine(org.jgroups.raft.StateMachine stateMachine) {
doSetProperty("stateMachine", stateMachine);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default JgroupsRaftComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
| JgroupsRaftComponentBuilder |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/ext/JsonValueExtTypeIdTest.java | {
"start": 848,
"end": 1153
} | class ____ {
public DecimalEntry() {}
public String getKey() { return "num"; }
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXTERNAL_PROPERTY)
public DecimalValue getValue(){
return new DecimalValue();
}
}
public static | DecimalEntry |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/groupwindow/internal/MergingWindowProcessFunction.java | {
"start": 8734,
"end": 10201
} | class ____<W extends Window>
implements BiConsumerWithException<W, Collection<W>, Throwable> {
private final Context<?, W> ctx;
private final NamespaceAggsHandleFunctionBase<W> windowAggregator;
public DefaultAccMergingConsumer(
Context<?, W> ctx, NamespaceAggsHandleFunctionBase<W> windowAggregator) {
this.ctx = ctx;
this.windowAggregator = windowAggregator;
}
@Override
public void accept(W stateWindowResult, Collection<W> stateWindowsToBeMerged)
throws Throwable {
RowData targetAcc = ctx.getWindowAccumulators(stateWindowResult);
if (targetAcc == null) {
targetAcc = windowAggregator.createAccumulators();
}
windowAggregator.setAccumulators(stateWindowResult, targetAcc);
for (W w : stateWindowsToBeMerged) {
RowData acc = ctx.getWindowAccumulators(w);
if (acc != null) {
windowAggregator.merge(w, acc);
}
// clear merged window
ctx.clearWindowState(w);
ctx.clearPreviousState(w);
}
targetAcc = windowAggregator.getAccumulators();
ctx.setWindowAccumulators(stateWindowResult, targetAcc);
}
}
/** A {@link Context} used for {@link MergingWindowProcessFunction}. */
public | DefaultAccMergingConsumer |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/kstream/SessionWindowedDeserializer.java | {
"start": 1394,
"end": 3525
} | class ____ a windowed record. Must implement the {@link Serde} interface.
*/
public static final String WINDOWED_INNER_DESERIALIZER_CLASS = "windowed.inner.deserializer.class";
private final Logger log = LoggerFactory.getLogger(SessionWindowedDeserializer.class);
private Deserializer<T> inner;
// Default constructor needed by Kafka
public SessionWindowedDeserializer() {}
public SessionWindowedDeserializer(final Deserializer<T> inner) {
this.inner = inner;
}
@SuppressWarnings({"deprecation", "unchecked"})
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
String deserializerConfigKey = WINDOWED_INNER_DESERIALIZER_CLASS;
String deserializerConfigValue = (String) configs.get(WINDOWED_INNER_DESERIALIZER_CLASS);
if (deserializerConfigValue == null) {
final String windowedInnerClassSerdeConfig = (String) configs.get(StreamsConfig.WINDOWED_INNER_CLASS_SERDE);
if (windowedInnerClassSerdeConfig != null) {
deserializerConfigKey = StreamsConfig.WINDOWED_INNER_CLASS_SERDE;
deserializerConfigValue = windowedInnerClassSerdeConfig;
log.warn("Config {} is deprecated. Please use {} instead.",
StreamsConfig.WINDOWED_INNER_CLASS_SERDE, WINDOWED_INNER_DESERIALIZER_CLASS);
}
}
Serde<T> windowedInnerDeserializerClass = null;
if (deserializerConfigValue != null) {
try {
windowedInnerDeserializerClass = Utils.newInstance(deserializerConfigValue, Serde.class);
} catch (final ClassNotFoundException e) {
throw new ConfigException(deserializerConfigKey, deserializerConfigValue,
"Serde class " + deserializerConfigValue + " could not be found.");
}
}
if (inner != null && deserializerConfigValue != null) {
if (!inner.getClass().getName().equals(windowedInnerDeserializerClass.deserializer().getClass().getName())) {
throw new IllegalArgumentException("Inner | of |
java | elastic__elasticsearch | x-pack/plugin/mapper-aggregate-metric/src/main/java/org/elasticsearch/xpack/aggregatemetric/mapper/AggregateMetricDoubleFieldMapper.java | {
"start": 32146,
"end": 33019
} | class ____ implements DocValuesLoader {
@Override
public boolean advanceToDoc(int docId) throws IOException {
// It is required that all defined metrics must exist. In this case
// it is enough to check for the first docValue. However, in the future
// we may relax the requirement of all metrics existing. In this case
// we should check the doc value for each metric separately
metricHasValue.clear();
for (Map.Entry<Metric, SortedNumericDocValues> e : metricDocValues.entrySet()) {
if (e.getValue().advanceExact(docId)) {
metricHasValue.add(e.getKey());
}
}
return metricHasValue.isEmpty() == false;
}
}
}
}
| AggregateDocValuesLoader |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmTests.java | {
"start": 1192,
"end": 4925
} | class ____ extends ESTestCase {
private final String concreteSecurityIndexName = randomFrom(
TestRestrictedIndices.INTERNAL_SECURITY_MAIN_INDEX_6,
TestRestrictedIndices.INTERNAL_SECURITY_MAIN_INDEX_7
);
private SecurityIndexManager.IndexState dummyState(ClusterHealthStatus indexStatus) {
return mock(SecurityIndexManager.class).new IndexState(
Metadata.DEFAULT_PROJECT_ID, SecurityIndexManager.ProjectStatus.PROJECT_AVAILABLE, Instant.now(), true, true, true, true, true,
null, false, null, null, null, concreteSecurityIndexName, indexStatus, IndexMetadata.State.OPEN, "my_uuid", Set.of()
);
}
public void testCacheClearOnIndexHealthChange() {
final ThreadPool threadPool = mock(ThreadPool.class);
final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
when(threadPool.getThreadContext()).thenReturn(threadContext);
final AtomicInteger numInvalidation = new AtomicInteger(0);
int expectedInvalidation = 0;
RealmConfig.RealmIdentifier realmId = new RealmConfig.RealmIdentifier("native", "native");
Settings settings = Settings.builder()
.put("path.home", createTempDir())
.put(RealmSettings.realmSettingPrefix(realmId) + "order", 0)
.build();
RealmConfig config = new RealmConfig(realmId, settings, TestEnvironment.newEnvironment(settings), new ThreadContext(settings));
final NativeRealm nativeRealm = new NativeRealm(config, mock(NativeUsersStore.class), threadPool) {
@Override
void clearCache() {
numInvalidation.incrementAndGet();
}
};
// existing to no longer present
SecurityIndexManager.IndexState previousState = dummyState(randomFrom(ClusterHealthStatus.GREEN, ClusterHealthStatus.YELLOW));
SecurityIndexManager.IndexState currentState = dummyState(null);
nativeRealm.onSecurityIndexStateChange(Metadata.DEFAULT_PROJECT_ID, previousState, currentState);
assertEquals(++expectedInvalidation, numInvalidation.get());
// doesn't exist to exists
previousState = dummyState(null);
currentState = dummyState(randomFrom(ClusterHealthStatus.GREEN, ClusterHealthStatus.YELLOW));
nativeRealm.onSecurityIndexStateChange(Metadata.DEFAULT_PROJECT_ID, previousState, currentState);
assertEquals(++expectedInvalidation, numInvalidation.get());
// green or yellow to red
previousState = dummyState(randomFrom(ClusterHealthStatus.GREEN, ClusterHealthStatus.YELLOW));
currentState = dummyState(ClusterHealthStatus.RED);
nativeRealm.onSecurityIndexStateChange(Metadata.DEFAULT_PROJECT_ID, previousState, currentState);
assertEquals(expectedInvalidation, numInvalidation.get());
// red to non red
previousState = dummyState(ClusterHealthStatus.RED);
currentState = dummyState(randomFrom(ClusterHealthStatus.GREEN, ClusterHealthStatus.YELLOW));
nativeRealm.onSecurityIndexStateChange(Metadata.DEFAULT_PROJECT_ID, previousState, currentState);
assertEquals(++expectedInvalidation, numInvalidation.get());
// green to yellow or yellow to green
previousState = dummyState(randomFrom(ClusterHealthStatus.GREEN, ClusterHealthStatus.YELLOW));
currentState = dummyState(
previousState.indexHealth == ClusterHealthStatus.GREEN ? ClusterHealthStatus.YELLOW : ClusterHealthStatus.GREEN
);
nativeRealm.onSecurityIndexStateChange(Metadata.DEFAULT_PROJECT_ID, previousState, currentState);
assertEquals(expectedInvalidation, numInvalidation.get());
}
}
| NativeRealmTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/OptimisticLockingAnnotation.java | {
"start": 475,
"end": 1584
} | class ____ implements OptimisticLocking {
private org.hibernate.annotations.OptimisticLockType type;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public OptimisticLockingAnnotation(ModelsContext modelContext) {
this.type = org.hibernate.annotations.OptimisticLockType.VERSION;
}
/**
* Used in creating annotation instances from JDK variant
*/
public OptimisticLockingAnnotation(OptimisticLocking annotation, ModelsContext modelContext) {
this.type = annotation.type();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public OptimisticLockingAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
this.type = (org.hibernate.annotations.OptimisticLockType) attributeValues.get( "type" );
}
@Override
public Class<? extends Annotation> annotationType() {
return OptimisticLocking.class;
}
@Override
public org.hibernate.annotations.OptimisticLockType type() {
return type;
}
public void type(org.hibernate.annotations.OptimisticLockType value) {
this.type = value;
}
}
| OptimisticLockingAnnotation |
java | apache__kafka | core/src/test/java/kafka/server/share/SharePartitionManagerTest.java | {
"start": 178298,
"end": 180711
} | class ____ {
private final Persister persister = new NoOpStatePersister();
private ReplicaManager replicaManager = mock(ReplicaManager.class);
private Time time = new MockTime();
private ShareSessionCache cache = new ShareSessionCache(10);
private SharePartitionCache partitionCache = new SharePartitionCache();
private Timer timer = new MockTimer();
private ShareGroupMetrics shareGroupMetrics = new ShareGroupMetrics(time);
private BrokerTopicStats brokerTopicStats;
private SharePartitionManagerBuilder withReplicaManager(ReplicaManager replicaManager) {
this.replicaManager = replicaManager;
return this;
}
private SharePartitionManagerBuilder withTime(Time time) {
this.time = time;
return this;
}
private SharePartitionManagerBuilder withCache(ShareSessionCache cache) {
this.cache = cache;
return this;
}
SharePartitionManagerBuilder withPartitionCache(SharePartitionCache partitionCache) {
this.partitionCache = partitionCache;
return this;
}
private SharePartitionManagerBuilder withTimer(Timer timer) {
this.timer = timer;
return this;
}
private SharePartitionManagerBuilder withShareGroupMetrics(ShareGroupMetrics shareGroupMetrics) {
this.shareGroupMetrics = shareGroupMetrics;
return this;
}
private SharePartitionManagerBuilder withBrokerTopicStats(BrokerTopicStats brokerTopicStats) {
this.brokerTopicStats = brokerTopicStats;
return this;
}
public static SharePartitionManagerBuilder builder() {
return new SharePartitionManagerBuilder();
}
public SharePartitionManager build() {
return new SharePartitionManager(replicaManager,
time,
cache,
partitionCache,
DEFAULT_RECORD_LOCK_DURATION_MS,
timer,
MAX_DELIVERY_COUNT,
MAX_IN_FLIGHT_MESSAGES,
REMOTE_FETCH_MAX_WAIT_MS,
persister,
mock(GroupConfigManager.class),
shareGroupMetrics,
brokerTopicStats
);
}
}
}
| SharePartitionManagerBuilder |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/commands/ConsolidatedAclCommandIntegrationTests.java | {
"start": 1282,
"end": 3748
} | class ____ {
private static RedisClient client;
private static RedisCommands<String, String> redis;
@BeforeAll
public static void setup() {
RedisURI redisURI = RedisURI.Builder.redis("127.0.0.1").withPort(16379).build();
client = RedisClient.create(redisURI);
redis = client.connect().sync();
assumeTrue(RedisConditions.of(redis).hasVersionGreaterOrEqualsTo("7.9"));
}
@AfterAll
static void teardown() {
if (client != null) {
client.shutdown();
}
}
@BeforeEach
void setUp() {
redis.flushall();
redis.aclUsers().stream().filter(o -> !"default".equals(o)).forEach(redis::aclDeluser);
redis.aclLogReset();
}
@Test
public void listACLCategoriesTest() {
assertThat(redis.aclCat()).containsAll(Arrays.asList(AclCategory.BLOOM, AclCategory.CUCKOO, AclCategory.CMS,
AclCategory.TOPK, AclCategory.TDIGEST, AclCategory.SEARCH, AclCategory.TIMESERIES, AclCategory.JSON));
}
@Test
void grantBloomCommandCatTest() {
grantModuleCommandCatTest(AclCategory.BLOOM, "bloom");
}
@Test
void grantCuckooCommandCatTest() {
grantModuleCommandCatTest(AclCategory.CUCKOO, "cuckoo");
}
@Test
void grantCmsCommandCatTest() {
grantModuleCommandCatTest(AclCategory.CMS, "cms");
}
@Test
void grantTopkCommandCatTest() {
grantModuleCommandCatTest(AclCategory.TOPK, "topk");
}
@Test
void grantTdigestCommandCatTest() {
grantModuleCommandCatTest(AclCategory.TDIGEST, "tdigest");
}
@Test
void grantSearchCommandCatTest() {
grantModuleCommandCatTest(AclCategory.SEARCH, "search");
}
@Test
void grantTimeseriesCommandCatTest() {
grantModuleCommandCatTest(AclCategory.TIMESERIES, "timeseries");
}
@Test
void grantJsonCommandCatTest() {
grantModuleCommandCatTest(AclCategory.JSON, "json");
}
private void grantModuleCommandCatTest(AclCategory category, String categoryStr) {
assertThat(redis.aclDeluser("foo")).isNotNull();
AclSetuserArgs args = AclSetuserArgs.Builder.on().addCategory(category);
assertThat(redis.aclSetuser("foo", args)).isEqualTo("OK");
assertThat(redis.aclGetuser("foo")).contains("-@all +@" + categoryStr);
assertThat(redis.aclDeluser("foo")).isNotNull();
}
}
| ConsolidatedAclCommandIntegrationTests |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest72.java | {
"start": 976,
"end": 2444
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"Select A,B,C,sum(E) from test group by rollup(A,B,C)";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.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());
assertEquals(4, visitor.getColumns().size());
{
String text = SQLUtils.toOracleString(stmt);
assertEquals("SELECT A, B, C, sum(E)\n" +
"FROM test\n" +
"GROUP BY ROLLUP (A, B, C)", text);
}
// assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh")));
// assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name")));
}
}
| OracleSelectTest72 |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/configproperties/MyConfigInner.java | {
"start": 781,
"end": 1037
} | class ____ {
private List<InnerVal> innerVals;
public List<InnerVal> getInnerVals() {
return innerVals;
}
public void setInnerVals(List<InnerVal> innerVals) {
this.innerVals = innerVals;
}
public static | MyConfigInner |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/DoNotClaimAnnotations.java | {
"start": 2197,
"end": 4625
} | class ____ extends BugChecker implements MethodTreeMatcher {
private static final Supplier<Name> PROCESS_NAME = memoize(s -> s.getName("process"));
private static final Supplier<ImmutableList<Type>> PARAMETER_TYPES =
memoize(
s ->
Stream.of("java.util.Set", "javax.annotation.processing.RoundEnvironment")
.map(s::getTypeFromString)
.filter(x -> x != null)
.collect(toImmutableList()));
private static final Supplier<Symbol> PROCESSOR_SYMBOL =
memoize(s -> s.getSymbolFromString("javax.annotation.processing.Processor"));
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!tree.getName().equals(PROCESS_NAME.get(state))) {
return NO_MATCH;
}
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (!ASTHelpers.isSameType(sym.getReturnType(), state.getSymtab().booleanType, state)) {
return NO_MATCH;
}
if (sym.getParameters().size() != 2) {
return NO_MATCH;
}
if (!Streams.zip(
sym.getParameters().stream(),
PARAMETER_TYPES.get(state).stream(),
(p, t) -> ASTHelpers.isSameType(p.asType(), t, state))
.allMatch(x -> x)) {
return NO_MATCH;
}
if (!enclosingClass(sym).isSubClass(PROCESSOR_SYMBOL.get(state), state.getTypes())) {
return NO_MATCH;
}
List<ReturnTree> returns = new ArrayList<>();
new TreeScanner<Void, Void>() {
@Override
public Void visitLambdaExpression(LambdaExpressionTree node, Void aVoid) {
return null;
}
@Override
public Void visitClass(ClassTree node, Void aVoid) {
return null;
}
@Override
public Void visitReturn(ReturnTree node, Void unused) {
if (!Objects.equals(ASTHelpers.constValue(node.getExpression(), Boolean.class), false)) {
returns.add(node);
}
return super.visitReturn(node, null);
}
}.scan(tree.getBody(), null);
if (returns.isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
for (ReturnTree returnTree : returns) {
if (Objects.equals(ASTHelpers.constValue(returnTree.getExpression(), Boolean.class), true)) {
fix.replace(returnTree.getExpression(), "false");
}
}
return describeMatch(returns.getFirst(), fix.build());
}
}
| DoNotClaimAnnotations |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/jdk/CollectionSerializationTest.java | {
"start": 1910,
"end": 1998
} | class ____ {
public String[] empty = new String[0];
}
static | EmptyArrayBean |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/BufferEntityInExceptionMapperTest.java | {
"start": 2637,
"end": 2914
} | class ____ implements ResponseExceptionMapper<RuntimeException> {
@Override
public RuntimeException toThrowable(Response response) {
response.bufferEntity();
return new NoStackTraceException("dummy");
}
}
}
| DummyExceptionMapper |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/cache/interceptor/AbstractFallbackCacheOperationSource.java | {
"start": 6682,
"end": 7473
} | class ____ retrieve the cache operations for
* @return all cache operations associated with this class, or {@code null} if none
*/
protected abstract @Nullable Collection<CacheOperation> findCacheOperations(Class<?> clazz);
/**
* Subclasses need to implement this to return the cache operations for the
* given method, if any.
* @param method the method to retrieve the cache operations for
* @return all cache operations associated with this method, or {@code null} if none
*/
protected abstract @Nullable Collection<CacheOperation> findCacheOperations(Method method);
/**
* Should only public methods be allowed to have caching semantics?
* <p>The default implementation returns {@code false}.
*/
protected boolean allowPublicMethodsOnly() {
return false;
}
}
| to |
java | alibaba__nacos | core/src/main/java/com/alibaba/nacos/core/listener/startup/NacosCoreStartUp.java | {
"start": 1929,
"end": 8968
} | class ____ extends AbstractNacosStartUp {
private static final String MODE_PROPERTY_KEY_STAND_MODE = "nacos.mode";
private static final String MODE_PROPERTY_KEY_FUNCTION_MODE = "nacos.function.mode";
private static final String LOCAL_IP_PROPERTY_KEY = "nacos.local.ip";
private static final String NACOS_APPLICATION_CONF = "nacos_application_conf";
private static final String NACOS_MODE_STAND_ALONE = "stand alone";
private static final String NACOS_MODE_CLUSTER = "cluster";
private static final String DEFAULT_FUNCTION_MODE = "All";
private static final String DATASOURCE_PLATFORM_PROPERTY = "spring.sql.init.platform";
private static final String DERBY_DATABASE = "derby";
private static final String DEFAULT_DATASOURCE_PLATFORM = "";
private static final String DATASOURCE_MODE_EXTERNAL = "external";
private static final String DATASOURCE_MODE_EMBEDDED = "embedded";
private static final Map<String, Object> SOURCES = new ConcurrentHashMap<>();
public NacosCoreStartUp() {
super(NacosStartUp.CORE_START_UP_PHASE);
}
@Override
public String[] makeWorkDir() {
String[] dirNames = new String[] {"logs", "conf", "data"};
List<String> result = new ArrayList<>(dirNames.length);
for (String dirName : dirNames) {
try {
Path path = Paths.get(EnvUtil.getNacosHome(), dirName);
DiskUtils.forceMkdir(new File(path.toUri()));
result.add(path.toString());
} catch (Exception e) {
throw new NacosRuntimeException(ErrorCode.IOMakeDirError.getCode(), e);
}
}
return result.toArray(new String[0]);
}
@Override
public void injectEnvironment(ConfigurableEnvironment environment) {
EnvUtil.setEnvironment(environment);
}
@Override
public void loadPreProperties(ConfigurableEnvironment environment) {
try {
SOURCES.putAll(EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource()));
environment.getPropertySources()
.addLast(new OriginTrackedMapPropertySource(NACOS_APPLICATION_CONF, SOURCES));
registerWatcher();
} catch (Exception e) {
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e);
}
}
@Override
public void initSystemProperty() {
if (EnvUtil.getStandaloneMode()) {
System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, NACOS_MODE_STAND_ALONE);
} else {
System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, NACOS_MODE_CLUSTER);
}
if (EnvUtil.getFunctionMode() == null) {
System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, DEFAULT_FUNCTION_MODE);
} else if (EnvUtil.FUNCTION_MODE_CONFIG.equals(EnvUtil.getFunctionMode())) {
System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_CONFIG);
} else if (EnvUtil.FUNCTION_MODE_NAMING.equals(EnvUtil.getFunctionMode())) {
System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_NAMING);
}
System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIP());
}
@Override
public void logStartingInfo(Logger logger) {
logClusterConf(logger);
super.logStartingInfo(logger);
}
@Override
public void customEnvironment() {
EnvUtil.customEnvironment();
}
@Override
public void started() {
super.started();
ApplicationUtils.setStarted(true);
}
@Override
protected String getPhaseNameInStartingInfo() {
return "Nacos Server";
}
@Override
public void logStarted(Logger logger) {
long endTimestamp = System.currentTimeMillis();
long startupCost = endTimestamp - getStartTimestamp();
boolean useExternalStorage = judgeStorageMode(EnvUtil.getEnvironment());
logger.info("Nacos started successfully in {} mode with {} storage in {} ms",
System.getProperty(MODE_PROPERTY_KEY_STAND_MODE),
useExternalStorage ? DATASOURCE_MODE_EXTERNAL : DATASOURCE_MODE_EMBEDDED, startupCost);
}
@Override
public void failed(Throwable exception, ConfigurableApplicationContext context) {
super.failed(exception, context);
ThreadPoolManager.shutdown();
WatchFileCenter.shutdown();
NotifyCenter.shutdown();
}
private void registerWatcher() throws NacosException {
WatchFileCenter.registerWatcher(EnvUtil.getConfPath(), new FileWatcher() {
@Override
public void onChange(FileChangeEvent event) {
try {
Map<String, ?> tmp = EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource());
SOURCES.putAll(tmp);
NotifyCenter.publishEvent(ServerConfigChangeEvent.newEvent());
} catch (IOException ignore) {
}
}
@Override
public boolean interest(String context) {
return StringUtils.contains(context, "application.properties");
}
});
}
private void logClusterConf(Logger logger) {
if (!EnvUtil.getStandaloneMode()) {
try {
List<String> clusterConf = EnvUtil.readClusterConf();
logger.info("The server IP list of Nacos is {}", clusterConf);
} catch (IOException e) {
logger.error("read cluster conf fail", e);
}
}
}
private boolean judgeStorageMode(ConfigurableEnvironment env) {
// External data sources are used by default in cluster mode
String platform = this.getDatasourcePlatform(env);
boolean useExternalStorage =
!DEFAULT_DATASOURCE_PLATFORM.equalsIgnoreCase(platform) && !DERBY_DATABASE.equalsIgnoreCase(platform);
// must initialize after setUseExternalDB
// This value is true in stand-alone mode and false in cluster mode
// If this value is set to true in cluster mode, nacos's distributed storage engine is turned on
// default value is depend on ${nacos.standalone}
if (!useExternalStorage) {
boolean embeddedStorage = EnvUtil.getStandaloneMode() || Boolean.getBoolean("embeddedStorage");
// If the embedded data source storage is not turned on, it is automatically
// upgraded to the external data source storage, as before
if (!embeddedStorage) {
useExternalStorage = true;
}
}
return useExternalStorage;
}
private String getDatasourcePlatform(ConfigurableEnvironment env) {
return env.getProperty(DATASOURCE_PLATFORM_PROPERTY, DEFAULT_DATASOURCE_PLATFORM);
}
}
| NacosCoreStartUp |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/custom/CustomService.java | {
"start": 17168,
"end": 18137
} | class ____ {
public static InferenceServiceConfiguration get() {
return configuration.getOrCompute();
}
private static final LazyInitializable<InferenceServiceConfiguration, RuntimeException> configuration = new LazyInitializable<>(
() -> {
var configurationMap = new HashMap<String, SettingsConfiguration>();
// TODO revisit this
return new InferenceServiceConfiguration.Builder().setService(NAME)
.setName(SERVICE_NAME)
.setTaskTypes(supportedTaskTypes)
.setConfigurations(configurationMap)
.build();
}
);
}
@Override
public ServiceIntegrationValidator getServiceIntegrationValidator(TaskType taskType) {
if (taskType == TaskType.RERANK) {
return new CustomServiceIntegrationValidator();
}
return null;
}
}
| Configuration |
java | elastic__elasticsearch | x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/StringUtils.java | {
"start": 942,
"end": 1041
} | class ____ from sql-proto
// find a way to share it across or potentially just copy it over
final | comes |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/MonitorResourcesTest.java | {
"start": 1960,
"end": 6288
} | class ____ {
@Test
void test_reconfiguration(@TempDir(cleanup = CleanupMode.ON_SUCCESS) final Path tempDir) throws IOException {
final ConfigurationBuilder<?> configBuilder = ConfigurationBuilderFactory.newConfigurationBuilder(
// Explicitly deviating from `BuiltConfiguration`, since it is not `Reconfigurable`, and this
// results in `instanceof Reconfigurable` checks in `AbstractConfiguration` to fail while arming
// the watcher. Hence, using `PropertiesConfiguration`, which is `Reconfigurable`, instead.
PropertiesConfiguration.class);
final Path configFile = tempDir.resolve("log4j.xml");
final Path externalResourceFile1 = tempDir.resolve("external-resource-1.txt");
final Path externalResourceFile2 = tempDir.resolve("external-resource-2.txt");
final ConfigurationSource configSource = new ConfigurationSource(new Source(configFile), new byte[] {}, 0);
final int monitorInterval = 3;
final ComponentBuilder<?> monitorResourcesComponent = configBuilder.newComponent("MonitorResources");
monitorResourcesComponent.addComponent(configBuilder
.newComponent("MonitorResource")
.addAttribute("uri", externalResourceFile1.toUri().toString()));
monitorResourcesComponent.addComponent(configBuilder
.newComponent("MonitorResource")
.addAttribute("uri", externalResourceFile2.toUri().toString()));
final Configuration config = configBuilder
.setConfigurationSource(configSource)
.setMonitorInterval(String.valueOf(monitorInterval))
.addComponent(monitorResourcesComponent)
.build(false);
try (final LoggerContext loggerContext = Configurator.initialize(config)) {
assertMonitorResourceFileNames(
loggerContext,
configFile.getFileName().toString(),
externalResourceFile1.getFileName().toString(),
externalResourceFile2.getFileName().toString());
Files.write(externalResourceFile2, Collections.singletonList("a change"));
waitAtMost(2 * monitorInterval, TimeUnit.SECONDS).until(() -> loggerContext.getConfiguration() != config);
}
}
@Test
@LoggerContextSource("config/MonitorResource/log4j.xml")
void test_config_of_type_XML(final LoggerContext loggerContext) {
assertMonitorResourceFileNames(loggerContext, "log4j.xml");
}
@Test
@LoggerContextSource("config/MonitorResource/log4j.json")
void test_config_of_type_JSON(final LoggerContext loggerContext) {
assertMonitorResourceFileNames(loggerContext, "log4j.json");
}
@Test
@LoggerContextSource("config/MonitorResource/log4j.yaml")
void test_config_of_type_YAML(final LoggerContext loggerContext) {
assertMonitorResourceFileNames(loggerContext, "log4j.yaml");
}
@Test
@LoggerContextSource("config/MonitorResource/log4j.properties")
void test_config_of_type_properties(final LoggerContext loggerContext) {
assertMonitorResourceFileNames(loggerContext, "log4j.properties");
}
private static void assertMonitorResourceFileNames(final LoggerContext loggerContext, final String configFileName) {
assertMonitorResourceFileNames(loggerContext, configFileName, "external-file-1.txt", "external-file-2.txt");
}
private static void assertMonitorResourceFileNames(
final LoggerContext loggerContext, final String configFileName, final String... externalResourceFileNames) {
final Set<Source> sources = loggerContext
.getConfiguration()
.getWatchManager()
.getConfigurationWatchers()
.keySet();
final Set<String> actualFileNames =
sources.stream().map(source -> source.getFile().getName()).collect(Collectors.toSet());
final Set<String> expectedFileNames = new LinkedHashSet<>();
expectedFileNames.add(configFileName);
expectedFileNames.addAll(Arrays.asList(externalResourceFileNames));
assertThat(actualFileNames).as("watch manager sources: %s", sources).isEqualTo(expectedFileNames);
}
}
| MonitorResourcesTest |
java | apache__kafka | streams/src/test/java/org/apache/kafka/streams/tests/RelationalSmokeTest.java | {
"start": 24404,
"end": 44606
} | class ____ {
public static Topology getTopology() {
final StreamsBuilder streamsBuilder = new StreamsBuilder();
final KTable<Integer, Article> articles =
streamsBuilder.table(ARTICLE_SOURCE, Consumed.with(intSerde, new Article.ArticleSerde()));
final KTable<Integer, Comment> comments =
streamsBuilder.table(COMMENT_SOURCE, Consumed.with(intSerde, new Comment.CommentSerde()));
final KTable<Integer, Long> commentCounts =
comments.groupBy(
(key, value) -> new KeyValue<>(value.getArticleId(), (short) 1),
Grouped.with(Serdes.Integer(), Serdes.Short())
)
.count();
articles
.leftJoin(
commentCounts,
AugmentedArticle.joiner(),
Materialized.with(null, new AugmentedArticle.AugmentedArticleSerde())
)
.toStream()
.to(ARTICLE_RESULT_SINK);
comments.join(articles,
Comment::getArticleId,
AugmentedComment.joiner(),
Materialized.with(null, new AugmentedComment.AugmentedCommentSerde()))
.toStream()
.to(COMMENT_RESULT_SINK);
return streamsBuilder.build();
}
public static Properties getConfig(final String broker,
final String application,
final String id,
final String processingGuarantee,
final String groupProtocol,
final String stateDir) {
final Properties properties =
mkProperties(
mkMap(
mkEntry(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, broker),
mkEntry(StreamsConfig.APPLICATION_ID_CONFIG, application),
mkEntry(StreamsConfig.CLIENT_ID_CONFIG, id),
mkEntry(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, processingGuarantee),
mkEntry(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"),
mkEntry(StreamsConfig.STATE_DIR_CONFIG, stateDir),
mkEntry(StreamsConfig.GROUP_PROTOCOL_CONFIG, groupProtocol)
)
);
properties.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000L);
properties.put(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG, Duration.ofDays(5).toMillis());
return properties;
}
public static KafkaStreams startSync(final String broker,
final String application,
final String id,
final String processingGuarantee,
final String groupProtocol,
final String stateDir) throws InterruptedException {
final KafkaStreams kafkaStreams =
new KafkaStreams(getTopology(), getConfig(broker, application, id, processingGuarantee, groupProtocol, stateDir));
final CountDownLatch startUpLatch = new CountDownLatch(1);
kafkaStreams.setStateListener((newState, oldState) -> {
if (oldState == KafkaStreams.State.REBALANCING && newState == KafkaStreams.State.RUNNING) {
startUpLatch.countDown();
}
});
kafkaStreams.start();
startUpLatch.await();
LOG.info("Streams has started.");
return kafkaStreams;
}
public static boolean verifySync(final String broker, final Instant deadline) throws InterruptedException {
final Deserializer<Article> articleDeserializer = new Article.ArticleDeserializer();
final Deserializer<AugmentedArticle> augmentedArticleDeserializer =
new AugmentedArticle.AugmentedArticleDeserializer();
final Deserializer<Comment> commentDeserializer = new Comment.CommentDeserializer();
final Deserializer<AugmentedComment> augmentedCommentDeserializer =
new AugmentedComment.AugmentedCommentDeserializer();
final Properties consumerProperties = new Properties();
final String id = "RelationalSmokeTestConsumer" + UUID.randomUUID();
consumerProperties.put(ConsumerConfig.CLIENT_ID_CONFIG, id);
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, id);
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, broker);
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
consumerProperties.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
consumerProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
try (final KafkaConsumer<Integer, byte[]> consumer = new KafkaConsumer<>(consumerProperties)) {
final List<PartitionInfo> articlePartitions = consumer.partitionsFor(ARTICLE_SOURCE);
final List<PartitionInfo> augmentedArticlePartitions = consumer.partitionsFor(ARTICLE_RESULT_SINK);
final List<PartitionInfo> commentPartitions = consumer.partitionsFor(COMMENT_SOURCE);
final List<PartitionInfo> augmentedCommentPartitions = consumer.partitionsFor(COMMENT_RESULT_SINK);
final List<TopicPartition> assignment =
Stream.concat(
Stream.concat(
articlePartitions.stream().map(p -> new TopicPartition(p.topic(), p.partition())),
augmentedArticlePartitions.stream().map(p -> new TopicPartition(p.topic(), p.partition()))
),
Stream.concat(
commentPartitions.stream().map(p -> new TopicPartition(p.topic(), p.partition())),
augmentedCommentPartitions.stream().map(p -> new TopicPartition(p.topic(), p.partition()))
)
).collect(toList());
consumer.assign(assignment);
consumer.seekToBeginning(assignment);
final Map<Integer, Article> consumedArticles = new TreeMap<>();
final Map<Integer, AugmentedArticle> consumedAugmentedArticles = new TreeMap<>();
final Map<Integer, Comment> consumedComments = new TreeMap<>();
final Map<Integer, AugmentedComment> consumedAugmentedComments = new TreeMap<>();
boolean printedConsumedArticle = false;
boolean printedConsumedAugmentedArticle = false;
boolean printedConsumedComment = false;
boolean printedConsumedAugmentedComment = false;
boolean passed = false;
while (!passed && Instant.now().isBefore(deadline)) {
boolean lastPollWasEmpty = false;
while (!lastPollWasEmpty) {
final ConsumerRecords<Integer, byte[]> poll = consumer.poll(Duration.ofSeconds(1));
lastPollWasEmpty = poll.isEmpty();
for (final ConsumerRecord<Integer, byte[]> record : poll) {
final Integer key = record.key();
switch (record.topic()) {
case ARTICLE_SOURCE: {
final Article article = articleDeserializer.deserialize("", record.value());
if (consumedArticles.containsKey(key)) {
LOG.warn("Duplicate article: {} and {}", consumedArticles.get(key), article);
}
consumedArticles.put(key, article);
break;
}
case COMMENT_SOURCE: {
final Comment comment = commentDeserializer.deserialize("", record.value());
if (consumedComments.containsKey(key)) {
LOG.warn("Duplicate comment: {} and {}", consumedComments.get(key), comment);
}
consumedComments.put(key, comment);
break;
}
case ARTICLE_RESULT_SINK: {
final AugmentedArticle article =
augmentedArticleDeserializer.deserialize("", record.value());
consumedAugmentedArticles.put(key, article);
break;
}
case COMMENT_RESULT_SINK: {
final AugmentedComment comment =
augmentedCommentDeserializer.deserialize("", record.value());
consumedAugmentedComments.put(key, comment);
break;
}
default:
throw new IllegalArgumentException(record.toString());
}
}
consumer.commitSync();
}
if (!printedConsumedArticle && !consumedArticles.isEmpty()) {
LOG.info("Consumed first Article");
printedConsumedArticle = true;
}
if (!printedConsumedComment && !consumedComments.isEmpty()) {
LOG.info("Consumed first Comment");
printedConsumedComment = true;
}
if (!printedConsumedAugmentedArticle && !consumedAugmentedArticles.isEmpty()) {
LOG.info("Consumed first AugmentedArticle");
printedConsumedAugmentedArticle = true;
}
if (!printedConsumedAugmentedComment && !consumedAugmentedComments.isEmpty()) {
LOG.info("Consumed first AugmentedComment");
printedConsumedAugmentedComment = true;
}
passed = verifySync(
false,
consumedArticles,
consumedComments,
consumedAugmentedArticles,
consumedAugmentedComments
);
if (!passed) {
LOG.info("Verification has not passed yet. ");
Thread.sleep(500);
}
}
return verifySync(
true,
consumedArticles,
consumedComments,
consumedAugmentedArticles,
consumedAugmentedComments
);
}
}
public static void assertThat(final AtomicBoolean pass,
final StringBuilder failures,
final String message,
final boolean passed) {
if (!passed) {
if (failures != null) {
failures.append("\n").append(message);
}
pass.set(false);
}
}
static boolean verifySync(final boolean logResults,
final Map<Integer, Article> consumedArticles,
final Map<Integer, Comment> consumedComments,
final Map<Integer, AugmentedArticle> consumedAugmentedArticles,
final Map<Integer, AugmentedComment> consumedAugmentedComments) {
final AtomicBoolean pass = new AtomicBoolean(true);
final StringBuilder report = logResults ? new StringBuilder() : null;
assertThat(
pass,
report,
"Expected 1 article, got " + consumedArticles.size(),
!consumedArticles.isEmpty()
);
assertThat(
pass,
report,
"Expected 1 comment, got " + consumedComments.size(),
!consumedComments.isEmpty()
);
assertThat(
pass,
report,
"Mismatched article size between augmented articles (size "
+ consumedAugmentedArticles.size() +
") and consumed articles (size "
+ consumedArticles.size() + ")",
consumedAugmentedArticles.size() == consumedArticles.size()
);
assertThat(
pass,
report,
"Mismatched comments size between augmented comments (size "
+ consumedAugmentedComments.size() +
") and consumed comments (size " +
consumedComments.size() + ")",
consumedAugmentedComments.size() == consumedComments.size()
);
final Map<Integer, Long> commentCounts = new TreeMap<>();
for (final RelationalSmokeTest.AugmentedComment augmentedComment : consumedAugmentedComments.values()) {
final int key = augmentedComment.getKey();
assertThat(
pass,
report,
"comment missing, but found in augmentedComment: " + key,
consumedComments.containsKey(key)
);
final Comment comment = consumedComments.get(key);
if (comment != null) {
assertThat(
pass,
report,
"comment missing, but found in augmentedComment: " + key,
consumedComments.containsKey(key)
);
}
commentCounts.put(
augmentedComment.getArticleId(),
commentCounts.getOrDefault(augmentedComment.getArticleId(), 0L) + 1
);
assertThat(
pass,
report,
"augmentedArticle [" + augmentedComment.getArticleId() + "] " +
"missing for augmentedComment [" + augmentedComment.getKey() + "]",
consumedAugmentedArticles.containsKey(augmentedComment.getArticleId())
);
final AugmentedArticle augmentedArticle =
consumedAugmentedArticles.get(augmentedComment.getArticleId());
if (augmentedArticle != null) {
assertThat(
pass,
report,
"articlePrefix didn't match augmentedArticle: " + augmentedArticle.getText(),
augmentedArticle.getText().startsWith(augmentedComment.getArticlePrefix())
);
}
assertThat(
pass,
report,
"article " + augmentedComment.getArticleId() + " missing from consumedArticles",
consumedArticles.containsKey(augmentedComment.getArticleId())
);
final Article article = consumedArticles.get(augmentedComment.getArticleId());
if (article != null) {
assertThat(
pass,
report,
"articlePrefix didn't match article: " + article.getText(),
article.getText().startsWith(augmentedComment.getArticlePrefix())
);
}
}
for (final RelationalSmokeTest.AugmentedArticle augmentedArticle : consumedAugmentedArticles.values()) {
assertThat(
pass,
report,
"article " + augmentedArticle.getKey() + " comment count mismatch",
augmentedArticle.getCommentCount() == commentCounts.getOrDefault(augmentedArticle.getKey(), 0L)
);
}
if (logResults) {
if (pass.get()) {
LOG.info(
"Evaluation passed ({}/{}) articles and ({}/{}) comments",
consumedAugmentedArticles.size(),
consumedArticles.size(),
consumedAugmentedComments.size(),
consumedComments.size()
);
} else {
LOG.error(
"Evaluation failed\nReport: {}\n" +
"Consumed Input Articles: {}\n" +
"Consumed Input Comments: {}\n" +
"Consumed Augmented Articles: {}\n" +
"Consumed Augmented Comments: {}",
report,
consumedArticles,
consumedComments,
consumedAugmentedArticles,
consumedAugmentedComments
);
}
}
return pass.get();
}
}
/*
* Used by the smoke tests.
*/
public static void main(final String[] args) {
System.out.println(Arrays.toString(args));
final String mode = args[0];
final String kafka = args[1];
try {
switch (mode) {
case "driver": {
// this starts the driver (data generation and result verification)
final int numArticles = 1_000;
final int numComments = 10_000;
final DataSet dataSet = DataSet.generate(numArticles, numComments);
// publish the data for at least one minute
dataSet.produce(kafka, Duration.ofMinutes(1));
LOG.info("Smoke test finished producing");
// let it soak in
Thread.sleep(1000);
LOG.info("Smoke test starting verification");
// wait for at most 10 minutes to get a passing result
final boolean pass = App.verifySync(kafka, Instant.now().plus(Duration.ofMinutes(10)));
if (pass) {
LOG.info("Smoke test complete: passed");
} else {
LOG.error("Smoke test complete: failed");
}
break;
}
case "application": {
final String nodeId = args[2];
final String processingGuarantee = args[3];
final String groupProtocol = args[4];
final String stateDir = args[5];
App.startSync(kafka, UUID.randomUUID().toString(), nodeId, processingGuarantee, groupProtocol, stateDir);
break;
}
default:
LOG.error("Unknown command: {}", mode);
throw new RuntimeException("Unknown command: " + mode);
}
} catch (final InterruptedException e) {
LOG.error("Interrupted", e);
}
}
}
| App |
java | apache__flink | flink-yarn/src/main/java/org/apache/flink/yarn/TaskExecutorProcessSpecContainerResourcePriorityAdapter.java | {
"start": 1211,
"end": 1340
} | class ____ converting between Flink {@link TaskExecutorProcessSpec} and Yarn {@link
* Resource} and {@link Priority}.
*/
public | for |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TypeNameShadowingTest.java | {
"start": 9118,
"end": 9269
} | class ____ {
final Object T = new Object();
<T> void doIt(T t) {}
}
""")
.doTest();
}
}
| Test |
java | apache__dubbo | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java | {
"start": 9749,
"end": 16546
} | class ____ be generated correctly,
// replace "." with "_" to make the package name of the generated parameter class
// consistent with the package name of the actual parameter class.
builder.append('_').append(parameterType.getName().replace(".", "_"));
}
return builder.toString();
}
private static boolean hasConstraintParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
return true;
}
}
}
return false;
}
private static String toUpperMethodName(String methodName) {
return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
}
// Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass);
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
if (memberValue instanceof BooleanMemberValue) {
((BooleanMemberValue) memberValue).setValue((Boolean) value);
} else if (memberValue instanceof ByteMemberValue) {
((ByteMemberValue) memberValue).setValue((Byte) value);
} else if (memberValue instanceof CharMemberValue) {
((CharMemberValue) memberValue).setValue((Character) value);
} else if (memberValue instanceof ShortMemberValue) {
((ShortMemberValue) memberValue).setValue((Short) value);
} else if (memberValue instanceof IntegerMemberValue) {
((IntegerMemberValue) memberValue).setValue((Integer) value);
} else if (memberValue instanceof LongMemberValue) {
((LongMemberValue) memberValue).setValue((Long) value);
} else if (memberValue instanceof FloatMemberValue) {
((FloatMemberValue) memberValue).setValue((Float) value);
} else if (memberValue instanceof DoubleMemberValue) {
((DoubleMemberValue) memberValue).setValue((Double) value);
} else if (memberValue instanceof ClassMemberValue) {
((ClassMemberValue) memberValue).setValue(((Class<?>) value).getName());
} else if (memberValue instanceof StringMemberValue) {
((StringMemberValue) memberValue).setValue((String) value);
} else if (memberValue instanceof EnumMemberValue) {
((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
}
/* else if (memberValue instanceof AnnotationMemberValue) */
else if (memberValue instanceof ArrayMemberValue) {
CtClass arrayType = type.getComponentType();
int len = Array.getLength(value);
MemberValue[] members = new MemberValue[len];
for (int i = 0; i < len; i++) {
members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
}
((ArrayMemberValue) memberValue).setValue(members);
}
return memberValue;
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (methodClass != null) {
groups.add(methodClass);
}
Method method = clazz.getMethod(methodName, parameterTypes);
Class<?>[] methodClasses;
if (method.isAnnotationPresent(MethodValidated.class)) {
methodClasses = method.getAnnotation(MethodValidated.class).value();
groups.addAll(Arrays.asList(methodClasses));
}
// add into default group
groups.add(0, Default.class);
groups.add(1, clazz);
// convert list to array
Class<?>[] classGroups = groups.toArray(new Class[0]);
Set<ConstraintViolation<?>> violations = new HashSet<>();
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
violations.addAll(validator.validate(parameterBean, classGroups));
}
for (Object arg : arguments) {
validate(violations, arg, classGroups);
}
if (!violations.isEmpty()) {
logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations);
throw new ConstraintViolationException(
"Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations,
violations);
}
}
@Override
public boolean isSupport() {
Class<?> cls = null;
try {
cls = jakarta.validation.Validation.class;
} catch (Throwable ignore) {
}
return cls != null;
}
private Class<?> methodClass(String methodName) {
Class<?> methodClass = null;
String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName);
Class<?> cached = methodClassMap.get(methodClassName);
if (cached != null) {
return cached == clazz ? null : cached;
}
try {
methodClass =
Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
methodClassMap.put(methodClassName, methodClass);
} catch (ClassNotFoundException e) {
methodClassMap.put(methodClassName, clazz);
}
return methodClass;
}
private void validate(Set<ConstraintViolation<?>> violations, Object arg, Class<?>... groups) {
if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) {
if (arg instanceof Object[]) {
for (Object item : (Object[]) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Collection) {
for (Object item : (Collection<?>) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) arg).entrySet()) {
validate(violations, entry.getKey(), groups);
validate(violations, entry.getValue(), groups);
}
} else {
violations.addAll(validator.validate(arg, groups));
}
}
}
}
| can |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/StompEndpointBuilderFactory.java | {
"start": 1634,
"end": 6220
} | interface ____
extends
EndpointConsumerBuilder {
default AdvancedStompEndpointConsumerBuilder advanced() {
return (AdvancedStompEndpointConsumerBuilder) this;
}
/**
* The URI of the Stomp broker to connect to.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Default: tcp://localhost:61613
* Group: common
*
* @param brokerURL the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder brokerURL(String brokerURL) {
doSetProperty("brokerURL", brokerURL);
return this;
}
/**
* To set custom headers.
*
* The option is a: <code>java.util.Properties</code> type.
*
* Group: common
*
* @param customHeaders the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder customHeaders(Properties customHeaders) {
doSetProperty("customHeaders", customHeaders);
return this;
}
/**
* To set custom headers.
*
* The option will be converted to a <code>java.util.Properties</code>
* type.
*
* Group: common
*
* @param customHeaders the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder customHeaders(String customHeaders) {
doSetProperty("customHeaders", customHeaders);
return this;
}
/**
* The virtual host name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param host the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder host(String host) {
doSetProperty("host", host);
return this;
}
/**
* The stomp version (1.1, or 1.2).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param version the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder version(String version) {
doSetProperty("version", version);
return this;
}
/**
* The username.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param login the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder login(String login) {
doSetProperty("login", login);
return this;
}
/**
* The password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param passcode the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder passcode(String passcode) {
doSetProperty("passcode", passcode);
return this;
}
/**
* To configure security using SSLContextParameters.
*
* The option is a:
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* To configure security using SSLContextParameters.
*
* The option will be converted to a
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default StompEndpointConsumerBuilder sslContextParameters(String sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Stomp component.
*/
public | StompEndpointConsumerBuilder |
java | elastic__elasticsearch | benchmarks/src/main/java/org/elasticsearch/benchmark/index/codec/tsdb/internal/EncodeBenchmark.java | {
"start": 698,
"end": 1482
} | class ____ extends AbstractDocValuesForUtilBenchmark {
protected ByteArrayDataOutput dataOutput;
protected long[] input;
protected byte[] output;
@Override
public void setupIteration(int unUsedBitsPerValue, Supplier<long[]> arraySupplier) throws IOException {
this.input = arraySupplier.get();
this.output = new byte[Long.BYTES * blockSize];
this.dataOutput = new ByteArrayDataOutput(this.output);
}
@Override
public void setupInvocation(int unusedBitsPerValue) {
dataOutput.reset(this.output);
}
@Override
public void benchmark(int bitsPerValue, Blackhole bh) throws IOException {
forUtil.encode(this.input, bitsPerValue, this.dataOutput);
bh.consume(this.dataOutput);
}
}
| EncodeBenchmark |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/scanning/ResteasyReactiveInterceptorScanner.java | {
"start": 1399,
"end": 11392
} | class ____ {
private ResteasyReactiveInterceptorScanner() {
}
/**
* Creates a fully populated resource interceptors instance, that are created via reflection.
*/
public static ResourceInterceptors createResourceInterceptors(IndexView indexView, ApplicationScanningResult result) {
return createResourceInterceptors(indexView, result, null);
}
/**
* Creates a fully populated resource interceptors instance, that are created via the provided factory creator
*/
public static ResourceInterceptors createResourceInterceptors(IndexView indexView, ApplicationScanningResult result,
Function<String, BeanFactory<?>> factoryCreator) {
ResourceInterceptors interceptors = new ResourceInterceptors();
scanForContainerRequestFilters(interceptors, indexView, result);
scanForIOInterceptors(interceptors, indexView, result);
if (factoryCreator != null) {
interceptors.initializeDefaultFactories(factoryCreator);
}
return interceptors;
}
public static void scanForContainerRequestFilters(ResourceInterceptors interceptors, IndexView index,
ApplicationScanningResult applicationScanningResult) {
//the quarkus version of these filters will not be in the index
//so you need an explicit check for both
Collection<ClassInfo> specReqFilters = new HashSet<>(index
.getAllKnownImplementors(CONTAINER_REQUEST_FILTER));
Collection<ClassInfo> allReqFilters = new HashSet<>(specReqFilters);
allReqFilters.addAll(index
.getAllKnownImplementors(RESTEASY_REACTIVE_CONTAINER_REQUEST_FILTER));
for (var filterClass : allReqFilters) {
var interceptor = handleDiscoveredInterceptor(applicationScanningResult, interceptors.getContainerRequestFilters(),
index, filterClass);
if (interceptor == null) {
continue;
}
setFilterMethodSourceForReqFilter(index, specReqFilters, filterClass, interceptor);
}
Collection<ClassInfo> specRespFilters = new HashSet<>(index
.getAllKnownImplementors(CONTAINER_RESPONSE_FILTER));
Collection<ClassInfo> allRespFilters = new HashSet<>(specRespFilters);
allRespFilters.addAll(index
.getAllKnownImplementors(RESTEASY_REACTIVE_CONTAINER_RESPONSE_FILTER));
for (var filterClass : allRespFilters) {
var interceptor = handleDiscoveredInterceptor(applicationScanningResult, interceptors.getContainerResponseFilters(),
index, filterClass);
if (interceptor == null) {
continue;
}
setFilterMethodSourceForRespFilter(index, specRespFilters, filterClass, interceptor);
}
}
private static void setFilterMethodSourceForReqFilter(IndexView index, Collection<ClassInfo> specRequestFilters,
ClassInfo filterClass, ResourceInterceptor<ContainerRequestFilter> interceptor) {
boolean isSpecFilter = specRequestFilters.contains(filterClass);
ClassInfo ci = filterClass;
MethodInfo filterSourceMethod = null;
do {
for (var method : ci.methods()) {
if (!method.name().equals("filter") || method.parametersCount() != 1) {
continue;
}
List<Type> parameterTypes = method.parameterTypes();
if (isSpecFilter) {
if (parameterTypes.get(0).name().equals(CONTAINER_REQUEST_CONTEXT)) {
filterSourceMethod = method;
break;
}
} else {
if (parameterTypes.get(0).name().equals(RESTEASY_REACTIVE_CONTAINER_REQUEST_CONTEXT)) {
filterSourceMethod = method;
break;
}
}
}
if (filterSourceMethod != null) {
break;
}
if (OBJECT.equals(ci.superName())) {
break;
}
ci = index.getClassByName(ci.superName());
if (ci == null) {
break;
}
} while (true);
if (filterSourceMethod != null) {
interceptor.metadata = Map.of(FILTER_SOURCE_METHOD_METADATA_KEY, filterSourceMethod);
}
}
private static void setFilterMethodSourceForRespFilter(IndexView index, Collection<ClassInfo> specResponseFilters,
ClassInfo filterClass, ResourceInterceptor<ContainerResponseFilter> interceptor) {
boolean isSpecFilter = specResponseFilters.contains(filterClass);
ClassInfo ci = filterClass;
MethodInfo filterSourceMethod = null;
do {
for (var method : ci.methods()) {
if (!method.name().equals("filter") || method.parametersCount() != 2) {
continue;
}
List<Type> parameterTypes = method.parameterTypes();
if (isSpecFilter) {
if (parameterTypes.get(0).name().equals(CONTAINER_REQUEST_CONTEXT) &&
parameterTypes.get(1).name().equals(CONTAINER_RESPONSE_CONTEXT)) {
filterSourceMethod = method;
break;
}
} else {
if (parameterTypes.get(0).name().equals(RESTEASY_REACTIVE_CONTAINER_REQUEST_CONTEXT) &&
parameterTypes.get(1).name().equals(CONTAINER_RESPONSE_CONTEXT)) {
filterSourceMethod = method;
break;
}
}
}
if (filterSourceMethod != null) {
break;
}
if (OBJECT.equals(ci.superName())) {
break;
}
ci = index.getClassByName(ci.superName());
if (ci == null) {
break;
}
} while (true);
if (filterSourceMethod != null) {
interceptor.metadata = Map.of(FILTER_SOURCE_METHOD_METADATA_KEY, filterSourceMethod);
}
}
public static void scanForIOInterceptors(ResourceInterceptors interceptors, IndexView index,
ApplicationScanningResult applicationScanningResult) {
Collection<ClassInfo> readerInterceptors = index
.getAllKnownImplementors(READER_INTERCEPTOR);
Collection<ClassInfo> writerInterceptors = index
.getAllKnownImplementors(WRITER_INTERCEPTOR);
for (ClassInfo filterClass : writerInterceptors) {
handleDiscoveredInterceptor(applicationScanningResult, interceptors.getWriterInterceptors(), index, filterClass);
}
for (ClassInfo filterClass : readerInterceptors) {
handleDiscoveredInterceptor(applicationScanningResult, interceptors.getReaderInterceptors(), index, filterClass);
}
}
private static <T> ResourceInterceptor<T> handleDiscoveredInterceptor(
ApplicationScanningResult applicationResultBuildItem, InterceptorContainer<T> interceptorContainer, IndexView index,
ClassInfo filterClass) {
if (Modifier.isAbstract(filterClass.flags())) {
return null;
}
ApplicationScanningResult.KeepProviderResult keepProviderResult = applicationResultBuildItem.keepProvider(filterClass);
if (keepProviderResult != ApplicationScanningResult.KeepProviderResult.DISCARD) {
ResourceInterceptor<T> interceptor = interceptorContainer.create();
interceptor.setClassName(filterClass.name().toString());
interceptor.setNameBindingNames(NameBindingUtil.nameBindingNames(index, filterClass));
AnnotationInstance priorityInstance = filterClass.declaredAnnotation(PRIORITY);
if (priorityInstance != null) {
interceptor.setPriority(priorityInstance.value().asInt());
}
AnnotationInstance nonBlockingInstance = filterClass.declaredAnnotation(NON_BLOCKING);
if (nonBlockingInstance != null) {
interceptor.setNonBlockingRequired(true);
}
if (interceptorContainer instanceof PreMatchInterceptorContainer
&& filterClass.declaredAnnotation(PRE_MATCHING) != null) {
((PreMatchInterceptorContainer<T>) interceptorContainer).addPreMatchInterceptor(interceptor);
} else {
Set<String> nameBindingNames = interceptor.getNameBindingNames();
if (nameBindingNames.isEmpty()
|| namePresent(nameBindingNames, applicationResultBuildItem.getGlobalNameBindings())) {
interceptorContainer.addGlobalRequestInterceptor(interceptor);
} else {
interceptorContainer.addNameRequestInterceptor(interceptor);
}
}
RuntimeType runtimeType = null;
if (keepProviderResult == ApplicationScanningResult.KeepProviderResult.SERVER_ONLY) {
runtimeType = RuntimeType.SERVER;
}
AnnotationInstance constrainedToInstance = filterClass
.declaredAnnotation(ResteasyReactiveDotNames.CONSTRAINED_TO);
if (constrainedToInstance != null) {
runtimeType = RuntimeType.valueOf(constrainedToInstance.value().asEnum());
}
interceptor.setRuntimeType(runtimeType);
return interceptor;
}
return null;
}
private static boolean namePresent(Set<String> nameBindingNames, Set<String> globalNameBindings) {
for (String i : globalNameBindings) {
if (nameBindingNames.contains(i)) {
return true;
}
}
return false;
}
}
| ResteasyReactiveInterceptorScanner |
java | processing__processing4 | core/src/processing/core/PVector.java | {
"start": 2840,
"end": 2938
} | class ____
* <a href="http://www.shiffman.net">Dan Shiffman</a>.
*
* @webref math
* @webBrief A | by |
java | quarkusio__quarkus | extensions/devservices/keycloak/src/main/java/io/quarkus/devservices/keycloak/KeycloakDevServicesConfig.java | {
"start": 3509,
"end": 3658
} | class ____ file system resource path.
*/
@ConfigDocMapKey("alias-name")
Map<String, String> resourceAliases();
/**
* Additional | or |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/io/Versioned.java | {
"start": 902,
"end": 1071
} | interface ____ implemented by classes that provide a version number. Versions numbers can be
* used to differentiate between evolving classes.
*/
@PublicEvolving
public | is |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/ReachabilityChecker.java | {
"start": 1166,
"end": 1551
} | class ____ to trigger the GC at various points but does not
* guarantee a full GC. If we're unlucky, some of these objects may move to old enough heap generations that they are not subject to our GC
* attempts, resulting in test flakiness. Time will tell whether this is a problem in practice or not; if it is then we'll have to introduce
* some extra measures here.
*/
public | attempts |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteCacheEndpointBuilderFactory.java | {
"start": 32632,
"end": 36241
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final IgniteCacheHeaderNameBuilder INSTANCE = new IgniteCacheHeaderNameBuilder();
/**
* The cache key for the entry value in the message body.
*
* The option is a: {@code Object} type.
*
* Group: common
*
* @return the name of the header {@code IgniteCacheKey}.
*/
public String igniteCacheKey() {
return "CamelIgniteCacheKey";
}
/**
* The query to run when invoking the QUERY operation.
*
* The option is a: {@code org.apache.ignite.cache.query.Query} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteCacheQuery}.
*/
public String igniteCacheQuery() {
return "CamelIgniteCacheQuery";
}
/**
* Allows you to dynamically change the cache operation to execute.
*
* The option is a: {@code
* org.apache.camel.component.ignite.cache.IgniteCacheOperation} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteCacheOperation}.
*/
public String igniteCacheOperation() {
return "CamelIgniteCacheOperation";
}
/**
* Allows you to dynamically change the cache peek mode when running the
* SIZE operation.
*
* The option is a: {@code org.apache.ignite.cache.CachePeekMode} type.
*
* Group: producer
*
* @return the name of the header {@code IgniteCachePeekMode}.
*/
public String igniteCachePeekMode() {
return "CamelIgniteCachePeekMode";
}
/**
* This header carries the received event type when using the continuous
* query consumer.
*
* The option is a: {@code javax.cache.event.EventType} type.
*
* Group: consumer
*
* @return the name of the header {@code IgniteCacheEventType}.
*/
public String igniteCacheEventType() {
return "CamelIgniteCacheEventType";
}
/**
* This header carries the cache name for which a continuous query event
* was received (consumer). It does not allow you to dynamically change
* the cache against which a producer operation is performed. Use EIPs
* for that (e.g. recipient list, dynamic router).
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code IgniteCacheName}.
*/
public String igniteCacheName() {
return "CamelIgniteCacheName";
}
/**
* (producer) The old cache value to be replaced when invoking the
* REPLACE operation. (consumer) This header carries the old cache value
* when passed in the incoming cache event.
*
* The option is a: {@code Object} type.
*
* Group: common
*
* @return the name of the header {@code IgniteCacheOldValue}.
*/
public String igniteCacheOldValue() {
return "CamelIgniteCacheOldValue";
}
}
static IgniteCacheEndpointBuilder endpointBuilder(String componentName, String path) {
| IgniteCacheHeaderNameBuilder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/policies/amrmproxy/LocalityMulticastAMRMProxyPolicy.java | {
"start": 27797,
"end": 27945
} | class ____ used to book-keep the requests made to each
* subcluster, and maintain useful statistics to split ANY requests.
*/
protected final | is |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/plugin/PluginException.java | {
"start": 784,
"end": 1170
} | class ____ extends PersistenceException {
private static final long serialVersionUID = 8548771664564998595L;
public PluginException() {
}
public PluginException(String message) {
super(message);
}
public PluginException(String message, Throwable cause) {
super(message, cause);
}
public PluginException(Throwable cause) {
super(cause);
}
}
| PluginException |
java | netty__netty | codec-base/src/main/java/io/netty/handler/codec/base64/Base64.java | {
"start": 15151,
"end": 21531
} | class ____ implements ByteProcessor {
private final byte[] b4 = new byte[4];
private int b4Posn;
private byte[] decodabet;
private int outBuffPosn;
private ByteBuf dest;
ByteBuf decode(ByteBuf src, int off, int len, ByteBufAllocator allocator, Base64Dialect dialect) {
dest = allocator.buffer(decodedBufferSize(len)).order(src.order()); // Upper limit on size of output
decodabet = decodabet(dialect);
try {
src.forEachByte(off, len, this);
// Padding missing, process additional bytes
if (b4Posn == 1) {
throw new IllegalArgumentException(
"Invalid Base64 input, single remaining character implies incorrect length or padding");
} else if (b4Posn == 2) {
b4[2] = EQUALS_SIGN;
b4[3] = EQUALS_SIGN;
outBuffPosn += decode4to3(b4, dest, outBuffPosn, decodabet);
} else if (b4Posn == 3) {
b4[3] = EQUALS_SIGN;
outBuffPosn += decode4to3(b4, dest, outBuffPosn, decodabet);
}
return dest.slice(0, outBuffPosn);
} catch (Throwable cause) {
dest.release();
PlatformDependent.throwException(cause);
return null;
}
}
@Override
public boolean process(byte value) throws Exception {
if (value > 0) {
byte sbiDecode = decodabet[value];
if (sbiDecode >= WHITE_SPACE_ENC) { // White space, Equals sign or better
if (sbiDecode >= EQUALS_SIGN_ENC) { // Equals sign or better
b4[b4Posn ++] = value;
if (b4Posn > 3) { // Quartet built
outBuffPosn += decode4to3(b4, dest, outBuffPosn, decodabet);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
return value != EQUALS_SIGN;
}
}
return true;
}
}
throw new IllegalArgumentException(
"invalid Base64 input character: " + (short) (value & 0xFF) + " (decimal)");
}
private static int decode4to3(byte[] src, ByteBuf dest, int destOffset, byte[] decodabet) {
final byte src0 = src[0];
final byte src1 = src[1];
final byte src2 = src[2];
final int decodedValue;
if (src2 == EQUALS_SIGN) {
// Example: Dk==
try {
decodedValue = (decodabet[src0] & 0xff) << 2 | (decodabet[src1] & 0xff) >>> 4;
} catch (IndexOutOfBoundsException ignored) {
throw new IllegalArgumentException("not encoded in Base64");
}
dest.setByte(destOffset, decodedValue);
return 1;
}
final byte src3 = src[3];
if (src3 == EQUALS_SIGN) {
// Example: DkL=
final byte b1 = decodabet[src1];
// Packing bytes into a short to reduce bound and reference count checking.
try {
if (dest.order() == ByteOrder.BIG_ENDIAN) {
// The decodabet bytes are meant to straddle byte boundaries and so we must carefully mask out
// the bits we care about.
decodedValue = ((decodabet[src0] & 0x3f) << 2 | (b1 & 0xf0) >> 4) << 8 |
(b1 & 0xf) << 4 | (decodabet[src2] & 0xfc) >>> 2;
} else {
// This is just a simple byte swap of the operation above.
decodedValue = (decodabet[src0] & 0x3f) << 2 | (b1 & 0xf0) >> 4 |
((b1 & 0xf) << 4 | (decodabet[src2] & 0xfc) >>> 2) << 8;
}
} catch (IndexOutOfBoundsException ignored) {
throw new IllegalArgumentException("not encoded in Base64");
}
dest.setShort(destOffset, decodedValue);
return 2;
}
// Example: DkLE
try {
if (dest.order() == ByteOrder.BIG_ENDIAN) {
decodedValue = (decodabet[src0] & 0x3f) << 18 |
(decodabet[src1] & 0xff) << 12 |
(decodabet[src2] & 0xff) << 6 |
decodabet[src3] & 0xff;
} else {
final byte b1 = decodabet[src1];
final byte b2 = decodabet[src2];
// The goal is to byte swap the BIG_ENDIAN case above. There are 2 interesting things to consider:
// 1. We are byte swapping a 3 byte data type. The left and the right byte switch, but the middle
// remains the same.
// 2. The contents straddles byte boundaries. This means bytes will be pulled apart during the byte
// swapping process.
decodedValue = (decodabet[src0] & 0x3f) << 2 |
// The bottom half of b1 remains in the middle.
(b1 & 0xf) << 12 |
// The top half of b1 are the least significant bits after the swap.
(b1 & 0xf0) >>> 4 |
// The bottom 2 bits of b2 will be the most significant bits after the swap.
(b2 & 0x3) << 22 |
// The remaining 6 bits of b2 remain in the middle.
(b2 & 0xfc) << 6 |
(decodabet[src3] & 0xff) << 16;
}
} catch (IndexOutOfBoundsException ignored) {
throw new IllegalArgumentException("not encoded in Base64");
}
dest.setMedium(destOffset, decodedValue);
return 3;
}
}
private Base64() {
// Unused
}
}
| Decoder |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/util/NonReusingMutableToRegularIteratorWrapper.java | {
"start": 1121,
"end": 1303
} | class ____ a {@link org.apache.flink.util.MutableObjectIterator} into a regular {@link
* java.util.Iterator}. It will always create new instances and not reuse objects.
*/
public | wraps |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/transport/ClusterSettingsLinkedProjectConfigService.java | {
"start": 1156,
"end": 4061
} | class ____ extends AbstractLinkedProjectConfigService {
private final Settings settings;
private final ProjectResolver projectResolver;
/**
* Constructs a new {@link ClusterSettingsLinkedProjectConfigService}.
*
* @param settings The initial node settings available on startup, used in {@link #getInitialLinkedProjectConfigs()}.
* @param clusterSettings The {@link ClusterSettings} to add setting update consumers to, if non-null.
* @param projectResolver The {@link ProjectResolver} to use to resolve the origin project ID.
*/
@SuppressWarnings("this-escape")
public ClusterSettingsLinkedProjectConfigService(
Settings settings,
@Nullable ClusterSettings clusterSettings,
ProjectResolver projectResolver
) {
this.settings = settings;
this.projectResolver = projectResolver;
if (clusterSettings != null) {
List<Setting.AffixSetting<?>> remoteClusterSettings = List.of(
RemoteClusterSettings.REMOTE_CLUSTER_COMPRESS,
RemoteClusterSettings.REMOTE_CLUSTER_PING_SCHEDULE,
RemoteClusterSettings.REMOTE_CONNECTION_MODE,
RemoteClusterSettings.REMOTE_CLUSTER_SKIP_UNAVAILABLE,
RemoteClusterSettings.SniffConnectionStrategySettings.REMOTE_CLUSTERS_PROXY,
RemoteClusterSettings.SniffConnectionStrategySettings.REMOTE_CLUSTER_SEEDS,
RemoteClusterSettings.SniffConnectionStrategySettings.REMOTE_NODE_CONNECTIONS,
RemoteClusterSettings.ProxyConnectionStrategySettings.PROXY_ADDRESS,
RemoteClusterSettings.ProxyConnectionStrategySettings.REMOTE_SOCKET_CONNECTIONS,
RemoteClusterSettings.ProxyConnectionStrategySettings.SERVER_NAME
);
clusterSettings.addAffixGroupUpdateConsumer(remoteClusterSettings, this::settingsChangedCallback);
}
}
@Override
@FixForMultiProject(description = "Refactor to add the linked project IDs associated with the aliases.")
public Collection<LinkedProjectConfig> getInitialLinkedProjectConfigs() {
return RemoteClusterSettings.getRemoteClusters(settings)
.stream()
.map(alias -> RemoteClusterSettings.toConfig(projectResolver.getProjectId(), ProjectId.DEFAULT, alias, settings))
.toList();
}
private void settingsChangedCallback(String clusterAlias, Settings newSettings) {
final var mergedSettings = Settings.builder().put(settings, false).put(newSettings, false).build();
@FixForMultiProject(description = "Refactor to add the linked project ID associated with the alias.")
final var config = RemoteClusterSettings.toConfig(projectResolver.getProjectId(), ProjectId.DEFAULT, clusterAlias, mergedSettings);
handleUpdate(config);
}
}
| ClusterSettingsLinkedProjectConfigService |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/resume/BasicResumeStrategyConfigurationBuilder.java | {
"start": 1384,
"end": 2279
} | class ____<
T extends BasicResumeStrategyConfigurationBuilder<T, Y>, Y extends ResumeStrategyConfiguration>
implements ResumeStrategyConfigurationBuilder<T, Y> {
protected Cacheable.FillPolicy cacheFillPolicy = Cacheable.FillPolicy.MAXIMIZING;
protected ResumeCache<?> resumeCache;
@Override
public T withCacheFillPolicy(Cacheable.FillPolicy fillPolicy) {
this.cacheFillPolicy = fillPolicy;
return (T) this;
}
@Override
public T withResumeCache(ResumeCache<?> resumeCache) {
this.resumeCache = resumeCache;
return (T) this;
}
protected void buildCommonConfiguration(ResumeStrategyConfiguration resumeStrategyConfiguration) {
resumeStrategyConfiguration.setResumeCache(resumeCache);
resumeStrategyConfiguration.setCacheFillPolicy(cacheFillPolicy);
}
}
| BasicResumeStrategyConfigurationBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/associations/OneToManyJoinFetchDiscriminatorTest.java | {
"start": 3661,
"end": 4017
} | class ____ extends BodyPart {
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Person person;
public Leg() {
}
public Leg(String name, Person person) {
this.name = name;
this.person = person;
}
public Person getPerson() {
return person;
}
}
@Entity(name = "Arm")
@DiscriminatorValue("ArmBodyPart")
public static | Leg |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java | {
"start": 18907,
"end": 19013
} | interface ____ {
@Async
void work();
Thread getThreadOfExecution();
}
public static | AsyncInterface |
java | google__guava | android/guava/src/com/google/common/io/CharSink.java | {
"start": 2355,
"end": 6871
} | class ____ {
/** Constructor for use by subclasses. */
protected CharSink() {}
/**
* Opens a new {@link Writer} for writing to this sink. This method returns a new, independent
* writer each time it is called.
*
* <p>The caller is responsible for ensuring that the returned writer is closed.
*
* @throws IOException if an I/O error occurs while opening the writer
*/
public abstract Writer openStream() throws IOException;
/**
* Opens a new buffered {@link Writer} for writing to this sink. The returned stream is not
* required to be a {@link BufferedWriter} in order to allow implementations to simply delegate to
* {@link #openStream()} when the stream returned by that method does not benefit from additional
* buffering. This method returns a new, independent writer each time it is called.
*
* <p>The caller is responsible for ensuring that the returned writer is closed.
*
* @throws IOException if an I/O error occurs while opening the writer
* @since 15.0 (in 14.0 with return type {@link BufferedWriter})
*/
public Writer openBufferedStream() throws IOException {
Writer writer = openStream();
return (writer instanceof BufferedWriter)
? (BufferedWriter) writer
: new BufferedWriter(writer);
}
/**
* Writes the given character sequence to this sink.
*
* @throws IOException if an I/O error while writing to this sink
*/
public void write(CharSequence charSequence) throws IOException {
checkNotNull(charSequence);
try (Writer out = openStream()) {
out.append(charSequence);
}
}
/**
* Writes the given lines of text to this sink with each line (including the last) terminated with
* the operating system's default line separator. This method is equivalent to {@code
* writeLines(lines, System.getProperty("line.separator"))}.
*
* @throws IOException if an I/O error occurs while writing to this sink
*/
public void writeLines(Iterable<? extends CharSequence> lines) throws IOException {
writeLines(lines, System.getProperty("line.separator"));
}
/**
* Writes the given lines of text to this sink with each line (including the last) terminated with
* the given line separator.
*
* @throws IOException if an I/O error occurs while writing to this sink
*/
public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator)
throws IOException {
writeLines(lines.iterator(), lineSeparator);
}
/**
* Writes the given lines of text to this sink with each line (including the last) terminated with
* the operating system's default line separator. This method is equivalent to {@code
* writeLines(lines, System.getProperty("line.separator"))}.
*
* @throws IOException if an I/O error occurs while writing to this sink
* @since 33.4.0 (but since 22.0 in the JRE flavor)
*/
@IgnoreJRERequirement // Users will use this only if they're already using Stream.
public void writeLines(Stream<? extends CharSequence> lines) throws IOException {
writeLines(lines, LINE_SEPARATOR.value());
}
/**
* Writes the given lines of text to this sink with each line (including the last) terminated with
* the given line separator.
*
* @throws IOException if an I/O error occurs while writing to this sink
* @since 33.4.0 (but since 22.0 in the JRE flavor)
*/
@IgnoreJRERequirement // Users will use this only if they're already using Stream.
public void writeLines(Stream<? extends CharSequence> lines, String lineSeparator)
throws IOException {
writeLines(lines.iterator(), lineSeparator);
}
private void writeLines(Iterator<? extends CharSequence> lines, String lineSeparator)
throws IOException {
checkNotNull(lineSeparator);
try (Writer out = openBufferedStream()) {
while (lines.hasNext()) {
out.append(lines.next()).append(lineSeparator);
}
}
}
/**
* Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink.
* Does not close {@code readable} if it is {@code Closeable}.
*
* @return the number of characters written
* @throws IOException if an I/O error occurs while reading from {@code readable} or writing to
* this sink
*/
@CanIgnoreReturnValue
public long writeFrom(Readable readable) throws IOException {
checkNotNull(readable);
try (Writer out = openStream()) {
return CharStreams.copy(readable, out);
}
}
}
| CharSink |
java | elastic__elasticsearch | libs/x-content/src/main/java/org/elasticsearch/xcontent/smile/SmileXContent.java | {
"start": 739,
"end": 1242
} | class ____ {
private static final XContentProvider.FormatProvider provider = XContentProvider.provider().getSmileXContent();
private SmileXContent() {}
/**
* Returns an {@link XContentBuilder} for building Smile XContent.
*/
public static XContentBuilder contentBuilder() throws IOException {
return provider.getContentBuilder();
}
/**
* A Smile based XContent.
*/
public static final XContent smileXContent = provider.XContent();
}
| SmileXContent |
java | apache__camel | catalog/camel-report-maven-plugin/src/main/java/org/apache/camel/maven/ValidateMojo.java | {
"start": 49593,
"end": 50792
} | class ____ {
private int endpointErrors = 0;
private int configurationErrors = 0;
private int unknownComponents = 0;
private int incapableErrors = 0;
private int deprecatedOptions = 0;
public void incrementEndpointErrors() {
endpointErrors++;
}
public void incrementConfigurationErrors() {
configurationErrors++;
}
public void incrementUnknownComponents() {
unknownComponents++;
}
public void incrementIncapableErrors() {
incapableErrors++;
}
public void incrementDeprecatedOptionsBy(int extra) {
deprecatedOptions += extra;
}
public int getEndpointErrors() {
return endpointErrors;
}
public int getConfigurationErrors() {
return configurationErrors;
}
public int getUnknownComponents() {
return unknownComponents;
}
public int getIncapableErrors() {
return incapableErrors;
}
public int getDeprecatedOptions() {
return deprecatedOptions;
}
}
}
| ValidationComputedResult |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/chunking/ChunkingSettingsBuilder.java | {
"start": 475,
"end": 3116
} | class ____ {
public static final SentenceBoundaryChunkingSettings DEFAULT_SETTINGS = new SentenceBoundaryChunkingSettings(250, 1);
// Old settings used for backward compatibility for endpoints created before 8.16 when default was changed
public static final WordBoundaryChunkingSettings OLD_DEFAULT_SETTINGS = new WordBoundaryChunkingSettings(250, 100);
public static final int ELASTIC_RERANKER_TOKEN_LIMIT = 512;
public static final int ELASTIC_RERANKER_EXTRA_TOKEN_COUNT = 3;
public static final float WORDS_PER_TOKEN = 0.75f;
public static ChunkingSettings fromMap(Map<String, Object> settings) {
return fromMap(settings, true);
}
public static ChunkingSettings fromMap(Map<String, Object> settings, boolean returnDefaultValues) {
if (returnDefaultValues) {
if (settings == null) {
return OLD_DEFAULT_SETTINGS;
}
if (settings.isEmpty()) {
return DEFAULT_SETTINGS;
}
} else {
if (settings == null || settings.isEmpty()) {
return null;
}
}
if (settings.containsKey(ChunkingSettingsOptions.STRATEGY.toString()) == false) {
throw new IllegalArgumentException("Can't generate Chunker without ChunkingStrategy provided");
}
ChunkingStrategy chunkingStrategy = ChunkingStrategy.fromString(
settings.get(ChunkingSettingsOptions.STRATEGY.toString()).toString()
);
return switch (chunkingStrategy) {
case NONE -> NoneChunkingSettings.INSTANCE;
case WORD -> WordBoundaryChunkingSettings.fromMap(new HashMap<>(settings));
case SENTENCE -> SentenceBoundaryChunkingSettings.fromMap(new HashMap<>(settings));
case RECURSIVE -> RecursiveChunkingSettings.fromMap(new HashMap<>(settings));
};
}
public static ChunkingSettings buildChunkingSettingsForElasticRerank(int queryWordCount) {
var queryTokenCount = Math.ceil(queryWordCount / WORDS_PER_TOKEN);
var chunkSizeTokenCountWithFullQuery = (ELASTIC_RERANKER_TOKEN_LIMIT - ELASTIC_RERANKER_EXTRA_TOKEN_COUNT - queryTokenCount);
var maxChunkSizeTokenCount = Math.floor((float) ELASTIC_RERANKER_TOKEN_LIMIT / 2);
if (chunkSizeTokenCountWithFullQuery > maxChunkSizeTokenCount) {
maxChunkSizeTokenCount = chunkSizeTokenCountWithFullQuery;
}
var maxChunkSizeWordCount = (int) (maxChunkSizeTokenCount * WORDS_PER_TOKEN);
return new SentenceBoundaryChunkingSettings(maxChunkSizeWordCount, 1);
}
}
| ChunkingSettingsBuilder |
java | apache__flink | flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/junit/extensions/parameterized/Parameters.java | {
"start": 1223,
"end": 1285
} | interface ____ {
String name() default "{index}";
}
| Parameters |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/BlobEndpointBuilderFactory.java | {
"start": 50155,
"end": 88149
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedBlobEndpointProducerBuilder advanced() {
return (AdvancedBlobEndpointProducerBuilder) this;
}
/**
* The blob name, to consume specific blob from a container. However, on
* producer it is only required for the operations on the blob level.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param blobName the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobName(String blobName) {
doSetProperty("blobName", blobName);
return this;
}
/**
* Set the blob offset for the upload or download operations, default is
* 0.
*
* The option is a: <code>long</code> type.
*
* Default: 0
* Group: common
*
* @param blobOffset the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobOffset(long blobOffset) {
doSetProperty("blobOffset", blobOffset);
return this;
}
/**
* Set the blob offset for the upload or download operations, default is
* 0.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 0
* Group: common
*
* @param blobOffset the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobOffset(String blobOffset) {
doSetProperty("blobOffset", blobOffset);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* getBlobContainerClient(String), and operations on a blob are
* available on BlobClient through
* getBlobContainerClient(String).getBlobClient(String).
*
* The option is a:
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param blobServiceClient the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobServiceClient(com.azure.storage.blob.BlobServiceClient blobServiceClient) {
doSetProperty("blobServiceClient", blobServiceClient);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* getBlobContainerClient(String), and operations on a blob are
* available on BlobClient through
* getBlobContainerClient(String).getBlobClient(String).
*
* The option will be converted to a
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param blobServiceClient the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobServiceClient(String blobServiceClient) {
doSetProperty("blobServiceClient", blobServiceClient);
return this;
}
/**
* The blob type in order to initiate the appropriate settings for each
* blob type.
*
* The option is a:
* <code>org.apache.camel.component.azure.storage.blob.BlobType</code>
* type.
*
* Default: blockblob
* Group: common
*
* @param blobType the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobType(org.apache.camel.component.azure.storage.blob.BlobType blobType) {
doSetProperty("blobType", blobType);
return this;
}
/**
* The blob type in order to initiate the appropriate settings for each
* blob type.
*
* The option will be converted to a
* <code>org.apache.camel.component.azure.storage.blob.BlobType</code>
* type.
*
* Default: blockblob
* Group: common
*
* @param blobType the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobType(String blobType) {
doSetProperty("blobType", blobType);
return this;
}
/**
* Close the stream after read or keep it open, default is true.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param closeStreamAfterRead the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder closeStreamAfterRead(boolean closeStreamAfterRead) {
doSetProperty("closeStreamAfterRead", closeStreamAfterRead);
return this;
}
/**
* Close the stream after read or keep it open, default is true.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param closeStreamAfterRead the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder closeStreamAfterRead(String closeStreamAfterRead) {
doSetProperty("closeStreamAfterRead", closeStreamAfterRead);
return this;
}
/**
* StorageSharedKeyCredential can be injected to create the azure
* client, this holds the important authentication information.
*
* The option is a:
* <code>com.azure.storage.common.StorageSharedKeyCredential</code>
* type.
*
* Group: common
*
* @param credentials the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder credentials(com.azure.storage.common.StorageSharedKeyCredential credentials) {
doSetProperty("credentials", credentials);
return this;
}
/**
* StorageSharedKeyCredential can be injected to create the azure
* client, this holds the important authentication information.
*
* The option will be converted to a
* <code>com.azure.storage.common.StorageSharedKeyCredential</code>
* type.
*
* Group: common
*
* @param credentials the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder credentials(String credentials) {
doSetProperty("credentials", credentials);
return this;
}
/**
* Determines the credential strategy to adopt.
*
* The option is a:
* <code>org.apache.camel.component.azure.storage.blob.CredentialType</code> type.
*
* Default: AZURE_IDENTITY
* Group: common
*
* @param credentialType the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder credentialType(org.apache.camel.component.azure.storage.blob.CredentialType credentialType) {
doSetProperty("credentialType", credentialType);
return this;
}
/**
* Determines the credential strategy to adopt.
*
* The option will be converted to a
* <code>org.apache.camel.component.azure.storage.blob.CredentialType</code> type.
*
* Default: AZURE_IDENTITY
* Group: common
*
* @param credentialType the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder credentialType(String credentialType) {
doSetProperty("credentialType", credentialType);
return this;
}
/**
* How many bytes to include in the range. Must be greater than or equal
* to 0 if specified.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: common
*
* @param dataCount the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder dataCount(Long dataCount) {
doSetProperty("dataCount", dataCount);
return this;
}
/**
* How many bytes to include in the range. Must be greater than or equal
* to 0 if specified.
*
* The option will be converted to a <code>java.lang.Long</code> type.
*
* Group: common
*
* @param dataCount the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder dataCount(String dataCount) {
doSetProperty("dataCount", dataCount);
return this;
}
/**
* The file directory where the downloaded blobs will be saved to, this
* can be used in both, producer and consumer.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param fileDir the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder fileDir(String fileDir) {
doSetProperty("fileDir", fileDir);
return this;
}
/**
* Sets whether a lease should be acquired when accessing the blob. When
* set to true, the component will acquire a lease before performing
* blob operations that require exclusive access.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param leaseBlob the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder leaseBlob(boolean leaseBlob) {
doSetProperty("leaseBlob", leaseBlob);
return this;
}
/**
* Sets whether a lease should be acquired when accessing the blob. When
* set to true, the component will acquire a lease before performing
* blob operations that require exclusive access.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param leaseBlob the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder leaseBlob(String leaseBlob) {
doSetProperty("leaseBlob", leaseBlob);
return this;
}
/**
* Sets the lease duration in seconds. Use -1 for infinite or a value
* between 15 and 60 for fixed leases.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Default: 60
* Group: common
*
* @param leaseDurationInSeconds the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder leaseDurationInSeconds(Integer leaseDurationInSeconds) {
doSetProperty("leaseDurationInSeconds", leaseDurationInSeconds);
return this;
}
/**
* Sets the lease duration in seconds. Use -1 for infinite or a value
* between 15 and 60 for fixed leases.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Default: 60
* Group: common
*
* @param leaseDurationInSeconds the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder leaseDurationInSeconds(String leaseDurationInSeconds) {
doSetProperty("leaseDurationInSeconds", leaseDurationInSeconds);
return this;
}
/**
* Specifies the maximum number of blobs to return, including all
* BlobPrefix elements. If the request does not specify
* maxResultsPerPage or specifies a value greater than 5,000, the server
* will return up to 5,000 items.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: common
*
* @param maxResultsPerPage the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder maxResultsPerPage(Integer maxResultsPerPage) {
doSetProperty("maxResultsPerPage", maxResultsPerPage);
return this;
}
/**
* Specifies the maximum number of blobs to return, including all
* BlobPrefix elements. If the request does not specify
* maxResultsPerPage or specifies a value greater than 5,000, the server
* will return up to 5,000 items.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: common
*
* @param maxResultsPerPage the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder maxResultsPerPage(String maxResultsPerPage) {
doSetProperty("maxResultsPerPage", maxResultsPerPage);
return this;
}
/**
* Specifies the maximum number of additional HTTP Get requests that
* will be made while reading the data from a response body.
*
* The option is a: <code>int</code> type.
*
* Default: 0
* Group: common
*
* @param maxRetryRequests the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder maxRetryRequests(int maxRetryRequests) {
doSetProperty("maxRetryRequests", maxRetryRequests);
return this;
}
/**
* Specifies the maximum number of additional HTTP Get requests that
* will be made while reading the data from a response body.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 0
* Group: common
*
* @param maxRetryRequests the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder maxRetryRequests(String maxRetryRequests) {
doSetProperty("maxRetryRequests", maxRetryRequests);
return this;
}
/**
* Filters the results to return only blobs whose names begin with the
* specified prefix. May be null to return all blobs.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param prefix the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder prefix(String prefix) {
doSetProperty("prefix", prefix);
return this;
}
/**
* Filters the results to return only blobs whose names match the
* specified regular expression. May be null to return all if both
* prefix and regex are set, regex takes the priority and prefix is
* ignored.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param regex the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder regex(String regex) {
doSetProperty("regex", regex);
return this;
}
/**
* In case of usage of Shared Access Signature we'll need to set a SAS
* Token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param sasToken the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder sasToken(String sasToken) {
doSetProperty("sasToken", sasToken);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* BlobServiceClient#getBlobContainerClient(String), and operations on a
* blob are available on BlobClient through
* BlobContainerClient#getBlobClient(String).
*
* The option is a:
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param serviceClient the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder serviceClient(com.azure.storage.blob.BlobServiceClient serviceClient) {
doSetProperty("serviceClient", serviceClient);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* BlobServiceClient#getBlobContainerClient(String), and operations on a
* blob are available on BlobClient through
* BlobContainerClient#getBlobClient(String).
*
* The option will be converted to a
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param serviceClient the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder serviceClient(String serviceClient) {
doSetProperty("serviceClient", serviceClient);
return this;
}
/**
* An optional timeout value beyond which a RuntimeException will be
* raised.
*
* The option is a: <code>java.time.Duration</code> type.
*
* Group: common
*
* @param timeout the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder timeout(java.time.Duration timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* An optional timeout value beyond which a RuntimeException will be
* raised.
*
* The option will be converted to a <code>java.time.Duration</code>
* type.
*
* Group: common
*
* @param timeout the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder timeout(String timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* A user-controlled value that you can use to track requests. The value
* of the sequence number must be between 0 and 263 - 1.The default
* value is 0.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Default: 0
* Group: producer
*
* @param blobSequenceNumber the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobSequenceNumber(Long blobSequenceNumber) {
doSetProperty("blobSequenceNumber", blobSequenceNumber);
return this;
}
/**
* A user-controlled value that you can use to track requests. The value
* of the sequence number must be between 0 and 263 - 1.The default
* value is 0.
*
* The option will be converted to a <code>java.lang.Long</code> type.
*
* Default: 0
* Group: producer
*
* @param blobSequenceNumber the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blobSequenceNumber(String blobSequenceNumber) {
doSetProperty("blobSequenceNumber", blobSequenceNumber);
return this;
}
/**
* Specifies which type of blocks to return.
*
* The option is a:
* <code>com.azure.storage.blob.models.BlockListType</code> type.
*
* Default: COMMITTED
* Group: producer
*
* @param blockListType the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blockListType(com.azure.storage.blob.models.BlockListType blockListType) {
doSetProperty("blockListType", blockListType);
return this;
}
/**
* Specifies which type of blocks to return.
*
* The option will be converted to a
* <code>com.azure.storage.blob.models.BlockListType</code> type.
*
* Default: COMMITTED
* Group: producer
*
* @param blockListType the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder blockListType(String blockListType) {
doSetProperty("blockListType", blockListType);
return this;
}
/**
* When using getChangeFeed producer operation, this gives additional
* context that is passed through the Http pipeline during the service
* call.
*
* The option is a: <code>com.azure.core.util.Context</code> type.
*
* Group: producer
*
* @param changeFeedContext the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder changeFeedContext(com.azure.core.util.Context changeFeedContext) {
doSetProperty("changeFeedContext", changeFeedContext);
return this;
}
/**
* When using getChangeFeed producer operation, this gives additional
* context that is passed through the Http pipeline during the service
* call.
*
* The option will be converted to a
* <code>com.azure.core.util.Context</code> type.
*
* Group: producer
*
* @param changeFeedContext the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder changeFeedContext(String changeFeedContext) {
doSetProperty("changeFeedContext", changeFeedContext);
return this;
}
/**
* When using getChangeFeed producer operation, this filters the results
* to return events approximately before the end time. Note: A few
* events belonging to the next hour can also be returned. A few events
* belonging to this hour can be missing; to ensure all events from the
* hour are returned, round the end time up by an hour.
*
* The option is a: <code>java.time.OffsetDateTime</code> type.
*
* Group: producer
*
* @param changeFeedEndTime the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder changeFeedEndTime(java.time.OffsetDateTime changeFeedEndTime) {
doSetProperty("changeFeedEndTime", changeFeedEndTime);
return this;
}
/**
* When using getChangeFeed producer operation, this filters the results
* to return events approximately before the end time. Note: A few
* events belonging to the next hour can also be returned. A few events
* belonging to this hour can be missing; to ensure all events from the
* hour are returned, round the end time up by an hour.
*
* The option will be converted to a
* <code>java.time.OffsetDateTime</code> type.
*
* Group: producer
*
* @param changeFeedEndTime the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder changeFeedEndTime(String changeFeedEndTime) {
doSetProperty("changeFeedEndTime", changeFeedEndTime);
return this;
}
/**
* When using getChangeFeed producer operation, this filters the results
* to return events approximately after the start time. Note: A few
* events belonging to the previous hour can also be returned. A few
* events belonging to this hour can be missing; to ensure all events
* from the hour are returned, round the start time down by an hour.
*
* The option is a: <code>java.time.OffsetDateTime</code> type.
*
* Group: producer
*
* @param changeFeedStartTime the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder changeFeedStartTime(java.time.OffsetDateTime changeFeedStartTime) {
doSetProperty("changeFeedStartTime", changeFeedStartTime);
return this;
}
/**
* When using getChangeFeed producer operation, this filters the results
* to return events approximately after the start time. Note: A few
* events belonging to the previous hour can also be returned. A few
* events belonging to this hour can be missing; to ensure all events
* from the hour are returned, round the start time down by an hour.
*
* The option will be converted to a
* <code>java.time.OffsetDateTime</code> type.
*
* Group: producer
*
* @param changeFeedStartTime the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder changeFeedStartTime(String changeFeedStartTime) {
doSetProperty("changeFeedStartTime", changeFeedStartTime);
return this;
}
/**
* Close the stream after write or keep it open, default is true.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param closeStreamAfterWrite the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder closeStreamAfterWrite(boolean closeStreamAfterWrite) {
doSetProperty("closeStreamAfterWrite", closeStreamAfterWrite);
return this;
}
/**
* Close the stream after write or keep it open, default is true.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param closeStreamAfterWrite the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder closeStreamAfterWrite(String closeStreamAfterWrite) {
doSetProperty("closeStreamAfterWrite", closeStreamAfterWrite);
return this;
}
/**
* When is set to true, the staged blocks will not be committed
* directly.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param commitBlockListLater the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder commitBlockListLater(boolean commitBlockListLater) {
doSetProperty("commitBlockListLater", commitBlockListLater);
return this;
}
/**
* When is set to true, the staged blocks will not be committed
* directly.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param commitBlockListLater the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder commitBlockListLater(String commitBlockListLater) {
doSetProperty("commitBlockListLater", commitBlockListLater);
return this;
}
/**
* When is set to true, the append blocks will be created when
* committing append blocks.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param createAppendBlob the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder createAppendBlob(boolean createAppendBlob) {
doSetProperty("createAppendBlob", createAppendBlob);
return this;
}
/**
* When is set to true, the append blocks will be created when
* committing append blocks.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param createAppendBlob the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder createAppendBlob(String createAppendBlob) {
doSetProperty("createAppendBlob", createAppendBlob);
return this;
}
/**
* When is set to true, the page blob will be created when uploading
* page blob.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param createPageBlob the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder createPageBlob(boolean createPageBlob) {
doSetProperty("createPageBlob", createPageBlob);
return this;
}
/**
* When is set to true, the page blob will be created when uploading
* page blob.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param createPageBlob the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder createPageBlob(String createPageBlob) {
doSetProperty("createPageBlob", createPageBlob);
return this;
}
/**
* Override the default expiration (millis) of URL download link.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: producer
*
* @param downloadLinkExpiration the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder downloadLinkExpiration(Long downloadLinkExpiration) {
doSetProperty("downloadLinkExpiration", downloadLinkExpiration);
return this;
}
/**
* Override the default expiration (millis) of URL download link.
*
* The option will be converted to a <code>java.lang.Long</code> type.
*
* Group: producer
*
* @param downloadLinkExpiration the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder downloadLinkExpiration(String downloadLinkExpiration) {
doSetProperty("downloadLinkExpiration", downloadLinkExpiration);
return this;
}
/**
* The blob operation that can be used with this component on the
* producer.
*
* The option is a:
* <code>org.apache.camel.component.azure.storage.blob.BlobOperationsDefinition</code> type.
*
* Default: listBlobContainers
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder operation(org.apache.camel.component.azure.storage.blob.BlobOperationsDefinition operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The blob operation that can be used with this component on the
* producer.
*
* The option will be converted to a
* <code>org.apache.camel.component.azure.storage.blob.BlobOperationsDefinition</code> type.
*
* Default: listBlobContainers
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* Specifies the maximum size for the page blob, up to 8 TB. The page
* blob size must be aligned to a 512-byte boundary.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Default: 512
* Group: producer
*
* @param pageBlobSize the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder pageBlobSize(Long pageBlobSize) {
doSetProperty("pageBlobSize", pageBlobSize);
return this;
}
/**
* Specifies the maximum size for the page blob, up to 8 TB. The page
* blob size must be aligned to a 512-byte boundary.
*
* The option will be converted to a <code>java.lang.Long</code> type.
*
* Default: 512
* Group: producer
*
* @param pageBlobSize the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder pageBlobSize(String pageBlobSize) {
doSetProperty("pageBlobSize", pageBlobSize);
return this;
}
/**
* Access key for the associated azure account name to be used for
* authentication with azure blob services.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessKey the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder accessKey(String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* Azure Client ID for authentication with Azure Identity.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param azureClientId the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder azureClientId(String azureClientId) {
doSetProperty("azureClientId", azureClientId);
return this;
}
/**
* Azure Client Secret for authentication with Azure Identity.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param azureClientSecret the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder azureClientSecret(String azureClientSecret) {
doSetProperty("azureClientSecret", azureClientSecret);
return this;
}
/**
* Azure Tenant ID for authentication with Azure Identity.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param azureTenantId the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder azureTenantId(String azureTenantId) {
doSetProperty("azureTenantId", azureTenantId);
return this;
}
/**
* Source Blob Access Key: for copyblob operation, sadly, we need to
* have an accessKey for the source blob we want to copy Passing an
* accessKey as header, it's unsafe so we could set as key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param sourceBlobAccessKey the value to set
* @return the dsl builder
*/
default BlobEndpointProducerBuilder sourceBlobAccessKey(String sourceBlobAccessKey) {
doSetProperty("sourceBlobAccessKey", sourceBlobAccessKey);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Azure Storage Blob Service component.
*/
public | BlobEndpointProducerBuilder |
java | redisson__redisson | redisson/src/main/java/org/redisson/codec/JacksonCodec.java | {
"start": 1613,
"end": 5778
} | class ____<T> implements JsonCodec {
private final Encoder encoder = new Encoder() {
@Override
public ByteBuf encode(Object in) throws IOException {
ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
try {
ByteBufOutputStream os = new ByteBufOutputStream(out);
mapObjectMapper.writeValue((OutputStream) os, in);
return os.buffer();
} catch (IOException e) {
out.release();
throw e;
}
}
};
private final Decoder<Object> decoder = new Decoder<Object>() {
@Override
public Object decode(ByteBuf buf, State state) throws IOException {
if (valueClass != null) {
return mapObjectMapper.readValue((InputStream) new ByteBufInputStream(buf), valueClass);
}
return mapObjectMapper.readValue((InputStream) new ByteBufInputStream(buf), valueTypeReference);
}
};
private Class<T> valueClass;
private TypeReference<T> valueTypeReference;
private final ObjectMapper mapObjectMapper;
public JacksonCodec(Class<T> valueClass) {
if (valueClass == null) {
throw new NullPointerException("valueClass isn't defined");
}
this.valueClass = valueClass;
this.mapObjectMapper = new ObjectMapper();
init(mapObjectMapper);
}
public JacksonCodec(TypeReference<T> valueTypeReference) {
if (valueTypeReference == null) {
throw new NullPointerException("valueTypeReference isn't defined");
}
this.valueTypeReference = valueTypeReference;
this.mapObjectMapper = new ObjectMapper();
init(mapObjectMapper);
}
public JacksonCodec(ObjectMapper mapObjectMapper, TypeReference<T> valueTypeReference) {
if (mapObjectMapper == null) {
throw new NullPointerException("mapObjectMapper isn't defined");
}
if (valueTypeReference == null) {
throw new NullPointerException("valueTypeReference isn't defined");
}
this.mapObjectMapper = mapObjectMapper;
this.valueTypeReference = valueTypeReference;
}
public JacksonCodec(ObjectMapper mapObjectMapper, Class<T> valueClass) {
if (mapObjectMapper == null) {
throw new NullPointerException("mapObjectMapper isn't defined");
}
if (valueClass == null) {
throw new NullPointerException("valueClass isn't defined");
}
this.mapObjectMapper = mapObjectMapper;
this.valueClass = valueClass;
}
public JacksonCodec(ClassLoader classLoader, JacksonCodec<T> codec) {
this.valueClass = codec.valueClass;
this.valueTypeReference = codec.valueTypeReference;
this.mapObjectMapper = createObjectMapper(classLoader, codec.mapObjectMapper.copy());
}
protected static ObjectMapper createObjectMapper(ClassLoader classLoader, ObjectMapper om) {
TypeFactory tf = TypeFactory.defaultInstance().withClassLoader(classLoader);
om.setTypeFactory(tf);
return om;
}
protected void init(ObjectMapper objectMapper) {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setVisibility(objectMapper.getSerializationConfig()
.getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
}
@Override
public Encoder getEncoder() {
return encoder;
}
@Override
public Decoder<Object> getDecoder() {
return decoder;
}
}
| JacksonCodec |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java | {
"start": 41911,
"end": 42681
} | class ____ {
static int constructorCount = 0;
static int toStringCount = 0;
static int valueOfCount = 0;
static void reset() {
constructorCount = 0;
toStringCount = 0;
valueOfCount = 0;
}
private final String value;
public ISBN(String value) {
constructorCount++;
this.value = value;
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof ISBN isbn)) {
return false;
}
return this.value.equals(isbn.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
toStringCount++;
return value;
}
@SuppressWarnings("unused")
public static ISBN valueOf(String value) {
valueOfCount++;
return new ISBN(value);
}
}
}
| ISBN |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/scalar/MapValuesFunction.java | {
"start": 1254,
"end": 1630
} | class ____ extends BuiltInScalarFunction {
public MapValuesFunction(SpecializedFunction.SpecializedContext context) {
super(BuiltInFunctionDefinitions.MAP_VALUES, context);
}
public @Nullable ArrayData eval(@Nullable MapData input) {
if (input == null) {
return null;
}
return input.valueArray();
}
}
| MapValuesFunction |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java | {
"start": 2065,
"end": 19795
} | class ____ extends AbstractLangTest {
private static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZ";
private static final int NTHREADS = 10;
private static final int NROUNDS = 10000;
final Locale FINNISH = Locale.forLanguageTag("fi");
final Locale HUNGARIAN = Locale.forLanguageTag("hu");
private void assertCalendar(final TimeZone expectedTimeZone, final Date expectedDate, final Calendar actual) {
assertSame(expectedTimeZone, actual.getTimeZone());
// Calendar.getTime() returns a new Date in Java 8.
assertEquals(expectedDate, actual.getTime());
}
private AtomicLongArray measureTime(final Format printer, final Format parser) throws InterruptedException {
final ExecutorService pool = Executors.newFixedThreadPool(NTHREADS);
final AtomicInteger failures = new AtomicInteger();
final AtomicLongArray totalElapsed = new AtomicLongArray(2);
try {
for (int i = 0; i < NTHREADS; ++i) {
pool.submit(() -> {
for (int j = 0; j < NROUNDS; ++j) {
try {
final Date date = new Date();
final long t0Millis = System.currentTimeMillis();
final String formattedDate = printer.format(date);
totalElapsed.addAndGet(0, System.currentTimeMillis() - t0Millis);
final long t1Millis = System.currentTimeMillis();
final Object pd = parser.parseObject(formattedDate);
totalElapsed.addAndGet(1, System.currentTimeMillis() - t1Millis);
if (!date.equals(pd)) {
failures.incrementAndGet();
}
} catch (final Exception e) {
failures.incrementAndGet();
e.printStackTrace();
}
}
});
}
} finally {
pool.shutdown();
// depending on the performance of the machine used to run the parsing,
// the tests can run for a while. It should however complete within
// 30 seconds. Might need increase on very slow machines.
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
pool.shutdownNow();
fail("did not complete tasks");
}
}
assertEquals(0, failures.get());
return totalElapsed;
}
@DefaultLocale(language = "en", country = "US")
@Test
void test_changeDefault_Locale_DateInstance() {
final FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
final FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
Locale.setDefault(Locale.GERMANY);
final FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
assertSame(Locale.GERMANY, format1.getLocale());
assertEquals(Locale.US, format2.getLocale());
assertSame(Locale.GERMANY, format3.getLocale());
assertNotSame(format1, format2);
assertNotSame(format2, format3);
}
@DefaultLocale(language = "en", country = "US")
@Test
void test_changeDefault_Locale_DateTimeInstance() {
final FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
final FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
Locale.setDefault(Locale.GERMANY);
final FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
assertSame(Locale.GERMANY, format1.getLocale());
assertEquals(Locale.US, format2.getLocale());
assertSame(Locale.GERMANY, format3.getLocale());
assertNotSame(format1, format2);
assertNotSame(format2, format3);
}
/*
* Only the cache methods need to be tested here.
* The print methods are tested by {@link FastDateFormat_PrinterTest}
* and the parse methods are tested by {@link FastDateFormat_ParserTest}
*/
@Test
void test_getInstance() {
final FastDateFormat format1 = FastDateFormat.getInstance();
final FastDateFormat format2 = FastDateFormat.getInstance();
assertSame(format1, format2);
}
@Test
void test_getInstance_String() {
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy");
final FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy");
final FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy");
assertNotSame(format1, format2);
assertSame(format2, format3);
assertEquals("MM/DD/yyyy", format1.getPattern());
assertEquals(TimeZone.getDefault(), format1.getTimeZone());
assertEquals(TimeZone.getDefault(), format2.getTimeZone());
assertNotNull(FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZ"));
}
@DefaultLocale(language = "en", country = "US")
@Test
void test_getInstance_String_Locale() {
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
assertNotSame(format1, format2);
assertSame(format1, format3);
assertEquals(Locale.GERMANY, format1.getLocale());
}
@DefaultLocale(language = "en", country = "US")
@DefaultTimeZone("America/New_York")
@Test
void test_getInstance_String_TimeZone() {
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
TimeZones.getTimeZone("Atlantic/Reykjavik"));
final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
final FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
final FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
final FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
assertNotSame(format1, format2);
assertEquals(TimeZones.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
assertEquals(TimeZone.getDefault(), format2.getTimeZone());
assertSame(format3, format4);
assertNotSame(format3, format5);
assertNotSame(format4, format6);
}
@DefaultLocale(language = "en", country = "US")
@DefaultTimeZone("America/New_York")
@Test
void test_getInstance_String_TimeZone_Locale() {
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
TimeZones.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY);
final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
TimeZone.getDefault(), Locale.GERMANY);
assertNotSame(format1, format2);
assertEquals(TimeZones.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
assertEquals(TimeZone.getDefault(), format2.getTimeZone());
assertEquals(TimeZone.getDefault(), format3.getTimeZone());
assertEquals(Locale.GERMANY, format1.getLocale());
assertEquals(Locale.GERMANY, format2.getLocale());
assertEquals(Locale.GERMANY, format3.getLocale());
}
@Test
void testCheckDefaults() {
final FastDateFormat format = FastDateFormat.getInstance();
final FastDateFormat medium = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT);
assertEquals(medium, format);
final SimpleDateFormat sdf = new SimpleDateFormat();
assertEquals(sdf.toPattern(), format.getPattern());
assertEquals(Locale.getDefault(), format.getLocale());
assertEquals(TimeZone.getDefault(), format.getTimeZone());
}
@Test
void testCheckDifferingStyles() {
final FastDateFormat shortShort = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT, Locale.US);
final FastDateFormat shortLong = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.LONG, Locale.US);
final FastDateFormat longShort = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.SHORT, Locale.US);
final FastDateFormat longLong = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.LONG, Locale.US);
assertNotEquals(shortShort, shortLong);
assertNotEquals(shortShort, longShort);
assertNotEquals(shortShort, longLong);
assertNotEquals(shortLong, longShort);
assertNotEquals(shortLong, longLong);
assertNotEquals(longShort, longLong);
}
@Test
void testDateDefaults() {
assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, Locale.CANADA),
FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZones.getTimeZone("America/New_York")),
FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZones.getTimeZone("America/New_York"), Locale.getDefault()));
assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG),
FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
}
@Test
void testLang1152() {
final TimeZone utc = FastTimeZone.getGmtTimeZone();
final Date date = new Date(Long.MAX_VALUE);
String dateAsString = FastDateFormat.getInstance("yyyy-MM-dd", utc, Locale.US).format(date);
assertEquals("292278994-08-17", dateAsString);
dateAsString = FastDateFormat.getInstance("dd/MM/yyyy", utc, Locale.US).format(date);
assertEquals("17/08/292278994", dateAsString);
}
@Test
void testLang1267() {
FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
}
@Test
void testLang1641() {
assertSame(FastDateFormat.getInstance(ISO_8601_DATE_FORMAT), FastDateFormat.getInstance(ISO_8601_DATE_FORMAT));
// commons-lang's GMT TimeZone
assertSame(FastDateFormat.getInstance(ISO_8601_DATE_FORMAT, FastTimeZone.getGmtTimeZone()),
FastDateFormat.getInstance(ISO_8601_DATE_FORMAT, FastTimeZone.getGmtTimeZone()));
// default TimeZone
assertSame(FastDateFormat.getInstance(ISO_8601_DATE_FORMAT, TimeZone.getDefault()),
FastDateFormat.getInstance(ISO_8601_DATE_FORMAT, TimeZone.getDefault()));
// TimeZones that are identical in every way except ID
assertNotSame(FastDateFormat.getInstance(ISO_8601_DATE_FORMAT, TimeZones.getTimeZone("Australia/Broken_Hill")),
FastDateFormat.getInstance(ISO_8601_DATE_FORMAT, TimeZones.getTimeZone("Australia/Yancowinna")));
}
/**
* See LANG-1791 https://issues.apache.org/jira/browse/LANG-1791.
*/
@Test
@DefaultTimeZone("America/Toronto")
void testLang1791() {
final Instant now = Instant.now();
final String pattern = "yyyyMMddHH";
final FastDateFormat gmtFormatter = FastDateFormat.getInstance(pattern, TimeZones.GMT);
final Calendar gmtCal = Calendar.getInstance(TimeZones.GMT);
final TimeZone timeZone = gmtCal.getTimeZone();
final Date date = gmtCal.getTime();
final String gmtString = gmtFormatter.format(gmtCal);
// Asserts formatting doesn't edit the given Calendar
assertCalendar(timeZone, date, gmtCal);
assertEquals(DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.of("GMT")).format(now), gmtString);
final FastDateFormat defaultFormatter = FastDateFormat.getInstance(pattern);
final String defaultString = defaultFormatter.format(gmtCal);
// Asserts formatting doesn't edit the given Calendar
assertCalendar(timeZone, date, gmtCal);
assertEquals(DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault()).format(now), defaultString);
}
/**
* According to LANG-954 (https://issues.apache.org/jira/browse/LANG-954) this is broken in Android 2.1.
*/
@Test
void testLang954() {
final String pattern = "yyyy-MM-dd'T'";
FastDateFormat.getInstance(pattern);
}
/**
* Tests [LANG-1767] FastDateFormat.parse can not recognize "CEST" Timezone.
*
* @throws ParseException Throws on test failure.
*/
@Test
void testParseCentralEuropeanSummerTime() throws ParseException {
assertNotNull(FastDateFormat.getInstance("dd.MM.yyyy HH:mm:ss", Locale.GERMANY).parse("26.10.2014 02:00:00"));
assertNotNull(FastDateFormat.getInstance("dd.MM.yyyy HH:mm:ss z", Locale.US).parse("26.10.2014 02:00:00 CEST"));
assertNotNull(FastDateFormat.getInstance("dd.MM.yyyy HH:mm:ss z", Locale.GERMANY).parse("26.10.2014 02:00:00 MESZ"));
}
@Test
void testParseSync() throws InterruptedException {
final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
final SimpleDateFormat inner = new SimpleDateFormat(pattern);
final Format sdf = new Format() {
private static final long serialVersionUID = 1L;
@Override
public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
synchronized (this) {
return inner.format(obj, toAppendTo, fieldPosition);
}
}
@Override
public Object parseObject(final String source, final ParsePosition pos) {
synchronized (this) {
return inner.parseObject(source, pos);
}
}
};
final AtomicLongArray sdfTime = measureTime(sdf, sdf);
final Format fdf = FastDateFormat.getInstance(pattern);
final AtomicLongArray fdfTime = measureTime(fdf, fdf);
// System.out.println(">>FastDateFormatTest: FastDatePrinter:"+fdfTime.get(0)+" SimpleDateFormat:"+sdfTime.get(0));
// System.out.println(">>FastDateFormatTest: FastDateParser:"+fdfTime.get(1)+" SimpleDateFormat:"+sdfTime.get(1));
}
@Test
void testStandaloneLongMonthForm() {
final TimeZone utc = FastTimeZone.getGmtTimeZone();
final Instant testInstant = LocalDate.of(1970, 9, 15).atStartOfDay(ZoneId.of("UTC")).toInstant();
final Date date = Date.from(testInstant);
String dateAsString = FastDateFormat.getInstance("yyyy-LLLL-dd", utc, Locale.GERMAN).format(date);
assertEquals("1970-September-15", dateAsString);
dateAsString = FastDateFormat.getInstance("yyyy-LLLL-dd", utc, FINNISH).format(date);
assertEquals("1970-syyskuu-15", dateAsString);
dateAsString = FastDateFormat.getInstance("yyyy-LLLL-dd", utc, HUNGARIAN).format(date);
assertEquals("1970-szeptember-15", dateAsString);
}
@Test
void testStandaloneShortMonthForm() {
final TimeZone utc = FastTimeZone.getGmtTimeZone();
final Instant testInstant = LocalDate.of(1970, 9, 15).atStartOfDay(ZoneId.of("UTC")).toInstant();
final Date date = Date.from(testInstant);
String dateAsString = FastDateFormat.getInstance("yyyy-LLL-dd", utc, Locale.GERMAN).format(date);
assertEquals("1970-Sep-15", dateAsString);
dateAsString = FastDateFormat.getInstance("yyyy-LLL-dd", utc, FINNISH).format(date);
assertEquals("1970-syys-15", dateAsString);
dateAsString = FastDateFormat.getInstance("yyyy-LLL-dd", utc, HUNGARIAN).format(date);
assertEquals("1970-szept.-15", dateAsString);
}
@Test
void testTimeDateDefaults() {
assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, Locale.CANADA),
FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.CANADA));
assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZones.getTimeZone("America/New_York")),
FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZones.getTimeZone("America/New_York"), Locale.getDefault()));
assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM),
FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.getDefault()));
}
@Test
void testTimeDefaults() {
assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, Locale.CANADA),
FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZones.getTimeZone("America/New_York")),
FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZones.getTimeZone("America/New_York"), Locale.getDefault()));
assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG),
FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
}
}
| FastDateFormatTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/source/ignore/IgnoreUnmappedSourcePropertiesTest.java | {
"start": 485,
"end": 631
} | class ____ {
@ProcessorTest
public void shouldNotReportErrorOnIgnoredUnmappedSourceProperties() {
}
}
| IgnoreUnmappedSourcePropertiesTest |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/RouteConfigurationPreconditionTest.java | {
"start": 1162,
"end": 2087
} | class ____ extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/RouteConfigurationPreconditionTest.xml");
}
@Test
void testRouteConfigurationAreIncludedOrExcludedAsExpected() throws Exception {
assertCollectionSize(context.getRouteConfigurationDefinitions(), 2);
assertCollectionSize(context.getRouteDefinitions(), 2);
assertCollectionSize(context.getRoutes(), 2);
getMockEndpoint("mock:error").expectedMessageCount(2);
getMockEndpoint("mock:error").expectedBodiesReceived("Activated", "Default");
template.sendBody("direct:start", "Hello Activated Route Config");
template.sendBody("direct:start2", "Hello Not Activated Route Config");
assertMockEndpointsSatisfied();
}
}
| RouteConfigurationPreconditionTest |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/expressions/NullOrdering.java | {
"start": 998,
"end": 1207
} | enum ____ {
NULLS_FIRST, NULLS_LAST;
@Override
public String toString() {
return switch (this) {
case NULLS_FIRST -> "NULLS FIRST";
case NULLS_LAST -> "NULLS LAST";
};
}
}
| NullOrdering |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/WebListenerRegistry.java | {
"start": 999,
"end": 1096
} | class ____ of the web listeners
*/
void addWebListeners(String... webListenerClassNames);
}
| names |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/state/MapStateDescriptor.java | {
"start": 3916,
"end": 5183
} | class ____ the type of values in the state.
*/
public MapStateDescriptor(String name, Class<UK> keyClass, Class<UV> valueClass) {
super(name, new MapTypeInfo<>(keyClass, valueClass), null);
}
@Override
public Type getType() {
return Type.MAP;
}
/**
* Gets the serializer for the keys in the state.
*
* @return The serializer for the keys in the state.
*/
public TypeSerializer<UK> getKeySerializer() {
final TypeSerializer<Map<UK, UV>> rawSerializer = getSerializer();
if (!(rawSerializer instanceof MapSerializer)) {
throw new IllegalStateException("Unexpected serializer type.");
}
return ((MapSerializer<UK, UV>) rawSerializer).getKeySerializer();
}
/**
* Gets the serializer for the values in the state.
*
* @return The serializer for the values in the state.
*/
public TypeSerializer<UV> getValueSerializer() {
final TypeSerializer<Map<UK, UV>> rawSerializer = getSerializer();
if (!(rawSerializer instanceof MapSerializer)) {
throw new IllegalStateException("Unexpected serializer type.");
}
return ((MapSerializer<UK, UV>) rawSerializer).getValueSerializer();
}
}
| of |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.