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
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRoc.java
|
{
"start": 10866,
"end": 12876
}
|
class ____ implements EvaluationMetricResult {
public static final String NAME = "auc_roc_result";
private static final String VALUE = "value";
private static final String CURVE = "curve";
private final double value;
private final List<AucRocPoint> curve;
public Result(double value, List<AucRocPoint> curve) {
this.value = value;
this.curve = Objects.requireNonNull(curve);
}
public Result(StreamInput in) throws IOException {
this.value = in.readDouble();
this.curve = in.readCollectionAsList(AucRocPoint::new);
}
public double getValue() {
return value;
}
public List<AucRocPoint> getCurve() {
return Collections.unmodifiableList(curve);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public String getMetricName() {
return AbstractAucRoc.NAME.getPreferredName();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeDouble(value);
out.writeCollection(curve);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(VALUE, value);
if (curve.isEmpty() == false) {
builder.field(CURVE, curve);
}
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Result that = (Result) o;
return value == that.value && Objects.equals(curve, that.curve);
}
@Override
public int hashCode() {
return Objects.hash(value, curve);
}
}
}
|
Result
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitorAdapter.java
|
{
"start": 737,
"end": 826
}
|
class ____ extends SQLASTVisitorAdapter implements MySqlASTVisitor {
}
|
MySqlASTVisitorAdapter
|
java
|
apache__dubbo
|
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java
|
{
"start": 1103,
"end": 1185
}
|
interface ____ {
/**
* Listener for receive response.
*/
|
ClientCall
|
java
|
spring-projects__spring-framework
|
spring-messaging/src/main/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistry.java
|
{
"start": 2921,
"end": 8935
}
|
class ____ extends AbstractSubscriptionRegistry {
/** Default maximum number of entries for the destination cache: 1024. */
public static final int DEFAULT_CACHE_LIMIT = 1024;
/** Static evaluation context to reuse. */
private static final EvaluationContext messageEvalContext =
SimpleEvaluationContext.forPropertyAccessors(new SimpMessageHeaderPropertyAccessor()).build();
private PathMatcher pathMatcher = new AntPathMatcher();
private int cacheLimit = DEFAULT_CACHE_LIMIT;
private @Nullable String selectorHeaderName;
private volatile boolean selectorHeaderInUse;
private final ExpressionParser expressionParser = new SpelExpressionParser();
private final DestinationCache destinationCache = new DestinationCache();
private final SessionRegistry sessionRegistry = new SessionRegistry();
/**
* Specify the {@link PathMatcher} to use.
*/
public void setPathMatcher(PathMatcher pathMatcher) {
this.pathMatcher = pathMatcher;
}
/**
* Return the configured {@link PathMatcher}.
*/
public PathMatcher getPathMatcher() {
return this.pathMatcher;
}
/**
* Specify the maximum number of entries for the resolved destination cache.
* Default is 1024.
*/
public void setCacheLimit(int cacheLimit) {
this.cacheLimit = cacheLimit;
this.destinationCache.ensureCacheLimit();
}
/**
* Return the maximum number of entries for the resolved destination cache.
*/
public int getCacheLimit() {
return this.cacheLimit;
}
/**
* Configure the name of a header that a subscription message can have for
* the purpose of filtering messages matched to the subscription.
* <p>The header value is expected to be a Spring Expression Language (SpEL)
* boolean expression to be applied to the headers of messages matched to the
* subscription.
* <p>For example:
* <pre style="code">
* headers.foo == 'bar'
* </pre>
* <p>By default the selector header name is set to {@code null} which disables
* this feature. You can set it to {@code "selector"} or a different name to
* enable support for a selector header.
* @param selectorHeaderName the name to use for a selector header, or {@code null}
* or blank to disable selector header support
* @since 4.2
*/
public void setSelectorHeaderName(@Nullable String selectorHeaderName) {
this.selectorHeaderName = (StringUtils.hasText(selectorHeaderName) ? selectorHeaderName : null);
}
/**
* Return the name of the selector header.
* @since 4.2
* @see #setSelectorHeaderName(String)
*/
public @Nullable String getSelectorHeaderName() {
return this.selectorHeaderName;
}
@Override
protected void addSubscriptionInternal(
String sessionId, String subscriptionId, String destination, Message<?> message) {
boolean isPattern = this.pathMatcher.isPattern(destination);
Expression expression = getSelectorExpression(message.getHeaders());
Subscription subscription = new Subscription(subscriptionId, destination, isPattern, expression);
this.sessionRegistry.addSubscription(sessionId, subscription);
this.destinationCache.updateAfterNewSubscription(sessionId, subscription);
}
private @Nullable Expression getSelectorExpression(MessageHeaders headers) {
if (getSelectorHeaderName() == null) {
return null;
}
String selector = NativeMessageHeaderAccessor.getFirstNativeHeader(getSelectorHeaderName(), headers);
if (selector == null) {
return null;
}
Expression expression = null;
try {
expression = this.expressionParser.parseExpression(selector);
this.selectorHeaderInUse = true;
if (logger.isTraceEnabled()) {
logger.trace("Subscription selector: [" + selector + "]");
}
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to parse selector: " + selector, ex);
}
}
return expression;
}
@Override
protected void removeSubscriptionInternal(String sessionId, String subscriptionId, Message<?> message) {
SessionInfo info = this.sessionRegistry.getSession(sessionId);
if (info != null) {
Subscription subscription = info.removeSubscription(subscriptionId);
if (subscription != null) {
this.destinationCache.updateAfterRemovedSubscription(sessionId, subscription);
}
}
}
@Override
public void unregisterAllSubscriptions(String sessionId) {
SessionInfo info = this.sessionRegistry.removeSubscriptions(sessionId);
if (info != null) {
this.destinationCache.updateAfterRemovedSession(sessionId, info);
}
}
@Override
protected MultiValueMap<String, String> findSubscriptionsInternal(String destination, Message<?> message) {
MultiValueMap<String, String> allMatches = this.destinationCache.getSubscriptions(destination);
if (!this.selectorHeaderInUse) {
return allMatches;
}
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(allMatches.size());
allMatches.forEach((sessionId, subscriptionIds) -> {
SessionInfo info = this.sessionRegistry.getSession(sessionId);
if (info != null) {
for (String subscriptionId : subscriptionIds) {
Subscription subscription = info.getSubscription(subscriptionId);
if (subscription != null && evaluateExpression(subscription.getSelector(), message)) {
result.add(sessionId, subscription.getId());
}
}
}
});
return result;
}
private boolean evaluateExpression(@Nullable Expression expression, Message<?> message) {
if (expression == null) {
return true;
}
try {
Boolean result = expression.getValue(messageEvalContext, message, Boolean.class);
if (Boolean.TRUE.equals(result)) {
return true;
}
}
catch (SpelEvaluationException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to evaluate selector: " + ex.getMessage());
}
}
catch (Throwable ex) {
logger.debug("Failed to evaluate selector", ex);
}
return false;
}
/**
* Cache for destinations resolved previously via
* {@link DefaultSubscriptionRegistry#findSubscriptionsInternal(String, Message)}.
*/
private final
|
DefaultSubscriptionRegistry
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/buffer/LocalBufferPoolTest.java
|
{
"start": 38172,
"end": 38678
}
|
class ____ extends NetworkBufferPool {
private int requestCounter;
public TestNetworkBufferPool(int numberOfSegmentsToAllocate, int segmentSize) {
super(numberOfSegmentsToAllocate, segmentSize);
}
@Nullable
@Override
public MemorySegment requestPooledMemorySegment() {
if (requestCounter++ == 1) {
return null;
}
return super.requestPooledMemorySegment();
}
}
}
|
TestNetworkBufferPool
|
java
|
elastic__elasticsearch
|
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/EnterpriseGeoIpDownloaderTaskExecutor.java
|
{
"start": 2430,
"end": 8240
}
|
class ____ extends PersistentTasksExecutor<EnterpriseGeoIpTaskParams>
implements
ClusterStateListener {
private static final Logger logger = LogManager.getLogger(EnterpriseGeoIpDownloader.class);
static final String MAXMIND_SETTINGS_PREFIX = "ingest.geoip.downloader.maxmind.";
static final String IPINFO_SETTINGS_PREFIX = "ingest.ip_location.downloader.ipinfo.";
public static final Setting<SecureString> MAXMIND_LICENSE_KEY_SETTING = SecureSetting.secureString(
MAXMIND_SETTINGS_PREFIX + "license_key",
null
);
public static final Setting<SecureString> IPINFO_TOKEN_SETTING = SecureSetting.secureString(IPINFO_SETTINGS_PREFIX + "token", null);
private final Client client;
private final HttpClient httpClient;
private final ClusterService clusterService;
private final ThreadPool threadPool;
private final Settings settings;
private volatile TimeValue pollInterval;
private final AtomicReference<EnterpriseGeoIpDownloader> currentTask = new AtomicReference<>();
private volatile SecureSettings cachedSecureSettings;
EnterpriseGeoIpDownloaderTaskExecutor(Client client, HttpClient httpClient, ClusterService clusterService, ThreadPool threadPool) {
super(ENTERPRISE_GEOIP_DOWNLOADER, threadPool.generic());
this.client = new OriginSettingClient(client, IngestService.INGEST_ORIGIN);
this.httpClient = httpClient;
this.clusterService = clusterService;
this.threadPool = threadPool;
this.settings = clusterService.getSettings();
this.pollInterval = POLL_INTERVAL_SETTING.get(settings);
// do an initial load using the node settings
reload(clusterService.getSettings());
}
/**
* This method completes the initialization of the EnterpriseGeoIpDownloaderTaskExecutor by registering several listeners.
*/
public void init() {
clusterService.addListener(this);
clusterService.getClusterSettings().addSettingsUpdateConsumer(POLL_INTERVAL_SETTING, this::setPollInterval);
}
private void setPollInterval(TimeValue pollInterval) {
if (Objects.equals(this.pollInterval, pollInterval) == false) {
this.pollInterval = pollInterval;
EnterpriseGeoIpDownloader currentDownloader = getCurrentTask();
if (currentDownloader != null) {
currentDownloader.restartPeriodicRun();
}
}
}
private char[] getSecureToken(final String type) {
char[] token = null;
if (type.equals("maxmind")) {
if (cachedSecureSettings.getSettingNames().contains(MAXMIND_LICENSE_KEY_SETTING.getKey())) {
token = cachedSecureSettings.getString(MAXMIND_LICENSE_KEY_SETTING.getKey()).getChars();
}
} else if (type.equals("ipinfo")) {
if (cachedSecureSettings.getSettingNames().contains(IPINFO_TOKEN_SETTING.getKey())) {
token = cachedSecureSettings.getString(IPINFO_TOKEN_SETTING.getKey()).getChars();
}
}
return token;
}
@Override
protected EnterpriseGeoIpDownloader createTask(
long id,
String type,
String action,
TaskId parentTaskId,
PersistentTasksCustomMetadata.PersistentTask<EnterpriseGeoIpTaskParams> taskInProgress,
Map<String, String> headers
) {
return new EnterpriseGeoIpDownloader(
client,
httpClient,
clusterService,
threadPool,
id,
type,
action,
getDescription(taskInProgress),
parentTaskId,
headers,
() -> pollInterval,
this::getSecureToken
);
}
@Override
protected void nodeOperation(AllocatedPersistentTask task, EnterpriseGeoIpTaskParams params, PersistentTaskState state) {
EnterpriseGeoIpDownloader downloader = (EnterpriseGeoIpDownloader) task;
EnterpriseGeoIpTaskState geoIpTaskState = (state == null) ? EnterpriseGeoIpTaskState.EMPTY : (EnterpriseGeoIpTaskState) state;
downloader.setState(geoIpTaskState);
currentTask.set(downloader);
if (ENABLED_SETTING.get(clusterService.state().metadata().settings(), settings)) {
downloader.restartPeriodicRun();
}
}
public EnterpriseGeoIpDownloader getCurrentTask() {
return currentTask.get();
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
EnterpriseGeoIpDownloader currentDownloader = getCurrentTask();
if (currentDownloader != null) {
boolean hasGeoIpMetadataChanges = event.metadataChanged()
&& event.changedCustomProjectMetadataSet().contains(IngestGeoIpMetadata.TYPE);
if (hasGeoIpMetadataChanges) {
// watching the cluster changed events to kick the thing off if it's not running
currentDownloader.requestRunOnDemand();
}
}
}
public synchronized void reload(Settings settings) {
// `SecureSettings` are available here! cache them as they will be needed
// whenever dynamic cluster settings change and we have to rebuild the accounts
try {
this.cachedSecureSettings = InMemoryClonedSecureSettings.cloneSecureSettings(
settings,
List.of(MAXMIND_LICENSE_KEY_SETTING, IPINFO_TOKEN_SETTING)
);
} catch (GeneralSecurityException e) {
// rethrow as a runtime exception, there's logging higher up the call chain around ReloadablePlugin
throw new ElasticsearchException("Exception while reloading enterprise geoip download task executor", e);
}
}
}
|
EnterpriseGeoIpDownloaderTaskExecutor
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TokenAndRegisterResponse.java
|
{
"start": 1075,
"end": 1177
}
|
class ____ information about the AMRM token and the RegisterApplicationMasterResponse.
*/
public
|
contains
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/core/fs/FileSystemSafetyNet.java
|
{
"start": 1979,
"end": 2453
}
|
class ____ extends Thread {
*
* public void run() {
* FileSystemSafetyNet.initializeSafetyNetForThread();
* try {
* // do some heavy stuff where you are unsure whether it closes all streams
* // like some untrusted user code or library code
* }
* finally {
* FileSystemSafetyNet.closeSafetyNetAndGuardedResourcesForThread();
* }
* }
* }
* }</pre>
*/
@Internal
public
|
GuardedThread
|
java
|
quarkusio__quarkus
|
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/DeprecatedGraphQLDirectivesTest.java
|
{
"start": 533,
"end": 2331
}
|
class ____ extends AbstractGraphQLTest {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Person.class)
.addAsResource(new StringAsset("quarkus.smallrye-graphql.schema-include-directives=true"),
"application.properties")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));
@Test
public void deprecatedDirectivesPresentInSchema() {
get("/graphql/schema.graphql")
.then()
.body(
containsString("input PersonInput {\n" +
" age: Int! @deprecated\n" +
" name: String @deprecated(reason : \"reason0\")\n" +
" numberOfEyes: BigInteger! @deprecated\n" +
"}\n"),
containsString("graphQLDeprecatedQuery: String @deprecated"),
containsString("javaLangDeprecatedQuery: String @deprecated"),
containsString(
"queryWithGraphQLDeprecatedArgument(deprecated: String @deprecated(reason : \"reason1\")): String"),
containsString("queryWithJavaLangDeprecatedArgument(deprecated: String @deprecated): String"),
containsString("type Person {\n" +
" age: Int! @deprecated\n" +
" name: String @deprecated(reason : \"reason0\")\n" +
" numberOfEyes: BigInteger! @deprecated\n" +
"}"),
containsString("
|
DeprecatedGraphQLDirectivesTest
|
java
|
apache__camel
|
components/camel-azure/camel-azure-storage-blob/src/main/java/org/apache/camel/component/azure/storage/blob/BlobOperationsDefinition.java
|
{
"start": 916,
"end": 5444
}
|
enum ____ {
// Operations on the service level
//
/**
* Returns a list of containers in the storage account.
*/
listBlobContainers,
// Operations on the container level
//
/**
* Creates a new container within a storage account. If a container with the same name already exists, the producer
* will ignore it.
*/
createBlobContainer,
/**
* Deletes the specified container in the storage account. If the container doesn't exist the operation fails.
*/
deleteBlobContainer,
/**
* Returns a list of blobs in this container, with folder structures flattened.
*/
listBlobs,
// Operations on the blob level
//
/**
* Get the content of the blob, can be restricted to a blob range.
*/
getBlob,
/**
* Delete a blob
*/
deleteBlob,
/**
* Downloads the entire blob into a file specified by the path.
*
* The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} will
* be thrown.
*/
downloadBlobToFile,
/**
* Generates the download link for the specified blob using shared access signatures (SAS). This by default only
* limit to 1hour of allowed access. However, you can override the default expiration duration through the headers.
*/
downloadLink,
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content.
*/
uploadBlockBlob,
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlobBlockList. However in case header `CamelAzureStorageBlobCommitBlobBlockListLater` is set to false, this
* will also commit the blocks.
*/
stageBlockBlobList,
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior `stageBlockBlobList` operation. You
* can call `commitBlobBlockList` to update a blob by uploading only those blocks that have changed, then committing
* the new and existing blocks together. Any blocks not specified in the block list and permanently deleted.
*/
commitBlobBlockList,
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter.
*/
getBlobBlockList,
/**
* Creates a 0-length append blob. Call commitAppendBlo`b operation to append data to an append blob.
*/
createAppendBlob,
/**
* Commits a new block of data to the end of the existing append blob. In case of header
* `CamelAzureStorageBlobAppendBlobCreated` is set to false, it will attempt to create the appendBlob through
* internal call to `createAppendBlob` operation.
*/
commitAppendBlob,
/**
* Creates a page blob of the specified length. Call `uploadPageBlob` operation to upload data data to a page blob.
*/
createPageBlob,
/**
* Writes one or more pages to the page blob. The write size must be a multiple of 512. In case of header
* `CamelAzureStorageBlobPageBlockCreated` is set to false, it will attempt to create the appendBlob through
* internal call to `createPageBlob` operation.
*/
uploadPageBlob,
/**
* Resizes the page blob to the specified size (which must be a multiple of 512).
*/
resizePageBlob,
/**
* Frees the specified pages from the page blob. The size of the range must be a multiple of 512.
*/
clearPageBlob,
/**
* Returns the list of valid page ranges for a page blob or snapshot of a page blob.
*/
getPageBlobRanges,
/**
* Returns transaction logs of all the changes that occur to the blobs and the blob metadata in your storage
* account. The change feed provides ordered, guaranteed, durable, immutable, read-only log of these changes.
*/
getChangeFeed,
/**
* Returns transaction logs of all the changes that occur to the blobs and the blob metadata in your storage
* account. The change feed provides ordered, guaranteed, durable, immutable, read-only log of these changes.
*/
copyBlob
}
|
BlobOperationsDefinition
|
java
|
google__dagger
|
javatests/artifacts/dagger/build-tests/src/test/java/buildtests/TransitiveSubcomponentScopeTest.java
|
{
"start": 4605,
"end": 5593
}
|
interface ____ {",
" MySubcomponent mySubcomponent();",
"}");
GradleModule.create(projectDir, "library1")
.addBuildFile(
"plugins {",
" id 'java'",
" id 'java-library'",
"}",
"dependencies {",
transitiveDependencyType + " project(':library2')",
" implementation \"com.google.dagger:dagger:$dagger_version\"",
" annotationProcessor \"com.google.dagger:dagger-compiler:$dagger_version\"",
"}")
.addSrcFile(
"MySubcomponent.java",
"package library1;",
"",
"import dagger.Module;",
"import dagger.Provides;",
"import dagger.Subcomponent;",
"import library2.MySubcomponentScope;",
"",
"@MySubcomponentScope",
"@Subcomponent(modules = MySubcomponent.MySubcomponentModule.class)",
"public abstract
|
MyComponent
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/validation/Validator.java
|
{
"start": 2405,
"end": 2666
}
|
interface ____ its role in an enterprise application.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Toshiaki Maki
* @author Arjen Poutsma
* @see SmartValidator
* @see Errors
* @see ValidationUtils
* @see DataBinder#setValidator
*/
public
|
and
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/score/DecayLongEvaluator.java
|
{
"start": 4661,
"end": 5844
}
|
class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory value;
private final long origin;
private final long scale;
private final long offset;
private final double decay;
private final Decay.DecayFunction decayFunction;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory value, long origin,
long scale, long offset, double decay, Decay.DecayFunction decayFunction) {
this.source = source;
this.value = value;
this.origin = origin;
this.scale = scale;
this.offset = offset;
this.decay = decay;
this.decayFunction = decayFunction;
}
@Override
public DecayLongEvaluator get(DriverContext context) {
return new DecayLongEvaluator(source, value.get(context), origin, scale, offset, decay, decayFunction, context);
}
@Override
public String toString() {
return "DecayLongEvaluator[" + "value=" + value + ", origin=" + origin + ", scale=" + scale + ", offset=" + offset + ", decay=" + decay + ", decayFunction=" + decayFunction + "]";
}
}
}
|
Factory
|
java
|
apache__flink
|
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/operators/windowing/KeyMapTest.java
|
{
"start": 1143,
"end": 11907
}
|
class ____ {
@Test
void testInitialSizeComputation() {
KeyMap<String, String> map;
map = new KeyMap<>();
assertThat(map.getCurrentTableCapacity()).isEqualTo(64);
assertThat(map.getLog2TableCapacity()).isEqualTo(6);
assertThat(map.getShift()).isEqualTo(24);
assertThat(map.getRehashThreshold()).isEqualTo(48);
map = new KeyMap<>(0);
assertThat(map.getCurrentTableCapacity()).isEqualTo(64);
assertThat(map.getLog2TableCapacity()).isEqualTo(6);
assertThat(map.getShift()).isEqualTo(24);
assertThat(map.getRehashThreshold()).isEqualTo(48);
map = new KeyMap<>(1);
assertThat(map.getCurrentTableCapacity()).isEqualTo(64);
assertThat(map.getLog2TableCapacity()).isEqualTo(6);
assertThat(map.getShift()).isEqualTo(24);
assertThat(map.getRehashThreshold()).isEqualTo(48);
map = new KeyMap<>(9);
assertThat(map.getCurrentTableCapacity()).isEqualTo(64);
assertThat(map.getLog2TableCapacity()).isEqualTo(6);
assertThat(map.getShift()).isEqualTo(24);
assertThat(map.getRehashThreshold()).isEqualTo(48);
map = new KeyMap<>(63);
assertThat(map.getCurrentTableCapacity()).isEqualTo(64);
assertThat(map.getLog2TableCapacity()).isEqualTo(6);
assertThat(map.getShift()).isEqualTo(24);
assertThat(map.getRehashThreshold()).isEqualTo(48);
map = new KeyMap<>(64);
assertThat(map.getCurrentTableCapacity()).isEqualTo(128);
assertThat(map.getLog2TableCapacity()).isEqualTo(7);
assertThat(map.getShift()).isEqualTo(23);
assertThat(map.getRehashThreshold()).isEqualTo(96);
map = new KeyMap<>(500);
assertThat(map.getCurrentTableCapacity()).isEqualTo(512);
assertThat(map.getLog2TableCapacity()).isEqualTo(9);
assertThat(map.getShift()).isEqualTo(21);
assertThat(map.getRehashThreshold()).isEqualTo(384);
map = new KeyMap<>(127);
assertThat(map.getCurrentTableCapacity()).isEqualTo(128);
assertThat(map.getLog2TableCapacity()).isEqualTo(7);
assertThat(map.getShift()).isEqualTo(23);
assertThat(map.getRehashThreshold()).isEqualTo(96);
// no negative number of elements
assertThatThrownBy(() -> new KeyMap<>(-1)).isInstanceOf(IllegalArgumentException.class);
// check integer overflow
try {
map = new KeyMap<>(0x65715522);
final int maxCap = Integer.highestOneBit(Integer.MAX_VALUE);
assertThat(map.getCurrentTableCapacity()).isEqualTo(maxCap);
assertThat(map.getLog2TableCapacity()).isEqualTo(30);
assertThat(map.getShift()).isZero();
assertThat(map.getRehashThreshold()).isEqualTo(maxCap / 4 * 3);
} catch (OutOfMemoryError e) {
// this may indeed happen in small test setups. we tolerate this in this test
}
}
@Test
void testPutAndGetRandom() {
final KeyMap<Integer, Integer> map = new KeyMap<>();
final Random rnd = new Random();
final long seed = rnd.nextLong();
final int numElements = 10000;
final HashMap<Integer, Integer> groundTruth = new HashMap<>();
rnd.setSeed(seed);
for (int i = 0; i < numElements; i++) {
Integer key = rnd.nextInt();
Integer value = rnd.nextInt();
if (rnd.nextBoolean()) {
groundTruth.put(key, value);
map.put(key, value);
}
}
rnd.setSeed(seed);
for (int i = 0; i < numElements; i++) {
Integer key = rnd.nextInt();
// skip these, evaluating it is tricky due to duplicates
rnd.nextInt();
rnd.nextBoolean();
Integer expected = groundTruth.get(key);
if (expected == null) {
assertThat(map.get(key)).isNull();
} else {
Integer contained = map.get(key);
assertThat(contained).isNotNull().isEqualTo(expected);
}
}
}
@Test
void testConjunctTraversal() throws Exception {
final Random rootRnd = new Random(654685486325439L);
final int numMaps = 7;
final int numKeys = 1000000;
// ------ create a set of maps ------
@SuppressWarnings("unchecked")
final KeyMap<Integer, Integer>[] maps =
(KeyMap<Integer, Integer>[]) new KeyMap<?, ?>[numMaps];
for (int i = 0; i < numMaps; i++) {
maps[i] = new KeyMap<>();
}
// ------ prepare probabilities for maps ------
final double[] probabilities = new double[numMaps];
final double[] probabilitiesTemp = new double[numMaps];
{
probabilities[0] = 0.5;
double remainingProb = 1.0 - probabilities[0];
for (int i = 1; i < numMaps - 1; i++) {
remainingProb /= 2;
probabilities[i] = remainingProb;
}
// compensate for rounding errors
probabilities[numMaps - 1] = remainingProb;
}
// ------ generate random elements ------
final long probSeed = rootRnd.nextLong();
final long keySeed = rootRnd.nextLong();
final Random probRnd = new Random(probSeed);
final Random keyRnd = new Random(keySeed);
final int maxStride = Integer.MAX_VALUE / numKeys;
int totalNumElements = 0;
int nextKeyValue = 1;
for (int i = 0; i < numKeys; i++) {
int numCopies = (nextKeyValue % 3) + 1;
System.arraycopy(probabilities, 0, probabilitiesTemp, 0, numMaps);
double totalProb = 1.0;
for (int copy = 0; copy < numCopies; copy++) {
int pos = drawPosProportionally(probabilitiesTemp, totalProb, probRnd);
totalProb -= probabilitiesTemp[pos];
probabilitiesTemp[pos] = 0.0;
Integer boxed = nextKeyValue;
Integer previous = maps[pos].put(boxed, boxed);
assertThat(previous).as("Test problem - test does not assign unique maps").isNull();
}
totalNumElements += numCopies;
nextKeyValue += keyRnd.nextInt(maxStride) + 1;
}
// check that all maps contain the total number of elements
int numContained = 0;
for (KeyMap<?, ?> map : maps) {
numContained += map.size();
}
assertThat(numContained).isEqualTo(totalNumElements);
// ------ check that all elements can be found in the maps ------
keyRnd.setSeed(keySeed);
numContained = 0;
nextKeyValue = 1;
for (int i = 0; i < numKeys; i++) {
int numCopiesExpected = (nextKeyValue % 3) + 1;
int numCopiesContained = 0;
for (KeyMap<Integer, Integer> map : maps) {
Integer val = map.get(nextKeyValue);
if (val != null) {
assertThat(val).isEqualTo(nextKeyValue);
numCopiesContained++;
}
}
assertThat(numCopiesContained).isEqualTo(numCopiesExpected);
numContained += numCopiesContained;
nextKeyValue += keyRnd.nextInt(maxStride) + 1;
}
assertThat(numContained).isEqualTo(totalNumElements);
// ------ make a traversal over all keys and validate the keys in the traversal ------
final int[] keysStartedAndFinished = {0, 0};
KeyMap.TraversalEvaluator<Integer, Integer> traversal =
new KeyMap.TraversalEvaluator<Integer, Integer>() {
private int key;
private int valueCount;
@Override
public void startNewKey(Integer key) {
this.key = key;
this.valueCount = 0;
keysStartedAndFinished[0]++;
}
@Override
public void nextValue(Integer value) {
assertThat(value).isEqualTo(this.key);
this.valueCount++;
}
@Override
public void keyDone() {
int expected = (key % 3) + 1;
assertThat(valueCount)
.as(
"Wrong count for key "
+ key
+ " ; expected="
+ expected
+ " , count="
+ valueCount)
.isEqualTo(expected);
keysStartedAndFinished[1]++;
}
};
KeyMap.traverseMaps(shuffleArray(maps, rootRnd), traversal, 17);
assertThat(keysStartedAndFinished[0]).isEqualTo(numKeys);
assertThat(keysStartedAndFinished[1]).isEqualTo(numKeys);
}
@Test
void testSizeComparator() {
KeyMap<String, String> map1 = new KeyMap<>(5);
KeyMap<String, String> map2 = new KeyMap<>(80);
assertThat(map1.getCurrentTableCapacity()).isLessThan(map2.getCurrentTableCapacity());
assertThat(KeyMap.CapacityDescendingComparator.INSTANCE.compare(map1, map1)).isZero();
assertThat(KeyMap.CapacityDescendingComparator.INSTANCE.compare(map2, map2)).isZero();
assertThat(KeyMap.CapacityDescendingComparator.INSTANCE.compare(map1, map2)).isPositive();
assertThat(KeyMap.CapacityDescendingComparator.INSTANCE.compare(map2, map1)).isNegative();
}
// ------------------------------------------------------------------------
private static int drawPosProportionally(double[] array, double totalProbability, Random rnd) {
double val = rnd.nextDouble() * totalProbability;
double accum = 0;
for (int i = 0; i < array.length; i++) {
accum += array[i];
if (val <= accum && array[i] > 0.0) {
return i;
}
}
// in case of rounding errors
return array.length - 1;
}
private static <E> E[] shuffleArray(E[] array, Random rnd) {
E[] target = Arrays.copyOf(array, array.length);
for (int i = target.length - 1; i > 0; i--) {
int swapPos = rnd.nextInt(i + 1);
E temp = target[i];
target[i] = target[swapPos];
target[swapPos] = temp;
}
return target;
}
}
|
KeyMapTest
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/json/AbstractJsonContentAssertTests.java
|
{
"start": 3914,
"end": 4541
}
|
class ____ {
@Test
void convertToTargetType() {
assertThat(forJson(SIMPSONS, jsonContentConverter))
.convertTo(Family.class)
.satisfies(family -> assertThat(family.familyMembers()).hasSize(5));
}
@Test
void convertUsingAssertFactory() {
assertThat(forJson(SIMPSONS, jsonContentConverter))
.convertTo(new FamilyAssertFactory())
.hasFamilyMember("Homer");
}
private AssertProvider<AbstractJsonContentAssert<?>> forJson(
@Nullable String json, @Nullable JsonConverterDelegate converter) {
return () -> new TestJsonContentAssert(json, converter);
}
private static
|
ConversionTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/dialect/function/array/DdlTypeHelper.java
|
{
"start": 945,
"end": 6321
}
|
class ____ {
@SuppressWarnings("unchecked")
@AllowReflection
public static BasicType<?> resolveArrayType(DomainType<?> elementType, TypeConfiguration typeConfiguration) {
@SuppressWarnings("unchecked")
final var arrayJavaType =
(BasicPluralJavaType<Object>)
typeConfiguration.getJavaTypeRegistry()
.resolveArrayDescriptor( elementType.getJavaType() );
final Dialect dialect = typeConfiguration.getCurrentBaseSqlTypeIndicators().getDialect();
return arrayJavaType.resolveType(
typeConfiguration,
dialect,
(BasicType<Object>) elementType,
null,
typeConfiguration.getCurrentBaseSqlTypeIndicators()
);
}
@SuppressWarnings("unchecked")
public static BasicType<?> resolveListType(DomainType<?> elementType, TypeConfiguration typeConfiguration) {
@SuppressWarnings("unchecked")
final BasicPluralJavaType<Object> arrayJavaType =
(BasicPluralJavaType<Object>)
typeConfiguration.getJavaTypeRegistry()
.getDescriptor( List.class )
.createJavaType(
new ParameterizedTypeImpl( List.class, new Type[]{ elementType.getJavaType() }, null ),
typeConfiguration
);
final Dialect dialect = typeConfiguration.getCurrentBaseSqlTypeIndicators().getDialect();
return arrayJavaType.resolveType(
typeConfiguration,
dialect,
(BasicType<Object>) elementType,
null,
typeConfiguration.getCurrentBaseSqlTypeIndicators()
);
}
public static String getTypeName(BasicType<?> type, TypeConfiguration typeConfiguration) {
return getTypeName( (JdbcMappingContainer) type, typeConfiguration );
}
public static String getTypeName(BasicType<?> type, Size size, TypeConfiguration typeConfiguration) {
return getTypeName( (JdbcMappingContainer) type, size, typeConfiguration );
}
public static String getTypeName(JdbcMappingContainer type, TypeConfiguration typeConfiguration) {
return getTypeName( type, Size.nil(), typeConfiguration );
}
public static String getTypeName(JdbcMappingContainer type, Size size, TypeConfiguration typeConfiguration) {
if ( type instanceof SqlTypedMapping sqlTypedMapping ) {
return AbstractSqlAstTranslator.getSqlTypeName( sqlTypedMapping, typeConfiguration );
}
else {
final BasicType<?> basicType = (BasicType<?>) type.getSingleJdbcMapping();
final DdlTypeRegistry ddlTypeRegistry = typeConfiguration.getDdlTypeRegistry();
final DdlType ddlType = ddlTypeRegistry.getDescriptor(
basicType.getJdbcType().getDdlTypeCode()
);
return ddlType.getTypeName( size, basicType, ddlTypeRegistry );
}
}
public static String getTypeName(ReturnableType<?> type, TypeConfiguration typeConfiguration) {
return getTypeName( type, Size.nil(), typeConfiguration );
}
public static String getTypeName(ReturnableType<?> type, Size size, TypeConfiguration typeConfiguration) {
if ( type instanceof SqlTypedMapping sqlTypedMapping ) {
return AbstractSqlAstTranslator.getSqlTypeName( sqlTypedMapping, typeConfiguration );
}
else {
final BasicType<?> basicType = (BasicType<?>) ( (JdbcMappingContainer) type ).getSingleJdbcMapping();
final DdlTypeRegistry ddlTypeRegistry = typeConfiguration.getDdlTypeRegistry();
final DdlType ddlType = ddlTypeRegistry.getDescriptor(
basicType.getJdbcType().getDdlTypeCode()
);
return ddlType.getTypeName( size, basicType, ddlTypeRegistry );
}
}
public static String getCastTypeName(BasicType<?> type, TypeConfiguration typeConfiguration) {
return getCastTypeName( (JdbcMappingContainer) type, typeConfiguration );
}
public static String getCastTypeName(BasicType<?> type, Size size, TypeConfiguration typeConfiguration) {
return getCastTypeName( (JdbcMappingContainer) type, size, typeConfiguration );
}
public static String getCastTypeName(JdbcMappingContainer type, TypeConfiguration typeConfiguration) {
return getCastTypeName( type, Size.nil(), typeConfiguration );
}
public static String getCastTypeName(JdbcMappingContainer type, Size size, TypeConfiguration typeConfiguration) {
if ( type instanceof SqlTypedMapping sqlTypedMapping ) {
return AbstractSqlAstTranslator.getCastTypeName( sqlTypedMapping, typeConfiguration );
}
else {
final BasicType<?> basicType = (BasicType<?>) type.getSingleJdbcMapping();
final DdlTypeRegistry ddlTypeRegistry = typeConfiguration.getDdlTypeRegistry();
final DdlType ddlType = ddlTypeRegistry.getDescriptor(
basicType.getJdbcType().getDdlTypeCode()
);
return ddlType.getCastTypeName( size, basicType, ddlTypeRegistry );
}
}
public static String getCastTypeName(ReturnableType<?> type, TypeConfiguration typeConfiguration) {
return getCastTypeName( type, Size.nil(), typeConfiguration );
}
public static String getCastTypeName(ReturnableType<?> type, Size size, TypeConfiguration typeConfiguration) {
if ( type instanceof SqlTypedMapping sqlTypedMapping ) {
return AbstractSqlAstTranslator.getCastTypeName( sqlTypedMapping, typeConfiguration );
}
else {
final BasicType<?> basicType = (BasicType<?>) ( (JdbcMappingContainer) type ).getSingleJdbcMapping();
final DdlTypeRegistry ddlTypeRegistry = typeConfiguration.getDdlTypeRegistry();
final DdlType ddlType = ddlTypeRegistry.getDescriptor(
basicType.getJdbcType().getDdlTypeCode()
);
return ddlType.getCastTypeName( size, basicType, ddlTypeRegistry );
}
}
}
|
DdlTypeHelper
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PostDataFlushResponseTests.java
|
{
"start": 524,
"end": 1022
}
|
class ____ extends AbstractWireSerializingTestCase<Response> {
@Override
protected Response createTestInstance() {
return new Response(randomBoolean(), Instant.now());
}
@Override
protected Response mutateInstance(Response instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<Response> instanceReader() {
return Response::new;
}
}
|
PostDataFlushResponseTests
|
java
|
apache__camel
|
components/camel-jsonata/src/main/java/org/apache/camel/component/jsonata/JsonataComponent.java
|
{
"start": 1122,
"end": 3788
}
|
class ____ extends DefaultComponent {
@Metadata(defaultValue = "true", description = "Sets whether to use resource content cache or not")
private boolean contentCache = true;
@Metadata
private boolean allowTemplateFromHeader;
@Metadata(label = "advanced",
description = "To configure custom frame bindings and inject user functions.")
protected JsonataFrameBinding frameBinding;
public JsonataComponent() {
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
boolean cache = getAndRemoveParameter(parameters, "contentCache", Boolean.class, contentCache);
JsonataFrameBinding frameBinding
= resolveAndRemoveReferenceParameter(parameters, "frameBinding", JsonataFrameBinding.class);
if (frameBinding == null) {
// fallback to component configured
frameBinding = getFrameBinding();
}
JsonataEndpoint answer = new JsonataEndpoint(uri, this, remaining, frameBinding);
answer.setContentCache(cache);
answer.setAllowTemplateFromHeader(allowTemplateFromHeader);
// if its a http resource then append any remaining parameters and update the resource uri
if (ResourceHelper.isHttpUri(remaining)) {
remaining = ResourceHelper.appendParameters(remaining, parameters);
answer.setResourceUri(remaining);
}
return answer;
}
public boolean isContentCache() {
return contentCache;
}
/**
* Sets whether to use resource content cache or not
*/
public void setContentCache(boolean contentCache) {
this.contentCache = contentCache;
}
public boolean isAllowTemplateFromHeader() {
return allowTemplateFromHeader;
}
/**
* Whether to allow to use resource template from header or not (default false).
*
* Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential
* security vulnerability if the header is coming from a malicious user, so use this with care.
*/
public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
this.allowTemplateFromHeader = allowTemplateFromHeader;
}
/**
* To use the custom JsonataFrameBinding to perform configuration of custom functions that will be used.
*/
public void setFrameBinding(JsonataFrameBinding frameBinding) {
this.frameBinding = frameBinding;
}
public JsonataFrameBinding getFrameBinding() {
return frameBinding;
}
}
|
JsonataComponent
|
java
|
apache__camel
|
core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/AvroLibrary.java
|
{
"start": 1000,
"end": 1289
}
|
enum ____ {
ApacheAvro("avro"),
Jackson("avroJackson");
private final String dataFormatName;
AvroLibrary(String dataFormatName) {
this.dataFormatName = dataFormatName;
}
public String getDataFormatName() {
return dataFormatName;
}
}
|
AvroLibrary
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/PersistentDefaultableList.java
|
{
"start": 451,
"end": 900
}
|
class ____ extends PersistentList implements DefaultableList {
public PersistentDefaultableList(SharedSessionContractImplementor session) {
super( session );
}
public PersistentDefaultableList(SharedSessionContractImplementor session, List list) {
super( session, list );
}
public PersistentDefaultableList() {
}
public String getDefaultValue() {
return ( ( DefaultableList ) this.list ).getDefaultValue();
}
}
|
PersistentDefaultableList
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
|
{
"start": 1549,
"end": 2117
}
|
class ____ extends ToStringStyle {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1L;
/**
* Constructs a new instance.
*/
public RecursiveToStringStyle() {
}
/**
* Returns whether or not to recursively format the given {@link Class}.
* By default, this method always returns {@code true}, but may be overwritten by
* subclasses to filter specific classes.
*
* @param clazz
* The
|
RecursiveToStringStyle
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/SplitPythonConditionFromCorrelateRule.java
|
{
"start": 2779,
"end": 7462
}
|
class ____
extends RelRule<
SplitPythonConditionFromCorrelateRule.SplitPythonConditionFromCorrelateRuleConfig> {
public static final SplitPythonConditionFromCorrelateRule INSTANCE =
SplitPythonConditionFromCorrelateRule.SplitPythonConditionFromCorrelateRuleConfig
.DEFAULT
.toRule();
private SplitPythonConditionFromCorrelateRule(
SplitPythonConditionFromCorrelateRuleConfig config) {
super(config);
}
@Override
public boolean matches(RelOptRuleCall call) {
FlinkLogicalCorrelate correlate = call.rel(0);
FlinkLogicalCalc right = call.rel(2);
JoinRelType joinType = correlate.getJoinType();
FlinkLogicalCalc mergedCalc = StreamPhysicalCorrelateRule.getMergedCalc(right);
FlinkLogicalTableFunctionScan tableScan =
StreamPhysicalCorrelateRule.getTableScan(mergedCalc);
return joinType == JoinRelType.INNER
&& isNonPythonCall(tableScan.getCall())
&& mergedCalc.getProgram() != null
&& mergedCalc.getProgram().getCondition() != null
&& containsPythonCall(
mergedCalc
.getProgram()
.expandLocalRef(mergedCalc.getProgram().getCondition()),
null);
}
@Override
public void onMatch(RelOptRuleCall call) {
FlinkLogicalCorrelate correlate = call.rel(0);
FlinkLogicalCalc right = call.rel(2);
RexBuilder rexBuilder = call.builder().getRexBuilder();
FlinkLogicalCalc mergedCalc = StreamPhysicalCorrelateRule.getMergedCalc(right);
RexProgram mergedCalcProgram = mergedCalc.getProgram();
RelNode input = mergedCalc.getInput();
List<RexNode> correlateFilters =
RelOptUtil.conjunctions(
mergedCalcProgram.expandLocalRef(mergedCalcProgram.getCondition()));
List<RexNode> remainingFilters =
correlateFilters.stream()
.filter(filter -> !containsPythonCall(filter))
.collect(Collectors.toList());
RexNode bottomCalcCondition = RexUtil.composeConjunction(rexBuilder, remainingFilters);
FlinkLogicalCalc newBottomCalc =
new FlinkLogicalCalc(
mergedCalc.getCluster(),
mergedCalc.getTraitSet(),
input,
RexProgram.create(
input.getRowType(),
mergedCalcProgram.getProjectList(),
bottomCalcCondition,
mergedCalc.getRowType(),
rexBuilder));
FlinkLogicalCorrelate newCorrelate =
new FlinkLogicalCorrelate(
correlate.getCluster(),
correlate.getTraitSet(),
correlate.getLeft(),
newBottomCalc,
correlate.getCorrelationId(),
correlate.getRequiredColumns(),
correlate.getJoinType());
InputRefRewriter inputRefRewriter =
new InputRefRewriter(
correlate.getRowType().getFieldCount()
- mergedCalc.getRowType().getFieldCount());
List<RexNode> pythonFilters =
correlateFilters.stream()
.filter(filter -> containsPythonCall(filter))
.map(filter -> filter.accept(inputRefRewriter))
.collect(Collectors.toList());
RexNode topCalcCondition = RexUtil.composeConjunction(rexBuilder, pythonFilters);
RexProgram rexProgram =
new RexProgramBuilder(newCorrelate.getRowType(), rexBuilder).getProgram();
FlinkLogicalCalc newTopCalc =
new FlinkLogicalCalc(
newCorrelate.getCluster(),
newCorrelate.getTraitSet(),
newCorrelate,
RexProgram.create(
newCorrelate.getRowType(),
rexProgram.getExprList(),
topCalcCondition,
newCorrelate.getRowType(),
rexBuilder));
call.transformTo(newTopCalc);
}
/** Rule configuration. */
@Value.Immutable(singleton = false)
public
|
SplitPythonConditionFromCorrelateRule
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/component/Component.java
|
{
"start": 29323,
"end": 48635
}
|
class ____ implements MultipleArcTransition
<Component, ComponentEvent, ComponentState> {
@Override
public ComponentState transition(Component component,
ComponentEvent componentEvent) {
// checkIfStable also updates the state in definition when STABLE
ComponentState targetState = checkIfStable(component);
if (targetState.equals(STABLE) &&
!(component.upgradeStatus.isCompleted() &&
component.cancelUpgradeStatus.isCompleted())) {
// Component stable after upgrade or cancel upgrade
UpgradeStatus status = !component.cancelUpgradeStatus.isCompleted() ?
component.cancelUpgradeStatus : component.upgradeStatus;
component.componentSpec.overwrite(status.getTargetSpec());
status.reset();
ServiceEvent checkStable = new ServiceEvent(ServiceEventType.
CHECK_STABLE);
component.dispatcher.getEventHandler().handle(checkStable);
}
return targetState;
}
}
public void removePendingInstance(ComponentInstance instance) {
pendingInstances.remove(instance);
}
public void reInsertPendingInstance(ComponentInstance instance) {
pendingInstances.add(instance);
}
private void releaseContainer(Container container) {
scheduler.getAmRMClient().releaseAssignedContainer(container.getId());
componentMetrics.surplusContainers.incr();
scheduler.getServiceMetrics().surplusContainers.incr();
}
private void assignContainerToCompInstance(Container container) {
if (pendingInstances.size() == 0) {
LOG.info(
"[COMPONENT {}]: No pending component instance left, release surplus container {}",
getName(), container.getId());
releaseContainer(container);
return;
}
ComponentInstance instance = pendingInstances.remove(0);
LOG.info(
"[COMPONENT {}]: {} allocated, num pending component instances reduced to {}",
getName(), container.getId(), pendingInstances.size());
instance.setContainer(container);
scheduler.addLiveCompInstance(container.getId(), instance);
LOG.info(
"[COMPONENT {}]: Assigned {} to component instance {} and launch on host {} ",
getName(), container.getId(), instance.getCompInstanceName(),
container.getNodeId());
Future<ProviderService.ResolvedLaunchParams> resolvedParamFuture;
if (!(upgradeStatus.isCompleted() && cancelUpgradeStatus.isCompleted())) {
UpgradeStatus status = !cancelUpgradeStatus.isCompleted() ?
cancelUpgradeStatus : upgradeStatus;
resolvedParamFuture = scheduler.getContainerLaunchService()
.launchCompInstance(scheduler.getApp(), instance, container,
createLaunchContext(status.getTargetSpec(),
status.getTargetVersion()));
} else {
resolvedParamFuture = scheduler.getContainerLaunchService()
.launchCompInstance(
scheduler.getApp(), instance, container,
createLaunchContext(componentSpec, scheduler.getApp().getVersion()));
}
instance.updateResolvedLaunchParams(resolvedParamFuture);
}
public ContainerLaunchService.ComponentLaunchContext createLaunchContext(
org.apache.hadoop.yarn.service.api.records.Component compSpec,
String version) {
ContainerLaunchService.ComponentLaunchContext launchContext =
new ContainerLaunchService.ComponentLaunchContext(compSpec.getName(),
version);
launchContext.setArtifact(compSpec.getArtifact())
.setConfiguration(compSpec.getConfiguration())
.setLaunchCommand(compSpec.getLaunchCommand())
.setRunPrivilegedContainer(compSpec.getRunPrivilegedContainer());
return launchContext;
}
@SuppressWarnings({ "unchecked" })
public void requestContainers(long count) {
LOG.info("[COMPONENT {}] Requesting for {} container(s)",
componentSpec.getName(), count);
org.apache.hadoop.yarn.service.api.records.Resource componentResource =
componentSpec.getResource();
Resource resource = Resource.newInstance(componentResource.calcMemoryMB(),
componentResource.getCpus());
if (componentResource.getAdditional() != null) {
for (Map.Entry<String, ResourceInformation> entry : componentResource
.getAdditional().entrySet()) {
String resourceName = entry.getKey();
// Avoid setting memory/cpu under "additional"
if (resourceName.equals(
org.apache.hadoop.yarn.api.records.ResourceInformation.MEMORY_URI)
|| resourceName.equals(
org.apache.hadoop.yarn.api.records.ResourceInformation.VCORES_URI)) {
LOG.warn("Please set memory/vcore in the main section of resource, "
+ "ignoring this entry=" + resourceName);
continue;
}
ResourceInformation specInfo = entry.getValue();
org.apache.hadoop.yarn.api.records.ResourceInformation ri =
org.apache.hadoop.yarn.api.records.ResourceInformation.newInstance(
entry.getKey(),
specInfo.getUnit(),
specInfo.getValue(),
specInfo.getTags(),
specInfo.getAttributes());
resource.setResourceInformation(resourceName, ri);
}
}
if (!scheduler.hasAtLeastOnePlacementConstraint()) {
for (int i = 0; i < count; i++) {
ContainerRequest request = ContainerRequest.newBuilder()
.capability(resource).priority(priority)
.allocationRequestId(allocateId).relaxLocality(true).build();
LOG.info("[COMPONENT {}] Submitting container request : {}",
componentSpec.getName(), request);
amrmClient.addContainerRequest(request);
}
} else {
// Schedule placement requests. Validation of non-null target tags and
// that they refer to existing component names are already done. So, no
// need to validate here.
PlacementPolicy placementPolicy = componentSpec.getPlacementPolicy();
Collection<SchedulingRequest> schedulingRequests = new HashSet<>();
// We prepare an AND-ed composite constraint to be the final composite
// constraint. If placement expressions are specified to create advanced
// composite constraints then this AND-ed composite constraint is not
// used.
PlacementConstraint finalConstraint = null;
if (placementPolicy != null) {
for (org.apache.hadoop.yarn.service.api.records.PlacementConstraint
yarnServiceConstraint : placementPolicy.getConstraints()) {
List<TargetExpression> targetExpressions = new ArrayList<>();
// Currently only intra-application allocation tags are supported.
if (!yarnServiceConstraint.getTargetTags().isEmpty()) {
targetExpressions.add(PlacementTargets.allocationTag(
yarnServiceConstraint.getTargetTags().toArray(new String[0])));
}
// Add all node attributes
for (Map.Entry<String, List<String>> attribute : yarnServiceConstraint
.getNodeAttributes().entrySet()) {
targetExpressions
.add(PlacementTargets.nodeAttribute(attribute.getKey(),
attribute.getValue().toArray(new String[0])));
}
// Add all node partitions
if (!yarnServiceConstraint.getNodePartitions().isEmpty()) {
targetExpressions
.add(PlacementTargets.nodePartition(yarnServiceConstraint
.getNodePartitions().toArray(new String[0])));
}
PlacementConstraint constraint = null;
switch (yarnServiceConstraint.getType()) {
case AFFINITY:
constraint = getAffinityConstraint(yarnServiceConstraint,
targetExpressions);
break;
case ANTI_AFFINITY:
constraint = getAntiAffinityConstraint(yarnServiceConstraint,
targetExpressions);
break;
case AFFINITY_WITH_CARDINALITY:
constraint = PlacementConstraints.targetCardinality(
yarnServiceConstraint.getScope().name().toLowerCase(),
yarnServiceConstraint.getMinCardinality() == null ? 0
: yarnServiceConstraint.getMinCardinality().intValue(),
yarnServiceConstraint.getMaxCardinality() == null
? Integer.MAX_VALUE
: yarnServiceConstraint.getMaxCardinality().intValue(),
targetExpressions.toArray(new TargetExpression[0])).build();
break;
}
if (constraint == null) {
LOG.info("[COMPONENT {}] Placement constraint: null ",
componentSpec.getName());
continue;
}
// The default AND-ed final composite constraint
if (finalConstraint != null) {
finalConstraint = PlacementConstraints
.and(constraint.getConstraintExpr(),
finalConstraint.getConstraintExpr())
.build();
} else {
finalConstraint = constraint;
}
LOG.debug("[COMPONENT {}] Placement constraint: {}",
componentSpec.getName(),
constraint.getConstraintExpr().toString());
}
}
ResourceSizing resourceSizing = ResourceSizing.newInstance((int) count,
resource);
LOG.debug("[COMPONENT {}] Resource sizing: {}", componentSpec.getName(),
resourceSizing);
SchedulingRequest request = SchedulingRequest.newBuilder()
.priority(priority).allocationRequestId(allocateId)
.allocationTags(Collections.singleton(componentSpec.getName()))
.executionType(
ExecutionTypeRequest.newInstance(ExecutionType.GUARANTEED, true))
.placementConstraintExpression(finalConstraint)
.resourceSizing(resourceSizing).build();
LOG.info("[COMPONENT {}] Submitting scheduling request: {}",
componentSpec.getName(), request);
schedulingRequests.add(request);
amrmClient.addSchedulingRequests(schedulingRequests);
}
}
private PlacementConstraint getAffinityConstraint(
org.apache.hadoop.yarn.service.api.records.PlacementConstraint
yarnServiceConstraint, List<TargetExpression> targetExpressions) {
PlacementConstraint constraint = null;
if (!yarnServiceConstraint.getTargetTags().isEmpty() ||
!yarnServiceConstraint.getNodePartitions().isEmpty()) {
constraint = PlacementConstraints
.targetIn(yarnServiceConstraint.getScope().getValue(),
targetExpressions.toArray(new TargetExpression[0]))
.build();
}
if (!yarnServiceConstraint.getNodeAttributes().isEmpty()) {
constraint = PlacementConstraints
.targetNodeAttribute(yarnServiceConstraint.getScope().getValue(),
NodeAttributeOpCode.EQ, targetExpressions.toArray(
new TargetExpression[0])).build();
}
return constraint;
}
private PlacementConstraint getAntiAffinityConstraint(
org.apache.hadoop.yarn.service.api.records.PlacementConstraint
yarnServiceConstraint, List<TargetExpression> targetExpressions) {
PlacementConstraint constraint = null;
if (!yarnServiceConstraint.getTargetTags().isEmpty() ||
!yarnServiceConstraint.getNodePartitions().isEmpty()) {
constraint = PlacementConstraints
.targetNotIn(yarnServiceConstraint.getScope().getValue(),
targetExpressions.toArray(new TargetExpression[0]))
.build();
}
if (!yarnServiceConstraint.getNodeAttributes().isEmpty()) {
constraint = PlacementConstraints
.targetNodeAttribute(yarnServiceConstraint.getScope().getValue(),
NodeAttributeOpCode.NE, targetExpressions.toArray(
new TargetExpression[0])).build();
}
return constraint;
}
private void setDesiredContainers(int n) {
int delta = n - scheduler.getServiceMetrics().containersDesired.value();
if (delta != 0) {
scheduler.getServiceMetrics().containersDesired.incr(delta);
}
componentMetrics.containersDesired.set(n);
}
private void updateMetrics(ContainerStatus status) {
//when a container preparation fails while building launch context, then
//the container status may not exist.
if (status != null) {
switch (status.getExitStatus()) {
case SUCCESS:
componentMetrics.containersSucceeded.incr();
scheduler.getServiceMetrics().containersSucceeded.incr();
return;
case PREEMPTED:
componentMetrics.containersPreempted.incr();
scheduler.getServiceMetrics().containersPreempted.incr();
break;
case DISKS_FAILED:
componentMetrics.containersDiskFailure.incr();
scheduler.getServiceMetrics().containersDiskFailure.incr();
break;
default:
break;
}
}
// containersFailed include preempted, disks_failed etc.
componentMetrics.containersFailed.incr();
scheduler.getServiceMetrics().containersFailed.incr();
if (status != null && Apps.shouldCountTowardsNodeBlacklisting(
status.getExitStatus())) {
String host = scheduler.getLiveInstances().get(status.getContainerId())
.getNodeId().getHost();
failureTracker.incNodeFailure(host);
currentContainerFailure.getAndIncrement();
}
}
private boolean doesNeedUpgrade() {
return cancelUpgradeStatus.areContainersUpgrading() ||
upgradeStatus.areContainersUpgrading() ||
upgradeStatus.failed.get();
}
public boolean areDependenciesReady() {
List<String> dependencies = componentSpec.getDependencies();
if (ServiceUtils.isEmpty(dependencies)) {
return true;
}
for (String dependency : dependencies) {
Component dependentComponent = scheduler.getAllComponents().get(
dependency);
if (dependentComponent == null) {
LOG.error("Couldn't find dependency {} for {} (should never happen)",
dependency, getName());
continue;
}
if (!dependentComponent.isReadyForDownstream()) {
LOG.info("[COMPONENT {}]: Dependency {} not satisfied, only {} of {}"
+ " instances are ready or the dependent component has not "
+ "completed ", getName(), dependency,
dependentComponent.getNumReadyInstances(),
dependentComponent.getNumDesiredInstances());
return false;
}
}
return true;
}
public Map<String, String> getDependencyHostIpTokens() {
Map<String, String> tokens = new HashMap<>();
List<String> dependencies = componentSpec.getDependencies();
if (ServiceUtils.isEmpty(dependencies)) {
return tokens;
}
for (String dependency : dependencies) {
Collection<ComponentInstance> instances = scheduler.getAllComponents()
.get(dependency).getAllComponentInstances();
for (ComponentInstance instance : instances) {
if (instance.getContainerStatus() == null) {
continue;
}
if (ServiceUtils.isEmpty(instance.getContainerStatus().getIPs()) ||
ServiceUtils.isUnset(instance.getContainerStatus().getHost())) {
continue;
}
String ip = instance.getContainerStatus().getIPs().get(0);
String host = instance.getContainerStatus().getHost();
tokens.put(String.format(COMPONENT_INSTANCE_IP,
instance.getCompInstanceName().toUpperCase()), ip);
tokens.put(String.format(COMPONENT_INSTANCE_HOST,
instance.getCompInstanceName().toUpperCase()), host);
}
}
return tokens;
}
public void incRunningContainers() {
componentMetrics.containersRunning.incr();
scheduler.getServiceMetrics().containersRunning.incr();
}
public void decRunningContainers() {
componentMetrics.containersRunning.decr();
scheduler.getServiceMetrics().containersRunning.decr();
}
public void incContainersReady(boolean updateDefinition) {
componentMetrics.containersReady.incr();
scheduler.getServiceMetrics().containersReady.incr();
if (updateDefinition) {
checkAndUpdateComponentState(this, true);
}
}
public void decContainersReady(boolean updateDefinition) {
componentMetrics.containersReady.decr();
scheduler.getServiceMetrics().containersReady.decr();
if (updateDefinition) {
checkAndUpdateComponentState(this, false);
}
}
public int getNumReadyInstances() {
return componentMetrics.containersReady.value();
}
public int getNumRunningInstances() {
return componentMetrics.containersRunning.value();
}
public int getNumDesiredInstances() {
return componentMetrics.containersDesired.value();
}
public ComponentInstance getComponentInstance(String componentInstanceName) {
return compInstances.get(componentInstanceName);
}
public Collection<ComponentInstance> getAllComponentInstances() {
return compInstances.values();
}
public org.apache.hadoop.yarn.service.api.records.Component getComponentSpec() {
return this.componentSpec;
}
public void resetCompFailureCount() {
LOG.info("[COMPONENT {}]: Reset container failure count from {} to 0.",
getName(), currentContainerFailure.get());
currentContainerFailure.set(0);
failureTracker.resetContainerFailures();
}
public Probe getProbe() {
return probe;
}
public Priority getPriority() {
return priority;
}
public long getAllocateId() {
return allocateId;
}
public String getName () {
return componentSpec.getName();
}
public ComponentState getState() {
this.readLock.lock();
try {
return this.stateMachine.getCurrentState();
} finally {
this.readLock.unlock();
}
}
/**
* Returns whether a component is upgrading or not.
*/
public boolean isUpgrading() {
this.readLock.lock();
try {
return !(upgradeStatus.isCompleted() &&
cancelUpgradeStatus.isCompleted());
} finally {
this.readLock.unlock();
}
}
public UpgradeStatus getUpgradeStatus() {
this.readLock.lock();
try {
return upgradeStatus;
} finally {
this.readLock.unlock();
}
}
public UpgradeStatus getCancelUpgradeStatus() {
this.readLock.lock();
try {
return cancelUpgradeStatus;
} finally {
this.readLock.unlock();
}
}
public ServiceScheduler getScheduler() {
return scheduler;
}
@Override
public void handle(ComponentEvent event) {
writeLock.lock();
try {
ComponentState oldState = getState();
try {
stateMachine.doTransition(event.getType(), event);
} catch (InvalidStateTransitionException e) {
LOG.error(MessageFormat.format("[COMPONENT {0}]: Invalid event {1} at {2}",
componentSpec.getName(), event.getType(), oldState), e);
}
if (oldState != getState()) {
LOG.info("[COMPONENT {}] Transitioned from {} to {} on {} event.",
componentSpec.getName(), oldState, getState(), event.getType());
}
} finally {
writeLock.unlock();
}
}
private static
|
CheckStableTransition
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/mapper/CompositeSyntheticFieldLoader.java
|
{
"start": 5979,
"end": 6568
}
|
class ____ extends StoredFieldLayer {
public MalformedValuesLayer(String fieldName) {
super(IgnoreMalformedStoredValues.name(fieldName));
}
@Override
protected void writeValue(Object value, XContentBuilder b) throws IOException {
if (value instanceof BytesRef r) {
XContentDataHelper.decodeAndWrite(b, r);
} else {
b.value(value);
}
}
}
/**
* Layer that loads field values from a provided stored field.
*/
public abstract static
|
MalformedValuesLayer
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalEnumBinaryProcessor.java
|
{
"start": 507,
"end": 647
}
|
class ____ definition binary processors based on functions (for applying) defined as enums (for serialization purposes).
*/
public abstract
|
for
|
java
|
apache__camel
|
components/camel-aws/camel-aws-config/src/main/java/org/apache/camel/component/aws/config/client/AWSConfigInternalClient.java
|
{
"start": 1012,
"end": 1237
}
|
interface ____ {
/**
* Returns a Config client after a factory method determines which one to return.
*
* @return ConfigClient ConfigClient
*/
ConfigClient getConfigClient();
}
|
AWSConfigInternalClient
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistry.java
|
{
"start": 1213,
"end": 3003
}
|
class ____ {
private final List<InterceptorRegistration> registrations = new ArrayList<>();
/**
* Adds the provided {@link HandlerInterceptor}.
* @param interceptor the interceptor to add
* @return an {@link InterceptorRegistration} that allows you optionally configure the
* registered interceptor further for example adding URL patterns it should apply to.
*/
public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) {
InterceptorRegistration registration = new InterceptorRegistration(interceptor);
this.registrations.add(registration);
return registration;
}
/**
* Adds the provided {@link WebRequestInterceptor}.
* @param interceptor the interceptor to add
* @return an {@link InterceptorRegistration} that allows you optionally configure the
* registered interceptor further for example adding URL patterns it should apply to.
*/
public InterceptorRegistration addWebRequestInterceptor(WebRequestInterceptor interceptor) {
WebRequestHandlerInterceptorAdapter adapted = new WebRequestHandlerInterceptorAdapter(interceptor);
InterceptorRegistration registration = new InterceptorRegistration(adapted);
this.registrations.add(registration);
return registration;
}
/**
* Return all registered interceptors.
*/
protected List<Object> getInterceptors() {
return this.registrations.stream()
.sorted(INTERCEPTOR_ORDER_COMPARATOR)
.map(InterceptorRegistration::getInterceptor)
.toList();
}
private static final Comparator<Object> INTERCEPTOR_ORDER_COMPARATOR =
OrderComparator.INSTANCE.withSourceProvider(object -> {
if (object instanceof InterceptorRegistration interceptorRegistration) {
return (Ordered) interceptorRegistration::getOrder;
}
return null;
});
}
|
InterceptorRegistry
|
java
|
apache__rocketmq
|
common/src/test/java/org/apache/rocketmq/common/attribute/TopicMessageTypeTest.java
|
{
"start": 1141,
"end": 5005
}
|
class ____ {
private Map<String, String> normalMessageProperty;
private Map<String, String> transactionMessageProperty;
private Map<String, String> delayMessageProperty;
private Map<String, String> fifoMessageProperty;
@Before
public void setUp() {
normalMessageProperty = new HashMap<>();
transactionMessageProperty = new HashMap<>();
delayMessageProperty = new HashMap<>();
fifoMessageProperty = new HashMap<>();
transactionMessageProperty.put(MessageConst.PROPERTY_TRANSACTION_PREPARED, "true");
delayMessageProperty.put(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "1");
fifoMessageProperty.put(MessageConst.PROPERTY_SHARDING_KEY, "shardingKey");
}
@Test
public void testTopicMessageTypeSet() {
Set<String> expectedSet = Sets.newHashSet("UNSPECIFIED", "NORMAL", "FIFO", "DELAY", "TRANSACTION", "MIXED");
Set<String> actualSet = TopicMessageType.topicMessageTypeSet();
assertEquals(expectedSet, actualSet);
}
@Test
public void testParseFromMessageProperty_Normal() {
TopicMessageType actual = TopicMessageType.parseFromMessageProperty(normalMessageProperty);
assertEquals(TopicMessageType.NORMAL, actual);
}
@Test
public void testParseFromMessageProperty_Transaction() {
TopicMessageType actual = TopicMessageType.parseFromMessageProperty(transactionMessageProperty);
assertEquals(TopicMessageType.TRANSACTION, actual);
}
@Test
public void testParseFromMessageProperty_Delay() {
TopicMessageType actual = TopicMessageType.parseFromMessageProperty(delayMessageProperty);
assertEquals(TopicMessageType.DELAY, actual);
}
@Test
public void testParseFromMessageProperty_Fifo() {
TopicMessageType actual = TopicMessageType.parseFromMessageProperty(fifoMessageProperty);
assertEquals(TopicMessageType.FIFO, actual);
}
@Test
public void testGetMetricsValue() {
for (TopicMessageType type : TopicMessageType.values()) {
String expected = type.getValue().toLowerCase();
String actual = type.getMetricsValue();
assertEquals(expected, actual);
}
}
@Test
public void testParseFromMessageProperty() {
Map<String, String> properties = new HashMap<>();
// TRANSACTION
properties.put(MessageConst.PROPERTY_TRANSACTION_PREPARED, "true");
Assert.assertEquals(TopicMessageType.TRANSACTION, TopicMessageType.parseFromMessageProperty(properties));
// DELAY
properties.clear();
properties.put(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "3");
Assert.assertEquals(TopicMessageType.DELAY, TopicMessageType.parseFromMessageProperty(properties));
properties.clear();
properties.put(MessageConst.PROPERTY_TIMER_DELIVER_MS, System.currentTimeMillis() + 10000 + "");
Assert.assertEquals(TopicMessageType.DELAY, TopicMessageType.parseFromMessageProperty(properties));
properties.clear();
properties.put(MessageConst.PROPERTY_TIMER_DELAY_SEC, 10 + "");
Assert.assertEquals(TopicMessageType.DELAY, TopicMessageType.parseFromMessageProperty(properties));
properties.clear();
properties.put(MessageConst.PROPERTY_TIMER_DELAY_MS, 10000 + "");
Assert.assertEquals(TopicMessageType.DELAY, TopicMessageType.parseFromMessageProperty(properties));
// FIFO
properties.clear();
properties.put(MessageConst.PROPERTY_SHARDING_KEY, "sharding_key");
Assert.assertEquals(TopicMessageType.FIFO, TopicMessageType.parseFromMessageProperty(properties));
// NORMAL
properties.clear();
Assert.assertEquals(TopicMessageType.NORMAL, TopicMessageType.parseFromMessageProperty(properties));
}
}
|
TopicMessageTypeTest
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/DynamicFilteringData.java
|
{
"start": 1893,
"end": 7254
}
|
class ____ implements Serializable {
private final TypeInformation<RowData> typeInfo;
private final RowType rowType;
/**
* Serialized rows for filtering. The types of the row values must be Flink internal data type,
* i.e. type returned by the FieldGetter. The list should be sorted and distinct.
*/
private final List<byte[]> serializedData;
/** Whether the data actually does filter. If false, everything is considered contained. */
private final boolean isFiltering;
private transient volatile boolean prepared = false;
private transient Map<Integer, List<RowData>> dataMap;
private transient RowData.FieldGetter[] fieldGetters;
public DynamicFilteringData(
TypeInformation<RowData> typeInfo,
RowType rowType,
List<byte[]> serializedData,
boolean isFiltering) {
this.typeInfo = checkNotNull(typeInfo);
this.rowType = checkNotNull(rowType);
this.serializedData = checkNotNull(serializedData);
this.isFiltering = isFiltering;
}
public boolean isFiltering() {
return isFiltering;
}
public RowType getRowType() {
return rowType;
}
/**
* Returns true if the dynamic filtering data contains the specific row.
*
* @param row the row to be tested. Types of the row values must be Flink internal data type,
* i.e. type returned by the FieldGetter.
* @return true if the dynamic filtering data contains the specific row
*/
public boolean contains(RowData row) {
if (!isFiltering) {
return true;
} else if (row.getArity() != rowType.getFieldCount()) {
throw new TableException("The arity of RowData is different");
} else {
prepare();
List<RowData> mayMatchRowData = dataMap.get(hash(row));
if (mayMatchRowData == null) {
return false;
}
for (RowData mayMatch : mayMatchRowData) {
if (matchRow(row, mayMatch)) {
return true;
}
}
return false;
}
}
private boolean matchRow(RowData row, RowData mayMatch) {
for (int i = 0; i < rowType.getFieldCount(); ++i) {
if (!Objects.equals(
fieldGetters[i].getFieldOrNull(row),
fieldGetters[i].getFieldOrNull(mayMatch))) {
return false;
}
}
return true;
}
private void prepare() {
if (!prepared) {
synchronized (this) {
if (!prepared) {
doPrepare();
prepared = true;
}
}
}
}
private void doPrepare() {
this.dataMap = new HashMap<>();
if (isFiltering) {
this.fieldGetters =
IntStream.range(0, rowType.getFieldCount())
.mapToObj(i -> RowData.createFieldGetter(rowType.getTypeAt(i), i))
.toArray(RowData.FieldGetter[]::new);
TypeSerializer<RowData> serializer =
typeInfo.createSerializer(new SerializerConfigImpl());
for (byte[] bytes : serializedData) {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputViewStreamWrapper inView = new DataInputViewStreamWrapper(bais)) {
RowData partition = serializer.deserialize(inView);
List<RowData> partitions =
dataMap.computeIfAbsent(hash(partition), k -> new ArrayList<>());
partitions.add(partition);
} catch (Exception e) {
throw new TableException("Unable to deserialize the value.", e);
}
}
}
}
private int hash(RowData row) {
return Objects.hash(Arrays.stream(fieldGetters).map(g -> g.getFieldOrNull(row)).toArray());
}
public static boolean isEqual(DynamicFilteringData data, DynamicFilteringData another) {
if (data == null) {
return another == null;
}
if (another == null
|| (data.isFiltering != another.isFiltering)
|| !data.typeInfo.equals(another.typeInfo)
|| !data.rowType.equals(another.rowType)
|| data.serializedData.size() != another.serializedData.size()) {
return false;
}
BytePrimitiveArrayComparator comparator = new BytePrimitiveArrayComparator(true);
for (int i = 0; i < data.serializedData.size(); i++) {
if (comparator.compare(data.serializedData.get(i), another.serializedData.get(i))
!= 0) {
return false;
}
}
return true;
}
@VisibleForTesting
public Collection<RowData> getData() {
prepare();
return dataMap.values().stream().flatMap(List::stream).collect(Collectors.toList());
}
@Override
public String toString() {
return "DynamicFilteringData{"
+ "isFiltering="
+ isFiltering
+ ", data size="
+ serializedData.size()
+ '}';
}
}
|
DynamicFilteringData
|
java
|
apache__camel
|
components/camel-salesforce/camel-salesforce-codegen/src/main/java/org/apache/camel/component/salesforce/codegen/AbstractSalesforceExecution.java
|
{
"start": 7586,
"end": 14230
}
|
class ____ Jetty 9
httpClient.setFollowRedirects(true);
// set HTTP client parameters
if (httpClientProperties != null && !httpClientProperties.isEmpty()) {
try {
PropertyBindingSupport.bindProperties(camelContext, httpClient, new HashMap<>(httpClientProperties));
} catch (final Exception e) {
throw new RuntimeException("Error setting HTTP client properties: " + e.getMessage(), e);
}
}
// wait for 1 second longer than the HTTP client response timeout
responseTimeout = httpClient.getTimeout() + 1000L;
// set http proxy settings
// set HTTP proxy settings
if (httpProxyHost != null && httpProxyPort != null) {
final Origin.Address proxyAddress = new Origin.Address(httpProxyHost, httpProxyPort);
ProxyConfiguration.Proxy proxy;
if (isHttpProxySocks4) {
proxy = new Socks4Proxy(proxyAddress, isHttpProxySecure);
} else {
proxy = new HttpProxy(proxyAddress, isHttpProxySecure);
}
if (httpProxyIncludedAddresses != null && !httpProxyIncludedAddresses.isEmpty()) {
proxy.getIncludedAddresses().addAll(httpProxyIncludedAddresses);
}
if (httpProxyExcludedAddresses != null && !httpProxyExcludedAddresses.isEmpty()) {
proxy.getExcludedAddresses().addAll(httpProxyExcludedAddresses);
}
httpClient.getProxyConfiguration().addProxy(proxy);
}
if (httpProxyUsername != null && httpProxyPassword != null) {
StringHelper.notEmpty(httpProxyAuthUri, "httpProxyAuthUri");
StringHelper.notEmpty(httpProxyRealm, "httpProxyRealm");
final Authentication authentication;
if (httpProxyUseDigestAuth) {
authentication = new DigestAuthentication(
URI.create(httpProxyAuthUri), httpProxyRealm, httpProxyUsername, httpProxyPassword);
} else {
authentication = new BasicAuthentication(
URI.create(httpProxyAuthUri), httpProxyRealm, httpProxyUsername, httpProxyPassword);
}
httpClient.getAuthenticationStore().addAuthentication(authentication);
}
// set session before calling start()
final SalesforceSession session = new SalesforceSession(
new DefaultCamelContext(), httpClient, httpClient.getTimeout(),
getSalesforceLoginSession());
httpClient.setSession(session);
try {
httpClient.start();
} catch (final Exception e) {
throw new RuntimeException("Error creating HTTP client: " + e.getMessage(), e);
}
return httpClient;
}
private SalesforceLoginConfig getSalesforceLoginSession() {
if (keyStoreParameters != null) {
SalesforceLoginConfig salesforceLoginConfig
= new SalesforceLoginConfig(loginUrl, clientId, userName, keyStoreParameters, false);
salesforceLoginConfig.setJwtAudience(jwtAudience);
return salesforceLoginConfig;
}
return new SalesforceLoginConfig(loginUrl, clientId, clientSecret, userName, password, false);
}
private void disconnectFromSalesforce(final RestClient restClient) {
if (restClient == null) {
return;
}
try {
final SalesforceHttpClient httpClient = (SalesforceHttpClient) ((DefaultRestClient) restClient).getHttpClient();
ServiceHelper.stopAndShutdownServices(restClient, httpClient.getSession(), httpClient);
} catch (final Exception e) {
getLog().error("Error stopping Salesforce HTTP client", e);
}
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public void setHttpClientProperties(Map<String, Object> httpClientProperties) {
this.httpClientProperties = httpClientProperties;
}
public void setHttpProxyAuthUri(String httpProxyAuthUri) {
this.httpProxyAuthUri = httpProxyAuthUri;
}
public void setHttpProxyExcludedAddresses(Set<String> httpProxyExcludedAddresses) {
this.httpProxyExcludedAddresses = httpProxyExcludedAddresses;
}
public void setHttpProxyHost(String httpProxyHost) {
this.httpProxyHost = httpProxyHost;
}
public void setHttpProxyIncludedAddresses(Set<String> httpProxyIncludedAddresses) {
this.httpProxyIncludedAddresses = httpProxyIncludedAddresses;
}
public void setHttpProxyPassword(String httpProxyPassword) {
this.httpProxyPassword = httpProxyPassword;
}
public void setHttpProxyPort(Integer httpProxyPort) {
this.httpProxyPort = httpProxyPort;
}
public void setHttpProxyRealm(String httpProxyRealm) {
this.httpProxyRealm = httpProxyRealm;
}
public void setHttpProxyUseDigestAuth(boolean httpProxyUseDigestAuth) {
this.httpProxyUseDigestAuth = httpProxyUseDigestAuth;
}
public void setHttpProxyUsername(String httpProxyUsername) {
this.httpProxyUsername = httpProxyUsername;
}
public void setHttpProxySecure(boolean httpProxySecure) {
isHttpProxySecure = httpProxySecure;
}
public void setHttpProxySocks4(boolean httpProxySocks4) {
isHttpProxySocks4 = httpProxySocks4;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public void setPassword(String password) {
this.password = password;
}
public void setJwtAudience(String jwtAudience) {
this.jwtAudience = jwtAudience;
}
public void setKeyStoreParameters(KeyStoreParameters keyStoreParameters) {
this.keyStoreParameters = keyStoreParameters;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setSslContextParameters(SSLContextParameters sslContextParameters) {
this.sslContextParameters = sslContextParameters;
}
public void setVersion(String version) {
this.version = version;
}
public void setPubSubHost(String pubSubHost) {
this.pubSubHost = pubSubHost;
}
public void setPubSubPort(int pubSubPort) {
this.pubSubPort = pubSubPort;
}
protected abstract void executeWithClient() throws Exception;
protected abstract Logger getLog();
public void setup() {
}
}
|
in
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/benchmarks/HeadersEncodeBenchmark.java
|
{
"start": 1211,
"end": 1499
}
|
class ____ extends BenchmarkBase {
@Param({"true", "false"})
public boolean asciiNames;
@Param({"true", "false"})
public boolean asciiValues;
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public static void consume(final ByteBuf buf) {
}
static
|
HeadersEncodeBenchmark
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/EnumeratedAndGenerics2Test.java
|
{
"start": 1815,
"end": 1916
}
|
enum ____ implements EnumBase {
ONE, TWO
}
@MappedSuperclass
public static abstract
|
AnotherTestEnum
|
java
|
apache__kafka
|
trogdor/src/main/java/org/apache/kafka/trogdor/task/TaskController.java
|
{
"start": 956,
"end": 1226
}
|
interface ____ {
/**
* Get the agent nodes which this task is targetting.
*
* @param topology The topology to use.
*
* @return A set of target node names.
*/
Set<String> targetNodes(Topology topology);
}
|
TaskController
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsIndexRequest.java
|
{
"start": 1007,
"end": 3049
}
|
class ____ extends SingleShardRequest<GetFieldMappingsIndexRequest> {
private final boolean includeDefaults;
private final String[] fields;
private final OriginalIndices originalIndices;
GetFieldMappingsIndexRequest(StreamInput in) throws IOException {
super(in);
if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) {
in.readStringArray(); // former types array
}
fields = in.readStringArray();
includeDefaults = in.readBoolean();
if (in.getTransportVersion().before(TransportVersions.V_8_0_0)) {
in.readBoolean(); // former probablySingleField boolean
}
originalIndices = OriginalIndices.readOriginalIndices(in);
}
GetFieldMappingsIndexRequest(GetFieldMappingsRequest other, String index) {
this.includeDefaults = other.includeDefaults();
this.fields = other.fields();
assert index != null;
this.index(index);
this.originalIndices = new OriginalIndices(other);
}
@Override
public ActionRequestValidationException validate() {
return null;
}
public String[] fields() {
return fields;
}
public boolean includeDefaults() {
return includeDefaults;
}
@Override
public String[] indices() {
return originalIndices.indices();
}
@Override
public IndicesOptions indicesOptions() {
return originalIndices.indicesOptions();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) {
out.writeStringArray(Strings.EMPTY_ARRAY);
}
out.writeStringArray(fields);
out.writeBoolean(includeDefaults);
if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) {
out.writeBoolean(false);
}
OriginalIndices.writeOriginalIndices(originalIndices, out);
}
}
|
GetFieldMappingsIndexRequest
|
java
|
quarkusio__quarkus
|
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/config/RegistryConfigImpl.java
|
{
"start": 12590,
"end": 15096
}
|
class ____ extends JsonSerializer<RegistryConfig> {
@Override
public void serialize(RegistryConfig value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
JsonStreamContext ctx = gen.getOutputContext();
if (ctx.getParent() == null || ctx.getParent().inRoot()) {
gen.writeStartObject();
writeContents(value, gen);
gen.writeEndObject();
} else {
if (onlyId(value)) {
gen.writeNumber(value.getId());
} else {
gen.writeStartObject();
gen.writeObjectFieldStart(value.getId());
writeContents(value, gen);
gen.writeEndObject();
gen.writeEndObject();
}
}
}
static void writeContents(RegistryConfig value, JsonGenerator gen) throws IOException {
if (!value.isEnabled()) {
gen.writeObjectField("enabled", value.isEnabled());
}
writeUnlessNull(gen, "update-policy", value.getUpdatePolicy());
writeUnlessNullOrTest(gen, "descriptor", value.getDescriptor(),
RegistryDescriptorConfigImpl::isGenerated);
writeUnlessNull(gen, "platforms", value.getPlatforms());
writeUnlessNull(gen, "non-platform-extensions", value.getNonPlatformExtensions());
writeUnlessNull(gen, "maven", value.getMaven());
writeUnlessNull(gen, "quarkus-versions", value.getQuarkusVersions());
// Include any extra fields if there are any
Map<String, Object> extra = value.getExtra();
if (extra != null && !extra.isEmpty()) {
for (Map.Entry<?, ?> entry : extra.entrySet()) {
gen.writeObjectField(entry.getKey().toString(), entry.getValue());
}
}
}
static <T> void writeUnlessNullOrTest(JsonGenerator gen, String fieldName, T obj, Function<T, Boolean> test)
throws IOException {
if (obj == null || test.apply(obj)) {
return;
}
gen.writeObjectField(fieldName, obj);
}
static void writeUnlessNull(JsonGenerator gen, String fieldName, Object obj) throws IOException {
if (obj != null) {
gen.writeObjectField(fieldName, obj);
}
}
}
static
|
Serializer
|
java
|
apache__camel
|
core/camel-base/src/main/java/org/apache/camel/converter/ObjectConverter.java
|
{
"start": 1261,
"end": 4792
}
|
class ____ {
/**
* Utility classes should not have a public constructor.
*/
private ObjectConverter() {
}
/**
* Converts the given value to a boolean, handling strings or Boolean objects; otherwise returning false if the
* value could not be converted to a boolean
*/
@Converter(order = 1)
public static boolean toBool(Object value) {
Boolean answer = toBoolean(value);
if (answer == null) {
throw new IllegalArgumentException("Cannot convert type: " + value.getClass().getName() + " to boolean");
}
return answer;
}
/**
* Converts the given value to a Boolean, handling strings or Boolean objects; otherwise returning null if the value
* cannot be converted to a boolean
*/
@Converter(order = 2)
public static Boolean toBoolean(Object value) {
return org.apache.camel.util.ObjectHelper.toBoolean(value);
}
/**
* Creates an iterator over the value
*/
@Converter(order = 3)
public static Iterator<?> iterator(Object value) {
return ObjectHelper.createIterator(value);
}
/**
* Creates an iterable over the value
*/
@Converter(order = 4)
public static Iterable<?> iterable(Object value) {
return ObjectHelper.createIterable(value);
}
/**
* Returns the converted value, or null if the value is null
*/
@Converter(order = 5, allowNull = true)
public static Byte toByte(Number value) {
if (org.apache.camel.util.ObjectHelper.isNaN(value)) {
return null;
}
return value.byteValue();
}
@Converter(order = 6)
public static Byte toByte(String value) {
return Byte.valueOf(value);
}
@Converter(order = 7)
public static Byte toByte(byte[] value, Exchange exchange) {
String str = new String(value, ExchangeHelper.getCharset(exchange));
return Byte.valueOf(str);
}
@Converter(order = 8)
public static char[] toCharArray(String value) {
return value.toCharArray();
}
@Converter(order = 9)
public static char[] toCharArray(byte[] value, Exchange exchange) {
String str = new String(value, ExchangeHelper.getCharset(exchange));
return str.toCharArray();
}
@Converter(order = 10)
public static Character toCharacter(String value) {
return toChar(value);
}
@Converter(order = 11)
public static Character toCharacter(byte[] value) {
return toChar(value);
}
@Converter(order = 12)
public static char toChar(String value) {
// must be string with the length of 1
if (value.length() != 1) {
throw new IllegalArgumentException("String must have exactly a length of 1: " + value);
}
return value.charAt(0);
}
@Converter(order = 13)
public static char toChar(byte[] value) {
// must be string with the length of 1
if (value.length != 1) {
throw new IllegalArgumentException("byte[] must have exactly a length of 1: " + value.length);
}
byte b = value[0];
return (char) b;
}
@Converter(order = 14)
public static String fromCharArray(char[] value) {
return new String(value);
}
/**
* Returns the converted value, or null if the value is null
*/
@Converter(order = 15)
public static Class<?> toClass(String value, CamelContext camelContext) {
// prefer to use
|
ObjectConverter
|
java
|
quarkusio__quarkus
|
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/devmode/TemplateGlobalDevModeTest.java
|
{
"start": 1637,
"end": 1702
}
|
class ____ {
public static int foo = 24;
}
}
|
MyGlobals
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/ClassLoadingIsolaterExtension.java
|
{
"start": 925,
"end": 2256
}
|
interface ____ {
ClassLoader buildIsolatedClassLoader();
void releaseIsolatedClassLoader(ClassLoader isolatedClassLoader);
}
private ClassLoader isolatedClassLoader;
private ClassLoader originalTCCL;
@Override
public void afterEach(ExtensionContext context) throws Exception {
assert Thread.currentThread().getContextClassLoader() == isolatedClassLoader;
log.infof( "Reverting TCCL [%s] -> [%s]", isolatedClassLoader, originalTCCL );
Thread.currentThread().setContextClassLoader( originalTCCL );
provider.releaseIsolatedClassLoader( isolatedClassLoader );
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance().get();
if ( !( testInstance instanceof IsolatedClassLoaderProvider ) ) {
throw new RuntimeException(
"Test @ExtendWith( ClassLoadingIsolaterExtension.class ) have to implement ClassLoadingIsolaterExtension.IsolatedClassLoaderProvider" );
}
provider = (IsolatedClassLoaderProvider) testInstance;
originalTCCL = Thread.currentThread().getContextClassLoader();
isolatedClassLoader = provider.buildIsolatedClassLoader();
log.infof( "Overriding TCCL [%s] -> [%s]", originalTCCL, isolatedClassLoader );
Thread.currentThread().setContextClassLoader( isolatedClassLoader );
}
}
|
IsolatedClassLoaderProvider
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/Student.java
|
{
"start": 1047,
"end": 1869
}
|
class ____ {
@Id
private int id;
private String name;
@ManyToMany(cascade=CascadeType.PERSIST)
@JoinTable(
name="STUDENT_COURSES",
joinColumns=@JoinColumn(referencedColumnName="ID", name="STUDENT_ID"),
inverseJoinColumns=@JoinColumn(referencedColumnName="ID", name="COURSE_ID"),
uniqueConstraints={@UniqueConstraint(columnNames={"STUDENT_ID", "COURSE_ID"})}
)
private Set<Course> courses;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + "]";
}
}
|
Student
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/LockNotBeforeTryTest.java
|
{
"start": 996,
"end": 1513
}
|
class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(LockNotBeforeTry.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(LockNotBeforeTry.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import java.util.concurrent.locks.ReentrantLock;
|
LockNotBeforeTryTest
|
java
|
elastic__elasticsearch
|
libs/core/src/test/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoaderTests.java
|
{
"start": 5486,
"end": 6170
}
|
class ____ loaded, when the multi-release attribute
* is present and the versioned entry is less than or equal to the runtime version.
*/
public void testLoadWithMultiReleaseEnabled17() throws Exception {
assumeTrue("JDK version not greater than or equal to 17", Runtime.version().feature() >= 17);
Object foobar = newFooBar(true, 17);
// expect 17 version of FooBar to be loaded
assertThat(foobar.toString(), equalTo("FooBar " + 17));
foobar = newFooBar(true, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8);
assertThat(foobar.toString(), equalTo("FooBar " + 17));
}
/*
* Tests that the greatest specific version of a
|
is
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/dialect/function/HypotheticalSetWindowEmulation.java
|
{
"start": 1407,
"end": 4467
}
|
class ____ extends HypotheticalSetFunction {
public HypotheticalSetWindowEmulation(String name, BasicTypeReference<?> returnType, TypeConfiguration typeConfiguration) {
super(
name,
returnType,
typeConfiguration
);
}
@Override
public <T> SelfRenderingSqmOrderedSetAggregateFunction<T> generateSqmOrderedSetAggregateFunctionExpression(
List<? extends SqmTypedNode<?>> arguments,
SqmPredicate filter,
SqmOrderByClause withinGroupClause,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
return new SelfRenderingSqmOrderedSetAggregateFunction<>(
this,
this,
arguments,
filter,
withinGroupClause,
impliedResultType,
getArgumentsValidator(),
getReturnTypeResolver(),
queryEngine.getCriteriaBuilder(),
getName()
) {
@Override
public Expression convertToSqlAst(SqmToSqlAstConverter walker) {
final Clause currentClause = walker.getCurrentClauseStack().getCurrent();
if ( currentClause == Clause.OVER ) {
return super.convertToSqlAst( walker );
}
else if ( currentClause != Clause.SELECT ) {
throw new IllegalArgumentException( "Can't emulate [" + getName() + "] in clause " + currentClause + ". Only the SELECT clause is supported" );
}
final ReturnableType<?> resultType = resolveResultType( walker );
List<SqlAstNode> arguments = resolveSqlAstArguments( getArguments(), walker );
ArgumentsValidator argumentsValidator = getArgumentsValidator();
if ( argumentsValidator != null ) {
argumentsValidator.validateSqlTypes( arguments, getFunctionName() );
}
List<SortSpecification> withinGroup;
if ( this.getWithinGroup() == null ) {
withinGroup = emptyList();
}
else {
walker.getCurrentClauseStack().push( Clause.ORDER );
try {
final List<SqmSortSpecification> sortSpecifications = this.getWithinGroup().getSortSpecifications();
withinGroup = new ArrayList<>( sortSpecifications.size() );
for ( SqmSortSpecification sortSpecification : sortSpecifications ) {
final SortSpecification specification = (SortSpecification) walker.visitSortSpecification( sortSpecification );
if ( specification != null ) {
withinGroup.add( specification );
}
}
}
finally {
walker.getCurrentClauseStack().pop();
}
}
final SelfRenderingFunctionSqlAstExpression<?> function =
new SelfRenderingOrderedSetAggregateFunctionSqlAstExpression<>(
getFunctionName(),
getFunctionRenderer(),
emptyList(),
getFilter() == null ? null : (Predicate) getFilter().accept( walker ),
emptyList(),
resultType,
getMappingModelExpressible( walker, resultType, arguments )
);
final Over<Object> windowFunction = new Over<>( function, new ArrayList<>(), withinGroup );
walker.registerQueryTransformer(
new AggregateWindowEmulationQueryTransformer( windowFunction, withinGroup, arguments )
);
return windowFunction;
}
};
}
}
|
HypotheticalSetWindowEmulation
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/CompositeNaturalIdTest.java
|
{
"start": 728,
"end": 2002
}
|
class ____ {
@Test
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Book book = new Book();
book.setId(1L);
book.setTitle("High-Performance Java Persistence");
book.setAuthor("Vlad Mihalcea");
book.setIsbn(new Isbn(
"973022823X",
"978-9730228236"
));
entityManager.persist(book);
});
scope.inTransaction( entityManager -> {
//tag::naturalid-simple-load-access-example[]
Book book = entityManager
.unwrap(Session.class)
.bySimpleNaturalId(Book.class)
.load(
new Isbn(
"973022823X",
"978-9730228236"
)
);
//end::naturalid-simple-load-access-example[]
assertEquals("High-Performance Java Persistence", book.getTitle());
});
scope.inTransaction( entityManager -> {
//tag::naturalid-load-access-example[]
Book book = entityManager
.unwrap(Session.class)
.byNaturalId(Book.class)
.using(
"isbn",
new Isbn(
"973022823X",
"978-9730228236"
))
.load();
//end::naturalid-load-access-example[]
assertEquals("High-Performance Java Persistence", book.getTitle());
});
}
//tag::naturalid-single-embedded-attribute-mapping-example[]
@Entity(name = "Book")
public static
|
CompositeNaturalIdTest
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java
|
{
"start": 21650,
"end": 21864
}
|
class ____ annotated with
* {@code @SpringExtensionConfig(useTestClassScopedExtensionContext = true)},
* this method searches the {@code ExtensionContext} hierarchy for an
* {@code ExtensionContext} whose test
|
is
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/ExecutionGraphException.java
|
{
"start": 1018,
"end": 1428
}
|
class ____ extends JobManagerException {
private static final long serialVersionUID = -5439002256464886357L;
public ExecutionGraphException(String message) {
super(message);
}
public ExecutionGraphException(String message, Throwable cause) {
super(message, cause);
}
public ExecutionGraphException(Throwable cause) {
super(cause);
}
}
|
ExecutionGraphException
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/instance/destroy/InstanceDestroyTest.java
|
{
"start": 1761,
"end": 2017
}
|
class ____ {
static final AtomicBoolean DESTROYED = new AtomicBoolean(false);
void wash() {
}
@PreDestroy
void destroy() {
DESTROYED.set(true);
}
}
@ApplicationScoped
static
|
Washcloth
|
java
|
apache__rocketmq
|
client/src/main/java/org/apache/rocketmq/client/consumer/PullResult.java
|
{
"start": 933,
"end": 2300
}
|
class ____ {
private final PullStatus pullStatus;
private final long nextBeginOffset;
private final long minOffset;
private final long maxOffset;
private List<MessageExt> msgFoundList;
public PullResult(PullStatus pullStatus, long nextBeginOffset, long minOffset, long maxOffset,
List<MessageExt> msgFoundList) {
super();
this.pullStatus = pullStatus;
this.nextBeginOffset = nextBeginOffset;
this.minOffset = minOffset;
this.maxOffset = maxOffset;
this.msgFoundList = msgFoundList;
}
public PullStatus getPullStatus() {
return pullStatus;
}
public long getNextBeginOffset() {
return nextBeginOffset;
}
public long getMinOffset() {
return minOffset;
}
public long getMaxOffset() {
return maxOffset;
}
public List<MessageExt> getMsgFoundList() {
return msgFoundList;
}
public void setMsgFoundList(List<MessageExt> msgFoundList) {
this.msgFoundList = msgFoundList;
}
@Override
public String toString() {
return "PullResult [pullStatus=" + pullStatus + ", nextBeginOffset=" + nextBeginOffset
+ ", minOffset=" + minOffset + ", maxOffset=" + maxOffset + ", msgFoundList="
+ (msgFoundList == null ? 0 : msgFoundList.size()) + "]";
}
}
|
PullResult
|
java
|
apache__avro
|
lang/java/avro/src/main/java/org/apache/avro/SchemaBuilder.java
|
{
"start": 24267,
"end": 25052
}
|
enum ____'s symbols, and end its configuration. Populates the
* default if it was set.
**/
public R symbols(String... symbols) {
Schema schema = Schema.createEnum(name(), doc(), space(), Arrays.asList(symbols), this.enumDefault);
completeSchema(schema);
return context().complete(schema);
}
/** Set the default value of the enum. */
public EnumBuilder<R> defaultSymbol(String enumDefault) {
this.enumDefault = enumDefault;
return self();
}
}
/**
* Builds an Avro Map type with optional properties.
* <p/>
* Set properties with {@link #prop(String, String)}.
* <p/>
* The Map schema's properties are finalized when {@link #values()} or
* {@link #values(Schema)} is called.
**/
public static final
|
type
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/TimerSerializerTest.java
|
{
"start": 1156,
"end": 3076
}
|
class ____ extends SerializerTestBase<TimerHeapInternalTimer<Long, TimeWindow>> {
private static final TypeSerializer<Long> KEY_SERIALIZER = LongSerializer.INSTANCE;
private static final TypeSerializer<TimeWindow> NAMESPACE_SERIALIZER =
new TimeWindow.Serializer();
@Override
protected TypeSerializer<TimerHeapInternalTimer<Long, TimeWindow>> createSerializer() {
return new TimerSerializer<>(KEY_SERIALIZER, NAMESPACE_SERIALIZER);
}
@Override
protected int getLength() {
return Long.BYTES + KEY_SERIALIZER.getLength() + NAMESPACE_SERIALIZER.getLength();
}
@SuppressWarnings("unchecked")
@Override
protected Class<TimerHeapInternalTimer<Long, TimeWindow>> getTypeClass() {
return (Class<TimerHeapInternalTimer<Long, TimeWindow>>)
(Class<?>) TimerHeapInternalTimer.class;
}
@SuppressWarnings("unchecked")
@Override
protected TimerHeapInternalTimer<Long, TimeWindow>[] getTestData() {
return (TimerHeapInternalTimer<Long, TimeWindow>[])
new TimerHeapInternalTimer[] {
new TimerHeapInternalTimer<>(42L, 4711L, new TimeWindow(1000L, 2000L)),
new TimerHeapInternalTimer<>(0L, 0L, new TimeWindow(0L, 0L)),
new TimerHeapInternalTimer<>(1L, -1L, new TimeWindow(1L, -1L)),
new TimerHeapInternalTimer<>(-1L, 1L, new TimeWindow(-1L, 1L)),
new TimerHeapInternalTimer<>(
Long.MAX_VALUE,
Long.MIN_VALUE,
new TimeWindow(Long.MAX_VALUE, Long.MIN_VALUE)),
new TimerHeapInternalTimer<>(
Long.MIN_VALUE,
Long.MAX_VALUE,
new TimeWindow(Long.MIN_VALUE, Long.MAX_VALUE))
};
}
}
|
TimerSerializerTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/definition/ForeignKeyDefinitionManyToOneTest.java
|
{
"start": 862,
"end": 1113
}
|
class ____ {
@Id
public Integer id;
@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "thingy", foreignKeyDefinition = "foreign key /* FK */ (thing_id) references Thing"))
public Thing thing;
}
@Entity(name = "Thing")
public static
|
Box
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/OperatorTests.java
|
{
"start": 5043,
"end": 25360
}
|
class ____ extends MapperServiceTestCase {
public void testQueryOperator() throws IOException {
Map<BytesRef, Long> docs = new HashMap<>();
CheckedConsumer<DirectoryReader, IOException> verifier = reader -> {
final long from = randomBoolean() ? Long.MIN_VALUE : randomLongBetween(0, 10000);
final long to = randomBoolean() ? Long.MAX_VALUE : randomLongBetween(from, from + 10000);
final Query query = LongPoint.newRangeQuery("pt", from, to);
LuceneOperator.Factory factory = luceneOperatorFactory(
reader,
List.of(new LuceneSliceQueue.QueryAndTags(query, List.of())),
LuceneOperator.NO_LIMIT
);
List<Driver> drivers = new ArrayList<>();
try {
Set<Integer> actualDocIds = ConcurrentCollections.newConcurrentSet();
for (int t = 0; t < factory.taskConcurrency(); t++) {
PageConsumerOperator docCollector = new PageConsumerOperator(page -> {
DocVector docVector = page.<DocBlock>getBlock(0).asVector();
IntVector doc = docVector.docs();
IntVector segment = docVector.segments();
for (int i = 0; i < doc.getPositionCount(); i++) {
int docBase = reader.leaves().get(segment.getInt(i)).docBase;
int docId = docBase + doc.getInt(i);
assertTrue("duplicated docId=" + docId, actualDocIds.add(docId));
}
});
DriverContext driverContext = driverContext();
drivers.add(TestDriverFactory.create(driverContext, factory.get(driverContext), List.of(), docCollector));
}
OperatorTestCase.runDriver(drivers);
Set<Integer> expectedDocIds = searchForDocIds(reader, query);
assertThat("query=" + query, actualDocIds, equalTo(expectedDocIds));
drivers.stream().map(Driver::driverContext).forEach(OperatorTests::assertDriverContext);
} finally {
Releasables.close(drivers);
}
};
try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) {
int numDocs = randomIntBetween(0, 10_000);
for (int i = 0; i < numDocs; i++) {
Document d = new Document();
long point = randomLongBetween(0, 5000);
d.add(new LongPoint("pt", point));
BytesRef id = Uid.encodeId("id-" + randomIntBetween(0, 5000));
d.add(new Field("id", id, KeywordFieldMapper.Defaults.FIELD_TYPE));
if (docs.put(id, point) != null) {
w.updateDocument(new Term("id", id), d);
} else {
w.addDocument(d);
}
}
try (DirectoryReader reader = w.getReader()) {
verifier.accept(reader);
}
}
}
public void testPushRoundToToQuery() throws IOException {
long firstGroupMax = randomLong();
long secondGroupMax = randomLong();
long thirdGroupMax = randomLong();
CheckedConsumer<DirectoryReader, IOException> verifier = reader -> {
Query firstGroupQuery = LongPoint.newRangeQuery("g", Long.MIN_VALUE, 99);
Query secondGroupQuery = LongPoint.newRangeQuery("g", 100, 9999);
Query thirdGroupQuery = LongPoint.newRangeQuery("g", 10000, Long.MAX_VALUE);
LuceneSliceQueue.QueryAndTags firstGroupQueryAndTags = new LuceneSliceQueue.QueryAndTags(firstGroupQuery, List.of(0L));
LuceneSliceQueue.QueryAndTags secondGroupQueryAndTags = new LuceneSliceQueue.QueryAndTags(secondGroupQuery, List.of(100L));
LuceneSliceQueue.QueryAndTags thirdGroupQueryAndTags = new LuceneSliceQueue.QueryAndTags(thirdGroupQuery, List.of(10000L));
LuceneOperator.Factory factory = luceneOperatorFactory(
reader,
List.of(firstGroupQueryAndTags, secondGroupQueryAndTags, thirdGroupQueryAndTags),
LuceneOperator.NO_LIMIT
);
ValuesSourceReaderOperator.Factory load = new ValuesSourceReaderOperator.Factory(
ByteSizeValue.ofGb(1),
List.of(new ValuesSourceReaderOperator.FieldInfo("v", ElementType.LONG, false, f -> new LongsBlockLoader("v"))),
new IndexedByShardIdFromSingleton<>(new ValuesSourceReaderOperator.ShardContext(reader, (sourcePaths) -> {
throw new UnsupportedOperationException();
}, 0.8)),
0
);
List<Page> pages = new ArrayList<>();
DriverContext driverContext = driverContext();
try (
Driver driver = TestDriverFactory.create(
driverContext,
factory.get(driverContext),
List.of(load.get(driverContext)),
new TestResultPageSinkOperator(pages::add)
)
) {
OperatorTestCase.runDriver(driver);
}
assertDriverContext(driverContext);
boolean sawFirstMax = false;
boolean sawSecondMax = false;
boolean sawThirdMax = false;
for (Page page : pages) {
LongVector group = page.<LongBlock>getBlock(1).asVector();
LongVector value = page.<LongBlock>getBlock(2).asVector();
for (int p = 0; p < page.getPositionCount(); p++) {
long g = group.getLong(p);
long v = value.getLong(p);
switch ((int) g) {
case 0 -> {
assertThat(v, lessThanOrEqualTo(firstGroupMax));
sawFirstMax |= v == firstGroupMax;
}
case 100 -> {
assertThat(v, lessThanOrEqualTo(secondGroupMax));
sawSecondMax |= v == secondGroupMax;
}
case 10000 -> {
assertThat(v, lessThanOrEqualTo(thirdGroupMax));
sawThirdMax |= v == thirdGroupMax;
}
default -> throw new IllegalArgumentException("Unknown group [" + g + "]");
}
}
}
assertTrue(sawFirstMax);
assertTrue(sawSecondMax);
assertTrue(sawThirdMax);
};
try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) {
int numDocs = randomIntBetween(0, 10_000);
for (int i = 0; i < numDocs; i++) {
long g, v;
switch (between(0, 2)) {
case 0 -> {
g = randomLongBetween(Long.MIN_VALUE, 99);
v = randomLongBetween(Long.MIN_VALUE, firstGroupMax);
}
case 1 -> {
g = randomLongBetween(100, 9999);
v = randomLongBetween(Long.MIN_VALUE, secondGroupMax);
}
case 2 -> {
g = randomLongBetween(10000, Long.MAX_VALUE);
v = randomLongBetween(Long.MIN_VALUE, thirdGroupMax);
}
default -> throw new IllegalArgumentException();
}
w.addDocument(List.of(new LongField("g", g, Field.Store.NO), new LongField("v", v, Field.Store.NO)));
}
w.addDocument(List.of(new LongField("g", 0, Field.Store.NO), new LongField("v", firstGroupMax, Field.Store.NO)));
w.addDocument(List.of(new LongField("g", 200, Field.Store.NO), new LongField("v", secondGroupMax, Field.Store.NO)));
w.addDocument(List.of(new LongField("g", 20000, Field.Store.NO), new LongField("v", thirdGroupMax, Field.Store.NO)));
try (DirectoryReader reader = w.getReader()) {
verifier.accept(reader);
}
}
}
private static Set<Integer> searchForDocIds(IndexReader reader, Query query) throws IOException {
IndexSearcher searcher = new IndexSearcher(reader);
Set<Integer> docIds = new HashSet<>();
searcher.search(query, new Collector() {
@Override
public LeafCollector getLeafCollector(LeafReaderContext context) {
return new LeafCollector() {
@Override
public void setScorer(Scorable scorer) {
}
@Override
public void collect(int doc) {
int docId = context.docBase + doc;
assertTrue(docIds.add(docId));
}
};
}
@Override
public ScoreMode scoreMode() {
return ScoreMode.COMPLETE_NO_SCORES;
}
});
return docIds;
}
public void testHashLookup() {
// TODO move this to an integration test once we've plugged in the lookup
DriverContext driverContext = driverContext();
Map<Long, Integer> primeOrds = new TreeMap<>();
Block primesBlock;
try (LongBlock.Builder primes = driverContext.blockFactory().newLongBlockBuilder(30)) {
boolean[] sieve = new boolean[100];
Arrays.fill(sieve, true);
sieve[0] = false;
sieve[1] = false;
int prime = 2;
while (prime < 100) {
if (false == sieve[prime]) {
prime++;
continue;
}
primes.appendLong(prime);
primeOrds.put((long) prime, primeOrds.size());
for (int m = prime + prime; m < sieve.length; m += prime) {
sieve[m] = false;
}
prime++;
}
primesBlock = primes.build();
}
try {
List<Long> values = new ArrayList<>();
List<Object> expectedValues = new ArrayList<>();
List<Object> expectedPrimeOrds = new ArrayList<>();
for (int i = 0; i < 100; i++) {
long v = i % 10 == 0 ? randomFrom(primeOrds.keySet()) : randomLongBetween(0, 100);
values.add(v);
expectedValues.add(v);
expectedPrimeOrds.add(primeOrds.get(v));
}
var actualValues = new ArrayList<>();
var actualPrimeOrds = new ArrayList<>();
try (
var driver = TestDriverFactory.create(
driverContext,
new SequenceLongBlockSourceOperator(driverContext.blockFactory(), values, 100),
List.of(
new RowInTableLookupOperator(
driverContext.blockFactory(),
new RowInTableLookupOperator.Key[] { new RowInTableLookupOperator.Key("primes", primesBlock) },
new int[] { 0 }
)
),
new PageConsumerOperator(page -> {
try {
BlockTestUtils.readInto(actualValues, page.getBlock(0));
BlockTestUtils.readInto(actualPrimeOrds, page.getBlock(1));
} finally {
page.releaseBlocks();
}
})
)
) {
OperatorTestCase.runDriver(driver);
}
assertThat(actualValues, equalTo(expectedValues));
assertThat(actualPrimeOrds, equalTo(expectedPrimeOrds));
assertDriverContext(driverContext);
} finally {
primesBlock.close();
}
}
public void testPushRoundToCountToQuery() throws IOException {
int firstGroupDocs = randomIntBetween(0, 10_000);
int secondGroupDocs = randomIntBetween(0, 10_000);
int thirdGroupDocs = randomIntBetween(0, 10_000);
CheckedConsumer<DirectoryReader, IOException> verifier = reader -> {
Query firstGroupQuery = LongPoint.newRangeQuery("g", Long.MIN_VALUE, 99);
Query secondGroupQuery = LongPoint.newRangeQuery("g", 100, 9999);
Query thirdGroupQuery = LongPoint.newRangeQuery("g", 10000, Long.MAX_VALUE);
LuceneSliceQueue.QueryAndTags firstGroupQueryAndTags = new LuceneSliceQueue.QueryAndTags(firstGroupQuery, List.of(0L));
LuceneSliceQueue.QueryAndTags secondGroupQueryAndTags = new LuceneSliceQueue.QueryAndTags(secondGroupQuery, List.of(100L));
LuceneSliceQueue.QueryAndTags thirdGroupQueryAndTags = new LuceneSliceQueue.QueryAndTags(thirdGroupQuery, List.of(10000L));
// Data driver
List<Page> dataDriverPages = new ArrayList<>();
{
LuceneOperator.Factory factory = luceneCountOperatorFactory(
reader,
List.of(ElementType.LONG),
List.of(firstGroupQueryAndTags, secondGroupQueryAndTags, thirdGroupQueryAndTags)
);
DriverContext driverContext = driverContext();
try (
Driver driver = TestDriverFactory.create(
driverContext,
factory.get(driverContext),
List.of(),
new TestResultPageSinkOperator(dataDriverPages::add)
)
) {
OperatorTestCase.runDriver(driver);
}
assertDriverContext(driverContext);
}
// Reduce driver
List<Page> reduceDriverPages = new ArrayList<>();
try (CannedSourceOperator sourceOperator = new CannedSourceOperator(dataDriverPages.iterator())) {
HashAggregationOperator.HashAggregationOperatorFactory aggFactory =
new HashAggregationOperator.HashAggregationOperatorFactory(
List.of(new BlockHash.GroupSpec(0, ElementType.LONG)),
AggregatorMode.INTERMEDIATE,
List.of(CountAggregatorFunction.supplier().groupingAggregatorFactory(AggregatorMode.INTERMEDIATE, List.of(1, 2))),
Integer.MAX_VALUE,
null
);
DriverContext driverContext = driverContext();
try (
Driver driver = TestDriverFactory.create(
driverContext,
sourceOperator,
List.of(aggFactory.get(driverContext)),
new TestResultPageSinkOperator(reduceDriverPages::add)
)
) {
OperatorTestCase.runDriver(driver);
}
assertDriverContext(driverContext);
}
assertThat(reduceDriverPages, hasSize(1));
Page result = reduceDriverPages.getFirst();
assertThat(result.getBlockCount(), equalTo(3));
LongBlock groupsBlock = result.getBlock(0);
LongVector groups = groupsBlock.asVector();
LongBlock countsBlock = result.getBlock(1);
LongVector counts = countsBlock.asVector();
Map<Long, Long> actual = new TreeMap<>();
for (int p = 0; p < result.getPositionCount(); p++) {
actual.put(groups.getLong(p), counts.getLong(p));
}
assertMap(
actual,
matchesMap().entry(0L, (long) firstGroupDocs).entry(100L, (long) secondGroupDocs).entry(10000L, (long) thirdGroupDocs)
);
};
try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) {
for (int i = 0; i < firstGroupDocs; i++) {
long g = randomLongBetween(Long.MIN_VALUE, 99);
w.addDocument(List.of(new LongField("g", g, Field.Store.NO)));
}
for (int i = 0; i < secondGroupDocs; i++) {
long g = randomLongBetween(100, 9999);
w.addDocument(List.of(new LongField("g", g, Field.Store.NO)));
}
for (int i = 0; i < thirdGroupDocs; i++) {
long g = randomLongBetween(10000, Long.MAX_VALUE);
w.addDocument(List.of(new LongField("g", g, Field.Store.NO)));
}
try (DirectoryReader reader = w.getReader()) {
verifier.accept(reader);
}
}
}
/**
* Creates a {@link BigArrays} that tracks releases but doesn't throw circuit breaking exceptions.
*/
private BigArrays bigArrays() {
return new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService());
}
/**
* A {@link DriverContext} that won't throw {@link CircuitBreakingException}.
*/
protected final DriverContext driverContext() {
var breaker = new MockBigArrays.LimitedBreaker("esql-test-breaker", ByteSizeValue.ofGb(1));
return new DriverContext(bigArrays(), BlockFactory.getInstance(breaker, bigArrays()));
}
public static void assertDriverContext(DriverContext driverContext) {
assertTrue(driverContext.isFinished());
assertThat(driverContext.getSnapshot().releasables(), empty());
}
static LuceneOperator.Factory luceneOperatorFactory(IndexReader reader, List<LuceneSliceQueue.QueryAndTags> queryAndTags, int limit) {
final ShardContext searchContext = new LuceneSourceOperatorTests.MockShardContext(reader, 0);
return new LuceneSourceOperator.Factory(
new IndexedByShardIdFromSingleton<>(searchContext),
ctx -> queryAndTags,
randomFrom(DataPartitioning.values()),
DataPartitioning.AutoStrategy.DEFAULT,
randomIntBetween(1, 10),
randomPageSize(),
limit,
false // no scoring
);
}
static LuceneOperator.Factory luceneCountOperatorFactory(
IndexReader reader,
List<ElementType> tagTypes,
List<LuceneSliceQueue.QueryAndTags> queryAndTags
) {
final ShardContext searchContext = new LuceneSourceOperatorTests.MockShardContext(reader, 0);
return new LuceneCountOperator.Factory(
new IndexedByShardIdFromSingleton<>(searchContext),
ctx -> queryAndTags,
randomFrom(DataPartitioning.values()),
randomIntBetween(1, 10),
tagTypes,
LuceneOperator.NO_LIMIT
);
}
private MappedFieldType.BlockLoaderContext mockBlContext() {
return new MappedFieldType.BlockLoaderContext() {
@Override
public String indexName() {
throw new UnsupportedOperationException();
}
@Override
public IndexSettings indexSettings() {
throw new UnsupportedOperationException();
}
@Override
public MappedFieldType.FieldExtractPreference fieldExtractPreference() {
return MappedFieldType.FieldExtractPreference.NONE;
}
@Override
public SearchLookup lookup() {
throw new UnsupportedOperationException();
}
@Override
public Set<String> sourcePaths(String name) {
throw new UnsupportedOperationException();
}
@Override
public String parentField(String field) {
throw new UnsupportedOperationException();
}
@Override
public FieldNamesFieldMapper.FieldNamesFieldType fieldNames() {
throw new UnsupportedOperationException();
}
};
}
}
|
OperatorTests
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/UserResource.java
|
{
"start": 198,
"end": 469
}
|
class ____ {
@Context
SecurityContext securityContext;
@GET
public String get() {
if (securityContext.getUserPrincipal() == null) {
return null;
}
return securityContext.getUserPrincipal().getName();
}
}
|
UserResource
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/misc/AsyncSemaphore.java
|
{
"start": 836,
"end": 3549
}
|
class ____ {
private final ExecutorService executorService;
private final AtomicInteger tasksLatch = new AtomicInteger(1);
private final AtomicInteger stackSize = new AtomicInteger();
private final AtomicInteger counter;
private final FastRemovalQueue<CompletableFuture<Void>> listeners = new FastRemovalQueue<>();
public AsyncSemaphore(int permits) {
this(permits, null);
}
public AsyncSemaphore(int permits, ExecutorService executorService) {
counter = new AtomicInteger(permits);
this.executorService = executorService;
}
public int queueSize() {
return listeners.size();
}
public void removeListeners() {
listeners.clear();
}
public CompletableFuture<Void> acquire() {
CompletableFuture<Void> future = new CompletableFuture<>();
listeners.add(future);
future.whenComplete((r, e) -> {
if (e != null) {
listeners.remove(future);
}
});
tryForkAndRun();
return future;
}
private void tryForkAndRun() {
if (executorService != null) {
int val = tasksLatch.get();
if (stackSize.get() > 25 * val
&& tasksLatch.compareAndSet(val, val+1)) {
executorService.submit(() -> {
tasksLatch.decrementAndGet();
tryRun();
});
return;
}
}
tryRun();
}
private void tryRun() {
while (true) {
if (counter.decrementAndGet() >= 0) {
CompletableFuture<Void> future = listeners.poll();
if (future == null) {
counter.incrementAndGet();
return;
}
boolean complete;
if (executorService != null) {
stackSize.incrementAndGet();
complete = future.complete(null);
stackSize.decrementAndGet();
} else {
complete = future.complete(null);
}
if (complete) {
return;
} else {
counter.incrementAndGet();
}
}
if (counter.incrementAndGet() <= 0) {
return;
}
}
}
public int getCounter() {
return counter.get();
}
public void release() {
counter.incrementAndGet();
tryForkAndRun();
}
@Override
public String toString() {
return "value:" + counter + ":queue:" + queueSize();
}
}
|
AsyncSemaphore
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java
|
{
"start": 1727,
"end": 3170
}
|
class ____ {
private static final String CONFIG = "/log4j-test1.xml";
private static LoggerContext context;
@TempLoggingDir
private static Path loggingPath;
@BeforeAll
static void setupClass() {
context = LoggerContext.getContext(false);
}
@AfterAll
static void tearDownClass() {
Configurator.shutdown(context);
StatusLogger.getLogger().reset();
}
@Test
void testReconfiguration() throws Exception {
final Configuration cfg = context.getConfiguration();
assertNotNull(cfg, "No configuration");
assertInstanceOf(DefaultConfiguration.class, cfg, "Not set to default configuration");
final URI configLocation = LateConfigTest.class.getResource(CONFIG).toURI();
final LoggerContext loggerContext = LoggerContext.getContext(null, false, configLocation);
assertNotNull(loggerContext, "No Logger Context");
assertThat(loggingPath.resolve("test-xml.log")).exists();
final Configuration newConfig = loggerContext.getConfiguration();
assertNotSame(cfg, newConfig, "Configuration not reset");
assertInstanceOf(XmlConfiguration.class, newConfig, "Reconfiguration failed");
context = LoggerContext.getContext(false);
final Configuration sameConfig = context.getConfiguration();
assertSame(newConfig, sameConfig, "Configuration should not have been reset");
}
}
|
LateConfigTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/TransformInfoTransportAction.java
|
{
"start": 1758,
"end": 7218
}
|
class ____ extends XPackInfoFeatureTransportAction {
private static final Logger logger = LogManager.getLogger(TransformInfoTransportAction.class);
public static final String[] PROVIDED_STATS = new String[] {
TransformIndexerStats.NUM_PAGES.getPreferredName(),
TransformIndexerStats.NUM_INPUT_DOCUMENTS.getPreferredName(),
TransformIndexerStats.NUM_OUTPUT_DOCUMENTS.getPreferredName(),
TransformIndexerStats.NUM_DELETED_DOCUMENTS.getPreferredName(),
TransformIndexerStats.NUM_INVOCATIONS.getPreferredName(),
TransformIndexerStats.INDEX_TIME_IN_MS.getPreferredName(),
TransformIndexerStats.SEARCH_TIME_IN_MS.getPreferredName(),
TransformIndexerStats.PROCESSING_TIME_IN_MS.getPreferredName(),
TransformIndexerStats.DELETE_TIME_IN_MS.getPreferredName(),
TransformIndexerStats.INDEX_TOTAL.getPreferredName(),
TransformIndexerStats.SEARCH_TOTAL.getPreferredName(),
TransformIndexerStats.PROCESSING_TOTAL.getPreferredName(),
TransformIndexerStats.INDEX_FAILURES.getPreferredName(),
TransformIndexerStats.SEARCH_FAILURES.getPreferredName(),
TransformIndexerStats.EXPONENTIAL_AVG_CHECKPOINT_DURATION_MS.getPreferredName(),
TransformIndexerStats.EXPONENTIAL_AVG_DOCUMENTS_INDEXED.getPreferredName(),
TransformIndexerStats.EXPONENTIAL_AVG_DOCUMENTS_PROCESSED.getPreferredName(), };
@Inject
public TransformInfoTransportAction(TransportService transportService, ActionFilters actionFilters) {
super(XPackInfoFeatureAction.TRANSFORM.name(), transportService, actionFilters);
}
@Override
public String name() {
return XPackField.TRANSFORM;
}
@Override
public boolean available() {
return true;
}
@Override
public boolean enabled() {
return true;
}
static TransformIndexerStats parseSearchAggs(SearchResponse searchResponse) {
List<Double> statisticsList = new ArrayList<>(PROVIDED_STATS.length);
for (String statName : PROVIDED_STATS) {
Aggregation agg = searchResponse.getAggregations().get(statName);
if (agg instanceof NumericMetricsAggregation.SingleValue) {
statisticsList.add(((NumericMetricsAggregation.SingleValue) agg).value());
} else {
statisticsList.add(0.0);
}
}
return new TransformIndexerStats(
statisticsList.get(0).longValue(), // numPages
statisticsList.get(1).longValue(), // numInputDocuments
statisticsList.get(2).longValue(), // numOutputDocuments
statisticsList.get(3).longValue(), // numDeletedDocuments
statisticsList.get(4).longValue(), // numInvocations
statisticsList.get(5).longValue(), // indexTime
statisticsList.get(6).longValue(), // searchTime
statisticsList.get(7).longValue(), // processingTime
statisticsList.get(8).longValue(), // deleteTime
statisticsList.get(9).longValue(), // indexTotal
statisticsList.get(10).longValue(), // searchTotal
statisticsList.get(11).longValue(), // processingTotal
statisticsList.get(12).longValue(), // indexFailures
statisticsList.get(13).longValue(), // searchFailures
statisticsList.get(14), // exponential_avg_checkpoint_duration_ms
statisticsList.get(15), // exponential_avg_documents_indexed
statisticsList.get(16) // exponential_avg_documents_processed
);
}
static void getStatisticSummations(Client client, ActionListener<TransformIndexerStats> statsListener) {
QueryBuilder queryBuilder = QueryBuilders.constantScoreQuery(
QueryBuilders.boolQuery()
.filter(QueryBuilders.termQuery(TransformField.INDEX_DOC_TYPE.getPreferredName(), TransformStoredDoc.NAME))
);
SearchRequestBuilder requestBuilder = client.prepareSearch(
TransformInternalIndexConstants.INDEX_NAME_PATTERN,
TransformInternalIndexConstants.INDEX_NAME_PATTERN_DEPRECATED
).setSize(0).setQuery(queryBuilder);
final String path = TransformField.STATS_FIELD.getPreferredName() + ".";
for (String statName : PROVIDED_STATS) {
requestBuilder.addAggregation(AggregationBuilders.sum(statName).field(path + statName));
}
ActionListener<SearchResponse> getStatisticSummationsListener = ActionListener.wrap(searchResponse -> {
if (searchResponse.getShardFailures().length > 0) {
logger.error(
"statistics summations search returned shard failures: {}",
Arrays.toString(searchResponse.getShardFailures())
);
}
statsListener.onResponse(parseSearchAggs(searchResponse));
}, failure -> {
if (failure instanceof ResourceNotFoundException) {
statsListener.onResponse(new TransformIndexerStats());
} else {
statsListener.onFailure(failure);
}
});
ClientHelper.executeAsyncWithOrigin(
client.threadPool().getThreadContext(),
ClientHelper.TRANSFORM_ORIGIN,
requestBuilder.request(),
getStatisticSummationsListener,
client::search
);
}
}
|
TransformInfoTransportAction
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/IteratorRemovePageTests.java
|
{
"start": 1053,
"end": 3709
}
|
class ____ implements OperatorFactory {
@Override
public Operator get(DriverContext driverContext) {
return new IteratorRemovePage();
}
@Override
public String describe() {
return "IteratorRemovePage[]";
}
}
private boolean keep = true;
@Override
protected ReleasableIterator<Page> receive(Page page) {
if (keep) {
keep = false;
return new ReleasableIterator<>() {
Page p = page;
@Override
public boolean hasNext() {
return p != null;
}
@Override
public Page next() {
Page ret = p;
p = null;
return ret;
}
@Override
public void close() {
if (p != null) {
p.releaseBlocks();
}
}
};
}
keep = true;
page.releaseBlocks();
return new ReleasableIterator<>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Page next() {
throw new UnsupportedOperationException();
}
@Override
public void close() {}
};
}
@Override
public String toString() {
return "IteratorRemovePage[]";
}
}
@Override
protected SourceOperator simpleInput(BlockFactory blockFactory, int size) {
return new SequenceLongBlockSourceOperator(blockFactory, LongStream.range(0, size).map(l -> randomLong()));
}
@Override
protected void assertSimpleOutput(List<Page> input, List<Page> results) {
assertThat(results, hasSize((input.size() + 1) / 2));
for (int i = 0; i < input.size(); i += 2) {
assertThat(input.get(i), equalTo(results.get(i / 2)));
}
}
@Override
protected Operator.OperatorFactory simple(SimpleOptions options) {
return new IteratorRemovePage.Factory();
}
@Override
protected Matcher<String> expectedDescriptionOfSimple() {
return equalTo("IteratorRemovePage[]");
}
@Override
protected Matcher<String> expectedToStringOfSimple() {
return expectedDescriptionOfSimple();
}
}
|
Factory
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/mapreduce/RMapper.java
|
{
"start": 1132,
"end": 1466
}
|
interface ____<KIn, VIn, KOut, VOut> extends Serializable {
/**
* Invoked for each Map source entry
*
* @param key - input key
* @param value - input value
* @param collector - instance shared across all Mapper tasks
*/
void map(KIn key, VIn value, RCollector<KOut, VOut> collector);
}
|
RMapper
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/operators/util/UserCodeObjectWrapper.java
|
{
"start": 5072,
"end": 5800
}
|
class ____ checking for serializability.",
e);
}
}
@Override
public T getUserCodeObject(Class<? super T> superClass, ClassLoader cl) {
return userCodeObject;
}
@Override
public T getUserCodeObject() {
return userCodeObject;
}
@Override
public <A extends Annotation> A getUserCodeAnnotation(Class<A> annotationClass) {
return userCodeObject.getClass().getAnnotation(annotationClass);
}
@SuppressWarnings("unchecked")
@Override
public Class<? extends T> getUserCodeClass() {
return (Class<? extends T>) userCodeObject.getClass();
}
@Override
public boolean hasObject() {
return true;
}
}
|
while
|
java
|
micronaut-projects__micronaut-core
|
test-suite/src/test/java/io/micronaut/docs/http/server/netty/websocket/ChatClientWebSocket.java
|
{
"start": 1234,
"end": 2429
}
|
class ____ implements AutoCloseable { // <2>
private WebSocketSession session;
private HttpRequest request;
private String topic;
private String username;
private Collection<String> replies = new ConcurrentLinkedQueue<>();
@OnOpen
public void onOpen(String topic, String username,
WebSocketSession session, HttpRequest request) { // <3>
this.topic = topic;
this.username = username;
this.session = session;
this.request = request;
}
public String getTopic() {
return topic;
}
public String getUsername() {
return username;
}
public Collection<String> getReplies() {
return replies;
}
public WebSocketSession getSession() {
return session;
}
public HttpRequest getRequest() {
return request;
}
@OnMessage
public void onMessage(String message) {
replies.add(message); // <4>
}
// end::class[]
public abstract void send(String message);
public abstract Future<String> sendAsync(String message);
@SingleResult
public abstract Publisher<String> sendRx(String message);
}
|
ChatClientWebSocket
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/util/FileCopyUtils.java
|
{
"start": 1175,
"end": 1465
}
|
class ____ leave streams open can be found in {@link StreamUtils}.
*
* <p>Mainly for use within the framework, but also useful for application code.
*
* @author Juergen Hoeller
* @author Hyunjin Choi
* @since 06.10.2003
* @see StreamUtils
* @see FileSystemUtils
*/
public abstract
|
that
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/serialization/SerializerConfigImpl.java
|
{
"start": 7543,
"end": 13863
}
|
class ____ the type to register.
*/
public void registerKryoType(Class<?> type) {
if (type == null) {
throw new NullPointerException("Cannot register null type class.");
}
registeredKryoTypes.add(type);
}
/** Returns the registered types with Kryo Serializers. */
public LinkedHashMap<Class<?>, SerializableSerializer<?>>
getRegisteredTypesWithKryoSerializers() {
return registeredTypesWithKryoSerializers;
}
/** Returns the registered types with their Kryo Serializer classes. */
public LinkedHashMap<Class<?>, Class<? extends Serializer<?>>>
getRegisteredTypesWithKryoSerializerClasses() {
return registeredTypesWithKryoSerializerClasses;
}
/** Returns the registered default Kryo Serializers. */
public LinkedHashMap<Class<?>, SerializableSerializer<?>> getDefaultKryoSerializers() {
return defaultKryoSerializers;
}
/** Returns the registered default Kryo Serializer classes. */
public LinkedHashMap<Class<?>, Class<? extends Serializer<?>>>
getDefaultKryoSerializerClasses() {
return defaultKryoSerializerClasses;
}
/** Returns the registered Kryo types. */
public LinkedHashSet<Class<?>> getRegisteredKryoTypes() {
if (isForceKryoEnabled()) {
// if we force kryo, we must also return all the types that
// were previously only registered as POJO
LinkedHashSet<Class<?>> result = new LinkedHashSet<>(registeredKryoTypes);
result.addAll(registeredPojoTypes);
return result;
} else {
return registeredKryoTypes;
}
}
/** Returns the registered POJO types. */
public LinkedHashSet<Class<?>> getRegisteredPojoTypes() {
return registeredPojoTypes;
}
/** Returns the registered type info factories. */
public Map<Class<?>, Class<? extends TypeInfoFactory<?>>> getRegisteredTypeInfoFactories() {
return registeredTypeInfoFactories;
}
/**
* Checks whether generic types are supported. Generic types are types that go through Kryo
* during serialization.
*
* <p>Generic types are enabled by default.
*/
public boolean hasGenericTypesDisabled() {
return !configuration.get(PipelineOptions.GENERIC_TYPES);
}
public void setGenericTypes(boolean genericTypes) {
configuration.set(PipelineOptions.GENERIC_TYPES, genericTypes);
}
/** Returns whether Kryo is the serializer for POJOs. */
public boolean isForceKryoEnabled() {
return configuration.get(PipelineOptions.FORCE_KRYO);
}
public void setForceKryo(boolean forceKryo) {
configuration.set(PipelineOptions.FORCE_KRYO, forceKryo);
}
/** Returns whether the Apache Avro is the serializer for POJOs. */
public boolean isForceAvroEnabled() {
return configuration.get(PipelineOptions.FORCE_AVRO);
}
public void setForceAvro(boolean forceAvro) {
configuration.set(PipelineOptions.FORCE_AVRO, forceAvro);
}
public void setForceKryoAvro(boolean forceKryoAvro) {
configuration.set(PipelineOptions.FORCE_KRYO_AVRO, forceKryoAvro);
}
public TernaryBoolean isForceKryoAvroEnabled() {
return configuration
.getOptional(PipelineOptions.FORCE_KRYO_AVRO)
.map(TernaryBoolean::fromBoolean)
.orElse(TernaryBoolean.UNDEFINED);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SerializerConfigImpl) {
SerializerConfigImpl other = (SerializerConfigImpl) obj;
return Objects.equals(configuration, other.configuration)
&& registeredTypesWithKryoSerializers.equals(
other.registeredTypesWithKryoSerializers)
&& registeredTypesWithKryoSerializerClasses.equals(
other.registeredTypesWithKryoSerializerClasses)
&& defaultKryoSerializers.equals(other.defaultKryoSerializers)
&& defaultKryoSerializerClasses.equals(other.defaultKryoSerializerClasses)
&& registeredKryoTypes.equals(other.registeredKryoTypes)
&& registeredPojoTypes.equals(other.registeredPojoTypes)
&& registeredTypeInfoFactories.equals(other.registeredTypeInfoFactories);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(
configuration,
registeredTypesWithKryoSerializers,
registeredTypesWithKryoSerializerClasses,
defaultKryoSerializers,
defaultKryoSerializerClasses,
registeredKryoTypes,
registeredPojoTypes,
registeredTypeInfoFactories);
}
@Override
public String toString() {
return "SerializerConfig{"
+ "configuration="
+ configuration
+ ", registeredTypesWithKryoSerializers="
+ registeredTypesWithKryoSerializers
+ ", registeredTypesWithKryoSerializerClasses="
+ registeredTypesWithKryoSerializerClasses
+ ", defaultKryoSerializers="
+ defaultKryoSerializers
+ ", defaultKryoSerializerClasses="
+ defaultKryoSerializerClasses
+ ", registeredKryoTypes="
+ registeredKryoTypes
+ ", registeredPojoTypes="
+ registeredPojoTypes
+ ", registeredTypeFactories="
+ registeredTypeInfoFactories
+ '}';
}
// ------------------------------ Utilities ----------------------------------
/**
* Sets all relevant options contained in the {@link ReadableConfig} such as e.g. {@link
* PipelineOptions#FORCE_KRYO}.
*
* <p>It will change the value of a setting only if a corresponding option was set in the {@code
* configuration}. If a key is not present, the current value of a field will remain untouched.
*
* @param configuration a configuration to read the values from
* @param classLoader a
|
of
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/matching/PathParamOverlapTest.java
|
{
"start": 2526,
"end": 3149
}
|
class ____ {
@GET
@Path("/some/test")
@Produces(MediaType.TEXT_PLAIN)
public String test() {
return "Hello World!";
}
@GET
@Path("/{id}/test/new")
public String second(@RestPath String id) {
return "Hello " + id;
}
@GET
@Path("/foo/{param}")
public String foo(@RestPath String param) {
return "Foo " + param;
}
@GET
@Path("/foo/bar/{param}")
public String fooBar(@RestPath String param) {
return "FooBar " + param;
}
}
}
|
TestResource
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrarTests.java
|
{
"start": 20704,
"end": 20890
}
|
class ____ {
private final Map<String, List<Nested>> nested = new HashMap<>();
public Map<String, List<Nested>> getNested() {
return this.nested;
}
public static
|
NestedGenerics
|
java
|
jhy__jsoup
|
src/main/java/org/jsoup/parser/Tag.java
|
{
"start": 341,
"end": 11831
}
|
class ____ implements Cloneable {
/** Tag option: the tag is known (specifically defined). This impacts if options may need to be inferred (when not
known) in, e.g., the pretty-printer. Set when a tag is added to a TagSet, or when settings are set(). */
public static int Known = 1;
/** Tag option: the tag is a void tag (e.g., {@code <img>}), that can contain no children, and in HTML does not require closing. */
public static int Void = 1 << 1;
/** Tag option: the tag is a block tag (e.g., {@code <div>}, {@code <p>}). Causes the element to be indented when pretty-printing. If not a block, it is inline. */
public static int Block = 1 << 2;
/** Tag option: the tag is a block tag that will only hold inline tags (e.g., {@code <p>}); used for formatting. (Must also set Block.) */
public static int InlineContainer = 1 << 3;
/** Tag option: the tag can self-close (e.g., {@code <foo />}). */
public static int SelfClose = 1 << 4;
/** Tag option: the tag has been seen self-closing in this parse. */
public static int SeenSelfClose = 1 << 5;
/** Tag option: the tag preserves whitespace (e.g., {@code <pre>}). */
public static int PreserveWhitespace = 1 << 6;
/** Tag option: the tag is an RCDATA element that can have text and character references (e.g., {@code <title>}, {@code <textarea>}). */
public static int RcData = 1 << 7;
/** Tag option: the tag is a Data element that can have text but not character references (e.g., {@code <style>}, {@code <script>}). */
public static int Data = 1 << 8;
/** Tag option: the tag's value will be included when submitting a form (e.g., {@code <input>}). */
public static int FormSubmittable = 1 << 9;
String namespace;
String tagName;
String normalName; // always the lower case version of this tag, regardless of case preservation mode
int options = 0;
/**
Create a new Tag, with the given name and namespace.
<p>The tag is not implicitly added to any TagSet.</p>
@param tagName the name of the tag. Case-sensitive.
@param namespace the namespace for the tag.
@see TagSet#valueOf(String, String)
@since 1.20.1
*/
public Tag(String tagName, String namespace) {
this(tagName, ParseSettings.normalName(tagName), namespace);
}
/**
Create a new Tag, with the given name, in the HTML namespace.
<p>The tag is not implicitly added to any TagSet.</p>
@param tagName the name of the tag. Case-sensitive.
@see TagSet#valueOf(String, String)
@since 1.20.1
*/
public Tag(String tagName) {
this(tagName, ParseSettings.normalName(tagName), NamespaceHtml);
}
/** Path for TagSet defaults, no options set; normal name is already LC. */
Tag(String tagName, String normalName, String namespace) {
this.tagName = tagName;
this.normalName = normalName;
this.namespace = namespace;
}
/**
* Get this tag's name.
*
* @return the tag's name
*/
public String getName() {
return tagName;
}
/**
Get this tag's name.
@return the tag's name
*/
public String name() {
return tagName;
}
/**
Change the tag's name. As Tags are reused throughout a Document, this will change the name for all uses of this tag.
@param tagName the new name of the tag. Case-sensitive.
@return this tag
@since 1.20.1
*/
public Tag name(String tagName) {
this.tagName = tagName;
this.normalName = ParseSettings.normalName(tagName);
return this;
}
/**
Get this tag's prefix, if it has one; else the empty string.
<p>For example, {@code <book:title>} has prefix {@code book}, and tag name {@code book:title}.</p>
@return the tag's prefix
@since 1.20.1
*/
public String prefix() {
int pos = tagName.indexOf(':');
if (pos == -1) return "";
else return tagName.substring(0, pos);
}
/**
Get this tag's local name. The local name is the name without the prefix (if any).
<p>For exmaple, {@code <book:title>} has local name {@code title}, and tag name {@code book:title}.</p>
@return the tag's local name
@since 1.20.1
*/
public String localName() {
int pos = tagName.indexOf(':');
if (pos == -1) return tagName;
else return tagName.substring(pos + 1);
}
/**
* Get this tag's normalized (lowercased) name.
* @return the tag's normal name.
*/
public String normalName() {
return normalName;
}
/**
Get this tag's namespace.
@return the tag's namespace
*/
public String namespace() {
return namespace;
}
/**
Set the tag's namespace. As Tags are reused throughout a Document, this will change the namespace for all uses of this tag.
@param namespace the new namespace of the tag.
@return this tag
@since 1.20.1
*/
public Tag namespace(String namespace) {
this.namespace = namespace;
return this;
}
/**
Set an option on this tag.
<p>Once a tag has a setting applied, it will be considered a known tag.</p>
@param option the option to set
@return this tag
@since 1.20.1
*/
public Tag set(int option) {
options |= option;
options |= Tag.Known; // considered known if touched
return this;
}
/**
Test if an option is set on this tag.
@param option the option to test
@return true if the option is set
@since 1.20.1
*/
public boolean is(int option) {
return (options & option) != 0;
}
/**
Clear (unset) an option from this tag.
@param option the option to clear
@return this tag
@since 1.20.1
*/
public Tag clear(int option) {
options &= ~option;
// considered known if touched, unless explicitly clearing known
if (option != Tag.Known) options |= Tag.Known;
return this;
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (p, div etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". Case-insensitive.
* @param namespace the namespace for the tag.
* @param settings used to control tag name sensitivity
* @see TagSet
* @return The tag, either defined or new generic.
*/
public static Tag valueOf(String tagName, String namespace, ParseSettings settings) {
return TagSet.Html().valueOf(tagName, null, namespace, settings.preserveTagCase());
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>.
* @return The tag, either defined or new generic.
* @see #valueOf(String tagName, String namespace, ParseSettings settings)
*/
public static Tag valueOf(String tagName) {
return valueOf(tagName, NamespaceHtml, ParseSettings.preserveCase);
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>.
* @param settings used to control tag name sensitivity
* @return The tag, either defined or new generic.
* @see #valueOf(String tagName, String namespace, ParseSettings settings)
*/
public static Tag valueOf(String tagName, ParseSettings settings) {
return valueOf(tagName, NamespaceHtml, settings);
}
/**
* Gets if this is a block tag.
*
* @return if block tag
*/
public boolean isBlock() {
return (options & Block) != 0;
}
/**
Get if this is an InlineContainer tag.
@return true if an InlineContainer (which formats children as inline).
@deprecated setting is only used within the Printer. Will be removed in a future release.
*/
@Deprecated public boolean formatAsBlock() {
return (options & InlineContainer) != 0;
}
/**
* Gets if this tag is an inline tag. Just the opposite of isBlock.
*
* @return if this tag is an inline tag.
*/
public boolean isInline() {
return (options & Block) == 0;
}
/**
Get if this is void (aka empty) tag.
@return true if this is a void tag
*/
public boolean isEmpty() {
return (options & Void) != 0;
}
/**
* Get if this tag is self-closing.
*
* @return if this tag should be output as self-closing.
*/
public boolean isSelfClosing() {
return (options & SelfClose) != 0 || (options & Void) != 0;
}
/**
* Get if this is a pre-defined tag in the TagSet, or was auto created on parsing.
*
* @return if a known tag
*/
public boolean isKnownTag() {
return (options & Known) != 0;
}
/**
* Check if this tag name is a known HTML tag.
*
* @param tagName name of tag
* @return if known HTML tag
*/
public static boolean isKnownTag(String tagName) {
return TagSet.HtmlTagSet.get(tagName, NamespaceHtml) != null;
}
/**
* Get if this tag should preserve whitespace within child text nodes.
*
* @return if preserve whitespace
*/
public boolean preserveWhitespace() {
return (options & PreserveWhitespace) != 0;
}
/**
* Get if this tag represents an element that should be submitted with a form. E.g. input, option
* @return if submittable with a form
*/
public boolean isFormSubmittable() {
return (options & FormSubmittable) != 0;
}
void setSeenSelfClose() {
options |= Tag.SeenSelfClose; // does not change known status
}
/**
If this Tag uses a specific text TokeniserState for its content, returns that; otherwise null.
*/
@Nullable TokeniserState textState() {
if (is(RcData)) return TokeniserState.Rcdata;
if (is(Data)) return TokeniserState.Rawtext;
else return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tag)) return false;
Tag tag = (Tag) o;
return Objects.equals(tagName, tag.tagName) &&
Objects.equals(namespace, tag.namespace) &&
Objects.equals(normalName, tag.normalName) &&
options == tag.options;
}
/**
Hashcode of this Tag, consisting of the tag name and namespace.
*/
@Override
public int hashCode() {
return Objects.hash(tagName, namespace); // options not included so that mutations do not prevent use as a key
}
@Override
public String toString() {
return tagName;
}
@Override
protected Tag clone() {
try {
return (Tag) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
|
Tag
|
java
|
quarkusio__quarkus
|
independent-projects/bootstrap/app-model/src/test/java/io/quarkus/bootstrap/model/MutableXxJvmOptionTest.java
|
{
"start": 139,
"end": 1436
}
|
class ____ {
@Test
public void testHasNoValue() {
assertThat(MutableXxJvmOption.newInstance("AllowUserSignalHandlers").hasValue()).isFalse();
}
@Test
public void testHasValue() {
assertThat(MutableXxJvmOption.newInstance("AllowUserSignalHandlers", "true").hasValue()).isTrue();
}
@Test
public void testCliBooleanOptionWithNoValue() {
assertThat(MutableXxJvmOption.newInstance("AllowUserSignalHandlers").toCliOptions())
.containsExactly("-XX:+AllowUserSignalHandlers");
}
@Test
public void testCliBooleanOptionWithTrueValue() {
assertThat(MutableXxJvmOption.newInstance("AllowUserSignalHandlers", "true").toCliOptions())
.containsExactly("-XX:+AllowUserSignalHandlers");
}
@Test
public void testCliBooleanOptionWithFalseValue() {
assertThat(MutableXxJvmOption.newInstance("AllowUserSignalHandlers", "false").toCliOptions())
.containsExactly("-XX:-AllowUserSignalHandlers");
}
@Test
public void testCliOptionWithSingleStringValue() {
assertThat(MutableXxJvmOption.newInstance("ErrorFile", "./hs_err_pid<pid>.log").toCliOptions())
.containsExactly("-XX:ErrorFile=./hs_err_pid<pid>.log");
}
}
|
MutableXxJvmOptionTest
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java
|
{
"start": 6226,
"end": 6732
}
|
class ____ extends BaseBroadcastResponse {
public Response(StreamInput in) throws IOException {
super(in);
}
public Response(int totalShards, int successfulShards, int failedShards, List<DefaultShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
}
}
// empty per-shard result, but not a singleton so we can check each instance is released on cancellation
public static
|
Response
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/records/GetSubClusterPoliciesConfigurationsRequest.java
|
{
"start": 1233,
"end": 1444
}
|
class ____ {
public static GetSubClusterPoliciesConfigurationsRequest newInstance() {
return Records.newRecord(GetSubClusterPoliciesConfigurationsRequest.class);
}
}
|
GetSubClusterPoliciesConfigurationsRequest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/classification/Name.java
|
{
"start": 386,
"end": 1022
}
|
class ____ implements Comparable<Name> {
private String first;
private String last;
// ...
//end::collections-name-ex[]
private Name() {
// used by Hibernate
}
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
@Override
public int compareTo(Name o) {
return NameComparator.comparator.compare( this, o );
}
//tag::collections-name-ex[]
}
//end::collections-name-ex[]
|
Name
|
java
|
apache__camel
|
components/camel-mllp/src/main/java/org/apache/camel/processor/mllp/Hl7AcknowledgementGenerationException.java
|
{
"start": 998,
"end": 2849
}
|
class ____ extends Exception {
private final byte[] hl7MessageBytes;
private final Hl7Util hl7Util;
public Hl7AcknowledgementGenerationException(Hl7Util hl7Util, String message) {
super(message);
this.hl7Util = hl7Util;
this.hl7MessageBytes = null;
}
public Hl7AcknowledgementGenerationException(Hl7Util hl7Util, String message, byte[] hl7MessageBytes) {
super(message);
this.hl7Util = hl7Util;
this.hl7MessageBytes = hl7MessageBytes;
}
public Hl7AcknowledgementGenerationException(Hl7Util hl7Util, String message, byte[] hl7MessageBytes, Throwable cause) {
super(message, cause);
this.hl7Util = hl7Util;
this.hl7MessageBytes = hl7MessageBytes;
}
public boolean hasHl7MessageBytes() {
return hl7MessageBytes != null && hl7MessageBytes.length > 0;
}
public byte[] getHl7MessageBytes() {
return hl7MessageBytes;
}
/**
* Override the base version of this method, and include the HL7 Message and Acknowledgement, if any
*
* @return the detail message of this MLLP Exception
*/
@Override
public String getMessage() {
if (hasHl7MessageBytes()) {
String parentMessage = super.getMessage();
StringBuilder messageBuilder = new StringBuilder(parentMessage.length() + hl7MessageBytes.length);
messageBuilder.append(parentMessage).append("\n\t{hl7MessageBytes [")
.append(hl7MessageBytes.length)
.append("] = ");
hl7Util.appendBytesAsPrintFriendlyString(messageBuilder, hl7MessageBytes, 0, hl7MessageBytes.length);
messageBuilder.append('}');
return messageBuilder.toString();
}
return super.getMessage();
}
}
|
Hl7AcknowledgementGenerationException
|
java
|
apache__commons-lang
|
src/test/java/org/apache/commons/lang3/function/FailableTest.java
|
{
"start": 86467,
"end": 87000
}
|
interface ____ properly defined to throw any exception using String and IOExceptions as
* generic test types.
*/
@Test
void testThrows_FailableIntBinaryOperator_IOException() {
assertThrows(IOException.class, () -> new FailableIntBinaryOperator<IOException>() {
@Override
public int applyAsInt(final int left, final int right) throws IOException {
throw new IOException("test");
}
}.applyAsInt(0, 0));
}
/**
* Tests that our failable
|
is
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/tm/JtaAfterCompletionTest.java
|
{
"start": 4091,
"end": 4651
}
|
class ____ implements BeforeTransactionCompletionProcess {
@Override
public void doBeforeTransactionCompletion(SharedSessionContractImplementor session) {
try {
// Wait for the transaction to be rolled back by the Reaper thread.
final Transaction transaction = TestingJtaPlatformImpl.transactionManager().getTransaction();
while ( transaction.getStatus() != Status.STATUS_ROLLEDBACK ) {
Thread.sleep( 10 );
}
}
catch (Exception e) {
// we aren't concerned with this.
}
}
}
public static
|
BeforeCallbackCompletionHandler
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/GsonTest.java
|
{
"start": 23762,
"end": 24133
}
|
class ____ {
static final String NO_ARG_CONSTRUCTOR_VALUE = "default instance";
final String s;
@SuppressWarnings("EffectivelyPrivate")
public CustomClass3(String s) {
this.s = s;
}
@SuppressWarnings({"unused", "EffectivelyPrivate"}) // called by Gson
public CustomClass3() {
this(NO_ARG_CONSTRUCTOR_VALUE);
}
}
}
|
CustomClass3
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/JacksonJsonViewTests.java
|
{
"start": 12307,
"end": 12973
}
|
class ____ extends BeanSerializerFactory {
protected DelegatingSerializerFactory(SerializerFactoryConfig config) {
super(config);
}
@Override
public ValueSerializer<Object> createSerializer(SerializationContext ctxt, JavaType origType,
BeanDescription.Supplier beanDescRef, JsonFormat.Value formatOverrides) {
if (origType.getRawClass() == TestBeanSimple.class) {
return new TestBeanSimpleSerializer();
}
else {
return super.createSerializer(ctxt, origType, beanDescRef, formatOverrides);
}
}
@Override
public SerializerFactory withConfig(SerializerFactoryConfig config) {
return this;
}
}
}
|
DelegatingSerializerFactory
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestTextCommand.java
|
{
"start": 1693,
"end": 24038
}
|
class ____ {
private static final File TEST_ROOT_DIR =
GenericTestUtils.getTestDir("testText");
private static final String AVRO_FILENAME =
new File(TEST_ROOT_DIR, "weather.avro").toURI().getPath();
private static final String TEXT_FILENAME =
new File(TEST_ROOT_DIR, "testtextfile.txt").toURI().getPath();
private static final String SEQUENCE_FILENAME =
new File(TEST_ROOT_DIR, "NonWritableSequenceFile").toURI().getPath();
private static final String SEPARATOR = System.getProperty("line.separator");
private static final String AVRO_EXPECTED_OUTPUT =
"{\"station\":\"011990-99999\",\"time\":-619524000000,\"temp\":0}" + SEPARATOR
+ "{\"station\":\"011990-99999\",\"time\":-619506000000,\"temp\":22}" + SEPARATOR
+ "{\"station\":\"011990-99999\",\"time\":-619484400000,\"temp\":-11}" + SEPARATOR
+ "{\"station\":\"012650-99999\",\"time\":-655531200000,\"temp\":111}" + SEPARATOR
+ "{\"station\":\"012650-99999\",\"time\":-655509600000,\"temp\":78}" + SEPARATOR;
private static final String SEQUENCE_FILE_EXPECTED_OUTPUT =
"Key1\tValue1\nKey2\tValue2\n";
/**
* Tests whether binary Avro data files are displayed correctly.
*/
@Test
public void testDisplayForAvroFiles() throws Exception {
String output = readUsingTextCommand(AVRO_FILENAME,
generateWeatherAvroBinaryData());
assertThat(output).describedAs("output").isEqualTo(AVRO_EXPECTED_OUTPUT);
}
@Test
public void testDisplayForAvroFilesSmallMultiByteReads() throws Exception {
Configuration conf = new Configuration();
conf.setInt(IO_FILE_BUFFER_SIZE_KEY, 2);
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
String output = readUsingTextCommand(uri, conf);
assertThat(output).describedAs("output").isEqualTo(AVRO_EXPECTED_OUTPUT);
}
@Test
public void testEmptyAvroFile() throws Exception {
String output = readUsingTextCommand(AVRO_FILENAME,
generateEmptyAvroBinaryData());
assertThat(output).describedAs("output").isEmpty();
}
@Test
public void testAvroFileInputStreamNullBuffer() throws Exception {
assertThrows(NullPointerException.class, () -> {
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
Configuration conf = new Configuration();
try (InputStream is = getInputStream(uri, conf)) {
is.read(null, 0, 10);
}
});
}
@Test
public void testAvroFileInputStreamNegativePosition() throws Exception {
assertThrows(IndexOutOfBoundsException.class, () -> {
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
Configuration conf = new Configuration();
try (InputStream is = getInputStream(uri, conf)) {
is.read(new byte[10], -1, 10);
}
});
}
@Test
public void testAvroFileInputStreamTooLong() throws Exception {
assertThrows(IndexOutOfBoundsException.class, () -> {
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
Configuration conf = new Configuration();
try (InputStream is = getInputStream(uri, conf)) {
is.read(new byte[10], 0, 11);
}
});
}
@Test
public void testAvroFileInputStreamZeroLengthRead() throws Exception {
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
Configuration conf = new Configuration();
try (InputStream is = getInputStream(uri, conf)) {
assertThat(is.read(new byte[10], 0, 0)).describedAs("bytes read").isEqualTo(0);
}
}
@Test
public void testAvroFileInputStreamConsistentEOF() throws Exception {
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
Configuration conf = new Configuration();
try (InputStream is = getInputStream(uri, conf)) {
inputStreamToString(is);
assertThat(is.read()).describedAs("single byte EOF").isEqualTo(-1);
assertThat(is.read(new byte[10], 0, 10)).describedAs("multi byte EOF")
.isEqualTo(-1);
}
}
@Test
public void testAvroFileInputStreamSingleAndMultiByteReads() throws Exception {
createFile(AVRO_FILENAME, generateWeatherAvroBinaryData());
URI uri = new URI(AVRO_FILENAME);
Configuration conf = new Configuration();
try (InputStream is1 = getInputStream(uri, conf);
InputStream is2 = getInputStream(uri, conf)) {
String multiByteReads = inputStreamToString(is1);
String singleByteReads = inputStreamSingleByteReadsToString(is2);
assertThat(multiByteReads)
.describedAs("same bytes read from multi and single byte reads")
.isEqualTo(singleByteReads);
}
}
/**
* Tests that a zero-length file is displayed correctly.
*/
@Test
public void testEmptyTextFile() throws Exception {
byte[] emptyContents = {};
String output = readUsingTextCommand(TEXT_FILENAME, emptyContents);
assertThat(output).describedAs("output").isEmpty();
}
/**
* Tests that a one-byte file is displayed correctly.
*/
@Test
public void testOneByteTextFile() throws Exception {
byte[] oneByteContents = {'x'};
String output = readUsingTextCommand(TEXT_FILENAME, oneByteContents);
String expected = new String(oneByteContents, StandardCharsets.UTF_8);
assertThat(output).describedAs("output").isEqualTo(expected);
}
/**
* Tests that a two-byte file is displayed correctly.
*/
@Test
public void testTwoByteTextFile() throws Exception {
byte[] twoByteContents = {'x', 'y'};
String output = readUsingTextCommand(TEXT_FILENAME, twoByteContents);
String expected = new String(twoByteContents, StandardCharsets.UTF_8);
assertThat(output).describedAs("output").isEqualTo(expected);
}
@Test
public void testDisplayForNonWritableSequenceFile() throws Exception {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
String output = readUsingTextCommand(uri, conf);
assertThat(output).describedAs("output").isEqualTo(SEQUENCE_FILE_EXPECTED_OUTPUT);
}
@Test
public void testDisplayForSequenceFileSmallMultiByteReads() throws Exception {
Configuration conf = new Configuration();
conf.setInt(IO_FILE_BUFFER_SIZE_KEY, 2);
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
String output = readUsingTextCommand(uri, conf);
assertThat(output).describedAs("output").isEqualTo(SEQUENCE_FILE_EXPECTED_OUTPUT);
}
@Test
public void testEmptySequenceFile() throws Exception {
Configuration conf = new Configuration();
createEmptySequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
String output = readUsingTextCommand(uri, conf);
assertThat(output).describedAs("output").isEmpty();
}
@Test
public void testSequenceFileInputStreamNullBuffer() throws Exception {
assertThrows(NullPointerException.class, () -> {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
try (InputStream is = getInputStream(uri, conf)) {
is.read(null, 0, 10);
}
});
}
@Test
public void testSequenceFileInputStreamNegativePosition() throws Exception {
assertThrows(IndexOutOfBoundsException.class, () -> {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
try (InputStream is = getInputStream(uri, conf)) {
is.read(new byte[10], -1, 10);
}
});
}
@Test
public void testSequenceFileInputStreamTooLong() throws Exception {
assertThrows(IndexOutOfBoundsException.class, () -> {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
try (InputStream is = getInputStream(uri, conf)) {
is.read(new byte[10], 0, 11);
}
});
}
@Test
public void testSequenceFileInputStreamZeroLengthRead() throws Exception {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
try (InputStream is = getInputStream(uri, conf)) {
assertThat(is.read(new byte[10], 0, 0)).describedAs("bytes read").isEqualTo(0);
}
}
@Test
public void testSequenceFileInputStreamConsistentEOF() throws Exception {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
try (InputStream is = getInputStream(uri, conf)) {
inputStreamToString(is);
assertThat(is.read()).describedAs("single byte EOF").isEqualTo(-1);
assertThat(is.read(new byte[10], 0, 10)).describedAs("multi byte EOF")
.isEqualTo(-1);
}
}
@Test
public void testSequenceFileInputStreamSingleAndMultiByteReads() throws Exception {
Configuration conf = new Configuration();
createNonWritableSequenceFile(SEQUENCE_FILENAME, conf);
URI uri = new URI(SEQUENCE_FILENAME);
try (InputStream is1 = getInputStream(uri, conf);
InputStream is2 = getInputStream(uri, conf)) {
String multiByteReads = inputStreamToString(is1);
String singleByteReads = inputStreamSingleByteReadsToString(is2);
assertThat(multiByteReads)
.describedAs("same bytes read from multi and single byte reads")
.isEqualTo(singleByteReads);
}
}
// Create a file on the local file system and read it using
// the Display.Text class.
private static String readUsingTextCommand(String fileName, byte[] fileContents)
throws Exception {
createFile(fileName, fileContents);
Configuration conf = new Configuration();
URI localPath = new URI(fileName);
return readUsingTextCommand(localPath, conf);
}
// Read a file using Display.Text class.
private static String readUsingTextCommand(URI uri, Configuration conf)
throws Exception {
InputStream stream = getInputStream(uri, conf);
return inputStreamToString(stream);
}
private static String inputStreamToString(InputStream stream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer, StandardCharsets.UTF_8);
return writer.toString();
}
private static String inputStreamSingleByteReadsToString(InputStream stream) throws IOException {
StringWriter writer = new StringWriter();
for (int b = stream.read(); b != -1; b = stream.read()) {
writer.write(b);
}
return writer.toString();
}
private static void createFile(String fileName, byte[] contents) throws IOException {
Files.createDirectories(TEST_ROOT_DIR.toPath());
File file = new File(fileName);
file.createNewFile();
FileOutputStream stream = new FileOutputStream(file);
stream.write(contents);
stream.close();
}
private static byte[] generateWeatherAvroBinaryData() {
// The contents of a simple binary Avro file with weather records.
byte[] contents = {
(byte) 0x4f, (byte) 0x62, (byte) 0x6a, (byte) 0x1,
(byte) 0x4, (byte) 0x14, (byte) 0x61, (byte) 0x76,
(byte) 0x72, (byte) 0x6f, (byte) 0x2e, (byte) 0x63,
(byte) 0x6f, (byte) 0x64, (byte) 0x65, (byte) 0x63,
(byte) 0x8, (byte) 0x6e, (byte) 0x75, (byte) 0x6c,
(byte) 0x6c, (byte) 0x16, (byte) 0x61, (byte) 0x76,
(byte) 0x72, (byte) 0x6f, (byte) 0x2e, (byte) 0x73,
(byte) 0x63, (byte) 0x68, (byte) 0x65, (byte) 0x6d,
(byte) 0x61, (byte) 0xf2, (byte) 0x2, (byte) 0x7b,
(byte) 0x22, (byte) 0x74, (byte) 0x79, (byte) 0x70,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x72, (byte) 0x65, (byte) 0x63, (byte) 0x6f,
(byte) 0x72, (byte) 0x64, (byte) 0x22, (byte) 0x2c,
(byte) 0x22, (byte) 0x6e, (byte) 0x61, (byte) 0x6d,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x57, (byte) 0x65, (byte) 0x61, (byte) 0x74,
(byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x22,
(byte) 0x2c, (byte) 0x22, (byte) 0x6e, (byte) 0x61,
(byte) 0x6d, (byte) 0x65, (byte) 0x73, (byte) 0x70,
(byte) 0x61, (byte) 0x63, (byte) 0x65, (byte) 0x22,
(byte) 0x3a, (byte) 0x22, (byte) 0x74, (byte) 0x65,
(byte) 0x73, (byte) 0x74, (byte) 0x22, (byte) 0x2c,
(byte) 0x22, (byte) 0x66, (byte) 0x69, (byte) 0x65,
(byte) 0x6c, (byte) 0x64, (byte) 0x73, (byte) 0x22,
(byte) 0x3a, (byte) 0x5b, (byte) 0x7b, (byte) 0x22,
(byte) 0x6e, (byte) 0x61, (byte) 0x6d, (byte) 0x65,
(byte) 0x22, (byte) 0x3a, (byte) 0x22, (byte) 0x73,
(byte) 0x74, (byte) 0x61, (byte) 0x74, (byte) 0x69,
(byte) 0x6f, (byte) 0x6e, (byte) 0x22, (byte) 0x2c,
(byte) 0x22, (byte) 0x74, (byte) 0x79, (byte) 0x70,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x73, (byte) 0x74, (byte) 0x72, (byte) 0x69,
(byte) 0x6e, (byte) 0x67, (byte) 0x22, (byte) 0x7d,
(byte) 0x2c, (byte) 0x7b, (byte) 0x22, (byte) 0x6e,
(byte) 0x61, (byte) 0x6d, (byte) 0x65, (byte) 0x22,
(byte) 0x3a, (byte) 0x22, (byte) 0x74, (byte) 0x69,
(byte) 0x6d, (byte) 0x65, (byte) 0x22, (byte) 0x2c,
(byte) 0x22, (byte) 0x74, (byte) 0x79, (byte) 0x70,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x6c, (byte) 0x6f, (byte) 0x6e, (byte) 0x67,
(byte) 0x22, (byte) 0x7d, (byte) 0x2c, (byte) 0x7b,
(byte) 0x22, (byte) 0x6e, (byte) 0x61, (byte) 0x6d,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x74, (byte) 0x65, (byte) 0x6d, (byte) 0x70,
(byte) 0x22, (byte) 0x2c, (byte) 0x22, (byte) 0x74,
(byte) 0x79, (byte) 0x70, (byte) 0x65, (byte) 0x22,
(byte) 0x3a, (byte) 0x22, (byte) 0x69, (byte) 0x6e,
(byte) 0x74, (byte) 0x22, (byte) 0x7d, (byte) 0x5d,
(byte) 0x2c, (byte) 0x22, (byte) 0x64, (byte) 0x6f,
(byte) 0x63, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x41, (byte) 0x20, (byte) 0x77, (byte) 0x65,
(byte) 0x61, (byte) 0x74, (byte) 0x68, (byte) 0x65,
(byte) 0x72, (byte) 0x20, (byte) 0x72, (byte) 0x65,
(byte) 0x61, (byte) 0x64, (byte) 0x69, (byte) 0x6e,
(byte) 0x67, (byte) 0x2e, (byte) 0x22, (byte) 0x7d,
(byte) 0x0, (byte) 0xb0, (byte) 0x81, (byte) 0xb3,
(byte) 0xc4, (byte) 0xa, (byte) 0xc, (byte) 0xf6,
(byte) 0x62, (byte) 0xfa, (byte) 0xc9, (byte) 0x38,
(byte) 0xfd, (byte) 0x7e, (byte) 0x52, (byte) 0x0,
(byte) 0xa7, (byte) 0xa, (byte) 0xcc, (byte) 0x1,
(byte) 0x18, (byte) 0x30, (byte) 0x31, (byte) 0x31,
(byte) 0x39, (byte) 0x39, (byte) 0x30, (byte) 0x2d,
(byte) 0x39, (byte) 0x39, (byte) 0x39, (byte) 0x39,
(byte) 0x39, (byte) 0xff, (byte) 0xa3, (byte) 0x90,
(byte) 0xe8, (byte) 0x87, (byte) 0x24, (byte) 0x0,
(byte) 0x18, (byte) 0x30, (byte) 0x31, (byte) 0x31,
(byte) 0x39, (byte) 0x39, (byte) 0x30, (byte) 0x2d,
(byte) 0x39, (byte) 0x39, (byte) 0x39, (byte) 0x39,
(byte) 0x39, (byte) 0xff, (byte) 0x81, (byte) 0xfb,
(byte) 0xd6, (byte) 0x87, (byte) 0x24, (byte) 0x2c,
(byte) 0x18, (byte) 0x30, (byte) 0x31, (byte) 0x31,
(byte) 0x39, (byte) 0x39, (byte) 0x30, (byte) 0x2d,
(byte) 0x39, (byte) 0x39, (byte) 0x39, (byte) 0x39,
(byte) 0x39, (byte) 0xff, (byte) 0xa5, (byte) 0xae,
(byte) 0xc2, (byte) 0x87, (byte) 0x24, (byte) 0x15,
(byte) 0x18, (byte) 0x30, (byte) 0x31, (byte) 0x32,
(byte) 0x36, (byte) 0x35, (byte) 0x30, (byte) 0x2d,
(byte) 0x39, (byte) 0x39, (byte) 0x39, (byte) 0x39,
(byte) 0x39, (byte) 0xff, (byte) 0xb7, (byte) 0xa2,
(byte) 0x8b, (byte) 0x94, (byte) 0x26, (byte) 0xde,
(byte) 0x1, (byte) 0x18, (byte) 0x30, (byte) 0x31,
(byte) 0x32, (byte) 0x36, (byte) 0x35, (byte) 0x30,
(byte) 0x2d, (byte) 0x39, (byte) 0x39, (byte) 0x39,
(byte) 0x39, (byte) 0x39, (byte) 0xff, (byte) 0xdb,
(byte) 0xd5, (byte) 0xf6, (byte) 0x93, (byte) 0x26,
(byte) 0x9c, (byte) 0x1, (byte) 0xb0, (byte) 0x81,
(byte) 0xb3, (byte) 0xc4, (byte) 0xa, (byte) 0xc,
(byte) 0xf6, (byte) 0x62, (byte) 0xfa, (byte) 0xc9,
(byte) 0x38, (byte) 0xfd, (byte) 0x7e, (byte) 0x52,
(byte) 0x0, (byte) 0xa7,
};
return contents;
}
private static byte[] generateEmptyAvroBinaryData() {
// The binary contents of an empty Avro file (no records).
byte[] contents = new byte[] {
(byte) 0x4f, (byte) 0x62, (byte) 0x6a, (byte) 0x01,
(byte) 0x04, (byte) 0x16, (byte) 0x61, (byte) 0x76,
(byte) 0x72, (byte) 0x6f, (byte) 0x2e, (byte) 0x73,
(byte) 0x63, (byte) 0x68, (byte) 0x65, (byte) 0x6d,
(byte) 0x61, (byte) 0x92, (byte) 0x03, (byte) 0x7b,
(byte) 0x22, (byte) 0x74, (byte) 0x79, (byte) 0x70,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x72, (byte) 0x65, (byte) 0x63, (byte) 0x6f,
(byte) 0x72, (byte) 0x64, (byte) 0x22, (byte) 0x2c,
(byte) 0x22, (byte) 0x6e, (byte) 0x61, (byte) 0x6d,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x55, (byte) 0x73, (byte) 0x65, (byte) 0x72,
(byte) 0x22, (byte) 0x2c, (byte) 0x22, (byte) 0x6e,
(byte) 0x61, (byte) 0x6d, (byte) 0x65, (byte) 0x73,
(byte) 0x70, (byte) 0x61, (byte) 0x63, (byte) 0x65,
(byte) 0x22, (byte) 0x3a, (byte) 0x22, (byte) 0x65,
(byte) 0x78, (byte) 0x61, (byte) 0x6d, (byte) 0x70,
(byte) 0x6c, (byte) 0x65, (byte) 0x2e, (byte) 0x61,
(byte) 0x76, (byte) 0x72, (byte) 0x6f, (byte) 0x22,
(byte) 0x2c, (byte) 0x22, (byte) 0x66, (byte) 0x69,
(byte) 0x65, (byte) 0x6c, (byte) 0x64, (byte) 0x73,
(byte) 0x22, (byte) 0x3a, (byte) 0x5b, (byte) 0x7b,
(byte) 0x22, (byte) 0x6e, (byte) 0x61, (byte) 0x6d,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x6e, (byte) 0x61, (byte) 0x6d, (byte) 0x65,
(byte) 0x22, (byte) 0x2c, (byte) 0x22, (byte) 0x74,
(byte) 0x79, (byte) 0x70, (byte) 0x65, (byte) 0x22,
(byte) 0x3a, (byte) 0x22, (byte) 0x73, (byte) 0x74,
(byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x67,
(byte) 0x22, (byte) 0x7d, (byte) 0x2c, (byte) 0x7b,
(byte) 0x22, (byte) 0x6e, (byte) 0x61, (byte) 0x6d,
(byte) 0x65, (byte) 0x22, (byte) 0x3a, (byte) 0x22,
(byte) 0x66, (byte) 0x61, (byte) 0x76, (byte) 0x6f,
(byte) 0x72, (byte) 0x69, (byte) 0x74, (byte) 0x65,
(byte) 0x5f, (byte) 0x6e, (byte) 0x75, (byte) 0x6d,
(byte) 0x62, (byte) 0x65, (byte) 0x72, (byte) 0x22,
(byte) 0x2c, (byte) 0x22, (byte) 0x74, (byte) 0x79,
(byte) 0x70, (byte) 0x65, (byte) 0x22, (byte) 0x3a,
(byte) 0x5b, (byte) 0x22, (byte) 0x69, (byte) 0x6e,
(byte) 0x74, (byte) 0x22, (byte) 0x2c, (byte) 0x22,
(byte) 0x6e, (byte) 0x75, (byte) 0x6c, (byte) 0x6c,
(byte) 0x22, (byte) 0x5d, (byte) 0x7d, (byte) 0x2c,
(byte) 0x7b, (byte) 0x22, (byte) 0x6e, (byte) 0x61,
(byte) 0x6d, (byte) 0x65, (byte) 0x22, (byte) 0x3a,
(byte) 0x22, (byte) 0x66, (byte) 0x61, (byte) 0x76,
(byte) 0x6f, (byte) 0x72, (byte) 0x69, (byte) 0x74,
(byte) 0x65, (byte) 0x5f, (byte) 0x63, (byte) 0x6f,
(byte) 0x6c, (byte) 0x6f, (byte) 0x72, (byte) 0x22,
(byte) 0x2c, (byte) 0x22, (byte) 0x74, (byte) 0x79,
(byte) 0x70, (byte) 0x65, (byte) 0x22, (byte) 0x3a,
(byte) 0x5b, (byte) 0x22, (byte) 0x73, (byte) 0x74,
(byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x67,
(byte) 0x22, (byte) 0x2c, (byte) 0x22, (byte) 0x6e,
(byte) 0x75, (byte) 0x6c, (byte) 0x6c, (byte) 0x22,
(byte) 0x5d, (byte) 0x7d, (byte) 0x5d, (byte) 0x7d,
(byte) 0x14, (byte) 0x61, (byte) 0x76, (byte) 0x72,
(byte) 0x6f, (byte) 0x2e, (byte) 0x63, (byte) 0x6f,
(byte) 0x64, (byte) 0x65, (byte) 0x63, (byte) 0x0e,
(byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x6c,
(byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x00,
(byte) 0xed, (byte) 0xe0, (byte) 0xfa, (byte) 0x87,
(byte) 0x3c, (byte) 0x86, (byte) 0xf5, (byte) 0x5f,
(byte) 0x7d, (byte) 0x8d, (byte) 0x2f, (byte) 0xdb,
(byte) 0xc7, (byte) 0xe3, (byte) 0x11, (byte) 0x39,
};
return contents;
}
private static void createEmptySequenceFile(String fileName, Configuration conf)
throws IOException {
conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization");
Path path = new Path(fileName);
SequenceFile.Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(path),
SequenceFile.Writer.keyClass(String.class), SequenceFile.Writer.valueClass(String.class));
writer.close();
}
private static void createNonWritableSequenceFile(String fileName, Configuration conf)
throws IOException {
conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization");
Path path = new Path(fileName);
try (SequenceFile.Writer writer = SequenceFile.createWriter(conf,
SequenceFile.Writer.file(path), SequenceFile.Writer.keyClass(String.class),
SequenceFile.Writer.valueClass(String.class))) {
writer.append("Key1", "Value1");
writer.append("Key2", "Value2");
}
}
private static InputStream getInputStream(URI uri, Configuration conf) throws IOException {
// Prepare and call the Text command's protected getInputStream method.
PathData pathData = new PathData(uri, conf);
Display.Text text = new Display.Text() {
@Override
public InputStream getInputStream(PathData item) throws IOException {
return super.getInputStream(item);
}
};
text.setConf(conf);
return text.getInputStream(pathData);
}
}
|
TestTextCommand
|
java
|
spring-projects__spring-framework
|
spring-core-test/src/main/java/org/springframework/core/test/tools/ClassFiles.java
|
{
"start": 1008,
"end": 3245
}
|
class ____ implements Iterable<ClassFile> {
private static final ClassFiles NONE = new ClassFiles(Collections.emptyMap());
private final Map<String, ClassFile> files;
private ClassFiles(Map<String, ClassFile> files) {
this.files = files;
}
/**
* Return a {@link ClassFiles} instance with no items.
* @return the empty instance
*/
public static ClassFiles none() {
return NONE;
}
/**
* Factory method that can be used to create a {@link ClassFiles}
* instance containing the specified classes.
* @param ClassFiles the classes to include
* @return a {@link ClassFiles} instance
*/
public static ClassFiles of(ClassFile... ClassFiles) {
return none().and(ClassFiles);
}
/**
* Return a new {@link ClassFiles} instance that merges classes from
* another array of {@link ClassFile} instances.
* @param classFiles the instances to merge
* @return a new {@link ClassFiles} instance containing merged content
*/
public ClassFiles and(ClassFile... classFiles) {
Map<String, ClassFile> merged = new LinkedHashMap<>(this.files);
Arrays.stream(classFiles).forEach(file -> merged.put(file.getName(), file));
return new ClassFiles(Collections.unmodifiableMap(merged));
}
/**
* Return a new {@link ClassFiles} instance that merges classes from another
* iterable of {@link ClassFiles} instances.
* @param classFiles the instances to merge
* @return a new {@link ClassFiles} instance containing merged content
*/
public ClassFiles and(Iterable<ClassFile> classFiles) {
Map<String, ClassFile> merged = new LinkedHashMap<>(this.files);
classFiles.forEach(file -> merged.put(file.getName(), file));
return new ClassFiles(Collections.unmodifiableMap(merged));
}
@Override
public Iterator<ClassFile> iterator() {
return this.files.values().iterator();
}
/**
* Stream the {@link ClassFile} instances contained in this collection.
* @return a stream of classes
*/
public Stream<ClassFile> stream() {
return this.files.values().stream();
}
/**
* Returns {@code true} if this collection is empty.
* @return if this collection is empty
*/
public boolean isEmpty() {
return this.files.isEmpty();
}
/**
* Get the {@link ClassFile} with the given
|
ClassFiles
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvtVO/DataTransaction.java
|
{
"start": 821,
"end": 1105
}
|
class ____ {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
/**
* 处理结果
*/
public static
|
User
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/usertype/internal/OffsetDateTimeCompositeUserType.java
|
{
"start": 441,
"end": 1299
}
|
class ____ extends AbstractTimeZoneStorageCompositeUserType<OffsetDateTime> {
@Override
public Object getPropertyValue(OffsetDateTime component, int property) throws HibernateException {
return switch ( property ) {
case 0 -> component.toInstant();
case 1 -> component.getOffset();
default -> null;
};
}
@Override
public OffsetDateTime instantiate(ValueAccess values) {
final Instant instant = values.getValue( 0, Instant.class );
final ZoneOffset zoneOffset = values.getValue( 1, ZoneOffset.class );
return instant == null || zoneOffset == null ? null : OffsetDateTime.ofInstant( instant, zoneOffset );
}
@Override
public Class<?> embeddable() {
return OffsetDateTimeEmbeddable.class;
}
@Override
public Class<OffsetDateTime> returnedClass() {
return OffsetDateTime.class;
}
public static
|
OffsetDateTimeCompositeUserType
|
java
|
elastic__elasticsearch
|
libs/tdigest/src/main/java/org/elasticsearch/tdigest/AbstractTDigest.java
|
{
"start": 987,
"end": 2657
}
|
class ____ extends TDigest {
/**
* Same as {@link #weightedAverageSorted(double, double, double, double)} but flips
* the order of the variables if <code>x2</code> is greater than
* <code>x1</code>.
*/
static double weightedAverage(double x1, double w1, double x2, double w2) {
if (x1 <= x2) {
return weightedAverageSorted(x1, w1, x2, w2);
} else {
return weightedAverageSorted(x2, w2, x1, w1);
}
}
/**
* Compute the weighted average between <code>x1</code> with a weight of
* <code>w1</code> and <code>x2</code> with a weight of <code>w2</code>.
* This expects <code>x1</code> to be less than or equal to <code>x2</code>
* and is guaranteed to return a number in <code>[x1, x2]</code>. An
* explicit check is required since this isn't guaranteed with floating-point
* numbers.
*/
private static double weightedAverageSorted(double x1, double w1, double x2, double w2) {
assert x1 <= x2;
final double x = (x1 * w1 + x2 * w2) / (w1 + w2);
return Math.max(x1, Math.min(x, x2));
}
/**
* Interpolate from a given value given a low and a high reference values
* @param x value to interpolate from
* @param x0 low reference value
* @param x1 high reference value
* @return interpolated value
*/
static double interpolate(double x, double x0, double x1) {
return (x - x0) / (x1 - x0);
}
@Override
public void add(TDigest other) {
for (Centroid centroid : other.centroids()) {
add(centroid.mean(), centroid.count());
}
}
}
|
AbstractTDigest
|
java
|
quarkusio__quarkus
|
independent-projects/qute/core/src/main/java/io/quarkus/qute/ValueAccessor.java
|
{
"start": 136,
"end": 292
}
|
interface ____ {
/**
*
* @param instance
* @return the value
*/
CompletionStage<Object> getValue(Object instance);
}
|
ValueAccessor
|
java
|
quarkusio__quarkus
|
integration-tests/devtools/src/test/java/io/quarkus/devtools/codestarts/quarkus/HibernateOrmPanacheKotlinCodestartIT.java
|
{
"start": 351,
"end": 1099
}
|
class ____ {
@RegisterExtension
public static QuarkusCodestartTest codestartTest = QuarkusCodestartTest.builder()
.codestarts("hibernate-orm")
.extension(new ArtifactKey("io.quarkus", "quarkus-jdbc-h2"))
.extension(new ArtifactKey("io.quarkus", "quarkus-hibernate-orm-panache-kotlin"))
.languages(KOTLIN)
.build();
@Test
void testContent() throws Throwable {
codestartTest.checkGeneratedSource("org.acme.MyKotlinEntity");
codestartTest.assertThatGeneratedFileMatchSnapshot(KOTLIN, "src/main/resources/import.sql");
}
@Test
void testBuild() throws Throwable {
codestartTest.buildAllProjects();
}
}
|
HibernateOrmPanacheKotlinCodestartIT
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/proxy/TrustedXForwarderProxiesUnknownHostnameFailureTest.java
|
{
"start": 180,
"end": 598
}
|
class ____ extends AbstractTrustedXForwarderProxiesTest {
@RegisterExtension
static final QuarkusUnitTest config = createTrustedProxyUnitTest(
// let's hope this domain is not registered
"alnoenlkepdolndqoe334219384nvfeoslcxnxeoanelnsoe9.gov");
@Test
public void testHeadersAreIgnored() {
assertRequestFailure();
}
}
|
TrustedXForwarderProxiesUnknownHostnameFailureTest
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-csrf/runtime/src/main/java/io/quarkus/csrf/reactive/runtime/CsrfTokenParameterProvider.java
|
{
"start": 350,
"end": 1885
}
|
class ____ {
/**
* CSRF token key.
*/
private static final String CSRF_TOKEN_KEY = "csrf_token";
@Inject
RoutingContext context;
private final String csrfFormFieldName;
private final String csrfCookieName;
private final String csrfHeaderName;
public CsrfTokenParameterProvider(RestCsrfConfigHolder configHolder) {
RestCsrfConfig config = configHolder.getConfig();
this.csrfFormFieldName = config.formFieldName();
this.csrfCookieName = config.cookieName();
this.csrfHeaderName = config.tokenHeaderName();
}
/**
* Gets the CSRF token value.
*
* @throws IllegalStateException if the {@link RoutingContext} does not contain a CSRF token value.
*/
public String getToken() {
String token = (String) context.get(CSRF_TOKEN_KEY);
if (token == null) {
throw new IllegalStateException(
"CSRFFilter should have set the attribute " + csrfFormFieldName + ", but it is null");
}
return token;
}
/**
* Gets the name of the form parameter that is to contain the value returned by {@link #getToken()}.
*/
public String getParameterName() {
return csrfFormFieldName;
}
/**
* Gets the CSRF cookie name.
*/
public String getCookieName() {
return csrfCookieName;
}
/**
* Gets the CSRF header name.
*/
public String getHeaderName() {
return csrfHeaderName;
}
}
|
CsrfTokenParameterProvider
|
java
|
micronaut-projects__micronaut-core
|
http-client/src/main/java/io/micronaut/http/client/netty/Pool40.java
|
{
"start": 20659,
"end": 22059
}
|
class ____ extends PoolEntry implements Http2PoolEntry {
private final AtomicInteger earmarkedOrLiveRequests = new AtomicInteger(0);
private int maxStreamCount;
public Http2(EventLoop eventLoop, @NonNull ResizerConnection connection) {
super(eventLoop, connection);
}
@Override
boolean tryEarmarkForRequest() {
IntUnaryOperator upd = old -> {
if (old >= Math.min(connectionPoolConfiguration.getMaxConcurrentRequestsPerHttp2Connection(), maxStreamCount)) {
return old;
} else {
return old + 1;
}
};
int old = earmarkedOrLiveRequests.updateAndGet(upd);
return upd.applyAsInt(old) != old;
}
@Override
public void onConnectionEstablished(int maxStreamCount) {
this.maxStreamCount = maxStreamCount;
onNewConnectionEstablished2(this);
}
@Override
public void onConnectionInactive() {
onConnectionInactive2(this);
}
@Override
public void markAvailable() {
earmarkedOrLiveRequests.decrementAndGet();
markConnectionAvailable();
}
@Override
public void markUnavailable() {
earmarkedOrLiveRequests.set(Integer.MAX_VALUE);
}
}
}
|
Http2
|
java
|
apache__flink
|
flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/AvroFileFormatFactory.java
|
{
"start": 2900,
"end": 4662
}
|
class ____ implements BulkReaderFormatFactory, BulkWriterFormatFactory {
public static final String IDENTIFIER = "avro";
@Override
public BulkDecodingFormat<RowData> createDecodingFormat(
DynamicTableFactory.Context context, ReadableConfig formatOptions) {
return new AvroBulkDecodingFormat();
}
@Override
public EncodingFormat<BulkWriter.Factory<RowData>> createEncodingFormat(
DynamicTableFactory.Context context, ReadableConfig formatOptions) {
return new EncodingFormat<BulkWriter.Factory<RowData>>() {
@Override
public ChangelogMode getChangelogMode() {
return ChangelogMode.insertOnly();
}
@Override
public BulkWriter.Factory<RowData> createRuntimeEncoder(
DynamicTableSink.Context context, DataType consumedDataType) {
return new RowDataAvroWriterFactory(
(RowType) consumedDataType.getLogicalType(),
formatOptions.get(AVRO_OUTPUT_CODEC),
formatOptions.get(AVRO_TIMESTAMP_LEGACY_MAPPING));
}
};
}
@Override
public String factoryIdentifier() {
return IDENTIFIER;
}
@Override
public Set<ConfigOption<?>> requiredOptions() {
return new HashSet<>();
}
@Override
public Set<ConfigOption<?>> optionalOptions() {
Set<ConfigOption<?>> options = new HashSet<>();
options.add(AVRO_OUTPUT_CODEC);
options.add(AVRO_TIMESTAMP_LEGACY_MAPPING);
return options;
}
@Override
public Set<ConfigOption<?>> forwardOptions() {
return optionalOptions();
}
private static
|
AvroFileFormatFactory
|
java
|
apache__camel
|
components/camel-arangodb/src/test/java/org/apache/camel/component/arangodb/integration/ArangoGraphQueriesIT.java
|
{
"start": 1959,
"end": 4788
}
|
class ____ extends BaseGraph {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:query")
.to("arangodb:{{arangodb.testDb}}?operation=AQL_QUERY");
}
};
}
@Test
public void testTravesalOutbound() {
// depth = 3
Exchange result = getResultOutboundQuery(3, vertexA.getId(), " OUTBOUND ");
assertTrue(result.getMessage().getBody() instanceof Collection);
Collection<String> list = (Collection<String>) result.getMessage().getBody();
assertThat(list, hasItems("B", "C", "D", "E", "F", "G", "H", "I", "J"));
// depth = 2
result = getResultOutboundQuery(2, vertexA.getId(), " OUTBOUND ");
assertTrue(result.getMessage().getBody() instanceof Collection);
list = (Collection<String>) result.getMessage().getBody();
assertThat(list, hasItems("B", "C", "D", "E", "F", "G"));
}
private Exchange getResultOutboundQuery(int depth, String vertexId, String outInBound) {
String query = "FOR v IN 1.." + depth + outInBound + " '" + vertexId + "' GRAPH '" + GRAPH_NAME + "' RETURN v._key";
return getResult(query);
}
private Exchange getResult(String query) {
Exchange result = template.request("direct:query", exchange -> {
exchange.getMessage().setHeader(AQL_QUERY, query);
exchange.getMessage().setHeader(RESULT_CLASS_TYPE, String.class);
});
return result;
}
@Test
public void testTravesalInbound() {
// depth = 3
Exchange result = getResultOutboundQuery(3, vertexH.getId(), " INBOUND ");
assertTrue(result.getMessage().getBody() instanceof Collection);
Collection<String> list = (Collection<String>) result.getMessage().getBody();
assertEquals(3, list.size());
assertThat(list, hasItems("A", "B", "D"));
// depth = 2
result = getResultOutboundQuery(2, vertexH.getId(), " INBOUND ");
assertTrue(result.getMessage().getBody() instanceof Collection);
list = (Collection<String>) result.getMessage().getBody();
assertEquals(2, list.size());
assertThat(list, hasItems("B", "D"));
}
@Test
public void queryShortestPathFromAToH() throws ArangoDBException {
String query = "FOR v, e IN OUTBOUND SHORTEST_PATH '" + vertexA.getId() + "' TO '" + vertexH.getId() + "' GRAPH '"
+ GRAPH_NAME + "' RETURN v._key";
Exchange result = getResult(query);
Collection<String> list = (Collection<String>) result.getMessage().getBody();
assertEquals(4, list.size());
assertThat(list, hasItems("A", "B", "D", "H"));
}
}
|
ArangoGraphQueriesIT
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/compositefk/OneToOneEmbeddedIdWithGenericAttributeTest.java
|
{
"start": 3734,
"end": 4075
}
|
class ____<T> {
@EmbeddedId
private DomainEntityId<T> id;
public DomainEntityModel() {
}
protected DomainEntityModel(DomainEntityId<T> id) {
this.id = id;
}
public DomainEntityId<T> getId() {
return id;
}
public void setId(DomainEntityId<T> id) {
this.id = id;
}
}
@Embeddable
public static
|
DomainEntityModel
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/onetomany/OneToManyNotAuditedNullEntity.java
|
{
"start": 780,
"end": 2392
}
|
class ____ implements Serializable {
@Id
private Integer id;
private String data;
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(joinColumns = @JoinColumn(name = "O2MNotAudited_id"))
private List<UnversionedStrTestEntity> references = new ArrayList<UnversionedStrTestEntity>();
protected OneToManyNotAuditedNullEntity() {
}
public OneToManyNotAuditedNullEntity(Integer id, String data) {
this.id = id;
this.data = data;
}
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof OneToManyNotAuditedNullEntity ) ) return false;
OneToManyNotAuditedNullEntity that = (OneToManyNotAuditedNullEntity) o;
if ( data != null ? !data.equals( that.getData() ) : that.getData() != null ) return false;
if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) return false;
return true;
}
public int hashCode() {
int result = ( id != null ? id.hashCode() : 0 );
result = 31 * result + ( data != null ? data.hashCode() : 0 );
return result;
}
public String toString() {
return "OneToManyNotAuditedNullEntity(id = " + id + ", data = " + data + ")";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public List<UnversionedStrTestEntity> getReferences() {
return references;
}
public void setReferences(List<UnversionedStrTestEntity> references) {
this.references = references;
}
}
|
OneToManyNotAuditedNullEntity
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java
|
{
"start": 206,
"end": 889
}
|
class ____ implements MockitoLogger {
private StringBuilder loggedInfo = new StringBuilder();
public void log(Object what) {
loggedInfo.append(what);
}
public String getLoggedInfo() {
return loggedInfo.toString();
}
public boolean isEmpty() {
return loggedInfo.length() == 0;
}
public SimpleMockitoLogger clear() {
loggedInfo = new StringBuilder();
return this;
}
public void assertEmpty() {
if (loggedInfo.length() != 0) {
throw new AssertionError(
"Expected the logger to be empty but it has:\n" + loggedInfo.toString());
}
}
}
|
SimpleMockitoLogger
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/asm/Opcodes.java
|
{
"start": 6455,
"end": 7700
}
|
class ____ extends StuffVisitor {
* @Override public void visitOldStuff(int arg, ...) {
* super.visitOldStuff(int arg, ...); // optional
* [ do user stuff ]
* }
* }
* </pre>
*
* <p>and there are two cases:
*
* <ul>
* <li>call visitOldStuff: in the call to super.visitOldStuff, the source is set to
* SOURCE_DEPRECATED and visitNewStuff is called. Here 'do stuff' is run because the source
* was previously set to SOURCE_DEPRECATED, and execution eventually returns to
* UserStuffVisitor.visitOldStuff, where 'do user stuff' is run.
* <li>call visitNewStuff: the call is redirected to UserStuffVisitor.visitOldStuff because the
* source is 0. Execution continues as in the previous case, resulting in 'do stuff' and 'do
* user stuff' being executed, in this order.
* </ul>
*
* <h1>ASM subclasses</h1>
*
* <p>In ASM packages, subclasses of StuffVisitor can typically be sub classed again by the user,
* and can be used with API_OLD or API_NEW. Because of this, if such a subclass must override
* visitNewStuff, it must do so in the following way (and must not override visitOldStuff):
*
* <pre>
* public
|
UserStuffVisitor
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/rules/LogicalOptimizerContextTests.java
|
{
"start": 1010,
"end": 3287
}
|
class ____ extends ESTestCase {
public void testToString() {
// Random looking numbers for FoldContext are indeed random. Just so we have consistent numbers to assert on in toString.
// Same for the transport version.
LogicalOptimizerContext ctx = new LogicalOptimizerContext(
EsqlTestUtils.TEST_CFG,
new FoldContext(102),
FieldAttribute.ESQL_FIELD_ATTRIBUTE_DROP_TYPE
);
ctx.foldCtx().trackAllocation(Source.EMPTY, 99);
assertThat(
ctx.toString(),
equalTo(
"LogicalOptimizerContext[configuration=" + EsqlTestUtils.TEST_CFG + ", foldCtx=FoldContext[3/102], minimumVersion=9075000]"
)
);
}
public void testEqualsAndHashCode() {
EqualsHashCodeTestUtils.checkEqualsAndHashCode(randomLogicalOptimizerContext(), this::copy, this::mutate);
}
private LogicalOptimizerContext randomLogicalOptimizerContext() {
return new LogicalOptimizerContext(ConfigurationTestUtils.randomConfiguration(), randomFoldContext(), randomMinimumVersion());
}
private LogicalOptimizerContext copy(LogicalOptimizerContext c) {
return new LogicalOptimizerContext(c.configuration(), c.foldCtx(), c.minimumVersion());
}
private LogicalOptimizerContext mutate(LogicalOptimizerContext c) {
Configuration configuration = c.configuration();
FoldContext foldCtx = c.foldCtx();
TransportVersion minVersion = c.minimumVersion();
switch (randomIntBetween(0, 2)) {
case 0 -> configuration = randomValueOtherThan(configuration, ConfigurationTestUtils::randomConfiguration);
case 1 -> foldCtx = randomValueOtherThan(foldCtx, this::randomFoldContext);
case 2 -> minVersion = randomValueOtherThan(minVersion, EsqlTestUtils::randomMinimumVersion);
}
return new LogicalOptimizerContext(configuration, foldCtx, minVersion);
}
private FoldContext randomFoldContext() {
FoldContext ctx = new FoldContext(randomNonNegativeLong());
if (randomBoolean()) {
ctx.trackAllocation(Source.EMPTY, randomLongBetween(0, ctx.initialAllowedBytes()));
}
return ctx;
}
}
|
LogicalOptimizerContextTests
|
java
|
spring-projects__spring-boot
|
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Builder.java
|
{
"start": 12796,
"end": 13376
}
|
class ____ extends RuntimeException {
private PlatformMismatchException(ImageReference imageReference, ImagePlatform requestedPlatform,
ImagePlatform actualPlatform, @Nullable Throwable cause) {
super("Image platform mismatch detected. The configured platform '%s' is not supported by the image '%s'. Requested platform '%s' but got '%s'"
.formatted(requestedPlatform, imageReference, requestedPlatform, actualPlatform), cause);
}
}
/**
* A {@link DockerLog} implementation that adapts to an {@link AbstractBuildLog}.
*/
static final
|
PlatformMismatchException
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-uploader/src/main/java/org/apache/hadoop/mapred/uploader/DefaultJars.java
|
{
"start": 920,
"end": 2013
}
|
class ____ {
static final String DEFAULT_EXCLUDED_MR_JARS =
".*hadoop-yarn-server-applicationhistoryservice.*\\.jar," +
".*hadoop-yarn-server-nodemanager.*\\.jar," +
".*hadoop-yarn-server-resourcemanager.*\\.jar," +
".*hadoop-yarn-server-router.*\\.jar," +
".*hadoop-yarn-server-sharedcachemanager.*\\.jar," +
".*hadoop-yarn-server-timeline-pluginstorage.*\\.jar," +
".*hadoop-yarn-server-timelineservice.*\\.jar," +
".*hadoop-yarn-server-timelineservice-hbase.*\\.jar,";
static final String DEFAULT_MR_JARS =
"$HADOOP_HOME/share/hadoop/common/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/common/lib/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/hdfs/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/hdfs/lib/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/mapreduce/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/mapreduce/lib/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/yarn/.*\\.jar," +
"$HADOOP_HOME/share/hadoop/yarn/lib/.*\\.jar,";
private DefaultJars() {}
}
|
DefaultJars
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldContainValues_create_Test.java
|
{
"start": 1119,
"end": 2601
}
|
class ____ {
@Test
void should_create_error_message_with_multiple_values() {
// GIVEN
Map<?, ?> map = mapOf(entry("name", "Yoda"), entry("color", "green"));
ErrorMessageFactory factory = shouldContainValues(map, newLinkedHashSet("VeryOld", "Vader"));
// WHEN
String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(String.format("[Test] %n" +
"Expecting actual:%n" +
" {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" +
"to contain values:%n" +
" [\"VeryOld\", \"Vader\"]"));
}
@Test
void should_create_error_message_with_single_value() {
// GIVEN
Map<?, ?> map = mapOf(entry("name", "Yoda"), entry("color", "green"));
ErrorMessageFactory factory = shouldContainValues(map, newLinkedHashSet("VeryOld"));
// WHEN
String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(String.format("[Test] %n" +
"Expecting actual:%n" +
" {\"color\"=\"green\", \"name\"=\"Yoda\"}%n" +
"to contain value:%n" +
" \"VeryOld\""));
}
}
|
ShouldContainValues_create_Test
|
java
|
apache__camel
|
components/camel-twilio/src/test/java/org/apache/camel/component/twilio/AbstractTwilioTestSupport.java
|
{
"start": 1236,
"end": 1377
}
|
class ____ Twilio Integration tests generated by Camel API component maven plugin.
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public
|
for
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ForOverrideCheckerTest.java
|
{
"start": 9136,
"end": 9585
}
|
class ____ {
void invoke() {
forOverride();
}
}
}
""")
.doTest();
}
@Test
public void definerCanCallFromAnonymousInnerClass() {
compilationHelper
.addSourceLines(
"test/OuterClass.java",
"""
package test;
import com.google.errorprone.annotations.ForOverride;
public
|
InnerClass
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/util/concurrent/ScheduledExecutorServiceAdapter.java
|
{
"start": 1197,
"end": 2520
}
|
class ____ implements ScheduledExecutor {
private final ScheduledExecutorService scheduledExecutorService;
public ScheduledExecutorServiceAdapter(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = Preconditions.checkNotNull(scheduledExecutorService);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(command, delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(callable, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(
Runnable command, long initialDelay, long period, TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(
Runnable command, long initialDelay, long delay, TimeUnit unit) {
return scheduledExecutorService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
@Override
public void execute(Runnable command) {
scheduledExecutorService.execute(command);
}
}
|
ScheduledExecutorServiceAdapter
|
java
|
apache__camel
|
components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/utils/format/MimeType.java
|
{
"start": 896,
"end": 1772
}
|
enum ____ {
JSON("application/json"),
PROTOBUF("application/protobuf"),
PROTOBUF_BINARY("protobuf/binary"),
PROTOBUF_STRUCT("protobuf/x-struct"),
AVRO("application/avro"),
AVRO_BINARY("avro/binary"),
AVRO_STRUCT("avro/x-struct"),
BINARY("application/octet-stream"),
TEXT("text/plain"),
JAVA_OBJECT("application/x-java-object"),
STRUCT("application/x-struct");
private static final MimeType[] VALUES = values();
private final String type;
MimeType(String type) {
this.type = type;
}
public String type() {
return type;
}
public static MimeType of(String type) {
for (MimeType mt : VALUES) {
if (Objects.equals(type, mt.type)) {
return mt;
}
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
|
MimeType
|
java
|
apache__camel
|
core/camel-core-model/src/main/java/org/apache/camel/builder/TokenizerBuilderFactory.java
|
{
"start": 1286,
"end": 1343
}
|
class ____ builder of all supported tokenizers.
*/
public
|
of
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/collect/IteratorsTest.java
|
{
"start": 30506,
"end": 57499
}
|
class ____ extends IteratorTester<Integer> {
DoubletonIteratorTester() {
super(5, MODIFIABLE, newArrayList(1, 2), IteratorTester.KnownOrder.KNOWN_ORDER);
}
}
private static Iterator<Integer> iterateOver(int... values) {
// Note: Ints.asList's iterator does not support remove which we need for testing.
return new ArrayList<>(Ints.asList(values)).iterator();
}
public void testElementsEqual() {
Iterable<?> a;
Iterable<?> b;
// Base case.
a = new ArrayList<>();
b = emptySet();
assertTrue(elementsEqual(a.iterator(), b.iterator()));
// A few elements.
a = asList(4, 8, 15, 16, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertTrue(elementsEqual(a.iterator(), b.iterator()));
// The same, but with nulls.
a = Arrays.<@Nullable Integer>asList(4, 8, null, 16, 23, 42);
b = Arrays.<@Nullable Integer>asList(4, 8, null, 16, 23, 42);
assertTrue(elementsEqual(a.iterator(), b.iterator()));
// Different Iterable types (still equal elements, though).
a = ImmutableList.of(4, 8, 15, 16, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertTrue(elementsEqual(a.iterator(), b.iterator()));
// An element differs.
a = asList(4, 8, 15, 12, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(elementsEqual(a.iterator(), b.iterator()));
// null versus non-null.
a = Arrays.<@Nullable Integer>asList(4, 8, 15, null, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(elementsEqual(a.iterator(), b.iterator()));
assertFalse(elementsEqual(b.iterator(), a.iterator()));
// Different lengths.
a = asList(4, 8, 15, 16, 23);
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(elementsEqual(a.iterator(), b.iterator()));
assertFalse(elementsEqual(b.iterator(), a.iterator()));
// Different lengths, one is empty.
a = emptySet();
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(elementsEqual(a.iterator(), b.iterator()));
assertFalse(elementsEqual(b.iterator(), a.iterator()));
}
public void testPartition_badSize() {
Iterator<Integer> source = singletonIterator(1);
assertThrows(IllegalArgumentException.class, () -> Iterators.partition(source, 0));
}
public void testPartition_empty() {
Iterator<Integer> source = emptyIterator();
Iterator<List<Integer>> partitions = Iterators.partition(source, 1);
assertFalse(partitions.hasNext());
}
public void testPartition_singleton1() {
Iterator<Integer> source = singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.partition(source, 1);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(ImmutableList.of(1), partitions.next());
assertFalse(partitions.hasNext());
}
public void testPartition_singleton2() {
Iterator<Integer> source = singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.partition(source, 2);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(ImmutableList.of(1), partitions.next());
assertFalse(partitions.hasNext());
}
@GwtIncompatible // fairly slow (~50s)
public void testPartition_general() {
new IteratorTester<List<Integer>>(
5,
IteratorFeature.UNMODIFIABLE,
ImmutableList.of(asList(1, 2, 3), asList(4, 5, 6), asList(7)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<List<Integer>> newTargetIterator() {
Iterator<Integer> source = Iterators.forArray(1, 2, 3, 4, 5, 6, 7);
return Iterators.partition(source, 3);
}
}.test();
}
public void testPartition_view() {
List<Integer> list = asList(1, 2);
Iterator<List<Integer>> partitions = Iterators.partition(list.iterator(), 1);
// Changes before the partition is retrieved are reflected
list.set(0, 3);
List<Integer> first = partitions.next();
// Changes after are not
list.set(0, 4);
assertEquals(ImmutableList.of(3), first);
}
@J2ktIncompatible // Arrays.asList(...).subList() doesn't implement RandomAccess in J2KT.
@GwtIncompatible // Arrays.asList(...).subList() doesn't implement RandomAccess in GWT
public void testPartitionRandomAccess() {
Iterator<Integer> source = asList(1, 2, 3).iterator();
Iterator<List<Integer>> partitions = Iterators.partition(source, 2);
assertTrue(partitions.next() instanceof RandomAccess);
assertTrue(partitions.next() instanceof RandomAccess);
}
public void testPaddedPartition_badSize() {
Iterator<Integer> source = singletonIterator(1);
assertThrows(IllegalArgumentException.class, () -> Iterators.paddedPartition(source, 0));
}
public void testPaddedPartition_empty() {
Iterator<Integer> source = emptyIterator();
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1);
assertFalse(partitions.hasNext());
}
public void testPaddedPartition_singleton1() {
Iterator<Integer> source = singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(ImmutableList.of(1), partitions.next());
assertFalse(partitions.hasNext());
}
public void testPaddedPartition_singleton2() {
Iterator<Integer> source = singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(Arrays.<@Nullable Integer>asList(1, null), partitions.next());
assertFalse(partitions.hasNext());
}
@GwtIncompatible // fairly slow (~50s)
public void testPaddedPartition_general() {
ImmutableList<List<@Nullable Integer>> expectedElements =
ImmutableList.of(
asList(1, 2, 3), asList(4, 5, 6), Arrays.<@Nullable Integer>asList(7, null, null));
new IteratorTester<List<Integer>>(
5, IteratorFeature.UNMODIFIABLE, expectedElements, IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<List<Integer>> newTargetIterator() {
Iterator<Integer> source = Iterators.forArray(1, 2, 3, 4, 5, 6, 7);
return Iterators.paddedPartition(source, 3);
}
}.test();
}
public void testPaddedPartition_view() {
List<Integer> list = asList(1, 2);
Iterator<List<Integer>> partitions = Iterators.paddedPartition(list.iterator(), 1);
// Changes before the PaddedPartition is retrieved are reflected
list.set(0, 3);
List<Integer> first = partitions.next();
// Changes after are not
list.set(0, 4);
assertEquals(ImmutableList.of(3), first);
}
public void testPaddedPartitionRandomAccess() {
Iterator<Integer> source = asList(1, 2, 3).iterator();
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2);
assertTrue(partitions.next() instanceof RandomAccess);
assertTrue(partitions.next() instanceof RandomAccess);
}
public void testForArrayEmpty() {
String[] array = new String[0];
Iterator<String> iterator = Iterators.forArray(array);
assertFalse(iterator.hasNext());
assertThrows(NoSuchElementException.class, () -> iterator.next());
assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, 1));
}
@SuppressWarnings("DoNotCall")
public void testForArrayTypical() {
String[] array = {"foo", "bar"};
Iterator<String> iterator = Iterators.forArray(array);
assertTrue(iterator.hasNext());
assertEquals("foo", iterator.next());
assertTrue(iterator.hasNext());
assertThrows(UnsupportedOperationException.class, () -> iterator.remove());
assertEquals("bar", iterator.next());
assertFalse(iterator.hasNext());
assertThrows(NoSuchElementException.class, () -> iterator.next());
}
public void testForArrayWithPosition() {
String[] array = {"foo", "bar", "cat"};
Iterator<String> iterator = Iterators.forArrayWithPosition(array, 1);
assertTrue(iterator.hasNext());
assertEquals("bar", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("cat", iterator.next());
assertFalse(iterator.hasNext());
}
public void testForArrayLengthWithPositionBoundaryCases() {
String[] array = {"foo", "bar"};
assertFalse(Iterators.forArrayWithPosition(array, 2).hasNext());
assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, -1));
assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, 3));
}
@GwtIncompatible // unreasonably slow
public void testForArrayUsingTester() {
new IteratorTester<Integer>(
6, UNMODIFIABLE, asList(1, 2, 3), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.forArray(1, 2, 3);
}
}.test();
}
/*
* TODO(cpovirk): Test forArray with ListIteratorTester (not just IteratorTester), including with
* a start position other than 0.
*/
public void testForEnumerationEmpty() {
Enumeration<Integer> enumer = enumerate();
Iterator<Integer> iter = Iterators.forEnumeration(enumer);
assertFalse(iter.hasNext());
assertThrows(NoSuchElementException.class, () -> iter.next());
}
@SuppressWarnings("DoNotCall")
public void testForEnumerationSingleton() {
Enumeration<Integer> enumer = enumerate(1);
Iterator<Integer> iter = Iterators.forEnumeration(enumer);
assertTrue(iter.hasNext());
assertTrue(iter.hasNext());
assertEquals(1, (int) iter.next());
assertThrows(UnsupportedOperationException.class, () -> iter.remove());
assertFalse(iter.hasNext());
assertThrows(NoSuchElementException.class, () -> iter.next());
}
public void testForEnumerationTypical() {
Enumeration<Integer> enumer = enumerate(1, 2, 3);
Iterator<Integer> iter = Iterators.forEnumeration(enumer);
assertTrue(iter.hasNext());
assertEquals(1, (int) iter.next());
assertTrue(iter.hasNext());
assertEquals(2, (int) iter.next());
assertTrue(iter.hasNext());
assertEquals(3, (int) iter.next());
assertFalse(iter.hasNext());
}
public void testAsEnumerationEmpty() {
Iterator<Integer> iter = emptyIterator();
Enumeration<Integer> enumer = Iterators.asEnumeration(iter);
assertFalse(enumer.hasMoreElements());
assertThrows(NoSuchElementException.class, () -> enumer.nextElement());
}
public void testAsEnumerationSingleton() {
Iterator<Integer> iter = ImmutableList.of(1).iterator();
Enumeration<Integer> enumer = Iterators.asEnumeration(iter);
assertTrue(enumer.hasMoreElements());
assertTrue(enumer.hasMoreElements());
assertEquals(1, (int) enumer.nextElement());
assertFalse(enumer.hasMoreElements());
assertThrows(NoSuchElementException.class, () -> enumer.nextElement());
}
public void testAsEnumerationTypical() {
Iterator<Integer> iter = ImmutableList.of(1, 2, 3).iterator();
Enumeration<Integer> enumer = Iterators.asEnumeration(iter);
assertTrue(enumer.hasMoreElements());
assertEquals(1, (int) enumer.nextElement());
assertTrue(enumer.hasMoreElements());
assertEquals(2, (int) enumer.nextElement());
assertTrue(enumer.hasMoreElements());
assertEquals(3, (int) enumer.nextElement());
assertFalse(enumer.hasMoreElements());
}
// We're testing our asEnumeration method against a known-good implementation.
@SuppressWarnings("JdkObsolete")
private static Enumeration<Integer> enumerate(int... ints) {
Vector<Integer> vector = new Vector<>(Ints.asList(ints));
return vector.elements();
}
public void testToString() {
Iterator<String> iterator = Lists.newArrayList("yam", "bam", "jam", "ham").iterator();
assertEquals("[yam, bam, jam, ham]", Iterators.toString(iterator));
}
public void testToStringWithNull() {
Iterator<@Nullable String> iterator =
Lists.<@Nullable String>newArrayList("hello", null, "world").iterator();
assertEquals("[hello, null, world]", Iterators.toString(iterator));
}
public void testToStringEmptyIterator() {
Iterator<String> iterator = Collections.<String>emptyList().iterator();
assertEquals("[]", Iterators.toString(iterator));
}
@SuppressWarnings("JUnitIncompatibleType") // Fails with j2kt.
public void testLimit() {
List<String> list = new ArrayList<>();
assertThrows(IllegalArgumentException.class, () -> Iterators.limit(list.iterator(), -1));
assertFalse(Iterators.limit(list.iterator(), 0).hasNext());
assertFalse(Iterators.limit(list.iterator(), 1).hasNext());
list.add("cool");
assertFalse(Iterators.limit(list.iterator(), 0).hasNext());
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 1)));
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2)));
list.add("pants");
assertFalse(Iterators.limit(list.iterator(), 0).hasNext());
assertEquals(ImmutableList.of("cool"), newArrayList(Iterators.limit(list.iterator(), 1)));
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2)));
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 3)));
}
public void testLimitRemove() {
List<String> list = new ArrayList<>();
list.add("cool");
list.add("pants");
Iterator<String> iterator = Iterators.limit(list.iterator(), 1);
iterator.next();
iterator.remove();
assertFalse(iterator.hasNext());
assertEquals(1, list.size());
assertEquals("pants", list.get(0));
}
@GwtIncompatible // fairly slow (~30s)
public void testLimitUsingIteratorTester() {
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
new IteratorTester<Integer>(
5, MODIFIABLE, newArrayList(1, 2, 3), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.limit(new ArrayList<>(list).iterator(), 3);
}
}.test();
}
public void testGetNext_withDefault_singleton() {
Iterator<String> iterator = singletonList("foo").iterator();
assertEquals("foo", Iterators.getNext(iterator, "bar"));
}
public void testGetNext_withDefault_empty() {
Iterator<String> iterator = emptyIterator();
assertEquals("bar", Iterators.getNext(iterator, "bar"));
}
public void testGetNext_withDefault_empty_null() {
Iterator<String> iterator = emptyIterator();
assertThat(Iterators.<@Nullable String>getNext(iterator, null)).isNull();
}
public void testGetNext_withDefault_two() {
Iterator<String> iterator = asList("foo", "bar").iterator();
assertEquals("foo", Iterators.getNext(iterator, "x"));
}
public void testGetLast_basic() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
assertEquals("b", getLast(list.iterator()));
}
public void testGetLast_exception() {
List<String> list = new ArrayList<>();
assertThrows(NoSuchElementException.class, () -> getLast(list.iterator()));
}
public void testGetLast_withDefault_singleton() {
Iterator<String> iterator = singletonList("foo").iterator();
assertEquals("foo", Iterators.getLast(iterator, "bar"));
}
public void testGetLast_withDefault_empty() {
Iterator<String> iterator = emptyIterator();
assertEquals("bar", Iterators.getLast(iterator, "bar"));
}
public void testGetLast_withDefault_empty_null() {
Iterator<String> iterator = emptyIterator();
assertThat(Iterators.<@Nullable String>getLast(iterator, null)).isNull();
}
public void testGetLast_withDefault_two() {
Iterator<String> iterator = asList("foo", "bar").iterator();
assertEquals("bar", Iterators.getLast(iterator, "x"));
}
public void testGet_basic() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("b", get(iterator, 1));
assertFalse(iterator.hasNext());
}
public void testGet_atSize() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 2));
assertFalse(iterator.hasNext());
}
public void testGet_pastEnd() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 5));
assertFalse(iterator.hasNext());
}
public void testGet_empty() {
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 0));
assertFalse(iterator.hasNext());
}
public void testGet_negativeIndex() {
List<String> list = newArrayList("a", "b", "c");
Iterator<String> iterator = list.iterator();
assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, -1));
}
public void testGet_withDefault_basic() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("a", get(iterator, 0, "c"));
assertTrue(iterator.hasNext());
}
public void testGet_withDefault_atSize() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("c", get(iterator, 2, "c"));
assertFalse(iterator.hasNext());
}
public void testGet_withDefault_pastEnd() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("c", get(iterator, 3, "c"));
assertFalse(iterator.hasNext());
}
public void testGet_withDefault_negativeIndex() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, -1, "c"));
assertTrue(iterator.hasNext());
}
public void testAdvance_basic() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
advance(iterator, 1);
assertEquals("b", iterator.next());
}
public void testAdvance_pastEnd() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
advance(iterator, 5);
assertFalse(iterator.hasNext());
}
public void testAdvance_illegalArgument() {
List<String> list = newArrayList("a", "b", "c");
Iterator<String> iterator = list.iterator();
assertThrows(IllegalArgumentException.class, () -> advance(iterator, -1));
}
public void testFrequency() {
List<@Nullable String> list = newArrayList("a", null, "b", null, "a", null);
assertEquals(2, frequency(list.iterator(), "a"));
assertEquals(1, frequency(list.iterator(), "b"));
assertEquals(0, frequency(list.iterator(), "c"));
assertEquals(0, frequency(list.iterator(), 4.2));
assertEquals(3, frequency(list.iterator(), null));
}
@GwtIncompatible // slow (~4s)
public void testSingletonIterator() {
new IteratorTester<Integer>(
3, UNMODIFIABLE, singleton(1), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return singletonIterator(1);
}
}.test();
}
public void testRemoveAll() {
List<String> list = newArrayList("a", "b", "c", "d", "e");
assertTrue(Iterators.removeAll(list.iterator(), newArrayList("b", "d", "f")));
assertEquals(newArrayList("a", "c", "e"), list);
assertFalse(Iterators.removeAll(list.iterator(), newArrayList("x", "y", "z")));
assertEquals(newArrayList("a", "c", "e"), list);
}
public void testRemoveIf() {
List<String> list = newArrayList("a", "b", "c", "d", "e");
assertTrue(
Iterators.removeIf(
list.iterator(),
new Predicate<String>() {
@Override
public boolean apply(String s) {
return s.equals("b") || s.equals("d") || s.equals("f");
}
}));
assertEquals(newArrayList("a", "c", "e"), list);
assertFalse(
Iterators.removeIf(
list.iterator(),
new Predicate<String>() {
@Override
public boolean apply(String s) {
return s.equals("x") || s.equals("y") || s.equals("z");
}
}));
assertEquals(newArrayList("a", "c", "e"), list);
}
public void testRetainAll() {
List<String> list = newArrayList("a", "b", "c", "d", "e");
assertTrue(Iterators.retainAll(list.iterator(), newArrayList("b", "d", "f")));
assertEquals(newArrayList("b", "d"), list);
assertFalse(Iterators.retainAll(list.iterator(), newArrayList("b", "e", "d")));
assertEquals(newArrayList("b", "d"), list);
}
@J2ktIncompatible
@GwtIncompatible // ListTestSuiteBuilder
@AndroidIncompatible // test-suite builders
private static Test testsForRemoveAllAndRetainAll() {
return ListTestSuiteBuilder.using(
new TestStringListGenerator() {
@Override
public List<String> create(String[] elements) {
List<String> delegate = newArrayList(elements);
return new ForwardingList<String>() {
@Override
protected List<String> delegate() {
return delegate;
}
@Override
public boolean removeAll(Collection<?> c) {
return Iterators.removeAll(iterator(), c);
}
@Override
public boolean retainAll(Collection<?> c) {
return Iterators.retainAll(iterator(), c);
}
};
}
})
.named("ArrayList with Iterators.removeAll and retainAll")
.withFeatures(
ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY)
.createTestSuite();
}
public void testConsumingIterator() {
// Test data
List<String> list = Lists.newArrayList("a", "b");
// Test & Verify
Iterator<String> consumingIterator = Iterators.consumingIterator(list.iterator());
assertEquals("Iterators.consumingIterator(...)", consumingIterator.toString());
assertThat(list).containsExactly("a", "b").inOrder();
assertTrue(consumingIterator.hasNext());
assertThat(list).containsExactly("a", "b").inOrder();
assertEquals("a", consumingIterator.next());
assertThat(list).contains("b");
assertTrue(consumingIterator.hasNext());
assertEquals("b", consumingIterator.next());
assertThat(list).isEmpty();
assertFalse(consumingIterator.hasNext());
}
@GwtIncompatible // ?
// TODO: Figure out why this is failing in GWT.
public void testConsumingIterator_duelingIterators() {
// Test data
List<String> list = Lists.newArrayList("a", "b");
// Test & Verify
Iterator<String> i1 = Iterators.consumingIterator(list.iterator());
Iterator<String> i2 = Iterators.consumingIterator(list.iterator());
i1.next();
assertThrows(ConcurrentModificationException.class, () -> i2.next());
}
public void testIndexOf_consumedData() {
Iterator<String> iterator = Lists.newArrayList("manny", "mo", "jack").iterator();
assertEquals(1, Iterators.indexOf(iterator, equalTo("mo")));
assertEquals("jack", iterator.next());
assertFalse(iterator.hasNext());
}
public void testIndexOf_consumedDataWithDuplicates() {
Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator();
assertEquals(1, Iterators.indexOf(iterator, equalTo("mo")));
assertEquals("mo", iterator.next());
assertEquals("jack", iterator.next());
assertFalse(iterator.hasNext());
}
public void testIndexOf_consumedDataNoMatch() {
Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator();
assertEquals(-1, Iterators.indexOf(iterator, equalTo("bob")));
assertFalse(iterator.hasNext());
}
@SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method
public void testUnmodifiableIteratorShortCircuit() {
Iterator<String> mod = Lists.newArrayList("a", "b", "c").iterator();
UnmodifiableIterator<String> unmod = Iterators.unmodifiableIterator(mod);
assertNotSame(mod, unmod);
assertSame(unmod, Iterators.unmodifiableIterator(unmod));
assertSame(unmod, Iterators.unmodifiableIterator((Iterator<String>) unmod));
}
@SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method
public void testPeekingIteratorShortCircuit() {
Iterator<String> nonpeek = Lists.newArrayList("a", "b", "c").iterator();
PeekingIterator<String> peek = peekingIterator(nonpeek);
assertNotSame(peek, nonpeek);
assertSame(peek, peekingIterator(peek));
assertSame(peek, peekingIterator((Iterator<String>) peek));
}
public void testMergeSorted_stable_issue5773Example() {
ImmutableList<TestDatum> left = ImmutableList.of(new TestDatum("B", 1), new TestDatum("C", 1));
ImmutableList<TestDatum> right = ImmutableList.of(new TestDatum("A", 2), new TestDatum("C", 2));
Comparator<TestDatum> comparator = Comparator.comparing(d -> d.letter);
// When elements compare as equal (both C's have same letter), our merge should always return C1
// before C2, since C1 is from the first iterator.
Iterator<TestDatum> merged =
Iterators.mergeSorted(ImmutableList.of(left.iterator(), right.iterator()), comparator);
ImmutableList<TestDatum> result = ImmutableList.copyOf(merged);
assertThat(result)
.containsExactly(
new TestDatum("A", 2),
new TestDatum("B", 1),
new TestDatum("C", 1),
new TestDatum("C", 2))
.inOrder();
}
public void testMergeSorted_stable_allEqual() {
ImmutableList<TestDatum> first = ImmutableList.of(new TestDatum("A", 1), new TestDatum("A", 2));
ImmutableList<TestDatum> second =
ImmutableList.of(new TestDatum("A", 3), new TestDatum("A", 4));
Comparator<TestDatum> comparator = Comparator.comparing(d -> d.letter);
Iterator<TestDatum> merged =
Iterators.mergeSorted(ImmutableList.of(first.iterator(), second.iterator()), comparator);
ImmutableList<TestDatum> result = ImmutableList.copyOf(merged);
assertThat(result)
.containsExactly(
new TestDatum("A", 1),
new TestDatum("A", 2),
new TestDatum("A", 3),
new TestDatum("A", 4))
.inOrder();
}
private static final
|
DoubletonIteratorTester
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/hamcrest/InitializationCheckMatcher.java
|
{
"start": 305,
"end": 1314
}
|
class ____<T> extends BaseMatcher<T> {
public static final InitializationCheckMatcher INITIALIZED_MATCHER = new InitializationCheckMatcher();
public static final InitializationCheckMatcher UNINITIALIZED_MATCHER = new InitializationCheckMatcher( false );
public static <T> InitializationCheckMatcher<T> isInitialized() {
//noinspection unchecked
return INITIALIZED_MATCHER;
}
public static <T> Matcher<T> isNotInitialized() {
//noinspection unchecked
return UNINITIALIZED_MATCHER;
}
private final boolean assertInitialized;
public InitializationCheckMatcher() {
this( true );
}
public InitializationCheckMatcher(boolean assertInitialized) {
this.assertInitialized = assertInitialized;
}
@Override
public boolean matches(Object item) {
return assertInitialized == Hibernate.isInitialized( item );
}
@Override
public void describeTo(Description description) {
description.appendValue( "Hibernate#isInitialized() returns " + assertInitialized );
}
}
|
InitializationCheckMatcher
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.