language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | quarkusio__quarkus | test-framework/vertx/src/main/java/io/quarkus/test/vertx/RunOnVertxContext.java | {
"start": 602,
"end": 1800
} | interface ____ {
/**
* Vert.x provides various types of contexts; for testing purposes the two which
* can be controlled via this annotation are the global (root) context,
* and duplicate contexts, which have a narrower scope.
* Exact scope boundaries are defined by the integration, so this might vary depending
* on how extensions set this up, but most typically you will have a duplicated "local"
* scope for the current chain; for example when processing a RestEasy Reactive request
* the duplicate context will span a single request and data stored in the duplicated
* scope should not leak across different requests.
* In most cases you will want to run a test on such duplicate context as that's
* representative of how most operations will be processed in Quarkus.
* Set to {@code false} to run on the global (root) context instead.
*
* @return {@code true} by default.
*/
boolean duplicateContext() default true;
/**
* If {@code true}, the test method is run on the Event Loop, otherwise it will be run on Vert.x blocking thread pool
*/
boolean runOnEventLoop() default true;
}
| RunOnVertxContext |
java | spring-projects__spring-framework | spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java | {
"start": 1177,
"end": 2823
} | class ____ {
@Test
void testManagedConnectionFactoryIsRequired() {
assertThatIllegalArgumentException().isThrownBy(
new LocalConnectionFactoryBean()::afterPropertiesSet);
}
@Test
void testIsSingleton() {
LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean();
assertThat(factory.isSingleton()).isTrue();
}
@Test
void testGetObjectTypeIsNullIfConnectionFactoryHasNotBeenConfigured() {
LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean();
assertThat(factory.getObjectType()).isNull();
}
@Test
void testCreatesVanillaConnectionFactoryIfNoConnectionManagerHasBeenConfigured() throws Exception {
final Object CONNECTION_FACTORY = new Object();
ManagedConnectionFactory managedConnectionFactory = mock();
given(managedConnectionFactory.createConnectionFactory()).willReturn(CONNECTION_FACTORY);
LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean();
factory.setManagedConnectionFactory(managedConnectionFactory);
factory.afterPropertiesSet();
assertThat(factory.getObject()).isEqualTo(CONNECTION_FACTORY);
}
@Test
void testCreatesManagedConnectionFactoryIfAConnectionManagerHasBeenConfigured() throws Exception {
ManagedConnectionFactory managedConnectionFactory = mock();
ConnectionManager connectionManager = mock();
LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean();
factory.setManagedConnectionFactory(managedConnectionFactory);
factory.setConnectionManager(connectionManager);
factory.afterPropertiesSet();
verify(managedConnectionFactory).createConnectionFactory(connectionManager);
}
}
| LocalConnectionFactoryBeanTests |
java | apache__camel | components/camel-tahu/src/main/java/org/apache/camel/component/tahu/handlers/TahuEdgeClient.java | {
"start": 5368,
"end": 8906
} | class ____ {
private EdgeNodeDescriptor edgeNodeDescriptor;
private List<String> deviceIds;
private String primaryHostId;
private boolean useAliases;
private Long rebirthDebounceDelay = null;
private List<MqttServerDefinition> serverDefinitions;
private RandomStartupDelay randomStartupDelay = null;
private BdSeqManager bdSeqManager;
private ExecutorService clientExecutorService;
private volatile TahuEdgeClient tahuEdgeClient;
public ClientBuilder() {
}
public ClientBuilder edgeNodeDescriptor(EdgeNodeDescriptor end) {
checkBuildState();
this.edgeNodeDescriptor = end;
return this;
}
public ClientBuilder deviceIds(List<String> deviceIds) {
checkBuildState();
this.deviceIds = List.copyOf(deviceIds);
return this;
}
public ClientBuilder primaryHostId(String primaryHostId) {
checkBuildState();
this.primaryHostId = primaryHostId;
return this;
}
public ClientBuilder useAliases(boolean useAliases) {
checkBuildState();
this.useAliases = useAliases;
return this;
}
public ClientBuilder rebirthDebounceDelay(Long rebirthDebounceDelay) {
checkBuildState();
this.rebirthDebounceDelay = rebirthDebounceDelay;
return this;
}
public ClientBuilder serverDefinitions(List<MqttServerDefinition> serverDefinitions) {
checkBuildState();
this.serverDefinitions = List.copyOf(serverDefinitions);
return this;
}
public ClientBuilder bdSeqManager(BdSeqManager bsm) {
checkBuildState();
this.bdSeqManager = bsm;
return this;
}
public ClientBuilder clientExecutorService(ExecutorService clientExecutorService) {
checkBuildState();
this.clientExecutorService = clientExecutorService;
return this;
}
private void checkBuildState() throws IllegalStateException {
if (tahuEdgeClient != null) {
throw new IllegalStateException("Unable to reuse a ClientBuilder for multiple TahuEdgeClient instances");
}
}
public TahuEdgeClient build() {
TahuEdgeClient cachedTahuEdgeClient = tahuEdgeClient;
if (cachedTahuEdgeClient == null) {
TahuEdgeMetricHandler tahuEdgeNodeMetricHandler = new TahuEdgeMetricHandler(edgeNodeDescriptor, bdSeqManager);
TahuEdgeClientCallback tahuClientCallback
= new TahuEdgeClientCallback(edgeNodeDescriptor, tahuEdgeNodeMetricHandler);
cachedTahuEdgeClient = tahuEdgeClient = new TahuEdgeClient(
tahuEdgeNodeMetricHandler, edgeNodeDescriptor, deviceIds, primaryHostId,
useAliases, rebirthDebounceDelay, serverDefinitions, tahuClientCallback, randomStartupDelay,
clientExecutorService);
LOG.debug(tahuEdgeClient.loggingMarker, "Created TahuEdgeClient for {} with deviceIds {}", edgeNodeDescriptor,
deviceIds);
tahuEdgeNodeMetricHandler.setClient(cachedTahuEdgeClient);
tahuClientCallback.setClient(cachedTahuEdgeClient);
}
return cachedTahuEdgeClient;
}
}
}
| ClientBuilder |
java | spring-projects__spring-security | itest/context/src/main/java/org/springframework/security/integration/multiannotation/MultiAnnotationService.java | {
"start": 918,
"end": 1215
} | interface ____ {
@PreAuthorize("denyAll")
void preAuthorizeDenyAllMethod();
@PreAuthorize("hasRole('ROLE_A')")
void preAuthorizeHasRoleAMethod();
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
void securedAnonymousMethod();
@Secured("ROLE_A")
void securedRoleAMethod();
}
| MultiAnnotationService |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/aot/AotQueries.java | {
"start": 2871,
"end": 3630
} | class ____ implements QueryMetadata {
private final boolean paging;
AotQueryMetadata(boolean paging) {
this.paging = paging;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> serialized = new LinkedHashMap<>();
if (result() instanceof AotQuery.NamedQuery nq) {
serialized.put("name", nq.getQueryName());
}
if (result() instanceof StringAotQuery sq) {
serialized.put("query", sq.getQueryString());
}
if (paging) {
if (count() instanceof AotQuery.NamedQuery nq) {
serialized.put("count-name", nq.getQueryName());
}
if (count() instanceof StringAotQuery sq) {
serialized.put("count-query", sq.getQueryString());
}
}
return serialized;
}
}
}
| AotQueryMetadata |
java | apache__logging-log4j2 | log4j-1.2-api/src/test/java/org/apache/log4j/LayoutTest.java | {
"start": 1013,
"end": 1063
} | class ____ tests.
*/
private static final | for |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/JMSTransactionalClientIT.java | {
"start": 1323,
"end": 2164
} | class ____ extends AbstractSpringJMSITSupport {
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"/org/apache/camel/component/jms/integration/spring/tx/JMSTransactionalClientIT.xml");
}
@Test
public void testTransactionSuccess() throws Exception {
// START SNIPPET: e1
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived("Bye World");
// success at 3rd attempt
mock.message(0).header("count").isEqualTo(3);
template.sendBody("activemq:queue:okay.JMSTransactionalClientTest", "Hello World");
mock.assertIsSatisfied();
// END SNIPPET: e1
}
// END SNIPPET: e2
}
| JMSTransactionalClientIT |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/CountDistinctFloatAggregatorFunction.java | {
"start": 1106,
"end": 6032
} | class ____ implements AggregatorFunction {
private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of(
new IntermediateStateDesc("hll", ElementType.BYTES_REF) );
private final DriverContext driverContext;
private final HllStates.SingleState state;
private final List<Integer> channels;
private final int precision;
public CountDistinctFloatAggregatorFunction(DriverContext driverContext, List<Integer> channels,
HllStates.SingleState state, int precision) {
this.driverContext = driverContext;
this.channels = channels;
this.state = state;
this.precision = precision;
}
public static CountDistinctFloatAggregatorFunction create(DriverContext driverContext,
List<Integer> channels, int precision) {
return new CountDistinctFloatAggregatorFunction(driverContext, channels, CountDistinctFloatAggregator.initSingle(driverContext.bigArrays(), precision), precision);
}
public static List<IntermediateStateDesc> intermediateStateDesc() {
return INTERMEDIATE_STATE_DESC;
}
@Override
public int intermediateBlockCount() {
return INTERMEDIATE_STATE_DESC.size();
}
@Override
public void addRawInput(Page page, BooleanVector mask) {
if (mask.allFalse()) {
// Entire page masked away
} else if (mask.allTrue()) {
addRawInputNotMasked(page);
} else {
addRawInputMasked(page, mask);
}
}
private void addRawInputMasked(Page page, BooleanVector mask) {
FloatBlock vBlock = page.getBlock(channels.get(0));
FloatVector vVector = vBlock.asVector();
if (vVector == null) {
addRawBlock(vBlock, mask);
return;
}
addRawVector(vVector, mask);
}
private void addRawInputNotMasked(Page page) {
FloatBlock vBlock = page.getBlock(channels.get(0));
FloatVector vVector = vBlock.asVector();
if (vVector == null) {
addRawBlock(vBlock);
return;
}
addRawVector(vVector);
}
private void addRawVector(FloatVector vVector) {
for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) {
float vValue = vVector.getFloat(valuesPosition);
CountDistinctFloatAggregator.combine(state, vValue);
}
}
private void addRawVector(FloatVector vVector, BooleanVector mask) {
for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) {
if (mask.getBoolean(valuesPosition) == false) {
continue;
}
float vValue = vVector.getFloat(valuesPosition);
CountDistinctFloatAggregator.combine(state, vValue);
}
}
private void addRawBlock(FloatBlock vBlock) {
for (int p = 0; p < vBlock.getPositionCount(); p++) {
int vValueCount = vBlock.getValueCount(p);
if (vValueCount == 0) {
continue;
}
int vStart = vBlock.getFirstValueIndex(p);
int vEnd = vStart + vValueCount;
for (int vOffset = vStart; vOffset < vEnd; vOffset++) {
float vValue = vBlock.getFloat(vOffset);
CountDistinctFloatAggregator.combine(state, vValue);
}
}
}
private void addRawBlock(FloatBlock vBlock, BooleanVector mask) {
for (int p = 0; p < vBlock.getPositionCount(); p++) {
if (mask.getBoolean(p) == false) {
continue;
}
int vValueCount = vBlock.getValueCount(p);
if (vValueCount == 0) {
continue;
}
int vStart = vBlock.getFirstValueIndex(p);
int vEnd = vStart + vValueCount;
for (int vOffset = vStart; vOffset < vEnd; vOffset++) {
float vValue = vBlock.getFloat(vOffset);
CountDistinctFloatAggregator.combine(state, vValue);
}
}
}
@Override
public void addIntermediateInput(Page page) {
assert channels.size() == intermediateBlockCount();
assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size();
Block hllUncast = page.getBlock(channels.get(0));
if (hllUncast.areAllValuesNull()) {
return;
}
BytesRefVector hll = ((BytesRefBlock) hllUncast).asVector();
assert hll.getPositionCount() == 1;
BytesRef hllScratch = new BytesRef();
CountDistinctFloatAggregator.combineIntermediate(state, hll.getBytesRef(0, hllScratch));
}
@Override
public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
state.toIntermediate(blocks, offset, driverContext);
}
@Override
public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) {
blocks[offset] = CountDistinctFloatAggregator.evaluateFinal(state, driverContext);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("[");
sb.append("channels=").append(channels);
sb.append("]");
return sb.toString();
}
@Override
public void close() {
state.close();
}
}
| CountDistinctFloatAggregatorFunction |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/iterative/concurrent/SuperstepKickoffLatchTest.java | {
"start": 5673,
"end": 6654
} | class ____ extends Thread {
private final Thread toWatch;
private final long timeOut;
private volatile Throwable failed;
public WatchDog(Thread toWatch, long timeout) {
setDaemon(true);
setName("Watchdog");
this.toWatch = toWatch;
this.timeOut = timeout;
}
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
toWatch.join(timeOut);
if (toWatch.isAlive()) {
this.failed = new Exception("timed out");
toWatch.interrupt();
toWatch.join(2000);
if (toWatch.isAlive()) {
toWatch.stop();
}
}
} catch (Throwable t) {
failed = t;
}
}
public Throwable getError() {
return failed;
}
}
}
| WatchDog |
java | apache__flink | flink-metrics/flink-metrics-core/src/main/java/org/apache/flink/metrics/groups/UnregisteredMetricsGroup.java | {
"start": 1390,
"end": 3507
} | class ____ implements MetricGroup {
@Override
public Counter counter(String name) {
return new SimpleCounter();
}
@Override
public <C extends Counter> C counter(String name, C counter) {
return counter;
}
@Override
public <T, G extends Gauge<T>> G gauge(String name, G gauge) {
return gauge;
}
@Override
public <M extends Meter> M meter(String name, M meter) {
return meter;
}
@Override
public <H extends Histogram> H histogram(String name, H histogram) {
return histogram;
}
@Override
public MetricGroup addGroup(String name) {
return new UnregisteredMetricsGroup();
}
@Override
public MetricGroup addGroup(String key, String value) {
return new UnregisteredMetricsGroup();
}
@Override
public String[] getScopeComponents() {
return new String[0];
}
@Override
public Map<String, String> getAllVariables() {
return Collections.emptyMap();
}
@Override
public String getMetricIdentifier(String metricName) {
return metricName;
}
@Override
public String getMetricIdentifier(String metricName, CharacterFilter filter) {
return metricName;
}
public static OperatorMetricGroup createOperatorMetricGroup() {
return new UnregisteredOperatorMetricGroup();
}
public static OperatorIOMetricGroup createOperatorIOMetricGroup() {
return new UnregisteredOperatorIOMetricGroup();
}
public static SourceReaderMetricGroup createSourceReaderMetricGroup() {
return new UnregisteredSourceReaderMetricGroup();
}
public static SplitEnumeratorMetricGroup createSplitEnumeratorMetricGroup() {
return new UnregisteredSplitEnumeratorMetricGroup();
}
public static CacheMetricGroup createCacheMetricGroup() {
return new UnregisteredCacheMetricGroup();
}
public static SinkWriterMetricGroup createSinkWriterMetricGroup() {
return new UnregisteredSinkWriterMetricGroup();
}
private static | UnregisteredMetricsGroup |
java | elastic__elasticsearch | modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/DiscountedCumulativeGainTests.java | {
"start": 1679,
"end": 16642
} | class ____ extends ESTestCase {
static final double EXPECTED_DCG = 13.84826362927298;
static final double EXPECTED_IDCG = 14.595390756454922;
static final double EXPECTED_NDCG = EXPECTED_DCG / EXPECTED_IDCG;
private static final double DELTA = 10E-14;
/**
* Assuming the docs are ranked in the following order:
*
* rank | relevance | 2^(relevance) - 1 | log_2(rank + 1) | (2^(relevance) - 1) / log_2(rank + 1)
* -------------------------------------------------------------------------------------------
* 1 | 3 | 7.0 | 1.0 | 7.0 | 7.0 |
* 2 | 2 | 3.0 | 1.5849625007211563 | 1.8927892607143721
* 3 | 3 | 7.0 | 2.0 | 3.5
* 4 | 0 | 0.0 | 2.321928094887362 | 0.0
* 5 | 1 | 1.0 | 2.584962500721156 | 0.38685280723454163
* 6 | 2 | 3.0 | 2.807354922057604 | 1.0686215613240666
*
* dcg = 13.84826362927298 (sum of last column)
*/
public void testDCGAt() {
List<RatedDocument> rated = new ArrayList<>();
int[] relevanceRatings = new int[] { 3, 2, 3, 0, 1, 2 };
SearchHit[] hits = new SearchHit[6];
for (int i = 0; i < 6; i++) {
rated.add(new RatedDocument("index", Integer.toString(i), relevanceRatings[i]));
hits[i] = SearchHit.unpooled(i, Integer.toString(i));
hits[i].shard(new SearchShardTarget("testnode", new ShardId("index", "uuid", 0), null));
}
DiscountedCumulativeGain dcg = new DiscountedCumulativeGain();
assertEquals(EXPECTED_DCG, dcg.evaluate("id", hits, rated).metricScore(), DELTA);
/**
* Check with normalization: to get the maximal possible dcg, sort documents by
* relevance in descending order
*
* rank | relevance | 2^(relevance) - 1 | log_2(rank + 1) | (2^(relevance) - 1) / log_2(rank + 1)
* ---------------------------------------------------------------------------------------
* 1 | 3 | 7.0 | 1.0 | 7.0
* 2 | 3 | 7.0 | 1.5849625007211563 | 4.416508275000202
* 3 | 2 | 3.0 | 2.0 | 1.5
* 4 | 2 | 3.0 | 2.321928094887362 | 1.2920296742201793
* 5 | 1 | 1.0 | 2.584962500721156 | 0.38685280723454163
* 6 | 0 | 0.0 | 2.807354922057604 | 0.0
*
* idcg = 14.595390756454922 (sum of last column)
*/
dcg = new DiscountedCumulativeGain(true, null, 10);
assertEquals(EXPECTED_NDCG, dcg.evaluate("id", hits, rated).metricScore(), DELTA);
}
/**
* This tests metric when some documents in the search result don't have a
* rating provided by the user.
*
* rank | relevance | 2^(relevance) - 1 | log_2(rank + 1) | (2^(relevance) - 1) / log_2(rank + 1)
* -------------------------------------------------------------------------------------------
* 1 | 3 | 7.0 | 1.0 | 7.0 2 |
* 2 | 3.0 | 1.5849625007211563 | 1.8927892607143721
* 3 | 3 | 7.0 | 2.0 | 3.5
* 4 | n/a | n/a | n/a | n/a
* 5 | 1 | 1.0 | 2.584962500721156 | 0.38685280723454163
* 6 | n/a | n/a | n/a | n/a
*
* dcg = 12.779642067948913 (sum of last column)
*/
public void testDCGAtSixMissingRatings() {
List<RatedDocument> rated = new ArrayList<>();
Integer[] relevanceRatings = new Integer[] { 3, 2, 3, null, 1 };
SearchHit[] hits = new SearchHit[6];
for (int i = 0; i < 6; i++) {
if (i < relevanceRatings.length) {
if (relevanceRatings[i] != null) {
rated.add(new RatedDocument("index", Integer.toString(i), relevanceRatings[i]));
}
}
hits[i] = SearchHit.unpooled(i, Integer.toString(i));
hits[i].shard(new SearchShardTarget("testnode", new ShardId("index", "uuid", 0), null));
}
DiscountedCumulativeGain dcg = new DiscountedCumulativeGain();
EvalQueryQuality result = dcg.evaluate("id", hits, rated);
assertEquals(12.779642067948913, result.metricScore(), DELTA);
assertEquals(2, filterUnratedDocuments(result.getHitsAndRatings()).size());
/**
* Check with normalization: to get the maximal possible dcg, sort documents by
* relevance in descending order
*
* rank | relevance | 2^(relevance) - 1 | log_2(rank + 1) | (2^(relevance) - 1) / log_2(rank + 1)
* ----------------------------------------------------------------------------------------
* 1 | 3 | 7.0 | 1.0 | 7.0
* 2 | 3 | 7.0 | 1.5849625007211563 | 4.416508275000202
* 3 | 2 | 3.0 | 2.0 | 1.5
* 4 | 1 | 1.0 | 2.321928094887362 | 0.43067655807339
* 5 | n.a | n.a | n.a. | n.a.
* 6 | n.a | n.a | n.a | n.a
*
* idcg = 13.347184833073591 (sum of last column)
*/
dcg = new DiscountedCumulativeGain(true, null, 10);
assertEquals(12.779642067948913 / 13.347184833073591, dcg.evaluate("id", hits, rated).metricScore(), DELTA);
}
/**
* This tests that normalization works as expected when there are more rated
* documents than search hits because we restrict DCG to be calculated at the
* fourth position
*
* rank | relevance | 2^(relevance) - 1 | log_2(rank + 1) | (2^(relevance) - 1) / log_2(rank + 1)
* -------------------------------------------------------------------------------------------
* 1 | 3 | 7.0 | 1.0 | 7.0 2 |
* 2 | 3.0 | 1.5849625007211563 | 1.8927892607143721
* 3 | 3 | 7.0 | 2.0 | 3.5
* 4 | n/a | n/a | n/a | n/a
* -----------------------------------------------------------------
* 5 | 1 | 1.0 | 2.584962500721156 | 0.38685280723454163
* 6 | n/a | n/a | n/a | n/a
*
* dcg = 12.392789260714371 (sum of last column until position 4)
*/
public void testDCGAtFourMoreRatings() {
Integer[] relevanceRatings = new Integer[] { 3, 2, 3, null, 1, null };
List<RatedDocument> ratedDocs = new ArrayList<>();
for (int i = 0; i < 6; i++) {
if (i < relevanceRatings.length) {
if (relevanceRatings[i] != null) {
ratedDocs.add(new RatedDocument("index", Integer.toString(i), relevanceRatings[i]));
}
}
}
// only create four hits
SearchHit[] hits = new SearchHit[4];
for (int i = 0; i < 4; i++) {
hits[i] = SearchHit.unpooled(i, Integer.toString(i));
hits[i].shard(new SearchShardTarget("testnode", new ShardId("index", "uuid", 0), null));
}
DiscountedCumulativeGain dcg = new DiscountedCumulativeGain();
EvalQueryQuality result = dcg.evaluate("id", hits, ratedDocs);
assertEquals(12.392789260714371, result.metricScore(), DELTA);
assertEquals(1, filterUnratedDocuments(result.getHitsAndRatings()).size());
/**
* Check with normalization: to get the maximal possible dcg, sort documents by
* relevance in descending order
*
* rank | relevance | 2^(relevance) - 1 | log_2(rank + 1) | (2^(relevance) - 1) / log_2(rank + 1)
* ---------------------------------------------------------------------------------------
* 1 | 3 | 7.0 | 1.0 | 7.0
* 2 | 3 | 7.0 | 1.5849625007211563 | 4.416508275000202
* 3 | 2 | 3.0 | 2.0 | 1.5
* 4 | 1 | 1.0 | 2.321928094887362 | 0.43067655807339
* ---------------------------------------------------------------------------------------
* 5 | n.a | n.a | n.a. | n.a.
* 6 | n.a | n.a | n.a | n.a
*
* idcg = 13.347184833073591 (sum of last column)
*/
dcg = new DiscountedCumulativeGain(true, null, 10);
assertEquals(12.392789260714371 / 13.347184833073591, dcg.evaluate("id", hits, ratedDocs).metricScore(), DELTA);
}
/**
* test that metric returns 0.0 when there are no search results
*/
public void testNoResults() throws Exception {
Integer[] relevanceRatings = new Integer[] { 3, 2, 3, null, 1, null };
List<RatedDocument> ratedDocs = new ArrayList<>();
for (int i = 0; i < 6; i++) {
if (i < relevanceRatings.length) {
if (relevanceRatings[i] != null) {
ratedDocs.add(new RatedDocument("index", Integer.toString(i), relevanceRatings[i]));
}
}
}
DiscountedCumulativeGain dcg = new DiscountedCumulativeGain();
EvalQueryQuality result = dcg.evaluate("id", SearchHits.EMPTY, ratedDocs);
assertEquals(0.0d, result.metricScore(), DELTA);
assertEquals(0, filterUnratedDocuments(result.getHitsAndRatings()).size());
// also check normalized
dcg = new DiscountedCumulativeGain(true, null, 10);
result = dcg.evaluate("id", SearchHits.EMPTY, ratedDocs);
assertEquals(0.0d, result.metricScore(), DELTA);
assertEquals(0, filterUnratedDocuments(result.getHitsAndRatings()).size());
}
public void testParseFromXContent() throws IOException {
assertParsedCorrect("{ \"unknown_doc_rating\": 2, \"normalize\": true, \"k\" : 15 }", 2, true, 15);
assertParsedCorrect("{ \"normalize\": false, \"k\" : 15 }", null, false, 15);
assertParsedCorrect("{ \"unknown_doc_rating\": 2, \"k\" : 15 }", 2, false, 15);
assertParsedCorrect("{ \"unknown_doc_rating\": 2, \"normalize\": true }", 2, true, 10);
assertParsedCorrect("{ \"normalize\": true }", null, true, 10);
assertParsedCorrect("{ \"k\": 23 }", null, false, 23);
assertParsedCorrect("{ \"unknown_doc_rating\": 2 }", 2, false, 10);
}
private void assertParsedCorrect(String xContent, Integer expectedUnknownDocRating, boolean expectedNormalize, int expectedK)
throws IOException {
try (XContentParser parser = createParser(JsonXContent.jsonXContent, xContent)) {
DiscountedCumulativeGain dcgAt = DiscountedCumulativeGain.fromXContent(parser);
assertEquals(expectedUnknownDocRating, dcgAt.getUnknownDocRating());
assertEquals(expectedNormalize, dcgAt.getNormalize());
assertEquals(expectedK, dcgAt.getK());
}
}
public static DiscountedCumulativeGain createTestItem() {
boolean normalize = randomBoolean();
Integer unknownDocRating = frequently() ? Integer.valueOf(randomIntBetween(0, 1000)) : null;
return new DiscountedCumulativeGain(normalize, unknownDocRating, randomIntBetween(1, 10));
}
public void testXContentRoundtrip() throws IOException {
DiscountedCumulativeGain testItem = createTestItem();
XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
XContentBuilder shuffled = shuffleXContent(testItem.toXContent(builder, ToXContent.EMPTY_PARAMS));
try (XContentParser itemParser = createParser(shuffled)) {
itemParser.nextToken();
itemParser.nextToken();
DiscountedCumulativeGain parsedItem = DiscountedCumulativeGain.fromXContent(itemParser);
assertNotSame(testItem, parsedItem);
assertEquals(testItem, parsedItem);
assertEquals(testItem.hashCode(), parsedItem.hashCode());
}
}
public void testXContentParsingIsNotLenient() throws IOException {
DiscountedCumulativeGain testItem = createTestItem();
XContentType xContentType = randomFrom(XContentType.values());
BytesReference originalBytes = toShuffledXContent(testItem, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean());
BytesReference withRandomFields = insertRandomFields(xContentType, originalBytes, null, random());
try (XContentParser parser = createParser(xContentType.xContent(), withRandomFields)) {
parser.nextToken();
parser.nextToken();
XContentParseException exception = expectThrows(
XContentParseException.class,
() -> DiscountedCumulativeGain.fromXContent(parser)
);
assertThat(exception.getMessage(), containsString("[dcg] unknown field"));
}
}
public void testMetricDetails() {
double dcg = randomDoubleBetween(0, 1, true);
double idcg = randomBoolean() ? 0.0 : randomDoubleBetween(0, 1, true);
double expectedNdcg = idcg != 0 ? dcg / idcg : 0.0;
int unratedDocs = randomIntBetween(0, 100);
DiscountedCumulativeGain.Detail detail = new DiscountedCumulativeGain.Detail(dcg, idcg, unratedDocs);
assertEquals(dcg, detail.getDCG(), 0.0);
assertEquals(idcg, detail.getIDCG(), 0.0);
assertEquals(expectedNdcg, detail.getNDCG(), 0.0);
assertEquals(unratedDocs, detail.getUnratedDocs());
if (idcg != 0) {
assertEquals(Strings.format("""
{"dcg":{"dcg":%s,"ideal_dcg":%s,"normalized_dcg":%s,"unrated_docs":%s}}\
""", dcg, idcg, expectedNdcg, unratedDocs), Strings.toString(detail));
} else {
assertEquals(Strings.format("""
{"dcg":{"dcg":%s,"unrated_docs":%s}}\
""", dcg, unratedDocs), Strings.toString(detail));
}
}
public void testSerialization() throws IOException {
DiscountedCumulativeGain original = createTestItem();
DiscountedCumulativeGain deserialized = ESTestCase.copyWriteable(
original,
new NamedWriteableRegistry(Collections.emptyList()),
DiscountedCumulativeGain::new
);
assertEquals(deserialized, original);
assertEquals(deserialized.hashCode(), original.hashCode());
assertNotSame(deserialized, original);
}
public void testEqualsAndHash() throws IOException {
checkEqualsAndHashCode(createTestItem(), original -> {
return new DiscountedCumulativeGain(original.getNormalize(), original.getUnknownDocRating(), original.getK());
}, DiscountedCumulativeGainTests::mutateTestItem);
}
private static DiscountedCumulativeGain mutateTestItem(DiscountedCumulativeGain original) {
return switch (randomIntBetween(0, 2)) {
case 0 -> new DiscountedCumulativeGain(original.getNormalize() == false, original.getUnknownDocRating(), original.getK());
case 1 -> new DiscountedCumulativeGain(
original.getNormalize(),
randomValueOtherThan(original.getUnknownDocRating(), () -> randomIntBetween(0, 10)),
original.getK()
);
case 2 -> new DiscountedCumulativeGain(
original.getNormalize(),
original.getUnknownDocRating(),
randomValueOtherThan(original.getK(), () -> randomIntBetween(1, 10))
);
default -> throw new IllegalArgumentException("mutation variant not allowed");
};
}
}
| DiscountedCumulativeGainTests |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/MultipleResponseFiltersWithPrioritiesTest.java | {
"start": 2319,
"end": 2833
} | class ____ implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String previousFilterHeaderValue = (String) responseContext.getHeaders().getFirst("filter-response");
responseContext.getHeaders().putSingle("filter-response", previousFilterHeaderValue + "-default");
}
}
@Provider
@Priority(0)
public static | FilterDefault |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java | {
"start": 24420,
"end": 33509
} | interface ____.apache.dubbo.common.extension.ext7.InitErrorExt"));
assertThat(expected.getMessage(), containsString("java.lang.ExceptionInInitializerError"));
}
}
@Test
void testLoadActivateExtension() {
// test default
URL url = URL.valueOf("test://localhost/test");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "default_group");
Assertions.assertEquals(1, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
// test group
url = url.addParameter(GROUP_KEY, "group1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "group1");
Assertions.assertEquals(1, list.size());
assertSame(list.get(0).getClass(), GroupActivateExtImpl.class);
// test value
url = url.removeParameter(GROUP_KEY);
url = url.addParameter(GROUP_KEY, "value");
url = url.addParameter("value", "value");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "value");
Assertions.assertEquals(1, list.size());
assertSame(list.get(0).getClass(), ValueActivateExtImpl.class);
// test order
url = URL.valueOf("test://localhost/test");
url = url.addParameter(GROUP_KEY, "order");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl2.class);
}
@Test
void testLoadDefaultActivateExtension1() {
// test default
URL url = URL.valueOf("test://localhost/test?ext=order1,default");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class);
assertSame(list.get(1).getClass(), ActivateExt1Impl1.class);
url = URL.valueOf("test://localhost/test?ext=default,order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
url = URL.valueOf("test://localhost/test?ext=order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
}
@Test
void testLoadDefaultActivateExtension2() {
// test default
URL url = URL.valueOf("test://localhost/test?ext=order1 , default");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class);
assertSame(list.get(1).getClass(), ActivateExt1Impl1.class);
url = URL.valueOf("test://localhost/test?ext=default, order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
url = URL.valueOf("test://localhost/test?ext=order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
}
@Test
void testInjectExtension() {
// register bean for test ScopeBeanExtensionInjector
DemoImpl demoBean = new DemoImpl();
ApplicationModel.defaultModel().getBeanFactory().registerBean(demoBean);
// test default
InjectExt injectExt = getExtensionLoader(InjectExt.class).getExtension("injection");
InjectExtImpl injectExtImpl = (InjectExtImpl) injectExt;
Assertions.assertNotNull(injectExtImpl.getSimpleExt());
Assertions.assertNull(injectExtImpl.getSimpleExt1());
Assertions.assertNull(injectExtImpl.getGenericType());
Assertions.assertSame(demoBean, injectExtImpl.getDemo());
}
@Test
void testMultiNames() {
Ext10MultiNames ext10MultiNames =
getExtensionLoader(Ext10MultiNames.class).getExtension("impl");
Assertions.assertNotNull(ext10MultiNames);
ext10MultiNames = getExtensionLoader(Ext10MultiNames.class).getExtension("implMultiName");
Assertions.assertNotNull(ext10MultiNames);
Assertions.assertThrows(IllegalStateException.class, () -> getExtensionLoader(Ext10MultiNames.class)
.getExtension("impl,implMultiName"));
}
@Test
void testGetOrDefaultExtension() {
ExtensionLoader<InjectExt> loader = getExtensionLoader(InjectExt.class);
InjectExt injectExt = loader.getOrDefaultExtension("non-exists");
assertEquals(InjectExtImpl.class, injectExt.getClass());
assertEquals(
InjectExtImpl.class, loader.getOrDefaultExtension("injection").getClass());
}
@Test
void testGetSupported() {
ExtensionLoader<InjectExt> loader = getExtensionLoader(InjectExt.class);
assertEquals(1, loader.getSupportedExtensions().size());
assertEquals(Collections.singleton("injection"), loader.getSupportedExtensions());
}
/**
* @since 2.7.7
*/
@Test
void testOverridden() {
ExtensionLoader<Converter> loader = getExtensionLoader(Converter.class);
Converter converter = loader.getExtension("string-to-boolean");
assertEquals(String2BooleanConverter.class, converter.getClass());
converter = loader.getExtension("string-to-double");
assertEquals(String2DoubleConverter.class, converter.getClass());
converter = loader.getExtension("string-to-integer");
assertEquals(String2IntegerConverter.class, converter.getClass());
assertEquals("string-to-boolean", loader.getExtensionName(String2BooleanConverter.class));
assertEquals("string-to-boolean", loader.getExtensionName(StringToBooleanConverter.class));
assertEquals("string-to-double", loader.getExtensionName(String2DoubleConverter.class));
assertEquals("string-to-double", loader.getExtensionName(StringToDoubleConverter.class));
assertEquals("string-to-integer", loader.getExtensionName(String2IntegerConverter.class));
assertEquals("string-to-integer", loader.getExtensionName(StringToIntegerConverter.class));
}
/**
* @since 2.7.7
*/
@Test
void testGetLoadingStrategies() {
List<LoadingStrategy> strategies = getLoadingStrategies();
assertEquals(4, strategies.size());
int i = 0;
LoadingStrategy loadingStrategy = strategies.get(i++);
assertEquals(DubboInternalLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.MAX_PRIORITY, loadingStrategy.getPriority());
loadingStrategy = strategies.get(i++);
assertEquals(DubboExternalLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.MAX_PRIORITY + 1, loadingStrategy.getPriority());
loadingStrategy = strategies.get(i++);
assertEquals(DubboLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.NORMAL_PRIORITY, loadingStrategy.getPriority());
loadingStrategy = strategies.get(i++);
assertEquals(ServicesLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.MIN_PRIORITY, loadingStrategy.getPriority());
}
@Test
void testDuplicatedImplWithoutOverriddenStrategy() {
List<LoadingStrategy> loadingStrategies = ExtensionLoader.getLoadingStrategies();
ExtensionLoader.setLoadingStrategies(
new DubboExternalLoadingStrategyTest(false), new DubboInternalLoadingStrategyTest(false));
ExtensionLoader<DuplicatedWithoutOverriddenExt> extensionLoader =
getExtensionLoader(DuplicatedWithoutOverriddenExt.class);
try {
extensionLoader.getExtension("duplicated");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Failed to load extension class (interface: | org |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/state/OuterJoinRecordStateViews.java | {
"start": 12587,
"end": 13215
} | class ____ implements IterableIterator<RowData> {
private final Iterator<Tuple2<RowData, Integer>> tupleIterator;
private RecordsIterable(Iterable<Tuple2<RowData, Integer>> tuples) {
checkNotNull(tuples);
this.tupleIterator = tuples.iterator();
}
@Override
public Iterator<RowData> iterator() {
return this;
}
@Override
public boolean hasNext() {
return tupleIterator.hasNext();
}
@Override
public RowData next() {
return tupleIterator.next().f0;
}
}
}
| RecordsIterable |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java | {
"start": 111392,
"end": 111890
} | class ____ {
@RequestMapping(method = RequestMethod.GET)
public String get(Model model) {
model.addAttribute("object1", new Object());
model.addAttribute("object2", new Object());
return "page1";
}
@RequestMapping(method = RequestMethod.POST)
public String post(@ModelAttribute("object1") Object object1) {
//do something with object1
return "page2";
}
}
@RequestMapping("/myPage")
@SessionAttributes({"object1", "object2"})
@Controller
| MySessionAttributesController |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.java | {
"start": 1956,
"end": 2372
} | class ____ {
@com.google.errorprone.annotations.CheckReturnValue
public int f() {
return 0;
}
}
""")
.addSourceLines(
"TestCase.java",
"""
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.doReturn;
import org.mockito.Mockito;
| Test |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketExchangeReflectiveProcessorTests.java | {
"start": 1280,
"end": 2931
} | class ____ {
private final RSocketExchangeReflectiveProcessor processor = new RSocketExchangeReflectiveProcessor();
private final RuntimeHints hints = new RuntimeHints();
@Test
void shouldRegisterReflectionHintsForMethod() throws NoSuchMethodException {
Method method = SampleService.class.getDeclaredMethod("get", Request.class, Variable.class,
Metadata.class, MimeType.class);
processor.registerReflectionHints(hints.reflection(), method);
assertThat(reflection().onType(SampleService.class)).accepts(hints);
assertThat(reflection().onMethodInvocation(SampleService.class, "get")).accepts(hints);
assertThat(reflection().onType(Response.class)).accepts(hints);
assertThat(reflection().onMethodInvocation(Response.class, "getMessage")).accepts(hints);
assertThat(reflection().onMethodInvocation(Response.class, "setMessage")).accepts(hints);
assertThat(reflection().onType(Request.class)).accepts(hints);
assertThat(reflection().onMethodInvocation(Request.class, "getMessage")).accepts(hints);
assertThat(reflection().onMethodInvocation(Request.class, "setMessage")).accepts(hints);
assertThat(reflection().onType(Variable.class)).accepts(hints);
assertThat(reflection().onMethodInvocation(Variable.class, "getValue")).accepts(hints);
assertThat(reflection().onMethodInvocation(Variable.class, "setValue")).accepts(hints);
assertThat(reflection().onType(Metadata.class)).accepts(hints);
assertThat(reflection().onMethodInvocation(Metadata.class, "getValue")).accepts(hints);
assertThat(reflection().onMethodInvocation(Metadata.class, "setValue")).accepts(hints);
}
| RSocketExchangeReflectiveProcessorTests |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/WindowGroupReorderRule.java | {
"start": 7237,
"end": 8152
} | interface ____ extends RelRule.Config {
WindowGroupReorderRule.WindowGroupReorderRuleConfig DEFAULT =
ImmutableWindowGroupReorderRule.WindowGroupReorderRuleConfig.builder()
.build()
.withOperandSupplier(
b0 ->
b0.operand(LogicalWindow.class)
.inputs(
b1 ->
b1.operand(RelNode.class)
.anyInputs()))
.withDescription("ExchangeWindowGroupRule");
@Override
default WindowGroupReorderRule toRule() {
return new WindowGroupReorderRule(this);
}
}
}
| WindowGroupReorderRuleConfig |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/nestedbeans/mixed/FishTankMapperConstant.java | {
"start": 510,
"end": 1076
} | interface ____ {
FishTankMapperConstant INSTANCE = Mappers.getMapper( FishTankMapperConstant.class );
@Mappings({
@Mapping(target = "fish.kind", source = "fish.type"),
@Mapping(target = "fish.name", constant = "Nemo"),
@Mapping(target = "ornament", ignore = true ),
@Mapping(target = "material.materialType", source = "material"),
@Mapping(target = "material.manufacturer", constant = "MMM" ),
@Mapping(target = "quality", ignore = true)
})
FishTankDto map( FishTank source );
}
| FishTankMapperConstant |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/QueryToManyWithNestedToOneTest.java | {
"start": 3528,
"end": 3790
} | class ____ {
@Id
@GeneratedValue
private Long id;
@OneToMany( mappedBy = "parent" )
private Set<ValueEntity> values = new HashSet<>();
public Set<ValueEntity> getValues() {
return values;
}
}
@Entity( name = "ValueEntity" )
static | ParentEntity |
java | elastic__elasticsearch | modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/BulgarianAnalyzerProvider.java | {
"start": 885,
"end": 1469
} | class ____ extends AbstractIndexAnalyzerProvider<BulgarianAnalyzer> {
private final BulgarianAnalyzer analyzer;
BulgarianAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(name);
analyzer = new BulgarianAnalyzer(
Analysis.parseStopWords(env, settings, BulgarianAnalyzer.getDefaultStopSet()),
Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)
);
}
@Override
public BulgarianAnalyzer get() {
return this.analyzer;
}
}
| BulgarianAnalyzerProvider |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/namesuggestion/Garage.java | {
"start": 202,
"end": 388
} | class ____ {
private ColorRgb color;
public ColorRgb getColor() {
return color;
}
public void setColor(ColorRgb color) {
this.color = color;
}
}
| Garage |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java | {
"start": 2970,
"end": 3140
} | class ____ {
@Id
private Long id;
private String city;
private String stradă;
@ManyToOne
private Person personă;
}
@Entity(name = "Person")
public | Address |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/api/records/TestTaskReport.java | {
"start": 3980,
"end": 4586
} | class
____ report = Records.newRecord(TaskReport.class);
// Set raw counters
org.apache.hadoop.mapreduce.Counters rCounters = MockJobs.newCounters();
report.setRawCounters(rCounters);
// Verify getCounters converts properly from raw to real
Counters counters = report.getCounters();
assertNotEquals(null, counters);
// Clear counters to null and then verify
report.setCounters(null);
assertThat(report.getCounters()).isNull();
assertThat(report.getRawCounters()).isNull();
}
@Test
public void testSetNonNullRawCountersToNull() {
// Create basic | TaskReport |
java | spring-projects__spring-security | crypto/src/test/java/org/springframework/security/crypto/password/Pbkdf2PasswordEncoderTests.java | {
"start": 998,
"end": 9136
} | class ____ {
private Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder("secret", 8, 185000, 256);
private Pbkdf2PasswordEncoder encoderSalt16 = new Pbkdf2PasswordEncoder("", 16, 185000, 256);
private Pbkdf2PasswordEncoder[] encoders = new Pbkdf2PasswordEncoder[] { this.encoder, this.encoderSalt16 };
@Test
public void encodedLengthSuccess() {
// encode output is an hex coded String so with 2 chars per encoding result byte
// (ie. 1 char for 4 bits).
// The encoding result size is : (saltLength * 8) bits + hashWith bits.
assertThat(this.encoder.encode("password")).hasSize((8 * 8 + 256) / 4);
assertThat(this.encoderSalt16.encode("password")).hasSize((16 * 8 + 256) / 4);
}
@Test
public void matches() {
String result = this.encoder.encode("password");
assertThat(result.equals("password")).isFalse();
assertThat(this.encoder.matches("password", result)).isTrue();
}
@Test
public void matchesWhenCustomSaltLengthThenSuccess() {
String result = this.encoderSalt16.encode("password");
assertThat(result.equals("password")).isFalse();
assertThat(this.encoderSalt16.matches("password", result)).isTrue();
}
@Test
public void matchesLengthChecked() {
String result = this.encoder.encode("password");
assertThat(this.encoder.matches("password", result.substring(0, result.length() - 2))).isFalse();
}
@Test
public void matchesLengthCheckedWhenCustomSaltLengthThenSuccess() {
String result = this.encoderSalt16.encode("password");
assertThat(this.encoderSalt16.matches("password", result.substring(0, result.length() - 2))).isFalse();
}
@Test
public void notMatches() {
String result = this.encoder.encode("password");
assertThat(this.encoder.matches("bogus", result)).isFalse();
}
@Test
public void notMatchesWhenCustomSaltLengthThenSuccess() {
String result = this.encoderSalt16.encode("password");
assertThat(this.encoderSalt16.matches("bogus", result)).isFalse();
}
@Test
public void encodeSamePasswordMultipleTimesDiffers() {
String password = "password";
String encodeFirst = this.encoder.encode(password);
String encodeSecond = this.encoder.encode(password);
assertThat(encodeFirst).isNotEqualTo(encodeSecond);
}
@Test
public void encodeSamePasswordMultipleTimesWhenCustomSaltLengthThenDiffers() {
String password = "password";
String encodeFirst = this.encoderSalt16.encode(password);
String encodeSecond = this.encoderSalt16.encode(password);
assertThat(encodeFirst).isNotEqualTo(encodeSecond);
}
@Test
public void passivity() {
String encodedPassword = "ab1146a8458d4ce4e65789e5a3f60e423373cfa10b01abd23739e5ae2fdc37f8e9ede4ae6da65264";
String rawPassword = "password";
assertThat(this.encoder.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void passivityWhenCustomSaltLengthThenSuccess() {
String encodedPassword = "0123456789abcdef0123456789abcdef10d883c2a0e653c97175c4a2583a7f1fd3301b319a7657d95f75365ea7c04ce1";
String rawPassword = "password";
assertThat(this.encoderSalt16.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void migrate() {
final int saltLength = KeyGenerators.secureRandom().getKeyLength();
String encodedPassword = "ab1146a8458d4ce4e65789e5a3f60e423373cfa10b01abd23739e5ae2fdc37f8e9ede4ae6da65264";
String originalEncodedPassword = "ab1146a8458d4ce4ab1146a8458d4ce4e65789e5a3f60e423373cfa10b01abd23739e5ae2fdc37f8e9ede4ae6da65264";
byte[] originalBytes = Hex.decode(originalEncodedPassword);
byte[] fixedBytes = Arrays.copyOfRange(originalBytes, saltLength, originalBytes.length);
String fixedHex = String.valueOf(Hex.encode(fixedBytes));
assertThat(fixedHex).isEqualTo(encodedPassword);
}
@Test
public void encodeAndMatchWhenBase64ThenSuccess() {
this.encoder.setEncodeHashAsBase64(true);
String rawPassword = "password";
String encodedPassword = this.encoder.encode(rawPassword);
assertThat(this.encoder.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void encodeAndMatchWhenBase64AndCustomSaltLengthThenSuccess() {
this.encoderSalt16.setEncodeHashAsBase64(true);
String rawPassword = "password";
String encodedPassword = this.encoderSalt16.encode(rawPassword);
assertThat(this.encoderSalt16.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void encodeWhenBase64ThenBase64DecodeSuccess() {
assertThat(this.encoders).allSatisfy((pe) -> {
pe.setEncodeHashAsBase64(true);
String encodedPassword = pe.encode("password");
// validate can decode as Base64
assertThatNoException().isThrownBy(() -> java.util.Base64.getDecoder().decode(encodedPassword));
});
}
@Test
public void matchWhenBase64ThenSuccess() {
this.encoder.setEncodeHashAsBase64(true);
String rawPassword = "password";
String encodedPassword = "3FOwOMcDgxP+z1x/sv184LFY2WVD+ZGMgYP3LPOSmCcDmk1XPYvcCQ==";
assertThat(this.encoder.matches(rawPassword, encodedPassword)).isTrue();
java.util.Base64.getDecoder().decode(encodedPassword); // validate can decode as
// Base64
}
@Test
public void matchWhenBase64AndCustomSaltLengthThenSuccess() {
this.encoderSalt16.setEncodeHashAsBase64(true);
String rawPassword = "password";
String encodedPassword = "ASNFZ4mrze8BI0VniavN7xDYg8Kg5lPJcXXEolg6fx/TMBsxmnZX2V91Nl6nwEzh";
assertThat(this.encoderSalt16.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void encodeAndMatchWhenSha256ThenSuccess() {
this.encoder.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256);
String rawPassword = "password";
String encodedPassword = this.encoder.encode(rawPassword);
assertThat(this.encoder.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void encodeAndMatchWhenSha256AndCustomSaltLengthThenSuccess() {
this.encoderSalt16.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256);
String rawPassword = "password";
String encodedPassword = this.encoderSalt16.encode(rawPassword);
assertThat(this.encoderSalt16.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void matchWhenSha256ThenSuccess() {
this.encoder.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256);
String rawPassword = "password";
String encodedPassword = "821447f994e2b04c5014e31fa9fca4ae1cc9f2188c4ed53d3ddb5ba7980982b51a0ecebfc0b81a79";
assertThat(this.encoder.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void matchWhenSha256AndCustomSaltLengthThenSuccess() {
this.encoderSalt16.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256);
String rawPassword = "password";
String encodedPassword = "0123456789abcdef0123456789abcdefc7cfc96cd26b854d096ccbb3308fad860d719eb552ed52ef8352935539158287";
assertThat(this.encoderSalt16.matches(rawPassword, encodedPassword)).isTrue();
}
@Test
public void matchWhenDefaultsForSpringSecurity_v5_8ThenSuccess() {
Pbkdf2PasswordEncoder encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8();
String rawPassword = "password";
String encodedPassword = "fefe5120467e5d4ccff442dbb2fa86d276262d97435c0c54e5eebced51ffd144fcb05eb53fea2677216c4f3250010006";
assertThat(encoder.matches(rawPassword, encodedPassword)).isTrue();
}
/**
* Used to find the iteration count that takes .5 seconds.
*/
public void findDefaultIterationCount() {
// warm up
run(180000, 10);
// find the default
run(165000, 10);
}
private void run(int iterations, int count) {
long HALF_SECOND = 500L;
long avg = 0;
while (avg < HALF_SECOND) {
iterations += 10000;
Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder("", 8, iterations, 256);
String encoded = encoder.encode("password");
System.out.println("Trying " + iterations);
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
encoder.matches("password", encoded);
}
long end = System.currentTimeMillis();
long diff = end - start;
avg = diff / count;
System.out.println("Avgerage " + avg);
}
System.out.println("Iterations " + iterations);
}
}
| Pbkdf2PasswordEncoderTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/AssociationOverrideJpaAnnotation.java | {
"start": 686,
"end": 3110
} | class ____ implements AssociationOverride {
private String name;
private jakarta.persistence.JoinColumn[] joinColumns;
private jakarta.persistence.ForeignKey foreignKey;
private jakarta.persistence.JoinTable joinTable;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public AssociationOverrideJpaAnnotation(ModelsContext modelContext) {
this.joinColumns = new jakarta.persistence.JoinColumn[0];
this.foreignKey = JpaAnnotations.FOREIGN_KEY.createUsage( modelContext );
this.joinTable = JpaAnnotations.JOIN_TABLE.createUsage( modelContext );
}
/**
* Used in creating annotation instances from JDK variant
*/
public AssociationOverrideJpaAnnotation(AssociationOverride annotation, ModelsContext modelContext) {
this.name = annotation.name();
this.joinColumns = extractJdkValue( annotation, ASSOCIATION_OVERRIDE, "joinColumns", modelContext );
this.foreignKey = extractJdkValue( annotation, ASSOCIATION_OVERRIDE, "foreignKey", modelContext );
this.joinTable = extractJdkValue( annotation, ASSOCIATION_OVERRIDE, "joinTable", modelContext );
}
/**
* Used in creating annotation instances from Jandex variant
*/
public AssociationOverrideJpaAnnotation(
Map<String, Object> attributeValues,
ModelsContext modelContext) {
this.name = (String) attributeValues.get( "name" );
this.joinColumns = (jakarta.persistence.JoinColumn[]) attributeValues.get( "joinColumns" );
this.foreignKey = (jakarta.persistence.ForeignKey) attributeValues.get( "foreignKey" );
this.joinTable = (jakarta.persistence.JoinTable) attributeValues.get( "joinTable" );
}
@Override
public Class<? extends Annotation> annotationType() {
return AssociationOverride.class;
}
@Override
public String name() {
return name;
}
public void name(String value) {
this.name = value;
}
@Override
public jakarta.persistence.JoinColumn[] joinColumns() {
return joinColumns;
}
public void joinColumns(jakarta.persistence.JoinColumn[] value) {
this.joinColumns = value;
}
@Override
public jakarta.persistence.ForeignKey foreignKey() {
return foreignKey;
}
public void foreignKey(jakarta.persistence.ForeignKey value) {
this.foreignKey = value;
}
@Override
public jakarta.persistence.JoinTable joinTable() {
return joinTable;
}
public void joinTable(jakarta.persistence.JoinTable value) {
this.joinTable = value;
}
}
| AssociationOverrideJpaAnnotation |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentServiceTests.java | {
"start": 1127,
"end": 5999
} | class ____ {
private static final String REGISTERED_CLIENT_ID = "registered-client-id";
private static final String PRINCIPAL_NAME = "principal-name";
private static final OAuth2AuthorizationConsent AUTHORIZATION_CONSENT = OAuth2AuthorizationConsent
.withId(REGISTERED_CLIENT_ID, PRINCIPAL_NAME)
.authority(new SimpleGrantedAuthority("some.authority"))
.build();
private InMemoryOAuth2AuthorizationConsentService authorizationConsentService;
@BeforeEach
public void setUp() {
this.authorizationConsentService = new InMemoryOAuth2AuthorizationConsentService();
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
}
@Test
public void constructorVarargsWhenAuthorizationConsentNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryOAuth2AuthorizationConsentService((OAuth2AuthorizationConsent) null))
.withMessage("authorizationConsent cannot be null");
}
@Test
public void constructorListWhenAuthorizationConsentsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryOAuth2AuthorizationConsentService((List<OAuth2AuthorizationConsent>) null))
.withMessage("authorizationConsents cannot be null");
}
@Test
public void constructorWhenDuplicateAuthorizationConsentsThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(
() -> new InMemoryOAuth2AuthorizationConsentService(AUTHORIZATION_CONSENT, AUTHORIZATION_CONSENT))
.withMessage(
"The authorizationConsent must be unique. Found duplicate, with registered client id: [registered-client-id] and principal name: [principal-name]");
}
@Test
public void saveWhenAuthorizationConsentNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationConsentService.save(null))
.withMessage("authorizationConsent cannot be null");
}
@Test
public void saveWhenAuthorizationConsentNewThenSaved() {
OAuth2AuthorizationConsent expectedAuthorizationConsent = OAuth2AuthorizationConsent
.withId("new-client", "new-principal")
.authority(new SimpleGrantedAuthority("new.authority"))
.build();
this.authorizationConsentService.save(expectedAuthorizationConsent);
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById("new-client",
"new-principal");
assertThat(authorizationConsent).isEqualTo(expectedAuthorizationConsent);
}
@Test
public void saveWhenAuthorizationConsentExistsThenUpdated() {
OAuth2AuthorizationConsent expectedAuthorizationConsent = OAuth2AuthorizationConsent.from(AUTHORIZATION_CONSENT)
.authority(new SimpleGrantedAuthority("new.authority"))
.build();
this.authorizationConsentService.save(expectedAuthorizationConsent);
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
assertThat(authorizationConsent).isEqualTo(expectedAuthorizationConsent);
assertThat(authorizationConsent).isNotEqualTo(AUTHORIZATION_CONSENT);
}
@Test
public void removeWhenAuthorizationConsentNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationConsentService.remove(null))
.withMessage("authorizationConsent cannot be null");
}
@Test
public void removeWhenAuthorizationConsentProvidedThenRemoved() {
this.authorizationConsentService.remove(AUTHORIZATION_CONSENT);
assertThat(this.authorizationConsentService.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(),
AUTHORIZATION_CONSENT.getPrincipalName()))
.isNull();
}
@Test
public void findByIdWhenRegisteredClientIdNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizationConsentService.findById(null, "some-user"))
.withMessage("registeredClientId cannot be empty");
}
@Test
public void findByIdWhenPrincipalNameNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizationConsentService.findById("some-client", null))
.withMessage("principalName cannot be empty");
}
@Test
public void findByIdWhenAuthorizationConsentExistsThenFound() {
assertThat(this.authorizationConsentService.findById(REGISTERED_CLIENT_ID, PRINCIPAL_NAME))
.isEqualTo(AUTHORIZATION_CONSENT);
}
@Test
public void findByIdWhenAuthorizationConsentDoesNotExistThenNull() {
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
assertThat(this.authorizationConsentService.findById("unknown-client", PRINCIPAL_NAME)).isNull();
assertThat(this.authorizationConsentService.findById(REGISTERED_CLIENT_ID, "unknown-user")).isNull();
}
}
| InMemoryOAuth2AuthorizationConsentServiceTests |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/show/MySqlShowTest_users.java | {
"start": 929,
"end": 1771
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SHOW USERS";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
assertEquals(0, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertEquals(0, visitor.getOrderByColumns().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("mytable")));
assertEquals("SHOW USERS", stmt.toString());
}
}
| MySqlShowTest_users |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsDisabledByDefaultTest.java | {
"start": 3040,
"end": 3285
} | class ____ {
@Post("/refresh")
@Status(HttpStatus.OK)
void refresh() {
}
}
@Requires(property = "spec.name", value = SPECNAME)
@Replaces(HttpHostResolver.class)
@Singleton
static | RefreshController |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/TypeExtractorTest.java | {
"start": 79224,
"end": 80280
} | class ____<K, V> implements MapFunction<Edge<K, V>, Edge<K, V>> {
private static final long serialVersionUID = 1L;
@Override
public Edge<K, V> map(Edge<K, V> value) throws Exception {
return null;
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testInputInference1() {
EdgeMapper<String, Double> em = new EdgeMapper<String, Double>();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
(MapFunction) em,
TypeInformation.of(new TypeHint<Tuple3<String, String, Double>>() {}));
assertThat(ti.isTupleType()).isTrue();
assertThat(ti.getArity()).isEqualTo(3);
TupleTypeInfo<?> tti = (TupleTypeInfo<?>) ti;
assertThat(tti.getTypeAt(0)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO);
assertThat(tti.getTypeAt(1)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO);
assertThat(tti.getTypeAt(2)).isEqualTo(BasicTypeInfo.DOUBLE_TYPE_INFO);
}
public static | EdgeMapper |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/CronSchedule.java | {
"start": 980,
"end": 6241
} | class ____ {
private final CronExpression expression;
private final ZoneId zoneId;
CronSchedule(CronExpression expression, ZoneId zoneId) {
super();
this.expression = expression;
this.zoneId = zoneId;
}
/**
* Creates cron expression object with defined expression string
*
* @param expression of cron
* @return object
* @throws IllegalArgumentException
* wrapping a ParseException if the expression is invalid
*/
public static CronSchedule of(String expression) {
return of(expression, ZoneId.systemDefault());
}
/**
* Creates cron expression object with defined expression string and time-zone ID
*
* @param expression of cron
* @param zoneId id of zone
* @return object
* @throws IllegalArgumentException
* wrapping a ParseException if the expression is invalid
*/
public static CronSchedule of(String expression, ZoneId zoneId) {
CronExpression ce = new CronExpression(expression);
ce.setTimeZone(TimeZone.getTimeZone(zoneId));
return new CronSchedule(ce, zoneId);
}
/**
* Creates cron expression which schedule task execution
* every day at the given time
*
* @param hour of schedule
* @param minute of schedule
* @return object
* @throws IllegalArgumentException
* wrapping a ParseException if the expression is invalid
*/
public static CronSchedule dailyAtHourAndMinute(int hour, int minute) {
String expression = String.format("0 %d %d ? * *", minute, hour);
return of(expression);
}
/**
* Creates cron expression which schedule task execution
* every day at the given time in specified time-zone ID
*
* @param hour of schedule
* @param minute of schedule
* @param zoneId id of zone
* @return object
* @throws IllegalArgumentException
* wrapping a ParseException if the expression is invalid
*/
public static CronSchedule dailyAtHourAndMinute(int hour, int minute, ZoneId zoneId) {
String expression = String.format("0 %d %d ? * *", minute, hour);
return of(expression, zoneId);
}
/**
* Creates cron expression which schedule task execution
* every given days of the week at the given time.
* Use Calendar object constants to define day.
*
* @param hour of schedule
* @param minute of schedule
* @param daysOfWeek - Calendar object constants
* @return object
*/
public static CronSchedule weeklyOnDayAndHourAndMinute(int hour, int minute, Integer... daysOfWeek) {
if (daysOfWeek == null || daysOfWeek.length == 0) {
throw new IllegalArgumentException("You must specify at least one day of week.");
}
String expression = String.format("0 %d %d ? * %d", minute, hour, daysOfWeek[0]);
for (int i = 1; i < daysOfWeek.length; i++) {
expression = expression + "," + daysOfWeek[i];
}
return of(expression);
}
/**
* Creates cron expression which schedule task execution
* every given days of the week at the given time in specified time-zone ID.
* Use Calendar object constants to define day.
*
* @param hour of schedule
* @param minute of schedule
* @param zoneId id of zone
* @param daysOfWeek - Calendar object constants
* @return object
*/
public static CronSchedule weeklyOnDayAndHourAndMinute(int hour, int minute, ZoneId zoneId, Integer... daysOfWeek) {
if (daysOfWeek == null || daysOfWeek.length == 0) {
throw new IllegalArgumentException("You must specify at least one day of week.");
}
String expression = String.format("0 %d %d ? * %d", minute, hour, daysOfWeek[0]);
for (int i = 1; i < daysOfWeek.length; i++) {
expression = expression + "," + daysOfWeek[i];
}
return of(expression, zoneId);
}
/**
* Creates cron expression which schedule task execution
* every given day of the month at the given time
*
* @param hour of schedule
* @param minute of schedule
* @param dayOfMonth of schedule
* @return object
*/
public static CronSchedule monthlyOnDayAndHourAndMinute(int dayOfMonth, int hour, int minute) {
String expression = String.format("0 %d %d %d * ?", minute, hour, dayOfMonth);
return of(expression);
}
/**
* Creates cron expression which schedule task execution
* every given day of the month at the given time in specified time-zone ID.
*
* @param hour of schedule
* @param minute of schedule
* @param dayOfMonth of schedule
* @param zoneId id of zone
* @return object
*/
public static CronSchedule monthlyOnDayAndHourAndMinute(int dayOfMonth, int hour, int minute, ZoneId zoneId) {
String expression = String.format("0 %d %d %d * ?", minute, hour, dayOfMonth);
return of(expression, zoneId);
}
public CronExpression getExpression() {
return expression;
}
public ZoneId getZoneId() {
return zoneId;
}
}
| CronSchedule |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java | {
"start": 9805,
"end": 11842
} | class ____ extends ClassLoader {
private final Map<String, JavaFileObject> classes = new HashMap<>();
ClassLoaderImpl(final ClassLoader parentClassLoader) {
super(parentClassLoader);
}
Collection<JavaFileObject> files() {
return Collections.unmodifiableCollection(classes.values());
}
@Override
protected Class<?> findClass(final String qualifiedClassName) throws ClassNotFoundException {
JavaFileObject file = classes.get(qualifiedClassName);
if (file != null) {
byte[] bytes = ((JavaFileObjectImpl) file).getByteCode();
return defineClass(qualifiedClassName, bytes, 0, bytes.length);
}
try {
return org.apache.dubbo.common.utils.ClassUtils.forNameWithCallerClassLoader(
qualifiedClassName, getClass());
} catch (ClassNotFoundException nf) {
return super.findClass(qualifiedClassName);
}
}
void add(final String qualifiedClassName, final JavaFileObject javaFile) {
classes.put(qualifiedClassName, javaFile);
}
@Override
protected synchronized Class<?> loadClass(final String name, final boolean resolve)
throws ClassNotFoundException {
return super.loadClass(name, resolve);
}
@Override
public InputStream getResourceAsStream(final String name) {
if (name.endsWith(ClassUtils.CLASS_EXTENSION)) {
String qualifiedClassName = name.substring(0, name.length() - ClassUtils.CLASS_EXTENSION.length())
.replace('/', '.');
JavaFileObjectImpl file = (JavaFileObjectImpl) classes.get(qualifiedClassName);
if (file != null) {
return new ByteArrayInputStream(file.getByteCode());
}
}
return super.getResourceAsStream(name);
}
}
}
| ClassLoaderImpl |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/support/TestConstructorUtils.java | {
"start": 2492,
"end": 3372
} | class ____ an
* autowirable constructor.
* <p>This method delegates to {@link #isAutowirableConstructor(Executable, Class, PropertyProvider)}
* will a value of {@code null} for the fallback {@link PropertyProvider}.
* @param executable an executable for the test class
* @param testClass the test class
* @return {@code true} if the executable is an autowirable constructor
* @see #isAutowirableConstructor(Executable, PropertyProvider)
* @deprecated as of 6.2.13, in favor of {@link #isAutowirableConstructor(Executable, PropertyProvider)};
* to be removed in Spring Framework 7.1
*/
@Deprecated(since = "6.2.13", forRemoval = true)
public static boolean isAutowirableConstructor(Executable executable, Class<?> testClass) {
return isAutowirableConstructor(executable, testClass, null);
}
/**
* Determine if the supplied constructor for the given test | is |
java | mapstruct__mapstruct | core/src/main/java/org/mapstruct/InheritInverseConfiguration.java | {
"start": 1341,
"end": 1566
} | interface ____ {
* Human toHuman(HumanDto humanDto);
* @InheritInverseConfiguration
* HumanDto toHumanDto(Human human);
* }
* </code></pre>
* <pre><code class='java'>
* // generates
* public | HumanMapper |
java | apache__camel | core/camel-util/src/main/java/org/apache/camel/util/StopWatch.java | {
"start": 1009,
"end": 2347
} | class ____ {
private long start;
/**
* Starts the stop watch
*/
public StopWatch() {
this.start = System.nanoTime();
}
/**
* Creates the stop watch
*
* @param start whether it should start immediately
*/
public StopWatch(boolean start) {
if (start) {
this.start = System.nanoTime();
}
}
/**
* Starts or restarts the stop watch
*/
public void restart() {
start = System.nanoTime();
}
/**
* Whether the watch is started
*/
public boolean isStarted() {
return start > 0;
}
/**
* Returns the time taken in millis.
*
* @return time in millis, or <tt>0</tt> if not started yet.
*/
public long taken() {
if (start > 0) {
long delta = System.nanoTime() - start;
return Duration.ofNanos(delta).toMillis();
}
return 0;
}
/**
* Returns the time taken in millis and restarts the timer.
*
* @return time in millis, or <tt>0</tt> if not started yet.
*/
public long takenAndRestart() {
long answer = taken();
start = System.nanoTime();
return answer;
}
/**
* Stops the stop watch
*/
public void stop() {
start = 0;
}
}
| StopWatch |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java | {
"start": 33346,
"end": 33621
} | class ____ {
private @Nullable Class<? extends Throwable> value;
@Nullable Class<? extends Throwable> getValue() {
return this.value;
}
void setValue(@Nullable Class<? extends Throwable> value) {
this.value = value;
}
}
static | ExampleWithPropertyEditorType |
java | spring-projects__spring-framework | spring-web/src/testFixtures/java/org/springframework/web/testfixture/method/MvcAnnotationPredicates.java | {
"start": 7152,
"end": 7889
} | class ____ implements Predicate<MethodParameter> {
private String name;
private boolean required = true;
public RequestAttributePredicate name(String name) {
this.name = name;
return this;
}
public RequestAttributePredicate noName() {
this.name = "";
return this;
}
public RequestAttributePredicate notRequired() {
this.required = false;
return this;
}
@Override
public boolean test(MethodParameter parameter) {
RequestAttribute annotation = parameter.getParameterAnnotation(RequestAttribute.class);
return annotation != null &&
(this.name == null || annotation.name().equals(this.name)) &&
annotation.required() == this.required;
}
}
public static | RequestAttributePredicate |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2185/TodoMapper.java | {
"start": 476,
"end": 698
} | class ____ {
private final String note;
public TodoResponse(String note) {
this.note = note;
}
public String getNote() {
return note;
}
}
| TodoResponse |
java | quarkusio__quarkus | independent-projects/arc/runtime/src/main/java/io/quarkus/arc/InjectableReferenceProvider.java | {
"start": 142,
"end": 333
} | interface ____<T> {
/**
*
* @param creationalContext
* @return a contextual reference
*/
T get(CreationalContext<T> creationalContext);
}
| InjectableReferenceProvider |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/deployment/TaskDeploymentDescriptorFactory.java | {
"start": 24100,
"end": 26594
} | class ____ implements ShuffleDescriptorSerializer {
private final JobID jobID;
private final BlobWriter blobWriter;
private final int offloadShuffleDescriptorsThreshold;
public DefaultShuffleDescriptorSerializer(
JobID jobID, BlobWriter blobWriter, int offloadShuffleDescriptorsThreshold) {
this.jobID = checkNotNull(jobID);
this.blobWriter = checkNotNull(blobWriter);
this.offloadShuffleDescriptorsThreshold = offloadShuffleDescriptorsThreshold;
}
@Override
public MaybeOffloaded<ShuffleDescriptorGroup> serializeAndTryOffloadShuffleDescriptor(
ShuffleDescriptorGroup shuffleDescriptorGroup, int numConsumer) throws IOException {
final CompressedSerializedValue<ShuffleDescriptorGroup> compressedSerializedValue =
CompressedSerializedValue.fromObject(shuffleDescriptorGroup);
final Either<SerializedValue<ShuffleDescriptorGroup>, PermanentBlobKey>
serializedValueOrBlobKey =
shouldOffload(
shuffleDescriptorGroup.getShuffleDescriptors(),
numConsumer)
? BlobWriter.offloadWithException(
compressedSerializedValue, jobID, blobWriter)
: Either.Left(compressedSerializedValue);
if (serializedValueOrBlobKey.isLeft()) {
return new TaskDeploymentDescriptor.NonOffloaded<>(serializedValueOrBlobKey.left());
} else {
return new TaskDeploymentDescriptor.Offloaded<>(serializedValueOrBlobKey.right());
}
}
/**
* Determine whether shuffle descriptors should be offloaded to blob server.
*
* @param shuffleDescriptorsToSerialize shuffle descriptors to serialize
* @param numConsumers how many consumers this serialized shuffle descriptor should be sent
* @return whether shuffle descriptors should be offloaded to blob server
*/
private boolean shouldOffload(
ShuffleDescriptorAndIndex[] shuffleDescriptorsToSerialize, int numConsumers) {
return shuffleDescriptorsToSerialize.length * numConsumers
>= offloadShuffleDescriptorsThreshold;
}
}
}
| DefaultShuffleDescriptorSerializer |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/slm/action/GetSnapshotLifecycleAction.java | {
"start": 2561,
"end": 4182
} | class ____ extends ActionResponse implements ToXContentObject {
private List<SnapshotLifecyclePolicyItem> lifecycles;
public Response() {}
public Response(List<SnapshotLifecyclePolicyItem> lifecycles) {
this.lifecycles = lifecycles;
}
public Response(StreamInput in) throws IOException {
this.lifecycles = in.readCollectionAsList(SnapshotLifecyclePolicyItem::new);
}
public List<SnapshotLifecyclePolicyItem> getPolicies() {
return this.lifecycles;
}
@Override
public String toString() {
return Strings.toString(this);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
for (SnapshotLifecyclePolicyItem item : lifecycles) {
item.toXContent(builder, params);
}
builder.endObject();
return builder;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeCollection(lifecycles);
}
@Override
public int hashCode() {
return Objects.hash(lifecycles);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
Response other = (Response) obj;
return lifecycles.equals(other.lifecycles);
}
}
}
| Response |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/TreatPathTest.java | {
"start": 5481,
"end": 5905
} | class ____ {
private String embeddedProperty;
public EmbeddableType() {
}
public EmbeddableType(String embeddedProperty) {
this.embeddedProperty = embeddedProperty;
}
public String getEmbeddedProperty() {
return embeddedProperty;
}
public void setEmbeddedProperty(String embeddedProperty) {
this.embeddedProperty = embeddedProperty;
}
}
@Entity(name = "LocalTerm")
public static | EmbeddableType |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/scheduler/OpportunisticContainerAllocator.java | {
"start": 6043,
"end": 6581
} | class ____ {
private List<ResourceRequest> guaranteed = new ArrayList<>();
private List<ResourceRequest> opportunistic = new ArrayList<>();
public List<ResourceRequest> getGuaranteed() {
return guaranteed;
}
public List<ResourceRequest> getOpportunistic() {
return opportunistic;
}
}
private static final ResourceCalculator RESOURCE_CALCULATOR =
new DominantResourceCalculator();
private final BaseContainerTokenSecretManager tokenSecretManager;
/**
* This | PartitionedResourceRequests |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerArgumentFreedOnErrorTest.java | {
"start": 2617,
"end": 3178
} | class ____ implements Message, StringBuilderFormattable {
private ThrowingMessage() {}
@Override
public String getFormattedMessage() {
throw new Error("Expected");
}
@Override
public Object[] getParameters() {
return new Object[0];
}
@Override
public Throwable getThrowable() {
return null;
}
@Override
public void formatTo(final StringBuilder buffer) {
throw new Error("Expected");
}
}
}
| ThrowingMessage |
java | spring-projects__spring-boot | module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/observation/GraphQlObservationAutoConfigurationTests.java | {
"start": 4642,
"end": 4777
} | class ____ {
@Bean
WebGraphQlHandler webGraphQlHandler() {
return mock(WebGraphQlHandler.class);
}
}
}
| WebGraphQlConfiguration |
java | apache__flink | flink-architecture-tests/flink-architecture-tests-test/src/main/java/org/apache/flink/architecture/TestCodeArchitectureTestBase.java | {
"start": 1292,
"end": 1418
} | class ____ {
@ArchTest public static final ArchTests ITCASE = ArchTests.in(ITCaseRules.class);
}
| TestCodeArchitectureTestBase |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnicodeInCodeTest.java | {
"start": 2487,
"end": 2726
} | class ____ {
static final char pi = '\u03c0';
}
""")
.doTest();
}
@Test
public void positive() {
helper
.addSourceLines(
"Test.java",
"""
| Test |
java | apache__flink | flink-table/flink-table-code-splitter/src/test/resources/declaration/code/TestRewriteLocalVariableInForLoop1.java | {
"start": 7,
"end": 210
} | class ____ {
public void myFun() {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
System.out.println(sum);
}
}
| TestRewriteLocalVariableInForLoop1 |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/annotation/Commit.java | {
"start": 2103,
"end": 2515
} | class ____ default. See
* {@link org.springframework.test.context.NestedTestConfiguration @NestedTestConfiguration}
* for details.
*
* @author Sam Brannen
* @since 4.2
* @see Rollback
* @see org.springframework.test.context.transaction.TransactionalTestExecutionListener
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Rollback(false)
public @ | by |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/NestedCheckedException.java | {
"start": 1209,
"end": 2698
} | class ____ extends Exception {
/** Use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID = 7100714597678207546L;
/**
* Construct a {@code NestedCheckedException} with the specified detail message.
* @param msg the detail message
*/
public NestedCheckedException(String msg) {
super(msg);
}
/**
* Construct a {@code NestedCheckedException} with the specified detail message
* and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public NestedCheckedException(@Nullable String msg, @Nullable Throwable cause) {
super(msg, cause);
}
/**
* Retrieve the innermost cause of this exception, if any.
* @return the innermost exception, or {@code null} if none
*/
public @Nullable Throwable getRootCause() {
return NestedExceptionUtils.getRootCause(this);
}
/**
* Retrieve the most specific cause of this exception, that is,
* either the innermost cause (root cause) or this exception itself.
* <p>Differs from {@link #getRootCause()} in that it falls back
* to the present exception if there is no root cause.
* @return the most specific cause (never {@code null})
* @since 2.0.3
*/
public Throwable getMostSpecificCause() {
Throwable rootCause = getRootCause();
return (rootCause != null ? rootCause : this);
}
/**
* Check whether this exception contains an exception of the given type:
* either it is of the given | NestedCheckedException |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Y.java | {
"start": 143,
"end": 720
} | class ____ {
private Long id;
private String x;
private X theX;
/**
* Returns the id.
* @return Long
*/
public Long getId() {
return id;
}
/**
* Returns the x.
* @return String
*/
public String getX() {
return x;
}
/**
* Sets the id.
* @param id The id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* Sets the x.
* @param x The x to set
*/
public void setX(String x) {
this.x = x;
}
/**
* @return
*/
public X getTheX() {
return theX;
}
/**
* @param x
*/
public void setTheX(X x) {
theX = x;
}
}
| Y |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/TestLocalPhysicalPlanOptimizer.java | {
"start": 399,
"end": 898
} | class ____ extends LocalPhysicalPlanOptimizer {
private final boolean esRules;
public TestLocalPhysicalPlanOptimizer(LocalPhysicalOptimizerContext context) {
this(context, false);
}
public TestLocalPhysicalPlanOptimizer(LocalPhysicalOptimizerContext context, boolean esRules) {
super(context);
this.esRules = esRules;
}
@Override
protected List<Batch<PhysicalPlan>> batches() {
return rules(esRules);
}
}
| TestLocalPhysicalPlanOptimizer |
java | spring-projects__spring-boot | module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/CompressionConnectorCustomizer.java | {
"start": 1117,
"end": 2497
} | class ____ implements TomcatConnectorCustomizer {
private final @Nullable Compression compression;
public CompressionConnectorCustomizer(@Nullable Compression compression) {
this.compression = compression;
}
@Override
public void customize(Connector connector) {
if (this.compression != null && this.compression.getEnabled()) {
ProtocolHandler handler = connector.getProtocolHandler();
if (handler instanceof AbstractHttp11Protocol<?> abstractHttp11Protocol) {
customize(abstractHttp11Protocol, this.compression);
}
}
}
private void customize(AbstractHttp11Protocol<?> protocol, Compression compression) {
protocol.setCompression("on");
protocol.setCompressionMinSize(getMinResponseSize(compression));
protocol.setCompressibleMimeType(getMimeTypes(compression));
if (compression.getExcludedUserAgents() != null) {
protocol.setNoCompressionUserAgents(getExcludedUserAgents(compression));
}
}
private int getMinResponseSize(Compression compression) {
return (int) compression.getMinResponseSize().toBytes();
}
private String getMimeTypes(Compression compression) {
return StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes());
}
private String getExcludedUserAgents(Compression compression) {
return StringUtils.arrayToCommaDelimitedString(compression.getExcludedUserAgents());
}
}
| CompressionConnectorCustomizer |
java | quarkusio__quarkus | integration-tests/maven/src/test/resources-filtered/projects/test-template/src/test/java/com/acme/UserIdGeneratorTestInvocationContextProvider.java | {
"start": 613,
"end": 2821
} | class ____ implements TestTemplateInvocationContextProvider {
@Override
public boolean supportsTestTemplate(ExtensionContext extensionContext) {
return true;
}
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext extensionContext) {
return Stream.of(
genericContext(new UserIdGeneratorTestCase()),
genericContext(new UserIdGeneratorTestCase()));
}
private TestTemplateInvocationContext genericContext(
UserIdGeneratorTestCase userIdGeneratorTestCase) {
return new TestTemplateInvocationContext() {
@Override
public String getDisplayName(int invocationIndex) {
return userIdGeneratorTestCase.getDisplayName();
}
@Override
public List<Extension> getAdditionalExtensions() {
return Arrays.asList(parameterResolver(), preProcessor(), postProcessor());
}
private BeforeTestExecutionCallback preProcessor() {
return context -> System.out.println("Pre-process parameter: " + userIdGeneratorTestCase.getDisplayName());
}
private AfterTestExecutionCallback postProcessor() {
return context -> System.out.println("Post-process parameter: " + userIdGeneratorTestCase.getDisplayName());
}
private ParameterResolver parameterResolver() {
return new ParameterResolver() {
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return parameterContext.getParameter()
.getType()
.equals(UserIdGeneratorTestCase.class);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return userIdGeneratorTestCase;
}
};
}
};
}
}
| UserIdGeneratorTestInvocationContextProvider |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/appender/FailOnceAppender.java | {
"start": 4684,
"end": 5121
} | enum ____ {
;
public static final String RUNTIME_EXCEPTION = "RuntimeException";
public static final String LOGGING_EXCEPTION = "LoggingException";
public static final String EXCEPTION = "Exception";
public static final String ERROR = "Error";
public static final String THROWABLE = "Throwable";
public static final String THREAD_DEATH = "ThreadDeath";
}
}
| ThrowableClassName |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beancreationeventlistener/I.java | {
"start": 715,
"end": 760
} | class ____ {
public I(J someParamName) {}
}
| I |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/PreprocessedQuery.java | {
"start": 17410,
"end": 20401
} | class ____ {
private final MultiValueMap<BindingIdentifier, ParameterBinding> methodArgumentToLikeBindings = new LinkedMultiValueMap<>();
private final Consumer<ParameterBinding> registration;
public ParameterBindings(List<ParameterBinding> bindings, Consumer<ParameterBinding> registration) {
for (ParameterBinding binding : bindings) {
this.methodArgumentToLikeBindings.put(binding.getIdentifier(), new ArrayList<>(List.of(binding)));
}
this.registration = registration;
}
/**
* @param identifier
* @return whether the identifier is already bound.
*/
public boolean isBound(ParameterBinding.BindingIdentifier identifier) {
return !getBindings(identifier).isEmpty();
}
ParameterBinding.BindingIdentifier register(ParameterBinding.BindingIdentifier identifier,
ParameterBinding.ParameterOrigin origin,
Function<ParameterBinding.BindingIdentifier, ParameterBinding> bindingFactory,
IndexedParameterLabels parameterLabels) {
Assert.isInstanceOf(ParameterBinding.MethodInvocationArgument.class, origin);
ParameterBinding.BindingIdentifier methodArgument = ((ParameterBinding.MethodInvocationArgument) origin)
.identifier();
List<ParameterBinding> bindingsForOrigin = getBindings(methodArgument);
if (!isBound(identifier)) {
ParameterBinding binding = bindingFactory.apply(identifier);
registration.accept(binding);
bindingsForOrigin.add(binding);
return binding.getIdentifier();
}
ParameterBinding binding = bindingFactory.apply(identifier);
for (ParameterBinding existing : bindingsForOrigin) {
if (existing.isCompatibleWith(binding)) {
return existing.getIdentifier();
}
}
ParameterBinding.BindingIdentifier syntheticIdentifier;
if (identifier.hasName() && methodArgument.hasName()) {
int index = 0;
String newName = methodArgument.getName();
while (existsBoundParameter(newName)) {
index++;
newName = methodArgument.getName() + "_" + index;
}
syntheticIdentifier = ParameterBinding.BindingIdentifier.of(newName);
}
else {
syntheticIdentifier = ParameterBinding.BindingIdentifier.of(parameterLabels.allocate());
}
ParameterBinding newBinding = bindingFactory.apply(syntheticIdentifier);
registration.accept(newBinding);
bindingsForOrigin.add(newBinding);
return newBinding.getIdentifier();
}
private boolean existsBoundParameter(String key) {
return methodArgumentToLikeBindings.values().stream()
.flatMap(Collection::stream)
.anyMatch(it -> key.equals(it.getName()));
}
private List<ParameterBinding> getBindings(ParameterBinding.BindingIdentifier identifier) {
return methodArgumentToLikeBindings.computeIfAbsent(identifier, s -> new ArrayList<>());
}
public void register(ParameterBinding parameterBinding) {
registration.accept(parameterBinding);
}
}
/**
* Value object to track and allocate used parameter index labels in a query.
*/
static | ParameterBindings |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java | {
"start": 57316,
"end": 57970
} | class ____ extends SubjectInheritingThread {
VerifyActiveStatusThread() {
super(VerifyActiveStatusThread.class.getName());
}
@Override
public void work() {
try {
while (!isFencedState()) {
// Create and delete fencing node
zkManager.createTransaction(zkAcl, fencingNodePath).commit();
Thread.sleep(zkSessionTimeout);
}
} catch (InterruptedException ie) {
LOG.info(getName() + " thread interrupted! Exiting!");
interrupt();
} catch (Exception e) {
notifyStoreOperationFailed(new StoreFencedException());
}
}
}
}
| VerifyActiveStatusThread |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/predicates/IsTestFactoryMethodTests.java | {
"start": 4024,
"end": 5716
} | class ____ {
@TestFactory
Collection<DynamicTest> dynamicTestsFactoryFromCollection() {
return new ArrayList<>();
}
@TestFactory
Stream<? extends DynamicTest> dynamicTestsFactoryFromStreamWithExtendsWildcard() {
return Stream.empty();
}
@TestFactory
DynamicTest dynamicTestsFactoryFromNode() {
return dynamicTest("foo", Assertions::fail);
}
@TestFactory
DynamicTest dynamicTestsFactoryFromTest() {
return dynamicTest("foo", Assertions::fail);
}
@TestFactory
DynamicNode dynamicTestsFactoryFromContainer() {
return dynamicContainer("foo", Stream.empty());
}
@TestFactory
DynamicNode[] dynamicTestsFactoryFromNodeArray() {
return new DynamicNode[0];
}
@TestFactory
DynamicTest[] dynamicTestsFactoryFromTestArray() {
return new DynamicTest[0];
}
@TestFactory
DynamicContainer[] dynamicTestsFactoryFromContainerArray() {
return new DynamicContainer[0];
}
@TestFactory
void bogusVoidFactory() {
}
@TestFactory
Collection<String> bogusStringsFactory() {
return new ArrayList<>();
}
@TestFactory
String[] bogusStringArrayFactory() {
return new String[0];
}
@TestFactory
Stream<? super DynamicTest> dynamicTestsFactoryFromStreamWithSuperWildcard() {
return Stream.empty();
}
@TestFactory
Object objectFactory() {
return dynamicTest("foo", Assertions::fail);
}
@TestFactory
Object[] objectArrayFactory() {
return new DynamicNode[0];
}
@SuppressWarnings("rawtypes")
@TestFactory
Collection rawCollectionFactory() {
return new ArrayList<>();
}
@TestFactory
Stream<?> unboundStreamFactory() {
return Stream.of();
}
}
}
| ClassWithTestFactoryMethods |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/spi/ExtendedLogger.java | {
"start": 13111,
"end": 13583
} | 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 params The message parameters.
*/
void logIfEnabled(String fqcn, Level level, Marker marker, String message, Object... params);
/**
* Logs a message if the specified level is active.
*
* @param fqcn The fully qualified | and |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/IndexWarmer.java | {
"start": 3680,
"end": 3981
} | interface ____ {
/** Queue tasks to warm-up the given segments and return handles that allow to wait for termination of the
* execution of those tasks. */
TerminationHandle warmReader(IndexShard indexShard, ElasticsearchDirectoryReader reader);
}
private static | Listener |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/util/ExecUtil.java | {
"start": 1095,
"end": 11173
} | class ____ implements Runnable {
private final InputStream is;
private final Optional<Logger.Level> logLevel;
private final Logger logger;
public HandleOutput(InputStream is) {
this(is, null);
}
public HandleOutput(InputStream is, Logger.Level logLevel) {
this(is, logLevel, LOG);
}
public HandleOutput(InputStream is, Logger.Level logLevel, Logger logger) {
this.is = is;
this.logLevel = Optional.ofNullable(logLevel);
this.logger = logger;
}
@Override
public void run() {
try (InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr)) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
final String l = line;
logLevel.ifPresentOrElse(level -> logger.log(level, l), () -> System.out.println(l));
}
} catch (IOException e) {
logLevel.ifPresentOrElse(level -> logger.log(level, "Failed to handle output", e), () -> e.printStackTrace());
}
}
}
/**
* Execute the specified command from within the current directory.
*
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean exec(String command, String... args) {
return exec(new File("."), command, args);
}
/**
* Execute the specified command until the given timeout from within the current directory.
*
* @param timeout The timeout
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithTimeout(Duration timeout, String command, String... args) {
return execWithTimeout(new File("."), timeout, command, args);
}
/**
* Execute the specified command from within the specified directory.
*
* @param directory The directory
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean exec(File directory, String command, String... args) {
return exec(directory, DEFAULT_LOGGING, command, args);
}
/**
* Execute the specified command until the given timeout from within the specified directory.
*
* @param directory The directory
* @param timeout The timeout
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithTimeout(File directory, Duration timeout, String command, String... args) {
return execWithTimeout(directory, DEFAULT_LOGGING, timeout, command, args);
}
/**
* Execute the specified command from within the specified directory.
* The method allows specifying an output filter that processes the command output.
*
* @param directory The directory
* @param outputFilterFunction A {@link Function} that gets an {@link InputStream} and returns an outputFilter.
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean exec(File directory, Function<InputStream, Runnable> outputFilterFunction, String command,
String... args) {
return execProcess(startProcess(directory, command, args), outputFilterFunction) == 0;
}
public static int execProcess(Process process, Function<InputStream, Runnable> outputFilterFunction) {
try {
Function<InputStream, Runnable> loggingFunction = outputFilterFunction != null ? outputFilterFunction
: DEFAULT_LOGGING;
Thread t = new Thread(loggingFunction.apply(process.getInputStream()));
t.setName("Process stdout");
t.setDaemon(true);
t.start();
process.waitFor();
return process.exitValue();
} catch (InterruptedException e) {
return -1;
} finally {
destroyProcess(process);
}
}
public static int execProcessWithTimeout(Process process, Function<InputStream, Runnable> outputFilterFunction,
Duration timeout) {
try {
Function<InputStream, Runnable> loggingFunction = outputFilterFunction != null ? outputFilterFunction
: DEFAULT_LOGGING;
Thread t = new Thread(loggingFunction.apply(process.getInputStream()));
t.setName("Process stdout");
t.setDaemon(true);
t.start();
process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS);
return process.exitValue();
} catch (InterruptedException e) {
return -1;
} finally {
destroyProcess(process);
}
}
/**
* Execute the specified command until the given timeout from within the specified directory.
* The method allows specifying an output filter that processes the command output.
*
* @param directory The directory
* @param outputFilterFunction A {@link Function} that gets an {@link InputStream} and returns an outputFilter.
* @param timeout The timeout
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithTimeout(File directory, Function<InputStream, Runnable> outputFilterFunction,
Duration timeout, String command, String... args) {
return execProcessWithTimeout(startProcess(directory, command, args), outputFilterFunction, timeout) == 0;
}
/**
* Execute the specified command from within the current directory using debug logging.
*
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithDebugLogging(String command, String... args) {
return execWithDebugLogging(new File("."), command, args);
}
/**
* Execute the specified command from within the specified directory using debug logging.
*
* @param directory The directory
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithDebugLogging(File directory, String command, String... args) {
return exec(directory, DEBUG_LOGGING, command, args);
}
/**
* Execute the specified command from within the current directory using system logging.
*
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithSystemLogging(String command, String... args) {
return execWithSystemLogging(new File("."), command, args);
}
/**
* Execute the specified command from within the specified directory using system logging.
*
* @param directory The directory
* @param command The command
* @param args The command arguments
* @return true if commands where executed successfully
*/
public static boolean execWithSystemLogging(File directory, String command, String... args) {
return exec(directory, SYSTEM_LOGGING, command, args);
}
/**
* Start a process executing given command with arguments within the specified directory.
*
* @param directory The directory
* @param command The command and args
* @param environment The command environment
* @return the process
*/
public static Process startProcess(File directory, Map<String, String> environment, String command, String... args) {
try {
String[] cmd = new String[args.length + 1];
cmd[0] = command;
if (args.length > 0) {
System.arraycopy(args, 0, cmd, 1, args.length);
}
ProcessBuilder processBuilder = new ProcessBuilder()
.directory(directory)
.command(cmd)
.redirectErrorStream(true);
if (environment != null && !environment.isEmpty()) {
Map<String, String> env = processBuilder.environment();
environment.forEach((key, value) -> {
if (value == null) {
env.remove(key);
} else {
env.put(key, value);
}
});
}
return processBuilder.start();
} catch (IOException e) {
throw new RuntimeException("Input/Output error while executing command.", e);
}
}
/**
* Start a process executing given command with arguments within the specified directory.
*
* @param directory The directory
* @param command The command
* @param args The command arguments
* @return the process
*/
public static Process startProcess(File directory, String command, String... args) {
return startProcess(directory, Collections.emptyMap(), command, args);
}
/**
* Kill the process, if still alive, kill it forcibly
*
* @param process the process to kill
*/
public static void destroyProcess(Process process) {
process.destroy();
int i = 0;
while (process.isAlive() && i++ < 10) {
try {
process.waitFor(PROCESS_CHECK_INTERVAL, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
if (process.isAlive()) {
process.destroyForcibly();
}
}
}
| HandleOutput |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/persister/internal/StandardPersisterClassResolver.java | {
"start": 1425,
"end": 2802
} | class ____ children, we need to find of which kind
model = model.getDirectSubclasses().get(0);
}
else {
return singleTableEntityPersister();
}
}
if ( model instanceof JoinedSubclass ) {
return joinedSubclassEntityPersister();
}
else if ( model instanceof UnionSubclass ) {
return unionSubclassEntityPersister();
}
else if ( model instanceof SingleTableSubclass ) {
return singleTableEntityPersister();
}
else {
throw new UnknownPersisterException(
"Could not determine persister implementation for entity [" + model.getEntityName() + "]"
);
}
}
public Class<? extends EntityPersister> singleTableEntityPersister() {
return SingleTableEntityPersister.class;
}
public Class<? extends EntityPersister> joinedSubclassEntityPersister() {
return JoinedSubclassEntityPersister.class;
}
public Class<? extends EntityPersister> unionSubclassEntityPersister() {
return UnionSubclassEntityPersister.class;
}
@Override
public Class<? extends CollectionPersister> getCollectionPersisterClass(Collection metadata) {
return metadata.isOneToMany() ? oneToManyPersister() : basicCollectionPersister();
}
private Class<OneToManyPersister> oneToManyPersister() {
return OneToManyPersister.class;
}
private Class<BasicCollectionPersister> basicCollectionPersister() {
return BasicCollectionPersister.class;
}
}
| has |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/streaming/experimental/CollectITCase.java | {
"start": 1368,
"end": 1994
} | class ____ extends AbstractTestBaseJUnit4 {
@Test
public void testCollect() throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
final long n = 10;
DataStream<Long> stream = env.fromSequence(1, n);
long i = 1;
for (Iterator<Long> it = stream.executeAndCollect(); it.hasNext(); ) {
long x = it.next();
assertEquals("received wrong element", i, x);
i++;
}
assertEquals("received wrong number of elements", n + 1, i);
}
}
| CollectITCase |
java | google__guice | core/src/com/google/inject/internal/aop/Enhancer.java | {
"start": 3886,
"end": 4967
} | class ____$$EnhancerByGuice
* extends HostClass
* {
* // InterceptorStackCallbacks, one per enhanced method
* private final InvocationHandler[] GUICE$HANDLERS;
*
* public HostClass$$EnhancerByGuice(InvocationHandler[] handlers, ...) {
* // JVM lets us store this before calling the superclass constructor
* GUICE$HANDLERS = handlers;
* super(...);
* }
*
* public static Object GUICE$TRAMPOLINE(int index, Object context, Object[] args) {
* switch (index) {
* case 0: {
* return new HostClass$$EnhancerByGuice((InvocationHandler[]) context, ...);
* }
* case 1: {
* return context.super.instanceMethod(...); // call original unenhanced method
* }
* }
* return null;
* }
*
* // enhanced method
* public final Object instanceMethod(...) {
* // pack arguments and trigger the associated InterceptorStackCallback
* return GUICE$HANDLERS[0].invoke(this, null, args);
* }
*
* // ...
* }
* </pre>
*
* @author mcculls@gmail.com (Stuart McCulloch)
*/
final | HostClass |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/SetGenerators.java | {
"start": 15344,
"end": 16131
} | class ____
extends TestIntegerSortedSetGenerator {
static final ContiguousSet<Integer> checkedCreate(SortedSet<Integer> elementsSet) {
List<Integer> elements = new ArrayList<>(elementsSet);
/*
* A ContiguousSet can't have holes. If a test demands a hole, it should be changed so that it
* doesn't need one, or it should be suppressed for ContiguousSet.
*/
for (int i = 0; i < elements.size() - 1; i++) {
assertEquals(elements.get(i) + 1, (int) elements.get(i + 1));
}
Range<Integer> range =
elements.isEmpty() ? Range.closedOpen(0, 0) : Range.encloseAll(elements);
return ContiguousSet.create(range, DiscreteDomain.integers());
}
}
/**
* Useless constructor for a | AbstractContiguousSetGenerator |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/configproperties/eachbeaninterceptor/MyBean.java | {
"start": 283,
"end": 914
} | class ____ {
private final Connection defaultConnection, fooConnection, barConnection;
MyBean(@Named("default") Connection defaultConnection, @Named("foo") Connection fooConnection, @Named("bar") Connection barConnection) {
this.defaultConnection = defaultConnection;
this.fooConnection = fooConnection;
this.barConnection = barConnection;
}
public Connection getDefaultConnection() {
return defaultConnection;
}
public Connection getFooConnection() {
return fooConnection;
}
public Connection getBarConnection() {
return barConnection;
}
}
| MyBean |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/concurrent/ExplicitDelegatingSecurityContextScheduledExecutorServiceTests.java | {
"start": 964,
"end": 1395
} | class ____
extends AbstractDelegatingSecurityContextScheduledExecutorServiceTests {
@BeforeEach
public void setUp() throws Exception {
this.explicitSecurityContextSetup();
}
@Override
protected DelegatingSecurityContextScheduledExecutorService create() {
return new DelegatingSecurityContextScheduledExecutorService(this.delegate, this.securityContext);
}
}
| ExplicitDelegatingSecurityContextScheduledExecutorServiceTests |
java | elastic__elasticsearch | build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/HiddenFieldCheck.java | {
"start": 23146,
"end": 25028
} | class ____ enum).
* @param frameName name associated with the frame, which can be a
*/
/* package */ FieldFrame(FieldFrame parent, boolean staticType, String frameName) {
this.parent = parent;
this.staticType = staticType;
this.frameName = frameName;
}
/**
* Adds an instance field to this FieldFrame.
*
* @param field the name of the instance field.
*/
public void addInstanceField(String field) {
instanceFields.add(field);
}
/**
* Adds a static field to this FieldFrame.
*
* @param field the name of the instance field.
*/
public void addStaticField(String field) {
staticFields.add(field);
}
/**
* Determines whether this FieldFrame contains an instance field.
*
* @param field the field to check.
* @return true if this FieldFrame contains instance field field.
*/
public boolean containsInstanceField(String field) {
return instanceFields.contains(field) || parent != null && staticType == false && parent.containsInstanceField(field);
}
/**
* Determines whether this FieldFrame contains a static field.
*
* @param field the field to check.
* @return true if this FieldFrame contains static field field.
*/
public boolean containsStaticField(String field) {
return staticFields.contains(field) || parent != null && parent.containsStaticField(field);
}
/**
* Getter for parent frame.
*
* @return parent frame.
*/
public FieldFrame getParent() {
return parent;
}
/**
* Check if current frame is embedded in | or |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java | {
"start": 3509,
"end": 21784
} | class
____ final int[] subclassPropertyTableNumberClosure;
// discriminator column
private final Map<Object, String> subclassesByDiscriminatorValue;
private final boolean forceDiscriminator;
private final String discriminatorColumnName;
private final String discriminatorColumnReaders;
private final String discriminatorColumnReaderTemplate;
private final String discriminatorFormulaTemplate;
private final BasicType<?> discriminatorType;
private final Object discriminatorValue;
private final String discriminatorSQLValue;
private final boolean discriminatorInsertable;
private final String[] constraintOrderedTableNames;
private final String[][] constraintOrderedKeyColumnNames;
public SingleTableEntityPersister(
final PersistentClass persistentClass,
final EntityDataAccess cacheAccessStrategy,
final NaturalIdDataAccess naturalIdRegionAccessStrategy,
final RuntimeModelCreationContext creationContext)
throws HibernateException {
super( persistentClass, cacheAccessStrategy, naturalIdRegionAccessStrategy, creationContext );
final var dialect = creationContext.getDialect();
final var typeConfiguration = creationContext.getTypeConfiguration();
// CLASS + TABLE
joinSpan = persistentClass.getJoinClosureSpan() + 1;
// todo (6.2) : see note on AbstractEntityPersister#getTableName(int)
qualifiedTableNames = new String[joinSpan];
qualifiedTableNames[0] = determineTableName( persistentClass.getRootTable() );
isInverseTable = new boolean[joinSpan];
isNullableTable = new boolean[joinSpan];
keyColumnNames = new String[joinSpan][];
isInverseTable[0] = false;
isNullableTable[0] = false;
keyColumnNames[0] = getIdentifierColumnNames();
cascadeDeleteEnabled = new boolean[joinSpan];
// Custom sql
customSQLInsert = new String[joinSpan];
customSQLUpdate = new String[joinSpan];
customSQLDelete = new String[joinSpan];
insertCallable = new boolean[joinSpan];
updateCallable = new boolean[joinSpan];
deleteCallable = new boolean[joinSpan];
insertExpectations = new Expectation[joinSpan];
updateExpectations = new Expectation[joinSpan];
deleteExpectations = new Expectation[joinSpan];
customSQLInsert[0] = persistentClass.getCustomSQLInsert();
insertCallable[0] = persistentClass.isCustomInsertCallable();
insertExpectations[0] = createExpectation( persistentClass.getInsertExpectation(), insertCallable[0] );
customSQLUpdate[0] = persistentClass.getCustomSQLUpdate();
updateCallable[0] = persistentClass.isCustomUpdateCallable();
updateExpectations[0] = createExpectation( persistentClass.getUpdateExpectation(), updateCallable[0] );
customSQLDelete[0] = persistentClass.getCustomSQLDelete();
deleteCallable[0] = persistentClass.isCustomDeleteCallable();
deleteExpectations[0] = createExpectation( persistentClass.getDeleteExpectation(), deleteCallable[0] );
// JOINS
final var joinClosure = persistentClass.getJoinClosure();
boolean hasDuplicateTableName = false;
for ( int j = 1; j - 1 < joinClosure.size(); j++ ) {
final var join = joinClosure.get( j - 1 );
qualifiedTableNames[j] = determineTableName( join.getTable() );
hasDuplicateTableName = hasDuplicateTableName
|| indexOf( qualifiedTableNames, j, qualifiedTableNames[j] ) != -1;
isInverseTable[j] = join.isInverse();
isNullableTable[j] = join.isOptional();
cascadeDeleteEnabled[j] = join.getKey().isCascadeDeleteEnabled() && dialect.supportsCascadeDelete();
customSQLInsert[j] = join.getCustomSQLInsert();
insertCallable[j] = join.isCustomInsertCallable();
insertExpectations[j] = createExpectation( join.getInsertExpectation(), insertCallable[j] );
customSQLUpdate[j] = join.getCustomSQLUpdate();
updateCallable[j] = join.isCustomUpdateCallable();
updateExpectations[j] = createExpectation( join.getUpdateExpectation(), updateCallable[j] );
customSQLDelete[j] = join.getCustomSQLDelete();
deleteCallable[j] = join.isCustomDeleteCallable();
deleteExpectations[j] = createExpectation( join.getDeleteExpectation(), deleteCallable[j] );
keyColumnNames[j] = new String[join.getKey().getColumnSpan()];
final var columns = join.getKey().getColumns();
for ( int i = 0; i < columns.size(); i++ ) {
keyColumnNames[j][i] = columns.get( i ).getQuotedName( dialect );
}
}
hasDuplicateTables = hasDuplicateTableName;
constraintOrderedTableNames = new String[qualifiedTableNames.length];
constraintOrderedKeyColumnNames = new String[qualifiedTableNames.length][];
for ( int i = qualifiedTableNames.length - 1, position = 0; i >= 0; i--, position++ ) {
constraintOrderedTableNames[position] = qualifiedTableNames[i];
constraintOrderedKeyColumnNames[position] = keyColumnNames[i];
}
spaces = join( qualifiedTableNames, toStringArray( persistentClass.getSynchronizedTables() ) );
final ArrayList<String> subclassTables = new ArrayList<>();
final ArrayList<String[]> joinKeyColumns = new ArrayList<>();
final ArrayList<Boolean> isConcretes = new ArrayList<>();
final ArrayList<Boolean> isClassOrSuperclassJoins = new ArrayList<>();
final ArrayList<Boolean> isNullables = new ArrayList<>();
subclassTables.add( qualifiedTableNames[0] );
joinKeyColumns.add( getIdentifierColumnNames() );
isConcretes.add( true );
isClassOrSuperclassJoins.add( true );
isNullables.add( false );
for ( var join : persistentClass.getSubclassJoinClosure() ) {
isConcretes.add( persistentClass.isClassOrSuperclassTable( join.getTable() ) );
isClassOrSuperclassJoins.add( persistentClass.isClassOrSuperclassJoin( join ) );
isNullables.add( join.isOptional() );
subclassTables.add( determineTableName( join.getTable() ) );
final String[] keyCols = new String[join.getKey().getColumnSpan()];
final var columns = join.getKey().getColumns();
for ( int i = 0; i < columns.size(); i++ ) {
keyCols[i] = columns.get( i ).getQuotedName( dialect );
}
joinKeyColumns.add( keyCols );
}
subclassTableNameClosure = toStringArray( subclassTables );
subclassTableKeyColumnClosure = to2DStringArray( joinKeyColumns );
isClassOrSuperclassTable = toBooleanArray( isConcretes );
isClassOrSuperclassJoin = toBooleanArray( isClassOrSuperclassJoins );
isNullableSubclassTable = toBooleanArray( isNullables );
// DISCRIMINATOR
if ( persistentClass.isPolymorphic() ) {
final var discriminator = persistentClass.getDiscriminator();
if ( discriminator == null ) {
throw new MappingException( "discriminator mapping required for single table polymorphic persistence" );
}
forceDiscriminator = persistentClass.isForceDiscriminator();
final var selectable = discriminator.getSelectables().get( 0 );
discriminatorType = DiscriminatorHelper.getDiscriminatorType( persistentClass );
discriminatorValue = DiscriminatorHelper.getDiscriminatorValue( persistentClass );
discriminatorSQLValue = DiscriminatorHelper.getDiscriminatorSQLValue( persistentClass, dialect );
discriminatorInsertable = isDiscriminatorInsertable( persistentClass );
if ( selectable instanceof Formula formula ) {
discriminatorFormulaTemplate = formula.getTemplate( dialect, typeConfiguration );
discriminatorColumnName = null;
discriminatorColumnReaders = null;
discriminatorColumnReaderTemplate = null;
discriminatorAlias = "clazz_";
}
else if ( selectable instanceof Column column ) {
discriminatorColumnName = column.getQuotedName( dialect );
discriminatorColumnReaders = column.getReadExpr( dialect );
discriminatorColumnReaderTemplate = column.getTemplate( dialect, typeConfiguration );
discriminatorAlias = column.getAlias( dialect, persistentClass.getRootTable() );
discriminatorFormulaTemplate = null;
}
else {
throw new AssertionFailure( "Unrecognized selectable" );
}
}
else {
forceDiscriminator = false;
discriminatorInsertable = false;
discriminatorColumnName = null;
discriminatorColumnReaders = null;
discriminatorColumnReaderTemplate = null;
discriminatorAlias = null;
discriminatorType = null;
discriminatorValue = null;
discriminatorSQLValue = null;
discriminatorFormulaTemplate = null;
}
// PROPERTIES
propertyTableNumbers = new int[getPropertySpan()];
final var propertyClosure = persistentClass.getPropertyClosure();
for ( int k = 0; k < propertyClosure.size(); k++ ) {
propertyTableNumbers[k] = persistentClass.getJoinNumber( propertyClosure.get( k ) );
}
//TODO: code duplication with JoinedSubclassEntityPersister
final ArrayList<Integer> propertyJoinNumbers = new ArrayList<>();
final Map<Object, String> subclassesByDiscriminatorValueLocal = new HashMap<>();
for ( var property : persistentClass.getSubclassPropertyClosure() ) {
propertyJoinNumbers.add( persistentClass.getJoinNumber( property ) );
}
subclassPropertyTableNumberClosure = toIntArray( propertyJoinNumbers );
final int subclassSpan = persistentClass.getSubclassSpan() + 1;
subclassClosure = new String[subclassSpan];
subclassClosure[0] = getEntityName();
if ( persistentClass.isPolymorphic() ) {
addSubclassByDiscriminatorValue(
subclassesByDiscriminatorValueLocal,
discriminatorValue,
getEntityName()
);
// SUBCLASSES
final var subclasses = persistentClass.getSubclasses();
for ( int k = 0; k < subclasses.size(); k++ ) {
final var subclass = subclasses.get( k );
subclassClosure[k] = subclass.getEntityName();
addSubclassByDiscriminatorValue(
subclassesByDiscriminatorValueLocal,
DiscriminatorHelper.getDiscriminatorValue( subclass ),
subclass.getEntityName()
);
}
}
// Don't hold a reference to an empty HashMap:
subclassesByDiscriminatorValue = toSmallMap( subclassesByDiscriminatorValueLocal );
initSubclassPropertyAliasesMap( persistentClass );
postConstruct( creationContext.getMetadata() );
}
private static boolean isDiscriminatorInsertable(PersistentClass persistentClass) {
return !persistentClass.isDiscriminatorValueNull()
&& !persistentClass.isDiscriminatorValueNotNull()
&& persistentClass.isDiscriminatorInsertable()
&& !persistentClass.getDiscriminator().hasFormula();
}
private static void addSubclassByDiscriminatorValue(
Map<Object, String> subclassesByDiscriminatorValue,
Object discriminatorValue,
String entityName) {
final String mappedEntityName = subclassesByDiscriminatorValue.put( discriminatorValue, entityName );
if ( mappedEntityName != null ) {
throw new MappingException(
"Entities [" + entityName + "] and [" + mappedEntityName
+ "] are mapped with the same discriminator value '" + discriminatorValue + "'."
);
}
}
@Override
public boolean isInverseTable(int j) {
return isInverseTable[j];
}
@Override
public String getDiscriminatorColumnName() {
return discriminatorColumnName;
}
@Override
public String getDiscriminatorColumnReaders() {
return discriminatorColumnReaders;
}
@Override
public String getDiscriminatorColumnReaderTemplate() {
return discriminatorColumnReaderTemplate;
}
@Override
public String getDiscriminatorFormulaTemplate() {
return discriminatorFormulaTemplate;
}
@Override
public String getTableName() {
return qualifiedTableNames[0];
}
@Override
public BasicType<?> getDiscriminatorType() {
return discriminatorType;
}
@Override
public Map<Object, String> getSubclassByDiscriminatorValue() {
return subclassesByDiscriminatorValue;
}
@Override
public TableDetails getMappedTableDetails() {
return getTableMapping( 0 );
}
@Override
public TableDetails getIdentifierTableDetails() {
return getTableMapping( 0 );
}
@Override
public Object getDiscriminatorValue() {
return discriminatorValue;
}
@Override
public String getDiscriminatorSQLValue() {
return discriminatorSQLValue;
}
/**
* @deprecated No longer used.
*/
@Deprecated(forRemoval = true)
@Remove
public String[] getSubclassClosure() {
return subclassClosure;
}
@Override
public String[] getPropertySpaces() {
return spaces;
}
@Override
protected boolean isDiscriminatorFormula() {
return discriminatorColumnName == null;
}
@Override
public boolean hasDuplicateTables() {
return hasDuplicateTables;
}
@Override
public String getTableName(int j) {
return qualifiedTableNames[j];
}
@Override
public String[] getKeyColumns(int j) {
return keyColumnNames[j];
}
@Override
public boolean isTableCascadeDeleteEnabled(int j) {
return cascadeDeleteEnabled[j];
}
@Override
public boolean isPropertyOfTable(int property, int j) {
return propertyTableNumbers[property] == j;
}
// @Override
// protected boolean isSubclassTableSequentialSelect(int j) {
// return subclassTableSequentialSelect[j] && !isClassOrSuperclassTable[j];
// }
// Execute the SQL:
@Override
public boolean needsDiscriminator() {
return forceDiscriminator || isInherited();
}
public String getAttributeMutationTableName(int i) {
return subclassTableNameClosure[subclassPropertyTableNumberClosure[i]];
}
@Override
public int getTableSpan() {
return joinSpan;
}
@Override
public void addDiscriminatorToInsertGroup(MutationGroupBuilder insertGroupBuilder) {
if ( discriminatorInsertable ) {
final TableInsertBuilder tableInsertBuilder =
insertGroupBuilder.getTableDetailsBuilder( getRootTableName() );
tableInsertBuilder.addValueColumn(
discriminatorValue == NULL_DISCRIMINATOR ? NULL : discriminatorSQLValue,
getDiscriminatorMapping()
);
}
}
@Override
protected int[] getPropertyTableNumbers() {
return propertyTableNumbers;
}
@Override
protected String[] getSubclassTableKeyColumns(int j) {
return subclassTableKeyColumnClosure[j];
}
@Override
public String getSubclassTableName(int j) {
return subclassTableNameClosure[j];
}
@Override
protected String[] getSubclassTableNames() {
return subclassTableNameClosure;
}
@Override
public int getSubclassTableSpan() {
return subclassTableNameClosure.length;
}
@Override
protected boolean isClassOrSuperclassTable(int j) {
return isClassOrSuperclassTable[j];
}
@Override
protected boolean isClassOrSuperclassJoin(int j) {
return isClassOrSuperclassJoin[j];
}
@Override
public boolean isNullableTable(int j) {
return isNullableTable[j];
}
@Override
protected boolean isIdentifierTable(String tableExpression) {
return tableExpression.equals( getRootTableName() );
}
@Override
protected boolean isNullableSubclassTable(int j) {
return isNullableSubclassTable[j];
}
@Override
public boolean hasMultipleTables() {
return getTableSpan() > 1;
}
@Override
public String[] getConstraintOrderedTableNameClosure() {
return constraintOrderedTableNames;
}
@Override
public String[][] getConstraintOrderedTableKeyColumnClosure() {
return constraintOrderedKeyColumnNames;
}
@Override
public FilterAliasGenerator getFilterAliasGenerator(String rootAlias) {
return new DynamicFilterAliasGenerator( qualifiedTableNames, rootAlias );
}
@Override
public void pruneForSubclasses(TableGroup tableGroup, Map<String, EntityNameUse> entityNameUses) {
if ( needsDiscriminator() || !entityNameUses.isEmpty() ) {// The following optimization is to add the discriminator filter fragment for all treated entity names
final var mappingMetamodel = getFactory().getMappingMetamodel();
if ( containsTreatUse( entityNameUses, mappingMetamodel ) ) {
final String discriminatorPredicate =
getPrunedDiscriminatorPredicate( entityNameUses, mappingMetamodel, "t" );
if ( discriminatorPredicate != null ) {
final var tableReference = (NamedTableReference) tableGroup.getPrimaryTableReference();
tableReference.setPrunedTableExpression(
"(select * from " + getTableName() + " t where " + discriminatorPredicate + ")" );
}
}
// Otherwise, if we only have FILTER uses, we don't have to do anything here because
// the BaseSqmToSqlAstConverter will already apply the type filter in the WHERE clause
}
}
private boolean containsTreatUse(Map<String, EntityNameUse> entityNameUses, MappingMetamodel metamodel) {
for ( var entry : entityNameUses.entrySet() ) {
// We only care about treat uses which allow to reduce the amount of rows to select
if ( entry.getValue().getKind() == EntityNameUse.UseKind.TREAT ) {
final var persister = metamodel.getEntityDescriptor( entry.getKey() );
// Filtering for abstract entities makes no sense, so ignore that
if ( !persister.isAbstract() ) {
// Also, it makes no sense to filter for any of the super types,
// as the query will contain a filter for that already anyway
final var superMappingType = getSuperMappingType();
if ( superMappingType == null || !superMappingType.isTypeOrSuperType( persister ) ) {
return true;
}
}
}
}
return false;
}
@Override
public void visitConstraintOrderedTables(ConstraintOrderedTableConsumer consumer) {
for ( int i = 0; i < constraintOrderedTableNames.length; i++ ) {
final String tableName = constraintOrderedTableNames[i];
final int tablePosition = i;
consumer.consume(
tableName,
() -> columnConsumer -> columnConsumer.accept(
tableName,
constraintOrderedKeyColumnNames[tablePosition],
getIdentifierMapping()::getJdbcMapping
)
);
}
}
@Override
protected void visitMutabilityOrderedTables(MutabilityOrderedTableConsumer consumer) {
for ( int i = 0; i < qualifiedTableNames.length; i++ ) {
final String tableName = qualifiedTableNames[i];
final int tableIndex = i;
consumer.consume(
tableName,
tableIndex,
() -> columnConsumer -> columnConsumer.accept(
getIdentifierMapping(),
tableName,
keyColumnNames[tableIndex]
)
);
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Deprecations
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Deprecated private final String discriminatorAlias;
@Override
public String getDiscriminatorAlias() {
return discriminatorAlias;
}
}
| private |
java | apache__camel | components/camel-huawei/camel-huaweicloud-obs/src/test/java/org/apache/camel/component/huaweicloud/obs/ListBucketsTest.java | {
"start": 1610,
"end": 3937
} | class ____ extends CamelTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(ListBucketsTest.class.getName());
TestConfiguration testConfiguration = new TestConfiguration();
@BindToRegistry("obsClient")
ObsClient mockClient = Mockito.mock(ObsClient.class);
@BindToRegistry("serviceKeys")
ServiceKeys serviceKeys = new ServiceKeys(
testConfiguration.getProperty("accessKey"),
testConfiguration.getProperty("secretKey"));
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:list_buckets")
.to("hwcloud-obs:listBuckets?" +
"accessKey=" + testConfiguration.getProperty("accessKey") +
"&secretKey=" + testConfiguration.getProperty("secretKey") +
"®ion=" + testConfiguration.getProperty("region") +
"&ignoreSslVerification=true" +
"&obsClient=#obsClient")
.log("List buckets successful")
.to("mock:list_buckets_result");
}
};
}
@Test
public void testListBuckets() throws Exception {
List<ObsBucket> buckets = new ArrayList<>();
buckets.add(new ObsBucket("bucket1", "location-1"));
buckets.add(new ObsBucket("bucket2", "location-2"));
Owner owner = new Owner();
ListBucketsResult response = new ListBucketsResult(buckets, owner, false, null, 10, null);
Mockito.when(mockClient.listBucketsV2(Mockito.any(ListBucketsRequest.class))).thenReturn(response);
MockEndpoint mock = getMockEndpoint("mock:list_buckets_result");
mock.expectedMinimumMessageCount(1);
template.sendBody("direct:list_buckets", "sample_body");
Exchange responseExchange = mock.getExchanges().get(0);
mock.assertIsSatisfied();
assertEquals(
"[{\"bucketName\":\"bucket1\",\"location\":\"location-1\",\"metadata\":{},\"statusCode\":0},{\"bucketName\":\"bucket2\",\"location\":\"location-2\",\"metadata\":{},\"statusCode\":0}]",
responseExchange.getIn().getBody(String.class));
}
}
| ListBucketsTest |
java | google__guice | core/src/com/google/inject/internal/aop/Enhancer.java | {
"start": 4967,
"end": 9830
} | class ____ extends AbstractGlueGenerator {
private static final String HANDLERS_NAME = "GUICE$HANDLERS";
private static final String HANDLERS_DESCRIPTOR = "[Ljava/lang/reflect/InvocationHandler;";
private static final String HANDLER_TYPE = Type.getInternalName(InvocationHandler.class);
private static final String HANDLER_ARRAY_TYPE = Type.getInternalName(InvocationHandler[].class);
private static final String INVOKERS_NAME = "GUICE$INVOKERS";
private static final String INVOKERS_DESCRIPTOR = "Ljava/lang/invoke/MethodHandle;";
private static final String CALLBACK_DESCRIPTOR =
"(Ljava/lang/Object;"
+ "Ljava/lang/reflect/Method;"
+ "[Ljava/lang/Object;)"
+ "Ljava/lang/Object;";
// Describes the LambdaMetafactory.metafactory method arguments and return type
private static final String METAFACTORY_DESCRIPTOR =
"(Ljava/lang/invoke/MethodHandles$Lookup;"
+ "Ljava/lang/String;"
+ "Ljava/lang/invoke/MethodType;"
+ "Ljava/lang/invoke/MethodType;"
+ "Ljava/lang/invoke/MethodHandle;"
+ "Ljava/lang/invoke/MethodType;)"
+ "Ljava/lang/invoke/CallSite;";
private static final Type INDEX_TO_INVOKER_METHOD_TYPE =
Type.getMethodType("(I)Ljava/util/function/BiFunction;");
private static final Type RAW_INVOKER_METHOD_TYPE =
Type.getMethodType("(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
private static final Type INVOKER_METHOD_TYPE =
Type.getMethodType("(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
private final Map<Method, Method> bridgeDelegates;
private final String checkcastToProxy;
Enhancer(Class<?> hostClass, Map<Method, Method> bridgeDelegates) {
super(hostClass, ENHANCER_BY_GUICE_MARKER);
this.bridgeDelegates = bridgeDelegates;
// with defineAnonymousClass we can't downcast to the proxy and must use host instead
this.checkcastToProxy = ClassDefining.canDowncastToProxy(hostClass) ? proxyName : hostName;
}
@Override
protected byte[] generateGlue(Collection<Executable> members) {
ClassWriter cw = new ClassWriter(COMPUTE_MAXS);
// target Java8 because that's all we need for the generated trampoline code
cw.visit(V1_8, PUBLIC | ACC_SUPER, proxyName, null, hostName, null);
cw.visitSource(GENERATED_SOURCE, null);
// this shared field either contains the trampoline or glue to make it into an invoker table
cw.visitField(PUBLIC | STATIC | FINAL, INVOKERS_NAME, INVOKERS_DESCRIPTOR, null, null)
.visitEnd();
setupInvokerTable(cw);
generateTrampoline(cw, members);
// this field will hold the handlers configured for this particular enhanced instance
cw.visitField(PRIVATE | FINAL, HANDLERS_NAME, HANDLERS_DESCRIPTOR, null, null).visitEnd();
Set<Method> remainingBridgeMethods = new HashSet<>(bridgeDelegates.keySet());
int methodIndex = 0;
for (Executable member : members) {
if (member instanceof Constructor<?>) {
enhanceConstructor(cw, (Constructor<?>) member);
} else {
enhanceMethod(cw, (Method) member, methodIndex++);
remainingBridgeMethods.remove(member);
}
}
// replace any remaining bridge methods with virtual dispatch to their non-bridge targets
for (Method method : remainingBridgeMethods) {
Method target = bridgeDelegates.get(method);
if (target != null) {
generateVirtualBridge(cw, method, target);
}
}
cw.visitEnd();
return cw.toByteArray();
}
/** Generate static initializer to setup invoker table based on the trampoline. */
private void setupInvokerTable(ClassWriter cw) {
MethodVisitor mv = cw.visitMethod(PRIVATE | STATIC, "<clinit>", "()V", null, null);
mv.visitCode();
Handle trampolineHandle =
new Handle(H_INVOKESTATIC, proxyName, TRAMPOLINE_NAME, TRAMPOLINE_DESCRIPTOR, false);
if (ClassDefining.canLoadProxyByName(hostClass)) {
// generate lambda glue to make the raw trampoline look like an invoker table
mv.visitMethodInsn(
INVOKESTATIC,
"java/lang/invoke/MethodHandles",
"lookup",
"()Ljava/lang/invoke/MethodHandles$Lookup;",
false);
mv.visitLdcInsn("apply");
mv.visitLdcInsn(INDEX_TO_INVOKER_METHOD_TYPE);
mv.visitLdcInsn(RAW_INVOKER_METHOD_TYPE);
mv.visitLdcInsn(trampolineHandle);
mv.visitLdcInsn(INVOKER_METHOD_TYPE);
mv.visitMethodInsn(
INVOKESTATIC,
"java/lang/invoke/LambdaMetafactory",
"metafactory",
METAFACTORY_DESCRIPTOR,
false);
mv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/invoke/CallSite",
"getTarget",
"()Ljava/lang/invoke/MethodHandle;",
false);
} else {
// proxy | Enhancer |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/DefaultExecutionEventCatapult.java | {
"start": 1314,
"end": 1403
} | class ____ be changed or deleted without
* prior notice.
*
*/
@Named
@Singleton
public | can |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/foreach/MyNonBean.java | {
"start": 754,
"end": 951
} | class ____ {
@EachBean(MyConfiguration.class)
public NonBeanClass nonBeanClass(MyConfiguration myConfiguration) {
return new NonBeanClass(myConfiguration.getPort());
}
}
| MyNonBean |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/object/ObjectAssert_extracting_with_String_Test.java | {
"start": 4956,
"end": 5341
} | class ____ {
private final String name;
private Optional<String> nickname = Optional.empty();
private BigDecimal height;
public Person(String name) {
this.name = name;
}
public void setNickname(Optional<String> nickname) {
this.nickname = nickname;
}
public void setHeight(BigDecimal height) {
this.height = height;
}
}
}
| Person |
java | netty__netty | example/src/main/java/io/netty/example/spdy/server/SpdyServer.java | {
"start": 2078,
"end": 3978
} | class ____ {
static final int PORT = Integer.parseInt(System.getProperty("port", "8443"));
public static void main(String[] args) throws Exception {
// Configure SSL.
X509Bundle ssc = new CertificateBuilder()
.subject("cn=localhost")
.setIsCertificateAuthority(true)
.buildSelfSigned();
SslContext sslCtx = SslContextBuilder.forServer(ssc.toKeyManagerFactory())
.applicationProtocolConfig(new ApplicationProtocolConfig(
Protocol.ALPN,
// NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
SelectorFailureBehavior.NO_ADVERTISE,
// ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.SPDY_3_1,
ApplicationProtocolNames.HTTP_1_1))
.build();
// Configure the server.
EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
try {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 1024);
b.group(group)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new SpdyServerInitializer(sslCtx));
Channel ch = b.bind(PORT).sync().channel();
System.err.println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");
ch.closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
| SpdyServer |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/rpchook/NamespaceRpcHook.java | {
"start": 1098,
"end": 1799
} | class ____ implements RPCHook {
private final ClientConfig clientConfig;
public NamespaceRpcHook(ClientConfig clientConfig) {
this.clientConfig = clientConfig;
}
@Override
public void doBeforeRequest(String remoteAddr, RemotingCommand request) {
if (StringUtils.isNotEmpty(clientConfig.getNamespaceV2())) {
request.addExtField(MixAll.RPC_REQUEST_HEADER_NAMESPACED_FIELD, "true");
request.addExtField(MixAll.RPC_REQUEST_HEADER_NAMESPACE_FIELD, clientConfig.getNamespaceV2());
}
}
@Override
public void doAfterResponse(String remoteAddr, RemotingCommand request,
RemotingCommand response) {
}
}
| NamespaceRpcHook |
java | elastic__elasticsearch | modules/parent-join/src/test/java/org/elasticsearch/join/aggregations/ParentTests.java | {
"start": 737,
"end": 1232
} | class ____ extends BaseAggregationTestCase<ParentAggregationBuilder> {
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return Arrays.asList(ParentJoinPlugin.class);
}
@Override
protected ParentAggregationBuilder createTestAggregatorBuilder() {
String name = randomAlphaOfLengthBetween(3, 20);
String parentType = randomAlphaOfLengthBetween(5, 40);
return new ParentAggregationBuilder(name, parentType);
}
}
| ParentTests |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/ASTHelpersTest.java | {
"start": 22953,
"end": 23330
} | class ____ {
public List<?> myList;
}
""");
TestScanner scanner = getUpperBoundScanner("java.lang.Object");
tests.add(scanner);
assertCompiles(scanner);
}
@Test
public void getUpperBoundLowerBoundedWildcard() {
writeFile(
"A.java",
"""
import java.lang.Number;
import java.util.List;
public | A |
java | grpc__grpc-java | examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java | {
"start": 1409,
"end": 2797
} | class ____ extends AppCompatActivity {
private Button sendButton;
private EditText hostEdit;
private EditText portEdit;
private EditText messageEdit;
private TextView resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helloworld);
sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage(v);
}
});
hostEdit = (EditText) findViewById(R.id.host_edit_text);
portEdit = (EditText) findViewById(R.id.port_edit_text);
messageEdit = (EditText) findViewById(R.id.message_edit_text);
resultText = (TextView) findViewById(R.id.grpc_response_text);
resultText.setMovementMethod(new ScrollingMovementMethod());
}
public void sendMessage(View view) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(hostEdit.getWindowToken(), 0);
sendButton.setEnabled(false);
resultText.setText("");
new GrpcTask(this)
.execute(
hostEdit.getText().toString(),
messageEdit.getText().toString(),
portEdit.getText().toString());
}
private static | HelloworldActivity |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/procedure/DB2StoredProcedureTest.java | {
"start": 2434,
"end": 19937
} | class ____ {
private static final String CITY = "London";
private static final String STREET = "Lollard Street";
private static final String ZIP = "SE116U";
@Test
public void testStoredProcedureOutParameter(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_count_phones" );
query.registerStoredProcedureParameter( 1, Long.class, ParameterMode.IN );
query.registerStoredProcedureParameter( 2, Long.class, ParameterMode.OUT );
query.setParameter( 1, 1L );
query.execute();
final Long phoneCount = (Long) query.getOutputParameterValue( 2 );
assertEquals( Long.valueOf( 2 ), phoneCount );
} );
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-18302" )
public void testStoredProcedureNamedParameters(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_count_phones" );
query.registerStoredProcedureParameter( "personId", Long.class, ParameterMode.IN );
query.registerStoredProcedureParameter( "phoneCount", Long.class, ParameterMode.OUT );
query.setParameter( "personId", 1L );
query.execute();
final Long phoneCount = (Long) query.getOutputParameterValue( "phoneCount" );
assertEquals( Long.valueOf( 2 ), phoneCount );
} );
}
@Test
public void testStoredProcedureRefCursor(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_person_phones" );
query.registerStoredProcedureParameter( 1, Long.class, ParameterMode.IN );
query.registerStoredProcedureParameter( 2, Class.class, ParameterMode.REF_CURSOR );
query.setParameter( 1, 1L );
query.execute();
final List<Object[]> postComments = query.getResultList();
assertNotNull( postComments );
} );
}
@Test
public void testHibernateProcedureCallRefCursor(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final Session session = entityManager.unwrap( Session.class );
final ProcedureCall call = session.createStoredProcedureCall( "sp_person_phones" );
final ProcedureParameter<Long> inParam = call.registerParameter(
1,
Long.class,
ParameterMode.IN
);
call.setParameter( inParam, 1L );
call.registerParameter( 2, Class.class, ParameterMode.REF_CURSOR );
final Output output = call.getOutputs().getCurrent();
final List<Object[]> postComments = ( (ResultSetOutput) output ).getResultList();
assertEquals( 2, postComments.size() );
} );
}
@Test
public void testStoredProcedureReturnValue(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final Integer phoneCount = (Integer) entityManager
.createNativeQuery( "SELECT fn_count_phones(:personId) FROM SYSIBM.DUAL" )
.setParameter( "personId", 1L )
.getSingleResult();
assertEquals( 2, phoneCount );
} );
}
@Test
public void testFunctionCallWithJdbc(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final Session session = entityManager.unwrap( Session.class );
session.doWork( connection -> {
try (final PreparedStatement function = connection.prepareStatement(
"select * from table(fn_person_and_phones( ? ))" )) {
function.setInt( 1, 1 );
function.execute();
try (final ResultSet resultSet = function.getResultSet()) {
while ( resultSet.next() ) {
assertThat( resultSet.getLong( 1 ) ).isInstanceOf( Long.class );
assertThat( resultSet.getString( 2 ) ).isInstanceOf( String.class );
}
}
}
} );
} );
}
@Test
public void testSysRefCursorAsOutParameter(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final StoredProcedureQuery function = entityManager.createNamedStoredProcedureQuery( "singleRefCursor" );
function.execute();
assertFalse( function.hasMoreResults() );
Long value = null;
try (final ResultSet resultSet = (ResultSet) function.getOutputParameterValue( 1 )) {
while ( resultSet.next() ) {
value = resultSet.getLong( 1 );
}
}
catch (final SQLException e) {
fail( e.getMessage() );
}
assertEquals( Long.valueOf( 1 ), value );
} );
}
@Test
public void testOutAndSysRefCursorAsOutParameter(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final StoredProcedureQuery function = entityManager.createNamedStoredProcedureQuery( "outAndRefCursor" );
function.execute();
assertFalse( function.hasMoreResults() );
Long value = null;
try (final ResultSet resultSet = (ResultSet) function.getOutputParameterValue( 1 )) {
while ( resultSet.next() ) {
value = resultSet.getLong( 1 );
}
}
catch (final SQLException e) {
fail( e.getMessage() );
}
assertEquals( value, function.getOutputParameterValue( 2 ) );
} );
}
@Test
public void testBindParameterAsHibernateType(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_phone_validity" )
.registerStoredProcedureParameter( 1, NumericBooleanConverter.class, ParameterMode.IN )
.registerStoredProcedureParameter( 2, Class.class, ParameterMode.REF_CURSOR )
.setParameter( 1, true );
query.execute();
final List phones = query.getResultList();
assertEquals( 1, phones.size() );
assertEquals( "123-456-7890", phones.get( 0 ) );
} );
scope.inTransaction( entityManager -> {
final Vote vote1 = new Vote();
vote1.setId( 1L );
vote1.setVoteChoice( true );
entityManager.persist( vote1 );
final Vote vote2 = new Vote();
vote2.setId( 2L );
vote2.setVoteChoice( false );
entityManager.persist( vote2 );
} );
scope.inTransaction( entityManager -> {
final StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_votes" )
.registerStoredProcedureParameter( 1, YesNoConverter.class, ParameterMode.IN )
.registerStoredProcedureParameter( 2, Class.class, ParameterMode.REF_CURSOR )
.setParameter( 1, true );
query.execute();
final List votes = query.getResultList();
assertEquals( 1, votes.size() );
assertEquals( 1, ( (Number) votes.get( 0 ) ).intValue() );
} );
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-18302" )
public void testStoredProcedureInAndOutAndRefCursorParameters(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_get_address_by_street_city" );
query.registerStoredProcedureParameter( "street_in", String.class, ParameterMode.IN );
query.registerStoredProcedureParameter( "city_in", String.class, ParameterMode.IN );
query.registerStoredProcedureParameter( "rec_out", ResultSet.class, ParameterMode.REF_CURSOR );
query.setParameter( "street_in", STREET )
.setParameter( "city_in", CITY );
query.execute();
ResultSet rs = (ResultSet) query.getOutputParameterValue( "rec_out" );
try {
Assertions.assertTrue( rs.next() );
MatcherAssert.assertThat( rs.getString( "street" ), is( STREET ) );
MatcherAssert.assertThat( rs.getString( "city" ), is( CITY ) );
MatcherAssert.assertThat( rs.getString( "zip" ), is( ZIP ) );
}
catch (SQLException e) {
throw new RuntimeException( e );
}
}
);
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-18302" )
public void testStoredProcedureInAndOutAndRefCursorParametersDifferentRegistrationOrder(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_get_address_by_street_city" );
query.registerStoredProcedureParameter( "city_in", String.class, ParameterMode.IN );
query.registerStoredProcedureParameter( "street_in", String.class, ParameterMode.IN );
query.registerStoredProcedureParameter( "rec_out", ResultSet.class, ParameterMode.REF_CURSOR );
query.setParameter( "street_in", STREET )
.setParameter( "city_in", CITY );
query.execute();
ResultSet rs = (ResultSet) query.getOutputParameterValue( "rec_out" );
try {
Assertions.assertTrue( rs.next() );
MatcherAssert.assertThat( rs.getString( "street" ), is( STREET ) );
MatcherAssert.assertThat( rs.getString( "city" ), is( CITY ) );
MatcherAssert.assertThat( rs.getString( "zip" ), is( ZIP ) );
}
catch (SQLException e) {
throw new RuntimeException( e );
}
}
);
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-18302" )
public void testStoredProcedureInAndOutAndRefCursorParametersDifferentRegistrationOrder2(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
StoredProcedureQuery query = entityManager.createStoredProcedureQuery( "sp_get_address_by_street_city" );
query.registerStoredProcedureParameter( "rec_out", ResultSet.class, ParameterMode.REF_CURSOR );
query.registerStoredProcedureParameter( "city_in", String.class, ParameterMode.IN );
query.registerStoredProcedureParameter( "street_in", String.class, ParameterMode.IN );
query.setParameter( "street_in", STREET )
.setParameter( "city_in", CITY );
query.execute();
ResultSet rs = (ResultSet) query.getOutputParameterValue( "rec_out" );
try {
Assertions.assertTrue( rs.next() );
MatcherAssert.assertThat( rs.getString( "street" ), is( STREET ) );
MatcherAssert.assertThat( rs.getString( "city" ), is( CITY ) );
MatcherAssert.assertThat( rs.getString( "zip" ), is( ZIP ) );
}
catch (SQLException e) {
throw new RuntimeException( e );
}
}
);
}
@BeforeAll
public void prepareSchema(EntityManagerFactoryScope scope) {
scope.inTransaction( (entityManager) -> entityManager.unwrap( Session.class ).doWork( (connection) -> {
try (final Statement statement = connection.createStatement()) {
statement.executeUpdate(
"CREATE OR REPLACE PROCEDURE sp_count_phones( " +
" IN personId INT, " +
" OUT phoneCount INT ) " +
"BEGIN " +
" SELECT COUNT(*) INTO phoneCount " +
" FROM phone " +
" WHERE person_id = personId; " +
"END"
);
statement.executeUpdate(
"CREATE OR REPLACE PROCEDURE sp_person_phones( " +
" IN personId INT," +
" OUT personPhones CURSOR) " +
"BEGIN " +
" SET personPhones = CURSOR FOR " +
" SELECT *" +
" FROM phone " +
" WHERE person_id = personId; " +
" OPEN personPhones; " +
"END"
);
statement.executeUpdate(
"CREATE OR REPLACE FUNCTION fn_count_phones( " +
" IN personId INT ) " +
" RETURNS INT " +
"BEGIN " +
" DECLARE phoneCount INT; " +
" SELECT COUNT(*) INTO phoneCount " +
" FROM phone " +
" WHERE person_id = personId; " +
" RETURN phoneCount; " +
"END"
);
statement.executeUpdate(
"CREATE OR REPLACE FUNCTION fn_person_and_phones(personId INTEGER) " +
" RETURNS TABLE " +
" ( " +
" \"pr.id\" BIGINT, " +
" \"pr.name\" VARCHAR(255), " +
" \"pr.nickName\" VARCHAR(255), " +
" \"pr.address\" VARCHAR(255), " +
" \"pr.createdOn\" TIMESTAMP, " +
" \"pr.version\" INTEGER, " +
" \"ph.id\" BIGINT, " +
" \"ph.person_id\" BIGINT, " +
" \"ph.phone_number\" VARCHAR(255), " +
" \"ph.valid\" SMALLINT " +
" ) " +
" BEGIN ATOMIC " +
" RETURN SELECT pr.id AS \"pr.id\", " +
" pr.name AS \"pr.name\", " +
" pr.nickName AS \"pr.nickName\", " +
" pr.address AS \"pr.address\", " +
" pr.createdOn AS \"pr.createdOn\", " +
" pr.version AS \"pr.version\", " +
" ph.id AS \"ph.id\", " +
" ph.person_id AS \"ph.person_id\", " +
" ph.phone_number AS \"ph.phone_number\", " +
" ph.valid AS \"ph.valid\" " +
" FROM person pr " +
" JOIN phone ph ON pr.id = ph.person_id " +
" WHERE pr.id = personId; " +
" END " );
statement.executeUpdate(
"CREATE OR REPLACE " +
"PROCEDURE singleRefCursor(OUT p_recordset CURSOR) " +
" BEGIN " +
" SET p_recordset = CURSOR FOR " +
" SELECT 1 as id " +
" FROM sysibm.dual; " +
" OPEN p_recordset; " +
" END "
);
statement.executeUpdate(
"CREATE OR REPLACE " +
"PROCEDURE outAndRefCursor(OUT p_recordset CURSOR, OUT p_value INT) " +
" BEGIN " +
" SET p_recordset = CURSOR FOR " +
" SELECT 1 as id " +
" FROM sysibm.dual; " +
" SELECT 1 INTO p_value FROM sysibm.dual; " +
" OPEN p_recordset; " +
" END"
);
statement.executeUpdate(
"CREATE OR REPLACE PROCEDURE sp_phone_validity ( " +
" IN validity SMALLINT, " +
" OUT personPhones CURSOR ) " +
"BEGIN " +
" SET personPhones = CURSOR FOR " +
" SELECT phone_number " +
" FROM phone " +
" WHERE valid = validity; " +
" OPEN personPhones; " +
"END"
);
statement.executeUpdate(
"CREATE OR REPLACE PROCEDURE sp_votes ( " +
" IN validity CHAR(1), " +
" OUT votes CURSOR ) " +
"BEGIN " +
" SET votes = CURSOR FOR " +
" SELECT id " +
" FROM vote " +
" WHERE vote_choice = validity; " +
" OPEN votes; " +
"END"
);
statement.executeUpdate(
"CREATE OR REPLACE PROCEDURE sp_get_address_by_street_city ( " +
" IN street_in VARCHAR(255), " +
" IN city_in VARCHAR(255), " +
" OUT rec_out CURSOR ) " +
"BEGIN " +
" SET rec_out = CURSOR FOR " +
" SELECT * " +
" FROM ADDRESS_TABLE A " +
" WHERE " +
" A.STREET = street_in" +
" AND A.CITY = city_in;" +
" OPEN rec_out; " +
"END"
);
}
} ) );
}
@BeforeEach
public void setUp(EntityManagerFactoryScope scope){
scope.inTransaction( (entityManager) -> {
final Person person1 = new Person( 1L, "John Doe" );
person1.setNickName( "JD" );
person1.setAddress( "Earth" );
person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ).toInstant( ZoneOffset.UTC ) ) );
entityManager.persist( person1 );
final Phone phone1 = new Phone( "123-456-7890" );
phone1.setId( 1L );
phone1.setValid( true );
person1.addPhone( phone1 );
final Phone phone2 = new Phone( "098_765-4321" );
phone2.setId( 2L );
phone2.setValid( false );
person1.addPhone( phone2 );
Address address = new Address( 1l, STREET, CITY, ZIP );
entityManager.persist( address );
} );
}
@AfterAll
public void cleanUpSchema(EntityManagerFactoryScope scope) {
scope.inEntityManager( (em) -> {
final Session session = em.unwrap( Session.class );
session.doWork( connection -> {
try (final Statement statement = connection.createStatement()) {
statement.executeUpdate( "DROP PROCEDURE sp_count_phones" );
statement.executeUpdate( "DROP PROCEDURE sp_person_phones" );
statement.executeUpdate( "DROP FUNCTION fn_count_phones" );
statement.executeUpdate( "DROP FUNCTION fn_person_and_phones" );
statement.executeUpdate( "DROP PROCEDURE singleRefCursor" );
statement.executeUpdate( "DROP PROCEDURE outAndRefCursor" );
statement.executeUpdate( "DROP PROCEDURE sp_phone_validity" );
statement.executeUpdate( "DROP PROCEDURE sp_votes" );
statement.executeUpdate( "DROP PROCEDURE sp_get_address_by_street_city" );
}
catch (final SQLException ignore) {
}
} );
} );
}
@AfterEach
public void cleanData(EntityManagerFactoryScope scope) {
scope.inTransaction( (em) -> {
final List<Person> people = em.createQuery( "from Person", Person.class ).getResultList();
people.forEach( em::remove );
em.createQuery( "delete Address" ).executeUpdate();
} );
}
@NamedStoredProcedureQueries( {
@NamedStoredProcedureQuery(
name = "singleRefCursor",
procedureName = "singleRefCursor",
parameters = {
@StoredProcedureParameter( mode = ParameterMode.REF_CURSOR, type = void.class )
}
),
@NamedStoredProcedureQuery(
name = "outAndRefCursor",
procedureName = "outAndRefCursor",
parameters = {
@StoredProcedureParameter( mode = ParameterMode.REF_CURSOR, type = void.class ),
@StoredProcedureParameter( mode = ParameterMode.OUT, type = Long.class ),
}
)
} )
@Entity( name = "IdHolder" )
public static | DB2StoredProcedureTest |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java | {
"start": 7629,
"end": 9906
} | class ____<K, V> implements Map<K, V> {
private final Map<K, V> loaded = new ConcurrentHashMap<>();
private final Map<K, Supplier<V>> loaders;
LoadingMap(Map<K, Supplier<V>> loaders) {
this.loaders = Collections.unmodifiableMap(new HashMap<>(loaders));
}
@Override
public int size() {
return this.loaders.size();
}
@Override
public boolean isEmpty() {
return this.loaders.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return this.loaders.containsKey(key);
}
@Override
public Set<K> keySet() {
return this.loaders.keySet();
}
@Override
public V get(Object key) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.computeIfAbsent((K) key, (k) -> this.loaders.get(k).get());
}
@Override
public V put(K key, V value) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.put(key, value);
}
@Override
public V remove(Object key) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
this.loaded.clear();
}
@Override
public boolean containsValue(Object value) {
return this.loaded.containsValue(value);
}
@Override
public Collection<V> values() {
return this.loaded.values();
}
@Override
public Set<Entry<K, V>> entrySet() {
return this.loaded.entrySet();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoadingMap<?, ?> that = (LoadingMap<?, ?>) o;
return this.loaded.equals(that.loaded);
}
@Override
public int hashCode() {
return this.loaded.hashCode();
}
}
}
| LoadingMap |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartForm.java | {
"start": 877,
"end": 2919
} | class ____ extends ClientMultipartForm implements Iterable<QuarkusMultipartFormDataPart> {
@Override
public Iterator<QuarkusMultipartFormDataPart> iterator() {
return parts.iterator();
}
public void preparePojos(RestClientRequestContext context) throws IOException {
Serialisers serialisers = context.getRestClient().getClientContext().getSerialisers();
for (PojoFieldData pojo : pojos) {
MultivaluedMap<String, String> headers = new MultivaluedTreeMap<>();
Object entityObject = pojo.entity;
Entity<?> entity = Entity.entity(entityObject, pojo.mediaType);
Class<?> entityClass;
Type entityType;
if (entityObject instanceof GenericEntity) {
GenericEntity<?> genericEntity = (GenericEntity<?>) entityObject;
entityClass = genericEntity.getRawType();
entityType = pojo.type;
entityObject = genericEntity.getEntity();
} else {
entityType = entityClass = pojo.type;
}
List<MessageBodyWriter<?>> writers = serialisers.findWriters(context.getConfiguration(),
entityClass, entity.getMediaType(),
RuntimeType.CLIENT);
Buffer value = null;
for (MessageBodyWriter<?> w : writers) {
Buffer ret = ClientSerialisers.invokeClientWriter(entity, entityObject, entityClass, entityType, headers, w,
context.getConfiguration().getWriterInterceptors().toArray(Serialisers.NO_WRITER_INTERCEPTOR),
context.getProperties(), context, serialisers, context.getConfiguration());
if (ret != null) {
value = ret;
break;
}
}
parts.set(pojo.position,
new QuarkusMultipartFormDataPart(pojo.name, pojo.filename, value, pojo.mediaType, pojo.type));
}
}
public static | QuarkusMultipartForm |
java | elastic__elasticsearch | x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/TestSingleValueAggregation.java | {
"start": 733,
"end": 1953
} | class ____ extends InternalAggregation {
private final List<String> path;
private final Object value;
TestSingleValueAggregation(String name, List<String> path, Object value) {
super(name, emptyMap());
this.path = path;
this.value = value;
}
@Override
public String getWriteableName() {
throw new UnsupportedOperationException();
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
throw new UnsupportedOperationException();
}
@Override
protected AggregatorReducer getLeaderReducer(AggregationReduceContext reduceContext, int size) {
throw new UnsupportedOperationException();
}
@Override
protected boolean mustReduceOnSingleInternalAgg() {
return true;
}
@Override
public Object getProperty(List<String> path) {
if (this.path.equals(path)) {
return value;
}
throw new IllegalArgumentException("unknown path " + path);
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
throw new UnsupportedOperationException();
}
}
| TestSingleValueAggregation |
java | apache__avro | lang/java/ipc/src/main/java/org/apache/avro/ipc/stats/StatsServlet.java | {
"start": 1608,
"end": 1749
} | class ____ the same synchronization conventions as StatsPlugin, to
* avoid requiring StatsPlugin to serve a copy of the data.
*/
public | follows |
java | google__dagger | dagger-testing/main/java/dagger/model/testing/BindingGraphSubject.java | {
"start": 1232,
"end": 4058
} | class ____ extends Subject {
/** Starts a fluent assertion about a {@link BindingGraph}. */
public static BindingGraphSubject assertThat(BindingGraph bindingGraph) {
return assertAbout(BindingGraphSubject::new).that(bindingGraph);
}
private final BindingGraph actual;
private BindingGraphSubject(FailureMetadata metadata, @NullableDecl BindingGraph actual) {
super(metadata, actual);
this.actual = actual;
}
/**
* Asserts that the graph has at least one binding with an unqualified key.
*
* @param type the canonical name of the type, as returned by {@link TypeMirror#toString()}
*/
public void hasBindingWithKey(String type) {
bindingWithKey(type);
}
/**
* Asserts that the graph has at least one binding with a qualified key.
*
* @param qualifier the canonical string form of the qualifier, as returned by {@link
* javax.lang.model.element.AnnotationMirror AnnotationMirror.toString()}
* @param type the canonical name of the type, as returned by {@link TypeMirror#toString()}
*/
public void hasBindingWithKey(String qualifier, String type) {
bindingWithKey(qualifier, type);
}
/**
* Returns a subject for testing the binding for an unqualified key.
*
* @param type the canonical name of the type, as returned by {@link TypeMirror#toString()}
*/
public BindingSubject bindingWithKey(String type) {
return bindingWithKeyString(keyString(type));
}
/**
* Returns a subject for testing the binding for a qualified key.
*
* @param qualifier the canonical string form of the qualifier, as returned by {@link
* javax.lang.model.element.AnnotationMirror AnnotationMirror.toString()}
* @param type the canonical name of the type, as returned by {@link TypeMirror#toString()}
*/
public BindingSubject bindingWithKey(String qualifier, String type) {
return bindingWithKeyString(keyString(qualifier, type));
}
private BindingSubject bindingWithKeyString(String keyString) {
ImmutableSet<Binding> bindings = getBindingNodes(keyString);
// TODO(dpb): Handle multiple bindings for the same key.
check("bindingsWithKey(%s)", keyString).that(bindings).hasSize(1);
return check("bindingWithKey(%s)", keyString)
.about(BindingSubject::new)
.that(getOnlyElement(bindings));
}
private ImmutableSet<Binding> getBindingNodes(String keyString) {
return actual.bindings().stream()
.filter(binding -> binding.key().toString().equals(keyString))
.collect(toImmutableSet());
}
private static String keyString(String type) {
return type;
}
private static String keyString(String qualifier, String type) {
return String.format("%s %s", qualifier, type);
}
/** A Truth subject for a {@link Binding}. */
public final | BindingGraphSubject |
java | elastic__elasticsearch | x-pack/plugin/spatial/src/test/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/GeoHexAggregationBuilderTests.java | {
"start": 674,
"end": 3192
} | class ____ extends AbstractXContentSerializingTestCase<GeoHexGridAggregationBuilder> {
@Override
protected GeoHexGridAggregationBuilder doParseInstance(XContentParser parser) throws IOException {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
String name = parser.currentName();
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.currentName(), equalTo(GeoHexGridAggregationBuilder.NAME));
GeoHexGridAggregationBuilder parsed = GeoHexGridAggregationBuilder.PARSER.apply(parser, name);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
return parsed;
}
@Override
protected Writeable.Reader<GeoHexGridAggregationBuilder> instanceReader() {
return GeoHexGridAggregationBuilder::new;
}
@Override
protected GeoHexGridAggregationBuilder createTestInstance() {
GeoHexGridAggregationBuilder geoHexGridAggregationBuilder = new GeoHexGridAggregationBuilder("_name");
geoHexGridAggregationBuilder.field("field");
if (randomBoolean()) {
geoHexGridAggregationBuilder.precision(randomIntBetween(0, H3.MAX_H3_RES));
}
if (randomBoolean()) {
geoHexGridAggregationBuilder.size(randomIntBetween(1, 256 * 256));
}
if (randomBoolean()) {
geoHexGridAggregationBuilder.shardSize(randomIntBetween(1, 256 * 256));
}
if (randomBoolean()) {
geoHexGridAggregationBuilder.setGeoBoundingBox(GeoTestUtils.randomBBox());
}
return geoHexGridAggregationBuilder;
}
@Override
protected GeoHexGridAggregationBuilder mutateInstance(GeoHexGridAggregationBuilder instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
public void testInvalidPrecision() {
GeoHexGridAggregationBuilder geoHexGridAggregationBuilder = new GeoHexGridAggregationBuilder("_name");
expectThrows(IllegalArgumentException.class, () -> geoHexGridAggregationBuilder.precision(16));
expectThrows(IllegalArgumentException.class, () -> geoHexGridAggregationBuilder.precision(-1));
}
}
| GeoHexAggregationBuilderTests |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/codec/CancelWithoutDemandCodecTests.java | {
"start": 7983,
"end": 8176
} | class ____ extends BaseSubscriber<Message> {
@Override
protected void hookOnSubscribe(Subscription subscription) {
// Just subscribe without requesting
}
}
}
| ZeroDemandMessageSubscriber |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/naming/pojo/ListView.java | {
"start": 736,
"end": 1223
} | class ____<T> {
private List<T> data;
private int count;
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "ListView{" + "data=" + data + ", count=" + count + '}';
}
}
| ListView |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/filter/OneToManyWithDynamicFilterTest.java | {
"start": 1615,
"end": 3903
} | class ____ extends AbstractStatefulStatelessFilterTest {
@BeforeEach
void setUp() {
scope.inTransaction( session -> {
final ArticleTrading articleTrading = new ArticleTrading();
articleTrading.setClassifier( "no_classification" );
articleTrading.setPartyId( 2 );
articleTrading.setDeletionTimestamp( Timestamp.valueOf( "9999-12-31 00:00:00" ) );
articleTrading.setDeleted( true );
final ArticleRevision revision = new ArticleRevision();
revision.addArticleTradings( articleTrading );
revision.setDeletionTimestamp( Timestamp.valueOf( "9999-12-31 00:00:00" ) );
revision.setDeleted( true );
session.persist( revision );
} );
}
@AfterEach
void tearDown() {
scope.getSessionFactory().getSchemaManager().truncate();
}
@ParameterizedTest
@MethodSource("transactionKind")
void testForIssue(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
inTransaction.accept(scope, session -> {
final org.hibernate.Filter enableFilter = session.enableFilter( "aliveOnly" );
enableFilter.setParameter( "aliveTimestamp", Timestamp.valueOf( "9999-12-31 00:00:00" ) );
enableFilter.setParameter( "deleted", true );
enableFilter.validate();
final Query<Long> query = session.createQuery( "select a.id from ArticleRevision as a " +
"left join a.articleTradings as t " +
"with ( (t.partyId = :p_0) and (t.classifier = :p_1) )", Long.class );
query.setParameter( "p_0", 1L );
query.setParameter( "p_1", "no_classification" );
final List<Long> list = query.getResultList();
MatcherAssert.assertThat( list.size(), is( 1 ) );
} );
}
@SuppressWarnings({"unused", "FieldCanBeLocal", "FieldMayBeFinal", "MismatchedQueryAndUpdateOfCollection"})
@Entity(name = "ArticleRevision")
@Table(name = "REVISION")
@FilterDefs({
@FilterDef(
name = "aliveOnly",
parameters = {
@ParamDef(name = "aliveTimestamp", type = Timestamp.class),
@ParamDef(name = "deleted", type = Boolean.class)
},
defaultCondition = "DELETION_TIMESTAMP = :aliveTimestamp and DELETED = :deleted")
})
@Filters( { @Filter(name = "aliveOnly", condition = "DELETION_TIMESTAMP = :aliveTimestamp and DELETED = :deleted") } )
public static | OneToManyWithDynamicFilterTest |
java | apache__spark | sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/ParquetVectorUpdaterFactory.java | {
"start": 17684,
"end": 19060
} | class ____ implements ParquetVectorUpdater {
private final boolean failIfRebase;
DateToTimestampNTZWithRebaseUpdater(boolean failIfRebase) {
this.failIfRebase = failIfRebase;
}
@Override
public void readValues(
int total,
int offset,
WritableColumnVector values,
VectorizedValuesReader valuesReader) {
for (int i = 0; i < total; ++i) {
readValue(offset + i, values, valuesReader);
}
}
@Override
public void skipValues(int total, VectorizedValuesReader valuesReader) {
valuesReader.skipIntegers(total);
}
@Override
public void readValue(
int offset,
WritableColumnVector values,
VectorizedValuesReader valuesReader) {
int rebasedDays = rebaseDays(valuesReader.readInteger(), failIfRebase);
values.putLong(offset, DateTimeUtils.daysToMicros(rebasedDays, ZoneOffset.UTC));
}
@Override
public void decodeSingleDictionaryId(
int offset,
WritableColumnVector values,
WritableColumnVector dictionaryIds,
Dictionary dictionary) {
int rebasedDays =
rebaseDays(dictionary.decodeToInt(dictionaryIds.getDictId(offset)), failIfRebase);
values.putLong(offset, DateTimeUtils.daysToMicros(rebasedDays, ZoneOffset.UTC));
}
}
private static | DateToTimestampNTZWithRebaseUpdater |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-rest-data-panache/runtime/src/main/java/io/quarkus/hibernate/orm/rest/data/panache/runtime/RestDataPanacheExceptionMapper.java | {
"start": 244,
"end": 1410
} | class ____ implements ExceptionMapper<RestDataPanacheException> {
private static final Logger LOGGER = Logger.getLogger(RestDataPanacheExceptionMapper.class);
@Override
public Response toResponse(RestDataPanacheException exception) {
LOGGER.warnf(exception, "Mapping an unhandled %s", RestDataPanacheException.class.getSimpleName());
return throwableToResponse(exception, exception.getMessage());
}
private Response throwableToResponse(Throwable throwable, String message) {
if (throwable instanceof org.hibernate.exception.ConstraintViolationException) {
return Response.status(Response.Status.CONFLICT.getStatusCode(), message).build();
}
if (throwable instanceof jakarta.validation.ConstraintViolationException) {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode(), message).build();
}
if (throwable.getCause() != null) {
return throwableToResponse(throwable.getCause(), message);
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), message).build();
};
}
| RestDataPanacheExceptionMapper |
java | quarkusio__quarkus | integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/NettyMainEventLoopGroupResourceIT.java | {
"start": 115,
"end": 204
} | class ____ extends NettyMainEventLoopGroupResourceTest {
}
| NettyMainEventLoopGroupResourceIT |
java | quarkusio__quarkus | extensions/vertx/deployment/src/test/java/io/quarkus/vertx/customizers/VertxOptionsCustomizerTest.java | {
"start": 1187,
"end": 1563
} | class ____ implements VertxOptionsCustomizer {
volatile boolean invoked;
@Override
public void accept(VertxOptions options) {
invoked = true;
options.setFileSystemOptions(new FileSystemOptions().setFileCacheDir("target"));
}
public boolean wasInvoked() {
return invoked;
}
}
}
| MyCustomizer |
java | apache__camel | components/camel-thrift/src/test/java/org/apache/camel/component/thrift/generated/Calculator.java | {
"start": 249992,
"end": 258048
} | class ____ extends org.apache.thrift.scheme.TupleScheme<alltypes_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, alltypes_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetV1()) {
optionals.set(0);
}
if (struct.isSetV2()) {
optionals.set(1);
}
if (struct.isSetV3()) {
optionals.set(2);
}
if (struct.isSetV4()) {
optionals.set(3);
}
if (struct.isSetV5()) {
optionals.set(4);
}
if (struct.isSetV6()) {
optionals.set(5);
}
if (struct.isSetV7()) {
optionals.set(6);
}
if (struct.isSetV8()) {
optionals.set(7);
}
if (struct.isSetV9()) {
optionals.set(8);
}
if (struct.isSetV10()) {
optionals.set(9);
}
if (struct.isSetV11()) {
optionals.set(10);
}
if (struct.isSetV12()) {
optionals.set(11);
}
oprot.writeBitSet(optionals, 12);
if (struct.isSetV1()) {
oprot.writeBool(struct.v1);
}
if (struct.isSetV2()) {
oprot.writeByte(struct.v2);
}
if (struct.isSetV3()) {
oprot.writeI16(struct.v3);
}
if (struct.isSetV4()) {
oprot.writeI32(struct.v4);
}
if (struct.isSetV5()) {
oprot.writeI64(struct.v5);
}
if (struct.isSetV6()) {
oprot.writeDouble(struct.v6);
}
if (struct.isSetV7()) {
oprot.writeString(struct.v7);
}
if (struct.isSetV8()) {
oprot.writeBinary(struct.v8);
}
if (struct.isSetV9()) {
struct.v9.write(oprot);
}
if (struct.isSetV10()) {
{
oprot.writeI32(struct.v10.size());
for (int _iter13 : struct.v10) {
oprot.writeI32(_iter13);
}
}
}
if (struct.isSetV11()) {
{
oprot.writeI32(struct.v11.size());
for (java.lang.String _iter14 : struct.v11) {
oprot.writeString(_iter14);
}
}
}
if (struct.isSetV12()) {
{
oprot.writeI32(struct.v12.size());
for (java.util.Map.Entry<java.lang.String, java.lang.Long> _iter15 : struct.v12.entrySet()) {
oprot.writeString(_iter15.getKey());
oprot.writeI64(_iter15.getValue());
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, alltypes_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(12);
if (incoming.get(0)) {
struct.v1 = iprot.readBool();
struct.setV1IsSet(true);
}
if (incoming.get(1)) {
struct.v2 = iprot.readByte();
struct.setV2IsSet(true);
}
if (incoming.get(2)) {
struct.v3 = iprot.readI16();
struct.setV3IsSet(true);
}
if (incoming.get(3)) {
struct.v4 = iprot.readI32();
struct.setV4IsSet(true);
}
if (incoming.get(4)) {
struct.v5 = iprot.readI64();
struct.setV5IsSet(true);
}
if (incoming.get(5)) {
struct.v6 = iprot.readDouble();
struct.setV6IsSet(true);
}
if (incoming.get(6)) {
struct.v7 = iprot.readString();
struct.setV7IsSet(true);
}
if (incoming.get(7)) {
struct.v8 = iprot.readBinary();
struct.setV8IsSet(true);
}
if (incoming.get(8)) {
struct.v9 = new Work();
struct.v9.read(iprot);
struct.setV9IsSet(true);
}
if (incoming.get(9)) {
{
org.apache.thrift.protocol.TList _list16 = iprot.readListBegin(org.apache.thrift.protocol.TType.I32);
struct.v10 = new java.util.ArrayList<java.lang.Integer>(_list16.size);
int _elem17;
for (int _i18 = 0; _i18 < _list16.size; ++_i18) {
_elem17 = iprot.readI32();
struct.v10.add(_elem17);
}
}
struct.setV10IsSet(true);
}
if (incoming.get(10)) {
{
org.apache.thrift.protocol.TSet _set19 = iprot.readSetBegin(org.apache.thrift.protocol.TType.STRING);
struct.v11 = new java.util.HashSet<java.lang.String>(2 * _set19.size);
@org.apache.thrift.annotation.Nullable
java.lang.String _elem20;
for (int _i21 = 0; _i21 < _set19.size; ++_i21) {
_elem20 = iprot.readString();
struct.v11.add(_elem20);
}
}
struct.setV11IsSet(true);
}
if (incoming.get(11)) {
{
org.apache.thrift.protocol.TMap _map22 = iprot.readMapBegin(org.apache.thrift.protocol.TType.STRING,
org.apache.thrift.protocol.TType.I64);
struct.v12 = new java.util.HashMap<java.lang.String, java.lang.Long>(2 * _map22.size);
@org.apache.thrift.annotation.Nullable
java.lang.String _key23;
long _val24;
for (int _i25 = 0; _i25 < _map22.size; ++_i25) {
_key23 = iprot.readString();
_val24 = iprot.readI64();
struct.v12.put(_key23, _val24);
}
}
struct.setV12IsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme())
? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
@SuppressWarnings({ "cast", "rawtypes", "serial", "unchecked", "unused" })
public static | alltypes_argsTupleScheme |
java | google__dagger | javatests/dagger/hilt/android/TestInstallInModules.java | {
"start": 1078,
"end": 1244
} | interface ____ {
@Provides
@UsesComponentQualifier
static String provideLocalString() {
return "test_install_in_string";
}
}
}
| TestInstallInModule |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest100_var.java | {
"start": 1039,
"end": 2944
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"select * from zj_sb_zzs_fb3_mx where fphm=:\"SYS_B_0\" and sssq_q=date:\"SYS_B_1\"\n";
System.out.println(sql);
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
System.out.println(stmt.toString());
assertEquals(1, statementList.size());
// SQLMethodInvokeExpr expr = (SQLMethodInvokeExpr) stmt.getSelect().getQueryBlock().getSelectList().get(0).getExpr();
// SQLMethodInvokeExpr param0 = (SQLMethodInvokeExpr) expr.getParameters().get(0);
// assertTrue(param0.getParameters().get(0)
// instanceof SQLAggregateExpr);
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
{
String text = SQLUtils.toOracleString(stmt);
assertEquals("SELECT *\n" +
"FROM zj_sb_zzs_fb3_mx\n" +
"WHERE fphm = :\"SYS_B_0\"\n" +
"\tAND sssq_q = DATE '?'", text);
}
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(3, visitor.getColumns().size());
assertEquals(2, visitor.getConditions().size());
assertEquals(0, visitor.getRelationships().size());
assertEquals(0, visitor.getOrderByColumns().size());
}
}
| OracleSelectTest100_var |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/GooglePubsubLiteComponentBuilderFactory.java | {
"start": 2008,
"end": 9411
} | interface ____ extends ComponentBuilder<GooglePubsubLiteComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* The number of quota bytes that may be outstanding to the client. Must
* be greater than the allowed size of the largest message (1 MiB).
*
* The option is a: <code>long</code> type.
*
* Default: 10485760
* Group: consumer (advanced)
*
* @param consumerBytesOutstanding the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder consumerBytesOutstanding(long consumerBytesOutstanding) {
doSetProperty("consumerBytesOutstanding", consumerBytesOutstanding);
return this;
}
/**
* The number of messages that may be outstanding to the client. Must be
* 0.
*
* The option is a: <code>long</code> type.
*
* Default: 1000
* Group: consumer (advanced)
*
* @param consumerMessagesOutstanding the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder consumerMessagesOutstanding(long consumerMessagesOutstanding) {
doSetProperty("consumerMessagesOutstanding", consumerMessagesOutstanding);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Maximum number of producers to cache. This could be increased if you
* have producers for lots of different topics.
*
* The option is a: <code>int</code> type.
*
* Default: 100
* Group: producer (advanced)
*
* @param publisherCacheSize the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder publisherCacheSize(int publisherCacheSize) {
doSetProperty("publisherCacheSize", publisherCacheSize);
return this;
}
/**
* How many milliseconds should each producer stay alive in the cache.
*
* The option is a: <code>int</code> type.
*
* Default: 180000
* Group: producer (advanced)
*
* @param publisherCacheTimeout the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder publisherCacheTimeout(int publisherCacheTimeout) {
doSetProperty("publisherCacheTimeout", publisherCacheTimeout);
return this;
}
/**
* How many milliseconds should a producer be allowed to terminate.
*
* The option is a: <code>int</code> type.
*
* Default: 60000
* Group: producer (advanced)
*
* @param publisherTerminationTimeout the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder publisherTerminationTimeout(int publisherTerminationTimeout) {
doSetProperty("publisherTerminationTimeout", publisherTerminationTimeout);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* The Service account key that can be used as credentials for the
* PubSub Lite publisher/subscriber. It can be loaded by default from
* classpath, but you can prefix with classpath:, file:, or http: to
* load the resource from different systems.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param serviceAccountKey the value to set
* @return the dsl builder
*/
default GooglePubsubLiteComponentBuilder serviceAccountKey(java.lang.String serviceAccountKey) {
doSetProperty("serviceAccountKey", serviceAccountKey);
return this;
}
}
| GooglePubsubLiteComponentBuilder |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/utils/Shell.java | {
"start": 6110,
"end": 9240
} | class ____ extends Shell {
private final String[] command;
private StringBuffer output;
/**
* Create a new instance of the ShellCommandExecutor to execute a command.
*
* @param execString The command to execute with arguments
* @param timeout Specifies the time in milliseconds, after which the
* command will be killed. -1 means no timeout.
*/
public ShellCommandExecutor(String[] execString, long timeout) {
super(timeout);
command = execString.clone();
}
/** Execute the shell command. */
public void execute() throws IOException {
this.run();
}
protected String[] execString() {
return command;
}
protected void parseExecResult(BufferedReader reader) throws IOException {
output = new StringBuffer();
char[] buf = new char[512];
int nRead;
while ((nRead = reader.read(buf, 0, buf.length)) > 0) {
output.append(buf, 0, nRead);
}
}
/** Get the output of the shell command.*/
public String output() {
return (output == null) ? "" : output.toString();
}
/**
* Returns the commands of this instance.
* Arguments with spaces in are presented with quotes round; other
* arguments are presented raw
*
* @return a string representation of the object.
*/
public String toString() {
StringBuilder builder = new StringBuilder();
String[] args = execString();
for (String s : args) {
if (s.indexOf(' ') >= 0) {
builder.append('"').append(s).append('"');
} else {
builder.append(s);
}
builder.append(' ');
}
return builder.toString();
}
}
/**
* Static method to execute a shell command.
* Covers most of the simple cases without requiring the user to implement
* the <code>Shell</code> interface.
* @param cmd shell command to execute.
* @return the output of the executed command.
*/
public static String execCommand(String... cmd) throws IOException {
return execCommand(cmd, -1);
}
/**
* Static method to execute a shell command.
* Covers most of the simple cases without requiring the user to implement
* the <code>Shell</code> interface.
* @param cmd shell command to execute.
* @param timeout time in milliseconds after which script should be killed. -1 means no timeout.
* @return the output of the executed command.
*/
public static String execCommand(String[] cmd, long timeout) throws IOException {
ShellCommandExecutor exec = new ShellCommandExecutor(cmd, timeout);
exec.execute();
return exec.output();
}
/**
* Timer which is used to timeout scripts spawned off by shell.
*/
private static | ShellCommandExecutor |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java | {
"start": 23569,
"end": 23864
} | class ____ {
private final String foo;
private final String bar;
NestedImmutable(@DefaultValue("hello") String foo, String bar) {
this.foo = foo;
this.bar = bar;
}
String getFoo() {
return this.foo;
}
String getBar() {
return this.bar;
}
}
static | NestedImmutable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.