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
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
|
{
"start": 39064,
"end": 39254
}
|
class ____ implements DialectFeatureCheck {
public boolean apply(Dialect dialect) {
return definesFunction( dialect, "euclidean_distance" );
}
}
public static
|
SupportsEuclideanDistance
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/BlobEndpointBuilderFactory.java
|
{
"start": 1600,
"end": 42773
}
|
interface ____
extends
EndpointConsumerBuilder {
default AdvancedBlobEndpointConsumerBuilder advanced() {
return (AdvancedBlobEndpointConsumerBuilder) this;
}
/**
* The blob name, to consume specific blob from a container. However, on
* producer it is only required for the operations on the blob level.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param blobName the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobName(String blobName) {
doSetProperty("blobName", blobName);
return this;
}
/**
* Set the blob offset for the upload or download operations, default is
* 0.
*
* The option is a: <code>long</code> type.
*
* Default: 0
* Group: common
*
* @param blobOffset the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobOffset(long blobOffset) {
doSetProperty("blobOffset", blobOffset);
return this;
}
/**
* Set the blob offset for the upload or download operations, default is
* 0.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 0
* Group: common
*
* @param blobOffset the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobOffset(String blobOffset) {
doSetProperty("blobOffset", blobOffset);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* getBlobContainerClient(String), and operations on a blob are
* available on BlobClient through
* getBlobContainerClient(String).getBlobClient(String).
*
* The option is a:
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param blobServiceClient the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobServiceClient(com.azure.storage.blob.BlobServiceClient blobServiceClient) {
doSetProperty("blobServiceClient", blobServiceClient);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* getBlobContainerClient(String), and operations on a blob are
* available on BlobClient through
* getBlobContainerClient(String).getBlobClient(String).
*
* The option will be converted to a
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param blobServiceClient the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobServiceClient(String blobServiceClient) {
doSetProperty("blobServiceClient", blobServiceClient);
return this;
}
/**
* The blob type in order to initiate the appropriate settings for each
* blob type.
*
* The option is a:
* <code>org.apache.camel.component.azure.storage.blob.BlobType</code>
* type.
*
* Default: blockblob
* Group: common
*
* @param blobType the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobType(org.apache.camel.component.azure.storage.blob.BlobType blobType) {
doSetProperty("blobType", blobType);
return this;
}
/**
* The blob type in order to initiate the appropriate settings for each
* blob type.
*
* The option will be converted to a
* <code>org.apache.camel.component.azure.storage.blob.BlobType</code>
* type.
*
* Default: blockblob
* Group: common
*
* @param blobType the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder blobType(String blobType) {
doSetProperty("blobType", blobType);
return this;
}
/**
* Close the stream after read or keep it open, default is true.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param closeStreamAfterRead the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder closeStreamAfterRead(boolean closeStreamAfterRead) {
doSetProperty("closeStreamAfterRead", closeStreamAfterRead);
return this;
}
/**
* Close the stream after read or keep it open, default is true.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param closeStreamAfterRead the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder closeStreamAfterRead(String closeStreamAfterRead) {
doSetProperty("closeStreamAfterRead", closeStreamAfterRead);
return this;
}
/**
* StorageSharedKeyCredential can be injected to create the azure
* client, this holds the important authentication information.
*
* The option is a:
* <code>com.azure.storage.common.StorageSharedKeyCredential</code>
* type.
*
* Group: common
*
* @param credentials the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder credentials(com.azure.storage.common.StorageSharedKeyCredential credentials) {
doSetProperty("credentials", credentials);
return this;
}
/**
* StorageSharedKeyCredential can be injected to create the azure
* client, this holds the important authentication information.
*
* The option will be converted to a
* <code>com.azure.storage.common.StorageSharedKeyCredential</code>
* type.
*
* Group: common
*
* @param credentials the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder credentials(String credentials) {
doSetProperty("credentials", credentials);
return this;
}
/**
* Determines the credential strategy to adopt.
*
* The option is a:
* <code>org.apache.camel.component.azure.storage.blob.CredentialType</code> type.
*
* Default: AZURE_IDENTITY
* Group: common
*
* @param credentialType the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder credentialType(org.apache.camel.component.azure.storage.blob.CredentialType credentialType) {
doSetProperty("credentialType", credentialType);
return this;
}
/**
* Determines the credential strategy to adopt.
*
* The option will be converted to a
* <code>org.apache.camel.component.azure.storage.blob.CredentialType</code> type.
*
* Default: AZURE_IDENTITY
* Group: common
*
* @param credentialType the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder credentialType(String credentialType) {
doSetProperty("credentialType", credentialType);
return this;
}
/**
* How many bytes to include in the range. Must be greater than or equal
* to 0 if specified.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: common
*
* @param dataCount the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder dataCount(Long dataCount) {
doSetProperty("dataCount", dataCount);
return this;
}
/**
* How many bytes to include in the range. Must be greater than or equal
* to 0 if specified.
*
* The option will be converted to a <code>java.lang.Long</code> type.
*
* Group: common
*
* @param dataCount the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder dataCount(String dataCount) {
doSetProperty("dataCount", dataCount);
return this;
}
/**
* The file directory where the downloaded blobs will be saved to, this
* can be used in both, producer and consumer.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param fileDir the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder fileDir(String fileDir) {
doSetProperty("fileDir", fileDir);
return this;
}
/**
* Sets whether a lease should be acquired when accessing the blob. When
* set to true, the component will acquire a lease before performing
* blob operations that require exclusive access.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param leaseBlob the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder leaseBlob(boolean leaseBlob) {
doSetProperty("leaseBlob", leaseBlob);
return this;
}
/**
* Sets whether a lease should be acquired when accessing the blob. When
* set to true, the component will acquire a lease before performing
* blob operations that require exclusive access.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param leaseBlob the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder leaseBlob(String leaseBlob) {
doSetProperty("leaseBlob", leaseBlob);
return this;
}
/**
* Sets the lease duration in seconds. Use -1 for infinite or a value
* between 15 and 60 for fixed leases.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Default: 60
* Group: common
*
* @param leaseDurationInSeconds the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder leaseDurationInSeconds(Integer leaseDurationInSeconds) {
doSetProperty("leaseDurationInSeconds", leaseDurationInSeconds);
return this;
}
/**
* Sets the lease duration in seconds. Use -1 for infinite or a value
* between 15 and 60 for fixed leases.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Default: 60
* Group: common
*
* @param leaseDurationInSeconds the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder leaseDurationInSeconds(String leaseDurationInSeconds) {
doSetProperty("leaseDurationInSeconds", leaseDurationInSeconds);
return this;
}
/**
* Specifies the maximum number of blobs to return, including all
* BlobPrefix elements. If the request does not specify
* maxResultsPerPage or specifies a value greater than 5,000, the server
* will return up to 5,000 items.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: common
*
* @param maxResultsPerPage the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder maxResultsPerPage(Integer maxResultsPerPage) {
doSetProperty("maxResultsPerPage", maxResultsPerPage);
return this;
}
/**
* Specifies the maximum number of blobs to return, including all
* BlobPrefix elements. If the request does not specify
* maxResultsPerPage or specifies a value greater than 5,000, the server
* will return up to 5,000 items.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: common
*
* @param maxResultsPerPage the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder maxResultsPerPage(String maxResultsPerPage) {
doSetProperty("maxResultsPerPage", maxResultsPerPage);
return this;
}
/**
* Specifies the maximum number of additional HTTP Get requests that
* will be made while reading the data from a response body.
*
* The option is a: <code>int</code> type.
*
* Default: 0
* Group: common
*
* @param maxRetryRequests the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder maxRetryRequests(int maxRetryRequests) {
doSetProperty("maxRetryRequests", maxRetryRequests);
return this;
}
/**
* Specifies the maximum number of additional HTTP Get requests that
* will be made while reading the data from a response body.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 0
* Group: common
*
* @param maxRetryRequests the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder maxRetryRequests(String maxRetryRequests) {
doSetProperty("maxRetryRequests", maxRetryRequests);
return this;
}
/**
* Filters the results to return only blobs whose names begin with the
* specified prefix. May be null to return all blobs.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param prefix the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder prefix(String prefix) {
doSetProperty("prefix", prefix);
return this;
}
/**
* Filters the results to return only blobs whose names match the
* specified regular expression. May be null to return all if both
* prefix and regex are set, regex takes the priority and prefix is
* ignored.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param regex the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder regex(String regex) {
doSetProperty("regex", regex);
return this;
}
/**
* In case of usage of Shared Access Signature we'll need to set a SAS
* Token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param sasToken the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder sasToken(String sasToken) {
doSetProperty("sasToken", sasToken);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* BlobServiceClient#getBlobContainerClient(String), and operations on a
* blob are available on BlobClient through
* BlobContainerClient#getBlobClient(String).
*
* The option is a:
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param serviceClient the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder serviceClient(com.azure.storage.blob.BlobServiceClient serviceClient) {
doSetProperty("serviceClient", serviceClient);
return this;
}
/**
* Client to a storage account. This client does not hold any state
* about a particular storage account but is instead a convenient way of
* sending off appropriate requests to the resource on the service. It
* may also be used to construct URLs to blobs and containers. This
* client contains operations on a service account. Operations on a
* container are available on BlobContainerClient through
* BlobServiceClient#getBlobContainerClient(String), and operations on a
* blob are available on BlobClient through
* BlobContainerClient#getBlobClient(String).
*
* The option will be converted to a
* <code>com.azure.storage.blob.BlobServiceClient</code> type.
*
* Group: common
*
* @param serviceClient the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder serviceClient(String serviceClient) {
doSetProperty("serviceClient", serviceClient);
return this;
}
/**
* An optional timeout value beyond which a RuntimeException will be
* raised.
*
* The option is a: <code>java.time.Duration</code> type.
*
* Group: common
*
* @param timeout the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder timeout(java.time.Duration timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* An optional timeout value beyond which a RuntimeException will be
* raised.
*
* The option will be converted to a <code>java.time.Duration</code>
* type.
*
* Group: common
*
* @param timeout the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder timeout(String timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* If the polling consumer did not poll any files, you can enable this
* option to send an empty message (no body) instead.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param sendEmptyMessageWhenIdle the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder sendEmptyMessageWhenIdle(boolean sendEmptyMessageWhenIdle) {
doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle);
return this;
}
/**
* If the polling consumer did not poll any files, you can enable this
* option to send an empty message (no body) instead.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param sendEmptyMessageWhenIdle the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder sendEmptyMessageWhenIdle(String sendEmptyMessageWhenIdle) {
doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle);
return this;
}
/**
* The number of subsequent error polls (failed due some error) that
* should happen before the backoffMultipler should kick-in.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffErrorThreshold the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder backoffErrorThreshold(int backoffErrorThreshold) {
doSetProperty("backoffErrorThreshold", backoffErrorThreshold);
return this;
}
/**
* The number of subsequent error polls (failed due some error) that
* should happen before the backoffMultipler should kick-in.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffErrorThreshold the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder backoffErrorThreshold(String backoffErrorThreshold) {
doSetProperty("backoffErrorThreshold", backoffErrorThreshold);
return this;
}
/**
* The number of subsequent idle polls that should happen before the
* backoffMultipler should kick-in.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffIdleThreshold the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder backoffIdleThreshold(int backoffIdleThreshold) {
doSetProperty("backoffIdleThreshold", backoffIdleThreshold);
return this;
}
/**
* The number of subsequent idle polls that should happen before the
* backoffMultipler should kick-in.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffIdleThreshold the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder backoffIdleThreshold(String backoffIdleThreshold) {
doSetProperty("backoffIdleThreshold", backoffIdleThreshold);
return this;
}
/**
* To let the scheduled polling consumer backoff if there has been a
* number of subsequent idles/errors in a row. The multiplier is then
* the number of polls that will be skipped before the next actual
* attempt is happening again. When this option is in use then
* backoffIdleThreshold and/or backoffErrorThreshold must also be
* configured.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffMultiplier the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder backoffMultiplier(int backoffMultiplier) {
doSetProperty("backoffMultiplier", backoffMultiplier);
return this;
}
/**
* To let the scheduled polling consumer backoff if there has been a
* number of subsequent idles/errors in a row. The multiplier is then
* the number of polls that will be skipped before the next actual
* attempt is happening again. When this option is in use then
* backoffIdleThreshold and/or backoffErrorThreshold must also be
* configured.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffMultiplier the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder backoffMultiplier(String backoffMultiplier) {
doSetProperty("backoffMultiplier", backoffMultiplier);
return this;
}
/**
* Milliseconds before the next poll.
*
* The option is a: <code>long</code> type.
*
* Default: 500
* Group: scheduler
*
* @param delay the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder delay(long delay) {
doSetProperty("delay", delay);
return this;
}
/**
* Milliseconds before the next poll.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 500
* Group: scheduler
*
* @param delay the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder delay(String delay) {
doSetProperty("delay", delay);
return this;
}
/**
* If greedy is enabled, then the ScheduledPollConsumer will run
* immediately again, if the previous run polled 1 or more messages.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: scheduler
*
* @param greedy the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder greedy(boolean greedy) {
doSetProperty("greedy", greedy);
return this;
}
/**
* If greedy is enabled, then the ScheduledPollConsumer will run
* immediately again, if the previous run polled 1 or more messages.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: scheduler
*
* @param greedy the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder greedy(String greedy) {
doSetProperty("greedy", greedy);
return this;
}
/**
* Milliseconds before the first poll starts.
*
* The option is a: <code>long</code> type.
*
* Default: 1000
* Group: scheduler
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder initialDelay(long initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* Milliseconds before the first poll starts.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 1000
* Group: scheduler
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder initialDelay(String initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* Specifies a maximum limit of number of fires. So if you set it to 1,
* the scheduler will only fire once. If you set it to 5, it will only
* fire five times. A value of zero or negative means fire forever.
*
* The option is a: <code>long</code> type.
*
* Default: 0
* Group: scheduler
*
* @param repeatCount the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder repeatCount(long repeatCount) {
doSetProperty("repeatCount", repeatCount);
return this;
}
/**
* Specifies a maximum limit of number of fires. So if you set it to 1,
* the scheduler will only fire once. If you set it to 5, it will only
* fire five times. A value of zero or negative means fire forever.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 0
* Group: scheduler
*
* @param repeatCount the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder repeatCount(String repeatCount) {
doSetProperty("repeatCount", repeatCount);
return this;
}
/**
* The consumer logs a start/complete log line when it polls. This
* option allows you to configure the logging level for that.
*
* The option is a: <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: TRACE
* Group: scheduler
*
* @param runLoggingLevel the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder runLoggingLevel(org.apache.camel.LoggingLevel runLoggingLevel) {
doSetProperty("runLoggingLevel", runLoggingLevel);
return this;
}
/**
* The consumer logs a start/complete log line when it polls. This
* option allows you to configure the logging level for that.
*
* The option will be converted to a
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: TRACE
* Group: scheduler
*
* @param runLoggingLevel the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder runLoggingLevel(String runLoggingLevel) {
doSetProperty("runLoggingLevel", runLoggingLevel);
return this;
}
/**
* Allows for configuring a custom/shared thread pool to use for the
* consumer. By default each consumer has its own single threaded thread
* pool.
*
* The option is a:
* <code>java.util.concurrent.ScheduledExecutorService</code> type.
*
* Group: scheduler
*
* @param scheduledExecutorService the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
doSetProperty("scheduledExecutorService", scheduledExecutorService);
return this;
}
/**
* Allows for configuring a custom/shared thread pool to use for the
* consumer. By default each consumer has its own single threaded thread
* pool.
*
* The option will be converted to a
* <code>java.util.concurrent.ScheduledExecutorService</code> type.
*
* Group: scheduler
*
* @param scheduledExecutorService the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder scheduledExecutorService(String scheduledExecutorService) {
doSetProperty("scheduledExecutorService", scheduledExecutorService);
return this;
}
/**
* To use a cron scheduler from either camel-spring or camel-quartz
* component. Use value spring or quartz for built in scheduler.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Default: none
* Group: scheduler
*
* @param scheduler the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder scheduler(Object scheduler) {
doSetProperty("scheduler", scheduler);
return this;
}
/**
* To use a cron scheduler from either camel-spring or camel-quartz
* component. Use value spring or quartz for built in scheduler.
*
* The option will be converted to a <code>java.lang.Object</code> type.
*
* Default: none
* Group: scheduler
*
* @param scheduler the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder scheduler(String scheduler) {
doSetProperty("scheduler", scheduler);
return this;
}
/**
* To configure additional properties when using a custom scheduler or
* any of the Quartz, Spring based scheduler. This is a multi-value
* option with prefix: scheduler.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.Object></code> type.
* The option is multivalued, and you can use the
* schedulerProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: scheduler
*
* @param key the option key
* @param value the option value
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder schedulerProperties(String key, Object value) {
doSetMultiValueProperty("schedulerProperties", "scheduler." + key, value);
return this;
}
/**
* To configure additional properties when using a custom scheduler or
* any of the Quartz, Spring based scheduler. This is a multi-value
* option with prefix: scheduler.
*
* The option is a: <code>java.util.Map<java.lang.String,
* java.lang.Object></code> type.
* The option is multivalued, and you can use the
* schedulerProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: scheduler
*
* @param values the values
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder schedulerProperties(Map values) {
doSetMultiValueProperties("schedulerProperties", "scheduler.", values);
return this;
}
/**
* Whether the scheduler should be auto started.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param startScheduler the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder startScheduler(boolean startScheduler) {
doSetProperty("startScheduler", startScheduler);
return this;
}
/**
* Whether the scheduler should be auto started.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param startScheduler the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder startScheduler(String startScheduler) {
doSetProperty("startScheduler", startScheduler);
return this;
}
/**
* Time unit for initialDelay and delay options.
*
* The option is a: <code>java.util.concurrent.TimeUnit</code> type.
*
* Default: MILLISECONDS
* Group: scheduler
*
* @param timeUnit the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder timeUnit(TimeUnit timeUnit) {
doSetProperty("timeUnit", timeUnit);
return this;
}
/**
* Time unit for initialDelay and delay options.
*
* The option will be converted to a
* <code>java.util.concurrent.TimeUnit</code> type.
*
* Default: MILLISECONDS
* Group: scheduler
*
* @param timeUnit the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder timeUnit(String timeUnit) {
doSetProperty("timeUnit", timeUnit);
return this;
}
/**
* Controls if fixed delay or fixed rate is used. See
* ScheduledExecutorService in JDK for details.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param useFixedDelay the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder useFixedDelay(boolean useFixedDelay) {
doSetProperty("useFixedDelay", useFixedDelay);
return this;
}
/**
* Controls if fixed delay or fixed rate is used. See
* ScheduledExecutorService in JDK for details.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param useFixedDelay the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder useFixedDelay(String useFixedDelay) {
doSetProperty("useFixedDelay", useFixedDelay);
return this;
}
/**
* Access key for the associated azure account name to be used for
* authentication with azure blob services.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessKey the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder accessKey(String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* Azure Client ID for authentication with Azure Identity.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param azureClientId the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder azureClientId(String azureClientId) {
doSetProperty("azureClientId", azureClientId);
return this;
}
/**
* Azure Client Secret for authentication with Azure Identity.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param azureClientSecret the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder azureClientSecret(String azureClientSecret) {
doSetProperty("azureClientSecret", azureClientSecret);
return this;
}
/**
* Azure Tenant ID for authentication with Azure Identity.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param azureTenantId the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder azureTenantId(String azureTenantId) {
doSetProperty("azureTenantId", azureTenantId);
return this;
}
/**
* Source Blob Access Key: for copyblob operation, sadly, we need to
* have an accessKey for the source blob we want to copy Passing an
* accessKey as header, it's unsafe so we could set as key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param sourceBlobAccessKey the value to set
* @return the dsl builder
*/
default BlobEndpointConsumerBuilder sourceBlobAccessKey(String sourceBlobAccessKey) {
doSetProperty("sourceBlobAccessKey", sourceBlobAccessKey);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Azure Storage Blob Service component.
*/
public
|
BlobEndpointConsumerBuilder
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_flatExtracting_with_String_parameter_Test.java
|
{
"start": 1553,
"end": 5975
}
|
class ____ {
private CartoonCharacter bart;
private CartoonCharacter lisa;
private CartoonCharacter maggie;
private CartoonCharacter homer;
private CartoonCharacter pebbles;
private CartoonCharacter fred;
@BeforeEach
void setUp() {
bart = new CartoonCharacter("Bart Simpson");
lisa = new CartoonCharacter("Lisa Simpson");
maggie = new CartoonCharacter("Maggie Simpson");
homer = new CartoonCharacter("Homer Simpson");
homer.addChildren(bart, lisa, maggie);
pebbles = new CartoonCharacter("Pebbles Flintstone");
fred = new CartoonCharacter("Fred Flintstone");
fred.addChildren(pebbles);
}
@Test
void should_allow_assertions_on_joined_lists_when_extracting_children() {
assertThat(newArrayList(homer, fred)).flatExtracting("children").containsOnly(bart, lisa, maggie, pebbles);
}
@Test
void should_allow_assertions_on_joined_lists_when_extracting_children_array() {
assertThat(newArrayList(homer, fred)).flatExtracting("childrenArray").containsOnly(bart, lisa, maggie, pebbles);
}
@Test
void should_allow_assertions_on_empty_result_lists() {
assertThat(newArrayList(bart, lisa, maggie)).flatExtracting("children").isEmpty();
}
@Test
void should_throw_exception_when_extracting_from_null() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThat(newArrayList(homer, null)).flatExtracting("children"));
}
@Test
void should_throw_exception_when_extracted_value_is_not_an_array_or_an_iterable() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThat(newArrayList(homer, fred)).flatExtracting("name"))
.withMessage("Flat extracting expects extracted values to be Iterables or arrays but was a String");
}
@SuppressWarnings("deprecation")
@Test
void flatExtracting_should_keep_assertion_state() {
// GIVEN
AlwaysEqualComparator<CartoonCharacter> cartoonCharacterAlwaysEqualComparator = alwaysEqual();
// WHEN
// not all comparators are used but we want to test that they are passed correctly after extracting
// @format:off
AbstractListAssert<?, ?, ?, ?> assertion
= assertThat(newArrayList(homer, fred)).as("test description")
.withFailMessage("error message")
.withRepresentation(UNICODE_REPRESENTATION)
.usingComparatorForType(cartoonCharacterAlwaysEqualComparator, CartoonCharacter.class)
.flatExtracting("children")
.contains(bart, lisa, new CartoonCharacter("Unknown"));
// @format:on
// THEN
assertThat(assertion.descriptionText()).isEqualTo("test description");
assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION);
assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message");
assertThat(comparatorsByTypeOf(assertion).getComparatorForType(CartoonCharacter.class)).isSameAs(cartoonCharacterAlwaysEqualComparator);
}
@Test
void flatExtracting_with_multiple_properties_should_keep_assertion_state() {
// WHEN
// not all comparators are used but we want to test that they are passed correctly after extracting
// @format:off
AbstractListAssert<?, ?, ?, ?> assertion
= assertThat(newArrayList(homer)).as("test description")
.withFailMessage("error message")
.withRepresentation(UNICODE_REPRESENTATION)
.usingComparatorForType(ALWAYS_EQUALS_STRING, String.class)
.flatExtracting("name", "children")
.contains("Homer Simpson", newArrayList(bart, lisa, maggie));
// @format:on
// THEN
assertThat(assertion.descriptionText()).isEqualTo("test description");
assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION);
assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message");
assertThat(comparatorsByTypeOf(assertion).getComparatorForType(String.class)).isSameAs(ALWAYS_EQUALS_STRING);
}
}
|
IterableAssert_flatExtracting_with_String_parameter_Test
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/java8stream/wildcard/ErroneousIterableTypeVarBoundMapperOnMethod.java
|
{
"start": 368,
"end": 490
}
|
interface ____ {
<T extends BigDecimal> List<T> map(Stream<BigDecimal> in);
}
|
ErroneousIterableTypeVarBoundMapperOnMethod
|
java
|
quarkusio__quarkus
|
core/runtime/src/main/java/io/quarkus/runtime/graal/AwtImageIO.java
|
{
"start": 4734,
"end": 5217
}
|
class ____ {
@Substitute
public static ImageOutputStream createImageOutputStream(Object output) {
// Exception would not emerge.
AwtImageIO.LOGGER.error(AwtImageIO.AWT_EXTENSION_HINT);
return null;
}
@Substitute
public static ImageInputStream createImageInputStream(Object input) {
// Exception would not emerge.
AwtImageIO.LOGGER.error(AwtImageIO.AWT_EXTENSION_HINT);
return null;
}
}
|
Target_javax_imageio_ImageIO
|
java
|
apache__logging-log4j2
|
log4j-web/src/main/java/org/apache/logging/log4j/web/Log4jWebSupport.java
|
{
"start": 1802,
"end": 4200
}
|
interface ____ {
/**
* The {@link javax.servlet.ServletContext} parameter name for the name of the
* {@link org.apache.logging.log4j.core.LoggerContext}.
*/
String LOG4J_CONTEXT_NAME = "log4jContextName";
/**
* The {@link javax.servlet.ServletContext} parameter name for the location of the configuration.
*/
String LOG4J_CONFIG_LOCATION = "log4jConfiguration";
/**
* The {@link javax.servlet.ServletContext} parameter name for the JNDI flag.
*/
String IS_LOG4J_CONTEXT_SELECTOR_NAMED = "isLog4jContextSelectorNamed";
/**
* The {@link javax.servlet.ServletContext} parameter name for the flag that disables Log4j's auto-initialization
* in Servlet 3.0+ web applications. Set a context parameter with this name to "true" to disable
* auto-initialization.
*/
String IS_LOG4J_AUTO_INITIALIZATION_DISABLED = "isLog4jAutoInitializationDisabled";
/**
* The {@link javax.servlet.ServletContext} parameter name for the flag that disables Log4j's auto-shutdown
* in Servlet 3.0+ web applications. Set a context parameter with this name to "true" to disable
* auto-shutdown.
*/
String IS_LOG4J_AUTO_SHUTDOWN_DISABLED = "isLog4jAutoShutdownDisabled";
/**
* The attribute key for the {@link javax.servlet.ServletContext} attribute that the singleton support instance
* is stored in.
*/
String SUPPORT_ATTRIBUTE = Log4jWebSupport.class.getName() + ".INSTANCE";
/**
* The attribute key for the {@link javax.servlet.ServletContext} attribute that the {@link LoggerContext}
* is stored in.
*/
String CONTEXT_ATTRIBUTE = LoggerContext.class.getName() + ".INSTANCE";
/**
* Sets the logger context so that code executing afterwards can easily and quickly access loggers via
* {@link org.apache.logging.log4j.LogManager#getLogger()}.
*/
void setLoggerContext();
/**
* Clears the logger context set up in {@link #setLoggerContext}.
*/
void clearLoggerContext();
/**
* Sets the logger context by calling {@link #setLoggerContext}, executes the runnable argument, then clears the
* logger context by calling {@link #clearLoggerContext}.
*
* @param runnable The runnable to execute wrapped with a configured logger context
*/
void wrapExecution(Runnable runnable);
}
|
Log4jWebSupport
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-athena/src/main/java/org/apache/camel/component/aws2/athena/Athena2ProducerHealthCheck.java
|
{
"start": 1296,
"end": 2968
}
|
class ____ extends AbstractHealthCheck {
private final Athena2Endpoint athena2Endpoint;
public Athena2ProducerHealthCheck(Athena2Endpoint athena2Endpoint, String clientId) {
super("camel", "producer:aws2-athena-" + clientId);
this.athena2Endpoint = athena2Endpoint;
}
@Override
protected void doCall(HealthCheckResultBuilder builder, Map<String, Object> options) {
try {
if (ObjectHelper.isNotEmpty(athena2Endpoint.getConfiguration().getRegion())) {
if (!AthenaClient.serviceMetadata().regions()
.contains(Region.of(athena2Endpoint.getConfiguration().getRegion()))) {
builder.message("The service is not supported in this region");
builder.down();
return;
}
}
AthenaClient client = athena2Endpoint.getAthenaClient();
client.listQueryExecutions(ListQueryExecutionsRequest.builder().maxResults(1).build());
} catch (AwsServiceException e) {
builder.message(e.getMessage());
builder.error(e);
if (ObjectHelper.isNotEmpty(e.statusCode())) {
builder.detail(SERVICE_STATUS_CODE, e.statusCode());
}
if (ObjectHelper.isNotEmpty(e.awsErrorDetails().errorCode())) {
builder.detail(SERVICE_ERROR_CODE, e.awsErrorDetails().errorCode());
}
builder.down();
return;
} catch (Exception e) {
builder.error(e);
builder.down();
return;
}
builder.up();
}
}
|
Athena2ProducerHealthCheck
|
java
|
junit-team__junit5
|
junit-jupiter-params/src/main/java/org/junit/jupiter/params/ResolverFacade.java
|
{
"start": 3099,
"end": 5392
}
|
class ____ {
static ResolverFacade create(Class<?> clazz, List<Field> fields) {
Preconditions.notEmpty(fields, "Fields must not be empty");
NavigableMap<Integer, List<FieldParameterDeclaration>> allIndexedParameters = new TreeMap<>();
Set<FieldParameterDeclaration> aggregatorParameters = new LinkedHashSet<>();
for (Field field : fields) {
Parameter annotation = findAnnotation(field, Parameter.class) //
.orElseThrow(() -> new JUnitException("No @Parameter annotation present"));
int index = annotation.value();
FieldParameterDeclaration declaration = new FieldParameterDeclaration(field, annotation.value());
if (declaration.isAggregator()) {
aggregatorParameters.add(declaration);
}
else {
if (fields.size() == 1 && index == Parameter.UNSET_INDEX) {
index = 0;
declaration = new FieldParameterDeclaration(field, 0);
}
allIndexedParameters.computeIfAbsent(index, __ -> new ArrayList<>()) //
.add(declaration);
}
}
NavigableMap<Integer, FieldParameterDeclaration> uniqueIndexedParameters = validateFieldDeclarations(
allIndexedParameters, aggregatorParameters);
Stream.concat(uniqueIndexedParameters.values().stream(), aggregatorParameters.stream()) //
.forEach(declaration -> makeAccessible(declaration.getField()));
var requiredParameterCount = new RequiredParameterCount(uniqueIndexedParameters.size(), "field injection");
return new ResolverFacade(clazz, uniqueIndexedParameters, aggregatorParameters, 0, requiredParameterCount);
}
static ResolverFacade create(Constructor<?> constructor, ParameterizedClass annotation) {
// Inner classes get the outer instance as first (implicit) parameter
int implicitParameters = isInnerClass(constructor.getDeclaringClass()) ? 1 : 0;
return create(constructor, annotation, implicitParameters);
}
static ResolverFacade create(Method method, Annotation annotation) {
if (isKotlinSuspendingFunction(method)) {
return create(method, annotation, 0, getKotlinSuspendingFunctionParameters(method));
}
return create(method, annotation, 0);
}
/**
* Create a new {@link ResolverFacade} for the supplied {@link Executable}.
*
* <p>This method takes a best-effort approach at enforcing the following
* policy for parameterized
|
ResolverFacade
|
java
|
spring-projects__spring-boot
|
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/transport/HttpTransport.java
|
{
"start": 1386,
"end": 3913
}
|
interface ____ {
/**
* Perform an HTTP GET operation.
* @param uri the destination URI (excluding any host/port)
* @return the operation response
* @throws IOException on IO error
*/
Response get(URI uri) throws IOException;
/**
* Perform an HTTP POST operation.
* @param uri the destination URI (excluding any host/port)
* @return the operation response
* @throws IOException on IO error
*/
Response post(URI uri) throws IOException;
/**
* Perform an HTTP POST operation.
* @param uri the destination URI (excluding any host/port)
* @param registryAuth registry authentication credentials
* @return the operation response
* @throws IOException on IO error
*/
Response post(URI uri, @Nullable String registryAuth) throws IOException;
/**
* Perform an HTTP POST operation.
* @param uri the destination URI (excluding any host/port)
* @param contentType the content type to write
* @param writer a content writer
* @return the operation response
* @throws IOException on IO error
*/
Response post(URI uri, String contentType, IOConsumer<OutputStream> writer) throws IOException;
/**
* Perform an HTTP PUT operation.
* @param uri the destination URI (excluding any host/port)
* @param contentType the content type to write
* @param writer a content writer
* @return the operation response
* @throws IOException on IO error
*/
Response put(URI uri, String contentType, IOConsumer<OutputStream> writer) throws IOException;
/**
* Perform an HTTP DELETE operation.
* @param uri the destination URI (excluding any host/port)
* @return the operation response
* @throws IOException on IO error
*/
Response delete(URI uri) throws IOException;
/**
* Perform an HTTP HEAD operation.
* @param uri the destination URI (excluding any host/port)
* @return the operation response
* @throws IOException on IO error
*/
Response head(URI uri) throws IOException;
/**
* Create the most suitable {@link HttpTransport} based on the {@link DockerHost}.
* @param connectionConfiguration the Docker host information
* @return a {@link HttpTransport} instance
*/
static HttpTransport create(@Nullable DockerConnectionConfiguration connectionConfiguration) {
ResolvedDockerHost host = ResolvedDockerHost.from(connectionConfiguration);
HttpTransport remote = RemoteHttpClientTransport.createIfPossible(host);
return (remote != null) ? remote : LocalHttpClientTransport.create(host);
}
/**
* An HTTP operation response.
*/
|
HttpTransport
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/NullOptionalTest.java
|
{
"start": 2115,
"end": 2485
}
|
class ____ {
void a(@Nullable Optional<Object> o) {}
void test() {
a(null);
}
}
""")
.doTest();
}
@Test
public void notPassingNull_noMatch() {
helper
.addSourceLines(
"Test.java",
"""
import java.util.Optional;
|
Test
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2478/Issue2478Mapper.java
|
{
"start": 338,
"end": 515
}
|
interface ____ {
Issue2478Mapper INSTANCE = Mappers.getMapper( Issue2478Mapper.class );
ProductEntity productFromDto(Product dto, @Context Shop shop);
|
Issue2478Mapper
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/EndpointWebExtension.java
|
{
"start": 1492,
"end": 1645
}
|
class ____ which this Web extension relates.
* @return the endpoint class
*/
@AliasFor(annotation = EndpointExtension.class)
Class<?> endpoint();
}
|
to
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/inject/QualifierOrScopeOnInjectMethod.java
|
{
"start": 3549,
"end": 5049
}
|
class ____,
// and delete all of the other qualifiers
if (ASTHelpers.getSymbol(tree).isConstructor()) {
List<AnnotationTree> scopes = new ArrayList<>();
List<AnnotationTree> qualifiers = new ArrayList<>();
for (AnnotationTree annoTree : matchingAnnotations) {
(IS_SCOPING_ANNOTATION.matches(annoTree, state) ? scopes : qualifiers).add(annoTree);
}
ClassTree outerClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
scopes.forEach(
a -> {
fixBuilder.delete(a);
fixBuilder.prefixWith(outerClass, state.getSourceForNode(a) + " ");
});
deleteAll(qualifiers, fixBuilder);
return describeMatch(tree, fixBuilder.build());
}
// If it has a "@Provides" annotation as well as an @Inject annotation, removing the @Inject
// should be semantics-preserving (since Modules aren't generally themselves @Injected).
if (PROVIDES_METHOD.matches(tree, state)) {
deleteAll(injectAnnotations.matchingNodes(), fixBuilder);
return describeMatch(injectAnnotations.matchingNodes().getFirst(), fixBuilder.build());
}
// Don't know what else to do here, deleting is the no-op change.
deleteAll(matchingAnnotations, fixBuilder);
return describeMatch(matchingAnnotations.getFirst(), fixBuilder.build());
}
private static void deleteAll(List<AnnotationTree> scopes, SuggestedFix.Builder fixBuilder) {
scopes.forEach(fixBuilder::delete);
}
}
|
instead
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/inference/TreeInferenceModelTests.java
|
{
"start": 2060,
"end": 15314
}
|
class ____ extends ESTestCase {
private static final int NUMBER_OF_TEST_RUNS = 20;
public static TreeInferenceModel serializeFromTrainedModel(Tree tree) throws IOException {
NamedXContentRegistry registry = new NamedXContentRegistry(new MlInferenceNamedXContentProvider().getNamedXContentParsers());
TreeInferenceModel model = deserializeFromTrainedModel(tree, registry, TreeInferenceModel::fromXContent);
model.rewriteFeatureIndices(Collections.emptyMap());
return model;
}
@Override
protected NamedXContentRegistry xContentRegistry() {
List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>();
namedXContent.addAll(new MlInferenceNamedXContentProvider().getNamedXContentParsers());
namedXContent.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents());
return new NamedXContentRegistry(namedXContent);
}
public void testCtorWithNullTargetType() {
TreeInferenceModel treeInferenceModel = new TreeInferenceModel(
Collections.emptyList(),
Collections.singletonList(new TreeInferenceModel.NodeBuilder().setLeafValue(new double[] { 1.0 }).setNumberSamples(100L)),
null,
Collections.emptyList()
);
assertThat(treeInferenceModel.targetType(), equalTo(TargetType.REGRESSION));
}
public void testSerializationFromEnsemble() throws Exception {
for (int i = 0; i < NUMBER_OF_TEST_RUNS; ++i) {
Tree tree = TreeTests.createRandom(randomFrom(TargetType.values()));
assertThat(serializeFromTrainedModel(tree), is(not(nullValue())));
}
}
public void testInferenceWithoutPreparing() throws IOException {
Tree tree = TreeTests.createRandom(randomFrom(TargetType.values()));
TreeInferenceModel model = deserializeFromTrainedModel(tree, xContentRegistry(), TreeInferenceModel::fromXContent);
expectThrows(ElasticsearchException.class, () -> model.infer(Collections.emptyMap(), RegressionConfig.EMPTY_PARAMS, null));
}
public void testInferWithStump() throws IOException {
Tree.Builder builder = Tree.builder().setTargetType(TargetType.REGRESSION);
builder.setRoot(TreeNode.builder(0).setLeafValue(Collections.singletonList(42.0)));
builder.setFeatureNames(Collections.emptyList());
Tree treeObject = builder.build();
TreeInferenceModel tree = deserializeFromTrainedModel(treeObject, xContentRegistry(), TreeInferenceModel::fromXContent);
tree.rewriteFeatureIndices(Collections.emptyMap());
List<String> featureNames = Arrays.asList("foo", "bar");
List<Double> featureVector = Arrays.asList(0.6, 0.0);
Map<String, Object> featureMap = zipObjMap(featureNames, featureVector); // does not really matter as this is a stump
assertThat(
42.0,
closeTo(
((SingleValueInferenceResults) tree.infer(featureMap, RegressionConfig.EMPTY_PARAMS, Collections.emptyMap())).value(),
0.00001
)
);
}
public void testInfer() throws IOException {
// Build a tree with 2 nodes and 3 leaves using 2 features
// The leaves have unique values 0.1, 0.2, 0.3
Tree.Builder builder = Tree.builder().setTargetType(TargetType.REGRESSION);
TreeNode.Builder rootNode = builder.addJunction(0, 0, true, 0.5);
builder.addLeaf(rootNode.getRightChild(), 0.3);
TreeNode.Builder leftChildNode = builder.addJunction(rootNode.getLeftChild(), 1, true, 0.8);
builder.addLeaf(leftChildNode.getLeftChild(), 0.1);
builder.addLeaf(leftChildNode.getRightChild(), 0.2);
List<String> featureNames = Arrays.asList("foo", "bar");
Tree treeObject = builder.setFeatureNames(featureNames).build();
TreeInferenceModel tree = deserializeFromTrainedModel(treeObject, xContentRegistry(), TreeInferenceModel::fromXContent);
tree.rewriteFeatureIndices(Collections.emptyMap());
// This feature vector should hit the right child of the root node
List<Double> featureVector = Arrays.asList(0.6, 0.0);
Map<String, Object> featureMap = zipObjMap(featureNames, featureVector);
assertThat(
0.3,
closeTo(
((SingleValueInferenceResults) tree.infer(featureMap, RegressionConfig.EMPTY_PARAMS, Collections.emptyMap())).value(),
0.00001
)
);
// This should hit the left child of the left child of the root node
// i.e. it takes the path left, left
featureVector = Arrays.asList(0.3, 0.7);
featureMap = zipObjMap(featureNames, featureVector);
assertThat(
0.1,
closeTo(
((SingleValueInferenceResults) tree.infer(featureMap, RegressionConfig.EMPTY_PARAMS, Collections.emptyMap())).value(),
0.00001
)
);
// This should hit the right child of the left child of the root node
// i.e. it takes the path left, right
featureVector = Arrays.asList(0.3, 0.9);
featureMap = zipObjMap(featureNames, featureVector);
assertThat(
0.2,
closeTo(
((SingleValueInferenceResults) tree.infer(featureMap, RegressionConfig.EMPTY_PARAMS, Collections.emptyMap())).value(),
0.00001
)
);
// This should still work if the internal values are strings
List<String> featureVectorStrings = Arrays.asList("0.3", "0.9");
featureMap = zipObjMap(featureNames, featureVectorStrings);
assertThat(
0.2,
closeTo(
((SingleValueInferenceResults) tree.infer(featureMap, RegressionConfig.EMPTY_PARAMS, Collections.emptyMap())).value(),
0.00001
)
);
// This should handle missing values and take the default_left path
featureMap = Maps.newMapWithExpectedSize(2);
featureMap.put("foo", 0.3);
featureMap.put("bar", null);
assertThat(
0.1,
closeTo(
((SingleValueInferenceResults) tree.infer(featureMap, RegressionConfig.EMPTY_PARAMS, Collections.emptyMap())).value(),
0.00001
)
);
}
public void testTreeClassificationProbability() throws IOException {
// Build a tree with 2 nodes and 3 leaves using 2 features
// The leaves have unique values 0.1, 0.2, 0.3
Tree.Builder builder = Tree.builder().setTargetType(TargetType.CLASSIFICATION);
TreeNode.Builder rootNode = builder.addJunction(0, 0, true, 0.5);
builder.addLeaf(rootNode.getRightChild(), 1.0);
TreeNode.Builder leftChildNode = builder.addJunction(rootNode.getLeftChild(), 1, true, 0.8);
builder.addLeaf(leftChildNode.getLeftChild(), 1.0);
builder.addLeaf(leftChildNode.getRightChild(), 0.0);
List<String> featureNames = Arrays.asList("foo", "bar");
Tree treeObject = builder.setFeatureNames(featureNames).setClassificationLabels(Arrays.asList("cat", "dog")).build();
TreeInferenceModel tree = deserializeFromTrainedModel(treeObject, xContentRegistry(), TreeInferenceModel::fromXContent);
tree.rewriteFeatureIndices(Collections.emptyMap());
final double eps = 0.000001;
// This feature vector should hit the right child of the root node
List<Double> featureVector = Arrays.asList(0.6, 0.0);
List<Double> expectedProbs = Arrays.asList(1.0, 0.0);
List<String> expectedFields = Arrays.asList("dog", "cat");
Map<String, Object> featureMap = zipObjMap(featureNames, featureVector);
List<TopClassEntry> probabilities = ((ClassificationInferenceResults) tree.infer(
featureMap,
new ClassificationConfig(2),
Collections.emptyMap()
)).getTopClasses();
for (int i = 0; i < expectedProbs.size(); i++) {
assertThat(probabilities.get(i).getProbability(), closeTo(expectedProbs.get(i), eps));
assertThat(probabilities.get(i).getClassification(), equalTo(expectedFields.get(i)));
}
// This should hit the left child of the left child of the root node
// i.e. it takes the path left, left
featureVector = Arrays.asList(0.3, 0.7);
featureMap = zipObjMap(featureNames, featureVector);
probabilities = ((ClassificationInferenceResults) tree.infer(featureMap, new ClassificationConfig(2), Collections.emptyMap()))
.getTopClasses();
for (int i = 0; i < expectedProbs.size(); i++) {
assertThat(probabilities.get(i).getProbability(), closeTo(expectedProbs.get(i), eps));
assertThat(probabilities.get(i).getClassification(), equalTo(expectedFields.get(i)));
}
// This should handle missing values and take the default_left path
featureMap = Maps.newMapWithExpectedSize(2);
featureMap.put("foo", 0.3);
featureMap.put("bar", null);
probabilities = ((ClassificationInferenceResults) tree.infer(featureMap, new ClassificationConfig(2), Collections.emptyMap()))
.getTopClasses();
for (int i = 0; i < expectedProbs.size(); i++) {
assertThat(probabilities.get(i).getProbability(), closeTo(expectedProbs.get(i), eps));
assertThat(probabilities.get(i).getClassification(), equalTo(expectedFields.get(i)));
}
}
public void testFeatureImportance() throws IOException {
List<String> featureNames = Arrays.asList("foo", "bar");
Tree treeObject = Tree.builder()
.setFeatureNames(featureNames)
.setNodes(
TreeNode.builder(0)
.setSplitFeature(0)
.setOperator(Operator.LT)
.setLeftChild(1)
.setRightChild(2)
.setThreshold(0.5)
.setNumberSamples(4L),
TreeNode.builder(1)
.setSplitFeature(1)
.setLeftChild(3)
.setRightChild(4)
.setOperator(Operator.LT)
.setThreshold(0.5)
.setNumberSamples(2L),
TreeNode.builder(2)
.setSplitFeature(1)
.setLeftChild(5)
.setRightChild(6)
.setOperator(Operator.LT)
.setThreshold(0.5)
.setNumberSamples(2L),
TreeNode.builder(3).setLeafValue(3.0).setNumberSamples(1L),
TreeNode.builder(4).setLeafValue(8.0).setNumberSamples(1L),
TreeNode.builder(5).setLeafValue(13.0).setNumberSamples(1L),
TreeNode.builder(6).setLeafValue(18.0).setNumberSamples(1L)
)
.build();
TreeInferenceModel tree = deserializeFromTrainedModel(treeObject, xContentRegistry(), TreeInferenceModel::fromXContent);
tree.rewriteFeatureIndices(Collections.emptyMap());
double[][] featureImportance = tree.featureImportance(new double[] { 0.25, 0.25 });
final double eps = 1.0E-8;
assertThat(featureImportance[0][0], closeTo(-5.0, eps));
assertThat(featureImportance[1][0], closeTo(-2.5, eps));
featureImportance = tree.featureImportance(new double[] { 0.25, 0.75 });
assertThat(featureImportance[0][0], closeTo(-5.0, eps));
assertThat(featureImportance[1][0], closeTo(2.5, eps));
featureImportance = tree.featureImportance(new double[] { 0.75, 0.25 });
assertThat(featureImportance[0][0], closeTo(5.0, eps));
assertThat(featureImportance[1][0], closeTo(-2.5, eps));
featureImportance = tree.featureImportance(new double[] { 0.75, 0.75 });
assertThat(featureImportance[0][0], closeTo(5.0, eps));
assertThat(featureImportance[1][0], closeTo(2.5, eps));
}
public void testMinAndMaxBoundaries() throws IOException {
Tree.Builder builder = Tree.builder().setTargetType(TargetType.REGRESSION);
TreeNode.Builder rootNode = builder.addJunction(0, 0, true, 0.5);
builder.addLeaf(rootNode.getRightChild(), 0.3);
TreeNode.Builder leftChildNode = builder.addJunction(rootNode.getLeftChild(), 1, true, 0.8);
builder.addLeaf(leftChildNode.getLeftChild(), 0.1);
builder.addLeaf(leftChildNode.getRightChild(), 0.2);
List<String> featureNames = Arrays.asList("foo", "bar");
Tree treeObject = builder.setFeatureNames(featureNames).build();
TreeInferenceModel tree = deserializeFromTrainedModel(treeObject, xContentRegistry(), TreeInferenceModel::fromXContent);
tree.rewriteFeatureIndices(Collections.emptyMap());
assertThat(tree.getMinPredictedValue(), equalTo(0.1));
assertThat(tree.getMaxPredictedValue(), equalTo(0.3));
}
private static Map<String, Object> zipObjMap(List<String> keys, List<? extends Object> values) {
return IntStream.range(0, keys.size()).boxed().collect(Collectors.toMap(keys::get, values::get));
}
}
|
TreeInferenceModelTests
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/StreamingMultiJoinOperatorFactory.java
|
{
"start": 1937,
"end": 4589
}
|
class ____ extends AbstractStreamOperatorFactory<RowData>
implements Serializable {
private static final long serialVersionUID = 1L;
private final List<InternalTypeInfo<RowData>> inputTypeInfos;
private final List<JoinInputSideSpec> inputSideSpecs;
private final List<FlinkJoinType> joinTypes;
private final MultiJoinCondition multiJoinCondition;
private final long[] stateRetentionTime;
private final GeneratedJoinCondition[] joinConditions;
private final JoinKeyExtractor keyExtractor;
private final Map<Integer, List<ConditionAttributeRef>> joinAttributeMap;
public StreamingMultiJoinOperatorFactory(
final List<InternalTypeInfo<RowData>> inputTypeInfos,
final List<JoinInputSideSpec> inputSideSpecs,
final List<FlinkJoinType> joinTypes,
@Nullable final MultiJoinCondition multiJoinCondition,
final long[] stateRetentionTime,
final GeneratedJoinCondition[] joinConditions,
final JoinKeyExtractor keyExtractor,
final Map<Integer, List<ConditionAttributeRef>> joinAttributeMap) {
this.inputTypeInfos = inputTypeInfos;
this.inputSideSpecs = inputSideSpecs;
this.joinTypes = joinTypes;
this.multiJoinCondition = multiJoinCondition;
this.stateRetentionTime = stateRetentionTime;
this.joinConditions = joinConditions;
this.keyExtractor = keyExtractor;
this.joinAttributeMap = joinAttributeMap;
}
@Override
public <T extends StreamOperator<RowData>> T createStreamOperator(
final StreamOperatorParameters<RowData> parameters) {
final var inputRowTypes =
inputTypeInfos.stream()
.map(InternalTypeInfo::toRowType)
.collect(Collectors.toList());
final StreamingMultiJoinOperator operator =
new StreamingMultiJoinOperator(
parameters,
inputRowTypes,
inputSideSpecs,
joinTypes,
multiJoinCondition,
stateRetentionTime,
joinConditions,
keyExtractor,
joinAttributeMap);
@SuppressWarnings("unchecked")
final T castedOperator = (T) operator;
return castedOperator;
}
@Override
public Class<? extends StreamOperator<RowData>> getStreamOperatorClass(
final ClassLoader classLoader) {
return StreamingMultiJoinOperator.class;
}
}
|
StreamingMultiJoinOperatorFactory
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/over/RowTimeRowsUnboundedPrecedingFunctionTest.java
|
{
"start": 1392,
"end": 2517
}
|
class ____ extends RowTimeOverWindowTestBase {
@Test
void testLateRecordMetrics() throws Exception {
RowTimeRowsUnboundedPrecedingFunction<RowData> function =
new RowTimeRowsUnboundedPrecedingFunction<>(
1000, 2000, aggsHandleFunction, accTypes, inputFieldTypes, 2);
KeyedProcessOperator<RowData, RowData, RowData> operator =
new KeyedProcessOperator<>(function);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.open();
Counter counter = function.getCounter();
// put some records
testHarness.processElement(insertRecord("key", 1L, 100L));
testHarness.processElement(insertRecord("key", 1L, 100L));
testHarness.processElement(insertRecord("key", 1L, 500L));
testHarness.processWatermark(new Watermark(500L));
// late record
testHarness.processElement(insertRecord("key", 1L, 400L));
assertThat(counter.getCount()).isEqualTo(1L);
}
}
|
RowTimeRowsUnboundedPrecedingFunctionTest
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/reflect/InvokableTest.java
|
{
"start": 6416,
"end": 6463
}
|
interface ____ {}
private abstract static
|
Tested
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java
|
{
"start": 27973,
"end": 28935
}
|
class ____ extends UpdatableSqlQuery<Customer> {
public CustomerUpdateQuery(DataSource ds) {
super(ds, SELECT_ID_FORENAME_WHERE_ID);
declareParameter(new SqlParameter(Types.NUMERIC));
compile();
}
@Override
protected Customer updateRow(ResultSet rs, int rownum, @Nullable Map<? ,?> context)
throws SQLException {
rs.updateString(2, "" + context.get(rs.getInt(COLUMN_NAMES[0])));
return null;
}
}
CustomerUpdateQuery query = new CustomerUpdateQuery(dataSource);
Map<Integer, String> values = new HashMap<>(2);
values.put(1, "Rod");
values.put(2, "Thomas");
query.execute(2, values);
verify(resultSet).updateString(2, "Rod");
verify(resultSet).updateString(2, "Thomas");
verify(resultSet, times(2)).updateRow();
verify(preparedStatement).setObject(1, 2, Types.NUMERIC);
verify(resultSet).close();
verify(preparedStatement).close();
verify(connection).close();
}
private static
|
CustomerUpdateQuery
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregationStrategyBeanAdapterRefMethodNameTest.java
|
{
"start": 1022,
"end": 2107
}
|
class ____ extends ContextTestSupport {
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("myAppender", new AggregationStrategyBeanAdapterRefMethodNameTest.MyBodyAppender());
return jndi;
}
@Test
public void testAggregate() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("ABC");
template.sendBody("direct:start", "A");
template.sendBody("direct:start", "B");
template.sendBody("direct:start", "C");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").aggregate(constant(true)).aggregationStrategy("myAppender")
.aggregationStrategyMethodName("append").completionSize(3).to("mock:result");
}
};
}
public static final
|
AggregationStrategyBeanAdapterRefMethodNameTest
|
java
|
apache__spark
|
sql/api/src/main/java/org/apache/spark/sql/types/Geography.java
|
{
"start": 1139,
"end": 2439
}
|
class ____.
protected final byte[] value;
protected final int srid;
// We make the constructor private. We should use `fromWKB` to create new instances.
private Geography(byte[] value, int srid) {
this.value = value;
this.srid = srid;
}
// We provide `getBytes` and `fromBytes` methods to access GEOGRAPHY data.
public byte[] getBytes() {
return value;
}
public int getSrid() {
return srid;
}
// Default SRID value for the Geography client class.
public static final int DEFAULT_SRID = 4326;
// Factory methods to create new Geography instances from WKB bytes and optional SRID.
public static Geography fromWKB(byte[] bytes, int srid) {
return new Geography(bytes, srid);
}
public static Geography fromWKB(byte[] bytes) {
return new Geography(bytes, DEFAULT_SRID);
}
// Overrides for `equals` and `hashCode` methods.
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Geography other = (Geography) obj;
return srid == other.srid && java.util.Arrays.equals(value, other.value);
}
@Override
public int hashCode() {
return 31 * Arrays.hashCode(value) + Integer.hashCode(srid);
}
}
|
itself
|
java
|
spring-projects__spring-boot
|
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/LocalHttpClientTransportTests.java
|
{
"start": 1225,
"end": 2703
}
|
class ____ {
@Test
void createWhenDockerHostIsFileReturnsTransport(@TempDir Path tempDir) throws IOException {
String socketFilePath = Files.createTempFile(tempDir, "remote-transport", null).toAbsolutePath().toString();
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(new DockerConnectionConfiguration.Host(socketFilePath));
LocalHttpClientTransport transport = LocalHttpClientTransport.create(dockerHost);
assertThat(transport).isNotNull();
assertThat(transport.getHost().toHostString()).isEqualTo(socketFilePath);
}
@Test
void createWhenDockerHostIsFileThatDoesNotExistReturnsTransport(@TempDir Path tempDir) {
String socketFilePath = Paths.get(tempDir.toString(), "dummy").toAbsolutePath().toString();
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(new DockerConnectionConfiguration.Host(socketFilePath));
LocalHttpClientTransport transport = LocalHttpClientTransport.create(dockerHost);
assertThat(transport).isNotNull();
assertThat(transport.getHost().toHostString()).isEqualTo(socketFilePath);
}
@Test
void createWhenDockerHostIsAddressReturnsTransport() {
ResolvedDockerHost dockerHost = ResolvedDockerHost
.from(new DockerConnectionConfiguration.Host("tcp://192.168.1.2:2376"));
LocalHttpClientTransport transport = LocalHttpClientTransport.create(dockerHost);
assertThat(transport).isNotNull();
assertThat(transport.getHost().toHostString()).isEqualTo("tcp://192.168.1.2:2376");
}
}
|
LocalHttpClientTransportTests
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/cglib/proxy/Enhancer.java
|
{
"start": 13707,
"end": 14012
}
|
class ____ necessary and uses the specified
* callbacks (if any) to create a new object instance.
* Uses the no-arg constructor of the superclass.
* @return a new instance
*/
public Object create() {
classOnly = false;
argumentTypes = null;
return createHelper();
}
/**
* Generate a new
|
if
|
java
|
google__dagger
|
dagger-compiler/main/java/dagger/internal/codegen/binding/LegacyBindingGraphFactory.java
|
{
"start": 7779,
"end": 10811
}
|
class ____ {
private final Resolver resolver;
private final ImmutableList<LegacyBindingGraph> resolvedSubgraphs;
private final ComponentNode componentNode;
LegacyBindingGraph(Resolver resolver, ImmutableList<LegacyBindingGraph> resolvedSubgraphs) {
this.resolver = resolver;
this.resolvedSubgraphs = resolvedSubgraphs;
this.componentNode =
ComponentNodeImpl.create(resolver.componentPath, resolver.componentDescriptor);
}
/** Returns the {@link ComponentNode} associated with this binding graph. */
public ComponentNode componentNode() {
return componentNode;
}
/** Returns the {@link ComponentPath} associated with this binding graph. */
public ComponentPath componentPath() {
return resolver.componentPath;
}
/** Returns the {@link ComponentDescriptor} associated with this binding graph. */
public ComponentDescriptor componentDescriptor() {
return resolver.componentDescriptor;
}
/**
* Returns the {@link LegacyResolvedBindings} in this graph or a parent graph that matches the
* given request.
*
* <p>An exception is thrown if there are no resolved bindings found for the request; however,
* this should never happen since all dependencies should have been resolved at this point.
*/
public LegacyResolvedBindings resolvedBindings(BindingRequest request) {
return request.isRequestKind(RequestKind.MEMBERS_INJECTION)
? resolver.getResolvedMembersInjectionBindings(request.key())
: resolver.getResolvedContributionBindings(request.key());
}
/**
* Returns all {@link LegacyResolvedBindings} for the given request.
*
* <p>Note that this only returns the bindings resolved in this component. Bindings resolved in
* parent components are not included.
*/
public Iterable<LegacyResolvedBindings> resolvedBindings() {
// Don't return an immutable collection - this is only ever used for looping over all bindings
// in the graph. Copying is wasteful, especially if is a hashing collection, since the values
// should all, by definition, be distinct.
return Iterables.concat(
resolver.resolvedMembersInjectionBindings.values(),
resolver.resolvedContributionBindings.values());
}
/** Returns the resolved subgraphs. */
public ImmutableList<LegacyBindingGraph> subgraphs() {
return resolvedSubgraphs;
}
}
/**
* The collection of bindings that have been resolved for a key. For valid graphs, contains
* exactly one binding.
*
* <p>Separate {@link LegacyResolvedBindings} instances should be used if a {@link
* MembersInjectionBinding} and a {@link ProvisionBinding} for the same key exist in the same
* component. (This will only happen if a type has an {@code @Inject} constructor and members, the
* component has a members injection method, and the type is also requested normally.)
*/
@AutoValue
abstract static
|
LegacyBindingGraph
|
java
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/annotation/mapping/NonNullProducingMapper.java
|
{
"start": 269,
"end": 720
}
|
class ____ implements TypedAnnotationMapper<NonNullStereotyped> {
@Override
public List<AnnotationValue<?>> map(AnnotationValue<NonNullStereotyped> annotation, VisitorContext visitorContext) {
return Collections.singletonList(AnnotationValue.builder("jakarta.annotation.Nullable").build());
}
@Override
public Class<NonNullStereotyped> annotationType() {
return NonNullStereotyped.class;
}
}
|
NonNullProducingMapper
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/refaster/UWildcardType.java
|
{
"start": 1019,
"end": 1847
}
|
class ____ extends UType {
public static UWildcardType create(BoundKind boundKind, UType bound) {
return new AutoValue_UWildcardType(boundKind, bound);
}
/** This corresponds to a plain ? wildcard. */
public static UWildcardType create() {
return create(BoundKind.UNBOUND, UClassType.create("java.lang.Object"));
}
abstract BoundKind boundKind();
abstract UType bound();
@Override
public Choice<Unifier> visitWildcardType(WildcardType wildcard, Unifier unifier) {
return Choice.condition(boundKind().equals(wildcard.kind), unifier)
.flatMap(unifications(bound(), wildcard.type));
}
@Override
public Type inline(Inliner inliner) throws CouldNotResolveImportException {
return new WildcardType(bound().inline(inliner), boundKind(), inliner.symtab().boundClass);
}
}
|
UWildcardType
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Olingo4EndpointBuilderFactory.java
|
{
"start": 29524,
"end": 40239
}
|
interface ____
extends
EndpointConsumerBuilder {
default Olingo4EndpointConsumerBuilder basic() {
return (Olingo4EndpointConsumerBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option is a:
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option will be converted to a
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder pollStrategy(String pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* Custom HTTP async client builder for more complex HTTP client
* configuration, overrides connectionTimeout, socketTimeout, proxy and
* sslContext. Note that a socketTimeout MUST be specified in the
* builder, otherwise OData requests could block indefinitely.
*
* The option is a:
* <code>org.apache.http.impl.nio.client.HttpAsyncClientBuilder</code>
* type.
*
* Group: advanced
*
* @param httpAsyncClientBuilder the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder httpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder httpAsyncClientBuilder) {
doSetProperty("httpAsyncClientBuilder", httpAsyncClientBuilder);
return this;
}
/**
* Custom HTTP async client builder for more complex HTTP client
* configuration, overrides connectionTimeout, socketTimeout, proxy and
* sslContext. Note that a socketTimeout MUST be specified in the
* builder, otherwise OData requests could block indefinitely.
*
* The option will be converted to a
* <code>org.apache.http.impl.nio.client.HttpAsyncClientBuilder</code>
* type.
*
* Group: advanced
*
* @param httpAsyncClientBuilder the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder httpAsyncClientBuilder(String httpAsyncClientBuilder) {
doSetProperty("httpAsyncClientBuilder", httpAsyncClientBuilder);
return this;
}
/**
* Custom HTTP client builder for more complex HTTP client
* configuration, overrides connectionTimeout, socketTimeout, proxy and
* sslContext. Note that a socketTimeout MUST be specified in the
* builder, otherwise OData requests could block indefinitely.
*
* The option is a:
* <code>org.apache.http.impl.client.HttpClientBuilder</code> type.
*
* Group: advanced
*
* @param httpClientBuilder the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder httpClientBuilder(org.apache.http.impl.client.HttpClientBuilder httpClientBuilder) {
doSetProperty("httpClientBuilder", httpClientBuilder);
return this;
}
/**
* Custom HTTP client builder for more complex HTTP client
* configuration, overrides connectionTimeout, socketTimeout, proxy and
* sslContext. Note that a socketTimeout MUST be specified in the
* builder, otherwise OData requests could block indefinitely.
*
* The option will be converted to a
* <code>org.apache.http.impl.client.HttpClientBuilder</code> type.
*
* Group: advanced
*
* @param httpClientBuilder the value to set
* @return the dsl builder
*/
default AdvancedOlingo4EndpointConsumerBuilder httpClientBuilder(String httpClientBuilder) {
doSetProperty("httpClientBuilder", httpClientBuilder);
return this;
}
}
/**
* Builder for endpoint producers for the Olingo4 component.
*/
public
|
AdvancedOlingo4EndpointConsumerBuilder
|
java
|
apache__camel
|
core/camel-management/src/test/java/org/apache/camel/management/MyManagedBean.java
|
{
"start": 1082,
"end": 1598
}
|
class ____ {
private int camelsSeenCount;
public String doSomething(String body) {
if (body.contains("Camel")) {
camelsSeenCount++;
}
return "Managed " + body;
}
@ManagedAttribute(description = "How many Camels Have been Seen")
public int getCamelsSeenCount() {
return camelsSeenCount;
}
@ManagedOperation(description = "Set Camels Seen Count to Zero")
public void resetCamelsSeenCount() {
camelsSeenCount = 0;
}
}
|
MyManagedBean
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableRefCountTest.java
|
{
"start": 1771,
"end": 22854
}
|
class ____ extends RxJavaTest {
@Test
public void refCountAsync() throws InterruptedException {
// Flaky
for (int i = 0; i < 10; i++) {
try {
refCountAsyncActual();
return;
} catch (AssertionError ex) {
if (i == 9) {
throw ex;
}
Thread.sleep((int)(200 * (Math.random() * 10 + 1)));
}
}
}
/**
* Tries to coordinate async counting but it is flaky due to the low 10s of milliseconds.
*/
void refCountAsyncActual() {
final AtomicInteger subscribeCount = new AtomicInteger();
final AtomicInteger nextCount = new AtomicInteger();
Flowable<Long> r = Flowable.interval(0, 20, TimeUnit.MILLISECONDS)
.doOnSubscribe(new Consumer<Subscription>() {
@Override
public void accept(Subscription s) {
subscribeCount.incrementAndGet();
}
})
.doOnNext(new Consumer<Long>() {
@Override
public void accept(Long l) {
nextCount.incrementAndGet();
}
})
.publish().refCount();
final AtomicInteger receivedCount = new AtomicInteger();
Disposable d1 = r.subscribe(new Consumer<Long>() {
@Override
public void accept(Long l) {
receivedCount.incrementAndGet();
}
});
Disposable d2 = r.subscribe();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
for (;;) {
int a = nextCount.get();
int b = receivedCount.get();
if (a > 10 && a < 20 && a == b) {
break;
}
if (a >= 20) {
break;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
// give time to emit
// now unsubscribe
d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other
d1.dispose();
System.out.println("onNext: " + nextCount.get());
// should emit once for both subscribers
assertEquals(nextCount.get(), receivedCount.get());
// only 1 subscribe
assertEquals(1, subscribeCount.get());
}
@Test
public void refCountSynchronous() {
final AtomicInteger subscribeCount = new AtomicInteger();
final AtomicInteger nextCount = new AtomicInteger();
Flowable<Integer> r = Flowable.just(1, 2, 3, 4, 5, 6, 7, 8, 9)
.doOnSubscribe(new Consumer<Subscription>() {
@Override
public void accept(Subscription s) {
subscribeCount.incrementAndGet();
}
})
.doOnNext(new Consumer<Integer>() {
@Override
public void accept(Integer l) {
nextCount.incrementAndGet();
}
})
.publish().refCount();
final AtomicInteger receivedCount = new AtomicInteger();
Disposable d1 = r.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer l) {
receivedCount.incrementAndGet();
}
});
Disposable d2 = r.subscribe();
// give time to emit
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
// now unsubscribe
d2.dispose(); // unsubscribe s2 first as we're counting in 1 and there can be a race between unsubscribe and one subscriber getting a value but not the other
d1.dispose();
System.out.println("onNext Count: " + nextCount.get());
// it will emit twice because it is synchronous
assertEquals(nextCount.get(), receivedCount.get() * 2);
// it will subscribe twice because it is synchronous
assertEquals(2, subscribeCount.get());
}
@Test
public void refCountSynchronousTake() {
final AtomicInteger nextCount = new AtomicInteger();
Flowable<Integer> r = Flowable.just(1, 2, 3, 4, 5, 6, 7, 8, 9)
.doOnNext(new Consumer<Integer>() {
@Override
public void accept(Integer l) {
System.out.println("onNext --------> " + l);
nextCount.incrementAndGet();
}
})
.take(4)
.publish().refCount();
final AtomicInteger receivedCount = new AtomicInteger();
r.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer l) {
receivedCount.incrementAndGet();
}
});
System.out.println("onNext: " + nextCount.get());
assertEquals(4, receivedCount.get());
assertEquals(4, receivedCount.get());
}
@Test
public void repeat() {
final AtomicInteger subscribeCount = new AtomicInteger();
final AtomicInteger unsubscribeCount = new AtomicInteger();
Flowable<Long> r = Flowable.interval(0, 1, TimeUnit.MILLISECONDS)
.doOnSubscribe(new Consumer<Subscription>() {
@Override
public void accept(Subscription s) {
System.out.println("******************************* Subscribe received");
// when we are subscribed
subscribeCount.incrementAndGet();
}
})
.doOnCancel(new Action() {
@Override
public void run() {
System.out.println("******************************* Unsubscribe received");
// when we are unsubscribed
unsubscribeCount.incrementAndGet();
}
})
.publish().refCount();
for (int i = 0; i < 10; i++) {
TestSubscriber<Long> ts1 = new TestSubscriber<>();
TestSubscriber<Long> ts2 = new TestSubscriber<>();
r.subscribe(ts1);
r.subscribe(ts2);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ts1.cancel();
ts2.cancel();
ts1.assertNoErrors();
ts2.assertNoErrors();
assertTrue(ts1.values().size() > 0);
assertTrue(ts2.values().size() > 0);
}
assertEquals(10, subscribeCount.get());
assertEquals(10, unsubscribeCount.get());
}
@Test
public void connectUnsubscribe() throws InterruptedException {
final CountDownLatch unsubscribeLatch = new CountDownLatch(1);
final CountDownLatch subscribeLatch = new CountDownLatch(1);
Flowable<Long> f = synchronousInterval()
.doOnSubscribe(new Consumer<Subscription>() {
@Override
public void accept(Subscription s) {
System.out.println("******************************* Subscribe received");
// when we are subscribed
subscribeLatch.countDown();
}
})
.doOnCancel(new Action() {
@Override
public void run() {
System.out.println("******************************* Unsubscribe received");
// when we are unsubscribed
unsubscribeLatch.countDown();
}
});
TestSubscriberEx<Long> s = new TestSubscriberEx<>();
f.publish().refCount().subscribeOn(Schedulers.newThread()).subscribe(s);
System.out.println("send unsubscribe");
// wait until connected
subscribeLatch.await();
// now unsubscribe
s.cancel();
System.out.println("DONE sending unsubscribe ... now waiting");
if (!unsubscribeLatch.await(3000, TimeUnit.MILLISECONDS)) {
System.out.println("Errors: " + s.errors());
if (s.errors().size() > 0) {
s.errors().get(0).printStackTrace();
}
fail("timed out waiting for unsubscribe");
}
s.assertNoErrors();
}
@Test
public void connectUnsubscribeRaceConditionLoop() throws InterruptedException {
for (int i = 0; i < 100; i++) {
connectUnsubscribeRaceCondition();
}
}
@Test
public void connectUnsubscribeRaceCondition() throws InterruptedException {
final AtomicInteger subUnsubCount = new AtomicInteger();
Flowable<Long> f = synchronousInterval()
.doOnCancel(new Action() {
@Override
public void run() {
System.out.println("******************************* Unsubscribe received");
// when we are unsubscribed
subUnsubCount.decrementAndGet();
}
})
.doOnSubscribe(new Consumer<Subscription>() {
@Override
public void accept(Subscription s) {
System.out.println("******************************* SUBSCRIBE received");
subUnsubCount.incrementAndGet();
}
});
TestSubscriberEx<Long> s = new TestSubscriberEx<>();
f.publish().refCount().subscribeOn(Schedulers.computation()).subscribe(s);
System.out.println("send unsubscribe");
// now immediately unsubscribe while subscribeOn is racing to subscribe
s.cancel();
// this generally will mean it won't even subscribe as it is already unsubscribed by the time connect() gets scheduled
// give time to the counter to update
Thread.sleep(10);
// either we subscribed and then unsubscribed, or we didn't ever even subscribe
assertEquals(0, subUnsubCount.get());
System.out.println("DONE sending unsubscribe ... now waiting");
System.out.println("Errors: " + s.errors());
if (s.errors().size() > 0) {
s.errors().get(0).printStackTrace();
}
s.assertNoErrors();
}
private Flowable<Long> synchronousInterval() {
return Flowable.unsafeCreate(new Publisher<Long>() {
@Override
public void subscribe(Subscriber<? super Long> subscriber) {
final AtomicBoolean cancel = new AtomicBoolean();
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
cancel.set(true);
}
});
for (;;) {
if (cancel.get()) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
subscriber.onNext(1L);
}
}
});
}
@Test
public void onlyFirstShouldSubscribeAndLastUnsubscribe() {
final AtomicInteger subscriptionCount = new AtomicInteger();
final AtomicInteger unsubscriptionCount = new AtomicInteger();
Flowable<Integer> flowable = Flowable.unsafeCreate(new Publisher<Integer>() {
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
subscriptionCount.incrementAndGet();
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
unsubscriptionCount.incrementAndGet();
}
});
}
});
Flowable<Integer> refCounted = flowable.publish().refCount();
Disposable first = refCounted.subscribe();
assertEquals(1, subscriptionCount.get());
Disposable second = refCounted.subscribe();
assertEquals(1, subscriptionCount.get());
first.dispose();
assertEquals(0, unsubscriptionCount.get());
second.dispose();
assertEquals(1, unsubscriptionCount.get());
}
@Test
public void refCount() {
TestScheduler s = new TestScheduler();
Flowable<Long> interval = Flowable.interval(100, TimeUnit.MILLISECONDS, s).publish().refCount();
// subscribe list1
final List<Long> list1 = new ArrayList<>();
Disposable d1 = interval.subscribe(new Consumer<Long>() {
@Override
public void accept(Long t1) {
list1.add(t1);
}
});
s.advanceTimeBy(200, TimeUnit.MILLISECONDS);
assertEquals(2, list1.size());
assertEquals(0L, list1.get(0).longValue());
assertEquals(1L, list1.get(1).longValue());
// subscribe list2
final List<Long> list2 = new ArrayList<>();
Disposable d2 = interval.subscribe(new Consumer<Long>() {
@Override
public void accept(Long t1) {
list2.add(t1);
}
});
s.advanceTimeBy(300, TimeUnit.MILLISECONDS);
// list 1 should have 5 items
assertEquals(5, list1.size());
assertEquals(2L, list1.get(2).longValue());
assertEquals(3L, list1.get(3).longValue());
assertEquals(4L, list1.get(4).longValue());
// list 2 should only have 3 items
assertEquals(3, list2.size());
assertEquals(2L, list2.get(0).longValue());
assertEquals(3L, list2.get(1).longValue());
assertEquals(4L, list2.get(2).longValue());
// unsubscribe list1
d1.dispose();
// advance further
s.advanceTimeBy(300, TimeUnit.MILLISECONDS);
// list 1 should still have 5 items
assertEquals(5, list1.size());
// list 2 should have 6 items
assertEquals(6, list2.size());
assertEquals(5L, list2.get(3).longValue());
assertEquals(6L, list2.get(4).longValue());
assertEquals(7L, list2.get(5).longValue());
// unsubscribe list2
d2.dispose();
// advance further
s.advanceTimeBy(1000, TimeUnit.MILLISECONDS);
// subscribing a new one should start over because the source should have been unsubscribed
// subscribe list3
final List<Long> list3 = new ArrayList<>();
interval.subscribe(new Consumer<Long>() {
@Override
public void accept(Long t1) {
list3.add(t1);
}
});
s.advanceTimeBy(200, TimeUnit.MILLISECONDS);
assertEquals(2, list3.size());
assertEquals(0L, list3.get(0).longValue());
assertEquals(1L, list3.get(1).longValue());
}
@Test
public void alreadyUnsubscribedClient() {
Subscriber<Integer> done = CancelledSubscriber.INSTANCE;
Subscriber<Integer> subscriber = TestHelper.mockSubscriber();
Flowable<Integer> result = Flowable.just(1).publish().refCount();
result.subscribe(done);
result.subscribe(subscriber);
verify(subscriber).onNext(1);
verify(subscriber).onComplete();
verify(subscriber, never()).onError(any(Throwable.class));
}
@Test
public void alreadyUnsubscribedInterleavesWithClient() {
ReplayProcessor<Integer> source = ReplayProcessor.create();
Subscriber<Integer> done = CancelledSubscriber.INSTANCE;
Subscriber<Integer> subscriber = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber);
Flowable<Integer> result = source.publish().refCount();
result.subscribe(subscriber);
source.onNext(1);
result.subscribe(done);
source.onNext(2);
source.onComplete();
inOrder.verify(subscriber).onNext(1);
inOrder.verify(subscriber).onNext(2);
inOrder.verify(subscriber).onComplete();
verify(subscriber, never()).onError(any(Throwable.class));
}
@Test
public void connectDisconnectConnectAndSubjectState() {
Flowable<Integer> f1 = Flowable.just(10);
Flowable<Integer> f2 = Flowable.just(20);
Flowable<Integer> combined = Flowable.combineLatest(f1, f2, new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2) {
return t1 + t2;
}
})
.publish().refCount();
TestSubscriberEx<Integer> ts1 = new TestSubscriberEx<>();
TestSubscriberEx<Integer> ts2 = new TestSubscriberEx<>();
combined.subscribe(ts1);
combined.subscribe(ts2);
ts1.assertTerminated();
ts1.assertNoErrors();
ts1.assertValue(30);
ts2.assertTerminated();
ts2.assertNoErrors();
ts2.assertValue(30);
}
@Test
public void upstreamErrorAllowsRetry() throws InterruptedException {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
final AtomicInteger intervalSubscribed = new AtomicInteger();
Flowable<String> interval =
Flowable.interval(200, TimeUnit.MILLISECONDS)
.doOnSubscribe(new Consumer<Subscription>() {
@Override
public void accept(Subscription s) {
System.out.println("Subscribing to interval " + intervalSubscribed.incrementAndGet());
}
}
)
.flatMap(new Function<Long, Publisher<String>>() {
@Override
public Publisher<String> apply(Long t1) {
return Flowable.defer(new Supplier<Publisher<String>>() {
@Override
public Publisher<String> get() {
return Flowable.<String>error(new TestException("Some exception"));
}
});
}
})
.onErrorResumeNext(new Function<Throwable, Publisher<String>>() {
@Override
public Publisher<String> apply(Throwable t1) {
return Flowable.error(t1);
}
})
.publish()
.refCount();
interval
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t1) {
System.out.println("Subscriber 1 onError: " + t1);
}
})
.retry(5)
.subscribe(new Consumer<String>() {
@Override
public void accept(String t1) {
System.out.println("Subscriber 1: " + t1);
}
});
Thread.sleep(100);
interval
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t1) {
System.out.println("Subscriber 2 onError: " + t1);
}
})
.retry(5)
.subscribe(new Consumer<String>() {
@Override
public void accept(String t1) {
System.out.println("Subscriber 2: " + t1);
}
});
Thread.sleep(1300);
System.out.println(intervalSubscribed.get());
assertEquals(6, intervalSubscribed.get());
TestHelper.assertError(errors, 0, OnErrorNotImplementedException.class);
} finally {
RxJavaPlugins.reset();
}
}
private
|
FlowableRefCountTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/data/ExponentialHistogramScratch.java
|
{
"start": 558,
"end": 748
}
|
class ____ {
final BytesRef bytesRefScratch = new BytesRef();
final CompressedExponentialHistogram reusedHistogram = new CompressedExponentialHistogram();
}
|
ExponentialHistogramScratch
|
java
|
apache__avro
|
lang/java/avro/src/main/java/org/apache/avro/util/springframework/ConcurrentReferenceHashMap.java
|
{
"start": 32656,
"end": 33339
}
|
class ____<K, V> extends WeakReference<Entry<K, V>> implements Reference<K, V> {
private final int hash;
@Nullable
private final Reference<K, V> nextReference;
public WeakEntryReference(Entry<K, V> entry, int hash, @Nullable Reference<K, V> next,
ReferenceQueue<Entry<K, V>> queue) {
super(entry, queue);
this.hash = hash;
this.nextReference = next;
}
@Override
public int getHash() {
return this.hash;
}
@Override
@Nullable
public Reference<K, V> getNext() {
return this.nextReference;
}
@Override
public void release() {
enqueue();
clear();
}
}
}
|
WeakEntryReference
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configuration/DeferHttpSessionJavaConfigTests.java
|
{
"start": 2793,
"end": 3264
}
|
class ____ {
@Bean
Service service() {
return new Service();
}
@Bean
DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().permitAll()
)
.sessionManagement((sessions) -> sessions
.requireExplicitAuthenticationStrategy(true)
);
// @formatter:on
return http.build();
}
}
public static
|
DeferHttpSessionConfig
|
java
|
spring-projects__spring-security
|
test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsJwtTests.java
|
{
"start": 2686,
"end": 7346
}
|
class ____ {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
@Mock
private GrantedAuthority authority1;
@Mock
private GrantedAuthority authority2;
@BeforeEach
public void setup() {
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(this.repository);
MockServletContext servletContext = new MockServletContext();
servletContext.setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN,
new FilterChainProxy(new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, filter)));
this.request = new MockHttpServletRequest(servletContext);
WebTestUtils.setSecurityContextRepository(this.request, this.repository);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void jwtWhenUsingDefaultsThenProducesDefaultJwtAuthentication() {
jwt().postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
assertThat(token.getAuthorities()).isNotEmpty();
assertThat(token.getToken()).isNotNull();
assertThat(token.getToken().getSubject()).isEqualTo("user");
assertThat(token.getToken().getHeaders()).containsEntry("alg", "none");
}
@Test
public void jwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() {
String name = new String("user");
jwt().jwt((jwt) -> jwt.subject(name)).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
assertThat(token.getToken().getSubject()).isSameAs(name);
}
@Test
public void jwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() {
jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
.authorities(this.authority1, this.authority2)
.postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1,
this.authority2);
}
@Test
public void jwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() {
jwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities")).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities())
.containsOnly(new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
}
@Test
public void jwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() {
jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
.authorities((jwt) -> Arrays.asList(this.authority1))
.postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1);
}
@Test
public void jwtWhenProvidingPreparedJwtThenUsesItForAuthentication() {
Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build();
jwt().jwt(originalToken).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user");
assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token");
assertThat(retrievedToken.getToken().getHeaders()).containsEntry("header1", "value1");
}
}
|
SecurityMockMvcRequestPostProcessorsJwtTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/downsample/src/main/java/org/elasticsearch/xpack/downsample/DownsampleShardPersistentTaskExecutor.java
|
{
"start": 14681,
"end": 15966
}
|
class ____ extends TransportAction<Request, ActionResponse.Empty> {
private final Client client;
private final IndicesService indicesService;
private final DownsampleMetrics downsampleMetrics;
@Inject
public TA(
TransportService transportService,
ActionFilters actionFilters,
Client client,
IndicesService indicesService,
DownsampleMetrics downsampleMetrics
) {
// TODO: consider moving to Downsample.DOWSAMPLE_TASK_THREAD_POOL_NAME and simplify realNodeOperation
super(NAME, actionFilters, transportService.getTaskManager(), EsExecutors.DIRECT_EXECUTOR_SERVICE);
this.client = client;
this.indicesService = indicesService;
this.downsampleMetrics = downsampleMetrics;
}
@Override
protected void doExecute(Task t, Request request, ActionListener<ActionResponse.Empty> listener) {
realNodeOperation(client, indicesService, downsampleMetrics, request.task, request.params, request.lastDownsampleTsid);
listener.onResponse(ActionResponse.Empty.INSTANCE);
}
}
}
}
|
TA
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/serializer/ErrorGetterTest.java
|
{
"start": 485,
"end": 604
}
|
class ____ {
public int getValue() {
throw new UnsupportedOperationException();
}
}
}
|
Model
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/predicate/operator/arithmetic/Mul.java
|
{
"start": 1130,
"end": 3975
}
|
class ____ extends EsqlArithmeticOperation implements BinaryComparisonInversible {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Mul", Mul::new);
@FunctionInfo(
operator = "*",
returnType = { "double", "integer", "long", "unsigned_long" },
description = "Multiply two numbers together. "
+ "If either field is <<esql-multivalued-fields,multivalued>> then the result is `null`."
)
public Mul(
Source source,
@Param(name = "lhs", description = "A numeric value.", type = { "double", "integer", "long", "unsigned_long" }) Expression left,
@Param(name = "rhs", description = "A numeric value.", type = { "double", "integer", "long", "unsigned_long" }) Expression right
) {
super(
source,
left,
right,
MUL,
MulIntsEvaluator.Factory::new,
MulLongsEvaluator.Factory::new,
MulUnsignedLongsEvaluator.Factory::new,
MulDoublesEvaluator.Factory::new
);
}
private Mul(StreamInput in) throws IOException {
super(
in,
MUL,
MulIntsEvaluator.Factory::new,
MulLongsEvaluator.Factory::new,
MulUnsignedLongsEvaluator.Factory::new,
MulDoublesEvaluator.Factory::new
);
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
public ArithmeticOperationFactory binaryComparisonInverse() {
return Div::new;
}
@Override
protected boolean isCommutative() {
return true;
}
@Override
public Mul swapLeftAndRight() {
return new Mul(source(), right(), left());
}
@Override
protected NodeInfo<Mul> info() {
return NodeInfo.create(this, Mul::new, left(), right());
}
@Override
protected Mul replaceChildren(Expression left, Expression right) {
return new Mul(source(), left, right);
}
@Evaluator(extraName = "Ints", warnExceptions = { ArithmeticException.class })
static int processInts(int lhs, int rhs) {
return Math.multiplyExact(lhs, rhs);
}
@Evaluator(extraName = "Longs", warnExceptions = { ArithmeticException.class })
static long processLongs(long lhs, long rhs) {
return Math.multiplyExact(lhs, rhs);
}
@Evaluator(extraName = "UnsignedLongs", warnExceptions = { ArithmeticException.class })
static long processUnsignedLongs(long lhs, long rhs) {
return unsignedLongMultiplyExact(lhs, rhs);
}
@Evaluator(extraName = "Doubles", warnExceptions = { ArithmeticException.class })
static double processDoubles(double lhs, double rhs) {
return NumericUtils.asFiniteNumber(lhs * rhs);
}
}
|
Mul
|
java
|
apache__camel
|
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
|
{
"start": 191372,
"end": 193412
}
|
class ____ extends YamlDeserializerBase<CustomServiceCallServiceFilterConfiguration> {
public CustomServiceCallServiceFilterConfigurationDeserializer() {
super(CustomServiceCallServiceFilterConfiguration.class);
}
@Override
protected CustomServiceCallServiceFilterConfiguration newInstance() {
return new CustomServiceCallServiceFilterConfiguration();
}
@Override
protected boolean setProperty(CustomServiceCallServiceFilterConfiguration target,
String propertyKey, String propertyName, Node node) {
propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey);
switch(propertyKey) {
case "id": {
String val = asText(node);
target.setId(val);
break;
}
case "properties": {
java.util.List<org.apache.camel.model.PropertyDefinition> val = asFlatList(node, org.apache.camel.model.PropertyDefinition.class);
target.setProperties(val);
break;
}
case "ref": {
String val = asText(node);
target.setServiceFilterRef(val);
break;
}
default: {
return false;
}
}
return true;
}
}
@YamlType(
nodes = "customTransformer",
types = org.apache.camel.model.transformer.CustomTransformerDefinition.class,
order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1,
displayName = "Custom Transformer",
description = "To use a custom transformer on a route level.",
deprecated = false,
properties = {
@YamlProperty(name = "className", type = "string", description = "Set a
|
CustomServiceCallServiceFilterConfigurationDeserializer
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ReturnValueIgnoredTest.java
|
{
"start": 21801,
"end": 22684
}
|
class ____ {",
" void f() throws Exception {",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" Integer.reverse(2);",
" // BUG: Diagnostic contains: ReturnValueIgnored",
" new Integer(2).doubleValue();",
// We ignore the following "parsing" style methods:
" Integer.decode(\"1985\");",
" Integer.parseInt(\"1985\");",
" Integer.parseInt(\"1985\", 10);",
" Integer.parseUnsignedInt(\"1985\");",
" Integer.parseUnsignedInt(\"1985\", 10);",
" Integer.valueOf(\"1985\");",
" Integer.valueOf(\"1985\", 10);",
" }",
"}")
.doTest();
}
@Test
public void constructors() {
compilationHelper
.addSourceLines(
"Test.java",
"
|
Test
|
java
|
apache__dubbo
|
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/AdaptiveClientStreamFactory.java
|
{
"start": 1602,
"end": 2393
}
|
class ____ implements ClientStreamFactory {
@Override
public ClientStream createClientStream(
AbstractConnectionClient client,
FrameworkModel frameworkModel,
Executor executor,
TripleClientCall clientCall,
TripleWriteQueue writeQueue) {
if (client instanceof AutoSwitchConnectionClient) {
Channel channel = client.getChannel(true);
if (((AutoSwitchConnectionClient) client).isHttp3Connected()) {
return new Http3TripleClientStream(frameworkModel, executor, channel, clientCall, writeQueue);
}
return new Http2TripleClientStream(frameworkModel, executor, channel, clientCall, writeQueue);
}
return null;
}
}
|
AdaptiveClientStreamFactory
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
|
{
"start": 51098,
"end": 51854
}
|
class ____ implements PathMatcher {
@Override
public boolean isPattern(String path) {
return false;
}
@Override
public boolean match(String pattern, String path) {
return path.matches(pattern);
}
@Override
public boolean matchStart(String pattern, String path) {
return false;
}
@Override
public String extractPathWithinPattern(String pattern, String path) {
return null;
}
@Override
public Map<String, String> extractUriTemplateVariables(String pattern, String path) {
return null;
}
@Override
public Comparator<String> getPatternComparator(String path) {
return null;
}
@Override
public String combine(String pattern1, String pattern2) {
return null;
}
}
public static
|
TestPathMatcher
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/compositefk/OneToManyNestedEmbeddedIdTest.java
|
{
"start": 2936,
"end": 3849
}
|
class ____ {
@EmbeddedId
private ParentEntityIdWrapper parentEntityIdWrapper;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_entity_id", referencedColumnName = "id")
private List<ChildEntity> childEntities;
public ParentEntity() {
}
public ParentEntity(ParentEntityIdWrapper parentEntityIdWrapper, List<ChildEntity> childEntities) {
this.parentEntityIdWrapper = parentEntityIdWrapper;
this.childEntities = childEntities;
}
public ParentEntityIdWrapper getParentEntityIdWrapper() {
return parentEntityIdWrapper;
}
public void setParentEntityIdWrapper(ParentEntityIdWrapper parentEntityIdWrapper) {
this.parentEntityIdWrapper = parentEntityIdWrapper;
}
public List<ChildEntity> getChildEntities() {
return childEntities;
}
public void setChildEntities(List<ChildEntity> childEntities) {
this.childEntities = childEntities;
}
}
}
|
ParentEntity
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/creators/TwoCreators4602Test.java
|
{
"start": 754,
"end": 1469
}
|
class ____ {
private final List<String> list;
private final InnerBean4602 inner;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Bean4602(@JsonProperty("list") List<String> list, @JsonProperty("inner") InnerBean4602 inner) {
this.list = list;
this.inner = inner;
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
private static Bean4602 of(final List<String> list) {
return new Bean4602(list, new InnerBean4602("default"));
}
public List<String> getList() {
return list;
}
public InnerBean4602 getInner() {
return inner;
}
}
static
|
Bean4602
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/AbstractPersonResource.java
|
{
"start": 126,
"end": 470
}
|
class ____ {
@Path("abstract-with-security")
@GET
public Person abstractPerson() {
Person person = new Person();
person.setFirst("Bob");
person.setLast("Builder");
person.setAddress("10 Downing St");
person.setBirthDate("November 30, 1874");
return person;
}
}
|
AbstractPersonResource
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/refaster/ImportPolicy.java
|
{
"start": 7313,
"end": 9247
}
|
class ____'re refactoring
inliner.addImport(fullyQualifiedClazz.toString());
}
String simpleName = fullyQualifiedClazz.toString();
simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1);
return inliner.maker().Ident(inliner.asName(simpleName));
}
@Override
public JCExpression staticReference(
Inliner inliner,
CharSequence topLevelClazz,
CharSequence fullyQualifiedClazz,
CharSequence member) {
if (Refaster.class.getName().contentEquals(topLevelClazz)) {
// Special handling to ensure that the pretty-printer always recognizes Refaster references
return inliner
.maker()
.Select(inliner.maker().Ident(inliner.asName("Refaster")), inliner.asName(member));
}
return inliner
.maker()
.Select(
classReference(inliner, topLevelClazz, fullyQualifiedClazz), inliner.asName(member));
}
},
/**
* When inlining static methods, always static import the method. Non-static references to classes
* are imported from the top level as in {@code IMPORT_TOP_LEVEL}.
*/
STATIC_IMPORT_ALWAYS {
@Override
public JCExpression classReference(
Inliner inliner, CharSequence topLevelClazz, CharSequence fullyQualifiedClazz) {
return IMPORT_TOP_LEVEL.classReference(inliner, topLevelClazz, fullyQualifiedClazz);
}
@Override
public JCExpression staticReference(
Inliner inliner,
CharSequence topLevelClazz,
CharSequence fullyQualifiedClazz,
CharSequence member) {
if (Refaster.class.getName().contentEquals(topLevelClazz)) {
// Special handling to ensure that the pretty-printer always recognizes Refaster references
return inliner
.maker()
.Select(inliner.maker().Ident(inliner.asName("Refaster")), inliner.asName(member));
}
// Foo.
|
we
|
java
|
micronaut-projects__micronaut-core
|
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsDisabledByDefaultTest.java
|
{
"start": 3285,
"end": 3499
}
|
class ____ implements HttpHostResolver {
@Override
public String resolve(@Nullable HttpRequest request) {
return "https://micronautexample.com";
}
}
}
|
HttpHostResolverReplacement
|
java
|
spring-projects__spring-framework
|
spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AbstractCacheOperationTests.java
|
{
"start": 1219,
"end": 2917
}
|
class ____<O extends JCacheOperation<?>> extends AbstractJCacheTests {
protected final SampleObject sampleInstance = new SampleObject();
protected abstract O createSimpleOperation();
@Test
void simple() {
O operation = createSimpleOperation();
assertThat(operation.getCacheName()).as("Wrong cache name").isEqualTo("simpleCache");
assertThat(operation.getAnnotations()).singleElement().isEqualTo(operation.getCacheAnnotation());
assertThat(operation.getCacheResolver()).as("cache resolver should be set").isNotNull();
}
protected void assertCacheInvocationParameter(CacheInvocationParameter actual, Class<?> targetType,
Object value, int position) {
assertThat(actual.getRawType()).as("wrong parameter type for " + actual).isEqualTo(targetType);
assertThat(actual.getValue()).as("wrong parameter value for " + actual).isEqualTo(value);
assertThat(actual.getParameterPosition()).as("wrong parameter position for " + actual).isEqualTo(position);
}
protected <A extends Annotation> CacheMethodDetails<A> create(Class<A> annotationType,
Class<?> targetType, String methodName,
Class<?>... parameterTypes) {
Method method = ReflectionUtils.findMethod(targetType, methodName, parameterTypes);
Assert.notNull(method, () -> "requested method '" + methodName + "'does not exist");
A cacheAnnotation = method.getAnnotation(annotationType);
return new DefaultCacheMethodDetails<>(method, cacheAnnotation, getCacheName(cacheAnnotation));
}
private static String getCacheName(Annotation annotation) {
Object cacheName = AnnotationUtils.getValue(annotation, "cacheName");
return (cacheName != null ? cacheName.toString() : "test");
}
}
|
AbstractCacheOperationTests
|
java
|
apache__avro
|
lang/java/maven-plugin/src/main/java/org/apache/avro/mojo/AbstractAvroMojo.java
|
{
"start": 7904,
"end": 8264
}
|
class ____ of custom
* {@link org.apache.avro.Conversion} implementations to add to the compiler.
* The classes must be on the classpath at compile time and whenever the Java
* objects are serialized.
*
* @parameter property="customConversions"
*/
protected String[] customConversions = new String[0];
/**
* A set of fully qualified
|
names
|
java
|
apache__camel
|
components/camel-cometd/src/test/java/org/apache/camel/component/cometd/SslContextParametersCometdProducerConsumerTest.java
|
{
"start": 1523,
"end": 3631
}
|
class ____ extends CamelTestSupport {
private int port;
private String uri;
@Test
void testProducer() {
Person person = new Person("David", "Greco");
template.requestBody("direct:input", person);
MockEndpoint ep = context.getEndpoint("mock:test", MockEndpoint.class);
List<Exchange> exchanges = ep.getReceivedExchanges();
for (Exchange exchange : exchanges) {
Person person1 = (Person) exchange.getIn().getBody();
assertEquals("David", person1.getName());
assertEquals("Greco", person1.getSurname());
}
}
@Override
public void doPreSetup() {
port = AvailablePortFinder.getNextAvailable();
uri = "cometds://127.0.0.1:" + port + "/service/test?baseResource=file:./target/test-classes/webapp&"
+ "timeout=240000&interval=0&maxInterval=30000&multiFrameInterval=1500&jsonCommented=true&logLevel=2";
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("jsse/localhost.p12");
ksp.setPassword("changeit");
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyPassword("changeit");
kmp.setKeyStore(ksp);
TrustManagersParameters tmp = new TrustManagersParameters();
tmp.setKeyStore(ksp);
SSLContextParameters sslContextParameters = new SSLContextParameters();
sslContextParameters.setKeyManagers(kmp);
sslContextParameters.setTrustManagers(tmp);
CometdComponent component = (CometdComponent) context.getComponent("cometds");
component.setSslContextParameters(sslContextParameters);
from("direct:input").to(uri);
from(uri).to("mock:test");
}
};
}
public static
|
SslContextParametersCometdProducerConsumerTest
|
java
|
google__guava
|
android/guava/src/com/google/common/collect/LinkedListMultimap.java
|
{
"start": 25533,
"end": 27256
}
|
class ____ extends AbstractSequentialList<Entry<K, V>> {
@Override
public int size() {
return size;
}
@Override
public ListIterator<Entry<K, V>> listIterator(int index) {
return new NodeIterator(index);
}
}
return new EntriesImpl();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
Map<K, Collection<V>> createAsMap() {
return new Multimaps.AsMap<>(this);
}
/**
* @serialData the number of distinct keys, and then for each distinct key: the first key, the
* number of values for that key, and the key's values, followed by successive keys and values
* from the entries() ordering
*/
@GwtIncompatible
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
for (Entry<K, V> entry : entries()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
@GwtIncompatible
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyToKeyList = CompactLinkedHashMap.create();
int size = stream.readInt();
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeObject
K key = (K) stream.readObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
V value = (V) stream.readObject();
put(key, value);
}
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
|
EntriesImpl
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/MDCAsyncTest.java
|
{
"start": 2781,
"end": 4081
}
|
class ____ implements AsyncProcessor {
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);
MyAsyncProcessor() {
// submit a Runnable that does nothing just to initialise the
// threads
EXECUTOR.submit(new Runnable() {
@Override
public void run() {
// do nothing
}
});
}
@Override
public void process(Exchange exchange) {
throw new RuntimeCamelException("This processor does not support the sync pattern.");
}
@Override
public CompletableFuture<Exchange> processAsync(Exchange exchange) {
AsyncCallbackToCompletableFutureAdapter<Exchange> callback
= new AsyncCallbackToCompletableFutureAdapter<>(exchange);
process(exchange, callback);
return callback.getFuture();
}
@Override
public boolean process(Exchange exchange, final AsyncCallback callback) {
EXECUTOR.submit(() -> callback.done(false));
return false;
}
}
/**
* Stores values from the first invocation to compare them with the second invocation later.
*/
private static
|
MyAsyncProcessor
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/mapper/flattened/FlattenedSortedSetDocValuesSyntheticFieldLoader.java
|
{
"start": 1000,
"end": 4418
}
|
class ____ implements SourceLoader.SyntheticFieldLoader {
private final String fieldFullPath;
private final String keyedFieldFullPath;
private final String keyedIgnoredValuesFieldFullPath;
private final String leafName;
private DocValuesFieldValues docValues = NO_VALUES;
private List<Object> ignoredValues = List.of();
/**
* Build a loader for flattened fields from doc values.
*
* @param fieldFullPath full path to the original field
* @param keyedFieldFullPath full path to the keyed field to load doc values from
* @param keyedIgnoredValuesFieldFullPath full path to the keyed field that stores values that are not present in doc values
* due to ignore_above
* @param leafName the name of the leaf field to use in the rendered {@code _source}
*/
FlattenedSortedSetDocValuesSyntheticFieldLoader(
String fieldFullPath,
String keyedFieldFullPath,
@Nullable String keyedIgnoredValuesFieldFullPath,
String leafName
) {
this.fieldFullPath = fieldFullPath;
this.keyedFieldFullPath = keyedFieldFullPath;
this.keyedIgnoredValuesFieldFullPath = keyedIgnoredValuesFieldFullPath;
this.leafName = leafName;
}
@Override
public String fieldName() {
return fieldFullPath;
}
@Override
public Stream<Map.Entry<String, StoredFieldLoader>> storedFieldLoaders() {
if (keyedIgnoredValuesFieldFullPath == null) {
return Stream.empty();
}
return Stream.of(Map.entry(keyedIgnoredValuesFieldFullPath, (values) -> {
ignoredValues = new ArrayList<>();
ignoredValues.addAll(values);
}));
}
@Override
public DocValuesLoader docValuesLoader(LeafReader reader, int[] docIdsInLeaf) throws IOException {
final SortedSetDocValues dv = DocValues.getSortedSet(reader, keyedFieldFullPath);
if (dv.getValueCount() == 0) {
docValues = NO_VALUES;
return null;
}
final FlattenedFieldDocValuesLoader loader = new FlattenedFieldDocValuesLoader(dv);
docValues = loader;
return loader;
}
@Override
public boolean hasValue() {
return docValues.count() > 0 || ignoredValues.isEmpty() == false;
}
@Override
public void write(XContentBuilder b) throws IOException {
if (docValues.count() == 0 && ignoredValues.isEmpty()) {
return;
}
FlattenedFieldSyntheticWriterHelper.SortedKeyedValues sortedKeyedValues = new DocValuesSortedKeyedValues(docValues);
if (ignoredValues.isEmpty() == false) {
var ignoredValuesSet = new TreeSet<BytesRef>();
for (Object value : ignoredValues) {
ignoredValuesSet.add((BytesRef) value);
}
ignoredValues = List.of();
sortedKeyedValues = new DocValuesWithIgnoredSortedKeyedValues(sortedKeyedValues, ignoredValuesSet);
}
var writer = new FlattenedFieldSyntheticWriterHelper(sortedKeyedValues);
b.startObject(leafName);
writer.write(b);
b.endObject();
}
@Override
public void reset() {
ignoredValues = List.of();
}
private
|
FlattenedSortedSetDocValuesSyntheticFieldLoader
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client-jaxb/runtime/src/main/java/io/quarkus/rest/client/reactive/jaxb/runtime/ClientJaxbMessageBodyReader.java
|
{
"start": 703,
"end": 2677
}
|
class ____ implements MessageBodyReader<Object> {
@Inject
Unmarshaller unmarshaller;
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws WebApplicationException, IOException {
return doReadFrom(type, entityStream);
}
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return isReadable(mediaType, type);
}
protected boolean isReadable(MediaType mediaType, Class<?> type) {
if (mediaType == null) {
return false;
}
if (String.class.equals(type)) { // don't attempt to read plain strings
return false;
}
String subtype = mediaType.getSubtype();
boolean isCorrectMediaType = "application".equals(mediaType.getType()) || "text".equals(mediaType.getType());
return (isCorrectMediaType && "xml".equalsIgnoreCase(subtype) || subtype.endsWith("+xml"))
|| (mediaType.isWildcardSubtype() && (mediaType.isWildcardType() || isCorrectMediaType));
}
private Object doReadFrom(Class<Object> type, InputStream entityStream) throws IOException {
if (isInputStreamEmpty(entityStream)) {
return null;
}
return unmarshal(entityStream, type);
}
protected Object unmarshal(InputStream entityStream, Class<Object> type) {
try {
JAXBElement<Object> item = unmarshaller.unmarshal(new StreamSource(entityStream), type);
return item.getValue();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
private boolean isInputStreamEmpty(InputStream entityStream) throws IOException {
return StreamUtil.isEmpty(entityStream) || entityStream.available() == 0;
}
}
|
ClientJaxbMessageBodyReader
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
|
{
"start": 49262,
"end": 49794
}
|
class ____ implements Runnable {
private final CompletableFuture<?> future;
private final String timeoutMsg;
private Timeout(CompletableFuture<?> future, @Nullable String timeoutMsg) {
this.future = checkNotNull(future);
this.timeoutMsg = timeoutMsg;
}
@Override
public void run() {
future.completeExceptionally(new TimeoutException(timeoutMsg));
}
}
/**
* Delay scheduler used to timeout futures.
*
* <p>This
|
Timeout
|
java
|
apache__flink
|
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/rest/SqlGatewayRestEndpointTest.java
|
{
"start": 1926,
"end": 8582
}
|
class ____ {
private static final String ADDRESS1 = "123.123.123.123";
private static final String ADDRESS2 = "123.123.123.144";
private static final String BIND_ADDRESS1 = "023.023.023.023";
private static final String BIND_ADDRESS2 = "023.023.023.333";
private static final String BIND_PORT1 = "7282";
private static final String BIND_PORT2 = "7444";
private static final String PORT1 = "7661";
private static final String PORT2 = "7662";
public static final String SQL_GATEWAY_ADDRESS =
getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.ADDRESS.key());
public static final String SQL_GATEWAY_BIND_ADDRESS =
getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.BIND_ADDRESS.key());
public static final String SQL_GATEWAY_BIND_PORT =
getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.BIND_PORT.key());
public static final String SQL_GATEWAY_PORT =
getSqlGatewayRestOptionFullName(SqlGatewayRestOptions.PORT.key());
/**
* Test {@link SqlGatewayRestEndpoint} uses its own options when there are both runtime options
* and sql gateway options in the delegating configuration.
*/
@Test
void testIfSqlGatewayRestEndpointUseOverrideOptions() throws ConfigurationException {
Configuration flinkConfig = new Configuration();
flinkConfig.setString(RestOptions.ADDRESS.key(), ADDRESS1);
flinkConfig.setString(RestOptions.BIND_ADDRESS.key(), BIND_ADDRESS1);
flinkConfig.setString(RestOptions.BIND_PORT.key(), BIND_PORT1);
flinkConfig.setString(RestOptions.PORT.key(), PORT1);
flinkConfig.setString(SQL_GATEWAY_ADDRESS, ADDRESS2);
flinkConfig.setString(SQL_GATEWAY_BIND_ADDRESS, BIND_ADDRESS2);
flinkConfig.setString(SQL_GATEWAY_BIND_PORT, BIND_PORT2);
flinkConfig.setString(SQL_GATEWAY_PORT, PORT2);
Configuration sqlGatewayRestEndpointConfig = getBaseConfig(flinkConfig);
final RestServerEndpointConfiguration result =
RestServerEndpointConfiguration.fromConfiguration(sqlGatewayRestEndpointConfig);
assertThat(result.getRestAddress()).isEqualTo(ADDRESS2);
assertThat(result.getRestBindAddress()).isEqualTo(BIND_ADDRESS2);
assertThat(result.getRestBindPortRange()).isEqualTo(BIND_PORT2);
}
/** Test {@link SqlGatewayRestEndpoint} uses fallback options correctly. */
@Test
void testFallbackOptions() throws ConfigurationException {
Configuration flinkConfig = new Configuration();
flinkConfig.setString(SQL_GATEWAY_ADDRESS, ADDRESS2);
RestServerEndpointConfiguration result1 =
RestServerEndpointConfiguration.fromConfiguration(getBaseConfig(flinkConfig));
// Test bind-port get the default value
assertThat(result1.getRestBindPortRange()).isEqualTo("8083");
// Test bind-port fallback to port
flinkConfig.setString(SQL_GATEWAY_PORT, PORT2);
result1 = RestServerEndpointConfiguration.fromConfiguration(getBaseConfig(flinkConfig));
assertThat(result1.getRestBindPortRange()).isEqualTo(PORT2);
}
/** Test {@link SqlGatewayRestEndpoint} uses required options correctly. */
@Test
void testRequiredOptions() throws ConfigurationException {
// Empty options
Configuration flinkConfig1 = new Configuration();
SqlGatewayEndpointFactoryUtils.DefaultEndpointFactoryContext context =
new SqlGatewayEndpointFactoryUtils.DefaultEndpointFactoryContext(
null, flinkConfig1, getEndpointConfig(flinkConfig1, IDENTIFIER));
SqlGatewayEndpointFactoryUtils.EndpointFactoryHelper endpointFactoryHelper =
SqlGatewayEndpointFactoryUtils.createEndpointFactoryHelper(
new SqlGatewayRestEndpointFactory(), context);
assertThatThrownBy(endpointFactoryHelper::validate).isInstanceOf(ValidationException.class);
// Only ADDRESS
flinkConfig1.setString(SQL_GATEWAY_ADDRESS, ADDRESS2);
RestServerEndpointConfiguration result =
RestServerEndpointConfiguration.fromConfiguration(getBaseConfig(flinkConfig1));
assertThat(result.getRestAddress()).isEqualTo(ADDRESS2);
// Only BIND PORT
Configuration flinkConfig2 = new Configuration();
flinkConfig2.setString(SQL_GATEWAY_BIND_PORT, BIND_PORT2);
context =
new SqlGatewayEndpointFactoryUtils.DefaultEndpointFactoryContext(
null, flinkConfig2, getEndpointConfig(flinkConfig2, IDENTIFIER));
endpointFactoryHelper =
SqlGatewayEndpointFactoryUtils.createEndpointFactoryHelper(
new SqlGatewayRestEndpointFactory(), context);
assertThatThrownBy(endpointFactoryHelper::validate).isInstanceOf(ValidationException.class);
// Only PORT
Configuration flinkConfig3 = new Configuration();
flinkConfig3.setString(SQL_GATEWAY_PORT, PORT2);
context =
new SqlGatewayEndpointFactoryUtils.DefaultEndpointFactoryContext(
null, flinkConfig3, getEndpointConfig(flinkConfig3, IDENTIFIER));
endpointFactoryHelper =
SqlGatewayEndpointFactoryUtils.createEndpointFactoryHelper(
new SqlGatewayRestEndpointFactory(), context);
assertThatThrownBy(endpointFactoryHelper::validate).isInstanceOf(ValidationException.class);
// ADDRESS and PORT
flinkConfig1.setString(SQL_GATEWAY_PORT, PORT2);
result = RestServerEndpointConfiguration.fromConfiguration(getBaseConfig(flinkConfig1));
assertThat(result.getRestAddress()).isEqualTo(ADDRESS2);
assertThat(result.getRestBindPortRange()).isEqualTo(PORT2);
// ADDRESS and PORT and BIND PORT
flinkConfig1.setString(SQL_GATEWAY_BIND_PORT, BIND_PORT2);
result = RestServerEndpointConfiguration.fromConfiguration(getBaseConfig(flinkConfig1));
assertThat(result.getRestAddress()).isEqualTo(ADDRESS2);
assertThat(result.getRestBindPortRange()).isEqualTo(BIND_PORT2);
// ADDRESS and BIND PORT
Configuration flinkConfig4 = new Configuration();
flinkConfig4.setString(SQL_GATEWAY_ADDRESS, ADDRESS2);
flinkConfig4.setString(SQL_GATEWAY_BIND_PORT, BIND_PORT2);
result = RestServerEndpointConfiguration.fromConfiguration(getBaseConfig(flinkConfig1));
assertThat(result.getRestAddress()).isEqualTo(ADDRESS2);
assertThat(result.getRestBindPortRange()).isEqualTo(BIND_PORT2);
}
}
|
SqlGatewayRestEndpointTest
|
java
|
grpc__grpc-java
|
rls/src/main/java/io/grpc/rls/RlsProtoData.java
|
{
"start": 1665,
"end": 2350
}
|
enum ____ {
/** Unused. */
REASON_UNKNOWN,
/** No data available in local cache. */
REASON_MISS,
/** Data in local cache is stale. */
REASON_STALE;
}
/** Reason for making this request. */
abstract Reason reason();
/** Returns a map of key values extracted via key builders for the gRPC or HTTP request. */
abstract ImmutableMap<String, String> keyMap();
static RouteLookupRequest create(ImmutableMap<String, String> keyMap, Reason reason) {
return new AutoValue_RlsProtoData_RouteLookupRequest(reason, keyMap);
}
}
/** A response from route lookup service. */
@AutoValue
@Immutable
abstract static
|
Reason
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/filter/Filter_being_condition_Test.java
|
{
"start": 1033,
"end": 1708
}
|
class ____ extends WithPlayerData {
private PotentialMvpCondition potentialMvp = new PotentialMvpCondition();
@Test
void should_filter_iterable_elements_satisfying_condition() {
Iterable<Player> potentialMvpPlayers = filter(players).being(potentialMvp).get();
assertThat(potentialMvpPlayers).containsOnly(jordan);
// players is not modified
assertThat(players).hasSize(4);
}
@Test
void should_fail_if_filter_condition_is_null() {
assertThatIllegalArgumentException().isThrownBy(() -> filter(players).being(null))
.withMessage("The filter condition should not be null");
}
}
|
Filter_being_condition_Test
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/proxy/pojo/bytebuddy/ByteBuddyProxyFactory.java
|
{
"start": 663,
"end": 3940
}
|
class ____ implements ProxyFactory, Serializable {
private final ByteBuddyProxyHelper byteBuddyProxyHelper;
private Class<?> persistentClass;
private String entityName;
private Class<?>[] interfaces;
private Method getIdentifierMethod;
private Method setIdentifierMethod;
private CompositeType componentIdType;
private boolean overridesEquals;
private Class<?> proxyClass;
public ByteBuddyProxyFactory(ByteBuddyProxyHelper byteBuddyProxyHelper) {
this.byteBuddyProxyHelper = byteBuddyProxyHelper;
}
@Override
public void postInstantiate(
String entityName,
Class<?> persistentClass,
Set<Class<?>> interfaces,
Method getIdentifierMethod,
Method setIdentifierMethod,
CompositeType componentIdType) throws HibernateException {
this.entityName = entityName;
this.persistentClass = persistentClass;
this.interfaces = toArray( interfaces );
this.getIdentifierMethod = getIdentifierMethod;
this.setIdentifierMethod = setIdentifierMethod;
this.componentIdType = componentIdType;
this.overridesEquals = ReflectHelper.overridesEquals( persistentClass );
this.proxyClass = byteBuddyProxyHelper.buildProxy( persistentClass, this.interfaces );
}
private Class<?>[] toArray(Set<Class<?>> interfaces) {
return interfaces == null ? EMPTY_CLASS_ARRAY : interfaces.toArray(EMPTY_CLASS_ARRAY);
}
@Override
public HibernateProxy getProxy(
Object id,
SharedSessionContractImplementor session) throws HibernateException {
final var interceptor = new ByteBuddyInterceptor(
entityName,
persistentClass,
interfaces,
id,
getIdentifierMethod,
setIdentifierMethod,
componentIdType,
session,
overridesEquals
);
final var instance = getHibernateProxy();
final var proxyConfiguration = instance.asProxyConfiguration();
if ( proxyConfiguration == null ) {
throw new HibernateException( "Produced proxy does not correctly implement ProxyConfiguration" );
}
proxyConfiguration.$$_hibernate_set_interceptor( interceptor );
return instance;
}
private HibernateProxy getHibernateProxy() {
final var internal = getHibernateProxyInternal();
final var hibernateProxy = internal.asHibernateProxy();
if ( hibernateProxy == null ) {
throw new HibernateException( "Produced proxy does not correctly implement HibernateProxy" );
}
return hibernateProxy;
}
/**
* This technically returns a HibernateProxy, but declaring that type as the return
* type for the newInstance() action triggers an implicit case of type pollution.
* We therefore declare it as PrimeAmongSecondarySupertypes, and require the
* invoker to perform the narrowing
*/
private PrimeAmongSecondarySupertypes getHibernateProxyInternal() throws HibernateException {
try {
return (PrimeAmongSecondarySupertypes) proxyClass.getConstructor().newInstance();
}
catch (NoSuchMethodException e) {
throw new HibernateException(
"Bytecode enhancement failed because no public, protected or package-private default constructor was found for entity '"
+ entityName + "' (private constructors don't work with runtime proxies)", e );
}
catch (Throwable t) {
throw new HibernateException( "Bytecode enhancement failed for entity '" + entityName + "'", t );
}
}
}
|
ByteBuddyProxyFactory
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/refaster/TemplatingTest.java
|
{
"start": 18763,
"end": 19707
}
|
class ____ {",
" public void example(int from, int to) {",
" for (int i = from; i < to;) {",
" }",
" }",
"}");
assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
.isEqualTo(
BlockTemplate.create(
ImmutableMap.of(
"from", UPrimitiveType.INT,
"to", UPrimitiveType.INT),
UForLoop.create(
ImmutableList.of(
UVariableDecl.create(
"i", UPrimitiveTypeTree.INT, UFreeIdent.create("from"))),
UBinary.create(
Kind.LESS_THAN, ULocalVarIdent.create("i"), UFreeIdent.create("to")),
ImmutableList.<UExpressionStatement>of(),
UBlock.create())));
}
@Test
public void forLoopNoCondition() {
compile(
"
|
ForLoopExample
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/TransportAnalyzeIndexDiskUsageAction.java
|
{
"start": 2436,
"end": 4208
}
|
class ____ extends TransportBroadcastAction<
AnalyzeIndexDiskUsageRequest,
AnalyzeIndexDiskUsageResponse,
AnalyzeDiskUsageShardRequest,
AnalyzeDiskUsageShardResponse> {
public static final ActionType<AnalyzeIndexDiskUsageResponse> TYPE = new ActionType<>("indices:admin/analyze_disk_usage");
private final IndicesService indicesService;
private final ProjectResolver projectResolver;
private final ThreadPool threadPool;
@Inject
public TransportAnalyzeIndexDiskUsageAction(
ClusterService clusterService,
TransportService transportService,
IndicesService indexServices,
ActionFilters actionFilters,
ProjectResolver projectResolver,
IndexNameExpressionResolver indexNameExpressionResolver
) {
super(
TYPE.name(),
clusterService,
transportService,
actionFilters,
indexNameExpressionResolver,
AnalyzeIndexDiskUsageRequest::new,
AnalyzeDiskUsageShardRequest::new,
transportService.getThreadPool().executor(ThreadPool.Names.ANALYZE)
);
this.indicesService = indexServices;
this.projectResolver = projectResolver;
this.threadPool = transportService.getThreadPool();
}
@Override
protected void doExecute(Task task, AnalyzeIndexDiskUsageRequest request, ActionListener<AnalyzeIndexDiskUsageResponse> listener) {
new LimitingRequestPerNodeBroadcastAction(task, request, listener, 5).start();
}
private record ShardRequest(
DiscoveryNode node,
AnalyzeDiskUsageShardRequest shardRequest,
ActionListener<AnalyzeDiskUsageShardResponse> handler
) {
}
final
|
TransportAnalyzeIndexDiskUsageAction
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/IrateFloatAggregator.java
|
{
"start": 2651,
"end": 3225
}
|
class ____ {
static final long BASE_RAM_USAGE = RamUsageEstimator.sizeOfObject(FloatIrateState.class);
long lastTimestamp;
long secondLastTimestamp = -1;
float lastValue;
float secondLastValue;
boolean hasSecond;
FloatIrateState(long lastTimestamp, float lastValue) {
this.lastTimestamp = lastTimestamp;
this.lastValue = lastValue;
this.hasSecond = false;
}
long bytesUsed() {
return BASE_RAM_USAGE;
}
}
public static final
|
FloatIrateState
|
java
|
apache__camel
|
components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/integration/operations/HashicorpProducerListSecretsIT.java
|
{
"start": 1364,
"end": 3657
}
|
class ____ extends HashicorpVaultBase {
@EndpointInject("mock:result-write")
private MockEndpoint mockWrite;
@EndpointInject("mock:result-list")
private MockEndpoint mockRead;
@Test
public void createSecretTest() throws InterruptedException {
mockWrite.expectedMessageCount(2);
mockRead.expectedMessageCount(1);
Exchange exchange = template.request("direct:createSecret", new Processor() {
@Override
public void process(Exchange exchange) {
HashMap map = new HashMap();
map.put("integer", "30");
exchange.getIn().setBody(map);
}
});
exchange = template.request("direct:createSecret", new Processor() {
@Override
public void process(Exchange exchange) {
HashMap map = new HashMap();
map.put("secret", "30");
exchange.getIn().setBody(map);
}
});
exchange = template.request("direct:listSecrets", new Processor() {
@Override
public void process(Exchange exchange) {
}
});
MockEndpoint.assertIsSatisfied(context);
Exchange ret = mockRead.getExchanges().get(0);
assertNotNull(ret);
assertTrue(ret.getMessage().getBody(List.class).contains("test"));
assertEquals(1, ret.getMessage().getBody(List.class).size());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:createSecret")
.toF("hashicorp-vault://secret?operation=createSecret&token=RAW(%s)&host=%s&port=%s&scheme=http&secretPath=test",
service.token(), service.host(), service.port())
.to("mock:result-write");
from("direct:listSecrets")
.toF("hashicorp-vault://secret?operation=listSecrets&token=RAW(%s)&host=%s&port=%s&scheme=http&secretPath=test",
service.token(), service.host(), service.port())
.to("mock:result-list");
}
};
}
}
|
HashicorpProducerListSecretsIT
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/stat/JdbcResultSetStatMBean.java
|
{
"start": 705,
"end": 937
}
|
interface ____ {
long getHoldMillisTotal();
long getFetchRowCount();
long getOpenCount();
long getCloseCount();
int getOpeningCount();
int getOpeningMax();
long getErrorCount();
}
|
JdbcResultSetStatMBean
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/arm-java/org/apache/hadoop/ipc/protobuf/ProtobufRpcEngineProtos.java
|
{
"start": 15611,
"end": 15896
}
|
class ____ the called method
* </pre>
*/
public boolean hasClientProtocolVersion() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required uint64 clientProtocolVersion = 3;</code>
*
* <pre>
** protocol version of
|
declaring
|
java
|
elastic__elasticsearch
|
server/src/internalClusterTest/java/org/elasticsearch/indices/state/OpenCloseIndexIT.java
|
{
"start": 2581,
"end": 19118
}
|
class ____ extends ESIntegTestCase {
public void testSimpleCloseOpen() {
Client client = client();
createIndex("test1");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse closeIndexResponse = client.admin().indices().prepareClose("test1").get();
assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1");
OpenIndexResponse openIndexResponse = client.admin().indices().prepareOpen("test1").get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1");
}
public void testSimpleOpenMissingIndex() {
Exception e = expectThrows(IndexNotFoundException.class, indicesAdmin().prepareOpen("test1"));
assertThat(e.getMessage(), is("no such index [test1]"));
}
public void testOpenOneMissingIndex() {
Client client = client();
createIndex("test1");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
Exception e = expectThrows(IndexNotFoundException.class, client.admin().indices().prepareOpen("test1", "test2"));
assertThat(e.getMessage(), is("no such index [test2]"));
}
public void testOpenOneMissingIndexIgnoreMissing() {
Client client = client();
createIndex("test1");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
OpenIndexResponse openIndexResponse = client.admin()
.indices()
.prepareOpen("test1", "test2")
.setIndicesOptions(IndicesOptions.lenientExpandOpen())
.get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1");
}
public void testCloseOpenMultipleIndices() {
Client client = client();
createIndex("test1", "test2", "test3");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse closeIndexResponse1 = client.admin().indices().prepareClose("test1").get();
assertThat(closeIndexResponse1.isAcknowledged(), equalTo(true));
AcknowledgedResponse closeIndexResponse2 = client.admin().indices().prepareClose("test2").get();
assertThat(closeIndexResponse2.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1", "test2");
assertIndexIsOpened("test3");
OpenIndexResponse openIndexResponse1 = client.admin().indices().prepareOpen("test1").get();
assertThat(openIndexResponse1.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse1.isShardsAcknowledged(), equalTo(true));
OpenIndexResponse openIndexResponse2 = client.admin().indices().prepareOpen("test2").get();
assertThat(openIndexResponse2.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse2.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1", "test2", "test3");
}
public void testCloseOpenWildcard() {
Client client = client();
createIndex("test1", "test2", "a");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse closeIndexResponse = client.admin().indices().prepareClose("test*").get();
assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1", "test2");
assertIndexIsOpened("a");
OpenIndexResponse openIndexResponse = client.admin().indices().prepareOpen("test*").get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1", "test2", "a");
}
public void testCloseOpenAll() {
Client client = client();
createIndex("test1", "test2", "test3");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse closeIndexResponse = client.admin().indices().prepareClose("_all").get();
assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1", "test2", "test3");
OpenIndexResponse openIndexResponse = client.admin().indices().prepareOpen("_all").get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1", "test2", "test3");
}
public void testCloseOpenAllWildcard() {
Client client = client();
createIndex("test1", "test2", "test3");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse closeIndexResponse = client.admin().indices().prepareClose("*").get();
assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1", "test2", "test3");
OpenIndexResponse openIndexResponse = client.admin().indices().prepareOpen("*").get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1", "test2", "test3");
}
public void testOpenNoIndex() {
Exception e = expectThrows(ActionRequestValidationException.class, indicesAdmin().prepareOpen());
assertThat(e.getMessage(), containsString("index is missing"));
}
public void testOpenNullIndex() {
Exception e = expectThrows(ActionRequestValidationException.class, indicesAdmin().prepareOpen((String[]) null));
assertThat(e.getMessage(), containsString("index is missing"));
}
public void testOpenAlreadyOpenedIndex() {
Client client = client();
createIndex("test1");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
// no problem if we try to open an index that's already in open state
OpenIndexResponse openIndexResponse1 = client.admin().indices().prepareOpen("test1").get();
assertThat(openIndexResponse1.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse1.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1");
}
public void testSimpleCloseOpenAlias() {
Client client = client();
createIndex("test1");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse aliasesResponse = client.admin()
.indices()
.prepareAliases(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)
.addAlias("test1", "test1-alias")
.get();
assertThat(aliasesResponse.isAcknowledged(), equalTo(true));
AcknowledgedResponse closeIndexResponse = client.admin().indices().prepareClose("test1-alias").get();
assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1");
OpenIndexResponse openIndexResponse = client.admin().indices().prepareOpen("test1-alias").get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1");
}
public void testCloseOpenAliasMultipleIndices() {
Client client = client();
createIndex("test1", "test2");
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForGreenStatus().get();
assertThat(healthResponse.isTimedOut(), equalTo(false));
AcknowledgedResponse aliasesResponse1 = client.admin()
.indices()
.prepareAliases(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)
.addAlias("test1", "test-alias")
.get();
assertThat(aliasesResponse1.isAcknowledged(), equalTo(true));
AcknowledgedResponse aliasesResponse2 = client.admin()
.indices()
.prepareAliases(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT)
.addAlias("test2", "test-alias")
.get();
assertThat(aliasesResponse2.isAcknowledged(), equalTo(true));
AcknowledgedResponse closeIndexResponse = client.admin().indices().prepareClose("test-alias").get();
assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
assertIndexIsClosed("test1", "test2");
OpenIndexResponse openIndexResponse = client.admin().indices().prepareOpen("test-alias").get();
assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test1", "test2");
}
public void testOpenWaitingForActiveShardsFailed() throws Exception {
Client client = client();
Settings settings = indexSettings(1, 0).build();
assertAcked(client.admin().indices().prepareCreate("test").setSettings(settings).get());
assertAcked(client.admin().indices().prepareClose("test").get());
OpenIndexResponse response = client.admin()
.indices()
.prepareOpen("test")
.setTimeout(TimeValue.timeValueMillis(100))
.setWaitForActiveShards(2)
.get();
assertThat(response.isShardsAcknowledged(), equalTo(false));
assertBusy(
() -> assertThat(
client.admin()
.cluster()
.prepareState(TEST_REQUEST_TIMEOUT)
.get()
.getState()
.metadata()
.getProject()
.index("test")
.getState(),
equalTo(IndexMetadata.State.OPEN)
)
);
ensureGreen("test");
}
public void testOpenCloseWithDocs() throws IOException, ExecutionException, InterruptedException {
String mapping = Strings.toString(
XContentFactory.jsonBuilder()
.startObject()
.startObject("properties")
.startObject("test")
.field("type", "keyword")
.endObject()
.endObject()
.endObject()
);
assertAcked(indicesAdmin().prepareCreate("test").setMapping(mapping));
ensureGreen();
int docs = between(10, 100);
IndexRequestBuilder[] builder = new IndexRequestBuilder[docs];
for (int i = 0; i < docs; i++) {
builder[i] = prepareIndex("test").setId("" + i).setSource("test", "init");
}
indexRandom(true, builder);
if (randomBoolean()) {
indicesAdmin().prepareFlush("test").setForce(true).execute().get();
}
indicesAdmin().prepareClose("test").execute().get();
// check the index still contains the records that we indexed
indicesAdmin().prepareOpen("test").execute().get();
ensureGreen();
assertHitCountAndNoFailures(prepareSearch().setQuery(QueryBuilders.matchQuery("test", "init")), docs);
}
public void testOpenCloseIndexWithBlocks() {
createIndex("test");
ensureGreen("test");
int docs = between(10, 100);
for (int i = 0; i < docs; i++) {
prepareIndex("test").setId("" + i).setSource("test", "init").get();
}
for (String blockSetting : Arrays.asList(SETTING_BLOCKS_READ, SETTING_BLOCKS_WRITE)) {
try {
enableIndexBlock("test", blockSetting);
// Closing an index is not blocked
AcknowledgedResponse closeIndexResponse = indicesAdmin().prepareClose("test").get();
assertAcked(closeIndexResponse);
assertIndexIsClosed("test");
// Opening an index is not blocked
OpenIndexResponse openIndexResponse = indicesAdmin().prepareOpen("test").get();
assertAcked(openIndexResponse);
assertThat(openIndexResponse.isShardsAcknowledged(), equalTo(true));
assertIndexIsOpened("test");
} finally {
disableIndexBlock("test", blockSetting);
}
}
// Closing an index is blocked
for (String blockSetting : Arrays.asList(SETTING_READ_ONLY, SETTING_BLOCKS_METADATA)) {
try {
enableIndexBlock("test", blockSetting);
assertBlocked(indicesAdmin().prepareClose("test"));
assertIndexIsOpened("test");
} finally {
disableIndexBlock("test", blockSetting);
}
}
AcknowledgedResponse closeIndexResponse = indicesAdmin().prepareClose("test").get();
assertAcked(closeIndexResponse);
assertIndexIsClosed("test");
// Opening an index is blocked
for (String blockSetting : Arrays.asList(SETTING_READ_ONLY, SETTING_BLOCKS_METADATA)) {
try {
enableIndexBlock("test", blockSetting);
assertBlocked(indicesAdmin().prepareOpen("test"));
assertIndexIsClosed("test");
} finally {
disableIndexBlock("test", blockSetting);
}
}
}
public void testTranslogStats() throws Exception {
final String indexName = "test";
createIndex(indexName, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).build());
final int nbDocs = randomIntBetween(0, 50);
int uncommittedOps = 0;
for (long i = 0; i < nbDocs; i++) {
final DocWriteResponse indexResponse = prepareIndex(indexName).setId(Long.toString(i)).setSource("field", i).get();
assertThat(indexResponse.status(), is(RestStatus.CREATED));
if (rarely()) {
indicesAdmin().prepareFlush(indexName).get();
uncommittedOps = 0;
} else {
uncommittedOps += 1;
}
}
final int uncommittedTranslogOps = uncommittedOps;
assertBusy(() -> {
IndicesStatsResponse stats = indicesAdmin().prepareStats(indexName).clear().setTranslog(true).get();
assertThat(stats.getIndex(indexName), notNullValue());
assertThat(
stats.getIndex(indexName).getPrimaries().getTranslog().estimatedNumberOfOperations(),
equalTo(uncommittedTranslogOps)
);
assertThat(stats.getIndex(indexName).getPrimaries().getTranslog().getUncommittedOperations(), equalTo(uncommittedTranslogOps));
});
assertAcked(indicesAdmin().prepareClose("test"));
IndicesOptions indicesOptions = IndicesOptions.STRICT_EXPAND_OPEN;
IndicesStatsResponse stats = indicesAdmin().prepareStats(indexName)
.setIndicesOptions(indicesOptions)
.clear()
.setTranslog(true)
.get();
assertThat(stats.getIndex(indexName), notNullValue());
assertThat(stats.getIndex(indexName).getPrimaries().getTranslog().estimatedNumberOfOperations(), equalTo(0));
assertThat(stats.getIndex(indexName).getPrimaries().getTranslog().getUncommittedOperations(), equalTo(0));
}
}
|
OpenCloseIndexIT
|
java
|
apache__camel
|
components/camel-mock/src/main/java/org/apache/camel/component/mock/InterceptSendToMockEndpointStrategy.java
|
{
"start": 1607,
"end": 5801
}
|
class ____ implements EndpointStrategy {
private static final Logger LOG = LoggerFactory.getLogger(InterceptSendToMockEndpointStrategy.class);
private final String pattern;
private final boolean skip;
/**
* Mock all endpoints.
*/
public InterceptSendToMockEndpointStrategy() {
this(null);
}
/**
* Mock endpoints based on the given pattern.
*
* @param pattern the pattern.
* @see EndpointHelper#matchEndpoint(org.apache.camel.CamelContext, String, String)
*/
public InterceptSendToMockEndpointStrategy(String pattern) {
this(pattern, false);
}
/**
* Mock endpoints based on the given pattern.
*
* @param pattern the pattern.
* @param skip <tt>true</tt> to skip sending after the detour to the original endpoint
* @see EndpointHelper#matchEndpoint(org.apache.camel.CamelContext, String, String)
*/
public InterceptSendToMockEndpointStrategy(String pattern, boolean skip) {
this.pattern = pattern;
this.skip = skip;
}
@Override
public Endpoint registerEndpoint(String uri, Endpoint endpoint) {
if (endpoint instanceof InterceptSendToEndpoint) {
// endpoint already decorated
return endpoint;
} else if (endpoint.getEndpointUri().startsWith("mock:")) {
// we should not intercept mock endpoints
return endpoint;
} else if (matchPattern(uri, endpoint, pattern)) {
// if a pattern is null, then it means to match all
// only proxy if the uri is matched decorate endpoint with our proxy
// should be false by default
InterceptSendToEndpoint proxy = new DefaultInterceptSendToEndpoint(endpoint, skip);
try {
Producer producer = createProducer(endpoint.getCamelContext(), uri, proxy);
// allow custom logic
producer = onInterceptEndpoint(uri, endpoint, producer.getEndpoint(), producer);
proxy.setBefore(producer);
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
return proxy;
} else {
// no proxy so return regular endpoint
return endpoint;
}
}
protected Producer createProducer(CamelContext camelContext, String uri, Endpoint endpoint) throws Exception {
// create mock endpoint which we will use as interceptor
// replace :// from scheme to make it easy to look up the mock endpoint without having double :// in uri
String key = "mock:" + endpoint.getEndpointKey().replaceFirst("://", ":");
// strip off parameters as well
if (key.contains("?")) {
key = StringHelper.before(key, "?");
}
LOG.info("Adviced endpoint [{}] with mock endpoint [{}]", uri, key);
Endpoint mock = endpoint.getCamelContext().getEndpoint(key, Endpoint.class);
return mock.createProducer();
}
/**
* Does the pattern match the endpoint?
*
* @param uri the uri
* @param endpoint the endpoint
* @param pattern the pattern
* @return <tt>true</tt> to match and therefore intercept, <tt>false</tt> if not matched and should not
* intercept
*/
protected boolean matchPattern(String uri, Endpoint endpoint, String pattern) {
return uri == null || pattern == null || EndpointHelper.matchEndpoint(endpoint.getCamelContext(), uri, pattern);
}
/**
* Callback when an endpoint was intercepted with the given mock endpoint
*
* @param uri the uri
* @param endpoint the endpoint
* @param mockEndpoint the mocked endpoint
* @param mockProducer the mock producer
* @return the mock producer
*/
protected Producer onInterceptEndpoint(String uri, Endpoint endpoint, Endpoint mockEndpoint, Producer mockProducer) {
return mockProducer;
}
@Override
public String toString() {
return "InterceptSendToMockEndpointStrategy";
}
}
|
InterceptSendToMockEndpointStrategy
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/deser/creators/TestCreators.java
|
{
"start": 2186,
"end": 2465
}
|
class ____ {
String value;
private StringFactoryBean(String v, boolean dummy) { value = v; }
@JsonCreator static protected StringFactoryBean valueOf(String v) {
return new StringFactoryBean(v, true);
}
}
static
|
StringFactoryBean
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestRpcServiceProtosLegacy.java
|
{
"start": 59899,
"end": 65142
}
|
interface ____ {
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto ping(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto echo(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto error(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto error2(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto slowPing(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto2 echo2(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto2 request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddResponseProto add(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddResponseProto add2(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto testServerGet(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.ExchangeResponseProto exchange(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.ExchangeRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto sleep(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto lockAndSleep(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AuthMethodResponseProto getAuthMethod(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.UserResponseProto getAuthUser(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoResponseProto echoPostponed(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EchoRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto sendPostponed(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.UserResponseProto getCurrentUser(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.UserResponseProto getServerRemoteUser(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request)
throws com.google.protobuf.ServiceException;
}
private static final
|
BlockingInterface
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestPropertiesIntegrationTests.java
|
{
"start": 1122,
"end": 1346
}
|
class ____ {
@Autowired
private Environment environment;
@Test
void environmentWithNewProfile() {
assertThat(this.environment.getActiveProfiles()).containsExactly("test");
}
@Nested
|
JsonTestPropertiesIntegrationTests
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/GlobalStorageStatistics.java
|
{
"start": 3852,
"end": 4639
}
|
class ____ implements Iterator<StorageStatistics> {
private StorageStatistics next = null;
StorageIterator(StorageStatistics first) {
this.next = first;
}
@Override
public boolean hasNext() {
return (next != null);
}
@Override
public StorageStatistics next() {
if (next == null) {
throw new NoSuchElementException();
}
synchronized (GlobalStorageStatistics.this) {
StorageStatistics cur = next;
Entry<String, StorageStatistics> nextEntry =
map.higherEntry(cur.getName());
next = (nextEntry == null) ? null : nextEntry.getValue();
return cur;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
|
StorageIterator
|
java
|
quarkusio__quarkus
|
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoCollection.java
|
{
"start": 12330,
"end": 13155
}
|
class ____ decode each document into
* @param <D> the target document type of the iterable.
* @param options the stream options
* @return the stream with the selected documents, can be empty if none matches.
*/
<D> Multi<D> find(Bson filter, Class<D> clazz, FindOptions options);
/**
* Finds all documents in the collection.
*
* @param clientSession the client session with which to associate this operation
* @param options the stream options
* @return the stream with the selected documents, can be empty if none matches.
*/
Multi<T> find(ClientSession clientSession, FindOptions options);
/**
* Finds all documents in the collection.
*
* @param clientSession the client session with which to associate this operation
* @param clazz the
|
to
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java
|
{
"start": 10568,
"end": 10899
}
|
class ____ implements ProfileValueSource {
@Override
public String get(final String key) {
return (key.equals(NAME) ? "42" : null);
}
}
@ProfileValueSourceConfiguration(HardCodedProfileValueSource.class)
@IfProfileValue(name = NAME, value = "42")
@Retention(RetentionPolicy.RUNTIME)
private @
|
HardCodedProfileValueSource
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/mixins/TestMixinMerging.java
|
{
"start": 975,
"end": 2071
}
|
class ____ extends ContactMixin implements Person {}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
// for [databind#515]
@Test
public void testDisappearingMixins515() throws Exception
{
SimpleModule module = new SimpleModule("Test");
module.setMixInAnnotation(Person.class, PersonMixin.class);
ObjectMapper mapper = jsonMapperBuilder()
.disable(MapperFeature.INFER_PROPERTY_MUTATORS)
.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS)
.changeDefaultVisibility(vc -> vc
.withVisibility(PropertyAccessor.FIELD, Visibility.NONE)
.withVisibility(PropertyAccessor.GETTER, Visibility.NONE)
.withVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE))
.addModule(module)
.build();
assertEquals("{\"city\":\"Seattle\"}", mapper.writeValueAsString(new PersonImpl()));
}
}
|
PersonMixin
|
java
|
apache__dubbo
|
dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java
|
{
"start": 1475,
"end": 2477
}
|
class ____ implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
frameworkModel.addDestroyListener(new FrameworkModelCleaner());
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(DefaultConfigValidator.class);
// applicationDeployer
ApplicationDeployer applicationDeployer = beanFactory.registerBean(DefaultApplicationDeployer.class);
applicationModel.setDeployer(applicationDeployer);
}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {
ScopeBeanFactory beanFactory = moduleModel.getBeanFactory();
// moduleDeployer
ModuleDeployer moduleDeployer = beanFactory.registerBean(DefaultModuleDeployer.class);
moduleModel.setDeployer(moduleDeployer);
}
}
|
ConfigScopeModelInitializer
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ActiveMQEndpointBuilderFactory.java
|
{
"start": 27049,
"end": 28274
}
|
class ____ is good enough as
* subscription name). Note that shared subscriptions may also be
* durable, so this flag can (and often will) be combined with
* subscriptionDurable as well. Only makes sense when listening to a
* topic (pub-sub domain), therefore this method switches the
* pubSubDomain flag as well. Requires a JMS 2.0 compatible message
* broker.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param subscriptionShared the value to set
* @return the dsl builder
*/
default ActiveMQEndpointConsumerBuilder subscriptionShared(boolean subscriptionShared) {
doSetProperty("subscriptionShared", subscriptionShared);
return this;
}
/**
* Set whether to make the subscription shared. The shared subscription
* name to be used can be specified through the subscriptionName
* property. Default is false. Set this to true to register a shared
* subscription, typically in combination with a subscriptionName value
* (unless your message listener
|
name
|
java
|
quarkusio__quarkus
|
independent-projects/bootstrap/gradle-resolver/src/main/java/io/quarkus/bootstrap/resolver/QuarkusModelBuildAction.java
|
{
"start": 270,
"end": 737
}
|
class ____ implements BuildAction<ApplicationModel>, Serializable {
private static final long serialVersionUID = 9152408068581769671L;
private final String mode;
public QuarkusModelBuildAction(String mode) {
this.mode = mode;
}
@Override
public ApplicationModel execute(BuildController controller) {
return controller.getModel(ApplicationModel.class, ModelParameter.class, p -> p.setMode(mode));
}
}
|
QuarkusModelBuildAction
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AsyncBranchingStepTests.java
|
{
"start": 841,
"end": 4694
}
|
class ____ extends AbstractStepTestCase<AsyncBranchingStep> {
public void testPredicateNextStepChange() throws InterruptedException {
String indexName = randomAlphaOfLength(5);
final var indexMetadata = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()))
.numberOfShards(1)
.numberOfReplicas(0)
.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
StepKey stepKey = new StepKey(randomAlphaOfLength(5), randomAlphaOfLength(5), BranchingStep.NAME);
StepKey nextStepKey = new StepKey(randomAlphaOfLength(6), randomAlphaOfLength(6), BranchingStep.NAME);
StepKey nextSkipKey = new StepKey(randomAlphaOfLength(7), randomAlphaOfLength(7), BranchingStep.NAME);
{
AsyncBranchingStep step = new AsyncBranchingStep(stepKey, nextStepKey, nextSkipKey, (p, i, l) -> l.onResponse(true), client);
expectThrows(IllegalStateException.class, step::getNextStepKey);
CountDownLatch latch = new CountDownLatch(1);
step.performAction(indexMetadata, state, null, new Listener(latch));
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertThat(step.getNextStepKey(), equalTo(step.getNextStepKeyOnTrue()));
}
{
AsyncBranchingStep step = new AsyncBranchingStep(stepKey, nextStepKey, nextSkipKey, (p, i, l) -> l.onResponse(false), client);
expectThrows(IllegalStateException.class, step::getNextStepKey);
CountDownLatch latch = new CountDownLatch(1);
step.performAction(indexMetadata, state, null, new Listener(latch));
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertThat(step.getNextStepKey(), equalTo(step.getNextStepKeyOnFalse()));
}
}
@Override
public AsyncBranchingStep createRandomInstance() {
StepKey stepKey = new StepKey(randomAlphaOfLength(5), randomAlphaOfLength(5), BranchingStep.NAME);
StepKey nextStepKey = new StepKey(randomAlphaOfLength(6), randomAlphaOfLength(6), BranchingStep.NAME);
StepKey nextSkipKey = new StepKey(randomAlphaOfLength(7), randomAlphaOfLength(7), BranchingStep.NAME);
return new AsyncBranchingStep(stepKey, nextStepKey, nextSkipKey, (p, i, l) -> l.onResponse(randomBoolean()), client);
}
@Override
public AsyncBranchingStep mutateInstance(AsyncBranchingStep instance) {
StepKey key = instance.getKey();
StepKey nextStepKey = instance.getNextStepKeyOnFalse();
StepKey nextSkipStepKey = instance.getNextStepKeyOnTrue();
TriConsumer<ProjectId, IndexMetadata, ActionListener<Boolean>> asyncPredicate = instance.getAsyncPredicate();
switch (between(0, 2)) {
case 0 -> key = new StepKey(key.phase(), key.action(), key.name() + randomAlphaOfLength(5));
case 1 -> nextStepKey = new StepKey(nextStepKey.phase(), nextStepKey.action(), nextStepKey.name() + randomAlphaOfLength(5));
case 2 -> nextSkipStepKey = new StepKey(
nextSkipStepKey.phase(),
nextSkipStepKey.action(),
nextSkipStepKey.name() + randomAlphaOfLength(5)
);
default -> throw new AssertionError("Illegal randomisation branch");
}
return new AsyncBranchingStep(key, nextStepKey, nextSkipStepKey, asyncPredicate, client);
}
@Override
public AsyncBranchingStep copyInstance(AsyncBranchingStep instance) {
return new AsyncBranchingStep(
instance.getKey(),
instance.getNextStepKeyOnFalse(),
instance.getNextStepKeyOnTrue(),
instance.getAsyncPredicate(),
client
);
}
|
AsyncBranchingStepTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/onetoone/QueryOneToOneFKIsNullTest.java
|
{
"start": 1801,
"end": 2213
}
|
class ____ {
@Id
private long id;
@OneToOne
private Parent parent;
Child() {}
public Child(long id, Parent parent) {
this.id = id;
setParent(parent);
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
parent.setChild(this);
}
@Override
public String toString() {
return "Child [id=" + id + "]";
}
}
}
|
Child
|
java
|
quarkusio__quarkus
|
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithAutoMongoBindingTest.java
|
{
"start": 650,
"end": 3959
}
|
class ____ {
private static final String APP_NAME = "kubernetes-with-auto-mongo-binding";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
.setApplicationName(APP_NAME)
.setApplicationVersion("0.1-SNAPSHOT")
.withConfigurationResource(APP_NAME + ".properties")
.setLogFileName("k8s.log")
.setForcedDependencies(List.of(
Dependency.of("io.quarkus", "quarkus-mongodb-client", Version.getVersion()),
Dependency.of("io.quarkus", "quarkus-kubernetes", Version.getVersion()),
Dependency.of("io.quarkus", "quarkus-kubernetes-service-binding", Version.getVersion())));
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
public void assertGeneratedResources() throws IOException {
final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
assertThat(kubernetesDir)
.isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json"))
.isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml"));
List<HasMetadata> kubernetesList = DeserializationUtil.deserializeAsList(kubernetesDir.resolve("kubernetes.yml"));
assertThat(kubernetesList).filteredOn(i -> "Deployment".equals(i.getKind())).singleElement().satisfies(i -> {
assertThat(i).isInstanceOfSatisfying(Deployment.class, d -> {
assertThat(d.getMetadata()).satisfies(m -> {
assertThat(m.getName()).isEqualTo(APP_NAME);
});
assertThat(d.getSpec()).satisfies(deploymentSpec -> {
assertThat(deploymentSpec.getTemplate()).satisfies(t -> {
assertThat(t.getSpec()).satisfies(podSpec -> {
});
});
});
});
});
assertThat(kubernetesList).filteredOn(i -> "ServiceBinding".equals(i.getKind())).singleElement().satisfies(i -> {
assertThat(i).isInstanceOfSatisfying(ServiceBinding.class, s -> {
assertThat(s.getMetadata()).satisfies(m -> {
assertThat(m.getName()).isEqualTo(APP_NAME + "-mongodb");
});
assertThat(s.getSpec()).satisfies(spec -> {
assertThat(spec.getApplication()).satisfies(a -> {
assertThat(a.getGroup()).isEqualTo("apps");
assertThat(a.getVersion()).isEqualTo("v1");
assertThat(a.getKind()).isEqualTo("Deployment");
});
assertThat(spec.getServices()).hasOnlyOneElementSatisfying(service -> {
assertThat(service.getGroup()).isEqualTo("psmdb.percona.com");
assertThat(service.getVersion()).isEqualTo("v1-9-0");
assertThat(service.getKind()).isEqualTo("PerconaServerMongoDB");
assertThat(service.getName()).isEqualTo("mongodb");
});
});
});
});
}
}
|
KubernetesWithAutoMongoBindingTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/sql/ast/spi/ParameterMarkerStrategy.java
|
{
"start": 839,
"end": 1130
}
|
interface ____ extends Service {
/**
* Create a parameter marker
*
* @param position The 1-based position of the parameter.
* @param jdbcType The type of the parameter, if known - may be {@code null}.
*/
String createMarker(int position, JdbcType jdbcType);
}
|
ParameterMarkerStrategy
|
java
|
apache__flink
|
flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/table/module/StateModuleTest.java
|
{
"start": 1531,
"end": 2922
}
|
class ____ {
@Test
public void testDynamicBuiltinFunctionShouldBeLoaded() throws Exception {
Configuration config = new Configuration();
config.set(RUNTIME_MODE, RuntimeExecutionMode.BATCH);
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(config);
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
tEnv.executeSql("LOAD MODULE state");
Table table = tEnv.sqlQuery("SELECT * FROM example_dynamic_table_function()");
List<Row> result = tEnv.toDataStream(table).executeAndCollect(100);
assertThat(result.size()).isEqualTo(1);
Iterator<Row> it = result.iterator();
assertThat(it.next().toString()).isEqualTo("+I[my-value]");
}
@Test
public void testMultipleFunctionsWithSameNameShouldThrow() {
assertThatThrownBy(
() ->
StateModule.checkDuplicatedFunctions(
List.of(
ExampleDynamicTableFunction.FUNCTION_DEFINITION,
ExampleDynamicTableFunction.FUNCTION_DEFINITION)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate function names found: example_dynamic_table_function");
}
}
|
StateModuleTest
|
java
|
apache__commons-lang
|
src/test/java/org/apache/commons/lang3/StringUtilsEmptyBlankTest.java
|
{
"start": 1174,
"end": 7879
}
|
class ____ extends AbstractLangTest {
@Test
void testFirstNonBlank() {
assertNull(StringUtils.firstNonBlank());
assertNull(StringUtils.firstNonBlank((String[]) null));
assertNull(StringUtils.firstNonBlank(null, null, null));
assertNull(StringUtils.firstNonBlank(null, "", " "));
assertNull(StringUtils.firstNonBlank(null, null, " "));
assertEquals("a", StringUtils.firstNonBlank(null, "a"));
assertEquals("zz", StringUtils.firstNonBlank(null, "zz"));
assertEquals("abc", StringUtils.firstNonBlank("abc"));
assertEquals("xyz", StringUtils.firstNonBlank(null, "xyz"));
assertEquals("xyz", StringUtils.firstNonBlank(null, "xyz", "abc"));
}
@Test
void testFirstNonEmpty() {
assertNull(StringUtils.firstNonEmpty());
assertNull(StringUtils.firstNonEmpty((String[]) null));
assertNull(StringUtils.firstNonEmpty(null, null, null));
assertEquals(" ", StringUtils.firstNonEmpty(null, "", " "));
assertNull(StringUtils.firstNonEmpty(null, null, ""));
assertEquals("a", StringUtils.firstNonEmpty(null, "a"));
assertEquals("zz", StringUtils.firstNonEmpty(null, "zz"));
assertEquals("abc", StringUtils.firstNonEmpty("abc"));
assertEquals("xyz", StringUtils.firstNonEmpty(null, "xyz"));
assertEquals("xyz", StringUtils.firstNonEmpty(null, "xyz", "abc"));
}
@Test
void testIsAllBlank() {
assertTrue(StringUtils.isAllBlank((String) null));
assertTrue(StringUtils.isAllBlank((String[]) null));
assertTrue(StringUtils.isAllBlank(null, null));
assertTrue(StringUtils.isAllBlank(null, " "));
assertFalse(StringUtils.isAllBlank(null, "foo"));
assertFalse(StringUtils.isAllBlank(null, "a"));
assertFalse(StringUtils.isAllBlank("", "bar"));
assertFalse(StringUtils.isAllBlank("bob", ""));
assertFalse(StringUtils.isAllBlank(" bob ", null));
assertFalse(StringUtils.isAllBlank(" ", "bar"));
assertFalse(StringUtils.isAllBlank("foo", "bar"));
}
@Test
void testIsAllEmpty() {
assertTrue(StringUtils.isAllEmpty());
assertTrue(StringUtils.isAllEmpty());
assertTrue(StringUtils.isAllEmpty((String) null));
assertTrue(StringUtils.isAllEmpty((String[]) null));
assertFalse(StringUtils.isAllEmpty(null, "foo"));
assertFalse(StringUtils.isAllEmpty(null, "a"));
assertFalse(StringUtils.isAllEmpty("", "bar"));
assertFalse(StringUtils.isAllEmpty("bob", ""));
assertFalse(StringUtils.isAllEmpty(" bob ", null));
assertFalse(StringUtils.isAllEmpty(" ", "bar"));
assertFalse(StringUtils.isAllEmpty("foo", "bar"));
assertTrue(StringUtils.isAllEmpty("", null));
}
@Test
void testIsAnyBlank() {
assertTrue(StringUtils.isAnyBlank((String) null));
assertFalse(StringUtils.isAnyBlank((String[]) null));
assertTrue(StringUtils.isAnyBlank(null, "foo"));
assertTrue(StringUtils.isAnyBlank(null, null));
assertTrue(StringUtils.isAnyBlank("", "bar"));
assertTrue(StringUtils.isAnyBlank("bob", ""));
assertTrue(StringUtils.isAnyBlank(" bob ", null));
assertTrue(StringUtils.isAnyBlank(" ", "bar"));
assertFalse(StringUtils.isAnyBlank("foo", "bar"));
}
@Test
void testIsAnyEmpty() {
assertTrue(StringUtils.isAnyEmpty((String) null));
assertFalse(StringUtils.isAnyEmpty((String[]) null));
assertTrue(StringUtils.isAnyEmpty(null, "foo"));
assertTrue(StringUtils.isAnyEmpty(null, "a"));
assertTrue(StringUtils.isAnyEmpty("", "bar"));
assertTrue(StringUtils.isAnyEmpty("bob", ""));
assertTrue(StringUtils.isAnyEmpty(" bob ", null));
assertFalse(StringUtils.isAnyEmpty(" ", "bar"));
assertFalse(StringUtils.isAnyEmpty("foo", "bar"));
}
@Test
void testIsBlank() {
assertTrue(StringUtils.isBlank(null));
assertTrue(StringUtils.isBlank(""));
assertTrue(StringUtils.isBlank(StringUtilsTest.WHITESPACE));
assertFalse(StringUtils.isBlank("a"));
assertFalse(StringUtils.isBlank("foo"));
assertFalse(StringUtils.isBlank(" foo "));
}
@Test
void testIsEmpty() {
assertTrue(StringUtils.isEmpty(null));
assertTrue(StringUtils.isEmpty(""));
assertFalse(StringUtils.isEmpty(" "));
assertFalse(StringUtils.isEmpty("a"));
assertFalse(StringUtils.isEmpty("foo"));
assertFalse(StringUtils.isEmpty(" foo "));
}
@Test
void testIsNoneBlank() {
assertFalse(StringUtils.isNoneBlank((String) null));
assertTrue(StringUtils.isNoneBlank((String[]) null));
assertFalse(StringUtils.isNoneBlank(null, "a"));
assertFalse(StringUtils.isNoneBlank(null, "foo"));
assertFalse(StringUtils.isNoneBlank(null, null));
assertFalse(StringUtils.isNoneBlank("", "bar"));
assertFalse(StringUtils.isNoneBlank("a", ""));
assertFalse(StringUtils.isNoneBlank("bob", ""));
assertFalse(StringUtils.isNoneBlank(" bob ", null));
assertFalse(StringUtils.isNoneBlank(" ", "bar"));
assertTrue(StringUtils.isNoneBlank("foo", "bar"));
}
@Test
void testIsNoneEmpty() {
assertFalse(StringUtils.isNoneEmpty((String) null));
assertTrue(StringUtils.isNoneEmpty((String[]) null));
assertFalse(StringUtils.isNoneEmpty(null, "a"));
assertFalse(StringUtils.isNoneEmpty(null, "foo"));
assertFalse(StringUtils.isNoneEmpty("", "bar"));
assertFalse(StringUtils.isNoneEmpty("bob", ""));
assertFalse(StringUtils.isNoneEmpty("a", ""));
assertFalse(StringUtils.isNoneEmpty(" bob ", null));
assertTrue(StringUtils.isNoneEmpty(" ", "bar"));
assertTrue(StringUtils.isNoneEmpty("foo", "bar"));
}
@Test
void testIsNotBlank() {
assertFalse(StringUtils.isNotBlank(null));
assertFalse(StringUtils.isNotBlank(""));
assertFalse(StringUtils.isNotBlank(StringUtilsTest.WHITESPACE));
assertTrue(StringUtils.isNotBlank("a"));
assertTrue(StringUtils.isNotBlank("foo"));
assertTrue(StringUtils.isNotBlank(" foo "));
}
@Test
void testIsNotEmpty() {
assertFalse(StringUtils.isNotEmpty(null));
assertFalse(StringUtils.isNotEmpty(""));
assertTrue(StringUtils.isNotEmpty(" "));
assertTrue(StringUtils.isNotEmpty("a"));
assertTrue(StringUtils.isNotEmpty("foo"));
assertTrue(StringUtils.isNotEmpty(" foo "));
}
}
|
StringUtilsEmptyBlankTest
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java
|
{
"start": 3305,
"end": 6629
}
|
class ____ {
private final int replicaId;
private final Uuid replicaDirectoryId;
private final long logEndOffset;
private final OptionalLong lastFetchTimestamp;
private final OptionalLong lastCaughtUpTimestamp;
ReplicaState() {
this(0, Uuid.ZERO_UUID, 0, OptionalLong.empty(), OptionalLong.empty());
}
ReplicaState(
int replicaId,
Uuid replicaDirectoryId,
long logEndOffset,
OptionalLong lastFetchTimestamp,
OptionalLong lastCaughtUpTimestamp
) {
this.replicaId = replicaId;
this.replicaDirectoryId = replicaDirectoryId;
this.logEndOffset = logEndOffset;
this.lastFetchTimestamp = lastFetchTimestamp;
this.lastCaughtUpTimestamp = lastCaughtUpTimestamp;
}
/**
* Return the ID for this replica.
* @return The ID for this replica
*/
public int replicaId() {
return replicaId;
}
/**
* Return the directory id of the replica if configured, or Uuid.ZERO_UUID if not.
*/
public Uuid replicaDirectoryId() {
return replicaDirectoryId;
}
/**
* Return the logEndOffset known by the leader for this replica.
* @return The logEndOffset for this replica
*/
public long logEndOffset() {
return logEndOffset;
}
/**
* Return the last millisecond timestamp that the leader received a
* fetch from this replica.
* @return The value of the lastFetchTime if known, empty otherwise
*/
public OptionalLong lastFetchTimestamp() {
return lastFetchTimestamp;
}
/**
* Return the last millisecond timestamp at which this replica was known to be
* caught up with the leader.
* @return The value of the lastCaughtUpTime if known, empty otherwise
*/
public OptionalLong lastCaughtUpTimestamp() {
return lastCaughtUpTimestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReplicaState that = (ReplicaState) o;
return replicaId == that.replicaId
&& Objects.equals(replicaDirectoryId, that.replicaDirectoryId)
&& logEndOffset == that.logEndOffset
&& lastFetchTimestamp.equals(that.lastFetchTimestamp)
&& lastCaughtUpTimestamp.equals(that.lastCaughtUpTimestamp);
}
@Override
public int hashCode() {
return Objects.hash(replicaId, replicaDirectoryId, logEndOffset, lastFetchTimestamp, lastCaughtUpTimestamp);
}
@Override
public String toString() {
return "ReplicaState(" +
"replicaId=" + replicaId +
", replicaDirectoryId=" + replicaDirectoryId +
", logEndOffset=" + logEndOffset +
", lastFetchTimestamp=" + lastFetchTimestamp +
", lastCaughtUpTimestamp=" + lastCaughtUpTimestamp +
')';
}
}
public static
|
ReplicaState
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java
|
{
"start": 1142,
"end": 2266
}
|
class ____ extends SpringApplicationEvent {
private final ConfigurableBootstrapContext bootstrapContext;
private final ConfigurableEnvironment environment;
/**
* Create a new {@link ApplicationEnvironmentPreparedEvent} instance.
* @param bootstrapContext the bootstrap context
* @param application the current application
* @param args the arguments the application is running with
* @param environment the environment that was just created
*/
public ApplicationEnvironmentPreparedEvent(ConfigurableBootstrapContext bootstrapContext,
SpringApplication application, String[] args, ConfigurableEnvironment environment) {
super(application, args);
this.bootstrapContext = bootstrapContext;
this.environment = environment;
}
/**
* Return the bootstrap context.
* @return the bootstrap context
* @since 2.4.0
*/
public ConfigurableBootstrapContext getBootstrapContext() {
return this.bootstrapContext;
}
/**
* Return the environment.
* @return the environment
*/
public ConfigurableEnvironment getEnvironment() {
return this.environment;
}
}
|
ApplicationEnvironmentPreparedEvent
|
java
|
spring-projects__spring-framework
|
spring-webflux/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java
|
{
"start": 4655,
"end": 4964
}
|
class ____ extends HandlerResultHandlerSupport {
protected TestResultHandler() {
this(new HeaderContentTypeResolver());
}
public TestResultHandler(RequestedContentTypeResolver contentTypeResolver) {
super(contentTypeResolver, ReactiveAdapterRegistry.getSharedInstance());
}
}
}
|
TestResultHandler
|
java
|
micronaut-projects__micronaut-core
|
http/src/main/java/io/micronaut/http/annotation/Headers.java
|
{
"start": 940,
"end": 1393
}
|
class ____ have them always included.
* Example usage:
* <pre><code>
*{@literal @}Headers({
* {@literal @}Header(name = "Content-type", value = "application/octet-stream"),
* {@literal @}Header(name = "Content-length", value = "2048")
* })
* </code></pre>
*
* @author rvanderwerf
* @author graemerocher Graeme Rocher
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
public @
|
and
|
java
|
elastic__elasticsearch
|
libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/NetworkAccessCheckActions.java
|
{
"start": 4460,
"end": 4827
}
|
class ____ care about, LDAPCertStore (or its impl)
assert Arrays.stream(ex.getStackTrace()).anyMatch(e -> e.getClassName().endsWith("LDAPCertStore"));
} catch (NoSuchAlgorithmException e) {
// In some environments (e.g. with FIPS enabled) the LDAPCertStore is not present, so this will fail.
// This is OK, as this means the
|
we
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/pool/SpringIbatisFilterTest.java
|
{
"start": 1397,
"end": 4222
}
|
class ____ extends TestCase {
protected void setUp() throws Exception {
DruidDataSourceStatManager.clear();
}
protected void tearDown() throws Exception {
assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
}
public void test_spring() throws Exception {
assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"com/alibaba/druid/pool/ibatis/spring-config-ibatis.xml");
DataSource dataSource = (DataSource) context.getBean("dataSource");
{
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE sequence_seed (value INTEGER, name VARCHAR(50) PRIMARY KEY)");
stmt.close();
conn.close();
}
{
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE t_User (id BIGINT PRIMARY KEY, name VARCHAR(50))");
stmt.close();
conn.close();
}
{
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.execute("insert into sequence_seed (value ,name) values (0, 'druid-spring-test')");
stmt.close();
conn.commit();
conn.close();
}
// user-service
IUserService service = (IUserService) context.getBean("user-service");
User user = new User();
user.setName("xx");
service.addUser(user);
TestFilter filter = (TestFilter) context.getBean("test-filter");
assertEquals(2, filter.getConnectCount());
{
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
stmt.execute("DROP TABLE sequence_seed");
stmt.close();
conn.close();
}
{
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
stmt.execute("DROP TABLE t_User");
stmt.close();
conn.close();
}
assertEquals(1, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
Map<String, Object> wallStats = DruidStatService.getInstance().getWallStatMap(Collections.<String, String>emptyMap());
System.out.println("wall-stats : " + JSONUtils.toJSONString(wallStats));
context.close();
assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
}
public static
|
SpringIbatisFilterTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/PutLifecycleMetadataService.java
|
{
"start": 15180,
"end": 15545
}
|
class ____ extends SimpleBatchedAckListenerTaskExecutor<UpdateLifecyclePolicyTask> {
@Override
public Tuple<ClusterState, ClusterStateAckListener> executeTask(UpdateLifecyclePolicyTask task, ClusterState clusterState)
throws Exception {
return Tuple.tuple(task.execute(clusterState), task);
}
}
}
|
IlmLifecycleExecutor
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/state/VoidNamespaceSerializerUpgradeTest.java
|
{
"start": 1357,
"end": 2356
}
|
class ____
extends TypeSerializerUpgradeTestBase<VoidNamespace, VoidNamespace> {
private static final String SPEC_NAME = "void-namespace-serializer";
public Collection<TestSpecification<?, ?>> createTestSpecifications(FlinkVersion flinkVersion)
throws Exception {
ArrayList<TestSpecification<?, ?>> testSpecifications = new ArrayList<>();
testSpecifications.add(
new TestSpecification<>(
SPEC_NAME,
flinkVersion,
VoidNamespaceSerializerSetup.class,
VoidNamespaceSerializerVerifier.class));
return testSpecifications;
}
// ----------------------------------------------------------------------------------------------
// Specification for "voidnamespace-serializer"
// ----------------------------------------------------------------------------------------------
/**
* This
|
VoidNamespaceSerializerUpgradeTest
|
java
|
apache__camel
|
components/camel-jdbc/src/main/java/org/apache/camel/component/jdbc/JdbcEndpoint.java
|
{
"start": 1537,
"end": 8279
}
|
class ____ extends DefaultEndpoint {
private DataSource dataSource;
@UriPath
@Metadata(required = true)
private String dataSourceName;
@UriParam
private int readSize;
@UriParam
private boolean transacted;
@UriParam(defaultValue = "true")
private boolean resetAutoCommit = true;
@UriParam(prefix = "statement.", multiValue = true)
private Map<String, Object> parameters;
@UriParam(defaultValue = "true")
private boolean useJDBC4ColumnNameAndLabelSemantics = true;
@UriParam
private boolean useGetBytesForBlob;
@UriParam(label = "advanced")
private JdbcPrepareStatementStrategy prepareStatementStrategy = new DefaultJdbcPrepareStatementStrategy();
@UriParam(defaultValue = "true")
private boolean allowNamedParameters = true;
@UriParam
private boolean useHeadersAsParameters;
@UriParam(defaultValue = "SelectList")
private JdbcOutputType outputType = JdbcOutputType.SelectList;
@UriParam
private String outputClass;
@UriParam(label = "advanced")
private BeanRowMapper beanRowMapper = new DefaultBeanRowMapper();
@UriParam(label = "advanced")
private ConnectionStrategy connectionStrategy = new DefaultConnectionStrategy();
public JdbcEndpoint() {
}
public JdbcEndpoint(String endpointUri, Component component, DataSource dataSource) {
super(endpointUri, component);
this.dataSource = dataSource;
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Not supported");
}
@Override
public Producer createProducer() throws Exception {
return new JdbcProducer(this, dataSource, connectionStrategy, readSize, parameters);
}
public String getDataSourceName() {
return dataSourceName;
}
/**
* Name of DataSource to lookup in the Registry. If the name is dataSource or default, then Camel will attempt to
* lookup a default DataSource from the registry, meaning if there is a only one instance of DataSource found, then
* this DataSource will be used.
*/
public void setDataSourceName(String dataSourceName) {
this.dataSourceName = dataSourceName;
}
public int getReadSize() {
return readSize;
}
/**
* The default maximum number of rows that can be read by a polling query. The default value is 0.
*/
public void setReadSize(int readSize) {
this.readSize = readSize;
}
public boolean isTransacted() {
return transacted;
}
/**
* Whether transactions are in use.
*/
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public boolean isResetAutoCommit() {
return resetAutoCommit;
}
/**
* Camel will set the autoCommit on the JDBC connection to be false, commit the change after executed the statement
* and reset the autoCommit flag of the connection at the end, if the resetAutoCommit is true. If the JDBC
* connection doesn't support to reset the autoCommit flag, you can set the resetAutoCommit flag to be false, and
* Camel will not try to reset the autoCommit flag. When used with XA transactions you most likely need to set it to
* false so that the transaction manager is in charge of committing this tx.
*/
public void setResetAutoCommit(boolean resetAutoCommit) {
this.resetAutoCommit = resetAutoCommit;
}
public DataSource getDataSource() {
return dataSource;
}
/**
* The data source to use
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, Object> getParameters() {
return parameters;
}
/**
* Optional parameters to the {@link java.sql.Statement}.
* <p/>
* For example to set maxRows, fetchSize etc.
*
* @param parameters parameters which will be set using reflection
*/
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public boolean isUseJDBC4ColumnNameAndLabelSemantics() {
return useJDBC4ColumnNameAndLabelSemantics;
}
/**
* Sets whether to use JDBC 4 or JDBC 3.0 or older semantic when retrieving column name.
* <p/>
* JDBC 4.0 uses columnLabel to get the column name where as JDBC 3.0 uses both columnName or columnLabel.
* Unfortunately JDBC drivers behave differently so you can use this option to work out issues around your JDBC
* driver if you get problem using this component
* <p/>
* This option is default <tt>true</tt>.
*
* @param useJDBC4ColumnNameAndLabelSemantics <tt>true</tt> to use JDBC 4.0 semantics, <tt>false</tt> to use JDBC
* 3.0.
*/
public void setUseJDBC4ColumnNameAndLabelSemantics(boolean useJDBC4ColumnNameAndLabelSemantics) {
this.useJDBC4ColumnNameAndLabelSemantics = useJDBC4ColumnNameAndLabelSemantics;
}
public JdbcPrepareStatementStrategy getPrepareStatementStrategy() {
return prepareStatementStrategy;
}
/**
* Allows the plugin to use a custom org.apache.camel.component.jdbc.JdbcPrepareStatementStrategy to control
* preparation of the query and prepared statement.
*/
public void setPrepareStatementStrategy(JdbcPrepareStatementStrategy prepareStatementStrategy) {
this.prepareStatementStrategy = prepareStatementStrategy;
}
public boolean isAllowNamedParameters() {
return allowNamedParameters;
}
/**
* Whether to allow using named parameters in the queries.
*/
public void setAllowNamedParameters(boolean allowNamedParameters) {
this.allowNamedParameters = allowNamedParameters;
}
public boolean isUseHeadersAsParameters() {
return useHeadersAsParameters;
}
/**
* Set this option to true to use the prepareStatementStrategy with named parameters. This allows to define queries
* with named placeholders, and use headers with the dynamic values for the query placeholders.
*/
public void setUseHeadersAsParameters(boolean useHeadersAsParameters) {
this.useHeadersAsParameters = useHeadersAsParameters;
}
public JdbcOutputType getOutputType() {
return outputType;
}
/**
* Determines the output the producer should use.
*/
public void setOutputType(JdbcOutputType outputType) {
this.outputType = outputType;
}
public String getOutputClass() {
return outputClass;
}
/**
* Specify the full package and
|
JdbcEndpoint
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/generator/UUID2GeneratorStringUniqueIdentifierIdTest.java
|
{
"start": 1283,
"end": 2265
}
|
class ____ {
@AfterEach
void dropTestData(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@Test
public void testPaginationQuery(SessionFactoryScope factoryScope) {
var fooId = factoryScope.fromTransaction( (session) -> {
FooEntity entity = new FooEntity();
entity.getFooValues().add("one");
entity.getFooValues().add("two");
entity.getFooValues().add("three");
session.persist(entity);
return entity.getId();
} );
assertNotNull( fooId );
factoryScope.inTransaction( session -> {
FooEntity entity = session.find(FooEntity.class, fooId.toUpperCase());
assertNotNull(entity);
assertEquals( 3, entity.getFooValues().size() );
} );
factoryScope.inTransaction( entityManager -> {
FooEntity entity = entityManager.find(FooEntity.class, fooId);
assertNotNull(entity);
assertEquals( 3, entity.getFooValues().size() );
} );
}
@Entity
@Table(name = "foo")
public static
|
UUID2GeneratorStringUniqueIdentifierIdTest
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-jackson/runtime/src/main/java/io/quarkus/resteasy/reactive/jackson/runtime/serialisers/GeneratedSerializersRegister.java
|
{
"start": 789,
"end": 1152
}
|
class ____ implements ObjectMapperCustomizer {
private static final SimpleModule mappingModule = new SimpleModule();
private static final ExactSerializers serializers = new ExactSerializers();
static {
// Use a custom SimpleSerializers to use a json serializer only if it has been generated for that
// exact
|
GeneratedSerializersRegister
|
java
|
grpc__grpc-java
|
netty/src/main/java/io/grpc/netty/NettySslContextChannelCredentials.java
|
{
"start": 965,
"end": 1622
}
|
class ____ {
private NettySslContextChannelCredentials() {}
/**
* Create a credential using Netty's SslContext as configuration. It must have been configured
* with {@link GrpcSslContexts}, but options could have been overridden.
*/
public static ChannelCredentials create(SslContext sslContext) {
Preconditions.checkArgument(sslContext.isClient(),
"Server SSL context can not be used for client channel");
GrpcSslContexts.ensureAlpnAndH2Enabled(sslContext.applicationProtocolNegotiator());
return NettyChannelCredentials.create(ProtocolNegotiators.tlsClientFactory(sslContext, null));
}
}
|
NettySslContextChannelCredentials
|
java
|
apache__camel
|
components/camel-http/src/main/java/org/apache/camel/component/http/HttpConverters.java
|
{
"start": 1104,
"end": 1719
}
|
class ____ {
private HttpConverters() {
// Helper class
}
@Converter
public static Timeout toTimeout(long millis) {
return Timeout.ofMilliseconds(millis);
}
@Converter
public static Timeout toTimeout(String millis) {
return Timeout.ofMilliseconds(Long.parseLong(millis));
}
@Converter
public static TimeValue toTimeValue(long millis) {
return TimeValue.ofMilliseconds(millis);
}
@Converter
public static TimeValue toTimeValue(String millis) {
return TimeValue.ofMilliseconds(Long.parseLong(millis));
}
}
|
HttpConverters
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/SystemUtils.java
|
{
"start": 40486,
"end": 41003
}
|
class ____ loaded.
* </p>
*
* @since 3.9
*/
public static final boolean IS_JAVA_13 = getJavaVersionMatches("13");
/**
* The constant {@code true} if this is Java version 14 (also 14.x versions).
* <p>
* The result depends on the value of the {@link #JAVA_SPECIFICATION_VERSION} constant.
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_SPECIFICATION_VERSION} is {@code null}.
* </p>
* <p>
* This value is initialized when the
|
is
|
java
|
apache__flink
|
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/graph/StreamGraphGeneratorBatchExecutionTest.java
|
{
"start": 25722,
"end": 26214
}
|
class ____ extends AbstractStreamOperatorV2<Integer>
implements MultipleInputStreamOperator<Integer> {
public MultipleInputOperator(
StreamOperatorParameters<Integer> parameters, int inputsCount) {
super(parameters, inputsCount);
}
@Override
@SuppressWarnings({"rawtypes"})
public List<Input> getInputs() {
return Collections.emptyList();
}
}
private static final
|
MultipleInputOperator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/LockOnBoxedPrimitiveTest.java
|
{
"start": 4747,
"end": 6531
}
|
class ____ {
private final Object okLock = new Object();
private void test() throws InterruptedException {
okLock.wait();
okLock.wait(1);
okLock.wait(1, 2);
okLock.notify();
okLock.notifyAll();
}
}
""")
.doTest();
}
private static String bugOnSynchronizedBlock(String variableName) {
String formatString =
String.join(
"\n",
" // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock",
" synchronized (%s) {",
" }");
return String.format(formatString, variableName);
}
private static String bugOnMonitorMethods(String variableName) {
String formatString =
String.join(
"\n",
" // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock",
" %s.wait();",
" // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock",
" %<s.wait(1);",
" // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock",
" %<s.wait(1, 2);",
" // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock",
" %<s.notify();",
" // BUG: Diagnostic contains: It is dangerous to use a boxed primitive as a lock",
" %<s.notifyAll();");
return String.format(formatString, variableName);
}
@Test
public void refactoring() {
BugCheckerRefactoringTestHelper.newInstance(LockOnBoxedPrimitive.class, getClass())
.addInputLines(
"Test.java",
"""
|
Test
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/QuerydslRepositorySupportIntegrationTests.java
|
{
"start": 3825,
"end": 4149
}
|
class ____ extends QuerydslRepositorySupport {
public ReconfiguringUserRepositoryImpl() {
super(User.class);
}
@Override
@PersistenceContext(unitName = "querydsl")
public void setEntityManager(EntityManager entityManager) {
super.setEntityManager(entityManager);
}
}
static
|
ReconfiguringUserRepositoryImpl
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh17404/OracleOsonCompatibilityTest.java
|
{
"start": 5485,
"end": 5679
}
|
class ____ {
private String jsonString;
private UUID theUuid;
private LocalDateTime theLocalDateTime;
private LocalDate theLocalDate;
private LocalTime theLocalTime;
}
}
|
JsonEntityPayload
|
java
|
apache__camel
|
core/camel-main/src/main/java/org/apache/camel/main/DebuggerConfigurationProperties.java
|
{
"start": 1071,
"end": 12928
}
|
class ____ implements BootstrapCloseable {
private MainConfigurationProperties parent;
@Metadata
private boolean enabled;
@Metadata
private boolean standby;
@Metadata(label = "advanced")
private boolean waitForAttach;
@Metadata(defaultValue = "INFO")
private LoggingLevel loggingLevel = LoggingLevel.INFO;
@Metadata
private String breakpoints;
@Metadata(label = "advanced")
private boolean singleStepIncludeStartEnd;
@Metadata(defaultValue = "32768")
private int bodyMaxChars = 32 * 1024;
@Metadata
private boolean bodyIncludeStreams;
@Metadata(defaultValue = "true")
private boolean bodyIncludeFiles = true;
@Metadata(defaultValue = "true")
private boolean includeExchangeProperties = true;
@Metadata(defaultValue = "true")
private boolean includeExchangeVariables = true;
@Metadata(defaultValue = "true")
private boolean includeException = true;
@Metadata(label = "advanced", defaultValue = "300")
private long fallbackTimeout = 300;
@Metadata(label = "advanced", defaultValue = "true")
private boolean jmxConnectorEnabled = true;
@Metadata(label = "advanced", defaultValue = "1099")
private int jmxConnectorPort = 1099;
public DebuggerConfigurationProperties(MainConfigurationProperties parent) {
this.parent = parent;
}
public MainConfigurationProperties end() {
return parent;
}
@Override
public void close() {
parent = null;
}
public boolean isEnabled() {
return enabled;
}
/**
* Enables Debugger in your Camel application.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isStandby() {
return standby;
}
/**
* To set the debugger in standby mode, where the debugger will be installed by not automatic enabled. The debugger
* can then later be enabled explicit from Java, JMX or tooling.
*/
public void setStandby(boolean standby) {
this.standby = standby;
}
public boolean isWaitForAttach() {
return waitForAttach;
}
/**
* Whether the debugger should suspend on startup, and wait for a remote debugger to attach. This is what the IDEA
* and VSCode tooling is using.
*/
public void setWaitForAttach(boolean waitForAttach) {
this.waitForAttach = waitForAttach;
}
public LoggingLevel getLoggingLevel() {
return loggingLevel;
}
/**
* The debugger logging level to use when logging activity.
*/
public void setLoggingLevel(LoggingLevel loggingLevel) {
this.loggingLevel = loggingLevel;
}
public String getBreakpoints() {
return breakpoints;
}
/**
* Allows to pre-configure breakpoints (node ids) to use with debugger on startup. Multiple ids can be separated by
* comma. Use special value _all_routes_ to add a breakpoint for the first node for every route, in other words this
* makes it easy to debug from the beginning of every route without knowing the exact node ids.
*/
public void setBreakpoints(String breakpoints) {
this.breakpoints = breakpoints;
}
public boolean isSingleStepIncludeStartEnd() {
return singleStepIncludeStartEnd;
}
/**
* In single step mode, then when the exchange is created and completed, then simulate a breakpoint at start and
* end, that allows to suspend and watch the incoming/complete exchange at the route (you can see message body as
* response, failed exception etc).
*/
public void setSingleStepIncludeStartEnd(boolean singleStepIncludeStartEnd) {
this.singleStepIncludeStartEnd = singleStepIncludeStartEnd;
}
public int getBodyMaxChars() {
return bodyMaxChars;
}
/**
* To limit the message body to a maximum size in the traced message. Use 0 or negative value to use unlimited size.
*/
public void setBodyMaxChars(int bodyMaxChars) {
this.bodyMaxChars = bodyMaxChars;
}
public boolean isBodyIncludeStreams() {
return bodyIncludeStreams;
}
/**
* Whether to include the message body of stream based messages. If enabled then beware the stream may not be
* re-readable later. See more about Stream Caching.
*/
public void setBodyIncludeStreams(boolean bodyIncludeStreams) {
this.bodyIncludeStreams = bodyIncludeStreams;
}
public boolean isBodyIncludeFiles() {
return bodyIncludeFiles;
}
/**
* Whether to include the message body of file based messages. The overhead is that the file content has to be read
* from the file.
*/
public void setBodyIncludeFiles(boolean bodyIncludeFiles) {
this.bodyIncludeFiles = bodyIncludeFiles;
}
public boolean isIncludeExchangeProperties() {
return includeExchangeProperties;
}
/**
* Whether to include the exchange properties in the traced message
*/
public void setIncludeExchangeProperties(boolean includeExchangeProperties) {
this.includeExchangeProperties = includeExchangeProperties;
}
public boolean isIncludeExchangeVariables() {
return includeExchangeVariables;
}
/**
* Whether to include the exchange variables in the traced message
*/
public void setIncludeExchangeVariables(boolean includeExchangeVariables) {
this.includeExchangeVariables = includeExchangeVariables;
}
public boolean isIncludeException() {
return includeException;
}
/**
* Trace messages to include exception if the message failed
*/
public void setIncludeException(boolean includeException) {
this.includeException = includeException;
}
public long getFallbackTimeout() {
return fallbackTimeout;
}
/**
* Fallback Timeout in seconds (300 seconds as default) when block the message processing in Camel. A timeout used
* for waiting for a message to arrive at a given breakpoint.
*/
public void setFallbackTimeout(long fallbackTimeout) {
this.fallbackTimeout = fallbackTimeout;
}
public boolean isJmxConnectorEnabled() {
return jmxConnectorEnabled;
}
/**
* Whether to create JMX connector that allows tooling to control the Camel debugger. This is what the IDEA and
* VSCode tooling is using.
*/
public void setJmxConnectorEnabled(boolean jmxConnectorEnabled) {
this.jmxConnectorEnabled = jmxConnectorEnabled;
}
public int getJmxConnectorPort() {
return jmxConnectorPort;
}
/**
* Port number to expose a JMX RMI connector for tooling that needs to control the debugger.
*/
public void setJmxConnectorPort(int jmxConnectorPort) {
this.jmxConnectorPort = jmxConnectorPort;
}
/**
* Enables Debugger in your Camel application.
*/
public DebuggerConfigurationProperties withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* To set the debugger in standby mode, where the debugger will be installed by not automatic enabled. The debugger
* can then later be enabled explicit from Java, JMX or tooling.
*/
public DebuggerConfigurationProperties withStandby(boolean standby) {
this.standby = standby;
return this;
}
/**
* Whether the debugger should suspend on startup, and wait for a remote debugger to attach. This is what the IDEA
* and VSCode tooling is using.
*/
public DebuggerConfigurationProperties withWaitForAttach(boolean waitForAttach) {
this.waitForAttach = waitForAttach;
return this;
}
/**
* The debugger logging level to use when logging activity.
*/
public DebuggerConfigurationProperties withLoggingLevel(LoggingLevel loggingLevel) {
this.loggingLevel = loggingLevel;
return this;
}
/**
* Allows to pre-configure breakpoints (node ids) to use with debugger on startup. Multiple ids can be separated by
* comma. Use special value _all_routes_ to add a breakpoint for the first node for every route, in other words this
* makes it easy to debug from the beginning of every route without knowing the exact node ids.
*/
public DebuggerConfigurationProperties withBreakpoints(String breakpoints) {
this.breakpoints = breakpoints;
return this;
}
/**
* In single step mode, then when the exchange is created and completed, then simulate a breakpoint at start and
* end, that allows to suspend and watch the incoming/complete exchange at the route (you can see message body as
* response, failed exception etc).
*/
public DebuggerConfigurationProperties withSingleStepIncludeStartEnd(boolean singleStepIncludeStartEnd) {
this.singleStepIncludeStartEnd = singleStepIncludeStartEnd;
return this;
}
/**
* To limit the message body to a maximum size in the traced message. Use 0 or negative value to use unlimited size.
*/
public DebuggerConfigurationProperties withBodyMaxChars(int bodyMaxChars) {
this.bodyMaxChars = bodyMaxChars;
return this;
}
/**
* Whether to include the message body of stream based messages. If enabled then beware the stream may not be
* re-readable later. See more about Stream Caching.
*/
public DebuggerConfigurationProperties withBodyIncludeStreams(boolean bodyIncludeStreams) {
this.bodyIncludeStreams = bodyIncludeStreams;
return this;
}
/**
* Whether to include the message body of file based messages. The overhead is that the file content has to be read
* from the file.
*/
public DebuggerConfigurationProperties withBodyIncludeFiles(boolean bodyIncludeFiles) {
this.bodyIncludeFiles = bodyIncludeFiles;
return this;
}
/**
* Whether to include the exchange properties in the traced message
*/
public DebuggerConfigurationProperties withIncludeExchangeProperties(boolean includeExchangeProperties) {
this.includeExchangeProperties = includeExchangeProperties;
return this;
}
/**
* Whether to include the exchange variables in the traced message
*/
public DebuggerConfigurationProperties withIncludeExchangeVariables(boolean includeExchangeVariables) {
this.includeExchangeVariables = includeExchangeVariables;
return this;
}
/**
* Trace messages to include exception if the message failed
*/
public DebuggerConfigurationProperties withIncludeException(boolean includeException) {
this.includeException = includeException;
return this;
}
/**
* Fallback Timeout in seconds (300 seconds as default) when block the message processing in Camel. A timeout used
* for waiting for a message to arrive at a given breakpoint.
*/
public DebuggerConfigurationProperties withFallbackTimeout(long fallbackTimeout) {
this.fallbackTimeout = fallbackTimeout;
return this;
}
/**
* Whether to create JMX connector that allows tooling to control the Camel debugger. This is what the IDEA and
* VSCode tooling is using.
*/
public DebuggerConfigurationProperties withJmxConnectorEnabled(boolean jmxConnectorEnabled) {
this.jmxConnectorEnabled = jmxConnectorEnabled;
return this;
}
/**
* Port number to expose a JMX RMI connector for tooling that needs to control the debugger.
*/
public DebuggerConfigurationProperties withJmxConnectorPort(int jmxConnectorPort) {
this.jmxConnectorPort = jmxConnectorPort;
return this;
}
}
|
DebuggerConfigurationProperties
|
java
|
spring-projects__spring-boot
|
core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/service/connection/DockerComposeConnectionDetailsFactory.java
|
{
"start": 2424,
"end": 4929
}
|
class ____<D extends ConnectionDetails>
implements ConnectionDetailsFactory<DockerComposeConnectionSource, D> {
private final Predicate<DockerComposeConnectionSource> predicate;
private final String[] requiredClassNames;
/**
* Create a new {@link DockerComposeConnectionDetailsFactory} instance.
* @param connectionName the required connection name
* @param requiredClassNames the names of classes that must be present
*/
protected DockerComposeConnectionDetailsFactory(String connectionName, String... requiredClassNames) {
this(new ConnectionNamePredicate(connectionName), requiredClassNames);
}
/**
* Create a new {@link DockerComposeConnectionDetailsFactory} instance.
* @param connectionNames the required connection name
* @param requiredClassNames the names of classes that must be present
* @since 3.2.0
*/
protected DockerComposeConnectionDetailsFactory(String[] connectionNames, String... requiredClassNames) {
this(new ConnectionNamePredicate(connectionNames), requiredClassNames);
}
/**
* Create a new {@link DockerComposeConnectionDetailsFactory} instance.
* @param predicate a predicate used to check when a service is accepted
* @param requiredClassNames the names of classes that must be present
*/
protected DockerComposeConnectionDetailsFactory(Predicate<DockerComposeConnectionSource> predicate,
String... requiredClassNames) {
this.predicate = predicate;
this.requiredClassNames = requiredClassNames;
}
@Override
public final @Nullable D getConnectionDetails(DockerComposeConnectionSource source) {
return (!accept(source)) ? null : getDockerComposeConnectionDetails(source);
}
private boolean accept(DockerComposeConnectionSource source) {
return hasRequiredClasses() && this.predicate.test(source);
}
private boolean hasRequiredClasses() {
return ObjectUtils.isEmpty(this.requiredClassNames) || Arrays.stream(this.requiredClassNames)
.allMatch((requiredClassName) -> ClassUtils.isPresent(requiredClassName, null));
}
/**
* Get the {@link ConnectionDetails} from the given {@link RunningService}
* {@code source}. May return {@code null} if no connection can be created. Result
* types should consider extending {@link DockerComposeConnectionDetails}.
* @param source the source
* @return the service connection or {@code null}.
*/
protected abstract @Nullable D getDockerComposeConnectionDetails(DockerComposeConnectionSource source);
/**
* Convenient base
|
DockerComposeConnectionDetailsFactory
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.