language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/event/ApplicationEventsHolder.java | {
"start": 773,
"end": 1078
} | class ____ expose the application events published during the execution
* of a test in the form of a thread-bound {@link ApplicationEvents} object.
*
* <p>{@code ApplicationEvents} are registered in this holder and managed by
* the {@link ApplicationEventsTestExecutionListener}.
*
* <p>Although this | to |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsRemoteIT.java | {
"start": 1832,
"end": 6932
} | class ____ extends AbstractMultiClustersTestCase {
private static final String REMOTE1 = "cluster-a";
private static final String REMOTE2 = "cluster-b";
private static final String INDEX_NAME = "demo";
@Override
protected boolean reuseClusters() {
return false;
}
@Override
protected List<String> remoteClusterAlias() {
return List.of(REMOTE1, REMOTE2);
}
@Override
protected Map<String, Boolean> skipUnavailableForRemoteClusters() {
return Map.of(REMOTE1, false, REMOTE2, true);
}
public void testRemoteClusterStats() throws ExecutionException, InterruptedException {
setupClusters();
final Client client = client(LOCAL_CLUSTER);
SearchRequest searchRequest = new SearchRequest("*", "*:*");
searchRequest.allowPartialSearchResults(false);
searchRequest.setCcsMinimizeRoundtrips(randomBoolean());
searchRequest.source(new SearchSourceBuilder().query(new MatchAllQueryBuilder()).size(10));
// do a search
assertResponse(cluster(LOCAL_CLUSTER).client().search(searchRequest), Assert::assertNotNull);
// collect stats without remotes
ClusterStatsResponse response = client.admin().cluster().prepareClusterStats().get();
assertNotNull(response.getCcsMetrics());
var remotesUsage = response.getCcsMetrics().getByRemoteCluster();
assertThat(remotesUsage.size(), equalTo(3));
assertNull(response.getRemoteClustersStats());
// collect stats with remotes
response = client.admin().cluster().execute(TransportClusterStatsAction.TYPE, new ClusterStatsRequest(true)).get();
assertNotNull(response.getCcsMetrics());
remotesUsage = response.getCcsMetrics().getByRemoteCluster();
assertThat(remotesUsage.size(), equalTo(3));
assertNotNull(response.getRemoteClustersStats());
var remoteStats = response.getRemoteClustersStats();
assertThat(remoteStats.size(), equalTo(2));
for (String clusterAlias : remoteClusterAlias()) {
assertThat(remoteStats, hasKey(clusterAlias));
assertThat(remotesUsage, hasKey(clusterAlias));
assertThat(remoteStats.get(clusterAlias).status(), equalToIgnoringCase(ClusterHealthStatus.GREEN.name()));
assertThat(remoteStats.get(clusterAlias).indicesCount(), greaterThan(0L));
assertThat(remoteStats.get(clusterAlias).nodesCount(), greaterThan(0L));
assertThat(remoteStats.get(clusterAlias).shardsCount(), greaterThan(0L));
assertThat(remoteStats.get(clusterAlias).heapBytes(), greaterThan(0L));
assertThat(remoteStats.get(clusterAlias).memBytes(), greaterThan(0L));
assertThat(remoteStats.get(clusterAlias).indicesBytes(), greaterThan(0L));
assertThat(remoteStats.get(clusterAlias).versions(), hasItem(Version.CURRENT.toString()));
assertThat(remoteStats.get(clusterAlias).clusterUUID(), not(equalTo("")));
assertThat(remoteStats.get(clusterAlias).mode(), oneOf("sniff", "proxy"));
}
assertFalse(remoteStats.get(REMOTE1).skipUnavailable().get());
assertTrue(remoteStats.get(REMOTE2).skipUnavailable().get());
}
private void setupClusters() {
int numShardsLocal = randomIntBetween(2, 5);
Settings localSettings = indexSettings(numShardsLocal, randomIntBetween(0, 1)).build();
assertAcked(
client(LOCAL_CLUSTER).admin()
.indices()
.prepareCreate(INDEX_NAME)
.setSettings(localSettings)
.setMapping("@timestamp", "type=date", "f", "type=text")
);
indexDocs(client(LOCAL_CLUSTER));
int numShardsRemote = randomIntBetween(2, 10);
for (String clusterAlias : remoteClusterAlias()) {
final InternalTestCluster remoteCluster = cluster(clusterAlias);
remoteCluster.ensureAtLeastNumDataNodes(randomIntBetween(2, 3));
assertAcked(
client(clusterAlias).admin()
.indices()
.prepareCreate(INDEX_NAME)
.setSettings(indexSettings(numShardsRemote, randomIntBetween(0, 1)))
.setMapping("@timestamp", "type=date", "f", "type=text")
);
assertFalse(
client(clusterAlias).admin()
.cluster()
.prepareHealth(TEST_REQUEST_TIMEOUT, INDEX_NAME)
.setWaitForGreenStatus()
.setTimeout(TimeValue.timeValueSeconds(30))
.get()
.isTimedOut()
);
indexDocs(client(clusterAlias));
}
}
private void indexDocs(Client client) {
int numDocs = between(5, 20);
for (int i = 0; i < numDocs; i++) {
client.prepareIndex(INDEX_NAME).setSource("f", "v", "@timestamp", randomNonNegativeLong()).get();
}
client.admin().indices().prepareRefresh(INDEX_NAME).get();
}
}
| ClusterStatsRemoteIT |
java | spring-projects__spring-framework | spring-websocket/src/main/java/org/springframework/web/socket/sockjs/SockJsTransportFailureException.java | {
"start": 1042,
"end": 1698
} | class ____ extends SockJsException {
/**
* Constructor for SockJsTransportFailureException.
* @param message the exception message
* @param cause the root cause
* @since 4.1.7
*/
public SockJsTransportFailureException(String message, @Nullable Throwable cause) {
super(message, cause);
}
/**
* Constructor for SockJsTransportFailureException.
* @param message the exception message
* @param sessionId the SockJS session id
* @param cause the root cause
*/
public SockJsTransportFailureException(String message, String sessionId, @Nullable Throwable cause) {
super(message, sessionId, cause);
}
}
| SockJsTransportFailureException |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/FloatFieldTest.java | {
"start": 513,
"end": 723
} | class ____ {
private float value;
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
}
}
| User |
java | apache__kafka | streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java | {
"start": 33798,
"end": 35152
} | class ____<K, V> extends AsyncKafkaConsumer<K, V> implements TestingMetricsInterceptor {
private final List<KafkaMetric> passedMetrics = new ArrayList<>();
public TestingMetricsInterceptingAsyncConsumer(
final Map<String, Object> configs,
final Deserializer<K> keyDeserializer,
final Deserializer<V> valueDeserializer,
final Optional<StreamsRebalanceData> streamsRebalanceData
) {
super(
new ConsumerConfig(
ConsumerConfig.appendDeserializerToConfig(configs, keyDeserializer, valueDeserializer)
),
keyDeserializer,
valueDeserializer,
streamsRebalanceData
);
}
@Override
public void registerMetricForSubscription(final KafkaMetric metric) {
passedMetrics.add(metric);
super.registerMetricForSubscription(metric);
}
@Override
public void unregisterMetricFromSubscription(final KafkaMetric metric) {
passedMetrics.remove(metric);
super.unregisterMetricFromSubscription(metric);
}
@Override
public List<KafkaMetric> passedMetrics() {
return passedMetrics;
}
}
public static | TestingMetricsInterceptingAsyncConsumer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 71560,
"end": 72408
} | class ____ {
final WithContainerOf<ImmutableInterface> a = null;
final WithoutContainerOf<ImmutableInterface> b = null;
// MutableImpl is assumed to be immutable given it subclasses ImmutableInterface.
final WithContainerOf<MutableImpl> c = null;
final WithoutContainerOf<MutableImpl> d = null;
}
""")
.doTest();
}
// regression test for b/77781008
@Test
public void immutableTypeParameter_twoInstantiations() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.errorprone.annotations.ImmutableTypeParameter;
import com.google.errorprone.annotations.Immutable;
import com.google.common.collect.ImmutableList;
@Immutable
| Test |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/test/java/org/apache/hadoop/mapred/TestMRWithDistributedCache.java | {
"start": 5151,
"end": 5842
} | class ____.
assertNotNull(cl.getResource("distributed.jar.inside2"));
assertNotNull(cl.getResource("distributed.jar.inside3"));
assertNull(cl.getResource("distributed.jar.inside4"));
// Check that the symlink for the renaming was created in the cwd;
assertTrue(symlinkFile.exists(),
"symlink distributed.first.symlink doesn't exist");
assertEquals(1,
symlinkFile.length(),
"symlink distributed.first.symlink length not 1");
//This last one is a difference between MRv2 and MRv1
assertTrue(expectedAbsentSymlinkFile.exists(),
"second file should be symlinked too");
}
}
public static | loader |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ParameterResolverTests.java | {
"start": 12331,
"end": 12883
} | class ____ {
private final TestInfo innerTestInfo;
private final CustomType innerCustomType;
NestedTestCase(TestInfo testInfo, CustomType customType) {
this.innerTestInfo = testInfo;
this.innerCustomType = customType;
}
@Test
void test() {
assertNotNull(outerTestInfo);
assertNotNull(outerCustomType);
assertNotNull(this.innerTestInfo);
assertNotNull(this.innerCustomType);
}
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
@ExtendWith(CustomAnnotationParameterResolver.class)
static | NestedTestCase |
java | dropwizard__dropwizard | docs/source/examples/conscrypt/src/main/java/io/dropwizard/documentation/ConscryptApp.java | {
"start": 241,
"end": 589
} | class ____ extends Application<Configuration> {
// conscrypt: ConscryptApp->OpenSSLProvider
static {
Security.insertProviderAt(new OpenSSLProvider(), 1);
}
// conscrypt: ConscryptApp->OpenSSLProvider
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
}
}
| ConscryptApp |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java | {
"start": 2078,
"end": 3334
} | enum ____ implements Feature<Collection>, Comparable<CollectionSize> {
/** Test an empty collection. */
ZERO(0),
/** Test a one-element collection. */
ONE(1),
/** Test a three-element collection. */
SEVERAL(3),
/*
* TODO: add VERY_LARGE, noting that we currently assume that the fourth
* sample element is not in any collection
*/
ANY(ZERO, ONE, SEVERAL);
private final Set<Feature<? super Collection>> implied;
private final @Nullable Integer numElements;
CollectionSize(int numElements) {
this.implied = emptySet();
this.numElements = numElements;
}
CollectionSize(Feature<? super Collection>... implied) {
// Keep the order here, so that PerCollectionSizeTestSuiteBuilder
// gives a predictable order of test suites.
this.implied = copyToSet(implied);
this.numElements = null;
}
@Override
public Set<Feature<? super Collection>> getImpliedFeatures() {
return implied;
}
public int getNumElements() {
if (numElements == null) {
throw new IllegalStateException(
"A compound CollectionSize doesn't specify a number of elements.");
}
return numElements;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @ | CollectionSize |
java | apache__camel | components/camel-reactive-streams/src/generated/java/org/apache/camel/component/reactive/streams/ReactiveStreamsComponentConfigurer.java | {
"start": 743,
"end": 5233
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
ReactiveStreamsComponent target = (ReactiveStreamsComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "backpressurestrategy":
case "backpressureStrategy": target.setBackpressureStrategy(property(camelContext, org.apache.camel.component.reactive.streams.ReactiveStreamsBackpressureStrategy.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "reactivestreamsengineconfiguration":
case "reactiveStreamsEngineConfiguration": target.setReactiveStreamsEngineConfiguration(property(camelContext, org.apache.camel.component.reactive.streams.engine.ReactiveStreamsEngineConfiguration.class, value)); return true;
case "servicetype":
case "serviceType": target.setServiceType(property(camelContext, java.lang.String.class, value)); return true;
case "threadpoolmaxsize":
case "threadPoolMaxSize": target.setThreadPoolMaxSize(property(camelContext, int.class, value)); return true;
case "threadpoolminsize":
case "threadPoolMinSize": target.setThreadPoolMinSize(property(camelContext, int.class, value)); return true;
case "threadpoolname":
case "threadPoolName": target.setThreadPoolName(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "backpressurestrategy":
case "backpressureStrategy": return org.apache.camel.component.reactive.streams.ReactiveStreamsBackpressureStrategy.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "reactivestreamsengineconfiguration":
case "reactiveStreamsEngineConfiguration": return org.apache.camel.component.reactive.streams.engine.ReactiveStreamsEngineConfiguration.class;
case "servicetype":
case "serviceType": return java.lang.String.class;
case "threadpoolmaxsize":
case "threadPoolMaxSize": return int.class;
case "threadpoolminsize":
case "threadPoolMinSize": return int.class;
case "threadpoolname":
case "threadPoolName": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
ReactiveStreamsComponent target = (ReactiveStreamsComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "backpressurestrategy":
case "backpressureStrategy": return target.getBackpressureStrategy();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "reactivestreamsengineconfiguration":
case "reactiveStreamsEngineConfiguration": return target.getReactiveStreamsEngineConfiguration();
case "servicetype":
case "serviceType": return target.getServiceType();
case "threadpoolmaxsize":
case "threadPoolMaxSize": return target.getThreadPoolMaxSize();
case "threadpoolminsize":
case "threadPoolMinSize": return target.getThreadPoolMinSize();
case "threadpoolname":
case "threadPoolName": return target.getThreadPoolName();
default: return null;
}
}
}
| ReactiveStreamsComponentConfigurer |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalPooledTaskFactory.java | {
"start": 995,
"end": 1595
} | class ____ extends PooledObjectFactorySupport<CamelInternalTask> {
@Override
public void setStatisticsEnabled(boolean statisticsEnabled) {
// we do not want to capture statistics so its disabled
}
@Override
public CamelInternalTask acquire() {
return pool.poll();
}
@Override
public boolean release(CamelInternalTask task) {
task.reset();
return pool.offer(task);
}
@Override
public String toString() {
return "CamelInternalPooledTaskFactory[capacity: " + getCapacity() + "]";
}
}
| CamelInternalPooledTaskFactory |
java | apache__maven | impl/maven-logging/src/main/java/org/apache/maven/slf4j/SimpleLoggerConfiguration.java | {
"start": 1538,
"end": 10246
} | class ____ {
private static final String CONFIGURATION_FILE = "maven.logger.properties";
@Deprecated(since = "4.0.0")
private static final String LEGACY_CONFIGURATION_FILE = "simplelogger.properties";
static final int DEFAULT_LOG_LEVEL_DEFAULT = MavenBaseLogger.LOG_LEVEL_INFO;
int defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT;
private static final boolean SHOW_DATE_TIME_DEFAULT = false;
boolean showDateTime = SHOW_DATE_TIME_DEFAULT;
private static final String DATE_TIME_FORMAT_STR_DEFAULT = null;
DateTimeFormatter dateFormatter = null;
private static final boolean SHOW_THREAD_NAME_DEFAULT = true;
boolean showThreadName = SHOW_THREAD_NAME_DEFAULT;
/**
* See https://jira.qos.ch/browse/SLF4J-499
* @since 1.7.33 and 2.0.0-alpha6
*/
private static final boolean SHOW_THREAD_ID_DEFAULT = false;
boolean showThreadId = SHOW_THREAD_ID_DEFAULT;
static final boolean SHOW_LOG_NAME_DEFAULT = true;
boolean showLogName = SHOW_LOG_NAME_DEFAULT;
private static final boolean SHOW_SHORT_LOG_NAME_DEFAULT = false;
boolean showShortLogName = SHOW_SHORT_LOG_NAME_DEFAULT;
private static final boolean LEVEL_IN_BRACKETS_DEFAULT = false;
boolean levelInBrackets = LEVEL_IN_BRACKETS_DEFAULT;
private static final String LOG_FILE_DEFAULT = "System.err";
private String logFile = LOG_FILE_DEFAULT;
OutputChoice outputChoice = null;
private static final boolean CACHE_OUTPUT_STREAM_DEFAULT = false;
private boolean cacheOutputStream = CACHE_OUTPUT_STREAM_DEFAULT;
private static final String WARN_LEVELS_STRING_DEFAULT = "WARN";
String warnLevelString = WARN_LEVELS_STRING_DEFAULT;
private final Properties properties = new Properties();
void init() {
// Reset state before initialization
dateFormatter = null;
loadProperties();
String defaultLogLevelString = getStringProperty(Constants.MAVEN_LOGGER_DEFAULT_LOG_LEVEL, null);
if (defaultLogLevelString != null) {
defaultLogLevel = stringToLevel(defaultLogLevelString);
}
// local variable,
String dateTimeFormatStr;
showLogName = getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_LOG_NAME, SHOW_LOG_NAME_DEFAULT);
showShortLogName = getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_SHORT_LOG_NAME, SHOW_SHORT_LOG_NAME_DEFAULT);
showDateTime = getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_DATE_TIME, SHOW_DATE_TIME_DEFAULT);
showThreadName = getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_THREAD_NAME, SHOW_THREAD_NAME_DEFAULT);
showThreadId = getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_THREAD_ID, SHOW_THREAD_ID_DEFAULT);
dateTimeFormatStr = getStringProperty(Constants.MAVEN_LOGGER_DATE_TIME_FORMAT, DATE_TIME_FORMAT_STR_DEFAULT);
levelInBrackets = getBooleanProperty(Constants.MAVEN_LOGGER_LEVEL_IN_BRACKETS, LEVEL_IN_BRACKETS_DEFAULT);
warnLevelString = getStringProperty(Constants.MAVEN_LOGGER_WARN_LEVEL, WARN_LEVELS_STRING_DEFAULT);
logFile = getStringProperty(Constants.MAVEN_LOGGER_LOG_FILE, logFile);
cacheOutputStream = getBooleanProperty(Constants.MAVEN_LOGGER_CACHE_OUTPUT_STREAM, CACHE_OUTPUT_STREAM_DEFAULT);
outputChoice = computeOutputChoice(logFile, cacheOutputStream);
if (dateTimeFormatStr != null) {
try {
dateFormatter = DateTimeFormatter.ofPattern(dateTimeFormatStr);
} catch (IllegalArgumentException e) {
Reporter.error("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e);
}
}
}
private void loadProperties() {
ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
ClassLoader toUseCL = (threadCL != null ? threadCL : ClassLoader.getSystemClassLoader());
// Try loading maven properties first
boolean mavenPropsLoaded = false;
try (InputStream in = toUseCL.getResourceAsStream(CONFIGURATION_FILE)) {
if (in != null) {
properties.load(in);
mavenPropsLoaded = true;
}
} catch (java.io.IOException e) {
// ignored
}
// Try loading legacy properties
try (InputStream in = toUseCL.getResourceAsStream(LEGACY_CONFIGURATION_FILE)) {
if (in != null) {
Properties legacyProps = new Properties();
legacyProps.load(in);
if (!mavenPropsLoaded) {
Reporter.warn("Using deprecated " + LEGACY_CONFIGURATION_FILE + ". Please migrate to "
+ CONFIGURATION_FILE);
}
// Only load legacy properties if there's no maven equivalent
for (String propName : legacyProps.stringPropertyNames()) {
String mavenKey = propName.replace(MavenBaseLogger.LEGACY_PREFIX, Constants.MAVEN_LOGGER_PREFIX);
if (!properties.containsKey(mavenKey)) {
properties.setProperty(mavenKey, legacyProps.getProperty(propName));
}
}
}
} catch (java.io.IOException e) {
// ignored
}
}
String getStringProperty(String name, String defaultValue) {
String prop = getStringProperty(name);
return (prop == null) ? defaultValue : prop;
}
boolean getBooleanProperty(String name, boolean defaultValue) {
String prop = getStringProperty(name);
return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
}
String getStringProperty(String name) {
String prop = null;
try {
// Try maven property first
prop = System.getProperty(name);
if (prop == null && name.startsWith(Constants.MAVEN_LOGGER_PREFIX)) {
// Try legacy property
String legacyName = name.replace(Constants.MAVEN_LOGGER_PREFIX, MavenBaseLogger.LEGACY_PREFIX);
prop = System.getProperty(legacyName);
if (prop != null) {
Reporter.warn("Using deprecated property " + legacyName + ". Please migrate to " + name);
}
}
} catch (SecurityException e) {
// Ignore
}
if (prop == null) {
prop = properties.getProperty(name);
if (prop == null && name.startsWith(Constants.MAVEN_LOGGER_PREFIX)) {
// Try legacy property from properties file
String legacyName = name.replace(Constants.MAVEN_LOGGER_PREFIX, MavenBaseLogger.LEGACY_PREFIX);
prop = properties.getProperty(legacyName);
if (prop != null) {
Reporter.warn("Using deprecated property " + legacyName + ". Please migrate to " + name);
}
}
}
return prop;
}
static int stringToLevel(String levelStr) {
if ("trace".equalsIgnoreCase(levelStr)) {
return MavenBaseLogger.LOG_LEVEL_TRACE;
} else if ("debug".equalsIgnoreCase(levelStr)) {
return MavenBaseLogger.LOG_LEVEL_DEBUG;
} else if ("info".equalsIgnoreCase(levelStr)) {
return MavenBaseLogger.LOG_LEVEL_INFO;
} else if ("warn".equalsIgnoreCase(levelStr)) {
return MavenBaseLogger.LOG_LEVEL_WARN;
} else if ("error".equalsIgnoreCase(levelStr)) {
return MavenBaseLogger.LOG_LEVEL_ERROR;
} else if ("off".equalsIgnoreCase(levelStr)) {
return MavenBaseLogger.LOG_LEVEL_OFF;
}
// assume INFO by default
return MavenBaseLogger.LOG_LEVEL_INFO;
}
private static OutputChoice computeOutputChoice(String logFile, boolean cacheOutputStream) {
if ("System.err".equalsIgnoreCase(logFile)) {
return new OutputChoice(cacheOutputStream ? OutputChoiceType.CACHED_SYS_ERR : OutputChoiceType.SYS_ERR);
} else if ("System.out".equalsIgnoreCase(logFile)) {
return new OutputChoice(cacheOutputStream ? OutputChoiceType.CACHED_SYS_OUT : OutputChoiceType.SYS_OUT);
} else {
try {
FileOutputStream fos = new FileOutputStream(logFile, true);
PrintStream printStream = new PrintStream(fos, true);
return new OutputChoice(printStream);
} catch (FileNotFoundException e) {
Reporter.error("Could not open [" + logFile + "]. Defaulting to System.err", e);
return new OutputChoice(OutputChoiceType.SYS_ERR);
}
}
}
}
| SimpleLoggerConfiguration |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/api/RangeSetAssert_hasSize_Test.java | {
"start": 1174,
"end": 2610
} | class ____ {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
RangeSet<Integer> actual = null;
// WHEN
var error = expectAssertionError(() -> assertThat(actual).hasSize(5));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_actual_size_does_not_match_expected() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.<Integer> builder()
.add(closed(1, 10))
.add(closed(20, 35))
.add(closed(40, 45))
.build();
// WHEN
var error = expectAssertionError(() -> assertThat(actual).hasSize(5));
// THEN
then(error).isInstanceOf(AssertionError.class)
.hasMessage(shouldHaveSize(actual, actual.asRanges().size(), 5).create());
}
@Test
void should_pass_if_actual_size_matches_expected() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.<Integer> builder()
.add(closed(1, 10))
.add(closed(20, 35))
.add(closed(40, 45))
.build();
// WHEN/THEN
assertThat(actual).hasSize(actual.asRanges().size());
}
}
| RangeSetAssert_hasSize_Test |
java | google__dagger | dagger-producers/main/java/dagger/producers/internal/AbstractProducer.java | {
"start": 3603,
"end": 4571
} | class ____<T> extends AbstractFuture<T> {
@Override
public boolean setFuture(ListenableFuture<? extends T> future) {
return super.setFuture(future);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
/** Actually cancels this future. */
void doCancel(boolean mayInterruptIfRunning) {
super.cancel(mayInterruptIfRunning);
}
}
private static <T> ListenableFuture<T> nonCancellationPropagating(ListenableFuture<T> future) {
if (future.isDone()) {
return future;
}
NonCancellationPropagatingFuture<T> output = new NonCancellationPropagatingFuture<T>(future);
future.addListener(output, directExecutor());
return output;
}
/**
* Equivalent to {@code Futures.nonCancellationPropagating}, but allowing us to check whether or
* not {@code mayInterruptIfRunning} was set when cancelling it.
*/
private static final | NonExternallyCancellableFuture |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/authentication/HttpStatusEntryPointTests.java | {
"start": 1184,
"end": 2023
} | class ____ {
MockHttpServletRequest request;
MockHttpServletResponse response;
AuthenticationException authException;
HttpStatusEntryPoint entryPoint;
@SuppressWarnings("serial")
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.authException = new AuthenticationException("") {
};
this.entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}
@Test
public void constructorNullStatus() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusEntryPoint(null));
}
@Test
public void unauthorized() throws Exception {
this.entryPoint.commence(this.request, this.response, this.authException);
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
}
}
| HttpStatusEntryPointTests |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/schema/SchemaUpdateHelper.java | {
"start": 728,
"end": 2090
} | class ____ {
public static void update(Metadata metadata) {
update( metadata, ( ( MetadataImplementor) metadata ).getMetadataBuildingOptions().getServiceRegistry() );
}
public static void update(Metadata metadata, ServiceRegistry serviceRegistry) {
final Map settings = serviceRegistry.getService( ConfigurationService.class ).getSettings();
settings.put( AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, Action.UPDATE );
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
settings,
DelayedDropRegistryNotAvailableImpl.INSTANCE
);
}
@AllowSysOut
public static void toStdout(Metadata metadata) {
toWriter( metadata, new OutputStreamWriter( System.out ) );
}
public static void toWriter(Metadata metadata, Writer writer) {
final ServiceRegistry serviceRegistry = ( (MetadataImplementor) metadata ).getMetadataBuildingOptions().getServiceRegistry();
final Map settings = serviceRegistry.getService( ConfigurationService.class ).getSettings();
settings.put( AvailableSettings.HBM2DDL_SCRIPTS_ACTION, Action.UPDATE );
// atm we reuse the CREATE scripts setting
settings.put( AvailableSettings.HBM2DDL_SCRIPTS_CREATE_TARGET, writer );
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
settings,
DelayedDropRegistryNotAvailableImpl.INSTANCE
);
}
}
| SchemaUpdateHelper |
java | bumptech__glide | third_party/disklrucache/src/main/java/com/bumptech/glide/disklrucache/DiskLruCache.java | {
"start": 25465,
"end": 28280
} | class ____ {
private final Entry entry;
private final boolean[] written;
private boolean committed;
private Editor(Entry entry) {
this.entry = entry;
this.written = (entry.readable) ? null : new boolean[valueCount];
}
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
private InputStream newInputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
return null;
}
try {
return new FileInputStream(entry.getCleanFile(index));
} catch (FileNotFoundException e) {
return null;
}
}
}
/**
* Returns the last committed value as a string, or null if no value
* has been committed.
*/
public String getString(int index) throws IOException {
InputStream in = newInputStream(index);
return in != null ? inputStreamToString(in) : null;
}
public File getFile(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
written[index] = true;
}
File dirtyFile = entry.getDirtyFile(index);
directory.mkdirs();
return dirtyFile;
}
}
/** Sets the value at {@code index} to {@code value}. */
public void set(int index, String value) throws IOException {
Writer writer = null;
try {
OutputStream os = new FileOutputStream(getFile(index));
writer = new OutputStreamWriter(os, Util.UTF_8);
writer.write(value);
} finally {
Util.closeQuietly(writer);
}
}
/**
* Commits this edit so it is visible to readers. This releases the
* edit lock so another edit may be started on the same key.
*/
public void commit() throws IOException {
// The object using this Editor must catch and handle any errors
// during the write. If there is an error and they call commit
// anyway, we will assume whatever they managed to write was valid.
// Normally they should call abort.
completeEdit(this, true);
committed = true;
}
/**
* Aborts this edit. This releases the edit lock so another edit may be
* started on the same key.
*/
public void abort() throws IOException {
completeEdit(this, false);
}
public void abortUnlessCommitted() {
if (!committed) {
try {
abort();
} catch (IOException ignored) {
}
}
}
}
private final | Editor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyWithSealedClassesTest.java | {
"start": 2228,
"end": 2342
} | class ____ {
@Id
@GeneratedValue
private Long id;
}
@Entity(name = "Postman")
public static non-sealed | Actor |
java | google__guava | android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java | {
"start": 3764,
"end": 4569
} | class ____ perform
* significantly worse than a {@code PriorityQueue} with manual eviction above the maximum
* size. In many cases {@link Ordering#leastOf} may work for your use case with significantly
* improved (and asymptotically superior) performance.
* <li>The retrieval operations {@link #peek}, {@link #peekFirst}, {@link #peekLast}, {@link
* #element}, and {@link #size} are constant-time.
* <li>The enqueuing and dequeuing operations ({@link #offer}, {@link #add}, and all the forms of
* {@link #poll} and {@link #remove()}) run in {@code O(log n) time}.
* <li>The {@link #remove(Object)} and {@link #contains} operations require linear ({@code O(n)})
* time.
* <li>If you only access one end of the queue, and don't use a maximum size, this | will |
java | google__guava | android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java | {
"start": 18588,
"end": 19403
} | class ____ method
@Override
public E next() {
if (cursor >= array.length) throw new NoSuchElementException();
lastRet = cursor;
// array comes from q.toArray() and so should have only E's in it
@SuppressWarnings("unchecked")
E e = (E) array[cursor++];
return e;
}
@Override
public void remove() {
if (lastRet < 0) throw new IllegalStateException();
Object x = array[lastRet];
lastRet = -1;
// Traverse underlying queue to find == element,
// not just a .equals element.
monitor.enter();
try {
for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
if (it.next() == x) {
it.remove();
return;
}
}
} finally {
monitor.leave();
}
}
}
}
| to |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/enrich/EnrichLookupService.java | {
"start": 8363,
"end": 11290
} | class ____ extends AbstractLookupService.TransportRequest {
private final String matchType;
private final String matchField;
/**
* For mixed clusters with nodes <8.14, this will be null.
*/
@Nullable
final DataType inputDataType;
TransportRequest(
String sessionId,
ShardId shardId,
DataType inputDataType,
String matchType,
String matchField,
Page inputPage,
Page toRelease,
List<NamedExpression> extractFields,
Source source
) {
super(sessionId, shardId, shardId.getIndexName(), inputPage, toRelease, extractFields, source);
this.matchType = matchType;
this.matchField = matchField;
this.inputDataType = inputDataType;
}
static TransportRequest readFrom(StreamInput in, BlockFactory blockFactory) throws IOException {
TaskId parentTaskId = TaskId.readFromStream(in);
String sessionId = in.readString();
ShardId shardId = new ShardId(in);
DataType inputDataType = DataType.fromTypeName(in.readString());
String matchType = in.readString();
String matchField = in.readString();
Page inputPage;
try (BlockStreamInput bsi = new BlockStreamInput(in, blockFactory)) {
inputPage = new Page(bsi);
}
PlanStreamInput planIn = new PlanStreamInput(in, in.namedWriteableRegistry(), null);
List<NamedExpression> extractFields = planIn.readNamedWriteableCollectionAsList(NamedExpression.class);
var source = Source.readFrom(planIn);
TransportRequest result = new TransportRequest(
sessionId,
shardId,
inputDataType,
matchType,
matchField,
inputPage,
inputPage,
extractFields,
source
);
result.setParentTask(parentTaskId);
return result;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(sessionId);
out.writeWriteable(shardId);
out.writeString(inputDataType.typeName());
out.writeString(matchType);
out.writeString(matchField);
out.writeWriteable(inputPage);
PlanStreamOutput planOut = new PlanStreamOutput(out, null);
planOut.writeNamedWriteableCollection(extractFields);
source.writeTo(planOut);
}
@Override
protected String extraDescription() {
return " ,input_type=" + inputDataType + " ,match_type=" + matchType + " ,match_field=" + matchField;
}
}
private static | TransportRequest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointRecipientList2Test.java | {
"start": 1170,
"end": 2803
} | class ____ extends ContextTestSupport {
private static String beforeThreadName;
private static String afterThreadName;
@Test
public void testAsyncEndpoint() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel");
getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel");
String reply = template.requestBody("direct:start", "Hello Camel", String.class);
assertEquals("Bye Camel", reply);
assertMockEndpointsSatisfied();
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
context.addComponent("async", new MyAsyncComponent());
from("direct:start").to("mock:before").to("log:before").process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName = Thread.currentThread().getName();
}
}).recipientList(constant("direct:foo"));
from("direct:foo").to("async:bye:camel").process(new Processor() {
public void process(Exchange exchange) {
afterThreadName = Thread.currentThread().getName();
}
}).to("log:after").to("mock:after").to("mock:result");
}
};
}
}
| AsyncEndpointRecipientList2Test |
java | apache__camel | tooling/camel-tooling-model/src/main/java/org/apache/camel/tooling/model/LanguageModel.java | {
"start": 903,
"end": 1149
} | class ____ extends ArtifactModel<LanguageModel.LanguageOptionModel> {
protected String modelName;
protected String modelJavaType;
protected final List<LanguageFunctionModel> functions = new ArrayList<>();
public static | LanguageModel |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/spi/ExtendedLogger.java | {
"start": 17007,
"end": 17861
} | class ____
* method when location information needs to be logged.
* @param level The logging Level to check.
* @param marker A Marker or null.
* @param message The message format.
* @param p0 the message parameters
* @param p1 the message parameters
* @param p2 the message parameters
* @param p3 the message parameters
* @param p4 the message parameters
* @param p5 the message parameters
* @since 2.6
*/
void logIfEnabled(
String fqcn,
Level level,
Marker marker,
String message,
Object p0,
Object p1,
Object p2,
Object p3,
Object p4,
Object p5);
/**
* Logs a message if the specified level is active.
*
* @param fqcn The fully qualified | and |
java | micronaut-projects__micronaut-core | http-netty/src/main/java/io/micronaut/http/netty/channel/EpollAvailabilityCondition.java | {
"start": 913,
"end": 1276
} | class ____ implements Condition {
/**
* Checks if netty's epoll native transport is available.
*
* @param context The ConditionContext.
* @return true if the epoll native transport is available.
*/
@Override
public boolean matches(ConditionContext context) {
return Epoll.isAvailable();
}
}
| EpollAvailabilityCondition |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/GenericConverterAutoApplyTest.java | {
"start": 2691,
"end": 2809
} | class ____ {
@Id
@GeneratedValue
Long id;
Integer[] integerArray;
List<Integer> integerList;
}
}
| TestEntity |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/jdk/JavaUtilDateSerializationTest.java | {
"start": 1453,
"end": 1685
} | class ____ {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
public Date date;
public DateInCETBean(long l) { date = new java.util.Date(l); }
}
static | DateInCETBean |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/paths/Paths_assertHasSameFileSystemAsPath_Test.java | {
"start": 1384,
"end": 5191
} | class ____ extends PathsBaseTest {
@Test
void should_fail_if_actual_path_is_null() {
// GIVEN
Path expectedPath = mock(Path.class, withSettings().stubOnly());
// WHEN
var error = expectAssertionError(() -> underTest.assertHasSameFileSystemAs(INFO, null, expectedPath));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_expected_path_is_null() {
// GIVEN
Path actualPath = mock(Path.class, withSettings().stubOnly());
// WHEN
Throwable error = catchThrowable(() -> underTest.assertHasSameFileSystemAs(INFO, actualPath, null));
// THEN
then(error).isInstanceOf(NullPointerException.class)
.hasMessage("The expected path should not be null");
}
@Test
void should_fail_if_expected_filesystem_is_null() {
// GIVEN
Path actualPath = mock(Path.class, withSettings().stubOnly());
FileSystem actualFileSystem = mock(FileSystem.class, withSettings().stubOnly());
given(actualPath.getFileSystem()).willReturn(actualFileSystem);
Path expectedPath = mock(Path.class, withSettings().stubOnly());
given(expectedPath.getFileSystem()).willReturn(null);
// WHEN
Throwable error = catchThrowable(() -> underTest.assertHasSameFileSystemAs(INFO, actualPath, expectedPath));
// THEN
then(error).isInstanceOf(NullPointerException.class)
.hasMessage("The expected file system should not be null");
}
@Test
void should_fail_if_actual_filesystem_is_null() {
// GIVEN
Path actualPath = mock(Path.class, withSettings().stubOnly());
given(actualPath.getFileSystem()).willReturn(null);
Path expectedPath = mock(Path.class, withSettings().stubOnly());
FileSystem expectedFileSystem = mock(FileSystem.class, withSettings().stubOnly());
given(expectedPath.getFileSystem()).willReturn(expectedFileSystem);
// WHEN
Throwable error = catchThrowable(() -> underTest.assertHasSameFileSystemAs(INFO, actualPath, expectedPath));
// THEN
then(error).isInstanceOf(NullPointerException.class)
.hasMessage("The actual file system should not be null");
}
@Test
void should_fail_if_file_systems_differ() {
// GIVEN
Path actualPath = mock(Path.class, withSettings().stubOnly());
FileSystem actualFileSystem = mock(FileSystem.class, withSettings().stubOnly());
given(actualPath.getFileSystem()).willReturn(actualFileSystem);
Path expectedPath = mock(Path.class, withSettings().stubOnly());
FileSystem expectedFileSystem = mock(FileSystem.class, withSettings().stubOnly());
given(expectedPath.getFileSystem()).willReturn(expectedFileSystem);
// WHEN
var error = expectAssertionError(() -> underTest.assertHasSameFileSystemAs(INFO, actualPath, expectedPath));
// THEN
then(error).hasMessage(shouldHaveSameFileSystemAs(actualPath, expectedPath).create())
.isInstanceOf(AssertionFailedError.class)
.extracting(AssertionFailedError.class::cast)
.satisfies(failure -> assertThat(failure.getActual().getEphemeralValue()).isSameAs(actualFileSystem))
.satisfies(failure -> assertThat(failure.getExpected().getEphemeralValue()).isSameAs(expectedFileSystem));
}
@Test
void should_succeed_if_file_systems_are_same() {
// GIVEN
Path actualPath = mock(Path.class, withSettings().stubOnly());
FileSystem actualFileSystem = mock(FileSystem.class, withSettings().stubOnly());
given(actualPath.getFileSystem()).willReturn(actualFileSystem);
Path expectedPath = mock(Path.class, withSettings().stubOnly());
given(expectedPath.getFileSystem()).willReturn(actualFileSystem);
// WHEN/THEN
underTest.assertHasSameFileSystemAs(INFO, actualPath, expectedPath);
}
}
| Paths_assertHasSameFileSystemAsPath_Test |
java | quarkusio__quarkus | core/deployment/src/test/java/io/quarkus/deployment/recording/JobDetails.java | {
"start": 182,
"end": 2420
} | class ____ {
private final String className;
private final String staticFieldName;
private final String methodName;
private final ArrayList<JobParameter> jobParameters;
private Boolean cacheable;
private JobDetails() {
this(null, null, null, null);
// used for deserialization
}
public JobDetails(String className, String staticFieldName, String methodName, List<JobParameter> jobParameters) {
this.className = className;
this.staticFieldName = staticFieldName;
this.methodName = methodName;
this.jobParameters = new ArrayList<>(jobParameters);
this.cacheable = false;
}
public String getClassName() {
return className;
}
public String getStaticFieldName() {
return staticFieldName;
}
public boolean hasStaticFieldName() {
return staticFieldName != null;
}
public String getMethodName() {
return methodName;
}
public List<JobParameter> getJobParameters() {
return unmodifiableList(jobParameters);
}
public Class[] getJobParameterTypes() {
return jobParameters.stream()
.map(JobParameter::getClassName)
.toArray(Class[]::new);
}
public Object[] getJobParameterValues() {
return jobParameters.stream()
.map(JobParameter::getObject)
.toArray();
}
public Boolean getCacheable() {
return cacheable;
}
public void setCacheable(boolean cacheable) {
this.cacheable = cacheable;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof JobDetails that))
return false;
return Objects.equals(className, that.className)
&& Objects.equals(staticFieldName, that.staticFieldName)
&& Objects.equals(methodName, that.methodName)
&& Objects.equals(jobParameters, that.jobParameters)
&& Objects.equals(cacheable, that.cacheable);
}
@Override
public int hashCode() {
return Objects.hash(className, staticFieldName, methodName, jobParameters, cacheable);
}
}
| JobDetails |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyCursor.java | {
"start": 546,
"end": 1541
} | class ____ implements Cursor {
static final String NAME = "0";
static final EmptyCursor INSTANCE = new EmptyCursor();
private EmptyCursor() {
// Only one instance allowed
}
@Override
public void writeTo(StreamOutput out) throws IOException {
// Nothing to write
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public void nextPage(SqlConfiguration cfg, Client client, ActionListener<Page> listener) {
throw new SqlIllegalArgumentException("there is no next page");
}
@Override
public void clear(Client client, ActionListener<Boolean> listener) {
// There is nothing to clean
listener.onResponse(false);
}
@Override
public boolean equals(Object obj) {
return obj == this;
}
@Override
public int hashCode() {
return 27;
}
@Override
public String toString() {
return "no next page";
}
}
| EmptyCursor |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/services/ExtensibleEnumRegistry.java | {
"start": 1073,
"end": 1202
} | enum ____ by their identifiers.
* <p>
* This service provides access to all registered instances of a specific extensible | instances |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/utils/TypeStringUtilsTest.java | {
"start": 8079,
"end": 8323
} | class ____ {
public int field1;
public String field2;
public TestNoPojo(int field1, String field2) { // no default constructor
this.field1 = field1;
this.field2 = field2;
}
}
}
| TestNoPojo |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/name/NameResolutionTest.java | {
"start": 1614,
"end": 1894
} | class ____ {
@Named // -> defaulted to "producedBing"
@Produces
String producedBing = "bing";
@Named // -> defaulted to "bongo"
@Produces
Integer getBongo() {
return 12345;
}
}
@Dependent
static | Bravo |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/ToUpperConverter.java | {
"start": 261,
"end": 684
} | class ____ implements AttributeConverter<String,String> {
@Override
public String convertToDatabaseColumn(String value) {
if ( value == null ) {
return null;
}
return value.toUpperCase( Locale.ROOT );
}
@Override
public String convertToEntityAttribute(String value) {
if ( value == null ) {
return null;
}
assert value.toUpperCase( Locale.ROOT ).equals( value );
return value;
}
}
| ToUpperConverter |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/codec/FindBinary.java | {
"start": 1257,
"end": 2188
} | class ____ implements BinaryMessageCodec<List<Item>> {
@Override
public boolean supports(Type type) {
return type instanceof ParameterizedType && ((ParameterizedType) type).getRawType().equals(List.class);
}
@Override
public Buffer encode(List<Item> value) {
throw new UnsupportedOperationException();
}
@Override
public List<Item> decode(Type type, Buffer value) {
JsonArray json = value.toJsonArray();
List<Item> items = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Item item = new Item();
JsonObject jsonObject = json.getJsonObject(i);
// Intentionally skip the name
item.setCount(2 * jsonObject.getInteger("count"));
items.add(item);
}
return items;
}
}
}
| ListItemBinaryMessageCodec |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnSameConstructorTest.java | {
"start": 1454,
"end": 1615
} | class ____ {
/** Class has a constructor annotated with @javax.inject.Inject and @AssistedInject. */
public | AssistedInjectAndInjectOnSameConstructorPositiveCases |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/basic/MissingArgumentsInvokerTest.java | {
"start": 563,
"end": 2393
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(MyService.class)
.beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> {
MethodInfo hello = bean.getImplClazz().firstMethod("hello");
MethodInfo helloStatic = bean.getImplClazz().firstMethod("helloStatic");
for (MethodInfo method : List.of(hello, helloStatic)) {
invokers.put(method.name(), factory.createInvoker(bean, method).build());
}
}))
.build();
@Test
public void test() {
InvokerHelper helper = Arc.container().instance(InvokerHelper.class).get();
InstanceHandle<MyService> service = Arc.container().instance(MyService.class);
Invoker<MyService, String> hello = helper.getInvoker("hello");
assertThrows(NullPointerException.class, () -> {
hello.invoke(service.get(), null);
});
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
hello.invoke(service.get(), new Object[] {});
});
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
hello.invoke(new MyService(), new Object[] { 1 });
});
Invoker<MyService, String> helloStatic = helper.getInvoker("helloStatic");
assertThrows(NullPointerException.class, () -> {
helloStatic.invoke(null, null);
});
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
helloStatic.invoke(null, new Object[] { "" });
});
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
hello.invoke(null, new Object[] {});
});
}
@Singleton
static | MissingArgumentsInvokerTest |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java | {
"start": 6807,
"end": 7036
} | class ____ the bean
* @param name an explicit name for the bean
* (or {@code null} for generating a default bean name)
* @param qualifiers specific qualifier annotations to consider,
* in addition to qualifiers at the bean | of |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/event/TaskTAttemptFailedEvent.java | {
"start": 936,
"end": 1315
} | class ____ extends TaskTAttemptEvent {
private boolean fastFail;
public TaskTAttemptFailedEvent(TaskAttemptId id) {
this(id, false);
}
public TaskTAttemptFailedEvent(TaskAttemptId id, boolean fastFail) {
super(id, TaskEventType.T_ATTEMPT_FAILED);
this.fastFail = fastFail;
}
public boolean isFastFail() {
return fastFail;
}
}
| TaskTAttemptFailedEvent |
java | quarkusio__quarkus | integration-tests/rest-client-reactive-stork/src/test/java/io/quarkus/it/rest/reactive/stork/WiremockBase.java | {
"start": 290,
"end": 882
} | class ____ implements QuarkusTestResourceLifecycleManager {
private WireMockServer server;
abstract Map<String, String> initWireMock(WireMockServer server);
abstract int httpPort();
abstract int httpsPort();
@Override
public Map<String, String> start() {
server = new WireMockServer(options().port(httpPort()).httpsPort(httpsPort()));
var result = initWireMock(server);
server.start();
return result;
}
@Override
public void stop() {
if (server != null) {
server.stop();
}
}
}
| WiremockBase |
java | quarkusio__quarkus | extensions/info/deployment/src/main/java/io/quarkus/info/deployment/BuildInInfoEndpointEnabled.java | {
"start": 89,
"end": 416
} | class ____ implements BooleanSupplier {
private final InfoBuildTimeConfig config;
BuildInInfoEndpointEnabled(InfoBuildTimeConfig config) {
this.config = config;
}
@Override
public boolean getAsBoolean() {
return config.enabled() && config.build().enabled();
}
}
| BuildInInfoEndpointEnabled |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/predicates/type/ExactAny.java | {
"start": 960,
"end": 1510
} | class ____ implements TypePredicate {
public final Iterable<Supplier<Type>> types;
public ExactAny(Iterable<Supplier<Type>> types) {
this.types = types;
}
@Override
public boolean apply(Type type, VisitorState state) {
if (type == null) {
return false;
}
for (Supplier<Type> supplier : types) {
Type expected = supplier.get(state);
if (expected == null) {
continue;
}
if (ASTHelpers.isSameType(expected, type, state)) {
return true;
}
}
return false;
}
}
| ExactAny |
java | junit-team__junit5 | junit-vintage-engine/src/test/java/org/junit/vintage/engine/VintageTestEngineDiscoveryTests.java | {
"start": 4477,
"end": 36696
} | class ____ {
@Test
void resolvesSimpleJUnit4TestClass() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithSingleTestWhichFails.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var childDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(childDescriptor, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesIgnoredJUnit4TestClass() throws Exception {
Class<?> testClass = IgnoredJUnit4TestCase.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
assertThat(runnerDescriptor.getChildren()).hasSize(2);
List<? extends TestDescriptor> children = new ArrayList<>(runnerDescriptor.getChildren());
assertTestMethodDescriptor(children.get(0), testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
assertTestMethodDescriptor(children.get(1), testClass, "succeedingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesEmptyIgnoredTestClass() {
Class<?> testClass = EmptyIgnoredTestCase.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertFalse(runnerDescriptor.isContainer());
assertTrue(runnerDescriptor.isTest());
assertEquals(testClass.getSimpleName(), runnerDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForClass(testClass), runnerDescriptor.getUniqueId());
assertThat(runnerDescriptor.getChildren()).isEmpty();
}
@Test
void resolvesJUnit4TestClassWithCustomRunner() throws Exception {
Class<?> testClass = SingleFailingTheoryTestCase.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var childDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(childDescriptor, testClass, "theory",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesJUnit3TestCase() throws Exception {
Class<?> testClass = PlainJUnit3TestCaseWithSingleTestWhichFails.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var childDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(childDescriptor, testClass, "test",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesJUnit3SuiteWithSingleTestCaseWithSingleTestWhichFails() throws Exception {
Class<?> suiteClass = JUnit3SuiteWithSingleTestCaseWithSingleTestWhichFails.class;
Class<?> testClass = PlainJUnit3TestCaseWithSingleTestWhichFails.class;
var discoveryRequest = discoveryRequestForClass(suiteClass);
var engineDescriptor = discoverTests(discoveryRequest);
var suiteDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(suiteDescriptor, suiteClass);
assertThat(suiteDescriptor.getDisplayName()).describedAs("display name") //
.startsWith(suiteClass.getSimpleName());
assertThat(suiteDescriptor.getLegacyReportingName()).describedAs("legacy reporting name") //
.isEqualTo(suiteClass.getName());
var testClassDescriptor = getOnlyElement(suiteDescriptor.getChildren());
assertContainerTestDescriptor(testClassDescriptor, suiteClass, testClass);
var testMethodDescriptor = getOnlyElement(testClassDescriptor.getChildren());
assertTestMethodDescriptor(testMethodDescriptor, testClass, "test",
VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass));
}
@Test
void resolvesJUnit4SuiteWithPlainJUnit4TestCaseWithSingleTestWhichIsIgnored() throws Exception {
Class<?> suiteClass = JUnit4SuiteWithPlainJUnit4TestCaseWithSingleTestWhichIsIgnored.class;
Class<?> testClass = PlainJUnit4TestCaseWithSingleTestWhichIsIgnored.class;
var discoveryRequest = discoveryRequestForClass(suiteClass);
var engineDescriptor = discoverTests(discoveryRequest);
var suiteDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(suiteDescriptor, suiteClass);
var testClassDescriptor = getOnlyElement(suiteDescriptor.getChildren());
assertContainerTestDescriptor(testClassDescriptor, suiteClass, testClass);
var testMethodDescriptor = getOnlyElement(testClassDescriptor.getChildren());
assertTestMethodDescriptor(testMethodDescriptor, testClass, "ignoredTest",
VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass));
}
@Test
void resolvesJUnit4TestCaseWithIndistinguishableOverloadedMethod() {
Class<?> testClass = JUnit4TestCaseWithIndistinguishableOverloadedMethod.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
List<TestDescriptor> testMethodDescriptors = new ArrayList<>(runnerDescriptor.getChildren());
assertThat(testMethodDescriptors).hasSize(2);
var testMethodDescriptor = testMethodDescriptors.getFirst();
assertEquals("theory", testMethodDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "theory", "0"),
testMethodDescriptor.getUniqueId());
assertClassSource(testClass, testMethodDescriptor);
testMethodDescriptor = testMethodDescriptors.get(1);
assertEquals("theory", testMethodDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "theory", "1"),
testMethodDescriptor.getUniqueId());
assertClassSource(testClass, testMethodDescriptor);
}
@Test
void resolvesJUnit4TestCaseWithDistinguishableOverloadedMethod() throws Exception {
Class<?> testClass = JUnit4TestCaseWithDistinguishableOverloadedMethod.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
List<TestDescriptor> testMethodDescriptors = new ArrayList<>(runnerDescriptor.getChildren());
var testMethodDescriptor = getOnlyElement(testMethodDescriptors);
assertEquals("test", testMethodDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "test"), testMethodDescriptor.getUniqueId());
assertMethodSource(testClass.getMethod("test"), testMethodDescriptor);
}
@Test
void doesNotResolvePlainOldJavaClassesWithoutAnyTest() {
assertYieldsNoDescriptors(PlainOldJavaClassWithoutAnyTestsTestCase.class);
}
@Test
void doesNotResolveClassRunWithJUnitPlatform() {
assertYieldsNoDescriptors(TestCaseRunWithJUnitPlatformRunner.class);
}
@Test
void resolvesClasspathSelector() throws Exception {
var root = getClasspathRoot(PlainJUnit4TestCaseWithSingleTestWhichFails.class);
var discoveryRequest = request().selectors(selectClasspathRoots(Set.of(root))).build();
var engineDescriptor = discoverTests(discoveryRequest);
// @formatter:off
assertThat(engineDescriptor.getChildren())
.extracting(TestDescriptor::getDisplayName)
.contains(PlainJUnit4TestCaseWithSingleTestWhichFails.class.getSimpleName())
.contains(PlainJUnit3TestCaseWithSingleTestWhichFails.class.getSimpleName())
.doesNotContain(PlainOldJavaClassWithoutAnyTestsTestCase.class.getSimpleName());
// @formatter:on
}
@Test
void resolvesClasspathSelectorForJarFile() throws Exception {
var jarUrl = getClass().getResource("/vintage-testjar.jar");
var jarFile = Path.of(jarUrl.toURI());
var originalClassLoader = Thread.currentThread().getContextClassLoader();
try (var classLoader = new URLClassLoader(new URL[] { jarUrl })) {
Thread.currentThread().setContextClassLoader(classLoader);
var discoveryRequest = request().selectors(selectClasspathRoots(Set.of(jarFile))).build();
var engineDescriptor = discoverTests(discoveryRequest);
// @formatter:off
assertThat(engineDescriptor.getChildren())
.extracting(TestDescriptor::getDisplayName)
.containsExactly("JUnit4Test");
// @formatter:on
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
@Test
void resolvesApplyingClassNameFilters() throws Exception {
var root = getClasspathRoot(PlainJUnit4TestCaseWithSingleTestWhichFails.class);
var discoveryRequest = request().selectors(selectClasspathRoots(Set.of(root))).filters(
includeClassNamePatterns(".*JUnit4.*"), includeClassNamePatterns(".*Plain.*")).build();
var engineDescriptor = discoverTests(discoveryRequest);
// @formatter:off
assertThat(engineDescriptor.getChildren())
.extracting(TestDescriptor::getDisplayName)
.contains(PlainJUnit4TestCaseWithSingleTestWhichFails.class.getSimpleName())
.doesNotContain(JUnit4TestCaseWithIndistinguishableOverloadedMethod.class.getSimpleName())
.doesNotContain(PlainJUnit3TestCaseWithSingleTestWhichFails.class.getSimpleName());
// @formatter:on
}
@Test
void resolvesApplyingPackageNameFilters() throws Exception {
var root = getClasspathRoot(PlainJUnit4TestCaseWithSingleTestWhichFails.class);
var discoveryRequest = request().selectors(selectClasspathRoots(Set.of(root))).filters(
includePackageNames("org"), includePackageNames("org.junit")).build();
var engineDescriptor = discoverTests(discoveryRequest);
// @formatter:off
assertThat(engineDescriptor.getChildren())
.extracting(TestDescriptor::getDisplayName)
.contains(PlainJUnit4TestCaseWithSingleTestWhichFails.class.getSimpleName());
// @formatter:on
}
@Test
void resolvesPackageSelectorForJUnit4SamplesPackage() {
Class<?> testClass = PlainJUnit4TestCaseWithSingleTestWhichFails.class;
var discoveryRequest = request().selectors(selectPackage(testClass.getPackage().getName())).build();
var engineDescriptor = discoverTests(discoveryRequest);
// @formatter:off
assertThat(engineDescriptor.getChildren())
.extracting(TestDescriptor::getDisplayName)
.contains(testClass.getSimpleName())
.doesNotContain(PlainJUnit3TestCaseWithSingleTestWhichFails.class.getSimpleName());
// @formatter:on
}
@Test
void resolvesPackageSelectorForJUnit3SamplesPackage() {
Class<?> testClass = PlainJUnit3TestCaseWithSingleTestWhichFails.class;
var discoveryRequest = request().selectors(selectPackage(testClass.getPackage().getName())).build();
var engineDescriptor = discoverTests(discoveryRequest);
// @formatter:off
assertThat(engineDescriptor.getChildren())
.extracting(TestDescriptor::getDisplayName)
.contains(testClass.getSimpleName())
.doesNotContain(PlainJUnit4TestCaseWithSingleTestWhichFails.class.getSimpleName());
// @formatter:on
}
@Test
void resolvesClassesWithInheritedMethods() throws Exception {
Class<?> superclass = PlainJUnit4TestCaseWithSingleTestWhichFails.class;
Class<?> testClass = PlainJUnit4TestCaseWithSingleInheritedTestWhichFails.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertEquals(testClass.getSimpleName(), runnerDescriptor.getDisplayName());
assertClassSource(testClass, runnerDescriptor);
var testDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertEquals("failingTest", testDescriptor.getDisplayName());
assertMethodSource(testClass, superclass.getMethod("failingTest"), testDescriptor);
}
@Test
void resolvesCategoriesIntoTags() {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = discoveryRequestForClass(testClass);
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertThat(runnerDescriptor.getTags()).containsOnly(TestTag.create(Plain.class.getName()));
var failingTest = findChildByDisplayName(runnerDescriptor, "failingTest");
assertThat(failingTest.getTags()).containsOnly(//
TestTag.create(Plain.class.getName()), //
TestTag.create(Failing.class.getName()));
var ignoredWithoutReason = findChildByDisplayName(runnerDescriptor, "ignoredTest1_withoutReason");
assertThat(ignoredWithoutReason.getTags()).containsOnly(//
TestTag.create(Plain.class.getName()), //
TestTag.create(Skipped.class.getName()));
var ignoredWithReason = findChildByDisplayName(runnerDescriptor, "ignoredTest2_withReason");
assertThat(ignoredWithReason.getTags()).containsOnly(//
TestTag.create(Plain.class.getName()), //
TestTag.create(Skipped.class.getName()), //
TestTag.create(SkippedWithReason.class.getName()));
}
@Test
void resolvesMethodSelectorForSingleMethod() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors(selectMethod(testClass, testClass.getMethod("failingTest"))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var childDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(childDescriptor, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesMethodOfIgnoredJUnit4TestClass() throws Exception {
Class<?> testClass = IgnoredJUnit4TestCase.class;
var discoveryRequest = request().selectors(selectMethod(testClass, testClass.getMethod("failingTest"))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var childDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(childDescriptor, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesMethodSelectorForTwoMethodsOfSameClass() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors(selectMethod(testClass, testClass.getMethod("failingTest")),
selectMethod(testClass, testClass.getMethod("successfulTest"))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
List<TestDescriptor> testMethodDescriptors = new ArrayList<>(runnerDescriptor.getChildren());
assertThat(testMethodDescriptors).hasSize(2);
var failingTest = testMethodDescriptors.get(0);
assertTestMethodDescriptor(failingTest, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
var successfulTest = testMethodDescriptors.get(1);
assertTestMethodDescriptor(successfulTest, testClass, "successfulTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesUniqueIdSelectorForSingleMethod() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors(
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "failingTest"))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var childDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(childDescriptor, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void resolvesUniqueIdSelectorForSingleClass() {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors(
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForClass(testClass))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
assertThat(runnerDescriptor.getChildren()).hasSize(5);
}
@Test
void resolvesUniqueIdSelectorOfSingleClassWithinSuite() throws Exception {
Class<?> suiteClass = JUnit4SuiteWithTwoTestCases.class;
Class<?> testClass = PlainJUnit4TestCaseWithSingleTestWhichFails.class;
var discoveryRequest = request().selectors(
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var suiteDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(suiteDescriptor, suiteClass);
var testClassDescriptor = getOnlyElement(suiteDescriptor.getChildren());
assertContainerTestDescriptor(testClassDescriptor, suiteClass, testClass);
var testMethodDescriptor = getOnlyElement(testClassDescriptor.getChildren());
assertTestMethodDescriptor(testMethodDescriptor, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass));
}
@Test
void resolvesUniqueIdSelectorOfSingleMethodWithinSuite() throws Exception {
Class<?> suiteClass = JUnit4SuiteWithTwoTestCases.class;
Class<?> testClass = PlainJUnit4TestCaseWithTwoTestMethods.class;
var discoveryRequest = request().selectors(selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(
VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass), testClass, "successfulTest"))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var suiteDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(suiteDescriptor, suiteClass);
var testClassDescriptor = getOnlyElement(suiteDescriptor.getChildren());
assertContainerTestDescriptor(testClassDescriptor, suiteClass, testClass);
var testMethodDescriptor = getOnlyElement(testClassDescriptor.getChildren());
assertTestMethodDescriptor(testMethodDescriptor, testClass, "successfulTest",
VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass));
}
@Test
void resolvesMultipleUniqueIdSelectorsForMethodsOfSameClass() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithTwoTestMethods.class;
var discoveryRequest = request().selectors(
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "successfulTest")),
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "failingTest"))).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
List<TestDescriptor> testMethodDescriptors = new ArrayList<>(runnerDescriptor.getChildren());
assertThat(testMethodDescriptors).hasSize(2);
assertTestMethodDescriptor(testMethodDescriptors.get(0), testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
assertTestMethodDescriptor(testMethodDescriptors.get(1), testClass, "successfulTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void doesNotResolveMissingUniqueIdSelectorForSingleClass() {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors(
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForClass(testClass) + "/[test:doesNotExist]")).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var testDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertInitializationError(testDescriptor, Filter.class, testClass);
}
@Test
void ignoresMoreFineGrainedSelectorsWhenClassIsSelectedAsWell() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors( //
selectMethod(testClass, testClass.getMethod("failingTest")), //
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "abortedTest")), selectClass(testClass) //
).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
assertThat(runnerDescriptor.getChildren()).hasSize(5);
}
@Test
void resolvesCombinationOfMethodAndUniqueIdSelector() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors( //
selectMethod(testClass, testClass.getMethod("failingTest")), //
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "abortedTest") //
)).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
List<TestDescriptor> testMethodDescriptors = new ArrayList<>(runnerDescriptor.getChildren());
assertThat(testMethodDescriptors).hasSize(2);
assertTestMethodDescriptor(testMethodDescriptors.get(0), testClass, "abortedTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
assertTestMethodDescriptor(testMethodDescriptors.get(1), testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void ignoresRedundantSelector() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
var discoveryRequest = request().selectors( //
selectMethod(testClass, testClass.getMethod("failingTest")), //
selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "failingTest") //
)).build();
var engineDescriptor = discoverTests(discoveryRequest);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var testMethodDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertTestMethodDescriptor(testMethodDescriptor, testClass, "failingTest",
VintageUniqueIdBuilder.uniqueIdForClass(testClass));
}
@Test
void doesNotResolveMethodOfClassNotAcceptedByClassNameFilter() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
// @formatter:off
var request = request()
.selectors(selectMethod(testClass, testClass.getMethod("failingTest")))
.filters(includeClassNamePatterns("Foo"))
.build();
// @formatter:on
assertYieldsNoDescriptors(request);
}
@Test
void doesNotResolveMethodOfClassNotAcceptedByPackageNameFilter() throws Exception {
Class<?> testClass = PlainJUnit4TestCaseWithFiveTestMethods.class;
// @formatter:off
var request = request()
.selectors(selectMethod(testClass, testClass.getMethod("failingTest")))
.filters(includePackageNames("com.acme"))
.build();
// @formatter:on
assertYieldsNoDescriptors(request);
}
@Test
void resolvesClassForMethodSelectorForClassWithNonFilterableRunner() {
Class<?> testClass = JUnit4TestCaseWithNotFilterableRunner.class;
// @formatter:off
var request = request()
.selectors(selectUniqueId(VintageUniqueIdBuilder.uniqueIdForMethod(testClass, "Test #0")))
.build();
// @formatter:on
var engineDescriptor = discoverTests(request);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertEquals(testClass.getSimpleName(), runnerDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForClass(testClass), runnerDescriptor.getUniqueId());
assertThat(runnerDescriptor.getChildren()).isNotEmpty();
}
@Test
void usesCustomUniqueIdsAndDisplayNamesWhenPresent() {
Class<?> suiteClass = JUnit4SuiteWithJUnit4TestCaseWithRunnerWithCustomUniqueIdsAndDisplayNames.class;
var request = request().selectors(selectClass(suiteClass)).build();
var engineDescriptor = discoverTests(request);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, suiteClass);
var testClassDescriptor = getOnlyElement(runnerDescriptor.getChildren());
assertEquals("(TestClass)", testClassDescriptor.getDisplayName());
var childDescriptor = getOnlyElement(testClassDescriptor.getChildren());
var prefix = VintageUniqueIdBuilder.uniqueIdForClass(suiteClass);
assertThat(childDescriptor.getUniqueId().toString()).startsWith(prefix.toString());
assertEquals("(TestMethod)", childDescriptor.getDisplayName());
var customUniqueIdValue = childDescriptor.getUniqueId().getSegments().get(2).getType();
assertNotNull(Base64.getDecoder().decode(customUniqueIdValue.getBytes(StandardCharsets.UTF_8)),
"is a valid Base64 encoding scheme");
}
@Test
void resolvesTestSourceForParameterizedTests() throws Exception {
Class<?> testClass = ParameterizedTestCase.class;
var request = request().selectors(selectClass(testClass)).build();
var engineDescriptor = discoverTests(request);
var runnerDescriptor = getOnlyElement(engineDescriptor.getChildren());
assertRunnerTestDescriptor(runnerDescriptor, testClass);
var fooParentDescriptor = findChildByDisplayName(runnerDescriptor, "[foo]");
assertTrue(fooParentDescriptor.isContainer());
assertFalse(fooParentDescriptor.isTest());
assertThat(fooParentDescriptor.getSource()).isEmpty();
var testMethodDescriptor = getOnlyElement(fooParentDescriptor.getChildren());
assertEquals("test[foo]", testMethodDescriptor.getDisplayName());
assertTrue(testMethodDescriptor.isTest());
assertFalse(testMethodDescriptor.isContainer());
assertMethodSource(testClass.getMethod("test"), testMethodDescriptor);
}
@Test
void reportsNoDiscoveryIssuesWhenNoTestsAreFound() {
var request = discoveryRequestForClass(PlainOldJavaClassWithoutAnyTestsTestCase.class);
var results = discover(request);
assertThat(results.getDiscoveryIssues()).isEmpty();
}
@Test
void reportDiscoveryIssueWhenTestsAreFoundByDefault() {
var request = discoveryRequestForClass(PlainJUnit4TestCaseWithSingleTestWhichFails.class);
var results = discover(request);
assertThat(results.getDiscoveryIssues()).hasSize(1);
var issue = results.getDiscoveryIssues().getFirst();
assertThat(issue.severity()).isEqualTo(Severity.INFO);
assertThat(issue.message()).contains("JUnit Vintage engine is deprecated");
}
@SuppressWarnings("deprecation")
@Test
void reportNoDiscoveryIssueWhenTestsAreFoundButConfigurationParameterIsSet() {
var request = request() //
.selectors(selectClass(PlainJUnit4TestCaseWithSingleTestWhichFails.class)) //
.configurationParameter(Constants.DISCOVERY_ISSUE_REPORTING_ENABLED_PROPERTY_NAME, "false").build();
var results = discover(request);
assertThat(results.getDiscoveryIssues()).isEmpty();
}
private TestDescriptor findChildByDisplayName(TestDescriptor runnerDescriptor, String displayName) {
// @formatter:off
var children = runnerDescriptor.getChildren();
return children
.stream()
.filter(where(TestDescriptor::getDisplayName, isEqual(displayName)))
.findAny()
.orElseThrow(() ->
new AssertionError(format("No child with display name \"{0}\" in {1}", displayName, children)));
// @formatter:on
}
private TestDescriptor discoverTests(LauncherDiscoveryRequest discoveryRequest) {
return discover(discoveryRequest).getEngineDescriptor();
}
@SuppressWarnings("deprecation")
private static EngineDiscoveryResults discover(LauncherDiscoveryRequest discoveryRequest) {
return EngineTestKit.discover(new VintageTestEngine(), discoveryRequest);
}
private Path getClasspathRoot(Class<?> testClass) throws Exception {
var location = testClass.getProtectionDomain().getCodeSource().getLocation();
return Path.of(location.toURI());
}
private void assertYieldsNoDescriptors(Class<?> testClass) {
var request = discoveryRequestForClass(testClass);
assertYieldsNoDescriptors(request);
}
private void assertYieldsNoDescriptors(LauncherDiscoveryRequest request) {
var engineDescriptor = discoverTests(request);
assertThat(engineDescriptor.getChildren()).isEmpty();
}
private static void assertRunnerTestDescriptor(TestDescriptor runnerDescriptor, Class<?> testClass) {
assertTrue(runnerDescriptor.isContainer());
assertFalse(runnerDescriptor.isTest());
assertEquals(testClass.getSimpleName(), runnerDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForClass(testClass), runnerDescriptor.getUniqueId());
assertClassSource(testClass, runnerDescriptor);
}
private static void assertTestMethodDescriptor(TestDescriptor testMethodDescriptor, Class<?> testClass,
String methodName, UniqueId uniqueContainerId) throws Exception {
assertTrue(testMethodDescriptor.isTest());
assertFalse(testMethodDescriptor.isContainer());
assertEquals(methodName, testMethodDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForMethod(uniqueContainerId, testClass, methodName),
testMethodDescriptor.getUniqueId());
assertThat(testMethodDescriptor.getChildren()).isEmpty();
assertMethodSource(testClass.getMethod(methodName), testMethodDescriptor);
}
private static void assertContainerTestDescriptor(TestDescriptor containerDescriptor, Class<?> suiteClass,
Class<?> testClass) {
assertTrue(containerDescriptor.isContainer());
assertFalse(containerDescriptor.isTest());
assertEquals(testClass.getName(), containerDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForClasses(suiteClass, testClass),
containerDescriptor.getUniqueId());
assertClassSource(testClass, containerDescriptor);
}
private static void assertInitializationError(TestDescriptor testDescriptor, Class<?> failingClass,
Class<?> testClass) {
assertTrue(testDescriptor.isTest());
assertFalse(testDescriptor.isContainer());
assertEquals("initializationError", testDescriptor.getDisplayName());
assertEquals(VintageUniqueIdBuilder.uniqueIdForErrorInClass(testClass, failingClass),
testDescriptor.getUniqueId());
assertThat(testDescriptor.getChildren()).isEmpty();
assertClassSource(failingClass, testDescriptor);
}
private static void assertClassSource(Class<?> expectedClass, TestDescriptor testDescriptor) {
assertThat(testDescriptor.getSource()).containsInstanceOf(ClassSource.class);
var classSource = (ClassSource) testDescriptor.getSource().get();
assertThat(classSource.getJavaClass()).isEqualTo(expectedClass);
}
private static void assertMethodSource(Method expectedMethod, TestDescriptor testDescriptor) {
assertMethodSource(expectedMethod.getDeclaringClass(), expectedMethod, testDescriptor);
}
private static void assertMethodSource(Class<?> expectedClass, Method expectedMethod,
TestDescriptor testDescriptor) {
assertThat(testDescriptor.getSource()).containsInstanceOf(MethodSource.class);
var methodSource = (MethodSource) testDescriptor.getSource().get();
assertThat(methodSource.getClassName()).isEqualTo(expectedClass.getName());
assertThat(methodSource.getMethodName()).isEqualTo(expectedMethod.getName());
assertThat(methodSource.getMethodParameterTypes()).isEqualTo(
ClassUtils.nullSafeToString(expectedMethod.getParameterTypes()));
}
private static LauncherDiscoveryRequest discoveryRequestForClass(Class<?> testClass) {
return request().selectors(selectClass(testClass)).build();
}
}
| VintageTestEngineDiscoveryTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java | {
"start": 6756,
"end": 7171
} | class ____ implements PostCommitDeleteEventListener {
int success;
int failed;
@Override
public void onPostDelete(PostDeleteEvent event) {
success++;
}
@Override
public void onPostDeleteCommitFailed(PostDeleteEvent event) {
failed++;
}
@Override
public boolean requiresPostCommitHandling(EntityPersister persister) {
return true;
}
}
private static | TestPostCommitDeleteEventListener |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsProducerConcurrentWithReplyTest.java | {
"start": 1858,
"end": 4247
} | class ____ extends AbstractJMSTest {
@Order(2)
@RegisterExtension
public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension();
protected CamelContext context;
protected ProducerTemplate template;
protected ConsumerTemplate consumer;
private ExecutorService executor;
@AfterEach
void cleanupExecutor() {
executor.shutdownNow();
}
@RepeatedTest(50)
public void testNoConcurrentProducers() throws Exception {
doSendMessages(1, 1);
}
@RepeatedTest(50)
public void testConcurrentProducers() throws Exception {
doSendMessages(200, 5);
}
private void doSendMessages(int files, int poolSize) throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(files);
getMockEndpoint("mock:result").expectsNoDuplicates(body());
executor = Executors.newFixedThreadPool(poolSize);
final List<String> data = new ArrayList<>(files);
for (int i = 0; i < files; i++) {
final int index = i;
executor.submit(() -> {
String out = template.requestBody("direct:start", "Message " + index, String.class);
data.add(index, out);
});
}
MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
for (int i = 0; i < data.size(); i++) {
assertEquals("Bye Message " + i, data.get(i));
}
}
@Override
protected String getComponentName() {
return "jms";
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("jms:queue:JmsProducerConcurrentWithReplyTest");
from("jms:queue:JmsProducerConcurrentWithReplyTest?concurrentConsumers=5").transform(simple("Bye ${in.body}"))
.to("mock:result");
}
};
}
@Override
public CamelContextExtension getCamelContextExtension() {
return camelContextExtension;
}
@BeforeEach
void setUpRequirements() {
context = camelContextExtension.getContext();
template = camelContextExtension.getProducerTemplate();
consumer = camelContextExtension.getConsumerTemplate();
}
}
| JmsProducerConcurrentWithReplyTest |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/NullAwareJoinHelper.java | {
"start": 1125,
"end": 1798
} | class ____ {
public static int[] getNullFilterKeys(boolean[] filterNulls) {
checkNotNull(filterNulls);
List<Integer> nullFilterKeyList = new ArrayList<>();
for (int i = 0; i < filterNulls.length; i++) {
if (filterNulls[i]) {
nullFilterKeyList.add(i);
}
}
return ArrayUtils.toPrimitive(nullFilterKeyList.toArray(new Integer[0]));
}
public static boolean shouldFilter(
boolean nullSafe, boolean filterAllNulls, int[] nullFilterKeys, BinaryRowData key) {
return !nullSafe && (filterAllNulls ? key.anyNull() : key.anyNull(nullFilterKeys));
}
}
| NullAwareJoinHelper |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/fulltext/MatchOperator.java | {
"start": 941,
"end": 1334
} | class ____ a {@link org.elasticsearch.xpack.esql.querydsl.query.MatchQuery} using an operator.
* This is used as a convenience for generating documentation and for error message purposes - it’s a way to represent
* the match operator in the function syntax.
* Serialization is provided as a way to pass the corresponding tests - serialization must be done to a Match class.
*/
public | performs |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/promql/selector/InstantSelector.java | {
"start": 1360,
"end": 2752
} | class ____ extends Selector {
public InstantSelector(Source source, Expression series, List<Expression> labels, LabelMatchers labelMatchers, Evaluation evaluation) {
this(source, PlaceholderRelation.INSTANCE, series, labels, labelMatchers, evaluation);
}
public InstantSelector(
Source source,
LogicalPlan child,
Expression series,
List<Expression> labels,
LabelMatchers labelMatchers,
Evaluation evaluation
) {
super(source, child, series, labels, labelMatchers, evaluation);
}
@Override
protected NodeInfo<InstantSelector> info() {
return NodeInfo.create(this, InstantSelector::new, child(), series(), labels(), labelMatchers(), evaluation());
}
@Override
public InstantSelector replaceChild(LogicalPlan newChild) {
return new InstantSelector(source(), newChild, series(), labels(), labelMatchers(), evaluation());
}
// @Override
// public String telemetryLabel() {
// return "PROMQL_SELECTOR_INSTANT";
// }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| InstantSelector |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/network/SslTransportLayerTest.java | {
"start": 4206,
"end": 6329
} | class ____ {
private final String tlsProtocol;
private final boolean useInlinePem;
private CertStores serverCertStores;
private CertStores clientCertStores;
private Map<String, Object> sslClientConfigs;
private Map<String, Object> sslServerConfigs;
private final Map<String, Object> sslConfigOverrides;
public Args(String tlsProtocol, boolean useInlinePem) throws Exception {
this.tlsProtocol = tlsProtocol;
this.useInlinePem = useInlinePem;
sslConfigOverrides = new HashMap<>();
sslConfigOverrides.put(SslConfigs.SSL_PROTOCOL_CONFIG, tlsProtocol);
sslConfigOverrides.put(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, List.of(tlsProtocol));
sslConfigOverrides.put(SslConfigs.SSL_CIPHER_SUITES_CONFIG, List.of());
init();
}
Map<String, Object> getTrustingConfig(CertStores certStores, CertStores peerCertStores) {
Map<String, Object> configs = certStores.getTrustingConfig(peerCertStores);
configs.putAll(sslConfigOverrides);
return configs;
}
private void init() throws Exception {
// Create certificates for use by client and server. Add server cert to client truststore and vice versa.
serverCertStores = certBuilder(true, "server", useInlinePem).addHostName("localhost").build();
clientCertStores = certBuilder(false, "client", useInlinePem).addHostName("localhost").build();
sslServerConfigs = getTrustingConfig(serverCertStores, clientCertStores);
sslClientConfigs = getTrustingConfig(clientCertStores, serverCertStores);
sslServerConfigs.put(SslConfigs.SSL_ENGINE_FACTORY_CLASS_CONFIG, DefaultSslEngineFactory.class);
sslClientConfigs.put(SslConfigs.SSL_ENGINE_FACTORY_CLASS_CONFIG, DefaultSslEngineFactory.class);
}
@Override
public String toString() {
return "tlsProtocol=" + tlsProtocol +
", useInlinePem=" + useInlinePem;
}
}
private static | Args |
java | apache__flink | flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/ProcessConfigurableAndGlobalStreamImpl.java | {
"start": 1786,
"end": 3522
} | class ____<T>
extends ProcessConfigureHandle<T, ProcessConfigurableAndGlobalStream<T>>
implements ProcessConfigurableAndGlobalStream<T> {
private final GlobalStreamImpl<T> stream;
public ProcessConfigurableAndGlobalStreamImpl(GlobalStreamImpl<T> stream) {
super(stream.getEnvironment(), stream.getTransformation());
this.stream = stream;
}
@Override
public <OUT> ProcessConfigurableAndGlobalStream<OUT> process(
OneInputStreamProcessFunction<T, OUT> processFunction) {
return stream.process(processFunction);
}
@Override
public <OUT1, OUT2> TwoGlobalStreams<OUT1, OUT2> process(
TwoOutputStreamProcessFunction<T, OUT1, OUT2> processFunction) {
return stream.process(processFunction);
}
@Override
public <T_OTHER, OUT> ProcessConfigurableAndGlobalStream<OUT> connectAndProcess(
GlobalStream<T_OTHER> other,
TwoInputNonBroadcastStreamProcessFunction<T, T_OTHER, OUT> processFunction) {
return stream.connectAndProcess(other, processFunction);
}
@Override
public <K> KeyedPartitionStream<K, T> keyBy(KeySelector<T, K> keySelector) {
return stream.keyBy(keySelector);
}
@Override
public NonKeyedPartitionStream<T> shuffle() {
return stream.shuffle();
}
@Override
public BroadcastStream<T> broadcast() {
return stream.broadcast();
}
@Override
public ProcessConfigurable<?> toSink(Sink<T> sink) {
return stream.toSink(sink);
}
@Override
protected boolean canBeParallel() {
// global stream can not be parallel by define.
return false;
}
}
| ProcessConfigurableAndGlobalStreamImpl |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/functions/sink/filesystem/BulkWriterTest.java | {
"start": 8983,
"end": 9801
} | class ____ implements BulkWriter<Tuple2<String, Integer>> {
private static final Charset CHARSET = StandardCharsets.UTF_8;
private final FSDataOutputStream stream;
TestBulkWriter(final FSDataOutputStream stream) {
this.stream = Preconditions.checkNotNull(stream);
}
@Override
public void addElement(Tuple2<String, Integer> element) throws IOException {
stream.write((element.f0 + '@' + element.f1 + '\n').getBytes(CHARSET));
}
@Override
public void flush() throws IOException {
stream.flush();
}
@Override
public void finish() throws IOException {
flush();
}
}
/** A {@link BulkWriter.Factory} used for the tests. */
public static final | TestBulkWriter |
java | apache__camel | components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerAsyncEndpointTest.java | {
"start": 1179,
"end": 3232
} | class ____ extends BaseNettyTest {
private static String beforeThreadName;
private static String afterThreadName;
@Test
public void testAsyncEndpoint() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel");
getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel");
String reply = template.requestBody("direct:start", "Hello Camel", String.class);
assertEquals("Bye Camel", reply);
MockEndpoint.assertIsSatisfied(context);
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("mock:before")
.to("log:before")
.process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName = Thread.currentThread().getName();
}
})
.to("netty:tcp://localhost:{{port}}?textline=true&sync=true")
.process(new Processor() {
public void process(Exchange exchange) {
afterThreadName = Thread.currentThread().getName();
}
})
.to("log:after")
.to("mock:after")
.to("mock:result");
from("netty:tcp://localhost:{{port}}?textline=true&sync=true")
.delay(1000)
.validate(body().isInstanceOf(String.class))
.transform(body().regexReplaceAll("Hello", "Bye"));
}
};
}
}
| NettyProducerAsyncEndpointTest |
java | apache__dubbo | dubbo-common/src/test/java/com/service/Params.java | {
"start": 883,
"end": 1177
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
private Map<String, String> params;
public Params(Map<String, String> params) {
this.params = params;
}
public String get(String key) {
return params.get(key);
}
}
| Params |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/XorPowerTest.java | {
"start": 1124,
"end": 1424
} | class ____ {
static final int X = 2 ^ 16;
static final int TOO_BIG = 2 ^ 32;
static final int Z = 2 ^ 31;
static final int P = 10 ^ 6;
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/async/JCToolsBlockingQueueFactory.java | {
"start": 2321,
"end": 5506
} | class ____<E> extends MpscArrayQueue<E> implements BlockingQueue<E> {
private final JCToolsBlockingQueueFactory.WaitStrategy waitStrategy;
MpscBlockingQueue(final int capacity, final JCToolsBlockingQueueFactory.WaitStrategy waitStrategy) {
super(capacity);
this.waitStrategy = waitStrategy;
}
@Override
public int drainTo(final Collection<? super E> c) {
return drainTo(c, capacity());
}
@Override
public int drainTo(final Collection<? super E> c, final int maxElements) {
return drain(e -> c.add(e), maxElements);
}
@Override
public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
int idleCounter = 0;
final long timeoutNanos = System.nanoTime() + unit.toNanos(timeout);
do {
if (offer(e)) {
return true;
} else if (System.nanoTime() - timeoutNanos > 0) {
return false;
}
idleCounter = waitStrategy.idle(idleCounter);
} while (!Thread.interrupted()); // clear interrupted flag
throw new InterruptedException();
}
@Override
public E poll(final long timeout, final TimeUnit unit) throws InterruptedException {
int idleCounter = 0;
final long timeoutNanos = System.nanoTime() + unit.toNanos(timeout);
do {
final E result = poll();
if (result != null) {
return result;
} else if (System.nanoTime() - timeoutNanos > 0) {
return null;
}
idleCounter = waitStrategy.idle(idleCounter);
} while (!Thread.interrupted()); // clear interrupted flag
throw new InterruptedException();
}
@Override
public void put(final E e) throws InterruptedException {
int idleCounter = 0;
do {
if (offer(e)) {
return;
}
idleCounter = waitStrategy.idle(idleCounter);
} while (!Thread.interrupted()); // clear interrupted flag
throw new InterruptedException();
}
@Override
public boolean offer(final E e) {
// keep 2 cache lines empty to avoid false sharing that will slow the consumer thread when queue is full.
return offerIfBelowThreshold(e, capacity() - 32);
}
@Override
public int remainingCapacity() {
return capacity() - size();
}
@Override
public E take() throws InterruptedException {
int idleCounter = 100;
do {
final E result = relaxedPoll();
if (result != null) {
return result;
}
idleCounter = waitStrategy.idle(idleCounter);
} while (!Thread.interrupted()); // clear interrupted flag
throw new InterruptedException();
}
}
public | MpscBlockingQueue |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/ParameterTest.java | {
"start": 1527,
"end": 7179
} | class ____ {
@Test
@SkipForDialect(dialectClass = InformixDialect.class,
reason = "Blobs are not allowed in this expression")
public void testPrimitiveArrayParameterBinding(SessionFactoryScope scope) {
scope.inTransaction( em -> {
CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = em.getCriteriaBuilder()
.createQuery( MultiTypedBasicAttributesEntity.class );
Root<MultiTypedBasicAttributesEntity> rootEntity = criteria.from( MultiTypedBasicAttributesEntity.class );
Path<int[]> someIntsPath = rootEntity.get( MultiTypedBasicAttributesEntity_.someInts );
ParameterExpression<int[]> param = em.getCriteriaBuilder().parameter( int[].class, "theInts" );
criteria.where( em.getCriteriaBuilder().equal( someIntsPath, param ) );
TypedQuery<MultiTypedBasicAttributesEntity> query = em.createQuery( criteria );
query.setParameter( param, new int[] { 1,1,1 } );
assertThat( query.getParameterValue( param.getName() ), instanceOf( int[].class) );
query.getResultList();
} );
}
@Test
@SkipForDialect(dialectClass = InformixDialect.class,
reason = "Blobs are not allowed in this expression")
public void testNonPrimitiveArrayParameterBinding(SessionFactoryScope scope) {
scope.inTransaction( em -> {
CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = em.getCriteriaBuilder()
.createQuery( MultiTypedBasicAttributesEntity.class );
Root<MultiTypedBasicAttributesEntity> rootEntity = criteria.from( MultiTypedBasicAttributesEntity.class );
Path<Integer[]> thePath = rootEntity.get( MultiTypedBasicAttributesEntity_.someWrappedIntegers );
ParameterExpression<Integer[]> param = em.getCriteriaBuilder().parameter( Integer[].class, "theIntegers" );
criteria.where( em.getCriteriaBuilder().equal( thePath, param ) );
TypedQuery<MultiTypedBasicAttributesEntity> query = em.createQuery( criteria );
query.setParameter( param, new Integer[] { 1, 1, 1 } );
assertThat( query.getParameterValue( param.getName() ), instanceOf( Integer[].class ) );
query.getResultList();
} );
}
@Test
public void testNamedParameterMetadata(SessionFactoryScope scope) {
scope.inTransaction( em -> {
CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = em.getCriteriaBuilder()
.createQuery( MultiTypedBasicAttributesEntity.class );
Root<MultiTypedBasicAttributesEntity> rootEntity = criteria.from( MultiTypedBasicAttributesEntity.class );
criteria.where(
em.getCriteriaBuilder().equal(
rootEntity.get( MultiTypedBasicAttributesEntity_.id ),
em.getCriteriaBuilder().parameter( Long.class, "id" )
)
);
TypedQuery<MultiTypedBasicAttributesEntity> query = em.createQuery( criteria );
Parameter<?> parameter = query.getParameter( "id" );
assertEquals( "id", parameter.getName() );
} );
}
@Test
public void testParameterInParameterList(SessionFactoryScope scope) {
// Yes, this test makes no semantic sense. But the JPA TCK does it...
// it causes a problem on Derby, which does not like the form "... where ? in (?,?)"
// Derby wants one side or the other to be CAST (I assume so it can check typing).
scope.inTransaction( em -> {
CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = em.getCriteriaBuilder()
.createQuery( MultiTypedBasicAttributesEntity.class );
criteria.from( MultiTypedBasicAttributesEntity.class );
criteria.where(
em.getCriteriaBuilder().in( em.getCriteriaBuilder().parameter( Long.class, "p1" ) )
.value( em.getCriteriaBuilder().parameter( Long.class, "p2" ) )
.value( em.getCriteriaBuilder().parameter( Long.class, "p3" ) )
);
TypedQuery<MultiTypedBasicAttributesEntity> query = em.createQuery( criteria );
query.setParameter( "p1", 1L );
query.setParameter( "p2", 2L );
query.setParameter( "p3", 3L );
query.getResultList();
} );
}
@Test
@JiraKey("HHH-10870")
public void testParameterInParameterList2(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
final CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = criteriaBuilder
.createQuery( MultiTypedBasicAttributesEntity.class );
final ParameterExpression<Iterable> parameter = criteriaBuilder.parameter( Iterable.class );
final Root<MultiTypedBasicAttributesEntity> root = criteria.from( MultiTypedBasicAttributesEntity.class );
criteria.select( root ).where( root.get( "id" ).in( parameter ) );
final TypedQuery<MultiTypedBasicAttributesEntity> query1 = em.createQuery( criteria );
query1.setParameter( parameter, Arrays.asList( 1L, 2L, 3L ) );
query1.getResultList();
} );
}
@Test
@JiraKey("HHH-17912")
@SkipForDialect(dialectClass = InformixDialect.class,
reason = "Blobs are not allowed in this expression")
public void testAttributeEqualListParameter(SessionFactoryScope scope) {
scope.inTransaction( em -> {
final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
final CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = criteriaBuilder
.createQuery( MultiTypedBasicAttributesEntity.class );
final ParameterExpression<List> parameter = criteriaBuilder.parameter( List.class );
final Root<MultiTypedBasicAttributesEntity> root = criteria.from( MultiTypedBasicAttributesEntity.class );
criteria.select( root ).where( criteriaBuilder.equal( root.get( MultiTypedBasicAttributesEntity_.integerList ), parameter ) );
final TypedQuery<MultiTypedBasicAttributesEntity> query1 = em.createQuery( criteria );
query1.setParameter( parameter, List.of( 1, 2, 3 ) );
query1.getResultList();
} );
}
}
| ParameterTest |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/common/ResponseCode.java | {
"start": 704,
"end": 1122
} | class ____ inherited classes define codes separated from HTTP code to provide richer and preciser information of
* the API results. A recommended rule for defining response code is:
* <li> Global and common code starts with 10001.
* <li> Naming module code starts with 20001.
* <li> Config module code starts with 30001.
* <li> Core module code starts with 40001.
*
* @author nkorange
* @since 1.2.0
*/
public | and |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/basic/EntityClass.java | {
"start": 152,
"end": 592
} | class ____ {
private Long key;
private String field1;
private String field2;
public Long getKey() {
return this.key;
}
public void setKey(Long key) {
this.key = key;
}
public String getField2() {
return this.field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
public String getField1() {
return this.field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
}
| EntityClass |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/records/RouterRMDTSecretManagerState.java | {
"start": 1118,
"end": 1769
} | class ____ {
// DTIdentifier -> renewDate
private Map<RMDelegationTokenIdentifier, RouterStoreToken> delegationTokenState = new HashMap<>();
private Set<DelegationKey> masterKeyState = new HashSet<>();
private int dtSequenceNumber = 0;
public Map<RMDelegationTokenIdentifier, RouterStoreToken> getTokenState() {
return delegationTokenState;
}
public Set<DelegationKey> getMasterKeyState() {
return masterKeyState;
}
public int getDTSequenceNumber() {
return dtSequenceNumber;
}
public void setDtSequenceNumber(int dtSequenceNumber) {
this.dtSequenceNumber = dtSequenceNumber;
}
}
| RouterRMDTSecretManagerState |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/aot/AbstractAotProcessor.java | {
"start": 5186,
"end": 7700
} | class ____ {
private @Nullable Path sourceOutput;
private @Nullable Path resourceOutput;
private @Nullable Path classOutput;
private @Nullable String groupId;
private @Nullable String artifactId;
private Builder() {
// internal constructor
}
/**
* Set the output directory for generated sources.
* @param sourceOutput the location of generated sources
* @return this builder for method chaining
*/
public Builder sourceOutput(Path sourceOutput) {
this.sourceOutput = sourceOutput;
return this;
}
/**
* Set the output directory for generated resources.
* @param resourceOutput the location of generated resources
* @return this builder for method chaining
*/
public Builder resourceOutput(Path resourceOutput) {
this.resourceOutput = resourceOutput;
return this;
}
/**
* Set the output directory for generated classes.
* @param classOutput the location of generated classes
* @return this builder for method chaining
*/
public Builder classOutput(Path classOutput) {
this.classOutput = classOutput;
return this;
}
/**
* Set the group ID of the application.
* @param groupId the group ID of the application, used to locate
* {@code native-image.properties}
* @return this builder for method chaining
*/
public Builder groupId(String groupId) {
Assert.hasText(groupId, "'groupId' must not be empty");
this.groupId = groupId;
return this;
}
/**
* Set the artifact ID of the application.
* @param artifactId the artifact ID of the application, used to locate
* {@code native-image.properties}
* @return this builder for method chaining
*/
public Builder artifactId(String artifactId) {
Assert.hasText(artifactId, "'artifactId' must not be empty");
this.artifactId = artifactId;
return this;
}
/**
* Build the {@link Settings} configured in this {@code Builder}.
*/
public Settings build() {
Assert.notNull(this.sourceOutput, "'sourceOutput' must not be null");
Assert.notNull(this.resourceOutput, "'resourceOutput' must not be null");
Assert.notNull(this.classOutput, "'classOutput' must not be null");
Assert.notNull(this.groupId, "'groupId' must not be null");
Assert.notNull(this.artifactId, "'artifactId' must not be null");
return new Settings(this.sourceOutput, this.resourceOutput, this.classOutput,
this.groupId, this.artifactId);
}
}
}
}
| Builder |
java | micronaut-projects__micronaut-core | core/src/main/java/io/micronaut/core/annotation/AnnotationValue.java | {
"start": 12883,
"end": 13110
} | enum ____
*/
@Override
public <E extends Enum> Optional<E> enumValue(@NonNull String member, @NonNull Class<E> enumType) {
return enumValue(member, enumType, valueMapper);
}
/**
* Return the | value |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/LongArrayAssertBaseTest.java | {
"start": 903,
"end": 1405
} | class ____ extends BaseTestTemplate<LongArrayAssert, long[]> {
protected LongArrays arrays;
@Override
protected LongArrayAssert create_assertions() {
return new LongArrayAssert(emptyArray());
}
@Override
protected void inject_internal_objects() {
super.inject_internal_objects();
arrays = mock(LongArrays.class);
assertions.arrays = arrays;
}
protected LongArrays getArrays(LongArrayAssert someAssertions) {
return someAssertions.arrays;
}
}
| LongArrayAssertBaseTest |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AutoValueConstructorOrderChecker.java | {
"start": 1816,
"end": 3522
} | class ____ extends BugChecker
implements NewClassTreeMatcher {
private final ArgumentChangeFinder argumentChangeFinder =
ArgumentChangeFinder.builder()
.setDistanceFunction(buildDistanceFunction())
.addHeuristic(AutoValueConstructorOrderChecker::allArgumentsMustMatch)
.addHeuristic(new CreatesDuplicateCallHeuristic())
.build();
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!Matchers.isAutoValueConstructor(tree)) {
return Description.NO_MATCH;
}
InvocationInfo invocationInfo =
InvocationInfo.createFromNewClass(tree, ASTHelpers.getSymbol(tree), state);
Changes changes = argumentChangeFinder.findChanges(invocationInfo);
if (changes.isEmpty()) {
return Description.NO_MATCH;
}
return describeMatch(invocationInfo.tree(), changes.buildPermuteArgumentsFix(invocationInfo));
}
private static Function<ParameterPair, Double> buildDistanceFunction() {
return new Function<ParameterPair, Double>() {
@Override
public Double apply(ParameterPair parameterPair) {
Parameter formal = parameterPair.formal();
Parameter actual = parameterPair.actual();
if (formal.isUnknownName() || actual.isUnknownName()) {
return formal.index() == actual.index() ? 0.0 : 1.0;
} else {
return formal.name().equals(actual.name()) ? 0.0 : 1.0;
}
}
};
}
private static boolean allArgumentsMustMatch(
Changes changes, Tree node, Symbol.MethodSymbol sym, VisitorState state) {
return changes.assignmentCost().stream().allMatch(c -> c < 1.0);
}
}
| AutoValueConstructorOrderChecker |
java | apache__camel | components/camel-jacksonxml/src/test/java/org/apache/camel/component/jacksonxml/SpringJacksonEnableFeatureTest.java | {
"start": 1172,
"end": 1935
} | class ____ extends CamelSpringTestSupport {
@Test
public void testMarshal() {
TestPojoView in = new TestPojoView();
Object marshalled = template.requestBody("direct:in", in);
String marshalledAsString = context.getTypeConverter().convertTo(String.class, marshalled);
// we enable the wrap root type feature so we should have TestPojoView
assertEquals("<TestPojoView><age>30</age><height>190</height><weight>70</weight></TestPojoView>", marshalledAsString);
}
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/jacksonxml/SpringJacksonEnableFeatureTest.xml");
}
}
| SpringJacksonEnableFeatureTest |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/CannotMockFinalClass.java | {
"start": 2352,
"end": 3978
} | class ____ extends BugChecker
implements MethodInvocationTreeMatcher, VariableTreeMatcher {
// TODO(lowasser): consider stopping mocks of primitive types here or in its own checker
// Runners like GwtMockito allow mocking final types, so we conservatively stick to JUnit4.
private static final Matcher<AnnotationTree> runWithJunit4 =
allOf(
isType("org.junit.runner.RunWith"),
hasArgumentWithValue("value", classLiteral(isSameType("org.junit.runners.JUnit4"))));
private static final Matcher<Tree> enclosingClassIsJunit4Test =
enclosingClass(Matchers.<ClassTree>annotations(AT_LEAST_ONE, runWithJunit4));
private static final Matcher<VariableTree> variableOfFinalClassAnnotatedMock =
allOf(
variableType(hasModifier(Modifier.FINAL)),
hasAnnotation("org.mockito.Mock"),
enclosingClassIsJunit4Test);
private static final Matcher<MethodInvocationTree> creationOfMockForFinalClass =
allOf(
staticMethod().onClass("org.mockito.Mockito").named("mock"),
argument(0, classLiteral(hasModifier(Modifier.FINAL))),
enclosingClassIsJunit4Test);
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return variableOfFinalClassAnnotatedMock.matches(tree, state)
? describeMatch(tree)
: Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return creationOfMockForFinalClass.matches(tree, state)
? describeMatch(tree)
: Description.NO_MATCH;
}
}
| CannotMockFinalClass |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/suggest/Suggest.java | {
"start": 19229,
"end": 24029
} | class ____ implements Writeable, ToXContentFragment {
public static final ParseField TEXT = new ParseField("text");
public static final ParseField HIGHLIGHTED = new ParseField("highlighted");
public static final ParseField SCORE = new ParseField("score");
public static final ParseField COLLATE_MATCH = new ParseField("collate_match");
private final Text text;
private final Text highlighted;
private float score;
private Boolean collateMatch;
public Option(Text text, Text highlighted, float score, Boolean collateMatch) {
this.text = text;
this.highlighted = highlighted;
this.score = score;
this.collateMatch = collateMatch;
}
public Option(Text text, Text highlighted, float score) {
this(text, highlighted, score, null);
}
public Option(Text text, float score) {
this(text, null, score);
}
public Option(StreamInput in) throws IOException {
text = in.readText();
score = in.readFloat();
highlighted = in.readOptionalText();
collateMatch = in.readOptionalBoolean();
}
/**
* @return The actual suggested text.
*/
public Text getText() {
return text;
}
/**
* @return Copy of suggested text with changes from user supplied text highlighted.
*/
public Text getHighlighted() {
return highlighted;
}
/**
* @return The score based on the edit distance difference between the suggested term and the
* term in the suggest text.
*/
public float getScore() {
return score;
}
/**
* @return true if collation has found a match for the entry.
* if collate was not set, the value defaults to <code>true</code>
*/
public boolean collateMatch() {
return (collateMatch != null) ? collateMatch : true;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeText(text);
out.writeFloat(score);
out.writeOptionalText(highlighted);
out.writeOptionalBoolean(collateMatch);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(TEXT.getPreferredName(), text);
if (highlighted != null) {
builder.field(HIGHLIGHTED.getPreferredName(), highlighted);
}
builder.field(SCORE.getPreferredName(), score);
if (collateMatch != null) {
builder.field(COLLATE_MATCH.getPreferredName(), collateMatch.booleanValue());
}
return builder;
}
protected void mergeInto(Option otherOption) {
score = Math.max(score, otherOption.score);
if (otherOption.collateMatch != null) {
if (collateMatch == null) {
collateMatch = otherOption.collateMatch;
} else {
collateMatch |= otherOption.collateMatch;
}
}
}
/*
* We consider options equal if they have the same text, even if their other fields may differ
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Option that = (Option) o;
return Objects.equals(text, that.text);
}
@Override
public int hashCode() {
return Objects.hash(text);
}
}
}
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
}
| Option |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/seqno/SequenceNumbers.java | {
"start": 597,
"end": 4838
} | class ____ {
public static final String LOCAL_CHECKPOINT_KEY = "local_checkpoint";
public static final String MAX_SEQ_NO = "max_seq_no";
/**
* Represents an unassigned sequence number (e.g., can be used on primary operations before they are executed).
*/
public static final long UNASSIGNED_SEQ_NO = -2L;
/**
* Represents no operations have been performed on the shard. Initial value of a sequence number.
*/
public static final long NO_OPS_PERFORMED = -1L;
/**
* Represents an unassigned primary term (e.g., when a primary shard was not yet allocated)
*/
public static final long UNASSIGNED_PRIMARY_TERM = 0L;
/**
* Reads the sequence number stats from the commit data (maximum sequence number and local checkpoint).
*
* @param commitData the commit data
* @return the sequence number stats
*/
public static CommitInfo loadSeqNoInfoFromLuceneCommit(final Iterable<Map.Entry<String, String>> commitData) {
long maxSeqNo = NO_OPS_PERFORMED;
long localCheckpoint = NO_OPS_PERFORMED;
for (final Map.Entry<String, String> entry : commitData) {
final String key = entry.getKey();
if (key.equals(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) {
assert localCheckpoint == NO_OPS_PERFORMED : localCheckpoint;
localCheckpoint = Long.parseLong(entry.getValue());
} else if (key.equals(SequenceNumbers.MAX_SEQ_NO)) {
assert maxSeqNo == NO_OPS_PERFORMED : maxSeqNo;
maxSeqNo = Long.parseLong(entry.getValue());
}
}
return new CommitInfo(maxSeqNo, localCheckpoint);
}
/**
* Compute the minimum of the given current minimum sequence number and the specified sequence number, accounting for the fact that the
* current minimum sequence number could be {@link SequenceNumbers#NO_OPS_PERFORMED} or
* {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. When the current minimum sequence number is not
* {@link SequenceNumbers#NO_OPS_PERFORMED} nor {@link SequenceNumbers#UNASSIGNED_SEQ_NO}, the specified sequence number
* must not be {@link SequenceNumbers#UNASSIGNED_SEQ_NO}.
*
* @param minSeqNo the current minimum sequence number
* @param seqNo the specified sequence number
* @return the new minimum sequence number
*/
public static long min(final long minSeqNo, final long seqNo) {
if (minSeqNo == NO_OPS_PERFORMED) {
return seqNo;
} else if (minSeqNo == UNASSIGNED_SEQ_NO) {
return seqNo;
} else {
if (seqNo == UNASSIGNED_SEQ_NO) {
throw new IllegalArgumentException("sequence number must be assigned");
}
return Math.min(minSeqNo, seqNo);
}
}
/**
* Compute the maximum of the given current maximum sequence number and the specified sequence number, accounting for the fact that the
* current maximum sequence number could be {@link SequenceNumbers#NO_OPS_PERFORMED} or
* {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. When the current maximum sequence number is not
* {@link SequenceNumbers#NO_OPS_PERFORMED} nor {@link SequenceNumbers#UNASSIGNED_SEQ_NO}, the specified sequence number
* must not be {@link SequenceNumbers#UNASSIGNED_SEQ_NO}.
*
* @param maxSeqNo the current maximum sequence number
* @param seqNo the specified sequence number
* @return the new maximum sequence number
*/
public static long max(final long maxSeqNo, final long seqNo) {
if (maxSeqNo == NO_OPS_PERFORMED) {
return seqNo;
} else if (maxSeqNo == UNASSIGNED_SEQ_NO) {
return seqNo;
} else {
if (seqNo == UNASSIGNED_SEQ_NO) {
throw new IllegalArgumentException("sequence number must be assigned");
}
return Math.max(maxSeqNo, seqNo);
}
}
public record CommitInfo(long maxSeqNo, long localCheckpoint) {
@Override
public String toString() {
return "CommitInfo{maxSeqNo=" + maxSeqNo + ", localCheckpoint=" + localCheckpoint + '}';
}
}
}
| SequenceNumbers |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/lookup/cache/trigger/PeriodicCacheReloadTrigger.java | {
"start": 5736,
"end": 5964
} | enum ____ {
FIXED_DELAY, // reload interval is between the end of previous and start of the next reload
FIXED_RATE // reload interval is between the start of previous and start of the next reload
}
}
| ScheduleMode |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/ExcludePackageNameFilter.java | {
"start": 1082,
"end": 2777
} | class ____ implements PackageNameFilter {
private final List<String> packageNames;
private final String patternDescription;
ExcludePackageNameFilter(String... packageNames) {
Preconditions.notEmpty(packageNames, "packageNames must not be null or empty");
Preconditions.containsNoNullElements(packageNames, "packageNames must not contain null elements");
this.packageNames = Arrays.asList(packageNames);
this.patternDescription = Arrays.stream(packageNames).collect(joining("' OR '", "'", "'"));
}
@Override
public FilterResult apply(String packageName) {
return findMatchingName(packageName) //
.map(matchedName -> excluded(formatExclusionReason(packageName, matchedName))) //
.orElseGet(() -> included(formatInclusionReason(packageName)));
}
private String formatInclusionReason(String packageName) {
return "Package name [%s] does not match any excluded names: %s".formatted(packageName,
this.patternDescription);
}
private String formatExclusionReason(String packageName, String matchedName) {
return "Package name [%s] matches excluded name: '%s'".formatted(packageName, matchedName);
}
@Override
public Predicate<String> toPredicate() {
return packageName -> findMatchingName(packageName).isEmpty();
}
private Optional<String> findMatchingName(String packageName) {
return this.packageNames.stream().filter(
name -> name.equals(packageName) || packageName.startsWith(name + ".")).findAny();
}
@Override
public String toString() {
return "%s that excludes packages whose names are either equal to or start with one of the following: %s".formatted(
getClass().getSimpleName(), this.patternDescription);
}
}
| ExcludePackageNameFilter |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ClassInitializationDeadlockTest.java | {
"start": 1332,
"end": 1546
} | class ____ extends A {}
}
""")
.doTest();
}
@Test
public void negativeMethod() {
testHelper
.addSourceLines(
"A.java",
"""
public | B |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/annotation/UuidGeneratorAnnotationTests.java | {
"start": 1260,
"end": 4051
} | class ____ {
@Test
public void verifyRandomUuidGeneratorModel(DomainModelScope scope) {
scope.withHierarchy( TheEntity.class, (descriptor) -> {
final Property idProperty = descriptor.getIdentifierProperty();
final BasicValue value = (BasicValue) idProperty.getValue();
assertThat( value.getCustomIdGeneratorCreator() ).isNotNull();
final Generator generator = value.getCustomIdGeneratorCreator().createGenerator( new IdGeneratorCreationContext(
scope.getDomainModel(),
descriptor
));
assertThat( generator ).isInstanceOf( UuidGenerator.class );
final UuidGenerator uuidGenerator = (UuidGenerator) generator;
assertThat( uuidGenerator.getValueGenerator() ).isInstanceOf( StandardRandomStrategy.class );
} );
}
@Test
public void verifyCustomUuidGeneratorModel(DomainModelScope scope) {
scope.withHierarchy( AnotherEntity.class, (descriptor) -> {
final Property idProperty = descriptor.getIdentifierProperty();
final BasicValue value = (BasicValue) idProperty.getValue();
assertThat( value.getCustomIdGeneratorCreator() ).isNotNull();
final Generator generator = value.getCustomIdGeneratorCreator().createGenerator( new IdGeneratorCreationContext(
scope.getDomainModel(),
descriptor
));
assertThat( generator ).isInstanceOf( UuidGenerator.class );
final UuidGenerator uuidGenerator = (UuidGenerator) generator;
assertThat( uuidGenerator.getValueGenerator() ).isInstanceOf( CustomUuidValueGenerator.class );
} );
}
@Test
public void basicUseTest(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
TheEntity steve = new TheEntity("steve");
session.persist( steve );
session.flush();
assertThat( steve.id ).isNotNull();
} );
}
@Test
public void nonPkUseTest(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
TheOtherEntity gavin = new TheOtherEntity("gavin");
session.persist( gavin );
session.flush();
assertThat( gavin.id ).isNotNull();
} );
}
@Test
void testCustomValueGenerator(SessionFactoryScope sessionFactoryScope) {
sessionFactoryScope.inTransaction( (session) -> {
final UUID sessionIdentifier = session.getSessionIdentifier();
final AnotherEntity anotherEntity = new AnotherEntity( "johnny" );
session.persist( anotherEntity );
assertThat( anotherEntity.getId() ).isNotNull();
session.flush();
assertThat( anotherEntity.getId() ).isNotNull();
assertThat( anotherEntity.getId().getMostSignificantBits() ).isEqualTo( sessionIdentifier.getMostSignificantBits() );
assertThat( anotherEntity.getId().getLeastSignificantBits() ).isEqualTo( 1L );
} );
}
@AfterEach
void dropTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
}
| UuidGeneratorAnnotationTests |
java | apache__camel | components/camel-kafka/src/main/java/org/apache/camel/component/kafka/transform/RegexRouter.java | {
"start": 1048,
"end": 2101
} | class ____ {
public void process(
@ExchangeProperty("regex") String regex, @ExchangeProperty("replacement") String replacement, Exchange ex) {
Pattern regexPattern = Pattern.compile(regex);
String topicName = ex.getMessage().getHeader("kafka.TOPIC", String.class);
if (ObjectHelper.isNotEmpty(topicName)) {
final Matcher matcher = regexPattern.matcher(topicName);
if (matcher.matches()) {
final String topicUpdated = matcher.replaceFirst(replacement);
ex.getMessage().setHeader("kafka.OVERRIDE_TOPIC", topicUpdated);
}
}
String ceType = ex.getMessage().getHeader("ce-type", String.class);
if (ObjectHelper.isNotEmpty(ceType)) {
final Matcher matcher = regexPattern.matcher(ceType);
if (matcher.matches()) {
final String ceTypeUpdated = matcher.replaceFirst(replacement);
ex.getMessage().setHeader("ce-type", ceTypeUpdated);
}
}
}
}
| RegexRouter |
java | quarkusio__quarkus | extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/config/MpTelemetryRelocateConfigSourceInterceptor.java | {
"start": 384,
"end": 1366
} | class ____ implements ConfigSourceInterceptorFactory {
@Override
public ConfigSourceInterceptor getInterceptor(final ConfigSourceInterceptorContext context) {
ConfigValue mpCompatibility = context.proceed("quarkus.otel.mp.compatibility");
if (mpCompatibility != null && mpCompatibility.getValue() != null) {
if (Converters.getImplicitConverter(Boolean.class).convert(mpCompatibility.getValue())) {
return new RelocateConfigSourceInterceptor(Map.of(
"quarkus.otel.service.name", "otel.service.name",
"quarkus.otel.resource.attributes", "otel.resource.attributes"));
}
}
return new ConfigSourceInterceptor() {
@Override
public ConfigValue getValue(final ConfigSourceInterceptorContext context, final String name) {
return context.proceed(name);
}
};
}
}
| MpTelemetryRelocateConfigSourceInterceptor |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/exc/UnrecognizedPropertyException.java | {
"start": 200,
"end": 393
} | class ____ used
* to indicate problems due to encountering a JSON property that could
* not be mapped to an Object property (via getter, constructor argument
* or field).
*/
public | specifically |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/script/ScriptTests.java | {
"start": 1459,
"end": 8766
} | class ____ extends ESTestCase {
public void testScriptParsing() throws IOException {
Script expectedScript = createScript();
try (XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()))) {
expectedScript.toXContent(builder, ToXContent.EMPTY_PARAMS);
try (XContentParser parser = createParser(builder)) {
Script actualScript = Script.parse(parser);
assertThat(actualScript, equalTo(expectedScript));
}
}
}
public void testScriptSerialization() throws IOException {
Script expectedScript = createScript();
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
expectedScript.writeTo(new OutputStreamStreamOutput(out));
try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
Script actualScript = new Script(new InputStreamStreamInput(in));
assertThat(actualScript, equalTo(expectedScript));
}
}
}
private Script createScript() throws IOException {
final Map<String, Object> params = randomBoolean() ? Collections.emptyMap() : Collections.singletonMap("key", "value");
ScriptType scriptType = randomFrom(ScriptType.values());
String script;
if (scriptType == ScriptType.INLINE) {
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
builder.startObject();
builder.field("field", randomAlphaOfLengthBetween(1, 5));
builder.endObject();
script = Strings.toString(builder);
}
} else {
script = randomAlphaOfLengthBetween(1, 5);
}
return new Script(
scriptType,
scriptType == ScriptType.STORED ? null : randomFrom("_lang1", "_lang2", "_lang3"),
script,
scriptType == ScriptType.INLINE ? Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) : null,
params
);
}
public void testParse() throws IOException {
Script expectedScript = createScript();
try (XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()))) {
expectedScript.toXContent(builder, ToXContent.EMPTY_PARAMS);
try (XContentParser xParser = createParser(builder)) {
Settings settings = Settings.fromXContent(xParser);
Script actualScript = Script.parse(settings);
assertThat(actualScript, equalTo(expectedScript));
}
}
}
public void testParseFromObjectShortSyntax() {
Script script = Script.parse("doc['my_field']");
assertEquals(Script.DEFAULT_SCRIPT_LANG, script.getLang());
assertEquals("doc['my_field']", script.getIdOrCode());
assertEquals(0, script.getParams().size());
assertEquals(0, script.getOptions().size());
assertEquals(ScriptType.INLINE, script.getType());
}
public void testParseFromObject() {
Map<String, Object> map = new HashMap<>();
map.put("source", "doc['my_field']");
Map<String, Object> params = new HashMap<>();
int numParams = randomIntBetween(0, 3);
for (int i = 0; i < numParams; i++) {
params.put("param" + i, i);
}
map.put("params", params);
Map<String, String> options = new HashMap<>();
int numOptions = randomIntBetween(0, 3);
for (int i = 0; i < numOptions; i++) {
options.put("option" + i, Integer.toString(i));
}
map.put("options", options);
String lang = Script.DEFAULT_SCRIPT_LANG;
;
if (randomBoolean()) {
map.put("lang", lang);
} else if (randomBoolean()) {
lang = "expression";
map.put("lang", lang);
}
Script script = Script.parse(map);
assertEquals(lang, script.getLang());
assertEquals("doc['my_field']", script.getIdOrCode());
assertEquals(ScriptType.INLINE, script.getType());
assertEquals(params, script.getParams());
assertEquals(options, script.getOptions());
}
public void testParseFromObjectFromScript() {
Map<String, Object> params = new HashMap<>();
int numParams = randomIntBetween(0, 3);
for (int i = 0; i < numParams; i++) {
params.put("param" + i, i);
}
Map<String, String> options = new HashMap<>();
int numOptions = randomIntBetween(0, 3);
for (int i = 0; i < numOptions; i++) {
options.put("option" + i, Integer.toString(i));
}
Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "doc['field']", options, params);
Map<String, Object> scriptObject = XContentHelper.convertToMap(XContentType.JSON.xContent(), Strings.toString(script), false);
Script parsedScript = Script.parse(scriptObject);
assertEquals(script, parsedScript);
}
public void testParseFromObjectWrongFormat() {
{
NullPointerException exc = expectThrows(NullPointerException.class, () -> Script.parse((Object) null));
assertEquals("Script must not be null", exc.getMessage());
}
{
IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> Script.parse(3));
assertEquals("Script value should be a String or a Map", exc.getMessage());
}
{
ElasticsearchParseException exc = expectThrows(ElasticsearchParseException.class, () -> Script.parse(Collections.emptyMap()));
assertEquals("Expected one of [source] or [id] fields, but found none", exc.getMessage());
}
}
public void testParseFromObjectUnsupportedFields() {
ElasticsearchParseException exc = expectThrows(
ElasticsearchParseException.class,
() -> Script.parse(Map.of("source", "script", "unsupported", "value"))
);
assertEquals("Unsupported field [unsupported]", exc.getMessage());
}
public void testParseFromObjectWrongOptionsFormat() {
Map<String, Object> map = new HashMap<>();
map.put("source", "doc['my_field']");
map.put("options", 3);
ElasticsearchParseException exc = expectThrows(ElasticsearchParseException.class, () -> Script.parse(map));
assertEquals("Value must be of type Map: [options]", exc.getMessage());
}
public void testParseFromObjectWrongParamsFormat() {
Map<String, Object> map = new HashMap<>();
map.put("source", "doc['my_field']");
map.put("params", 3);
ElasticsearchParseException exc = expectThrows(ElasticsearchParseException.class, () -> Script.parse(map));
assertEquals("Value must be of type Map: [params]", exc.getMessage());
}
public void testDynamicMapToString() {
Map<String, Object> map = new HashMap<>();
map.put("long", 1L);
map.put("string", "value");
DynamicMap dm = new DynamicMap(map, Collections.emptyMap());
assertThat(dm.toString(), both(containsString("long=1")).and(containsString("string=value")));
}
}
| ScriptTests |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/MulticastCopyOfSplitSubUnitOfWorkTest.java | {
"start": 1115,
"end": 3277
} | class ____ extends ContextTestSupport {
private static int counter;
@Test
public void testOK() throws Exception {
counter = 0;
getMockEndpoint("mock:dead").expectedMessageCount(0);
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:b").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(1);
getMockEndpoint("mock:line").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testError() throws Exception {
counter = 0;
getMockEndpoint("mock:dead").expectedMessageCount(1);
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:b").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:line").expectedMessageCount(0);
template.sendBody("direct:start", "Hello Donkey");
assertMockEndpointsSatisfied();
// 1 first + 3 redeliveries
assertEquals(4, counter);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// START SNIPPET: e1
errorHandler(deadLetterChannel("mock:dead").useOriginalMessage().maximumRedeliveries(3).redeliveryDelay(0));
from("direct:start").to("mock:a")
// share unit of work in the multicast, which tells Camel to
// propagate failures from
// processing the multicast messages back to the result of
// the splitter, which allows
// it to act as a combined unit of work
.multicast().shareUnitOfWork().to("mock:b").to("direct:line").end().to("mock:result");
from("direct:line").to("log:line").process(new MyProcessor()).to("mock:line");
// END SNIPPET: e1
}
};
}
public static | MulticastCopyOfSplitSubUnitOfWorkTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/slm/action/ExecuteSnapshotLifecycleAction.java | {
"start": 2447,
"end": 3310
} | class ____ extends ActionResponse implements ToXContentObject {
private final String snapshotName;
public Response(String snapshotName) {
this.snapshotName = snapshotName;
}
public String getSnapshotName() {
return this.snapshotName;
}
public Response(StreamInput in) throws IOException {
this(in.readString());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(this.snapshotName);
}
@Override
public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("snapshot_name", getSnapshotName());
builder.endObject();
return builder;
}
}
}
| Response |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/stats/StatsAccumulator.java | {
"start": 643,
"end": 721
} | class ____ collect min, max, avg and total statistics for a quantity
*/
public | to |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTableTest.java | {
"start": 1368,
"end": 2479
} | class ____ {
// Expected script:
//
// create table Child (
// id bigint not null,
// some_fk bigint,
// primary key (id)
// );
//
// create table Parent (
// id bigint not null,
// primary key (id)
// );
private static final String DELIMITER = ";";
@Test
public void test(
DomainModelScope modelScope,
@TempDir File tmpDir) throws Exception {
var output = new File( tmpDir, "update_script.sql" );
var model = modelScope.getDomainModel();
model.orderColumns( false );
model.validate();
new SchemaUpdate()
.setHaltOnError( true )
.setOutputFile( output.getAbsolutePath() )
.setDelimiter( DELIMITER )
.setFormat( true )
.execute( EnumSet.of( TargetType.SCRIPT ), model );
String outputContent = new String(Files.readAllBytes(output.toPath()));
Assertions.assertFalse( outputContent.toLowerCase().contains( "foreign key" ) );
}
@Entity(name = "Parent")
@SecondaryTable(
name = "ParentDetails",
foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT)
)
public static | SchemaUpdateJoinColumnNoConstraintSecondaryTableTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java | {
"start": 15671,
"end": 15754
} | class ____ {
public void a() {}
}
public | A |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java | {
"start": 55851,
"end": 56144
} | class ____ [" + targetCanonicalClassName + "] cannot have multiple constructors"
);
}
javaConstructor = eachJavaConstructor;
}
}
if (javaConstructor == null) {
throw new IllegalArgumentException(" | binding |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/search/scriptfilter/ScriptQuerySearchIT.java | {
"start": 2226,
"end": 12093
} | class ____ extends MockScriptPlugin {
@Override
protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put("doc['num1'].value", vars -> {
Map<?, ?> doc = (Map) vars.get("doc");
return doc.get("num1");
});
scripts.put("doc['num1'].value > 1", vars -> {
Map<?, ?> doc = (Map) vars.get("doc");
ScriptDocValues.Doubles num1 = (ScriptDocValues.Doubles) doc.get("num1");
return num1.getValue() > 1;
});
scripts.put("doc['num1'].value > param1", vars -> {
Integer param1 = (Integer) vars.get("param1");
Map<?, ?> doc = (Map) vars.get("doc");
ScriptDocValues.Doubles num1 = (ScriptDocValues.Doubles) doc.get("num1");
return num1.getValue() > param1;
});
scripts.put("doc['binaryData'].get(0).length", vars -> {
Map<?, ?> doc = (Map) vars.get("doc");
return ((ScriptDocValues.BytesRefs) doc.get("binaryData")).get(0).length;
});
scripts.put("doc['binaryData'].get(0).length > 15", vars -> {
Map<?, ?> doc = (Map) vars.get("doc");
return ((ScriptDocValues.BytesRefs) doc.get("binaryData")).get(0).length > 15;
});
return scripts;
}
}
@Override
public Settings indexSettings() {
return Settings.builder()
.put(super.indexSettings())
// aggressive filter caching so that we can assert on the number of iterations of the script filters
.put(IndexModule.INDEX_QUERY_CACHE_ENABLED_SETTING.getKey(), true)
.put(IndexModule.INDEX_QUERY_CACHE_EVERYTHING_SETTING.getKey(), true)
.build();
}
public void testCustomScriptBinaryField() throws Exception {
final byte[] randomBytesDoc1 = getRandomBytes(15);
final byte[] randomBytesDoc2 = getRandomBytes(16);
assertAcked(indicesAdmin().prepareCreate("my-index").setMapping(createMappingSource("binary")).setSettings(indexSettings()));
prepareIndex("my-index").setId("1")
.setSource(jsonBuilder().startObject().field("binaryData", Base64.getEncoder().encodeToString(randomBytesDoc1)).endObject())
.get();
flush();
prepareIndex("my-index").setId("2")
.setSource(jsonBuilder().startObject().field("binaryData", Base64.getEncoder().encodeToString(randomBytesDoc2)).endObject())
.get();
flush();
refresh();
assertResponse(
prepareSearch().setQuery(
scriptQuery(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['binaryData'].get(0).length > 15", emptyMap()))
)
.addScriptField(
"sbinaryData",
new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['binaryData'].get(0).length", emptyMap())
),
response -> {
assertThat(response.getHits().getTotalHits().value(), equalTo(1L));
assertThat(response.getHits().getAt(0).getId(), equalTo("2"));
assertThat(response.getHits().getAt(0).getFields().get("sbinaryData").getValues().get(0), equalTo(16));
}
);
}
private byte[] getRandomBytes(int len) {
final byte[] randomBytes = new byte[len];
random().nextBytes(randomBytes);
return randomBytes;
}
private XContentBuilder createMappingSource(String fieldType) throws IOException {
return XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject("binaryData")
.field("type", fieldType)
.field("doc_values", "true")
.endObject()
.endObject()
.endObject()
.endObject();
}
public void testCustomScriptBoost() throws Exception {
createIndex("test");
prepareIndex("test").setId("1")
.setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 1.0f).endObject())
.get();
flush();
prepareIndex("test").setId("2")
.setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 2.0f).endObject())
.get();
flush();
prepareIndex("test").setId("3")
.setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 3.0f).endObject())
.get();
refresh();
logger.info("running doc['num1'].value > 1");
assertResponse(
prepareSearch().setQuery(
scriptQuery(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value > 1", Collections.emptyMap()))
)
.addSort("num1", SortOrder.ASC)
.addScriptField(
"sNum1",
new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value", Collections.emptyMap())
),
response -> {
assertThat(response.getHits().getTotalHits().value(), equalTo(2L));
assertThat(response.getHits().getAt(0).getId(), equalTo("2"));
assertThat(response.getHits().getAt(0).getFields().get("sNum1").getValues().get(0), equalTo(2.0));
assertThat(response.getHits().getAt(1).getId(), equalTo("3"));
assertThat(response.getHits().getAt(1).getFields().get("sNum1").getValues().get(0), equalTo(3.0));
}
);
Map<String, Object> params = new HashMap<>();
params.put("param1", 2);
logger.info("running doc['num1'].value > param1");
assertResponse(
prepareSearch().setQuery(
scriptQuery(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value > param1", params))
)
.addSort("num1", SortOrder.ASC)
.addScriptField(
"sNum1",
new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value", Collections.emptyMap())
),
response -> {
assertThat(response.getHits().getTotalHits().value(), equalTo(1L));
assertThat(response.getHits().getAt(0).getId(), equalTo("3"));
assertThat(response.getHits().getAt(0).getFields().get("sNum1").getValues().get(0), equalTo(3.0));
}
);
params = new HashMap<>();
params.put("param1", -1);
logger.info("running doc['num1'].value > param1");
assertResponse(
prepareSearch().setQuery(
scriptQuery(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value > param1", params))
)
.addSort("num1", SortOrder.ASC)
.addScriptField(
"sNum1",
new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value", Collections.emptyMap())
),
response -> {
assertThat(response.getHits().getTotalHits().value(), equalTo(3L));
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getFields().get("sNum1").getValues().get(0), equalTo(1.0));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(1).getFields().get("sNum1").getValues().get(0), equalTo(2.0));
assertThat(response.getHits().getAt(2).getId(), equalTo("3"));
assertThat(response.getHits().getAt(2).getFields().get("sNum1").getValues().get(0), equalTo(3.0));
}
);
}
public void testDisallowExpensiveQueries() {
try {
assertAcked(prepareCreate("test-index").setMapping("num1", "type=double"));
int docCount = 10;
for (int i = 1; i <= docCount; i++) {
prepareIndex("test-index").setId("" + i).setSource("num1", i).get();
}
refresh();
// Execute with search.allow_expensive_queries = null => default value = false => success
Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value > 1", Collections.emptyMap());
assertNoFailures(prepareSearch("test-index").setQuery(scriptQuery(script)));
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", false));
// Set search.allow_expensive_queries to "false" => assert failure
ElasticsearchException e = expectThrows(
ElasticsearchException.class,
prepareSearch("test-index").setQuery(scriptQuery(script))
);
assertEquals(
"[script] queries cannot be executed when 'search.allow_expensive_queries' is set to false.",
e.getCause().getMessage()
);
// Set search.allow_expensive_queries to "true" => success
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", true));
assertNoFailures(prepareSearch("test-index").setQuery(scriptQuery(script)));
} finally {
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", (String) null));
}
}
private static AtomicInteger scriptCounter = new AtomicInteger(0);
public static int incrementScriptCounter() {
return scriptCounter.incrementAndGet();
}
}
| CustomScriptPlugin |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/config/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig.java | {
"start": 2131,
"end": 2264
} | class ____ {
@Bean
public String foo() {
return "Production Foo";
}
}
@Configuration
@Profile("resolver")
| ProductionConfig |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/performance/ITestCreateSessionTimeout.java | {
"start": 3027,
"end": 7072
} | class ____ extends AbstractS3ACostTest {
private static final Logger LOG =
LoggerFactory.getLogger(ITestCreateSessionTimeout.class);
/**
* What is the duration for the operation after which the test is considered
* to have failed because timeouts didn't get passed down?
*/
private static final long TIMEOUT_EXCEPTION_THRESHOLD = Duration.ofSeconds(5).toMillis();
/**
* How long to sleep in requests?
*/
private static final AtomicLong SLEEP_DURATION = new AtomicLong(
Duration.ofSeconds(20).toMillis());
/**
* Flag set if the sleep was interrupted during signing.
*/
private static final AtomicBoolean SLEEP_INTERRUPTED = new AtomicBoolean(false);
/**
* Create a configuration with a 10 millisecond timeout on API calls
* and a custom signer which sleeps much longer than that.
* @return the configuration.
*/
@Override
public Configuration createConfiguration() {
final Configuration conf = super.createConfiguration();
skipIfNotS3ExpressBucket(conf);
disableFilesystemCaching(conf);
removeBaseAndBucketOverrides(conf,
CUSTOM_SIGNERS,
HTTP_SIGNER_ENABLED,
REQUEST_TIMEOUT,
RETRY_LIMIT,
S3A_BUCKET_PROBE,
S3EXPRESS_CREATE_SESSION,
SIGNING_ALGORITHM_S3
);
conf.setBoolean(HTTP_SIGNER_ENABLED, true);
conf.setClass(HTTP_SIGNER_CLASS_NAME, SlowSigner.class, HttpSigner.class);
Duration duration = Duration.ofMillis(10);
conf.setLong(REQUEST_TIMEOUT, duration.toMillis());
conf.setInt(RETRY_LIMIT, 1);
return conf;
}
@BeforeEach
@Override
public void setup() throws Exception {
// remove the safety check on minimum durations.
AWSClientConfig.setMinimumOperationDuration(Duration.ZERO);
try {
super.setup();
} finally {
// restore the safety check on minimum durations.
AWSClientConfig.resetMinimumOperationDuration();
}
}
@Override
protected void deleteTestDirInTeardown() {
// no-op
}
/**
* Make this a no-op to avoid IO.
* @param path path path
*/
@Override
protected void mkdirs(Path path) {
}
@Test
public void testSlowSigningTriggersTimeout() throws Throwable {
final S3AFileSystem fs = getFileSystem();
DurationInfo call = new DurationInfo(LOG, true, "Create session");
final AWSApiCallTimeoutException thrown = intercept(AWSApiCallTimeoutException.class,
() -> fs.getFileStatus(path("testShortTimeout")));
call.finished();
LOG.info("Exception raised after {}", call, thrown);
// if the timeout took too long, fail with details and include the original
// exception
if (call.value() > TIMEOUT_EXCEPTION_THRESHOLD) {
throw new AssertionError("Duration of create session " + call.getDurationString()
+ " exceeds threshold " + TIMEOUT_EXCEPTION_THRESHOLD + " ms: " + thrown, thrown);
}
Assertions.assertThat(SLEEP_INTERRUPTED.get())
.describedAs("Sleep interrupted during signing")
.isTrue();
// now scan the inner exception stack for "createSession"
Arrays.stream(thrown.getCause().getStackTrace())
.filter(e -> e.getMethodName().equals("createSession"))
.findFirst()
.orElseThrow(() ->
new AssertionError("No createSession() in inner stack trace of", thrown));
}
/**
* Sleep for as long as {@link #SLEEP_DURATION} requires.
*/
private static void sleep() {
long sleep = SLEEP_DURATION.get();
if (sleep > 0) {
LOG.info("Sleeping for {} ms", sleep, new Exception());
try (DurationInfo d = new DurationInfo(LOG, true, "Sleep for %d ms", sleep)) {
Thread.sleep(sleep);
} catch (InterruptedException e) {
LOG.info("Interrupted", e);
SLEEP_INTERRUPTED.set(true);
Thread.currentThread().interrupt();
}
}
}
/**
* A signer which calls {@link #sleep()} before signing.
* As this signing takes place within the CreateSession Pipeline,
*/
public static | ITestCreateSessionTimeout |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 91043,
"end": 91657
} | class ____ {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Header("foo") List<String> kit) {
return null;
}
}
Request request = buildRequest(Example.class, asList("bar", null, "baz"));
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.values("foo")).containsExactly("bar", "baz");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headerParamArray() {
| Example |
java | elastic__elasticsearch | modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/TrimProcessorTests.java | {
"start": 518,
"end": 1464
} | class ____ extends AbstractStringProcessorTestCase<String> {
@Override
protected AbstractStringProcessor<String> newProcessor(String field, boolean ignoreMissing, String targetField) {
return new TrimProcessor(randomAlphaOfLength(10), null, field, ignoreMissing, targetField);
}
@Override
protected String modifyInput(String input) {
String updatedFieldValue = "";
updatedFieldValue = addWhitespaces(updatedFieldValue);
updatedFieldValue += input;
updatedFieldValue = addWhitespaces(updatedFieldValue);
return updatedFieldValue;
}
@Override
protected String expectedResult(String input) {
return input.trim();
}
private static String addWhitespaces(String input) {
int prefixLength = randomIntBetween(0, 10);
for (int i = 0; i < prefixLength; i++) {
input += ' ';
}
return input;
}
}
| TrimProcessorTests |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java | {
"start": 4547,
"end": 4696
} | class ____ extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
setValue(new String[] {"test"});
}
}
}
| MyTestEditor |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateSynonymTest.java | {
"start": 937,
"end": 2486
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"CREATE SYNONYM offices \n" +
" FOR hr.locations;";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(0, visitor.getTables().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("cdc.en_complaint_ipr_stat_fdt0")));
assertEquals(0, visitor.getColumns().size());
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*")));
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR")));
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode")));
assertEquals("CREATE SYNONYM offices FOR hr.locations;", stmt.toString());
}
}
| OracleCreateSynonymTest |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/TestHeaderConfig.java | {
"start": 163,
"end": 343
} | class ____ {
public static final String HEADER_PARAM_NAME = "filterheader";
public String getHeaderPropertyName() {
return HEADER_PARAM_NAME;
}
}
| TestHeaderConfig |
java | apache__maven | its/core-it-support/core-it-plugins/maven-it-plugin-class-loader/dep-a/src/main/java/org/apache/maven/plugin/coreit/SomeClass.java | {
"start": 1017,
"end": 1100
} | class ____ ordering of dependencies.
*
* @author Benjamin Bentmann
*
*/
public | path |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmptyAttributeMappingsMap.java | {
"start": 362,
"end": 831
} | class ____ implements AttributeMappingsMap {
public static final EmptyAttributeMappingsMap INSTANCE = new EmptyAttributeMappingsMap();
@Override
public void forEachValue(Consumer<? super AttributeMapping> action) {
//no-op
}
@Override
public int size() {
return 0;
}
@Override
public AttributeMapping get(String name) {
return null;
}
@Override
public Iterable<AttributeMapping> valueIterator() {
return emptyList();
}
}
| EmptyAttributeMappingsMap |
java | google__error-prone | core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTest.java | {
"start": 82363,
"end": 83099
} | class ____ {
public void test(@NonNull Object nonnull, @Nullable Object nullable, Object o) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(nonnull);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullable);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(o);
}
}
""")
.doTest();
}
/** BugPattern to test dataflow analysis using nullness propagation */
@BugPattern(
summary = "Test checker for NullnessPropagationTest",
explanation =
"Outputs an error for each call to triggerNullnessChecker, describing its "
+ "argument as nullable or non-null",
severity = ERROR)
public static final | AnnotatedFormalTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/QuotaUsage.java | {
"start": 1157,
"end": 1467
} | class ____ {
private long fileAndDirectoryCount;
// Make the followings protected so that
// deprecated ContentSummary constructor can use them.
private long quota;
private long spaceConsumed;
private long spaceQuota;
private long[] typeConsumed;
private long[] typeQuota;
/** Builder | QuotaUsage |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/support/master/ShardsAcknowledgedResponseTests.java | {
"start": 1763,
"end": 2287
} | class ____ extends ShardsAcknowledgedResponse {
private TestImpl(StreamInput in, boolean readShardsAcknowledged) throws IOException {
super(in, readShardsAcknowledged);
}
private TestImpl(boolean acknowledged, boolean shardsAcknowledged) {
super(acknowledged, shardsAcknowledged);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
writeShardsAcknowledged(out);
}
}
}
| TestImpl |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropViewStatement.java | {
"start": 900,
"end": 3157
} | class ____ extends SQLStatementImpl implements SQLDropStatement {
protected List<SQLExprTableSource> tableSources = new ArrayList<SQLExprTableSource>();
protected boolean cascade;
protected boolean restrict;
protected boolean ifExists;
public SQLDropViewStatement() {
}
public SQLDropViewStatement(DbType dbType) {
super(dbType);
}
public SQLDropViewStatement(SQLName name) {
this(new SQLExprTableSource(name));
}
public SQLDropViewStatement(SQLExprTableSource tableSource) {
this.tableSources.add(tableSource);
}
public List<SQLExprTableSource> getTableSources() {
return tableSources;
}
public void addPartition(SQLExprTableSource tableSource) {
if (tableSource != null) {
tableSource.setParent(this);
}
this.tableSources.add(tableSource);
}
public void setName(SQLName name) {
this.addTableSource(new SQLExprTableSource(name));
}
public void addTableSource(SQLName name) {
this.addTableSource(new SQLExprTableSource(name));
}
public void addTableSource(SQLExprTableSource tableSource) {
tableSources.add(tableSource);
}
public boolean isCascade() {
return cascade;
}
public void setCascade(boolean cascade) {
this.cascade = cascade;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
for (int i = 0; i < tableSources.size(); i++) {
SQLExprTableSource item = tableSources.get(i);
if (item != null) {
item.accept(visitor);
}
}
}
visitor.endVisit(this);
}
public boolean isRestrict() {
return restrict;
}
public void setRestrict(boolean restrict) {
this.restrict = restrict;
}
public boolean isIfExists() {
return ifExists;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public List getChildren() {
return tableSources;
}
@Override
public DDLObjectType getDDLObjectType() {
return DDLObjectType.VIEW;
}
}
| SQLDropViewStatement |
java | apache__spark | core/src/main/java/org/apache/spark/shuffle/sort/BypassMergeSortShuffleWriter.java | {
"start": 2512,
"end": 3547
} | class ____ sort-based shuffle's hash-style shuffle fallback path. This write path
* writes incoming records to separate files, one file per reduce partition, then concatenates these
* per-partition files to form a single output file, regions of which are served to reducers.
* Records are not buffered in memory. It writes output in a format
* that can be served / consumed via {@link org.apache.spark.shuffle.IndexShuffleBlockResolver}.
* <p>
* This write path is inefficient for shuffles with large numbers of reduce partitions because it
* simultaneously opens separate serializers and file streams for all partitions. As a result,
* {@link SortShuffleManager} only selects this write path when
* <ul>
* <li>no map-side combine is specified, and</li>
* <li>the number of partitions is less than or equal to
* <code>spark.shuffle.sort.bypassMergeThreshold</code>.</li>
* </ul>
*
* This code used to be part of {@link org.apache.spark.util.collection.ExternalSorter} but was
* refactored into its own | implements |
java | micronaut-projects__micronaut-core | router/src/main/java/io/micronaut/web/router/uri/UriUtil.java | {
"start": 809,
"end": 6838
} | class ____ {
private UriUtil() {
}
/**
* Transform a path+query as specified by the whatwg url spec into a path+query that is allowed
* by RFC 3986. Whatwg permits certain characters (e.g. '|') and invalid percent escape
* sequences that RFC 3986 (or {@link URI}) does not allow. This method will percent-encode
* those cases, so that any URI sent by a browser can be transformed to {@link URI}.
*
* @param path The whatwg path+query
* @return A valid RFC 3986 {@code relative-ref}
*/
public static String toValidPath(String path) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.length();) {
int cp = path.codePointAt(i);
if (cp == '%') {
boolean validEscape;
if (i + 2 >= path.length()) {
validEscape = false;
} else {
char c1 = path.charAt(i + 1);
char c2 = path.charAt(i + 2);
validEscape = isAsciiHexDigit(c1) && isAsciiHexDigit(c2);
}
if (validEscape) {
sb.appendCodePoint(cp);
} else {
PercentEncoder.appendEncodedByte(sb, (byte) '%');
}
} else {
//noinspection StatementWithEmptyBody
if (cp == '/' && sb.length() == 1 && sb.charAt(0) == '/') {
// prevent '//' at start of url
} else {
PercentEncoder.RFC3986_QUERY_CHAR.encodeUtf8(sb, cp);
}
}
i += Character.charCount(cp);
}
return sb.toString();
}
/**
* Check whether the given HTTP request target is a valid RFC 3986 relative URI (path + query)
* that will be parsed without complaint by {@link URI}. If this is true, we can skip the
* expensive parsing until necessary.
*
* @param requestTarget The HTTP request line
* @return {@code true} iff this is a valid relative URI
*/
public static boolean isValidPath(@NonNull String requestTarget) {
if (requestTarget.isEmpty() || requestTarget.charAt(0) != '/') {
return false;
}
for (int i = 0; i < requestTarget.length(); i++) {
char c = requestTarget.charAt(i);
if (c == '%' || c > 0x7f || !PercentEncoder.RFC3986_QUERY_CHAR.keep((byte) c)) {
return false;
}
if (c == '/' && i < requestTarget.length() - 1) {
char next = requestTarget.charAt(i + 1);
if (next == '/') {
return false;
}
if (next == '.') {
if (i >= requestTarget.length() - 2) {
return false;
}
char nextNext = requestTarget.charAt(i + 2);
if (nextNext == '.' || nextNext == '/' || nextNext == '?' || nextNext == '#') {
return false;
}
}
}
}
return true;
}
/**
* Determine whether the given HTTP request target is a relative URI (path+query) appropriate
* for {@link #toValidPath(String)}. The invariants are:
*
* <ul>
* <li>This method returns {@code true} exactly when, according to the whatwg URL spec, this
* URL has no scheme</li>
* <li>If the input is a valid URI, this method is equal to the inverse of
* {@link URI#isAbsolute()}</li>
* <li>If this method returns {@code true}, and the input is a valid URI after going
* through {@link #toValidPath(String)}, {@link URI#isAbsolute()} is {@code false}</li>
* </ul>
*
* @param requestTarget The HTTP request target
* @return {@code true} if this URL is relative
*/
public static boolean isRelative(@NonNull String requestTarget) {
// yes this code is weird. There's a fuzz test that checks it against the whatwg spec
boolean start = true;
for (int i = 0; i < requestTarget.length(); i++) {
char c = requestTarget.charAt(i);
if (c == '\t' || c == '\n' || c == '\r') {
// newline and tab is ignored anywhere.
continue;
}
if (isAsciiLowerAlpha(c) || isAsciiUpperAlpha(c)) {
start = false;
continue;
}
if (!start) {
if (c == ':') {
return false;
}
if (isAsciiDigit(c) || c == '+' || c == '-' || c == '.') {
continue;
}
if (isC0OrSpace(c)) {
// c0 and space are trimmed at start and end, so we are either invalid or at
// the end
break;
}
} else {
if (isC0OrSpace(c)) {
// c0 and space are trimmed at start and end.
continue;
}
}
break;
}
return true;
}
private static boolean isC0(int c) {
return c <= 0x1f;
}
private static boolean isC0OrSpace(char c) {
return isC0(c) || c == ' ';
}
private static boolean isAsciiDigit(int c) {
return c >= '0' && c <= '9';
}
private static boolean isAsciiUpperHexDigit(int c) {
return isAsciiDigit(c) || (c >= 'A' && c <= 'F');
}
private static boolean isAsciiLowerHexDigit(int c) {
return isAsciiDigit(c) || (c >= 'a' && c <= 'f');
}
private static boolean isAsciiHexDigit(int c) {
return isAsciiLowerHexDigit(c) || isAsciiUpperHexDigit(c);
}
private static boolean isAsciiUpperAlpha(int c) {
return c >= 'A' && c <= 'Z';
}
private static boolean isAsciiLowerAlpha(int c) {
return c >= 'a' && c <= 'z';
}
}
| UriUtil |
java | spring-projects__spring-framework | spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheStandaloneConfigTests.java | {
"start": 932,
"end": 1199
} | class ____ extends AbstractJCacheAnnotationTests {
@Override
protected ApplicationContext getApplicationContext() {
return new GenericXmlApplicationContext(
"/org/springframework/cache/jcache/config/jCacheStandaloneConfig.xml");
}
}
| JCacheStandaloneConfigTests |
java | apache__flink | flink-core/src/main/java/org/apache/flink/util/IterableUtils.java | {
"start": 1238,
"end": 3694
} | class ____ {
/**
* Convert the given {@link Iterable} to a {@link Stream}.
*
* @param iterable to convert to a stream
* @param <E> type of the elements of the iterable
* @return stream converted from the given {@link Iterable}
*/
public static <E> Stream<E> toStream(Iterable<E> iterable) {
checkNotNull(iterable);
return iterable instanceof Collection
? ((Collection<E>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
}
/**
* Flatmap the two-dimensional {@link Iterable} into an one-dimensional {@link Iterable} and
* convert the keys into items.
*
* @param itemGroups to flatmap
* @param mapper convert the {@link K} into {@link V}
* @param <K> type of key in the two-dimensional iterable
* @param <V> type of items that are mapped to
* @param <G> iterable of {@link K}
* @return flattened one-dimensional {@link Iterable} from the given two-dimensional {@link
* Iterable}
*/
@Internal
public static <K, V, G extends Iterable<K>> Iterable<V> flatMap(
Iterable<G> itemGroups, Function<K, V> mapper) {
return () ->
new Iterator<V>() {
private final Iterator<G> groupIterator = itemGroups.iterator();
private Iterator<K> itemIterator;
@Override
public boolean hasNext() {
while (itemIterator == null || !itemIterator.hasNext()) {
if (!groupIterator.hasNext()) {
return false;
} else {
itemIterator = groupIterator.next().iterator();
}
}
return true;
}
@Override
public V next() {
if (hasNext()) {
return mapper.apply(itemIterator.next());
} else {
throw new NoSuchElementException();
}
}
};
}
// --------------------------------------------------------------------------------------------
/** Private default constructor to avoid instantiation. */
private IterableUtils() {}
}
| IterableUtils |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.